d() ); $manager->destroy_all(); } /** * Gets the user IDs of all users with no role on this site. * * @since 4.4.0 * @since 4.9.0 The `$site_id` parameter was added to support multisite. * * @global wpdb $wpdb WordPress database abstraction object. * * @param int|null $site_id Optional. The site ID to get users with no role for. Defaults to the current site. * @return string[] Array of user IDs as strings. */ function wp_get_users_with_no_role( $site_id = null ) { global $wpdb; if ( ! $site_id ) { $site_id = get_current_blog_id(); } $prefix = $wpdb->get_blog_prefix( $site_id ); if ( is_multisite() && get_current_blog_id() !== $site_id ) { switch_to_blog( $site_id ); $role_names = wp_roles()->get_names(); restore_current_blog(); } else { $role_names = wp_roles()->get_names(); } $regex = implode( '|', array_keys( $role_names ) ); $regex = preg_replace( '/[^a-zA-Z_\|-]/', '', $regex ); $users = $wpdb->get_col( $wpdb->prepare( "SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$prefix}capabilities' AND meta_value NOT REGEXP %s", $regex ) ); return $users; } /** * Retrieves the current user object. * * Will set the current user, if the current user is not set. The current user * will be set to the logged-in person. If no user is logged-in, then it will * set the current user to 0, which is invalid and won't have any permissions. * * This function is used by the pluggable functions wp_get_current_user() and * get_currentuserinfo(), the latter of which is deprecated but used for backward * compatibility. * * @since 4.5.0 * @access private * * @see wp_get_current_user() * @global WP_User $current_user Checks if the current user is set. * * @return WP_User Current WP_User instance. */ function _wp_get_current_user() { global $current_user; if ( ! empty( $current_user ) ) { if ( $current_user instanceof WP_User ) { return $current_user; } // Upgrade stdClass to WP_User. if ( is_object( $current_user ) && isset( $current_user->ID ) ) { $cur_id = $current_user->ID; $current_user = null; wp_set_current_user( $cur_id ); return $current_user; } // $current_user has a junk value. Force to WP_User with ID 0. $current_user = null; wp_set_current_user( 0 ); return $current_user; } if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) { wp_set_current_user( 0 ); return $current_user; } /** * Filters the current user. * * The default filters use this to determine the current user from the * request's cookies, if available. * * Returning a value of false will effectively short-circuit setting * the current user. * * @since 3.9.0 * * @param int|false $user_id User ID if one has been determined, false otherwise. */ $user_id = apply_filters( 'determine_current_user', false ); if ( ! $user_id ) { wp_set_current_user( 0 ); return $current_user; } wp_set_current_user( $user_id ); return $current_user; } /** * Sends a confirmation request email when a change of user email address is attempted. * * @since 3.0.0 * @since 4.9.0 This function was moved from wp-admin/includes/ms.php so it's no longer Multisite specific. * @since 7.0.3 Added the `$user_id` parameter, which is sent with the `personal_options_update` action. * * @global WP_Error $errors WP_Error object. * * @param int $user_id Optional. The ID of the user whose email is being changed. Defaults to `$_POST['user_id']` if set, otherwise 0. */ function send_confirmation_on_profile_email( $user_id = 0 ) { global $errors; // Maintain backward compatibility for those relying on a check based on $_POST['user_id']. if ( ! $user_id && isset( $_POST['user_id'] ) ) { $user_id = absint( $_POST['user_id'] ); } $current_user = wp_get_current_user(); if ( ! is_object( $errors ) ) { $errors = new WP_Error(); } if ( 0 === $current_user->ID || $current_user->ID !== (int) $user_id ) { return false; } if ( $current_user->user_email !== $_POST['email'] ) { if ( ! is_email( $_POST['email'] ) ) { $errors->add( 'user_email', __( 'Error: The email address is not correct.' ), array( 'form-field' => 'email', ) ); $_POST['email'] = addslashes( $current_user->user_email ); return; } if ( email_exists( $_POST['email'] ) ) { $errors->add( 'user_email', __( 'Error: The email address is already used.' ), array( 'form-field' => 'email', ) ); delete_user_meta( $current_user->ID, '_new_email' ); $_POST['email'] = addslashes( $current_user->user_email ); return; } $hash = md5( $_POST['email'] . time() . wp_rand() ); $new_user_email = array( 'hash' => $hash, 'newemail' => $_POST['email'], ); update_user_meta( $current_user->ID, '_new_email', $new_user_email ); $sitename = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ); /* translators: Do not translate USERNAME, ADMIN_URL, EMAIL, SITENAME, SITEURL: those are placeholders. */ $email_text = __( 'Howdy ###USERNAME###, You recently requested to have the email address on your account changed. If this is correct, please click on the following link to change it: ###ADMIN_URL### You can safely ignore and delete this email if you do not want to take this action. This email has been sent to ###EMAIL### Regards, All at ###SITENAME### ###SITEURL###' ); /** * Filters the text of the email sent when a change of user email address is attempted. * * The following strings have a special meaning and will get replaced dynamically: * * - `###USERNAME###` The current user's username. * - `###ADMIN_URL###` The link to click on to confirm the email change. * - `###EMAIL###` The new email. * - `###SITENAME###` The name of the site. * - `###SITEURL###` The URL to the site. * * @since MU (3.0.0) * @since 4.9.0 This filter is no longer Multisite specific. * * @param string $email_text Text in the email. * @param array $new_user_email { * Data relating to the new user email address. * * @type string $hash The secure hash used in the confirmation link URL. * @type string $newemail The proposed new email address. * } */ $content = apply_filters( 'new_user_email_content', $email_text, $new_user_email ); $content = str_replace( '###USERNAME###', $current_user->user_login, $content ); $content = str_replace( '###ADMIN_URL###', esc_url( self_admin_url( 'profile.php?newuseremail=' . $hash ) ), $content ); $content = str_replace( '###EMAIL###', $_POST['email'], $content ); $content = str_replace( '###SITENAME###', $sitename, $content ); $content = str_replace( '###SITEURL###', home_url(), $content ); /* translators: New email address notification email subject. %s: Site title. */ wp_mail( $_POST['email'], sprintf( __( '[%s] Email Change Request' ), $sitename ), $content ); $_POST['email'] = $current_user->user_email; } } /** * Adds an admin notice alerting the user to check for confirmation request email * after email address change. * * @since 3.0.0 * @since 4.9.0 This function was moved from wp-admin/includes/ms.php so it's no longer Multisite specific. * * @global string $pagenow The filename of the current screen. */ function new_user_email_admin_notice() { global $pagenow; if ( 'profile.php' === $pagenow && isset( $_GET['updated'] ) ) { $email = get_user_meta( get_current_user_id(), '_new_email', true ); if ( $email ) { $message = sprintf( /* translators: %s: New email address. */ __( 'Your email address has not been updated yet. Please check your inbox at %s for a confirmation email.' ), '' . esc_html( $email['newemail'] ) . '' ); wp_admin_notice( $message, array( 'type' => 'info' ) ); } } } /** * Gets all personal data request types. * * @since 4.9.6 * @access private * * @return string[] List of core privacy action types. */ function _wp_privacy_action_request_types() { return array( 'export_personal_data', 'remove_personal_data', ); } /** * Registers the personal data exporter for users. * * @since 4.9.6 * * @param array[] $exporters An array of personal data exporters. * @return array[] An array of personal data exporters. */ function wp_register_user_personal_data_exporter( $exporters ) { $exporters['wordpress-user'] = array( 'exporter_friendly_name' => __( 'WordPress User' ), 'callback' => 'wp_user_personal_data_exporter', ); return $exporters; } /** * Finds and exports personal data associated with an email address from the user and user_meta table. * * @since 4.9.6 * @since 5.4.0 Added 'Community Events Location' group to the export data. * @since 5.4.0 Added 'Session Tokens' group to the export data. * * @param string $email_address The user's email address. * @return array { * An array of personal data. * * @type array[] $data An array of personal data arrays. * @type bool $done Whether the exporter is finished. * } */ function wp_user_personal_data_exporter( $email_address ) { $email_address = trim( $email_address ); $data_to_export = array(); $user = get_user_by( 'email', $email_address ); if ( ! $user ) { return array( 'data' => array(), 'done' => true, ); } $user_meta = get_user_meta( $user->ID ); $user_props_to_export = array( 'ID' => __( 'User ID' ), 'user_login' => __( 'User Login Name' ), 'user_nicename' => __( 'User Nice Name' ), 'user_email' => __( 'User Email' ), 'user_url' => __( 'User URL' ), 'user_registered' => __( 'User Registration Date' ), 'display_name' => __( 'User Display Name' ), 'nickname' => __( 'User Nickname' ), 'first_name' => __( 'User First Name' ), 'last_name' => __( 'User Last Name' ), 'description' => __( 'User Description' ), ); $user_data_to_export = array(); foreach ( $user_props_to_export as $key => $name ) { $value = ''; switch ( $key ) { case 'ID': case 'user_login': case 'user_nicename': case 'user_email': case 'user_url': case 'user_registered': case 'display_name': $value = $user->data->$key; break; case 'nickname': case 'first_name': case 'last_name': case 'description': $value = $user_meta[ $key ][0]; break; } if ( ! empty( $value ) ) { $user_data_to_export[] = array( 'name' => $name, 'value' => $value, ); } } // Get the list of reserved names. $reserved_names = array_values( $user_props_to_export ); /** * Filters the user's profile data for the privacy exporter. * * @since 5.4.0 * * @param array $additional_user_profile_data { * An array of name-value pairs of additional user data items. Default empty array. * * @type string $name The user-facing name of an item name-value pair,e.g. 'IP Address'. * @type string $value The user-facing value of an item data pair, e.g. '50.60.70.0'. * } * @param WP_User $user The user whose data is being exported. * @param string[] $reserved_names An array of reserved names. Any item in `$additional_user_data` * that uses one of these for its `name` will not be included in the export. */ $_extra_data = apply_filters( 'wp_privacy_additional_user_profile_data', array(), $user, $reserved_names ); if ( is_array( $_extra_data ) && ! empty( $_extra_data ) ) { // Remove items that use reserved names. $extra_data = array_filter( $_extra_data, static function ( $item ) use ( $reserved_names ) { return ! in_array( $item['name'], $reserved_names, true ); } ); if ( count( $extra_data ) !== count( $_extra_data ) ) { _doing_it_wrong( __FUNCTION__, sprintf( /* translators: %s: wp_privacy_additional_user_profile_data */ __( 'Filter %s returned items with reserved names.' ), 'wp_privacy_additional_user_profile_data' ), '5.4.0' ); } if ( ! empty( $extra_data ) ) { $user_data_to_export = array_merge( $user_data_to_export, $extra_data ); } } $data_to_export[] = array( 'group_id' => 'user', 'group_label' => __( 'User' ), 'group_description' => __( 'User’s profile data.' ), 'item_id' => "user-{$user->ID}", 'data' => $user_data_to_export, ); if ( isset( $user_meta['community-events-location'] ) ) { $location = maybe_unserialize( $user_meta['community-events-location'][0] ); $location_props_to_export = array( 'description' => __( 'City' ), 'country' => __( 'Country' ), 'latitude' => __( 'Latitude' ), 'longitude' => __( 'Longitude' ), 'ip' => __( 'IP' ), ); $location_data_to_export = array(); foreach ( $location_props_to_export as $key => $name ) { if ( ! empty( $location[ $key ] ) ) { $location_data_to_export[] = array( 'name' => $name, 'value' => $location[ $key ], ); } } $data_to_export[] = array( 'group_id' => 'community-events-location', 'group_label' => __( 'Community Events Location' ), 'group_description' => __( 'User’s location data used for the Community Events in the WordPress Events and News dashboard widget.' ), 'item_id' => "community-events-location-{$user->ID}", 'data' => $location_data_to_export, ); } if ( isset( $user_meta['session_tokens'] ) ) { $session_tokens = maybe_unserialize( $user_meta['session_tokens'][0] ); $session_tokens_props_to_export = array( 'expiration' => __( 'Expiration' ), 'ip' => __( 'IP' ), 'ua' => __( 'User Agent' ), 'login' => __( 'Last Login' ), ); foreach ( $session_tokens as $token_key => $session_token ) { $session_tokens_data_to_export = array(); foreach ( $session_tokens_props_to_export as $key => $name ) { if ( ! empty( $session_token[ $key ] ) ) { $value = $session_token[ $key ]; if ( in_array( $key, array( 'expiration', 'login' ), true ) ) { $value = date_i18n( 'F d, Y H:i A', $value ); } $session_tokens_data_to_export[] = array( 'name' => $name, 'value' => $value, ); } } $data_to_export[] = array( 'group_id' => 'session-tokens', 'group_label' => __( 'Session Tokens' ), 'group_description' => __( 'User’s Session Tokens data.' ), 'item_id' => "session-tokens-{$user->ID}-{$token_key}", 'data' => $session_tokens_data_to_export, ); } } return array( 'data' => $data_to_export, 'done' => true, ); } /** * Updates log when privacy request is confirmed. * * @since 4.9.6 * @access private * * @param int $request_id ID of the request. */ function _wp_privacy_account_request_confirmed( $request_id ) { $request = wp_get_user_request( $request_id ); if ( ! $request ) { return; } if ( ! in_array( $request->status, array( 'request-pending', 'request-failed' ), true ) ) { return; } update_post_meta( $request_id, '_wp_user_request_confirmed_timestamp', time() ); wp_update_post( array( 'ID' => $request_id, 'post_status' => 'request-confirmed', ) ); } /** * Notifies the site administrator via email when a request is confirmed. * * Without this, the admin would have to manually check the site to see if any * action was needed on their part yet. * * @since 4.9.6 * * @param int $request_id The ID of the request. */ function _wp_privacy_send_request_confirmation_notification( $request_id ) { $request = wp_get_user_request( $request_id ); if ( ! ( $request instanceof WP_User_Request ) || 'request-confirmed' !== $request->status ) { return; } $already_notified = (bool) get_post_meta( $request_id, '_wp_admin_notified', true ); if ( $already_notified ) { return; } if ( 'export_personal_data' === $request->action_name ) { $manage_url = admin_url( 'export-personal-data.php' ); } elseif ( 'remove_personal_data' === $request->action_name ) { $manage_url = admin_url( 'erase-personal-data.php' ); } $action_description = wp_user_request_action_description( $request->action_name ); /** * Filters the recipient of the data request confirmation notification. * * In a Multisite environment, this will default to the email address of the * network admin because, by default, single site admins do not have the * capabilities required to process requests. Some networks may wish to * delegate those capabilities to a single-site admin, or a dedicated person * responsible for managing privacy requests. * * @since 4.9.6 * * @param string $admin_email The email address of the notification recipient. * @param WP_User_Request $request The request that is initiating the notification. */ $admin_email = apply_filters( 'user_request_confirmed_email_to', get_site_option( 'admin_email' ), $request ); $email_data = array( 'request' => $request, 'user_email' => $request->email, 'description' => $action_description, 'manage_url' => $manage_url, 'sitename' => wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ), 'siteurl' => home_url(), 'admin_email' => $admin_email, ); $subject = sprintf( /* translators: Privacy data request confirmed notification email subject. 1: Site title, 2: Name of the confirmed action. */ __( '[%1$s] Action Confirmed: %2$s' ), $email_data['sitename'], $action_description ); /** * Filters the subject of the user request confirmation email. * * @since 4.9.8 * * @param string $subject The email subject. * @param string $sitename The name of the site. * @param array $email_data { * Data relating to the account action email. * * @type WP_User_Request $request User request object. * @type string $user_email The email address confirming a request. * @type string $description Description of the action being performed so the user knows what the email is for. * @type string $manage_url The link to click manage privacy requests of this type. * @type string $sitename The site name sending the mail. * @type string $siteurl The site URL sending the mail. * @type string $admin_email The administrator email receiving the mail. * } */ $subject = apply_filters( 'user_request_confirmed_email_subject', $subject, $email_data['sitename'], $email_data ); /* translators: Do not translate SITENAME, USER_EMAIL, DESCRIPTION, MANAGE_URL, SITEURL; those are placeholders. */ $content = __( 'Howdy, A user data privacy request has been confirmed on ###SITENAME###: User: ###USER_EMAIL### Request: ###DESCRIPTION### You can view and manage these data privacy requests here: ###MANAGE_URL### Regards, All at ###SITENAME### ###SITEURL###' ); /** * Filters the body of the user request confirmation email. * * The email is sent to an administrator when a user request is confirmed. * * The following strings have a special meaning and will get replaced dynamically: * * - `###SITENAME###` The name of the site. * - `###USER_EMAIL###` The user email for the request. * - `###DESCRIPTION###` Description of the action being performed so the user knows what the email is for. * - `###MANAGE_URL###` The URL to manage requests. * - `###SITEURL###` The URL to the site. * * @since 4.9.6 * @deprecated 5.8.0 Use {@see 'user_request_confirmed_email_content'} instead. * For user erasure fulfillment email content * use {@see 'user_erasure_fulfillment_email_content'} instead. * * @param string $content The email content. * @param array $email_data { * Data relating to the account action email. * * @type WP_User_Request $request User request object. * @type string $user_email The email address confirming a request. * @type string $description Description of the action being performed * so the user knows what the email is for. * @type string $manage_url The link to click manage privacy requests of this type. * @type string $sitename The site name sending the mail. * @type string $siteurl The site URL sending the mail. * @type string $admin_email The administrator email receiving the mail. * } */ $content = apply_filters_deprecated( 'user_confirmed_action_email_content', array( $content, $email_data ), '5.8.0', sprintf( /* translators: 1 & 2: Deprecation replacement options. */ __( '%1$s or %2$s' ), 'user_request_confirmed_email_content', 'user_erasure_fulfillment_email_content' ) ); /** * Filters the body of the user request confirmation email. * * The email is sent to an administrator when a user request is confirmed. * The following strings have a special meaning and will get replaced dynamically: * * - `###SITENAME###` The name of the site. * - `###USER_EMAIL###` The user email for the request. * - `###DESCRIPTION###` Description of the action being performed so the user knows what the email is for. * - `###MANAGE_URL###` The URL to manage requests. * - `###SITEURL###` The URL to the site. * * @since 5.8.0 * * @param string $content The email content. * @param array $email_data { * Data relating to the account action email. * * @type WP_User_Request $request User request object. * @type string $user_email The email address confirming a request. * @type string $description Description of the action being performed so the user knows what the email is for. * @type string $manage_url The link to click manage privacy requests of this type. * @type string $sitename The site name sending the mail. * @type string $siteurl The site URL sending the mail. * @type string $admin_email The administrator email receiving the mail. * } */ $content = apply_filters( 'user_request_confirmed_email_content', $content, $email_data ); $content = str_replace( '###SITENAME###', $email_data['sitename'], $content ); $content = str_replace( '###USER_EMAIL###', $email_data['user_email'], $content ); $content = str_replace( '###DESCRIPTION###', $email_data['description'], $content ); $content = str_replace( '###MANAGE_URL###', sanitize_url( $email_data['manage_url'] ), $content ); $content = str_replace( '###SITEURL###', sanitize_url( $email_data['siteurl'] ), $content ); $headers = ''; /** * Filters the headers of the user request confirmation email. * * @since 5.4.0 * * @param string|array $headers The email headers. * @param string $subject The email subject. * @param string $content The email content. * @param int $request_id The request ID. * @param array $email_data { * Data relating to the account action email. * * @type WP_User_Request $request User request object. * @type string $user_email The email address confirming a request. * @type string $description Description of the action being performed so the user knows what the email is for. * @type string $manage_url The link to click manage privacy requests of this type. * @type string $sitename The site name sending the mail. * @type string $siteurl The site URL sending the mail. * @type string $admin_email The administrator email receiving the mail. * } */ $headers = apply_filters( 'user_request_confirmed_email_headers', $headers, $subject, $content, $request_id, $email_data ); $email_sent = wp_mail( $email_data['admin_email'], $subject, $content, $headers ); if ( $email_sent ) { update_post_meta( $request_id, '_wp_admin_notified', true ); } } /** * Notifies the user when their erasure request is fulfilled. * * Without this, the user would never know if their data was actually erased. * * @since 4.9.6 * * @param int $request_id The privacy request post ID associated with this request. */ function _wp_privacy_send_erasure_fulfillment_notification( $request_id ) { $request = wp_get_user_request( $request_id ); if ( ! ( $request instanceof WP_User_Request ) || 'request-completed' !== $request->status ) { return; } $already_notified = (bool) get_post_meta( $request_id, '_wp_user_notified', true ); if ( $already_notified ) { return; } // Localize message content for user; fallback to site default for visitors. if ( ! empty( $request->user_id ) ) { $switched_locale = switch_to_user_locale( $request->user_id ); } else { $switched_locale = switch_to_locale( get_locale() ); } /** * Filters the recipient of the data erasure fulfillment notification. * * @since 4.9.6 * * @param string $user_email The email address of the notification recipient. * @param WP_User_Request $request The request that is initiating the notification. */ $user_email = apply_filters( 'user_erasure_fulfillment_email_to', $request->email, $request ); $email_data = array( 'request' => $request, 'message_recipient' => $user_email, 'privacy_policy_url' => get_privacy_policy_url(), 'sitename' => wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ), 'siteurl' => home_url(), ); $subject = sprintf( /* translators: Erasure request fulfilled notification email subject. %s: Site title. */ __( '[%s] Erasure Request Fulfilled' ), $email_data['sitename'] ); /** * Filters the subject of the email sent when an erasure request is completed. * * @since 4.9.8 * @deprecated 5.8.0 Use {@see 'user_erasure_fulfillment_email_subject'} instead. * * @param string $subject The email subject. * @param string $sitename The name of the site. * @param array $email_data { * Data relating to the account action email. * * @type WP_User_Request $request User request object. * @type string $message_recipient The address that the email will be sent to. Defaults * to the value of `$request->email`, but can be changed * by the `user_erasure_fulfillment_email_to` filter. * @type string $privacy_policy_url Privacy policy URL. * @type string $sitename The site name sending the mail. * @type string $siteurl The site URL sending the mail. * } */ $subject = apply_filters_deprecated( 'user_erasure_complete_email_subject', array( $subject, $email_data['sitename'], $email_data ), '5.8.0', 'user_erasure_fulfillment_email_subject' ); /** * Filters the subject of the email sent when an erasure request is completed. * * @since 5.8.0 * * @param string $subject The email subject. * @param string $sitename The name of the site. * @param array $email_data { * Data relating to the account action email. * * @type WP_User_Request $request User request object. * @type string $message_recipient The address that the email will be sent to. Defaults * to the value of `$request->email`, but can be changed * by the `user_erasure_fulfillment_email_to` filter. * @type string $privacy_policy_url Privacy policy URL. * @type string $sitename The site name sending the mail. * @type string $siteurl The site URL sending the mail. * } */ $subject = apply_filters( 'user_erasure_fulfillment_email_subject', $subject, $email_data['sitename'], $email_data ); /* translators: Do not translate SITENAME, SITEURL; those are placeholders. */ $content = __( 'Howdy, Your request to erase your personal data on ###SITENAME### has been completed. If you have any follow-up questions or concerns, please contact the site administrator. Regards, All at ###SITENAME### ###SITEURL###' ); if ( ! empty( $email_data['privacy_policy_url'] ) ) { /* translators: Do not translate SITENAME, SITEURL, PRIVACY_POLICY_URL; those are placeholders. */ $content = __( 'Howdy, Your request to erase your personal data on ###SITENAME### has been completed. If you have any follow-up questions or concerns, please contact the site administrator. For more information, you can also read our privacy policy: ###PRIVACY_POLICY_URL### Regards, All at ###SITENAME### ###SITEURL###' ); } /** * Filters the body of the data erasure fulfillment notification. * * The email is sent to a user when their data erasure request is fulfilled * by an administrator. * * The following strings have a special meaning and will get replaced dynamically: * * - `###SITENAME###` The name of the site. * - `###PRIVACY_POLICY_URL###` Privacy policy page URL. * - `###SITEURL###` The URL to the site. * * @since 4.9.6 * @deprecated 5.8.0 Use {@see 'user_erasure_fulfillment_email_content'} instead. * For user request confirmation email content * use {@see 'user_request_confirmed_email_content'} instead. * * @param string $content The email content. * @param array $email_data { * Data relating to the account action email. * * @type WP_User_Request $request User request object. * @type string $message_recipient The address that the email will be sent to. Defaults * to the value of `$request->email`, but can be changed * by the `user_erasure_fulfillment_email_to` filter. * @type string $privacy_policy_url Privacy policy URL. * @type string $sitename The site name sending the mail. * @type string $siteurl The site URL sending the mail. * } */ $content = apply_filters_deprecated( 'user_confirmed_action_email_content', array( $content, $email_data ), '5.8.0', sprintf( /* translators: 1 & 2: Deprecation replacement options. */ __( '%1$s or %2$s' ), 'user_erasure_fulfillment_email_content', 'user_request_confirmed_email_content' ) ); /** * Filters the body of the data erasure fulfillment notification. * * The email is sent to a user when their data erasure request is fulfilled * by an administrator. * * The following strings have a special meaning and will get replaced dynamically: * * - `###SITENAME###` The name of the site. * - `###PRIVACY_POLICY_URL###` Privacy policy page URL. * - `###SITEURL###` The URL to the site. * * @since 5.8.0 * * @param string $content The email content. * @param array $email_data { * Data relating to the account action email. * * @type WP_User_Request $request User request object. * @type string $message_recipient The address that the email will be sent to. Defaults * to the value of `$request->email`, but can be changed * by the `user_erasure_fulfillment_email_to` filter. * @type string $privacy_policy_url Privacy policy URL. * @type string $sitename The site name sending the mail. * @type string $siteurl The site URL sending the mail. * } */ $content = apply_filters( 'user_erasure_fulfillment_email_content', $content, $email_data ); $content = str_replace( '###SITENAME###', $email_data['sitename'], $content ); $content = str_replace( '###PRIVACY_POLICY_URL###', $email_data['privacy_policy_url'], $content ); $content = str_replace( '###SITEURL###', sanitize_url( $email_data['siteurl'] ), $content ); $headers = ''; /** * Filters the headers of the data erasure fulfillment notification. * * @since 5.4.0 * @deprecated 5.8.0 Use {@see 'user_erasure_fulfillment_email_headers'} instead. * * @param string|array $headers The email headers. * @param string $subject The email subject. * @param string $content The email content. * @param int $request_id The request ID. * @param array $email_data { * Data relating to the account action email. * * @type WP_User_Request $request User request object. * @type string $message_recipient The address that the email will be sent to. Defaults * to the value of `$request->email`, but can be changed * by the `user_erasure_fulfillment_email_to` filter. * @type string $privacy_policy_url Privacy policy URL. * @type string $sitename The site name sending the mail. * @type string $siteurl The site URL sending the mail. * } */ $headers = apply_filters_deprecated( 'user_erasure_complete_email_headers', array( $headers, $subject, $content, $request_id, $email_data ), '5.8.0', 'user_erasure_fulfillment_email_headers' ); /** * Filters the headers of the data erasure fulfillment notification. * * @since 5.8.0 * * @param string|array $headers The email headers. * @param string $subject The email subject. * @param string $content The email content. * @param int $request_id The request ID. * @param array $email_data { * Data relating to the account action email. * * @type WP_User_Request $request User request object. * @type string $message_recipient The address that the email will be sent to. Defaults * to the value of `$request->email`, but can be changed * by the `user_erasure_fulfillment_email_to` filter. * @type string $privacy_policy_url Privacy policy URL. * @type string $sitename The site name sending the mail. * @type string $siteurl The site URL sending the mail. * } */ $headers = apply_filters( 'user_erasure_fulfillment_email_headers', $headers, $subject, $content, $request_id, $email_data ); $email_sent = wp_mail( $user_email, $subject, $content, $headers ); if ( $switched_locale ) { restore_previous_locale(); } if ( $email_sent ) { update_post_meta( $request_id, '_wp_user_notified', true ); } } /** * Returns request confirmation message HTML. * * @since 4.9.6 * @access private * * @param int $request_id The request ID being confirmed. * @return string The confirmation message. */ function _wp_privacy_account_request_confirmed_message( $request_id ) { $request = wp_get_user_request( $request_id ); $message = '

' . __( 'Action has been confirmed.' ) . '

'; $message .= '

' . __( 'The site administrator has been notified and will fulfill your request as soon as possible.' ) . '

'; if ( $request && in_array( $request->action_name, _wp_privacy_action_request_types(), true ) ) { if ( 'export_personal_data' === $request->action_name ) { $message = '

' . __( 'Thanks for confirming your export request.' ) . '

'; $message .= '

' . __( 'The site administrator has been notified. You will receive a link to download your export via email when they fulfill your request.' ) . '

'; } elseif ( 'remove_personal_data' === $request->action_name ) { $message = '

' . __( 'Thanks for confirming your erasure request.' ) . '

'; $message .= '

' . __( 'The site administrator has been notified. You will receive an email confirmation when they erase your data.' ) . '

'; } } /** * Filters the message displayed to a user when they confirm a data request. * * @since 4.9.6 * * @param string $message The message to the user. * @param int $request_id The ID of the request being confirmed. */ $message = apply_filters( 'user_request_action_confirmed_message', $message, $request_id ); return $message; } /** * Creates and logs a user request to perform a specific action. * * Requests are stored inside a post type named `user_request` since they can apply to both * users on the site, or guests without a user account. * * @since 4.9.6 * @since 5.7.0 Added the `$status` parameter. * * @param string $email_address User email address. This can be the address of a registered * or non-registered user. * @param string $action_name Name of the action that is being confirmed. Required. * @param array $request_data Misc data you want to send with the verification request and pass * to the actions once the request is confirmed. * @param string $status Optional request status (pending or confirmed). Default 'pending'. * @return int|WP_Error Returns the request ID if successful, or a WP_Error object on failure. */ function wp_create_user_request( $email_address = '', $action_name = '', $request_data = array(), $status = 'pending' ) { $email_address = sanitize_email( $email_address ); $action_name = sanitize_key( $action_name ); if ( ! is_email( $email_address ) ) { return new WP_Error( 'invalid_email', __( 'Invalid email address.' ) ); } if ( ! in_array( $action_name, _wp_privacy_action_request_types(), true ) ) { return new WP_Error( 'invalid_action', __( 'Invalid action name.' ) ); } if ( ! in_array( $status, array( 'pending', 'confirmed' ), true ) ) { return new WP_Error( 'invalid_status', __( 'Invalid request status.' ) ); } $user = get_user_by( 'email', $email_address ); $user_id = $user && ! is_wp_error( $user ) ? $user->ID : 0; // Check for duplicates. $requests_query = new WP_Query( array( 'post_type' => 'user_request', 'post_name__in' => array( $action_name ), // Action name stored in post_name column. 'title' => $email_address, // Email address stored in post_title column. 'post_status' => array( 'request-pending', 'request-confirmed', ), 'fields' => 'ids', ) ); if ( $requests_query->found_posts ) { return new WP_Error( 'duplicate_request', __( 'An incomplete personal data request for this email address already exists.' ) ); } $request_id = wp_insert_post( array( 'post_author' => $user_id, 'post_name' => $action_name, 'post_title' => $email_address, 'post_content' => wp_json_encode( $request_data ), 'post_status' => 'request-' . $status, 'post_type' => 'user_request', 'post_date' => current_time( 'mysql', false ), 'post_date_gmt' => current_time( 'mysql', true ), ), true ); return $request_id; } /** * Gets action description from the name and return a string. * * @since 4.9.6 * * @param string $action_name Action name of the request. * @return string Human readable action name. */ function wp_user_request_action_description( $action_name ) { switch ( $action_name ) { case 'export_personal_data': $description = __( 'Export Personal Data' ); break; case 'remove_personal_data': $description = __( 'Erase Personal Data' ); break; default: /* translators: %s: Action name. */ $description = sprintf( __( 'Confirm the "%s" action' ), $action_name ); break; } /** * Filters the user action description. * * @since 4.9.6 * * @param string $description The default description. * @param string $action_name The name of the request. */ return apply_filters( 'user_request_action_description', $description, $action_name ); } /** * Send a confirmation request email to confirm an action. * * If the request is not already pending, it will be updated. * * @since 4.9.6 * * @param int $request_id ID of the request created via wp_create_user_request(). * @return true|WP_Error True on success, `WP_Error` on failure. */ function wp_send_user_request( $request_id ) { $request_id = absint( $request_id ); $request = wp_get_user_request( $request_id ); if ( ! $request ) { return new WP_Error( 'invalid_request', __( 'Invalid personal data request.' ) ); } // Localize message content for user; fallback to site default for visitors. if ( ! empty( $request->user_id ) ) { $switched_locale = switch_to_user_locale( $request->user_id ); } else { $switched_locale = switch_to_locale( get_locale() ); } /* * Generate the new user request key first, as it is used by both the $request * object and the confirm_url array. * See https://core.trac.wordpress.org/ticket/44940 */ $request->confirm_key = wp_generate_user_request_key( $request_id ); $email_data = array( 'request' => $request, 'email' => $request->email, 'description' => wp_user_request_action_description( $request->action_name ), 'confirm_url' => add_query_arg( array( 'action' => 'confirmaction', 'request_id' => $request_id, 'confirm_key' => $request->confirm_key, ), wp_login_url() ), 'sitename' => wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ), 'siteurl' => home_url(), ); /* translators: Confirm privacy data request notification email subject. 1: Site title, 2: Name of the action. */ $subject = sprintf( __( '[%1$s] Confirm Action: %2$s' ), $email_data['sitename'], $email_data['description'] ); /** * Filters the subject of the email sent when an account action is attempted. * * @since 4.9.6 * * @param string $subject The email subject. * @param string $sitename The name of the site. * @param array $email_data { * Data relating to the account action email. * * @type WP_User_Request $request User request object. * @type string $email The email address this is being sent to. * @type string $description Description of the action being performed so the user knows what the email is for. * @type string $confirm_url The link to click on to confirm the account action. * @type string $sitename The site name sending the mail. * @type string $siteurl The site URL sending the mail. * } */ $subject = apply_filters( 'user_request_action_email_subject', $subject, $email_data['sitename'], $email_data ); /* translators: Do not translate DESCRIPTION, CONFIRM_URL, SITENAME, SITEURL: those are placeholders. */ $content = __( 'Howdy, A request has been made to perform the following action on your account: ###DESCRIPTION### To confirm this, please click on the following link: ###CONFIRM_URL### You can safely ignore and delete this email if you do not want to take this action. Regards, All at ###SITENAME### ###SITEURL###' ); /** * Filters the text of the email sent when an account action is attempted. * * The following strings have a special meaning and will get replaced dynamically: * * - `###DESCRIPTION###` Description of the action being performed so the user knows what the email is for. * - `###CONFIRM_URL###` The link to click on to confirm the account action. * - `###SITENAME###` The name of the site. * - `###SITEURL###` The URL to the site. * * @since 4.9.6 * * @param string $content Text in the email. * @param array $email_data { * Data relating to the account action email. * * @type WP_User_Request $request User request object. * @type string $email The email address this is being sent to. * @type string $description Description of the action being performed so the user knows what the email is for. * @type string $confirm_url The link to click on to confirm the account action. * @type string $sitename The site name sending the mail. * @type string $siteurl The site URL sending the mail. * } */ $content = apply_filters( 'user_request_action_email_content', $content, $email_data ); $content = str_replace( '###DESCRIPTION###', $email_data['description'], $content ); $content = str_replace( '###CONFIRM_URL###', sanitize_url( $email_data['confirm_url'] ), $content ); $content = str_replace( '###EMAIL###', $email_data['email'], $content ); $content = str_replace( '###SITENAME###', $email_data['sitename'], $content ); $content = str_replace( '###SITEURL###', sanitize_url( $email_data['siteurl'] ), $content ); $headers = ''; /** * Filters the headers of the email sent when an account action is attempted. * * @since 5.4.0 * * @param string|array $headers The email headers. * @param string $subject The email subject. * @param string $content The email content. * @param int $request_id The request ID. * @param array $email_data { * Data relating to the account action email. * * @type WP_User_Request $request User request object. * @type string $email The email address this is being sent to. * @type string $description Description of the action being performed so the user knows what the email is for. * @type string $confirm_url The link to click on to confirm the account action. * @type string $sitename The site name sending the mail. * @type string $siteurl The site URL sending the mail. * } */ $headers = apply_filters( 'user_request_action_email_headers', $headers, $subject, $content, $request_id, $email_data ); $email_sent = wp_mail( $email_data['email'], $subject, $content, $headers ); if ( $switched_locale ) { restore_previous_locale(); } if ( ! $email_sent ) { return new WP_Error( 'privacy_email_error', __( 'Unable to send personal data export confirmation email.' ) ); } return true; } /** * Returns a confirmation key for a user action and stores the hashed version for future comparison. * * @since 4.9.6 * * @param int $request_id Request ID. * @return string Confirmation key. */ function wp_generate_user_request_key( $request_id ) { // Generate something random for a confirmation key. $key = wp_generate_password( 20, false ); // Save the key, hashed. wp_update_post( array( 'ID' => $request_id, 'post_status' => 'request-pending', 'post_password' => wp_fast_hash( $key ), ) ); return $key; } /** * Validates a user request by comparing the key with the request's key. * * @since 4.9.6 * * @param int $request_id ID of the request being confirmed. * @param string $key Provided key to validate. * @return true|WP_Error True on success, WP_Error on failure. */ function wp_validate_user_request_key( $request_id, #[\SensitiveParameter] $key ) { $request_id = absint( $request_id ); $request = wp_get_user_request( $request_id ); $saved_key = $request->confirm_key; $key_request_time = $request->modified_timestamp; if ( ! $request || ! $saved_key || ! $key_request_time ) { return new WP_Error( 'invalid_request', __( 'Invalid personal data request.' ) ); } if ( ! in_array( $request->status, array( 'request-pending', 'request-failed' ), true ) ) { return new WP_Error( 'expired_request', __( 'This personal data request has expired.' ) ); } if ( empty( $key ) ) { return new WP_Error( 'missing_key', __( 'The confirmation key is missing from this personal data request.' ) ); } /** * Filters the expiration time of confirm keys. * * @since 4.9.6 * * @param int $expiration The expiration time in seconds. */ $expiration_duration = (int) apply_filters( 'user_request_key_expiration', DAY_IN_SECONDS ); $expiration_time = $key_request_time + $expiration_duration; if ( ! wp_verify_fast_hash( $key, $saved_key ) ) { return new WP_Error( 'invalid_key', __( 'The confirmation key is invalid for this personal data request.' ) ); } if ( ! $expiration_time || time() > $expiration_time ) { return new WP_Error( 'expired_key', __( 'The confirmation key has expired for this personal data request.' ) ); } return true; } /** * Returns the user request object for the specified request ID. * * @since 5.4.0 * * @param int $request_id The ID of the user request. * @return WP_User_Request|false */ function wp_get_user_request( $request_id ) { $request_id = absint( $request_id ); $post = get_post( $request_id ); if ( ! $post || 'user_request' !== $post->post_type ) { return false; } return new WP_User_Request( $post ); } /** * Checks if Application Passwords is supported. * * Application Passwords is supported only by sites using SSL or local environments * but may be made available using the {@see 'wp_is_application_passwords_available'} filter. * * @since 5.9.0 * * @return bool */ function wp_is_application_passwords_supported() { return is_ssl() || 'local' === wp_get_environment_type(); } /** * Checks if Application Passwords is globally available. * * By default, Application Passwords is available to all sites using SSL or to local environments. * Use the {@see 'wp_is_application_passwords_available'} filter to adjust its availability. * * @since 5.6.0 * * @return bool */ function wp_is_application_passwords_available() { /** * Filters whether Application Passwords is available. * * @since 5.6.0 * * @param bool $available True if available, false otherwise. */ return apply_filters( 'wp_is_application_passwords_available', wp_is_application_passwords_supported() ); } /** * Checks if Application Passwords is available for a specific user. * * By default all users can use Application Passwords. Use {@see 'wp_is_application_passwords_available_for_user'} * to restrict availability to certain users. * * @since 5.6.0 * * @param int|WP_User $user The user to check. * @return bool */ function wp_is_application_passwords_available_for_user( $user ) { if ( ! wp_is_application_passwords_available() ) { return false; } if ( ! is_object( $user ) ) { $user = get_userdata( $user ); } if ( ! $user || ! $user->exists() ) { return false; } /** * Filters whether Application Passwords is available for a specific user. * * @since 5.6.0 * * @param bool $available True if available, false otherwise. * @param WP_User $user The user to check. */ return apply_filters( 'wp_is_application_passwords_available_for_user', true, $user ); } /** * Registers the user meta property for persisted preferences. * * This property is used to store user preferences across page reloads and is * currently used by the block editor for preferences like 'fullscreenMode' and * 'fixedToolbar'. * * @since 6.1.0 * @access private * * @global wpdb $wpdb WordPress database abstraction object. */ function wp_register_persisted_preferences_meta() { /* * Create a meta key that incorporates the blog prefix so that each site * on a multisite can have distinct user preferences. */ global $wpdb; $meta_key = $wpdb->get_blog_prefix() . 'persisted_preferences'; register_meta( 'user', $meta_key, array( 'type' => 'object', 'single' => true, 'show_in_rest' => array( 'name' => 'persisted_preferences', 'type' => 'object', 'schema' => array( 'type' => 'object', 'context' => array( 'edit' ), 'properties' => array( '_modified' => array( 'description' => __( 'The date and time the preferences were updated.' ), 'type' => 'string', 'format' => 'date-time', 'readonly' => false, ), ), 'additionalProperties' => true, ), ), ) ); } /** * Sets the last changed time for the 'users' cache group. * * @since 6.3.0 */ function wp_cache_set_users_last_changed() { wp_cache_set_last_changed( 'users' ); } /** * Checks if password reset is allowed for a specific user. * * @since 6.3.0 * * @param int|WP_User $user The user to check. * @return bool|WP_Error True if allowed, false or WP_Error otherwise. */ function wp_is_password_reset_allowed_for_user( $user ) { if ( ! is_object( $user ) ) { $user = get_userdata( $user ); } if ( ! $user || ! $user->exists() ) { return false; } $allow = true; if ( is_multisite() && is_user_spammy( $user ) ) { $allow = false; } /** * Filters whether to allow a password to be reset. * * @since 2.7.0 * * @param bool $allow Whether to allow the password to be reset. Default true. * @param int $user_id The ID of the user attempting to reset a password. */ return apply_filters( 'allow_password_reset', $allow, $user->ID ); } turn $this->encryptSerializedProperties($data); } /** * Unserialize * * @param array $data Serialized data * * @return void */ public function __unserialize(array $data): void { // Decrypt properties $data = $this->decryptSerializedProperties($data); if ($this->isDecryptError()) { $this->saveOnShutdown(); } // Convert packageMysqldumpOptions arrays to GroupOptions objects $loadedOptionNames = []; if (isset($data['packageMysqldumpOptions']) && is_array($data['packageMysqldumpOptions'])) { foreach ($data['packageMysqldumpOptions'] as $index => $optionData) { $data['packageMysqldumpOptions'][$index] = GroupOptions::getObjectFromArray($optionData); // @phpstan-ignore-line $loadedOptionNames[] = $data['packageMysqldumpOptions'][$index]->getOptionName(); } } // Merge with default options for missing mysqldump modes foreach (self::getDefaultMysqlDumpOptions() as $defOpt) { if (in_array($defOpt->getOptionName(), $loadedOptionNames)) { continue; } $data['packageMysqldumpOptions'][] = $defOpt; } // Assign properties foreach ($data as $pName => $val) { if (!property_exists($this, $pName)) { continue; } $this->$pName = $val; } } /** * Return default options * * @return GroupOptions[] */ private static function getDefaultMysqlDumpOptions(): array { return [ new GroupOptions('quick', self::INPUT_MYSQLDUMP_OPTION_PREFIX, false), new GroupOptions('extended-insert', self::INPUT_MYSQLDUMP_OPTION_PREFIX, false), new GroupOptions('routines', self::INPUT_MYSQLDUMP_OPTION_PREFIX, true), new GroupOptions('disable-keys', self::INPUT_MYSQLDUMP_OPTION_PREFIX, false), new GroupOptions('compact', self::INPUT_MYSQLDUMP_OPTION_PREFIX, false), ]; } /** * This function is called on first istance of singletion object * Can be used to set dynamic properties values * * @return void */ protected function firstIstanceInit(): void { $result = $this->reset( [], [ self::class, 'getDefaultPropInitVal', ], function (): void { OptionsManager::getInstance()->applyDefaults(); if (!$this->setZipArchiveChunkSize(self::getDefaultZipArchiveChunkSize())) { throw new Exception('Unable to save the ZipArchive buffer size.'); } } ); if ($result === false) { throw new Exception('Can\'t reset the user settings'); } } /** * Return default prop val by system config * * @param string $name prop nam * @param mixed $val prop val * * @return mixed */ protected static function getDefaultPropInitVal(string $name, $val) { switch ($name) { case self::CLEANUP_EMAIL_KEY: return get_option('admin_email'); } return $val; } /** * Reset default values * * @return bool */ public function resetUserSettings(): bool { try { StaticGlobal::reset(); if (DynamicGlobalEntity::getInstance()->resetUserSettings() == false) { throw new Exception('Can\'t save dynamic global'); } $result = $this->reset( [ self::MANUAL_MODE_STORAGE_IDS_KEY, self::LAST_SYSTEM_CHECK_TIMESTAMP_KEY, self::INITIAL_ACTIVATION_TIMESTAMP_KEY, ], [ self::class, 'getDefaultPropInitVal', ], function (): void { OptionsManager::getInstance()->applyDefaults(); if (!$this->setZipArchiveChunkSize(self::getDefaultZipArchiveChunkSize())) { throw new Exception('Unable to save the ZipArchive buffer size.'); } } ); if ($result == false) { throw new Exception('Can\'t reset global entity values'); } } catch (Exception $e) { DupLog::traceError('Reset user settings error mrg: ' . $e->getMessage()); return false; } return true; } /** * Whether storage .htaccess generation is disabled. * * @return bool */ public function isStorageHtaccessOff(): bool { return DynamicGlobalEntity::getInstance()->getValBool(self::STORAGE_HTACCESS_OFF_KEY); } /** * Set whether storage .htaccess generation is disabled. * * @param bool $disabled Whether generation is disabled * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setStorageHtaccessOff(bool $disabled, bool $save = true): bool { return DynamicGlobalEntity::getInstance()->setValBool(self::STORAGE_HTACCESS_OFF_KEY, $disabled, $save); } /** * Get the last system check timestamp. * * @return int<0,max> */ public function getLastSystemCheckTimestamp(): int { return max(0, DynamicGlobalEntity::getInstance()->getValInt(self::LAST_SYSTEM_CHECK_TIMESTAMP_KEY)); } /** * Set the last system check timestamp. * * @param int $timestamp Timestamp * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setLastSystemCheckTimestamp(int $timestamp, bool $save = true): bool { return DynamicGlobalEntity::getInstance()->setValInt(self::LAST_SYSTEM_CHECK_TIMESTAMP_KEY, max(0, $timestamp), $save); } /** * Get the initial activation timestamp. * * @return int<0,max> */ public function getInitialActivationTimestamp(): int { return max(0, DynamicGlobalEntity::getInstance()->getValInt(self::INITIAL_ACTIVATION_TIMESTAMP_KEY)); } /** * Set the initial activation timestamp. * * @param int $timestamp Timestamp * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setInitialActivationTimestamp(int $timestamp, bool $save = true): bool { return DynamicGlobalEntity::getInstance()->setValInt(self::INITIAL_ACTIVATION_TIMESTAMP_KEY, max(0, $timestamp), $save); } /** * Whether SSL certificate verification is enabled. * * @return bool */ public function isSslVerifyEnabled(): bool { return !DynamicGlobalEntity::getInstance()->getValBool(self::SSL_DISABLE_VERIFY_KEY); } /** * Set whether SSL certificate verification is disabled. * * @param bool $disable Whether verification is disabled * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setSslDisableVerify(bool $disable, bool $save = true): bool { return DynamicGlobalEntity::getInstance()->setValBool(self::SSL_DISABLE_VERIFY_KEY, $disable, $save); } /** * Whether to use the server's SSL certificates instead of bundled ones. * * @return bool */ public function isUsingServerCerts(): bool { return DynamicGlobalEntity::getInstance()->getValBool(self::SSL_USE_SERVER_CERTS_KEY); } /** * Set whether to use server SSL certificates. * * @param bool $useServerCerts Whether to use server certificates * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setSslUseServerCerts(bool $useServerCerts, bool $save = true): bool { return DynamicGlobalEntity::getInstance()->setValBool(self::SSL_USE_SERVER_CERTS_KEY, $useServerCerts, $save); } /** * Get the SSL certificate path to use. * * @return string */ public function getSslCertPath(): string { return $this->isUsingServerCerts() ? '' : DUPLICATOR_CERT_PATH; } /** * Whether HTTP clients should force IPv4. * * @return bool */ public function isIpv4Only(): bool { return DynamicGlobalEntity::getInstance()->getValBool(self::IPV4_ONLY_KEY); } /** * Set whether HTTP clients should force IPv4. * * @param bool $ipv4Only Whether to force IPv4 * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setIpv4Only(bool $ipv4Only, bool $save = true): bool { return DynamicGlobalEntity::getInstance()->setValBool(self::IPV4_ONLY_KEY, $ipv4Only, $save); } /** * Whether third-party JavaScript should be unhooked. * * @return bool */ public function shouldUnhookThirdPartyJs(): bool { return DynamicGlobalEntity::getInstance()->getValBool(self::UNHOOK_THIRD_PARTY_JS_KEY); } /** * Set whether third-party JavaScript should be unhooked. * * @param bool $unhook Whether to unhook the assets * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setUnhookThirdPartyJs(bool $unhook, bool $save = true): bool { return DynamicGlobalEntity::getInstance()->setValBool(self::UNHOOK_THIRD_PARTY_JS_KEY, $unhook, $save); } /** * Whether third-party CSS should be unhooked. * * @return bool */ public function shouldUnhookThirdPartyCss(): bool { return DynamicGlobalEntity::getInstance()->getValBool(self::UNHOOK_THIRD_PARTY_CSS_KEY); } /** * Set whether third-party CSS should be unhooked. * * @param bool $unhook Whether to unhook the assets * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setUnhookThirdPartyCss(bool $unhook, bool $save = true): bool { return DynamicGlobalEntity::getInstance()->setValBool(self::UNHOOK_THIRD_PARTY_CSS_KEY, $unhook, $save); } /** * Update global settings after install * * @return bool true on success false on failure */ public function updateAftreInstall(): bool { OptionsManager::getInstance()->applyCorrections(); AsyncSetupActions::resetAndReschedule(); return $this->save(); } /** * To export data * * @return array */ public function settingsExport(): array { $skipProps = [ 'id', self::LAST_SYSTEM_CHECK_TIMESTAMP_KEY, self::INITIAL_ACTIVATION_TIMESTAMP_KEY, self::MANUAL_MODE_STORAGE_IDS_KEY, self::STORAGE_HTACCESS_OFF_KEY, 'purgeBackupRecords', self::SSL_USE_SERVER_CERTS_KEY, self::SSL_DISABLE_VERIFY_KEY, self::IPV4_ONLY_KEY, self::UNHOOK_THIRD_PARTY_JS_KEY, self::UNHOOK_THIRD_PARTY_CSS_KEY, 'basic_auth_password', 'lkp', 'uninstall_settings', 'uninstall_packages', 'crypt', self::EMAIL_SUMMARY_FREQUENCY_KEY, self::EMAIL_SUMMARY_RECIPIENTS_KEY, 'usageTracking', 'amNotices', self::PACKAGE_MYSQLDUMP_KEY, self::PACKAGE_MYSQLDUMP_PATH_KEY, self::PACKAGE_PHPDUMP_MODE_KEY, self::PACKAGE_MYSQLDUMP_QRYLIMIT_KEY, 'packageMysqldumpOptions', self::ARCHIVE_BUILD_MODE_KEY, self::ARCHIVE_COMPRESSION_KEY, self::ZIPARCHIVE_VALIDATION_KEY, self::ZIPARCHIVE_MODE_KEY, self::ZIPARCHIVE_CHUNK_SIZE_IN_MB_KEY, self::HOMEPATH_AS_ABSPATH_KEY, self::SERVER_LOAD_REDUCTION_KEY, self::MAX_PACKAGE_RUNTIME_IN_MIN_KEY, self::MAX_PACKAGE_TRANSFER_TIME_IN_MIN_KEY, self::CLEANUP_MODE_KEY, self::CLEANUP_EMAIL_KEY, self::AUTO_CLEANUP_HOURS_KEY, self::INSTALLER_NAME_MODE_KEY, self::SKIP_ARCHIVE_SCAN_KEY, self::LEGACY_SEND_EMAIL_ON_BUILD_MODE_PROP, self::LEGACY_NOTIFICATION_EMAIL_ADDRESS_PROP, ]; $data = JsonSerialize::serializeToData($this, JsonSerialize::JSON_SKIP_MAGIC_METHODS | JsonSerialize::JSON_SKIP_CLASS_NAME); foreach ($skipProps as $prop) { unset($data[$prop]); } return $data; } /** * Update object properties from import data * * @param array $data data to import * @param string $dataVersion version of data * @param array $extraData extra data, useful form id mapping etc. * * @return bool True if success, otherwise false */ public function settingsImport($data, $dataVersion, array $extraData = []): bool { $skipProps = [ 'id', self::LAST_SYSTEM_CHECK_TIMESTAMP_KEY, self::INITIAL_ACTIVATION_TIMESTAMP_KEY, self::MANUAL_MODE_STORAGE_IDS_KEY, self::STORAGE_HTACCESS_OFF_KEY, 'purgeBackupRecords', self::SSL_USE_SERVER_CERTS_KEY, self::SSL_DISABLE_VERIFY_KEY, self::IPV4_ONLY_KEY, self::UNHOOK_THIRD_PARTY_JS_KEY, self::UNHOOK_THIRD_PARTY_CSS_KEY, 'license_key_visible', 'lkp', 'basic_auth_password', 'uninstall_settings', 'uninstall_packages', 'crypt', self::EMAIL_SUMMARY_FREQUENCY_KEY, self::EMAIL_SUMMARY_RECIPIENTS_KEY, 'usageTracking', 'amNotices', self::PACKAGE_MYSQLDUMP_KEY, self::PACKAGE_MYSQLDUMP_PATH_KEY, self::PACKAGE_PHPDUMP_MODE_KEY, self::PACKAGE_MYSQLDUMP_QRYLIMIT_KEY, 'packageMysqldumpOptions', self::ARCHIVE_BUILD_MODE_KEY, self::ARCHIVE_COMPRESSION_KEY, self::ZIPARCHIVE_VALIDATION_KEY, self::ZIPARCHIVE_MODE_KEY, self::ZIPARCHIVE_CHUNK_SIZE_IN_MB_KEY, self::HOMEPATH_AS_ABSPATH_KEY, self::SERVER_LOAD_REDUCTION_KEY, self::MAX_PACKAGE_RUNTIME_IN_MIN_KEY, self::MAX_PACKAGE_TRANSFER_TIME_IN_MIN_KEY, self::CLEANUP_MODE_KEY, self::CLEANUP_EMAIL_KEY, self::AUTO_CLEANUP_HOURS_KEY, self::INSTALLER_NAME_MODE_KEY, self::SKIP_ARCHIVE_SCAN_KEY, self::LEGACY_SEND_EMAIL_ON_BUILD_MODE_PROP, self::LEGACY_NOTIFICATION_EMAIL_ADDRESS_PROP, ]; $reflect = new ReflectionClass(self::class); $props = $reflect->getProperties(); foreach ($props as $prop) { if (in_array($prop->getName(), $skipProps)) { continue; } if (!isset($data[$prop->getName()])) { continue; } if (PHP_VERSION_ID < 80100) { $prop->setAccessible(true); } $prop->setValue($this, $data[$prop->getName()]); } return true; } /** * Set from object * * @param self $global_data global data * * @return void */ public function setFromImportData(self $global_data): void { $reflect = new ReflectionClass(self::class); $props = $reflect->getProperties(); $skipProps = [ 'id', self::LAST_SYSTEM_CHECK_TIMESTAMP_KEY, self::INITIAL_ACTIVATION_TIMESTAMP_KEY, self::MANUAL_MODE_STORAGE_IDS_KEY, self::STORAGE_HTACCESS_OFF_KEY, 'purgeBackupRecords', self::SSL_USE_SERVER_CERTS_KEY, self::SSL_DISABLE_VERIFY_KEY, self::IPV4_ONLY_KEY, self::UNHOOK_THIRD_PARTY_JS_KEY, self::UNHOOK_THIRD_PARTY_CSS_KEY, 'license_key_visible', 'lkp', self::EMAIL_SUMMARY_FREQUENCY_KEY, self::EMAIL_SUMMARY_RECIPIENTS_KEY, 'usageTracking', 'amNotices', self::PACKAGE_MYSQLDUMP_KEY, self::PACKAGE_MYSQLDUMP_PATH_KEY, self::PACKAGE_PHPDUMP_MODE_KEY, self::PACKAGE_MYSQLDUMP_QRYLIMIT_KEY, 'packageMysqldumpOptions', self::ARCHIVE_BUILD_MODE_KEY, self::ARCHIVE_COMPRESSION_KEY, self::ZIPARCHIVE_VALIDATION_KEY, self::ZIPARCHIVE_MODE_KEY, self::ZIPARCHIVE_CHUNK_SIZE_IN_MB_KEY, self::HOMEPATH_AS_ABSPATH_KEY, self::SERVER_LOAD_REDUCTION_KEY, self::MAX_PACKAGE_RUNTIME_IN_MIN_KEY, self::MAX_PACKAGE_TRANSFER_TIME_IN_MIN_KEY, self::CLEANUP_MODE_KEY, self::CLEANUP_EMAIL_KEY, self::AUTO_CLEANUP_HOURS_KEY, self::INSTALLER_NAME_MODE_KEY, self::SKIP_ARCHIVE_SCAN_KEY, self::LEGACY_SEND_EMAIL_ON_BUILD_MODE_PROP, self::LEGACY_NOTIFICATION_EMAIL_ADDRESS_PROP, ]; foreach ($props as $prop) { if (in_array($prop->getName(), $skipProps)) { continue; } if (PHP_VERSION_ID < 80100) { $prop->setAccessible(true); } $prop->setValue($this, $prop->getValue($global_data)); } } /** * Check if build mode is available * * @param int $buildMode ENUM PackageArchive::BUILD_MODE_* * * @return bool */ public static function isBuildModeAvailable(int $buildMode): bool { return OptionsManager::getInstance()->availability(ArchiveEngineRule::OPTION_KEY)->isAvailable($buildMode); } /** * Return Backup build mode. The stored value is authoritative: resolved by * OptionsManager::applyDefaults() on first install/reset, kept valid by * applyCorrections() on plugin update and corrected by the pre-backup gate * when it became unavailable in the meantime. * * @return int Return enum PackageArchive::BUILD_MODE_* */ public function getBuildMode(): int { return DynamicGlobalEntity::getInstance()->getValInt(self::ARCHIVE_BUILD_MODE_KEY); } /** * Return whether mysqldump is selected. * * @return bool */ public function isMysqldumpEnabled(): bool { return DynamicGlobalEntity::getInstance()->getValBool(self::PACKAGE_MYSQLDUMP_KEY); } /** * Return the custom mysqldump path. * * @return string */ public function getMysqldumpPath(): string { return DynamicGlobalEntity::getInstance()->getValString(self::PACKAGE_MYSQLDUMP_PATH_KEY); } /** * Return the PHP dump mode. * * @return int<0,1> */ public function getPhpDumpMode(): int { /** @var int<0,1> $mode */ $mode = DynamicGlobalEntity::getInstance()->getValInt(self::PACKAGE_PHPDUMP_MODE_KEY); return $mode; } /** * Return the mysqldump query limit. * * @return int<0,max> */ public function getMysqldumpQueryLimit(): int { /** @var int<0,max> $limit */ $limit = DynamicGlobalEntity::getInstance()->getValInt(self::PACKAGE_MYSQLDUMP_QRYLIMIT_KEY); return $limit; } /** * Persist whether mysqldump is selected. * * @param bool $enabled Whether mysqldump is selected * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setMysqldumpEnabled(bool $enabled, bool $save = true): bool { return DynamicGlobalEntity::getInstance()->setValBool(self::PACKAGE_MYSQLDUMP_KEY, $enabled, $save); } /** * Persist the custom mysqldump path. * * @param string $path Custom executable path * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setMysqldumpPath(string $path, bool $save = true): bool { return DynamicGlobalEntity::getInstance()->setValString(self::PACKAGE_MYSQLDUMP_PATH_KEY, $path, $save); } /** * Persist the PHP dump mode. * * @param int $mode PHPDUMP_MODE_* value * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setPhpDumpMode(int $mode, bool $save = true): bool { if (!in_array($mode, [WpDbUtils::PHPDUMP_MODE_MULTI, WpDbUtils::PHPDUMP_MODE_SINGLE], true)) { throw new Exception('Invalid PHP dump mode.'); } return DynamicGlobalEntity::getInstance()->setValInt(self::PACKAGE_PHPDUMP_MODE_KEY, $mode, $save); } /** * Persist the mysqldump query limit. * * @param int $limit Query limit * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setMysqldumpQueryLimit(int $limit, bool $save = true): bool { if ($limit < 0) { throw new Exception('Invalid mysqldump query limit.'); } return DynamicGlobalEntity::getInstance()->setValInt(self::PACKAGE_MYSQLDUMP_QRYLIMIT_KEY, $limit, $save); } /** * Persist the archive build mode. * * @param int $mode PackageArchive::BUILD_MODE_* value * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setBuildMode(int $mode, bool $save = true): bool { if ( !in_array( $mode, [ PackageArchive::BUILD_MODE_SHELL_EXEC, PackageArchive::BUILD_MODE_ZIP_ARCHIVE, PackageArchive::BUILD_MODE_DUP_ARCHIVE, ], true ) ) { throw new Exception('Invalid archive build mode.'); } return DynamicGlobalEntity::getInstance()->setValInt(self::ARCHIVE_BUILD_MODE_KEY, $mode, $save); } /** @return bool Whether archive compression is enabled */ public function isArchiveCompressionEnabled(): bool { return DynamicGlobalEntity::getInstance()->getValBool(self::ARCHIVE_COMPRESSION_KEY); } /** * @param bool $enabled Whether archive compression is enabled * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setArchiveCompression(bool $enabled, bool $save = true): bool { return DynamicGlobalEntity::getInstance()->setValBool(self::ARCHIVE_COMPRESSION_KEY, $enabled, $save); } /** @return bool Whether ZipArchive file validation is enabled */ public function isZipArchiveValidationEnabled(): bool { return DynamicGlobalEntity::getInstance()->getValBool(self::ZIPARCHIVE_VALIDATION_KEY); } /** * @param bool $enabled Whether ZipArchive file validation is enabled * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setZipArchiveValidation(bool $enabled, bool $save = true): bool { return DynamicGlobalEntity::getInstance()->setValBool(self::ZIPARCHIVE_VALIDATION_KEY, $enabled, $save); } /** @return int<0,1> ZipArchive execution mode */ public function getZipArchiveMode(): int { /** @var int<0,1> $mode */ $mode = DynamicGlobalEntity::getInstance()->getValInt(self::ZIPARCHIVE_MODE_KEY); return $mode; } /** * @param int $mode ZipArchive execution mode * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setZipArchiveMode(int $mode, bool $save = true): bool { if ($mode < PackageArchive::ZIP_MODE_MULTI_THREAD || $mode > PackageArchive::ZIP_MODE_SINGLE_THREAD) { throw new Exception('Invalid ZipArchive mode.'); } return DynamicGlobalEntity::getInstance()->setValInt(self::ZIPARCHIVE_MODE_KEY, $mode, $save); } /** * Return the default ZipArchive buffer size for the current PHP execution limit. * * @return int Buffer size in MB */ public static function getDefaultZipArchiveChunkSize(): int { $maxExecutionTime = SnapUtil::phpIniGet('max_execution_time', 30, 'int'); if ($maxExecutionTime > 0 && $maxExecutionTime <= 30) { return 32; } if ($maxExecutionTime > 30 && $maxExecutionTime < 60) { return 64; } return 128; } /** @return int<0,max> ZipArchive chunk size in MB */ public function getZipArchiveChunkSize(): int { /** @var int<0,max> $size */ $size = DynamicGlobalEntity::getInstance()->getValInt(self::ZIPARCHIVE_CHUNK_SIZE_IN_MB_KEY); return $size; } /** * @param int $sizeInMb Chunk size in MB * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setZipArchiveChunkSize(int $sizeInMb, bool $save = true): bool { if ($sizeInMb < 0) { throw new Exception('Invalid ZipArchive chunk size.'); } return DynamicGlobalEntity::getInstance()->setValInt(self::ZIPARCHIVE_CHUNK_SIZE_IN_MB_KEY, $sizeInMb, $save); } /** @return bool Whether the home path is treated as an absolute path */ public function isHomePathAsAbsolute(): bool { return DynamicGlobalEntity::getInstance()->getValBool(self::HOMEPATH_AS_ABSPATH_KEY); } /** * @param bool $enabled Whether the home path is treated as an absolute path * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setHomePathAsAbsolute(bool $enabled, bool $save = true): bool { return DynamicGlobalEntity::getInstance()->setValBool(self::HOMEPATH_AS_ABSPATH_KEY, $enabled, $save); } /** @return int<0,3> Server load reduction level */ public function getServerLoadReduction(): int { /** @var int<0,3> $level */ $level = DynamicGlobalEntity::getInstance()->getValInt(self::SERVER_LOAD_REDUCTION_KEY); return $level; } /** * @param int $level Server load reduction level * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setServerLoadReduction(int $level, bool $save = true): bool { if ($level < ServerThrottle::NONE || $level > ServerThrottle::A_LOT) { throw new Exception('Invalid server load reduction level.'); } return DynamicGlobalEntity::getInstance()->setValInt(self::SERVER_LOAD_REDUCTION_KEY, $level, $save); } /** @return int<0,max> Maximum package runtime in minutes */ public function getMaxPackageRuntime(): int { /** @var int<0,max> $minutes */ $minutes = DynamicGlobalEntity::getInstance()->getValInt(self::MAX_PACKAGE_RUNTIME_IN_MIN_KEY); return $minutes; } /** * @param int $minutes Runtime in minutes * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setMaxPackageRuntime(int $minutes, bool $save = true): bool { if ($minutes < 0) { throw new Exception('Invalid maximum package runtime.'); } return DynamicGlobalEntity::getInstance()->setValInt(self::MAX_PACKAGE_RUNTIME_IN_MIN_KEY, $minutes, $save); } /** @return int<0,max> Maximum package transfer time in minutes */ public function getMaxPackageTransferTime(): int { /** @var int<0,max> $minutes */ $minutes = DynamicGlobalEntity::getInstance()->getValInt(self::MAX_PACKAGE_TRANSFER_TIME_IN_MIN_KEY); return $minutes; } /** * @param int $minutes Transfer time in minutes * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setMaxPackageTransferTime(int $minutes, bool $save = true): bool { if ($minutes < 0) { throw new Exception('Invalid maximum package transfer time.'); } return DynamicGlobalEntity::getInstance()->setValInt(self::MAX_PACKAGE_TRANSFER_TIME_IN_MIN_KEY, $minutes, $save); } /** @return int<0,2> Cleanup mode */ public function getCleanupMode(): int { /** @var int<0,2> $mode */ $mode = DynamicGlobalEntity::getInstance()->getValInt(self::CLEANUP_MODE_KEY); return $mode; } /** * @param int $mode Cleanup mode * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setCleanupMode(int $mode, bool $save = true): bool { if ($mode < self::CLEANUP_MODE_OFF || $mode > self::CLEANUP_MODE_AUTO) { throw new Exception('Invalid cleanup mode.'); } return DynamicGlobalEntity::getInstance()->setValInt(self::CLEANUP_MODE_KEY, $mode, $save); } /** @return string Cleanup notification email */ public function getCleanupEmail(): string { return DynamicGlobalEntity::getInstance()->getValString(self::CLEANUP_EMAIL_KEY); } /** * @param string $email Cleanup notification email * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setCleanupEmail(string $email, bool $save = true): bool { return DynamicGlobalEntity::getInstance()->setValString(self::CLEANUP_EMAIL_KEY, $email, $save); } /** @return int<0,max> Automatic cleanup interval in hours */ public function getAutoCleanupHours(): int { /** @var int<0,max> $hours */ $hours = DynamicGlobalEntity::getInstance()->getValInt(self::AUTO_CLEANUP_HOURS_KEY); return $hours; } /** * @param int $hours Automatic cleanup interval in hours * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setAutoCleanupHours(int $hours, bool $save = true): bool { if ($hours < 1) { throw new Exception('Invalid automatic cleanup interval.'); } return DynamicGlobalEntity::getInstance()->setValInt(self::AUTO_CLEANUP_HOURS_KEY, $hours, $save); } /** @return string Installer filename mode */ public function getInstallerNameMode(): string { return DynamicGlobalEntity::getInstance()->getValString(self::INSTALLER_NAME_MODE_KEY); } /** * @param string $mode Installer filename mode * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setInstallerNameMode(string $mode, bool $save = true): bool { if (!in_array($mode, [self::INSTALLER_NAME_MODE_WITH_HASH, self::INSTALLER_NAME_MODE_SIMPLE], true)) { throw new Exception('Invalid installer name mode.'); } return DynamicGlobalEntity::getInstance()->setValString(self::INSTALLER_NAME_MODE_KEY, $mode, $save); } /** @return bool Whether the archive scan is skipped */ public function isArchiveScanSkipped(): bool { return DynamicGlobalEntity::getInstance()->getValBool(self::SKIP_ARCHIVE_SCAN_KEY); } /** * @param bool $skip Whether the archive scan is skipped * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setSkipArchiveScan(bool $skip, bool $save = true): bool { return DynamicGlobalEntity::getInstance()->setValBool(self::SKIP_ARCHIVE_SCAN_KEY, $skip, $save); } /** @return int<0,max> Load-reduction delay in microseconds */ public function getMicrosecLoadReduction(): int { return ServerThrottle::microsecondsFromThrottle($this->getServerLoadReduction()); } /** * Set db mode and all related params. * The related params (custom mysqldump path included) are stored first, * then the engine goes through the options system: the requirement caches * are reset because the mysqldump detection depends on the custom path * just written in this same request. * * @param null|string $dbMode if null get INPUT_POST * @param null|int $phpDumpMode if null get INPUT_POST * @param null|int $dbPhpQueryLimit if null get INPUT_POST * @param null|string $packageMysqldumpPath if null get INPUT_POST * @param null|int $dbMysqlDumpQueryLimit if null get INPUT_POST * * @return array Submitted values not stored as-is (empty when everything is stored) */ public function setDbMode( $dbMode = null, $phpDumpMode = null, $dbPhpQueryLimit = null, $packageMysqldumpPath = null, $dbMysqlDumpQueryLimit = null ): array { //DATABASE $dbMode ??= SnapUtil::sanitizeDefaultInput(INPUT_POST, '_package_dbmode'); $phpDumpMode ??= filter_input( INPUT_POST, '_phpdump_mode', FILTER_VALIDATE_INT, [ 'options' => [ 'default' => 0, 'min_range' => 0, 'max_range' => 1, ], ] ); $dbMysqlDumpQueryLimit ??= filter_input( INPUT_POST, '_package_mysqldump_qrylimit', FILTER_VALIDATE_INT, [ 'options' => [ 'default' => Constants::DEFAULT_MYSQL_DUMP_CHUNK_SIZE, 'min_range' => Constants::MYSQL_DUMP_CHUNK_SIZE_MIN_LIMIT, 'max_range' => Constants::MYSQL_DUMP_CHUNK_SIZE_MAX_LIMIT, ], ] ); $packageMysqldumpPath ??= SnapUtil::sanitizeDefaultInput(INPUT_POST, '_package_mysqldump_path'); $packageMysqldumpPath = SnapUtil::sanitizeNSCharsNewlineTabs($packageMysqldumpPath); $packageMysqldumpPath = preg_match('/^([A-Za-z]\:)?[\/\\\\]/', $packageMysqldumpPath) ? $packageMysqldumpPath : ''; $packageMysqldumpPath = preg_replace('/[\'"]/m', '', $packageMysqldumpPath); $packageMysqldumpPath = SnapIO::safePathUntrailingslashit($packageMysqldumpPath); $dGlobal = DynamicGlobalEntity::getInstance(); $this->setPhpDumpMode((int) $phpDumpMode, false); $this->setMysqldumpPath($packageMysqldumpPath, false); $this->setMysqldumpQueryLimit((int) $dbMysqlDumpQueryLimit, false); $mysqldumpOptions = $this->getMysqldumpOptions(); foreach ($mysqldumpOptions as $option) { $option->update(); } $this->setMysqldumpOptions($mysqldumpOptions, false); // The custom path just written changes the mysqldump detection: reset // the caches so the engine is validated against the new path. WpDbUtils::resetMySqlDumpPathCache(); OptionsManager::getInstance()->resetRequirementResults([RequirementDefs::REQ_MYSQLDUMP_BINARY]); // A disabled radio doesn't submit: keep the stored engine. if (!in_array($dbMode, ['mysql', 'php'], true)) { $dbMode = $this->isMysqldumpEnabled() ? 'mysql' : 'php'; } // An unavailable submitted engine is replaced by the first available one // and reported: the storage always ends up with a valid value. $failures = OptionsManager::getInstance()->applyValues([ DbDumpEngineRule::OPTION_KEY => ($dbMode === 'mysql') ? DbDumpEngineRule::VALUE_MYSQLDUMP : DbDumpEngineRule::VALUE_PHP, ]); foreach ($failures as $failure) { DupLog::trace( 'Adjusted unavailable option value for ' . $failure->getOptionKey() . ': ' . implode(' ', $failure->getReasons()) ); } if (!$dGlobal->save()) { throw new Exception('Unable to save the database build settings.'); } return $failures; } /** * Sets cleanup fields and configures WP Cron accordingly * * @param int $cleanup_mode Cleanup mode to set * @param string $cleanup_email Email address to send cleanup notification to * @param int $auto_cleanup_hours Number of hours after which cleanup should be performed * * @return void */ public function setCleanupFields( $cleanup_mode = null, $cleanup_email = null, $auto_cleanup_hours = null ): void { $cleanupMode = $cleanup_mode ?? filter_input( INPUT_POST, self::CLEANUP_MODE_KEY, FILTER_VALIDATE_INT, [ 'options' => [ 'default' => self::CLEANUP_MODE_OFF, 'min_range' => 0, 'max_range' => 2, ], ] ); $email = filter_input(INPUT_POST, self::CLEANUP_EMAIL_KEY, FILTER_VALIDATE_EMAIL, ['options' => ['default' => '']]); $email = $email === '' ? get_option('admin_email') : $email; $cleanupEmail = $cleanup_email ?? $email; $autoCleanupHours = $auto_cleanup_hours ?? filter_input( INPUT_POST, self::AUTO_CLEANUP_HOURS_KEY, FILTER_VALIDATE_INT, [ 'options' => [ 'default' => 24, 'min_range' => 1, ], ] ); $this->setCleanupMode((int) $cleanupMode, false); $this->setCleanupEmail((string) $cleanupEmail, false); if (!$this->setAutoCleanupHours((int) $autoCleanupHours)) { throw new Exception('Unable to save the cleanup settings.'); } self::cleanupScheduleSetup(); } /** * Schedules cron event for installer files cleanup purposes, * and unschedules it if it's not needed anymore. * * @return void */ public static function cleanupScheduleSetup(): void { DupLog::trace("CLEANUP SCHEDULE SETUP"); $global = self::getInstance(); CronUtils::unscheduleEvent(self::CLEANUP_HOOK); if ($global->getCleanupMode() == self::CLEANUP_MODE_MAIL) { $nextRunTime = time() + self::CLEANUP_EMAIL_NOTICE_INTERVAL * 3600; CronUtils::scheduleEvent($nextRunTime, self::CLEANUP_INTERVAL_NAME, self::CLEANUP_HOOK); } elseif ($global->getCleanupMode() == self::CLEANUP_MODE_AUTO) { $nextRunTime = time() + $global->getAutoCleanupHours() * 3600; CronUtils::scheduleEvent($nextRunTime, self::CLEANUP_INTERVAL_NAME, self::CLEANUP_HOOK); } } /** * Customizes schedules according to current cleanup_mode. If necessary, it * adds a custom cron schedule that will run every N hours. * * @param array $schedules An array of non-default cron schedules. * * @return array Filtered array of non-default cron schedules. */ public static function customCleanupCronInterval(array $schedules): array { $global = self::getInstance(); $intervalHours = null; switch ($global->getCleanupMode()) { case self::CLEANUP_MODE_OFF: // No need to modify anything break; case self::CLEANUP_MODE_MAIL: $intervalHours = self::CLEANUP_EMAIL_NOTICE_INTERVAL; break; case self::CLEANUP_MODE_AUTO: $intervalHours = $global->getAutoCleanupHours(); break; default: throw new Exception('Invalid cleanup mode:' . SnapLog::v2str($global->getCleanupMode())); } if ($intervalHours !== null) { $display = SnapWP::isTranslationReady(DUPLICATOR____TEXT_DOMAIN) ? sprintf(esc_html__('Every %1$d hours', 'duplicator'), $intervalHours) : sprintf('Every %1$d hours', $intervalHours); $schedules[self::CLEANUP_INTERVAL_NAME] = [ 'interval' => $intervalHours * 3600, 'display' => $display, ]; } return $schedules; } /** * The function that gets executed by WP Cron for cleanup of installer files. * It does different tasks based on current cleanup_mode setting. * * @return void */ public static function cleanupCronJob(): void { $global = self::getInstance(); DupLog::trace("CLEANUP CRON JOB"); $websiteUrl = SnapURL::getCurrentUrl(false, false, 1); $to = $global->getCleanupEmail(); if (empty($to)) { $to = get_option('admin_email'); } switch ($global->getCleanupMode()) { case self::CLEANUP_MODE_MAIL: // Email Notice cron job routine for cleanup of installer files $listOfInstallerFiles = MigrationMng::checkInstallerFilesList(); $filesToRemove = []; foreach ($listOfInstallerFiles as $path) { if (time() - filectime($path) > self::CLEANUP_FILE_TIME_DELAY) { $filesToRemove[] = $path; } } if (count($filesToRemove) > 0 && !empty($to)) { // Send an Email Notice in the site language regardless of the sending request's locale $switchedLocale = switch_to_locale(get_locale()); $subject = __("Action required", 'duplicator'); $message = sprintf( /* translators: %1$s: plugin name, %2$s: website URL */ __('This email is sent by your WordPress plugin "%1$s" from website: %2$s. ', 'duplicator'), esc_html(DUPLICATOR____NAME), $websiteUrl ); $message .= __('You received this email because Cleanup mode is set to "Email Notice". ', 'duplicator'); $message .= __('The cleanup routine discovered that some installer files (leftovers from migration) were not removed. ', 'duplicator'); $message .= __('We strongly advise you to remove these files. ', 'duplicator'); $message .= __('Here is the list of files found on your website that you should remove:', 'duplicator') . "
"; foreach ($filesToRemove as $path) { $message .= "-> $path
"; } $message .= "
"; $message .= __('Note: You could enable "Auto Cleanup" mode if you go to:', 'duplicator') . "
"; $message .= sprintf( /* translators: %s: plugin name */ __('WordPress Admin > %s > Settings > Backups Tab > Cleanup.', 'duplicator'), esc_html(DUPLICATOR____NAME) ) . "
"; $message .= __('That mode will do cleanup of those files automatically for you.', 'duplicator') . "
"; $message .= "
"; $message .= __('Best regards,', 'duplicator') . "
"; $message .= esc_html(DUPLICATOR____NAME); if (wp_mail($to, $subject, $message, ['Content-Type: text/html; charset=UTF-8'])) { // OK DupLog::trace('wp_mail sent email notice regarding cleanup of installer files'); } else { DupLog::trace("Problem sending email notice regarding cleanup of installer files to {$to}"); } if ($switchedLocale) { restore_previous_locale(); } } break; case self::CLEANUP_MODE_AUTO: // Auto Cleanup cron job routine for cleanup of installer files $installerFiles = MigrationMng::cleanMigrationFiles(false, self::CLEANUP_FILE_TIME_DELAY); if (count($installerFiles) == 0) { // No installer files were found, so we do nothing else return; } $filesFailedRemoval = []; foreach ($installerFiles as $path => $success) { if (!$success) { $filesFailedRemoval[] = $path; } } if (count($filesFailedRemoval) == 0) { // All found installer files were removed successfully, // or they did not even need to be removed yet because of CLEANUP_FILE_TIME_DELAY return; } // If this is executed that means that some of installer files // could not be removed for some reason (permission issues?) if (!empty($to)) { // Send an Email Notice about files that could not be removed during auto cleanup, // in the site language regardless of the sending request's locale $switchedLocale = switch_to_locale(get_locale()); $subject = __("Action required", 'duplicator'); $message = sprintf( /* translators: %1$s: plugin name, %2$s: website URL */ __('This email is sent by your WordPress plugin "%1$s" from website: %2$s. ', 'duplicator'), esc_html(DUPLICATOR____NAME), $websiteUrl ); $message .= __('"Auto Cleanup" mode is ON, ', 'duplicator'); $message .= __( 'however the cleanup routine discovered that some installer files (leftovers from migration) could not be removed. ', 'duplicator' ); $message .= __('We strongly advise you to remove those files manually. ', 'duplicator'); $message .= __('Here is the list of files found on your website that you should remove:', 'duplicator') . "
"; foreach ($filesFailedRemoval as $path) { $message .= "-> $path
"; } $message .= "
"; $message .= __('Those files probably could not be removed due to permission issues. ', 'duplicator'); $message .= sprintf( __('You can find more info in FAQ %1$son this link%2$s.', 'duplicator'), "", "" ) . "
"; $message .= "
"; $message .= __('Note: To edit "Cleanup" settings go to:', 'duplicator') . "
"; $message .= sprintf( /* translators: %s: plugin name */ __('WordPress Admin > %s > Settings > Backups Tab > Cleanup.', 'duplicator'), esc_html(DUPLICATOR____NAME) ) . "
"; $message .= "
"; $message .= __('Best regards,', 'duplicator') . "
"; $message .= esc_html(DUPLICATOR____NAME); if (wp_mail($to, $subject, $message, ['Content-Type: text/html; charset=UTF-8'])) { // OK DupLog::trace('wp_mail sent email notice regarding failed auto cleanup of installer files'); } else { DupLog::trace("Problem sending email notice regarding failed auto cleanup of installer files to {$to}"); } if ($switchedLocale) { restore_previous_locale(); } } break; case self::CLEANUP_MODE_OFF: default: break; } } /** * Set archive mode * * @param ?int $archiveBuildMode Archive build mode, if null get INPUT_POST * @param ?int $zipArchiveMode Zip archive mode, if null get INPUT_POST * @param ?bool $archiveCompression Archive compression, if null get INPUT_POST * @param ?bool $ziparchiveValidation Zip archive validation, if null get INPUT_POST * @param ?int $ziparchiveChunkSizeInMb Zip archive chunk size in MB, if null get INPUT_POST * * @return array Submitted values not stored as-is (empty when everything is stored) */ public function setArchiveMode( $archiveBuildMode = null, $zipArchiveMode = null, $archiveCompression = null, $ziparchiveValidation = null, $ziparchiveChunkSizeInMb = null ): array { $newBuildMode = $archiveBuildMode ?? filter_input( INPUT_POST, self::ARCHIVE_BUILD_MODE_KEY, FILTER_VALIDATE_INT, [ 'options' => [ 'min_range' => 1, 'max_range' => 3, ], ] ); // A disabled radio doesn't submit: keep the stored engine. $newBuildMode ??= $this->getBuildMode(); $newCompression = $archiveCompression ?? filter_input(INPUT_POST, self::ARCHIVE_COMPRESSION_KEY, FILTER_VALIDATE_BOOLEAN); // An unavailable submitted value is replaced by the first available one // and reported: the storage always ends up with a valid value. $submitted = [ ArchiveEngineRule::OPTION_KEY => $newBuildMode, CompressionRule::OPTION_KEY => (bool) $newCompression, ]; $failures = OptionsManager::getInstance()->applyValues($submitted); foreach ($failures as $failure) { DupLog::trace( 'Adjusted unavailable option value for ' . $failure->getOptionKey() . ': ' . implode(' ', $failure->getReasons()) ); } $newZipArchiveMode = $zipArchiveMode ?? filter_input( INPUT_POST, self::ZIPARCHIVE_MODE_KEY, FILTER_VALIDATE_INT, [ 'options' => [ 'default' => 0, 'min_range' => 0, 'max_range' => 1, ], ] ); $newZipValidation = $ziparchiveValidation ?? filter_input(INPUT_POST, self::ZIPARCHIVE_VALIDATION_KEY, FILTER_VALIDATE_BOOLEAN); $newChunkSize = $ziparchiveChunkSizeInMb ?? filter_input( INPUT_POST, self::ZIPARCHIVE_CHUNK_SIZE_IN_MB_KEY, FILTER_VALIDATE_INT, [ 'options' => [ 'default' => self::getDefaultZipArchiveChunkSize(), 'min_range' => 1, ], ] ); $this->setZipArchiveMode((int) $newZipArchiveMode, false); $this->setZipArchiveValidation((bool) $newZipValidation, false); if (!$this->setZipArchiveChunkSize((int) $newChunkSize)) { throw new Exception('Unable to save the archive settings.'); } return $failures; } /** * Get archive engine label * * @return string */ public function getArchiveEngine(): string { $buildMode = $this->getBuildMode(); $mode = OptionsManager::getInstance()->getValueLabel(ArchiveEngineRule::OPTION_KEY, $buildMode); if ($buildMode == PackageArchive::BUILD_MODE_ZIP_ARCHIVE) { $mode .= ($this->getZipArchiveMode() == PackageArchive::ZIP_MODE_MULTI_THREAD) ? __(': multi-thread', 'duplicator') : __(': single-thread', 'duplicator'); } return $mode; } /** * Return archive extension type * * @return string */ public function getArchiveExtensionType(): string { $mode = 'zip'; if ($this->getBuildMode() == PackageArchive::BUILD_MODE_DUP_ARCHIVE) { $mode = 'daf'; } return $mode; } /** * Return Mysqldump options * * @return GroupOptions[] */ public function getMysqldumpOptions(): array { $options = []; $loadedOptionNames = []; $stored = DynamicGlobalEntity::getInstance()->getValArray(self::PACKAGE_MYSQLDUMP_OPTIONS_KEY); foreach ($stored as $optionData) { if (!is_array($optionData)) { continue; } $option = GroupOptions::getObjectFromArray($optionData); $options[] = $option; $loadedOptionNames[] = $option->getOptionName(); } foreach (self::getDefaultMysqlDumpOptions() as $defaultOption) { if (!in_array($defaultOption->getOptionName(), $loadedOptionNames, true)) { $options[] = $defaultOption; } } return $options; } /** * Store mysqldump domain options. * * @param GroupOptions[] $options Mysqldump options * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setMysqldumpOptions(array $options, bool $save = true): bool { return DynamicGlobalEntity::getInstance()->setValArray( self::PACKAGE_MYSQLDUMP_OPTIONS_KEY, array_map(static fn(GroupOptions $option): array => $option->toArray(), $options), $save ); } /** * Get manual mode storage ids. * * If none of the stored storages is valid anymore, the default storage id * is added to the returned list so the UI can preselect it. * * @return int[] */ public function getManualModeStorageIds(): array { /** @var int[] $storageIds */ $storageIds = array_values( array_filter( array_map('intval', DynamicGlobalEntity::getInstance()->getValArray(self::MANUAL_MODE_STORAGE_IDS_KEY)), static fn(int $id): bool => $id > 0 ) ); if (count($storageIds) == 0) { return [StoragesUtil::getDefaultStorageId()]; } if (StoragesUtil::hasValidStorage($storageIds)) { return $storageIds; } return array_values(array_unique(array_merge($storageIds, [StoragesUtil::getDefaultStorageId()]))); } /** * Set manual mode storage ids. * * @param int[] $storageIds Storage ids * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setManualModeStorageIds(array $storageIds, bool $save = true): bool { $storageIds = array_values( array_filter( array_map('intval', $storageIds), static fn(int $id): bool => $id > 0 ) ); if (count($storageIds) == 0) { $storageIds = [StoragesUtil::getDefaultStorageId()]; } return DynamicGlobalEntity::getInstance()->setValArray(self::MANUAL_MODE_STORAGE_IDS_KEY, $storageIds, $save); } /** * Return the default mysqldump options as dynamic-setting data. * * @return array */ public static function getDefaultMysqlDumpOptionsData(): array { return array_map( static fn(GroupOptions $option): array => $option->toArray(), self::getDefaultMysqlDumpOptions() ); } /** * Get Email Summary Recipients * * @return string[] */ public function getEmailSummaryRecipients(): array { /** @var string[] $recipients */ $recipients = DynamicGlobalEntity::getInstance()->getValArray(self::EMAIL_SUMMARY_RECIPIENTS_KEY); return $recipients; } /** * Set Email Summary Recipients * * @param string[] $recipients List of recipient email addreses * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setEmailSummaryRecipients(array $recipients, bool $save = true): bool { $recipients = filter_var($recipients, FILTER_VALIDATE_EMAIL, FILTER_REQUIRE_ARRAY); if ($recipients === false) { $recipients = []; } foreach ($recipients as $key => $recipient) { if ($recipient === false) { continue; } $recipients[$key] = sanitize_email($recipient); } return DynamicGlobalEntity::getInstance()->setValArray( self::EMAIL_SUMMARY_RECIPIENTS_KEY, array_values(array_unique($recipients)), $save ); } /** * Get email summary frequency * * @return string */ public function getEmailSummaryFrequency(): string { return DynamicGlobalEntity::getInstance()->getValString(self::EMAIL_SUMMARY_FREQUENCY_KEY); } /** * Set email summary frequency * * @param string $frequency The frequency * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setEmailSummaryFrequency($frequency, bool $save = true): bool { $oldFrequency = $this->getEmailSummaryFrequency(); if (EmailSummaryBootstrap::updateFrequency($oldFrequency, $frequency) === false) { DupLog::trace("Invalid email summary frequency: {$frequency}"); return false; } return DynamicGlobalEntity::getInstance()->setValString(self::EMAIL_SUMMARY_FREQUENCY_KEY, $frequency, $save); } /** * True if AM notifications are enabled * * @return bool */ public function isAmNoticesEnabled(): bool { return DynamicGlobalEntity::getInstance()->getValBool(self::AM_NOTICES_KEY); } /** * Set notifications enabled * * @param bool $enable true if enabled * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setAmNotices(bool $enable, bool $save = true): bool { return DynamicGlobalEntity::getInstance()->setValBool(self::AM_NOTICES_KEY, $enable, $save); } /** * Set purge backup records * * @param int<0,2> $value ENUM AbstractStorageEntity::BACKUP_RECORDS_* * @param bool $save Whether to persist immediately * * @return bool True on success */ public function setPurgeBackupRecords(int $value, bool $save = true): bool { if (!self::isValidPurgeBackupRecordsValue($value)) { throw new Exception('Invalid value'); } return DynamicGlobalEntity::getInstance()->setValInt(self::PURGE_BACKUP_RECORDS_KEY, $value, $save); } /** * Get option on how to handle the old backup records * * @return int<0,2> ENUM AbstractStorageEntity::BACKUP_RECORDS_* */ public function getPurgeBackupRecords(): int { $value = DynamicGlobalEntity::getInstance()->getValInt(self::PURGE_BACKUP_RECORDS_KEY); return self::isValidPurgeBackupRecordsValue($value) ? $value : AbstractStorageEntity::BACKUP_RECORDS_REMOVE_ALL; } /** * Whether a purge-backup-records value is supported. * * @param int $value Value to validate * * @return bool */ private static function isValidPurgeBackupRecordsValue(int $value): bool { return in_array( $value, [ AbstractStorageEntity::BACKUP_RECORDS_REMOVE_ALL, AbstractStorageEntity::BACKUP_RECORDS_REMOVE_NEVER, AbstractStorageEntity::BACKUP_RECORDS_REMOVE_DEFAULT, ], true ); } }
Fatal error: Uncaught Error: Class 'Duplicator\Models\GlobalEntity' not found in /home/emdadcar/public_html/assets/plugins/duplicator/src/Utils/Settings/CoreSettingsDefaults.php:43 Stack trace: #0 /home/emdadcar/public_html/assets/plugins/duplicator/src/Core/Bootstrap.php(72): Duplicator\Utils\Settings\CoreSettingsDefaults::register() #1 /home/emdadcar/public_html/assets/plugins/duplicator/duplicator-main.php(28): Duplicator\Core\Bootstrap::init('7b2273223a22633...') #2 /home/emdadcar/public_html/assets/plugins/duplicator/duplicator.php(48): require_once('/home/emdadcar/...') #3 /home/emdadcar/public_html/wp-settings.php(597): include_once('/home/emdadcar/...') #4 /home/emdadcar/public_html/wp-config.php(111): require_once('/home/emdadcar/...') #5 /home/emdadcar/public_html/wp-load.php(50): require_once('/home/emdadcar/...') #6 /home/emdadcar/public_html/wp-blog-header.php(13): require_once('/home/emdadcar/...') #7 /home/emdadcar/public_html/index.php(17): require('/home/emdadcar/...') #8 {main} thrown in /home/emdadcar/public_html/assets/plugins/duplicator/src/Utils/Settings/CoreSettingsDefaults.php on line 43