+ /**
+ * Clears the directory where this item is going to be installed into.
+ *
+ * @since 4.3.0
+ *
+ * @global WP_Filesystem_Base $wp_filesystem Subclass
+ *
+ * @param string $remote_destination The location on the remote filesystem to be cleared
+ * @return bool|WP_Error True upon success, WP_Error on failure.
+ */
+ public function clear_destination( $remote_destination ) {
+ global $wp_filesystem;
+
+ if ( ! $wp_filesystem->exists( $remote_destination ) ) {
+ return true;
+ }
+
+ // Check all files are writable before attempting to clear the destination.
+ $unwritable_files = array();
+
+ $_files = $wp_filesystem->dirlist( $remote_destination, true, true );
+
+ // Flatten the resulting array, iterate using each as we append to the array during iteration.
+ while ( $f = each( $_files ) ) {
+ $file = $f['value'];
+ $name = $f['key'];
+
+ if ( ! isset( $file['files'] ) ) {
+ continue;
+ }
+
+ foreach ( $file['files'] as $filename => $details ) {
+ $_files[ $name . '/' . $filename ] = $details;
+ }
+ }
+
+ // 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;
+ }
+