���� 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 class-plugin-upgrader-skin.php000064400000006316146715570560012455 0ustar00 '', 'plugin' => '', 'nonce' => '', 'title' => __( 'Update Plugin' ), ); $args = wp_parse_args( $args, $defaults ); $this->plugin = $args['plugin']; $this->plugin_active = is_plugin_active( $this->plugin ); $this->plugin_network_active = is_plugin_active_for_network( $this->plugin ); parent::__construct( $args ); } /** * Performs an action following a single plugin update. * * @since 2.8.0 */ public function after() { $this->plugin = $this->upgrader->plugin_info(); if ( ! empty( $this->plugin ) && ! is_wp_error( $this->result ) && $this->plugin_active ) { // Currently used only when JS is off for a single plugin update? printf( '', esc_attr__( 'Update progress' ), wp_nonce_url( 'update.php?action=activate-plugin&networkwide=' . $this->plugin_network_active . '&plugin=' . urlencode( $this->plugin ), 'activate-plugin_' . $this->plugin ) ); } $this->decrement_update_count( 'plugin' ); $update_actions = array( 'activate_plugin' => sprintf( '%s', wp_nonce_url( 'plugins.php?action=activate&plugin=' . urlencode( $this->plugin ), 'activate-plugin_' . $this->plugin ), __( 'Activate Plugin' ) ), 'plugins_page' => sprintf( '%s', self_admin_url( 'plugins.php' ), __( 'Go to Plugins page' ) ), ); if ( $this->plugin_active || ! $this->result || is_wp_error( $this->result ) || ! current_user_can( 'activate_plugin', $this->plugin ) ) { unset( $update_actions['activate_plugin'] ); } /** * Filters the list of action links available following a single plugin update. * * @since 2.7.0 * * @param string[] $update_actions Array of plugin action links. * @param string $plugin Path to the plugin file relative to the plugins directory. */ $update_actions = apply_filters( 'update_plugin_complete_actions', $update_actions, $this->plugin ); if ( ! empty( $update_actions ) ) { $this->feedback( implode( ' | ', (array) $update_actions ) ); } } } class-ftp-pure.php000064400000012462146715570560010147 0ustar00 // // 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"); } } } ?> translation-install.php000064400000021323146715570560011300 0ustar00 3, 'body' => array( 'wp_version' => $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 Response as an associative array or WP_Error. * @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, each an array of data, keyed by the language. If the API response results * in an error, an empty array will be returned. */ function wp_get_available_translations() { if ( ! wp_installing() ) { $translations = get_site_transient( 'available_translations' ); if ( false !== $translations ) { return $translations; } } // Include an unmodified $wp_version. require ABSPATH . WPINC . '/version.php'; $api = translations_api( 'core', array( 'version' => $wp_version ) ); if ( is_wp_error( $api ) || empty( $api['translations'] ) ) { return array(); } $translations = array(); // Key the array with the language code for now. 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-wp-privacy-data-export-requests-list-table.php000064400000012673146715570560016647 0ustar00status; $request_id = $item->ID; $nonce = wp_create_nonce( 'wp-privacy-export-personal-data-' . $request_id ); $download_data_markup = ''; $download_data_markup .= '' . '' . '' . ''; $download_data_markup .= ''; $row_actions['download-data'] = $download_data_markup; if ( 'request-completed' !== $status ) { $complete_request_markup = ''; $complete_request_markup .= sprintf( '%s', esc_url( wp_nonce_url( add_query_arg( array( 'action' => 'complete', 'request_id' => array( $request_id ), ), admin_url( 'export-personal-data.php' ) ), 'bulk-privacy_requests' ) ), esc_attr( sprintf( /* translators: %s: Request email. */ __( 'Mark export request for “%s” as completed.' ), $item->email ) ), __( 'Complete request' ) ); $complete_request_markup .= ''; } if ( ! empty( $complete_request_markup ) ) { $row_actions['complete-request'] = $complete_request_markup; } return sprintf( '%2$s %3$s', esc_url( 'mailto:' . $item->email ), $item->email, $this->row_actions( $row_actions ) ); } /** * Displays the next steps column. * * @since 4.9.6 * * @param WP_User_Request $item Item being shown. */ public function column_next_steps( $item ) { $status = $item->status; switch ( $status ) { case 'request-pending': esc_html_e( 'Waiting for confirmation' ); break; case 'request-confirmed': /** This filter is documented in wp-admin/includes/ajax-actions.php */ $exporters = apply_filters( 'wp_privacy_personal_data_exporters', array() ); $exporters_count = count( $exporters ); $request_id = $item->ID; $nonce = wp_create_nonce( 'wp-privacy-export-personal-data-' . $request_id ); echo '
'; ?> '; break; case 'request-failed': echo ''; break; case 'request-completed': echo '' . esc_html__( 'Remove request' ) . ''; break; } } } export.php000064400000061735146715570560006632 0ustar00 '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"; ?> <?php bloginfo_rss( 'name' ); ?> 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; ?> <?php echo $title; ?> 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 ); ?> Note that password carefully! It is a random password that was generated just for you.' ); $user_id = wp_create_user( $user_name, $user_password, $user_email ); update_user_meta( $user_id, 'default_password_nag', true ); $email_password = true; $user_created = true; } elseif ( ! $user_id ) { // Password has been provided. $message = '' . __( 'Your chosen password.' ) . ''; $user_id = wp_create_user( $user_name, $user_password, $user_email ); $user_created = true; } else { $message = __( 'User already exists. Password inherited.' ); } $user = new WP_User( $user_id ); $user->set_role( 'administrator' ); if ( $user_created ) { $user->user_url = $guessurl; wp_update_user( $user ); } wp_install_defaults( $user_id ); wp_install_maybe_enable_pretty_permalinks(); flush_rewrite_rules(); wp_new_blog_notification( $blog_title, $guessurl, $user_id, ( $email_password ? $user_password : __( 'The password you chose during installation.' ) ) ); wp_cache_flush(); /** * Fires after a site is fully installed. * * @since 3.9.0 * * @param WP_User $user The site owner. */ do_action( 'wp_install', $user ); return array( 'url' => $guessurl, 'user_id' => $user_id, 'password' => $user_password, 'password_message' => $message, ); } endif; if ( ! function_exists( 'wp_install_defaults' ) ) : /** * Creates the initial content for a newly-installed site. * * Adds the default "Uncategorized" category, the first post (with comment), * first page, and default widgets for default theme for the current version. * * @since 2.1.0 * * @global wpdb $wpdb WordPress database abstraction object. * @global WP_Rewrite $wp_rewrite WordPress rewrite component. * @global string $table_prefix The database table prefix. * * @param int $user_id User ID. */ function wp_install_defaults( $user_id ) { global $wpdb, $wp_rewrite, $table_prefix; // Default category. $cat_name = __( 'Uncategorized' ); /* translators: Default category slug. */ $cat_slug = sanitize_title( _x( 'Uncategorized', 'Default category slug' ) ); $cat_id = 1; $wpdb->insert( $wpdb->terms, array( 'term_id' => $cat_id, 'name' => $cat_name, 'slug' => $cat_slug, 'term_group' => 0, ) ); $wpdb->insert( $wpdb->term_taxonomy, array( 'term_id' => $cat_id, 'taxonomy' => 'category', 'description' => '', 'parent' => 0, 'count' => 1, ) ); $cat_tt_id = $wpdb->insert_id; // First post. $now = current_time( 'mysql' ); $now_gmt = current_time( 'mysql', 1 ); $first_post_guid = get_option( 'home' ) . '/?p=1'; if ( is_multisite() ) { $first_post = get_site_option( 'first_post' ); if ( ! $first_post ) { $first_post = "\n

" . /* translators: First post content. %s: Site link. */ __( 'Welcome to %s. This is your first post. Edit or delete it, then start writing!' ) . "

\n"; } $first_post = sprintf( $first_post, sprintf( '%s', esc_url( network_home_url() ), get_network()->site_name ) ); // Back-compat for pre-4.4. $first_post = str_replace( 'SITE_URL', esc_url( network_home_url() ), $first_post ); $first_post = str_replace( 'SITE_NAME', get_network()->site_name, $first_post ); } else { $first_post = "\n

" . /* translators: First post content. %s: Site link. */ __( 'Welcome to WordPress. This is your first post. Edit or delete it, then start writing!' ) . "

\n"; } $wpdb->insert( $wpdb->posts, array( 'post_author' => $user_id, 'post_date' => $now, 'post_date_gmt' => $now_gmt, 'post_content' => $first_post, 'post_excerpt' => '', 'post_title' => __( 'Hello world!' ), /* translators: Default post slug. */ 'post_name' => sanitize_title( _x( 'hello-world', 'Default post slug' ) ), 'post_modified' => $now, 'post_modified_gmt' => $now_gmt, 'guid' => $first_post_guid, 'comment_count' => 1, 'to_ping' => '', 'pinged' => '', 'post_content_filtered' => '', ) ); if ( is_multisite() ) { update_posts_count(); } $wpdb->insert( $wpdb->term_relationships, array( 'term_taxonomy_id' => $cat_tt_id, 'object_id' => 1, ) ); // Default comment. if ( is_multisite() ) { $first_comment_author = get_site_option( 'first_comment_author' ); $first_comment_email = get_site_option( 'first_comment_email' ); $first_comment_url = get_site_option( 'first_comment_url', network_home_url() ); $first_comment = get_site_option( 'first_comment' ); } $first_comment_author = ! empty( $first_comment_author ) ? $first_comment_author : __( 'A WordPress Commenter' ); $first_comment_email = ! empty( $first_comment_email ) ? $first_comment_email : 'wapuu@wordpress.example'; $first_comment_url = ! empty( $first_comment_url ) ? $first_comment_url : esc_url( __( 'https://wordpress.org/' ) ); $first_comment = ! empty( $first_comment ) ? $first_comment : sprintf( /* translators: %s: Gravatar URL. */ __( 'Hi, this is a comment. To get started with moderating, editing, and deleting comments, please visit the Comments screen in the dashboard. Commenter avatars come from Gravatar.' ), esc_url( __( 'https://en.gravatar.com/' ) ) ); $wpdb->insert( $wpdb->comments, array( 'comment_post_ID' => 1, 'comment_author' => $first_comment_author, 'comment_author_email' => $first_comment_email, 'comment_author_url' => $first_comment_url, 'comment_date' => $now, 'comment_date_gmt' => $now_gmt, 'comment_content' => $first_comment, 'comment_type' => 'comment', ) ); // First page. if ( is_multisite() ) { $first_page = get_site_option( 'first_page' ); } if ( empty( $first_page ) ) { $first_page = "\n

"; /* 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 .= "

\n"; } $first_post_guid = get_option( 'home' ) . '/?page_id=2'; $wpdb->insert( $wpdb->posts, array( 'post_author' => $user_id, 'post_date' => $now, 'post_date_gmt' => $now_gmt, 'post_content' => $first_page, 'post_excerpt' => '', 'comment_status' => 'closed', 'post_title' => __( 'Sample Page' ), /* translators: Default page slug. */ 'post_name' => __( 'sample-page' ), 'post_modified' => $now, 'post_modified_gmt' => $now_gmt, 'guid' => $first_post_guid, 'post_type' => 'page', 'to_ping' => '', 'pinged' => '', 'post_content_filtered' => '', ) ); $wpdb->insert( $wpdb->postmeta, array( 'post_id' => 2, 'meta_key' => '_wp_page_template', 'meta_value' => 'default', ) ); // Privacy Policy page. if ( is_multisite() ) { // Disable by default unless the suggested content is provided. $privacy_policy_content = get_site_option( 'default_privacy_policy_content' ); } else { if ( ! class_exists( 'WP_Privacy_Policy_Content' ) ) { require_once ABSPATH . 'wp-admin/includes/class-wp-privacy-policy-content.php'; } $privacy_policy_content = WP_Privacy_Policy_Content::get_default_content(); } if ( ! empty( $privacy_policy_content ) ) { $privacy_policy_guid = get_option( 'home' ) . '/?page_id=3'; $wpdb->insert( $wpdb->posts, array( 'post_author' => $user_id, 'post_date' => $now, 'post_date_gmt' => $now_gmt, 'post_content' => $privacy_policy_content, 'post_excerpt' => '', 'comment_status' => 'closed', 'post_title' => __( 'Privacy Policy' ), /* translators: Privacy Policy page slug. */ 'post_name' => __( 'privacy-policy' ), 'post_modified' => $now, 'post_modified_gmt' => $now_gmt, 'guid' => $privacy_policy_guid, 'post_type' => 'page', 'post_status' => 'draft', 'to_ping' => '', 'pinged' => '', 'post_content_filtered' => '', ) ); $wpdb->insert( $wpdb->postmeta, array( 'post_id' => 3, 'meta_key' => '_wp_page_template', 'meta_value' => 'default', ) ); update_option( 'wp_page_for_privacy_policy', 3 ); } // Set up default widgets for default theme. update_option( 'widget_block', array( 2 => array( 'content' => '' ), 3 => array( 'content' => '

' . __( 'Recent Posts' ) . '

' ), 4 => array( 'content' => '

' . __( 'Recent Comments' ) . '

' ), 5 => array( 'content' => '

' . __( 'Archives' ) . '

' ), 6 => array( 'content' => '

' . __( 'Categories' ) . '

' ), '_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 = __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 = __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(); } 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 != $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 ( 1 != $option->dupes ) { // 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 == $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 ( get_option( 'thread_comments_depth' ) == '1' ) { 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, 'no' ); } } } /** * 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, '', 'yes' ); } } } } /** * 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, 'no' ); wp_set_option_autoload_values( $autoload ); } } /** * 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 "
  1. $alteration
  2. \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-wp-upgrader.php000064400000133713146715570560010645 0ustar00skin = 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['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']; 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; $source_files = array_keys( $wp_filesystem->dirlist( $remote_source ) ); $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 ) { $source_files = array_keys( $wp_filesystem->dirlist( $source ) ); } /* * 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() ); 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'; class-custom-image-header.php000064400000137650146715570560012234 0ustar00admin_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.' ) . '

', ) ); get_current_screen()->add_help_tab( array( 'id' => 'set-header-image', 'title' => __( 'Header Image' ), 'content' => '

' . __( '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”.' ) . '

', ) ); get_current_screen()->add_help_tab( array( 'id' => 'set-header-text', 'title' => __( 'Header Text' ), 'content' => '

' . 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!' ) . '

', ) ); get_current_screen()->set_help_sidebar( '

' . __( 'For more information:' ) . '

' . '

' . __( 'Documentation on Custom Header' ) . '

' . '

' . __( 'Support forums' ) . '

' ); } /** * Gets the current step. * * @since 2.6.0 * * @return int Current step. */ public function step() { if ( ! isset( $_GET['step'] ) ) { return 1; } $step = (int) $_GET['step']; if ( $step < 1 || 3 < $step || ( 2 === $step && ! wp_verify_nonce( $_REQUEST['_wpnonce-custom-header-upload'], 'custom-header-upload' ) ) || ( 3 === $step && ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'custom-header-crop-image' ) ) ) { return 1; } return $step; } /** * Sets up the enqueue for the JavaScript files. * * @since 2.1.0 */ public function js_includes() { $step = $this->step(); if ( ( 1 === $step || 3 === $step ) ) { wp_enqueue_media(); wp_enqueue_script( 'custom-header' ); if ( current_theme_supports( 'custom-header', 'header-text' ) ) { wp_enqueue_script( 'wp-color-picker' ); } } elseif ( 2 === $step ) { wp_enqueue_script( 'imgareaselect' ); } } /** * Sets up the enqueue for the CSS files. * * @since 2.7.0 */ public function css_includes() { $step = $this->step(); if ( ( 1 === $step || 3 === $step ) && current_theme_supports( 'custom-header', 'header-text' ) ) { wp_enqueue_style( 'wp-color-picker' ); } elseif ( 2 === $step ) { wp_enqueue_style( 'imgareaselect' ); } } /** * Executes custom header modification. * * @since 2.6.0 */ public function take_action() { if ( ! current_user_can( 'edit_theme_options' ) ) { return; } if ( empty( $_POST ) ) { return; } $this->updated = true; if ( isset( $_POST['resetheader'] ) ) { check_admin_referer( 'custom-header-options', '_wpnonce-custom-header-options' ); $this->reset_header_image(); return; } if ( isset( $_POST['removeheader'] ) ) { check_admin_referer( 'custom-header-options', '_wpnonce-custom-header-options' ); $this->remove_header_image(); return; } if ( isset( $_POST['text-color'] ) && ! isset( $_POST['display-header-text'] ) ) { check_admin_referer( 'custom-header-options', '_wpnonce-custom-header-options' ); set_theme_mod( 'header_textcolor', 'blank' ); } elseif ( isset( $_POST['text-color'] ) ) { check_admin_referer( 'custom-header-options', '_wpnonce-custom-header-options' ); $_POST['text-color'] = str_replace( '#', '', $_POST['text-color'] ); $color = preg_replace( '/[^0-9a-fA-F]/', '', $_POST['text-color'] ); if ( strlen( $color ) === 6 || strlen( $color ) === 3 ) { set_theme_mod( 'header_textcolor', $color ); } elseif ( ! $color ) { set_theme_mod( 'header_textcolor', 'blank' ); } } if ( isset( $_POST['default-header'] ) ) { check_admin_referer( 'custom-header-options', '_wpnonce-custom-header-options' ); $this->set_header_image( $_POST['default-header'] ); return; } } /** * Processes the default headers. * * @since 3.0.0 * * @global array $_wp_default_headers */ public function process_default_headers() { global $_wp_default_headers; if ( ! isset( $_wp_default_headers ) ) { return; } if ( ! empty( $this->default_headers ) ) { return; } $this->default_headers = $_wp_default_headers; $template_directory_uri = get_template_directory_uri(); $stylesheet_directory_uri = get_stylesheet_directory_uri(); foreach ( array_keys( $this->default_headers ) as $header ) { $this->default_headers[ $header ]['url'] = sprintf( $this->default_headers[ $header ]['url'], $template_directory_uri, $stylesheet_directory_uri ); $this->default_headers[ $header ]['thumbnail_url'] = sprintf( $this->default_headers[ $header ]['thumbnail_url'], $template_directory_uri, $stylesheet_directory_uri ); } } /** * Displays UI for selecting one of several default headers. * * Shows the random image option if this theme has multiple header images. * Random image option is on by default if no header has been set. * * @since 3.0.0 * * @param string $type The header type. One of 'default' (for the Uploaded Images control) * or 'uploaded' (for the Uploaded Images control). */ public function show_header_selector( $type = 'default' ) { if ( 'default' === $type ) { $headers = $this->default_headers; } else { $headers = get_uploaded_header_images(); $type = 'uploaded'; } if ( 1 < count( $headers ) ) { echo '
'; echo ''; echo '
'; } echo '
'; foreach ( $headers as $header_key => $header ) { $header_thumbnail = $header['thumbnail_url']; $header_url = $header['url']; $header_alt_text = empty( $header['alt_text'] ) ? '' : $header['alt_text']; echo '
'; echo ''; echo '
'; } echo '
'; } /** * Executes JavaScript depending on step. * * @since 2.1.0 */ public function js() { $step = $this->step(); if ( ( 1 === $step || 3 === $step ) && current_theme_supports( 'custom-header', 'header-text' ) ) { $this->js_1(); } elseif ( 2 === $step ) { $this->js_2(); } } /** * Displays JavaScript based on Step 1 and 3. * * @since 2.6.0 */ public function js_1() { $default_color = ''; if ( current_theme_supports( 'custom-header', 'default-text-color' ) ) { $default_color = get_theme_support( 'custom-header', 'default-text-color' ); if ( $default_color && ! str_contains( $default_color, '#' ) ) { $default_color = '#' . $default_color; } } ?> process_default_headers(); ?>

Customizer.' ), admin_url( 'customize.php?autofocus[control]=header_image' ) ); wp_admin_notice( $message, array( 'type' => 'info', 'additional_classes' => array( 'hide-if-no-customize' ), ) ); } if ( ! empty( $this->updated ) ) { $updated_message = sprintf( /* translators: %s: Home URL. */ __( 'Header updated. Visit your site to see how it looks.' ), esc_url( home_url( '/' ) ) ); wp_admin_notice( $updated_message, array( 'id' => 'message', 'additional_classes' => array( 'updated' ), ) ); } ?>

default_headers ) ) : ?>

' . __( 'Something went wrong.' ) . '' . '

' . __( 'The active theme does not support uploading a custom header image.' ) . '

', 403 ); } if ( empty( $_POST ) && isset( $_GET['file'] ) ) { $attachment_id = absint( $_GET['file'] ); $file = get_attached_file( $attachment_id, true ); $url = wp_get_attachment_image_src( $attachment_id, 'full' ); $url = $url[0]; } elseif ( isset( $_POST ) ) { $data = $this->step_2_manage_upload(); $attachment_id = $data['attachment_id']; $file = $data['file']; $url = $data['url']; } if ( file_exists( $file ) ) { list( $width, $height, $type, $attr ) = wp_getimagesize( $file ); } else { $data = wp_get_attachment_metadata( $attachment_id ); $height = isset( $data['height'] ) ? (int) $data['height'] : 0; $width = isset( $data['width'] ) ? (int) $data['width'] : 0; unset( $data ); } $max_width = 0; // For flex, limit size of image displayed to 1500px unless theme says otherwise. if ( current_theme_supports( 'custom-header', 'flex-width' ) ) { $max_width = 1500; } if ( current_theme_supports( 'custom-header', 'max-width' ) ) { $max_width = max( $max_width, get_theme_support( 'custom-header', 'max-width' ) ); } $max_width = max( $max_width, get_theme_support( 'custom-header', 'width' ) ); // If flexible height isn't supported and the image is the exact right size. if ( ! current_theme_supports( 'custom-header', 'flex-height' ) && ! current_theme_supports( 'custom-header', 'flex-width' ) && (int) get_theme_support( 'custom-header', 'width' ) === $width && (int) get_theme_support( 'custom-header', 'height' ) === $height ) { // Add the metadata. if ( file_exists( $file ) ) { wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) ); } $this->set_header_image( compact( 'url', 'attachment_id', 'width', 'height' ) ); /** * Filters the attachment file path after the custom header or background image is set. * * Used for file replication. * * @since 2.1.0 * * @param string $file Path to the file. * @param int $attachment_id Attachment ID. */ $file = apply_filters( 'wp_create_file_in_uploads', $file, $attachment_id ); // For replication. return $this->finished(); } elseif ( $width > $max_width ) { $oitar = $width / $max_width; $image = wp_crop_image( $attachment_id, 0, 0, $width, $height, $max_width, $height / $oitar, false, str_replace( wp_basename( $file ), 'midsize-' . wp_basename( $file ), $file ) ); if ( ! $image || is_wp_error( $image ) ) { 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 */ $image = apply_filters( 'wp_create_file_in_uploads', $image, $attachment_id ); // For replication. $url = str_replace( wp_basename( $url ), wp_basename( $image ), $url ); $width = $width / $oitar; $height = $height / $oitar; } else { $oitar = 1; } ?>

false ); $uploaded_file = $_FILES['import']; $wp_filetype = wp_check_filetype_and_ext( $uploaded_file['tmp_name'], $uploaded_file['name'] ); if ( ! wp_match_mime_types( 'image', $wp_filetype['type'] ) ) { wp_die( __( 'The uploaded file is not a valid image. Please try again.' ) ); } $file = wp_handle_upload( $uploaded_file, $overrides ); if ( isset( $file['error'] ) ) { wp_die( $file['error'], __( 'Image Upload Error' ) ); } $url = $file['url']; $type = $file['type']; $file = $file['file']; $filename = wp_basename( $file ); // Construct the attachment array. $attachment = array( 'post_title' => $filename, 'post_content' => $url, 'post_mime_type' => $type, 'guid' => $url, 'context' => 'custom-header', ); // Save the data. $attachment_id = wp_insert_attachment( $attachment, $file ); return compact( 'attachment_id', 'file', 'filename', 'url', 'type' ); } /** * Displays third step of custom header image page. * * @since 2.1.0 * @since 4.4.0 Switched to using wp_get_attachment_url() instead of the guid * for retrieving the header image URL. */ public function step_3() { check_admin_referer( 'custom-header-crop-image' ); if ( ! current_theme_supports( 'custom-header', 'uploads' ) ) { wp_die( '

' . __( 'Something went wrong.' ) . '

' . '

' . __( 'The active theme does not support uploading a custom header image.' ) . '

', 403 ); } if ( ! empty( $_POST['skip-cropping'] ) && ! current_theme_supports( 'custom-header', 'flex-height' ) && ! current_theme_supports( 'custom-header', 'flex-width' ) ) { wp_die( '

' . __( 'Something went wrong.' ) . '

' . '

' . __( '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; } } image.php000064400000121614146715570560006364 0ustar00crop( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs ); if ( is_wp_error( $src ) ) { return $src; } if ( ! $dst_file ) { $dst_file = str_replace( wp_basename( $src_file ), 'cropped-' . wp_basename( $src_file ), $src_file ); } /* * The directory containing the original file may no longer exist when * using a replication plugin. */ wp_mkdir_p( dirname( $dst_file ) ); $dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), wp_basename( $dst_file ) ); $result = $editor->save( $dst_file ); if ( is_wp_error( $result ) ) { return $result; } if ( ! empty( $result['path'] ) ) { return $result['path']; } return $dst_file; } /** * Compare the existing image sub-sizes (as saved in the attachment meta) * to the currently registered image sub-sizes, and return the difference. * * Registered sub-sizes that are larger than the image are skipped. * * @since 5.3.0 * * @param int $attachment_id The image attachment post ID. * @return array[] Associative array of arrays of image sub-size information for * missing image sizes, keyed by image size name. */ function wp_get_missing_image_subsizes( $attachment_id ) { if ( ! wp_attachment_is_image( $attachment_id ) ) { return array(); } $registered_sizes = wp_get_registered_image_subsizes(); $image_meta = wp_get_attachment_metadata( $attachment_id ); // Meta error? if ( empty( $image_meta ) ) { return $registered_sizes; } // Use the originally uploaded image dimensions as full_width and full_height. if ( ! empty( $image_meta['original_image'] ) ) { $image_file = wp_get_original_image_path( $attachment_id ); $imagesize = wp_getimagesize( $image_file ); } if ( ! empty( $imagesize ) ) { $full_width = $imagesize[0]; $full_height = $imagesize[1]; } else { $full_width = (int) $image_meta['width']; $full_height = (int) $image_meta['height']; } $possible_sizes = array(); // Skip registered sizes that are too large for the uploaded image. foreach ( $registered_sizes as $size_name => $size_data ) { if ( image_resize_dimensions( $full_width, $full_height, $size_data['width'], $size_data['height'], $size_data['crop'] ) ) { $possible_sizes[ $size_name ] = $size_data; } } if ( empty( $image_meta['sizes'] ) ) { $image_meta['sizes'] = array(); } /* * Remove sizes that already exist. Only checks for matching "size names". * It is possible that the dimensions for a particular size name have changed. * For example the user has changed the values on the Settings -> Media screen. * However we keep the old sub-sizes with the previous dimensions * as the image may have been used in an older post. */ $missing_sizes = array_diff_key( $possible_sizes, $image_meta['sizes'] ); /** * Filters the array of missing image sub-sizes for an uploaded image. * * @since 5.3.0 * * @param array[] $missing_sizes Associative array of arrays of image sub-size information for * missing image sizes, keyed by image size name. * @param array $image_meta The image meta data. * @param int $attachment_id The image attachment post ID. */ return apply_filters( 'wp_get_missing_image_subsizes', $missing_sizes, $image_meta, $attachment_id ); } /** * If any of the currently registered image sub-sizes are missing, * create them and update the image meta data. * * @since 5.3.0 * * @param int $attachment_id The image attachment post ID. * @return array|WP_Error The updated image meta data array or WP_Error object * if both the image meta and the attached file are missing. */ function wp_update_image_subsizes( $attachment_id ) { $image_meta = wp_get_attachment_metadata( $attachment_id ); $image_file = wp_get_original_image_path( $attachment_id ); if ( empty( $image_meta ) || ! is_array( $image_meta ) ) { /* * Previously failed upload? * If there is an uploaded file, make all sub-sizes and generate all of the attachment meta. */ if ( ! empty( $image_file ) ) { $image_meta = wp_create_image_subsizes( $image_file, $attachment_id ); } else { return new WP_Error( 'invalid_attachment', __( 'The attached file cannot be found.' ) ); } } else { $missing_sizes = wp_get_missing_image_subsizes( $attachment_id ); if ( empty( $missing_sizes ) ) { return $image_meta; } // This also updates the image meta. $image_meta = _wp_make_subsizes( $missing_sizes, $image_file, $image_meta, $attachment_id ); } /** This filter is documented in wp-admin/includes/image.php */ $image_meta = apply_filters( 'wp_generate_attachment_metadata', $image_meta, $attachment_id, 'update' ); // Save the updated metadata. wp_update_attachment_metadata( $attachment_id, $image_meta ); return $image_meta; } /** * Updates the attached file and image meta data when the original image was edited. * * @since 5.3.0 * @since 6.0.0 The `$filesize` value was added to the returned array. * @access private * * @param array $saved_data The data returned from WP_Image_Editor after successfully saving an image. * @param string $original_file Path to the original file. * @param array $image_meta The image meta data. * @param int $attachment_id The attachment post ID. * @return array The updated image meta data. */ function _wp_image_meta_replace_original( $saved_data, $original_file, $image_meta, $attachment_id ) { $new_file = $saved_data['path']; // Update the attached file meta. update_attached_file( $attachment_id, $new_file ); // Width and height of the new image. $image_meta['width'] = $saved_data['width']; $image_meta['height'] = $saved_data['height']; // Make the file path relative to the upload dir. $image_meta['file'] = _wp_relative_upload_path( $new_file ); // Add image file size. $image_meta['filesize'] = wp_filesize( $new_file ); // Store the original image file name in image_meta. $image_meta['original_image'] = wp_basename( $original_file ); return $image_meta; } /** * Creates image sub-sizes, adds the new data to the image meta `sizes` array, and updates the image metadata. * * Intended for use after an image is uploaded. Saves/updates the image metadata after each * sub-size is created. If there was an error, it is added to the returned image metadata array. * * @since 5.3.0 * * @param string $file Full path to the image file. * @param int $attachment_id Attachment ID to process. * @return array The image attachment meta data. */ function wp_create_image_subsizes( $file, $attachment_id ) { $imagesize = wp_getimagesize( $file ); if ( empty( $imagesize ) ) { // File is not an image. return array(); } // Default image meta. $image_meta = array( 'width' => $imagesize[0], 'height' => $imagesize[1], 'file' => _wp_relative_upload_path( $file ), 'filesize' => wp_filesize( $file ), 'sizes' => array(), ); // Fetch additional metadata from EXIF/IPTC. $exif_meta = wp_read_image_metadata( $file ); if ( $exif_meta ) { $image_meta['image_meta'] = $exif_meta; } // Do not scale (large) PNG images. May result in sub-sizes that have greater file size than the original. See #48736. if ( 'image/png' !== $imagesize['mime'] ) { /** * Filters the "BIG image" threshold value. * * If the original image width or height is above the threshold, it will be scaled down. The threshold is * used as max width and max height. The scaled down image will be used as the largest available size, including * the `_wp_attached_file` post meta value. * * Returning `false` from the filter callback will disable the scaling. * * @since 5.3.0 * * @param int $threshold The threshold value in pixels. Default 2560. * @param array $imagesize { * Indexed array of the image width and height in pixels. * * @type int $0 The image width. * @type int $1 The image height. * } * @param string $file Full path to the uploaded image file. * @param int $attachment_id Attachment post ID. */ $threshold = (int) apply_filters( 'big_image_size_threshold', 2560, $imagesize, $file, $attachment_id ); /* * If the original image's dimensions are over the threshold, * scale the image and use it as the "full" size. */ if ( $threshold && ( $image_meta['width'] > $threshold || $image_meta['height'] > $threshold ) ) { $editor = wp_get_image_editor( $file ); if ( is_wp_error( $editor ) ) { // This image cannot be edited. return $image_meta; } // Resize the image. $resized = $editor->resize( $threshold, $threshold ); $rotated = null; // If there is EXIF data, rotate according to EXIF Orientation. if ( ! is_wp_error( $resized ) && is_array( $exif_meta ) ) { $resized = $editor->maybe_exif_rotate(); $rotated = $resized; } if ( ! is_wp_error( $resized ) ) { /* * Append "-scaled" to the image file name. It will look like "my_image-scaled.jpg". * This doesn't affect the sub-sizes names as they are generated from the original image (for best quality). */ $saved = $editor->save( $editor->generate_filename( 'scaled' ) ); if ( ! is_wp_error( $saved ) ) { $image_meta = _wp_image_meta_replace_original( $saved, $file, $image_meta, $attachment_id ); // If the image was rotated update the stored EXIF data. if ( true === $rotated && ! empty( $image_meta['image_meta']['orientation'] ) ) { $image_meta['image_meta']['orientation'] = 1; } } else { // TODO: Log errors. } } else { // TODO: Log errors. } } elseif ( ! empty( $exif_meta['orientation'] ) && 1 !== (int) $exif_meta['orientation'] ) { // Rotate the whole original image if there is EXIF data and "orientation" is not 1. $editor = wp_get_image_editor( $file ); if ( is_wp_error( $editor ) ) { // This image cannot be edited. return $image_meta; } // Rotate the image. $rotated = $editor->maybe_exif_rotate(); if ( true === $rotated ) { // Append `-rotated` to the image file name. $saved = $editor->save( $editor->generate_filename( 'rotated' ) ); if ( ! is_wp_error( $saved ) ) { $image_meta = _wp_image_meta_replace_original( $saved, $file, $image_meta, $attachment_id ); // Update the stored EXIF data. if ( ! empty( $image_meta['image_meta']['orientation'] ) ) { $image_meta['image_meta']['orientation'] = 1; } } else { // TODO: Log errors. } } } } /* * Initial save of the new metadata. * At this point the file was uploaded and moved to the uploads directory * but the image sub-sizes haven't been created yet and the `sizes` array is empty. */ wp_update_attachment_metadata( $attachment_id, $image_meta ); $new_sizes = wp_get_registered_image_subsizes(); /** * Filters the image sizes automatically generated when uploading an image. * * @since 2.9.0 * @since 4.4.0 Added the `$image_meta` argument. * @since 5.3.0 Added the `$attachment_id` argument. * * @param array $new_sizes Associative array of image sizes to be created. * @param array $image_meta The image meta data: width, height, file, sizes, etc. * @param int $attachment_id The attachment post ID for the image. */ $new_sizes = apply_filters( 'intermediate_image_sizes_advanced', $new_sizes, $image_meta, $attachment_id ); return _wp_make_subsizes( $new_sizes, $file, $image_meta, $attachment_id ); } /** * Low-level function to create image sub-sizes. * * Updates the image meta after each sub-size is created. * Errors are stored in the returned image metadata array. * * @since 5.3.0 * @access private * * @param array $new_sizes Array defining what sizes to create. * @param string $file Full path to the image file. * @param array $image_meta The attachment meta data array. * @param int $attachment_id Attachment ID to process. * @return array The attachment meta data with updated `sizes` array. Includes an array of errors encountered while resizing. */ function _wp_make_subsizes( $new_sizes, $file, $image_meta, $attachment_id ) { if ( empty( $image_meta ) || ! is_array( $image_meta ) ) { // Not an image attachment. return array(); } // Check if any of the new sizes already exist. if ( isset( $image_meta['sizes'] ) && is_array( $image_meta['sizes'] ) ) { foreach ( $image_meta['sizes'] as $size_name => $size_meta ) { /* * Only checks "size name" so we don't override existing images even if the dimensions * don't match the currently defined size with the same name. * To change the behavior, unset changed/mismatched sizes in the `sizes` array in image meta. */ if ( array_key_exists( $size_name, $new_sizes ) ) { unset( $new_sizes[ $size_name ] ); } } } else { $image_meta['sizes'] = array(); } if ( empty( $new_sizes ) ) { // Nothing to do... return $image_meta; } /* * Sort the image sub-sizes in order of priority when creating them. * This ensures there is an appropriate sub-size the user can access immediately * even when there was an error and not all sub-sizes were created. */ $priority = array( 'medium' => null, 'large' => null, 'thumbnail' => null, 'medium_large' => null, ); $new_sizes = array_filter( array_merge( $priority, $new_sizes ) ); $editor = wp_get_image_editor( $file ); if ( is_wp_error( $editor ) ) { // The image cannot be edited. return $image_meta; } // If stored EXIF data exists, rotate the source image before creating sub-sizes. if ( ! empty( $image_meta['image_meta'] ) ) { $rotated = $editor->maybe_exif_rotate(); if ( is_wp_error( $rotated ) ) { // TODO: Log errors. } } if ( method_exists( $editor, 'make_subsize' ) ) { foreach ( $new_sizes as $new_size_name => $new_size_data ) { $new_size_meta = $editor->make_subsize( $new_size_data ); if ( is_wp_error( $new_size_meta ) ) { // TODO: Log errors. } else { // Save the size meta value. $image_meta['sizes'][ $new_size_name ] = $new_size_meta; wp_update_attachment_metadata( $attachment_id, $image_meta ); } } } else { // Fall back to `$editor->multi_resize()`. $created_sizes = $editor->multi_resize( $new_sizes ); if ( ! empty( $created_sizes ) ) { $image_meta['sizes'] = array_merge( $image_meta['sizes'], $created_sizes ); wp_update_attachment_metadata( $attachment_id, $image_meta ); } } return $image_meta; } /** * Copy parent attachment properties to newly cropped image. * * @since 6.5.0 * * @param string $cropped Path to the cropped image file. * @param int $parent_attachment_id Parent file Attachment ID. * @param string $context Control calling the function. * @return array Properties of attachment. */ function wp_copy_parent_attachment_properties( $cropped, $parent_attachment_id, $context = '' ) { $parent = get_post( $parent_attachment_id ); $parent_url = wp_get_attachment_url( $parent->ID ); $parent_basename = wp_basename( $parent_url ); $url = str_replace( wp_basename( $parent_url ), wp_basename( $cropped ), $parent_url ); $size = wp_getimagesize( $cropped ); $image_type = $size ? $size['mime'] : 'image/jpeg'; $sanitized_post_title = sanitize_file_name( $parent->post_title ); $use_original_title = ( ( '' !== trim( $parent->post_title ) ) && /* * Check if the original image has a title other than the "filename" default, * meaning the image had a title when originally uploaded or its title was edited. */ ( $parent_basename !== $sanitized_post_title ) && ( pathinfo( $parent_basename, PATHINFO_FILENAME ) !== $sanitized_post_title ) ); $use_original_description = ( '' !== trim( $parent->post_content ) ); $attachment = array( 'post_title' => $use_original_title ? $parent->post_title : wp_basename( $cropped ), 'post_content' => $use_original_description ? $parent->post_content : $url, 'post_mime_type' => $image_type, 'guid' => $url, 'context' => $context, ); // Copy the image caption attribute (post_excerpt field) from the original image. if ( '' !== trim( $parent->post_excerpt ) ) { $attachment['post_excerpt'] = $parent->post_excerpt; } // Copy the image alt text attribute from the original image. if ( '' !== trim( $parent->_wp_attachment_image_alt ) ) { $attachment['meta_input'] = array( '_wp_attachment_image_alt' => wp_slash( $parent->_wp_attachment_image_alt ), ); } $attachment['post_parent'] = $parent_attachment_id; return $attachment; } /** * Generates attachment meta data and create image sub-sizes for images. * * @since 2.1.0 * @since 6.0.0 The `$filesize` value was added to the returned array. * * @param int $attachment_id Attachment ID to process. * @param string $file Filepath of the attached image. * @return array Metadata for attachment. */ function wp_generate_attachment_metadata( $attachment_id, $file ) { $attachment = get_post( $attachment_id ); $metadata = array(); $support = false; $mime_type = get_post_mime_type( $attachment ); if ( preg_match( '!^image/!', $mime_type ) && file_is_displayable_image( $file ) ) { // Make thumbnails and other intermediate sizes. $metadata = wp_create_image_subsizes( $file, $attachment_id ); } elseif ( wp_attachment_is( 'video', $attachment ) ) { $metadata = wp_read_video_metadata( $file ); $support = current_theme_supports( 'post-thumbnails', 'attachment:video' ) || post_type_supports( 'attachment:video', 'thumbnail' ); } elseif ( wp_attachment_is( 'audio', $attachment ) ) { $metadata = wp_read_audio_metadata( $file ); $support = current_theme_supports( 'post-thumbnails', 'attachment:audio' ) || post_type_supports( 'attachment:audio', 'thumbnail' ); } /* * wp_read_video_metadata() and wp_read_audio_metadata() return `false` * if the attachment does not exist in the local filesystem, * so make sure to convert the value to an array. */ if ( ! is_array( $metadata ) ) { $metadata = array(); } if ( $support && ! empty( $metadata['image']['data'] ) ) { // Check for existing cover. $hash = md5( $metadata['image']['data'] ); $posts = get_posts( array( 'fields' => 'ids', 'post_type' => 'attachment', 'post_mime_type' => $metadata['image']['mime'], 'post_status' => 'inherit', 'posts_per_page' => 1, 'meta_key' => '_cover_hash', 'meta_value' => $hash, ) ); $exists = reset( $posts ); if ( ! empty( $exists ) ) { update_post_meta( $attachment_id, '_thumbnail_id', $exists ); } else { $ext = '.jpg'; switch ( $metadata['image']['mime'] ) { case 'image/gif': $ext = '.gif'; break; case 'image/png': $ext = '.png'; break; case 'image/webp': $ext = '.webp'; break; } $basename = str_replace( '.', '-', wp_basename( $file ) ) . '-image' . $ext; $uploaded = wp_upload_bits( $basename, '', $metadata['image']['data'] ); if ( false === $uploaded['error'] ) { $image_attachment = array( 'post_mime_type' => $metadata['image']['mime'], 'post_type' => 'attachment', 'post_content' => '', ); /** * Filters the parameters for the attachment thumbnail creation. * * @since 3.9.0 * * @param array $image_attachment An array of parameters to create the thumbnail. * @param array $metadata Current attachment metadata. * @param array $uploaded { * Information about the newly-uploaded file. * * @type string $file Filename of the newly-uploaded file. * @type string $url URL of the uploaded file. * @type string $type File type. * } */ $image_attachment = apply_filters( 'attachment_thumbnail_args', $image_attachment, $metadata, $uploaded ); $sub_attachment_id = wp_insert_attachment( $image_attachment, $uploaded['file'] ); add_post_meta( $sub_attachment_id, '_cover_hash', $hash ); $attach_data = wp_generate_attachment_metadata( $sub_attachment_id, $uploaded['file'] ); wp_update_attachment_metadata( $sub_attachment_id, $attach_data ); update_post_meta( $attachment_id, '_thumbnail_id', $sub_attachment_id ); } } } elseif ( 'application/pdf' === $mime_type ) { // Try to create image thumbnails for PDFs. $fallback_sizes = array( 'thumbnail', 'medium', 'large', ); /** * Filters the image sizes generated for non-image mime types. * * @since 4.7.0 * * @param string[] $fallback_sizes An array of image size names. * @param array $metadata Current attachment metadata. */ $fallback_sizes = apply_filters( 'fallback_intermediate_image_sizes', $fallback_sizes, $metadata ); $registered_sizes = wp_get_registered_image_subsizes(); $merged_sizes = array_intersect_key( $registered_sizes, array_flip( $fallback_sizes ) ); // Force thumbnails to be soft crops. if ( isset( $merged_sizes['thumbnail'] ) && is_array( $merged_sizes['thumbnail'] ) ) { $merged_sizes['thumbnail']['crop'] = false; } // Only load PDFs in an image editor if we're processing sizes. if ( ! empty( $merged_sizes ) ) { $editor = wp_get_image_editor( $file ); if ( ! is_wp_error( $editor ) ) { // No support for this type of file. /* * PDFs may have the same file filename as JPEGs. * Ensure the PDF preview image does not overwrite any JPEG images that already exist. */ $dirname = dirname( $file ) . '/'; $ext = '.' . pathinfo( $file, PATHINFO_EXTENSION ); $preview_file = $dirname . wp_unique_filename( $dirname, wp_basename( $file, $ext ) . '-pdf.jpg' ); $uploaded = $editor->save( $preview_file, 'image/jpeg' ); unset( $editor ); // Resize based on the full size image, rather than the source. if ( ! is_wp_error( $uploaded ) ) { $image_file = $uploaded['path']; unset( $uploaded['path'] ); $metadata['sizes'] = array( 'full' => $uploaded, ); // Save the meta data before any image post-processing errors could happen. wp_update_attachment_metadata( $attachment_id, $metadata ); // Create sub-sizes saving the image meta after each. $metadata = _wp_make_subsizes( $merged_sizes, $image_file, $metadata, $attachment_id ); } } } } // Remove the blob of binary data from the array. unset( $metadata['image']['data'] ); // Capture file size for cases where it has not been captured yet, such as PDFs. if ( ! isset( $metadata['filesize'] ) && file_exists( $file ) ) { $metadata['filesize'] = wp_filesize( $file ); } /** * Filters the generated attachment meta data. * * @since 2.1.0 * @since 5.3.0 The `$context` parameter was added. * * @param array $metadata An array of attachment meta data. * @param int $attachment_id Current attachment ID. * @param string $context Additional context. Can be 'create' when metadata was initially created for new attachment * or 'update' when the metadata was updated. */ return apply_filters( 'wp_generate_attachment_metadata', $metadata, $attachment_id, 'create' ); } /** * Converts a fraction string to a decimal. * * @since 2.5.0 * * @param string $str Fraction string. * @return int|float Returns calculated fraction or integer 0 on invalid input. */ function wp_exif_frac2dec( $str ) { if ( ! is_scalar( $str ) || is_bool( $str ) ) { return 0; } if ( ! is_string( $str ) ) { return $str; // This can only be an integer or float, so this is fine. } // Fractions passed as a string must contain a single `/`. if ( substr_count( $str, '/' ) !== 1 ) { if ( is_numeric( $str ) ) { return (float) $str; } return 0; } list( $numerator, $denominator ) = explode( '/', $str ); // Both the numerator and the denominator must be numbers. if ( ! is_numeric( $numerator ) || ! is_numeric( $denominator ) ) { return 0; } // The denominator must not be zero. if ( 0 == $denominator ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual -- Deliberate loose comparison. return 0; } return $numerator / $denominator; } /** * Converts the exif date format to a unix timestamp. * * @since 2.5.0 * * @param string $str A date string expected to be in Exif format (Y:m:d H:i:s). * @return int|false The unix timestamp, or false on failure. */ function wp_exif_date2ts( $str ) { list( $date, $time ) = explode( ' ', trim( $str ) ); list( $y, $m, $d ) = explode( ':', $date ); return strtotime( "{$y}-{$m}-{$d} {$time}" ); } /** * Gets extended image metadata, exif or iptc as available. * * Retrieves the EXIF metadata aperture, credit, camera, caption, copyright, iso * created_timestamp, focal_length, shutter_speed, and title. * * The IPTC metadata that is retrieved is APP13, credit, byline, created date * and time, caption, copyright, and title. Also includes FNumber, Model, * DateTimeDigitized, FocalLength, ISOSpeedRatings, and ExposureTime. * * @todo Try other exif libraries if available. * @since 2.5.0 * * @param string $file * @return array|false Image metadata array on success, false on failure. */ function wp_read_image_metadata( $file ) { if ( ! file_exists( $file ) ) { return false; } list( , , $image_type ) = wp_getimagesize( $file ); /* * EXIF contains a bunch of data we'll probably never need formatted in ways * that are difficult to use. We'll normalize it and just extract the fields * that are likely to be useful. Fractions and numbers are converted to * floats, dates to unix timestamps, and everything else to strings. */ $meta = array( 'aperture' => 0, 'credit' => '', 'camera' => '', 'caption' => '', 'created_timestamp' => 0, 'copyright' => '', 'focal_length' => 0, 'iso' => 0, 'shutter_speed' => 0, 'title' => '', 'orientation' => 0, 'keywords' => array(), ); $iptc = array(); $info = array(); /* * Read IPTC first, since it might contain data not available in exif such * as caption, description etc. */ if ( is_callable( 'iptcparse' ) ) { wp_getimagesize( $file, $info ); if ( ! empty( $info['APP13'] ) ) { // Don't silence errors when in debug mode, unless running unit tests. if ( defined( 'WP_DEBUG' ) && WP_DEBUG && ! defined( 'WP_RUN_CORE_TESTS' ) ) { $iptc = iptcparse( $info['APP13'] ); } else { // Silencing notice and warning is intentional. See https://core.trac.wordpress.org/ticket/42480 $iptc = @iptcparse( $info['APP13'] ); } if ( ! is_array( $iptc ) ) { $iptc = array(); } // Headline, "A brief synopsis of the caption". if ( ! empty( $iptc['2#105'][0] ) ) { $meta['title'] = trim( $iptc['2#105'][0] ); /* * Title, "Many use the Title field to store the filename of the image, * though the field may be used in many ways". */ } elseif ( ! empty( $iptc['2#005'][0] ) ) { $meta['title'] = trim( $iptc['2#005'][0] ); } if ( ! empty( $iptc['2#120'][0] ) ) { // Description / legacy caption. $caption = trim( $iptc['2#120'][0] ); mbstring_binary_safe_encoding(); $caption_length = strlen( $caption ); reset_mbstring_encoding(); if ( empty( $meta['title'] ) && $caption_length < 80 ) { // Assume the title is stored in 2:120 if it's short. $meta['title'] = $caption; } $meta['caption'] = $caption; } if ( ! empty( $iptc['2#110'][0] ) ) { // Credit. $meta['credit'] = trim( $iptc['2#110'][0] ); } elseif ( ! empty( $iptc['2#080'][0] ) ) { // Creator / legacy byline. $meta['credit'] = trim( $iptc['2#080'][0] ); } if ( ! empty( $iptc['2#055'][0] ) && ! empty( $iptc['2#060'][0] ) ) { // Created date and time. $meta['created_timestamp'] = strtotime( $iptc['2#055'][0] . ' ' . $iptc['2#060'][0] ); } if ( ! empty( $iptc['2#116'][0] ) ) { // Copyright. $meta['copyright'] = trim( $iptc['2#116'][0] ); } if ( ! empty( $iptc['2#025'][0] ) ) { // Keywords array. $meta['keywords'] = array_values( $iptc['2#025'] ); } } } $exif = array(); /** * Filters the image types to check for exif data. * * @since 2.5.0 * * @param int[] $image_types Array of image types to check for exif data. Each value * is usually one of the `IMAGETYPE_*` constants. */ $exif_image_types = apply_filters( 'wp_read_image_metadata_types', array( IMAGETYPE_JPEG, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM ) ); if ( is_callable( 'exif_read_data' ) && in_array( $image_type, $exif_image_types, true ) ) { // Don't silence errors when in debug mode, unless running unit tests. if ( defined( 'WP_DEBUG' ) && WP_DEBUG && ! defined( 'WP_RUN_CORE_TESTS' ) ) { $exif = exif_read_data( $file ); } else { // Silencing notice and warning is intentional. See https://core.trac.wordpress.org/ticket/42480 $exif = @exif_read_data( $file ); } if ( ! is_array( $exif ) ) { $exif = array(); } $exif_description = ''; $exif_usercomment = ''; if ( ! empty( $exif['ImageDescription'] ) ) { $exif_description = trim( $exif['ImageDescription'] ); } if ( ! empty( $exif['COMPUTED']['UserComment'] ) ) { $exif_usercomment = trim( $exif['COMPUTED']['UserComment'] ); } if ( $exif_description ) { mbstring_binary_safe_encoding(); $description_length = strlen( $exif_description ); reset_mbstring_encoding(); if ( empty( $meta['title'] ) && $description_length < 80 ) { // Assume the title is stored in ImageDescription. $meta['title'] = $exif_description; } // If both user comments and description are present. if ( empty( $meta['caption'] ) && $exif_description && $exif_usercomment ) { if ( ! empty( $meta['title'] ) && $exif_description === $meta['title'] ) { $caption = $exif_usercomment; } else { if ( $exif_description === $exif_usercomment ) { $caption = $exif_description; } else { $caption = trim( $exif_description . ' ' . $exif_usercomment ); } } $meta['caption'] = $caption; } if ( empty( $meta['caption'] ) && $exif_usercomment ) { $meta['caption'] = $exif_usercomment; } if ( empty( $meta['caption'] ) ) { $meta['caption'] = $exif_description; } } elseif ( empty( $meta['caption'] ) && $exif_usercomment ) { $meta['caption'] = $exif_usercomment; $description_length = strlen( $exif_usercomment ); if ( empty( $meta['title'] ) && $description_length < 80 ) { $meta['title'] = trim( $exif_usercomment ); } } elseif ( empty( $meta['caption'] ) && ! empty( $exif['Comments'] ) ) { $meta['caption'] = trim( $exif['Comments'] ); } if ( empty( $meta['credit'] ) ) { if ( ! empty( $exif['Artist'] ) ) { $meta['credit'] = trim( $exif['Artist'] ); } elseif ( ! empty( $exif['Author'] ) ) { $meta['credit'] = trim( $exif['Author'] ); } } if ( empty( $meta['copyright'] ) && ! empty( $exif['Copyright'] ) ) { $meta['copyright'] = trim( $exif['Copyright'] ); } if ( ! empty( $exif['FNumber'] ) && is_scalar( $exif['FNumber'] ) ) { $meta['aperture'] = round( wp_exif_frac2dec( $exif['FNumber'] ), 2 ); } if ( ! empty( $exif['Model'] ) ) { $meta['camera'] = trim( $exif['Model'] ); } if ( empty( $meta['created_timestamp'] ) && ! empty( $exif['DateTimeDigitized'] ) ) { $meta['created_timestamp'] = wp_exif_date2ts( $exif['DateTimeDigitized'] ); } if ( ! empty( $exif['FocalLength'] ) ) { $meta['focal_length'] = (string) $exif['FocalLength']; if ( is_scalar( $exif['FocalLength'] ) ) { $meta['focal_length'] = (string) wp_exif_frac2dec( $exif['FocalLength'] ); } } if ( ! empty( $exif['ISOSpeedRatings'] ) ) { $meta['iso'] = is_array( $exif['ISOSpeedRatings'] ) ? reset( $exif['ISOSpeedRatings'] ) : $exif['ISOSpeedRatings']; $meta['iso'] = trim( $meta['iso'] ); } if ( ! empty( $exif['ExposureTime'] ) ) { $meta['shutter_speed'] = (string) $exif['ExposureTime']; if ( is_scalar( $exif['ExposureTime'] ) ) { $meta['shutter_speed'] = (string) wp_exif_frac2dec( $exif['ExposureTime'] ); } } if ( ! empty( $exif['Orientation'] ) ) { $meta['orientation'] = $exif['Orientation']; } } foreach ( array( 'title', 'caption', 'credit', 'copyright', 'camera', 'iso' ) as $key ) { if ( $meta[ $key ] && ! seems_utf8( $meta[ $key ] ) ) { $meta[ $key ] = utf8_encode( $meta[ $key ] ); } } foreach ( $meta['keywords'] as $key => $keyword ) { if ( ! seems_utf8( $keyword ) ) { $meta['keywords'][ $key ] = utf8_encode( $keyword ); } } $meta = wp_kses_post_deep( $meta ); /** * Filters the array of meta data read from an image's exif data. * * @since 2.5.0 * @since 4.4.0 The `$iptc` parameter was added. * @since 5.0.0 The `$exif` parameter was added. * * @param array $meta Image meta data. * @param string $file Path to image file. * @param int $image_type Type of image, one of the `IMAGETYPE_XXX` constants. * @param array $iptc IPTC data. * @param array $exif EXIF data. */ return apply_filters( 'wp_read_image_metadata', $meta, $file, $image_type, $iptc, $exif ); } /** * Validates that file is an image. * * @since 2.5.0 * * @param string $path File path to test if valid image. * @return bool True if valid image, false if not valid image. */ function file_is_valid_image( $path ) { $size = wp_getimagesize( $path ); return ! empty( $size ); } /** * Validates that file is suitable for displaying within a web page. * * @since 2.5.0 * * @param string $path File path to test. * @return bool True if suitable, false if not suitable. */ function file_is_displayable_image( $path ) { $displayable_image_types = array( IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP, IMAGETYPE_ICO, IMAGETYPE_WEBP, IMAGETYPE_AVIF ); $info = wp_getimagesize( $path ); if ( empty( $info ) ) { $result = false; } elseif ( ! in_array( $info[2], $displayable_image_types, true ) ) { $result = false; } else { $result = true; } /** * Filters whether the current image is displayable in the browser. * * @since 2.5.0 * * @param bool $result Whether the image can be displayed. Default true. * @param string $path Path to the image. */ return apply_filters( 'file_is_displayable_image', $result, $path ); } /** * Loads an image resource for editing. * * @since 2.9.0 * * @param int $attachment_id Attachment ID. * @param string $mime_type Image mime type. * @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 'full'. * @return resource|GdImage|false The resulting image resource or GdImage instance on success, * false on failure. */ function load_image_to_edit( $attachment_id, $mime_type, $size = 'full' ) { $filepath = _load_image_to_edit_path( $attachment_id, $size ); if ( empty( $filepath ) ) { return false; } switch ( $mime_type ) { case 'image/jpeg': $image = imagecreatefromjpeg( $filepath ); break; case 'image/png': $image = imagecreatefrompng( $filepath ); break; case 'image/gif': $image = imagecreatefromgif( $filepath ); break; case 'image/webp': $image = false; if ( function_exists( 'imagecreatefromwebp' ) ) { $image = imagecreatefromwebp( $filepath ); } break; default: $image = false; break; } if ( is_gd_image( $image ) ) { /** * Filters the current image being loaded for editing. * * @since 2.9.0 * * @param resource|GdImage $image Current image. * @param int $attachment_id Attachment ID. * @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). */ $image = apply_filters( 'load_image_to_edit', $image, $attachment_id, $size ); if ( function_exists( 'imagealphablending' ) && function_exists( 'imagesavealpha' ) ) { imagealphablending( $image, false ); imagesavealpha( $image, true ); } } return $image; } /** * Retrieves the path or URL of an attachment's attached file. * * If the attached file is not present on the local filesystem (usually due to replication plugins), * then the URL of the file is returned if `allow_url_fopen` is supported. * * @since 3.4.0 * @access private * * @param int $attachment_id Attachment ID. * @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 'full'. * @return string|false File path or URL on success, false on failure. */ function _load_image_to_edit_path( $attachment_id, $size = 'full' ) { $filepath = get_attached_file( $attachment_id ); if ( $filepath && file_exists( $filepath ) ) { if ( 'full' !== $size ) { $data = image_get_intermediate_size( $attachment_id, $size ); if ( $data ) { $filepath = path_join( dirname( $filepath ), $data['file'] ); /** * Filters the path to an attachment's file when editing the image. * * The filter is evaluated for all image sizes except 'full'. * * @since 3.1.0 * * @param string $path Path to the current image. * @param int $attachment_id Attachment ID. * @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). */ $filepath = apply_filters( 'load_image_to_edit_filesystempath', $filepath, $attachment_id, $size ); } } } elseif ( function_exists( 'fopen' ) && ini_get( 'allow_url_fopen' ) ) { /** * Filters the path to an attachment's URL when editing the image. * * The filter is only evaluated if the file isn't stored locally and `allow_url_fopen` is enabled on the server. * * @since 3.1.0 * * @param string|false $image_url Current image URL. * @param int $attachment_id Attachment ID. * @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). */ $filepath = apply_filters( 'load_image_to_edit_attachmenturl', wp_get_attachment_url( $attachment_id ), $attachment_id, $size ); } /** * Filters the returned path or URL of the current image. * * @since 2.9.0 * * @param string|false $filepath File path or URL to current image, or false. * @param int $attachment_id Attachment ID. * @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). */ return apply_filters( 'load_image_to_edit_path', $filepath, $attachment_id, $size ); } /** * Copies an existing image file. * * @since 3.4.0 * @access private * * @param int $attachment_id Attachment ID. * @return string|false New file path on success, false on failure. */ function _copy_image_file( $attachment_id ) { $dst_file = get_attached_file( $attachment_id ); $src_file = $dst_file; if ( ! file_exists( $src_file ) ) { $src_file = _load_image_to_edit_path( $attachment_id ); } if ( $src_file ) { $dst_file = str_replace( wp_basename( $dst_file ), 'copy-' . wp_basename( $dst_file ), $dst_file ); $dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), wp_basename( $dst_file ) ); /* * The directory containing the original file may no longer * exist when using a replication plugin. */ wp_mkdir_p( dirname( $dst_file ) ); if ( ! copy( $src_file, $dst_file ) ) { $dst_file = false; } } else { $dst_file = false; } return $dst_file; } class-wp-posts-list-table.php000064400000174466146715570560012254 0ustar00 '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[] $post_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[] $post_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[] $post_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; } /** * @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 ) { ?>
comment_pending_count[ $post->ID ] ) ? $this->comment_pending_count[ $post->ID ] : 0; $this->comments_bubble( $post->ID, $pending_comments ); ?>
$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, ); ?>
post_type}"; $quick_edit_classes = "quick-edit-row quick-edit-row-$hclass inline-edit-{$screen->post_type}"; $bulk = 0; while ( $bulk < 2 ) : $classes = $inline_edit_classes . ' '; $classes .= $bulk ? $bulk_edit_classes : $quick_edit_classes; ?>
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 = ""; } elseif ( isset( $msg->msg ) ) { $note = ""; } } /** * 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.' ) . '

'; ?>

' . $meta['width'] . ' × ' . $meta['height'] . '' ); ?>

, 'restore')" class="button button-primary" value="" />



stream( $mime_type ) ) ) { return false; } return true; } else { /* translators: 1: $image, 2: WP_Image_Editor */ _deprecated_argument( __FUNCTION__, '3.5.0', sprintf( __( '%1$s needs to be a %2$s object.' ), '$image', 'WP_Image_Editor' ) ); /** * Filters the GD image resource to be streamed to the browser. * * @since 2.9.0 * @deprecated 3.5.0 Use {@see 'image_editor_save_pre'} instead. * * @param resource|GdImage $image Image resource to be streamed. * @param int $attachment_id The attachment post ID. */ $image = apply_filters_deprecated( 'image_save_pre', array( $image, $attachment_id ), '3.5.0', 'image_editor_save_pre' ); switch ( $mime_type ) { case 'image/jpeg': header( 'Content-Type: image/jpeg' ); return imagejpeg( $image, null, 90 ); case 'image/png': header( 'Content-Type: image/png' ); return imagepng( $image ); case 'image/gif': header( 'Content-Type: image/gif' ); return imagegif( $image ); case 'image/webp': if ( function_exists( 'imagewebp' ) ) { header( 'Content-Type: image/webp' ); return imagewebp( $image, null, 90 ); } return false; case 'image/avif': if ( function_exists( 'imageavif' ) ) { header( 'Content-Type: image/avif' ); return imageavif( $image, null, 90 ); } return false; default: return false; } } } /** * Saves image to file. * * @since 2.9.0 * @since 3.5.0 The `$image` parameter expects a `WP_Image_Editor` instance. * @since 6.0.0 The `$filesize` value was added to the returned array. * * @param string $filename Name of the file to be saved. * @param WP_Image_Editor $image The image editor instance. * @param string $mime_type The mime type of the image. * @param int $post_id Attachment post ID. * @return array|WP_Error|bool { * Array on success or WP_Error if the file failed to save. * When called with a deprecated value for the `$image` parameter, * i.e. a non-`WP_Image_Editor` image resource or `GdImage` instance, * the function will return true on success, false on failure. * * @type string $path Path to the image file. * @type string $file Name of the image file. * @type int $width Image width. * @type int $height Image height. * @type string $mime-type The mime type of the image. * @type int $filesize File size of the image. * } */ function wp_save_image_file( $filename, $image, $mime_type, $post_id ) { if ( $image instanceof WP_Image_Editor ) { /** This filter is documented in wp-admin/includes/image-edit.php */ $image = apply_filters( 'image_editor_save_pre', $image, $post_id ); /** * Filters whether to skip saving the image file. * * Returning a non-null value will short-circuit the save method, * returning that value instead. * * @since 3.5.0 * * @param bool|null $override Value to return instead of saving. Default null. * @param string $filename Name of the file to be saved. * @param WP_Image_Editor $image The image editor instance. * @param string $mime_type The mime type of the image. * @param int $post_id Attachment post ID. */ $saved = apply_filters( 'wp_save_image_editor_file', null, $filename, $image, $mime_type, $post_id ); if ( null !== $saved ) { return $saved; } return $image->save( $filename, $mime_type ); } else { /* translators: 1: $image, 2: WP_Image_Editor */ _deprecated_argument( __FUNCTION__, '3.5.0', sprintf( __( '%1$s needs to be a %2$s object.' ), '$image', 'WP_Image_Editor' ) ); /** This filter is documented in wp-admin/includes/image-edit.php */ $image = apply_filters_deprecated( 'image_save_pre', array( $image, $post_id ), '3.5.0', 'image_editor_save_pre' ); /** * Filters whether to skip saving the image file. * * Returning a non-null value will short-circuit the save method, * returning that value instead. * * @since 2.9.0 * @deprecated 3.5.0 Use {@see 'wp_save_image_editor_file'} instead. * * @param bool|null $override Value to return instead of saving. Default null. * @param string $filename Name of the file to be saved. * @param resource|GdImage $image Image resource or GdImage instance. * @param string $mime_type The mime type of the image. * @param int $post_id Attachment post ID. */ $saved = apply_filters_deprecated( 'wp_save_image_file', array( null, $filename, $image, $mime_type, $post_id ), '3.5.0', 'wp_save_image_editor_file' ); if ( null !== $saved ) { return $saved; } switch ( $mime_type ) { case 'image/jpeg': /** This filter is documented in wp-includes/class-wp-image-editor.php */ return imagejpeg( $image, $filename, apply_filters( 'jpeg_quality', 90, 'edit_image' ) ); case 'image/png': return imagepng( $image, $filename ); case 'image/gif': return imagegif( $image, $filename ); case 'image/webp': if ( function_exists( 'imagewebp' ) ) { return imagewebp( $image, $filename ); } return false; case 'image/avif': if ( function_exists( 'imageavif' ) ) { return imageavif( $image, $filename ); } return false; default: return false; } } } /** * Image preview ratio. Internal use only. * * @since 2.9.0 * * @ignore * @param int $w Image width in pixels. * @param int $h Image height in pixels. * @return float|int Image preview ratio. */ function _image_get_preview_ratio( $w, $h ) { $max = max( $w, $h ); return $max > 600 ? ( 600 / $max ) : 1; } /** * Returns an image resource. Internal use only. * * @since 2.9.0 * @deprecated 3.5.0 Use WP_Image_Editor::rotate() * @see WP_Image_Editor::rotate() * * @ignore * @param resource|GdImage $img Image resource. * @param float|int $angle Image rotation angle, in degrees. * @return resource|GdImage|false GD image resource or GdImage instance, false otherwise. */ function _rotate_image_resource( $img, $angle ) { _deprecated_function( __FUNCTION__, '3.5.0', 'WP_Image_Editor::rotate()' ); if ( function_exists( 'imagerotate' ) ) { $rotated = imagerotate( $img, $angle, 0 ); if ( is_gd_image( $rotated ) ) { imagedestroy( $img ); $img = $rotated; } } return $img; } /** * Flips an image resource. Internal use only. * * @since 2.9.0 * @deprecated 3.5.0 Use WP_Image_Editor::flip() * @see WP_Image_Editor::flip() * * @ignore * @param resource|GdImage $img Image resource or GdImage instance. * @param bool $horz Whether to flip horizontally. * @param bool $vert Whether to flip vertically. * @return resource|GdImage (maybe) flipped image resource or GdImage instance. */ function _flip_image_resource( $img, $horz, $vert ) { _deprecated_function( __FUNCTION__, '3.5.0', 'WP_Image_Editor::flip()' ); $w = imagesx( $img ); $h = imagesy( $img ); $dst = wp_imagecreatetruecolor( $w, $h ); if ( is_gd_image( $dst ) ) { $sx = $vert ? ( $w - 1 ) : 0; $sy = $horz ? ( $h - 1 ) : 0; $sw = $vert ? -$w : $w; $sh = $horz ? -$h : $h; if ( imagecopyresampled( $dst, $img, 0, 0, $sx, $sy, $w, $h, $sw, $sh ) ) { imagedestroy( $img ); $img = $dst; } } return $img; } /** * Crops an image resource. Internal use only. * * @since 2.9.0 * * @ignore * @param resource|GdImage $img Image resource or GdImage instance. * @param float $x Source point x-coordinate. * @param float $y Source point y-coordinate. * @param float $w Source width. * @param float $h Source height. * @return resource|GdImage (maybe) cropped image resource or GdImage instance. */ function _crop_image_resource( $img, $x, $y, $w, $h ) { $dst = wp_imagecreatetruecolor( $w, $h ); if ( is_gd_image( $dst ) ) { if ( imagecopy( $dst, $img, 0, 0, $x, $y, $w, $h ) ) { imagedestroy( $img ); $img = $dst; } } return $img; } /** * Performs group of changes on Editor specified. * * @since 2.9.0 * * @param WP_Image_Editor $image WP_Image_Editor instance. * @param array $changes Array of change operations. * @return WP_Image_Editor WP_Image_Editor instance with changes applied. */ function image_edit_apply_changes( $image, $changes ) { if ( is_gd_image( $image ) ) { /* translators: 1: $image, 2: WP_Image_Editor */ _deprecated_argument( __FUNCTION__, '3.5.0', sprintf( __( '%1$s needs to be a %2$s object.' ), '$image', 'WP_Image_Editor' ) ); } if ( ! is_array( $changes ) ) { return $image; } // Expand change operations. foreach ( $changes as $key => $obj ) { if ( isset( $obj->r ) ) { $obj->type = 'rotate'; $obj->angle = $obj->r; unset( $obj->r ); } elseif ( isset( $obj->f ) ) { $obj->type = 'flip'; $obj->axis = $obj->f; unset( $obj->f ); } elseif ( isset( $obj->c ) ) { $obj->type = 'crop'; $obj->sel = $obj->c; unset( $obj->c ); } $changes[ $key ] = $obj; } // Combine operations. if ( count( $changes ) > 1 ) { $filtered = array( $changes[0] ); for ( $i = 0, $j = 1, $c = count( $changes ); $j < $c; $j++ ) { $combined = false; if ( $filtered[ $i ]->type === $changes[ $j ]->type ) { switch ( $filtered[ $i ]->type ) { case 'rotate': $filtered[ $i ]->angle += $changes[ $j ]->angle; $combined = true; break; case 'flip': $filtered[ $i ]->axis ^= $changes[ $j ]->axis; $combined = true; break; } } if ( ! $combined ) { $filtered[ ++$i ] = $changes[ $j ]; } } $changes = $filtered; unset( $filtered ); } // Image resource before applying the changes. if ( $image instanceof WP_Image_Editor ) { /** * Filters the WP_Image_Editor instance before applying changes to the image. * * @since 3.5.0 * * @param WP_Image_Editor $image WP_Image_Editor instance. * @param array $changes Array of change operations. */ $image = apply_filters( 'wp_image_editor_before_change', $image, $changes ); } elseif ( is_gd_image( $image ) ) { /** * Filters the GD image resource before applying changes to the image. * * @since 2.9.0 * @deprecated 3.5.0 Use {@see 'wp_image_editor_before_change'} instead. * * @param resource|GdImage $image GD image resource or GdImage instance. * @param array $changes Array of change operations. */ $image = apply_filters_deprecated( 'image_edit_before_change', array( $image, $changes ), '3.5.0', 'wp_image_editor_before_change' ); } foreach ( $changes as $operation ) { switch ( $operation->type ) { case 'rotate': if ( 0 !== $operation->angle ) { if ( $image instanceof WP_Image_Editor ) { $image->rotate( $operation->angle ); } else { $image = _rotate_image_resource( $image, $operation->angle ); } } break; case 'flip': if ( 0 !== $operation->axis ) { if ( $image instanceof WP_Image_Editor ) { $image->flip( ( $operation->axis & 1 ) !== 0, ( $operation->axis & 2 ) !== 0 ); } else { $image = _flip_image_resource( $image, ( $operation->axis & 1 ) !== 0, ( $operation->axis & 2 ) !== 0 ); } } break; case 'crop': $sel = $operation->sel; if ( $image instanceof WP_Image_Editor ) { $size = $image->get_size(); $w = $size['width']; $h = $size['height']; $scale = 1 / _image_get_preview_ratio( $w, $h ); // Discard preview scaling. $image->crop( (int) ( $sel->x * $scale ), (int) ( $sel->y * $scale ), (int) ( $sel->w * $scale ), (int) ( $sel->h * $scale ) ); } else { $scale = 1 / _image_get_preview_ratio( imagesx( $image ), imagesy( $image ) ); // Discard preview scaling. $image = _crop_image_resource( $image, $sel->x * $scale, $sel->y * $scale, $sel->w * $scale, $sel->h * $scale ); } break; } } return $image; } /** * Streams image in post to browser, along with enqueued changes * in `$_REQUEST['history']`. * * @since 2.9.0 * * @param int $post_id Attachment post ID. * @return bool True on success, false on failure. */ function stream_preview_image( $post_id ) { $post = get_post( $post_id ); wp_raise_memory_limit( 'admin' ); $img = wp_get_image_editor( _load_image_to_edit_path( $post_id ) ); if ( is_wp_error( $img ) ) { return false; } $changes = ! empty( $_REQUEST['history'] ) ? json_decode( wp_unslash( $_REQUEST['history'] ) ) : null; if ( $changes ) { $img = image_edit_apply_changes( $img, $changes ); } // Scale the image. $size = $img->get_size(); $w = $size['width']; $h = $size['height']; $ratio = _image_get_preview_ratio( $w, $h ); $w2 = max( 1, $w * $ratio ); $h2 = max( 1, $h * $ratio ); if ( is_wp_error( $img->resize( $w2, $h2 ) ) ) { return false; } return wp_stream_image( $img, $post->post_mime_type, $post_id ); } /** * Restores the metadata for a given attachment. * * @since 2.9.0 * * @param int $post_id Attachment post ID. * @return stdClass Image restoration message object. */ function wp_restore_image( $post_id ) { $meta = wp_get_attachment_metadata( $post_id ); $file = get_attached_file( $post_id ); $backup_sizes = get_post_meta( $post_id, '_wp_attachment_backup_sizes', true ); $old_backup_sizes = $backup_sizes; $restored = false; $msg = new stdClass(); if ( ! is_array( $backup_sizes ) ) { $msg->error = __( 'Cannot load image metadata.' ); return $msg; } $parts = pathinfo( $file ); $suffix = time() . rand( 100, 999 ); $default_sizes = get_intermediate_image_sizes(); if ( isset( $backup_sizes['full-orig'] ) && is_array( $backup_sizes['full-orig'] ) ) { $data = $backup_sizes['full-orig']; if ( $parts['basename'] !== $data['file'] ) { if ( defined( 'IMAGE_EDIT_OVERWRITE' ) && IMAGE_EDIT_OVERWRITE ) { // Delete only if it's an edited image. if ( preg_match( '/-e[0-9]{13}\./', $parts['basename'] ) ) { wp_delete_file( $file ); } } elseif ( isset( $meta['width'], $meta['height'] ) ) { $backup_sizes[ "full-$suffix" ] = array( 'width' => $meta['width'], 'height' => $meta['height'], 'file' => $parts['basename'], ); } } $restored_file = path_join( $parts['dirname'], $data['file'] ); $restored = update_attached_file( $post_id, $restored_file ); $meta['file'] = _wp_relative_upload_path( $restored_file ); $meta['width'] = $data['width']; $meta['height'] = $data['height']; } foreach ( $default_sizes as $default_size ) { if ( isset( $backup_sizes[ "$default_size-orig" ] ) ) { $data = $backup_sizes[ "$default_size-orig" ]; if ( isset( $meta['sizes'][ $default_size ] ) && $meta['sizes'][ $default_size ]['file'] !== $data['file'] ) { if ( defined( 'IMAGE_EDIT_OVERWRITE' ) && IMAGE_EDIT_OVERWRITE ) { // Delete only if it's an edited image. if ( preg_match( '/-e[0-9]{13}-/', $meta['sizes'][ $default_size ]['file'] ) ) { $delete_file = path_join( $parts['dirname'], $meta['sizes'][ $default_size ]['file'] ); wp_delete_file( $delete_file ); } } else { $backup_sizes[ "$default_size-{$suffix}" ] = $meta['sizes'][ $default_size ]; } } $meta['sizes'][ $default_size ] = $data; } else { unset( $meta['sizes'][ $default_size ] ); } } if ( ! wp_update_attachment_metadata( $post_id, $meta ) || ( $old_backup_sizes !== $backup_sizes && ! update_post_meta( $post_id, '_wp_attachment_backup_sizes', $backup_sizes ) ) ) { $msg->error = __( 'Cannot save image metadata.' ); return $msg; } if ( ! $restored ) { $msg->error = __( 'Image metadata is inconsistent.' ); } else { $msg->msg = __( 'Image restored successfully.' ); if ( defined( 'IMAGE_EDIT_OVERWRITE' ) && IMAGE_EDIT_OVERWRITE ) { delete_post_meta( $post_id, '_wp_attachment_backup_sizes' ); } } return $msg; } /** * Saves image to post, along with enqueued changes * in `$_REQUEST['history']`. * * @since 2.9.0 * * @param int $post_id Attachment post ID. * @return stdClass */ function wp_save_image( $post_id ) { $_wp_additional_image_sizes = wp_get_additional_image_sizes(); $return = new stdClass(); $success = false; $delete = false; $scaled = false; $nocrop = false; $post = get_post( $post_id ); $img = wp_get_image_editor( _load_image_to_edit_path( $post_id, 'full' ) ); if ( is_wp_error( $img ) ) { $return->error = esc_js( __( 'Unable to create new image.' ) ); return $return; } $full_width = ! empty( $_REQUEST['fwidth'] ) ? (int) $_REQUEST['fwidth'] : 0; $full_height = ! empty( $_REQUEST['fheight'] ) ? (int) $_REQUEST['fheight'] : 0; $target = ! empty( $_REQUEST['target'] ) ? preg_replace( '/[^a-z0-9_-]+/i', '', $_REQUEST['target'] ) : ''; $scale = ! empty( $_REQUEST['do'] ) && 'scale' === $_REQUEST['do']; /** This filter is documented in wp-admin/includes/image-edit.php */ $edit_thumbnails_separately = (bool) apply_filters( 'image_edit_thumbnails_separately', false ); if ( $scale ) { $size = $img->get_size(); $original_width = $size['width']; $original_height = $size['height']; if ( $full_width > $original_width || $full_height > $original_height ) { $return->error = esc_js( __( 'Images cannot be scaled to a size larger than the original.' ) ); return $return; } if ( $full_width > 0 && $full_height > 0 ) { // Check if it has roughly the same w / h ratio. $diff = round( $original_width / $original_height, 2 ) - round( $full_width / $full_height, 2 ); if ( -0.1 < $diff && $diff < 0.1 ) { // Scale the full size image. if ( $img->resize( $full_width, $full_height ) ) { $scaled = true; } } if ( ! $scaled ) { $return->error = esc_js( __( 'Error while saving the scaled image. Please reload the page and try again.' ) ); return $return; } } } elseif ( ! empty( $_REQUEST['history'] ) ) { $changes = json_decode( wp_unslash( $_REQUEST['history'] ) ); if ( $changes ) { $img = image_edit_apply_changes( $img, $changes ); } } else { $return->error = esc_js( __( 'Nothing to save, the image has not changed.' ) ); return $return; } $meta = wp_get_attachment_metadata( $post_id ); $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true ); if ( ! is_array( $meta ) ) { $return->error = esc_js( __( 'Image data does not exist. Please re-upload the image.' ) ); return $return; } if ( ! is_array( $backup_sizes ) ) { $backup_sizes = array(); } // Generate new filename. $path = get_attached_file( $post_id ); $basename = pathinfo( $path, PATHINFO_BASENAME ); $dirname = pathinfo( $path, PATHINFO_DIRNAME ); $ext = pathinfo( $path, PATHINFO_EXTENSION ); $filename = pathinfo( $path, PATHINFO_FILENAME ); $suffix = time() . rand( 100, 999 ); if ( defined( 'IMAGE_EDIT_OVERWRITE' ) && IMAGE_EDIT_OVERWRITE && isset( $backup_sizes['full-orig'] ) && $backup_sizes['full-orig']['file'] !== $basename ) { if ( $edit_thumbnails_separately && 'thumbnail' === $target ) { $new_path = "{$dirname}/{$filename}-temp.{$ext}"; } else { $new_path = $path; } } else { while ( true ) { $filename = preg_replace( '/-e([0-9]+)$/', '', $filename ); $filename .= "-e{$suffix}"; $new_filename = "{$filename}.{$ext}"; $new_path = "{$dirname}/$new_filename"; if ( file_exists( $new_path ) ) { ++$suffix; } else { break; } } } // Save the full-size file, also needed to create sub-sizes. if ( ! wp_save_image_file( $new_path, $img, $post->post_mime_type, $post_id ) ) { $return->error = esc_js( __( 'Unable to save the image.' ) ); return $return; } if ( 'nothumb' === $target || 'all' === $target || 'full' === $target || $scaled ) { $tag = false; if ( isset( $backup_sizes['full-orig'] ) ) { if ( ( ! defined( 'IMAGE_EDIT_OVERWRITE' ) || ! IMAGE_EDIT_OVERWRITE ) && $backup_sizes['full-orig']['file'] !== $basename ) { $tag = "full-$suffix"; } } else { $tag = 'full-orig'; } if ( $tag ) { $backup_sizes[ $tag ] = array( 'width' => $meta['width'], 'height' => $meta['height'], 'file' => $basename, ); } $success = ( $path === $new_path ) || update_attached_file( $post_id, $new_path ); $meta['file'] = _wp_relative_upload_path( $new_path ); $size = $img->get_size(); $meta['width'] = $size['width']; $meta['height'] = $size['height']; if ( $success && ( 'nothumb' === $target || 'all' === $target ) ) { $sizes = get_intermediate_image_sizes(); if ( $edit_thumbnails_separately && 'nothumb' === $target ) { $sizes = array_diff( $sizes, array( 'thumbnail' ) ); } } $return->fw = $meta['width']; $return->fh = $meta['height']; } elseif ( $edit_thumbnails_separately && 'thumbnail' === $target ) { $sizes = array( 'thumbnail' ); $success = true; $delete = true; $nocrop = true; } /* * We need to remove any existing resized image files because * a new crop or rotate could generate different sizes (and hence, filenames), * keeping the new resized images from overwriting the existing image files. * https://core.trac.wordpress.org/ticket/32171 */ if ( defined( 'IMAGE_EDIT_OVERWRITE' ) && IMAGE_EDIT_OVERWRITE && ! empty( $meta['sizes'] ) ) { foreach ( $meta['sizes'] as $size ) { if ( ! empty( $size['file'] ) && preg_match( '/-e[0-9]{13}-/', $size['file'] ) ) { $delete_file = path_join( $dirname, $size['file'] ); wp_delete_file( $delete_file ); } } } if ( isset( $sizes ) ) { $_sizes = array(); foreach ( $sizes as $size ) { $tag = false; if ( isset( $meta['sizes'][ $size ] ) ) { if ( isset( $backup_sizes[ "$size-orig" ] ) ) { if ( ( ! defined( 'IMAGE_EDIT_OVERWRITE' ) || ! IMAGE_EDIT_OVERWRITE ) && $backup_sizes[ "$size-orig" ]['file'] !== $meta['sizes'][ $size ]['file'] ) { $tag = "$size-$suffix"; } } else { $tag = "$size-orig"; } if ( $tag ) { $backup_sizes[ $tag ] = $meta['sizes'][ $size ]; } } if ( isset( $_wp_additional_image_sizes[ $size ] ) ) { $width = (int) $_wp_additional_image_sizes[ $size ]['width']; $height = (int) $_wp_additional_image_sizes[ $size ]['height']; $crop = ( $nocrop ) ? false : $_wp_additional_image_sizes[ $size ]['crop']; } else { $height = get_option( "{$size}_size_h" ); $width = get_option( "{$size}_size_w" ); $crop = ( $nocrop ) ? false : get_option( "{$size}_crop" ); } $_sizes[ $size ] = array( 'width' => $width, 'height' => $height, 'crop' => $crop, ); } $meta['sizes'] = array_merge( $meta['sizes'], $img->multi_resize( $_sizes ) ); } unset( $img ); if ( $success ) { wp_update_attachment_metadata( $post_id, $meta ); update_post_meta( $post_id, '_wp_attachment_backup_sizes', $backup_sizes ); if ( 'thumbnail' === $target || 'all' === $target || 'full' === $target ) { // Check if it's an image edit from attachment edit screen. if ( ! empty( $_REQUEST['context'] ) && 'edit-attachment' === $_REQUEST['context'] ) { $thumb_url = wp_get_attachment_image_src( $post_id, array( 900, 600 ), true ); $return->thumbnail = $thumb_url[0]; } else { $file_url = wp_get_attachment_url( $post_id ); if ( ! empty( $meta['sizes']['thumbnail'] ) ) { $thumb = $meta['sizes']['thumbnail']; $return->thumbnail = path_join( dirname( $file_url ), $thumb['file'] ); } else { $return->thumbnail = "$file_url?w=128&h=128"; } } } } else { $delete = true; } if ( $delete ) { wp_delete_file( $new_path ); } $return->msg = esc_js( __( 'Image saved' ) ); return $return; } class-wp-plugin-install-list-table.php000064400000060220146715570560014024 0ustar00no_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' ); ?>
_args['singular']; $data_attr = ''; if ( $singular ) { $data_attr = " data-wp-lists='list:$singular'"; } $this->display_tablenav( 'top' ); ?>
screen->render_screen_reader_content( 'heading_list' ); ?>
> display_rows_or_placeholder(); ?>
display_tablenav( 'bottom' ); } /** * @global string $tab * * @param string $which */ protected function display_tablenav( $which ) { if ( 'featured' === $GLOBALS['tab'] ) { return; } if ( 'top' === $which ) { wp_referer_field(); ?>
pagination( $which ); ?>
pagination( $which ); ?>
_args['plural'] ); } /** * @return string[] Array of column titles keyed by their column name. */ public function get_columns() { return array(); } /** * @param object $plugin_a * @param object $plugin_b * @return int */ private function order_callback( $plugin_a, $plugin_b ) { $orderby = $this->orderby; if ( ! isset( $plugin_a->$orderby, $plugin_b->$orderby ) ) { return 0; } $a = $plugin_a->$orderby; $b = $plugin_b->$orderby; if ( $a === $b ) { return 0; } if ( 'DESC' === $this->order ) { return ( $a < $b ) ? 1 : -1; } else { return ( $a < $b ) ? -1 : 1; } } public function display_rows() { $plugins_allowedtags = array( 'a' => array( 'href' => array(), 'title' => array(), 'target' => array(), ), 'abbr' => array( 'title' => array() ), 'acronym' => array( 'title' => array() ), 'code' => array(), 'pre' => array(), 'em' => array(), 'strong' => array(), 'ul' => array(), 'ol' => array(), 'li' => array(), 'p' => array(), 'br' => array(), ); $plugins_group_titles = array( 'Performance' => _x( 'Performance', 'Plugin installer group title' ), 'Social' => _x( 'Social', 'Plugin installer group title' ), 'Tools' => _x( 'Tools', 'Plugin installer group title' ), ); $group = null; foreach ( (array) $this->items as $plugin ) { if ( is_object( $plugin ) ) { $plugin = (array) $plugin; } // Display the group heading if there is one. if ( isset( $plugin['group'] ) && $plugin['group'] !== $group ) { if ( isset( $this->groups[ $plugin['group'] ] ) ) { $group_name = $this->groups[ $plugin['group'] ]; if ( isset( $plugins_group_titles[ $group_name ] ) ) { $group_name = $plugins_group_titles[ $group_name ]; } } else { $group_name = $plugin['group']; } // Starting a new group, close off the divs of the last one. if ( ! empty( $group ) ) { echo '
'; } echo '

' . esc_html( $group_name ) . '

'; // Needs an extra wrapping div for nth-child selectors to work. echo '
'; $group = $plugin['group']; } $title = wp_kses( $plugin['name'], $plugins_allowedtags ); // Remove any HTML from the description. $description = strip_tags( $plugin['short_description'] ); /** * Filters the plugin card description on the Add Plugins screen. * * @since 6.0.0 * * @param string $description Plugin card description. * @param array $plugin An array of plugin data. See {@see plugins_api()} * for the list of possible values. */ $description = apply_filters( 'plugin_install_description', $description, $plugin ); $version = wp_kses( $plugin['version'], $plugins_allowedtags ); $name = strip_tags( $title . ' ' . $version ); $author = wp_kses( $plugin['author'], $plugins_allowedtags ); if ( ! empty( $author ) ) { /* translators: %s: Plugin author. */ $author = ' ' . sprintf( __( 'By %s' ), $author ) . ''; } $requires_php = isset( $plugin['requires_php'] ) ? $plugin['requires_php'] : null; $requires_wp = isset( $plugin['requires'] ) ? $plugin['requires'] : null; $compatible_php = is_php_version_compatible( $requires_php ); $compatible_wp = is_wp_version_compatible( $requires_wp ); $tested_wp = ( empty( $plugin['tested'] ) || version_compare( get_bloginfo( 'version' ), $plugin['tested'], '<=' ) ); $action_links = array(); $action_links[] = wp_get_plugin_action_button( $name, $plugin, $compatible_php, $compatible_wp ); $details_link = self_admin_url( 'plugin-install.php?tab=plugin-information&plugin=' . $plugin['slug'] . '&TB_iframe=true&width=600&height=550' ); $action_links[] = sprintf( '%s', esc_url( $details_link ), /* translators: %s: Plugin name and version. */ esc_attr( sprintf( __( 'More information about %s' ), $name ) ), esc_attr( $name ), __( 'More Details' ) ); if ( ! empty( $plugin['icons']['svg'] ) ) { $plugin_icon_url = $plugin['icons']['svg']; } elseif ( ! empty( $plugin['icons']['2x'] ) ) { $plugin_icon_url = $plugin['icons']['2x']; } elseif ( ! empty( $plugin['icons']['1x'] ) ) { $plugin_icon_url = $plugin['icons']['1x']; } else { $plugin_icon_url = $plugin['icons']['default']; } /** * Filters the install action links for a plugin. * * @since 2.7.0 * * @param string[] $action_links An array of plugin action links. * Defaults are links to Details and Install Now. * @param array $plugin An array of plugin data. See {@see plugins_api()} * for the list of possible values. */ $action_links = apply_filters( 'plugin_install_action_links', $action_links, $plugin ); $last_updated_timestamp = strtotime( $plugin['last_updated'] ); ?>
Please update WordPress, and then learn more about updating PHP.' ), self_admin_url( 'update-core.php' ), esc_url( wp_get_update_php_url() ) ); $incompatible_notice_message .= wp_update_php_annotation( '

', '', false ); } elseif ( current_user_can( 'update_core' ) ) { $incompatible_notice_message .= sprintf( /* translators: %s: URL to WordPress Updates screen. */ ' ' . __( 'Please update WordPress.' ), self_admin_url( 'update-core.php' ) ); } elseif ( current_user_can( 'update_php' ) ) { $incompatible_notice_message .= sprintf( /* translators: %s: URL to Update PHP page. */ ' ' . __( 'Learn more about updating PHP.' ), esc_url( wp_get_update_php_url() ) ); $incompatible_notice_message .= wp_update_php_annotation( '

', '', false ); } } elseif ( ! $compatible_wp ) { $incompatible_notice_message .= __( 'This plugin does not work with your version of WordPress.' ); if ( current_user_can( 'update_core' ) ) { $incompatible_notice_message .= sprintf( /* translators: %s: URL to WordPress Updates screen. */ ' ' . __( 'Please update WordPress.' ), self_admin_url( 'update-core.php' ) ); } } elseif ( ! $compatible_php ) { $incompatible_notice_message .= __( 'This plugin does not work with your version of PHP.' ); if ( current_user_can( 'update_php' ) ) { $incompatible_notice_message .= sprintf( /* translators: %s: URL to Update PHP page. */ ' ' . __( 'Learn more about updating PHP.' ), esc_url( wp_get_update_php_url() ) ); $incompatible_notice_message .= wp_update_php_annotation( '

', '', false ); } } wp_admin_notice( $incompatible_notice_message, array( 'type' => 'error', 'additional_classes' => array( 'notice-alt', 'inline' ), ) ); } ?>

get_dependencies_notice( $plugin ); if ( ! empty( $dependencies_notice ) ) { echo $dependencies_notice; } ?>
$plugin['rating'], 'type' => 'percent', 'number' => $plugin['num_ratings'], ) ); ?>
= 1000000 ) { $active_installs_millions = floor( $plugin['active_installs'] / 1000000 ); $active_installs_text = sprintf( /* translators: %s: Number of millions. */ _nx( '%s+ Million', '%s+ Million', $active_installs_millions, 'Active plugin installations' ), number_format_i18n( $active_installs_millions ) ); } elseif ( 0 === $plugin['active_installs'] ) { $active_installs_text = _x( 'Less Than 10', 'Active plugin installations' ); } else { $active_installs_text = number_format_i18n( $plugin['active_installs'] ) . '+'; } /* translators: %s: Number of installations. */ printf( __( '%s Active Installations' ), $active_installs_text ); ?>
' . __( '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 = '
%s
'; $has_name_markup = '
%s %s
'; $dependencies_list = ''; foreach ( $plugin_data['requires_plugins'] as $dependency ) { $dependency_data = WP_Plugin_Dependencies::get_dependency_data( $dependency ); if ( false !== $dependency_data && ! empty( $dependency_data['name'] ) && ! empty( $dependency_data['slug'] ) && ! empty( $dependency_data['version'] ) ) { $more_details_link = $this->get_more_details_link( $dependency_data['name'], $dependency_data['slug'] ); $dependencies_list .= sprintf( $has_name_markup, esc_html( $dependency_data['name'] ), $more_details_link ); continue; } $result = plugins_api( 'plugin_information', array( 'slug' => $dependency ) ); if ( ! empty( $result->name ) ) { $more_details_link = $this->get_more_details_link( $result->name, $result->slug ); $dependencies_list .= sprintf( $has_name_markup, esc_html( $result->name ), $more_details_link ); continue; } $dependencies_list .= sprintf( $no_name_markup, esc_html( $dependency ) ); } $dependencies_notice = sprintf( '

%s

%s
', '' . __( 'Additional plugins are required' ) . '', $dependencies_list ); return $dependencies_notice; } /** * Creates a 'More 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 The 'More details' link for the plugin. */ protected function get_more_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' ) ); $more_details_link = sprintf( '%4$s', esc_url( $url ), /* translators: %s: Plugin name. */ sprintf( __( 'More information about %s' ), esc_html( $name ) ), esc_attr( $name ), __( 'More Details' ) ); return $more_details_link; } } class-wp-plugins-list-table.php000064400000160576146715570560012562 0ustar00 '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 ); } $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 ''; } ?> ! 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 '
'; if ( 'recently_activated' === $status ) { submit_button( __( 'Clear List' ), '', 'clear-recent-list', false ); } elseif ( 'top' === $which && 'mustuse' === $status ) { echo '

' . sprintf( /* translators: %s: mu-plugins directory name. */ __( 'Files in the %s directory are executed automatically.' ), '' . str_replace( ABSPATH, '/', WPMU_PLUGIN_DIR ) . '' ) . '

'; } elseif ( 'top' === $which && 'dropins' === $status ) { 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 ) . '' ) . '

'; } echo '
'; } /** * @return string */ public function current_action() { if ( isset( $_POST['clear-recent-list'] ) ) { return 'clear-recent-list'; } return parent::current_action(); } /** * @global string $status */ public function display_rows() { global $status; if ( is_multisite() && ! $this->screen->in_admin( 'network' ) && in_array( $status, array( 'mustuse', 'dropins' ), true ) ) { return; } foreach ( $this->items as $plugin_file => $plugin_data ) { $this->single_row( array( $plugin_file, $plugin_data ) ); } } /** * @global string $status * @global int $page * @global string $s * @global array $totals * * @param array $item */ public function single_row( $item ) { global $status, $page, $s, $totals; static $plugin_id_attrs = array(); list( $plugin_file, $plugin_data ) = $item; $plugin_slug = isset( $plugin_data['slug'] ) ? $plugin_data['slug'] : sanitize_title( $plugin_data['Name'] ); $plugin_id_attr = $plugin_slug; // Ensure the ID attribute is unique. $suffix = 2; while ( in_array( $plugin_id_attr, $plugin_id_attrs, true ) ) { $plugin_id_attr = "$plugin_slug-$suffix"; ++$suffix; } $plugin_id_attrs[] = $plugin_id_attr; $context = $status; $screen = $this->screen; // Pre-order. $actions = array( 'deactivate' => '', 'activate' => '', 'details' => '', 'delete' => '', ); // Do not restrict by default. $restrict_network_active = false; $restrict_network_only = false; $requires_php = isset( $plugin_data['RequiresPHP'] ) ? $plugin_data['RequiresPHP'] : null; $requires_wp = isset( $plugin_data['RequiresWP'] ) ? $plugin_data['RequiresWP'] : null; $compatible_php = is_php_version_compatible( $requires_php ); $compatible_wp = is_wp_version_compatible( $requires_wp ); $has_dependents = WP_Plugin_Dependencies::has_dependents( $plugin_file ); $has_active_dependents = WP_Plugin_Dependencies::has_active_dependents( $plugin_file ); $has_unmet_dependencies = WP_Plugin_Dependencies::has_unmet_dependencies( $plugin_file ); $has_circular_dependency = WP_Plugin_Dependencies::has_circular_dependency( $plugin_file ); if ( 'mustuse' === $context ) { $is_active = true; } elseif ( 'dropins' === $context ) { $dropins = _get_dropins(); $plugin_name = $plugin_file; if ( $plugin_file !== $plugin_data['Name'] ) { $plugin_name .= '
' . $plugin_data['Name']; } if ( true === ( $dropins[ $plugin_file ][1] ) ) { // Doesn't require a constant. $is_active = true; $description = '

' . $dropins[ $plugin_file ][0] . '

'; } elseif ( defined( $dropins[ $plugin_file ][1] ) && constant( $dropins[ $plugin_file ][1] ) ) { // Constant is true. $is_active = true; $description = '

' . $dropins[ $plugin_file ][0] . '

'; } else { $is_active = false; $description = '

' . $dropins[ $plugin_file ][0] . ' ' . __( 'Inactive:' ) . ' ' . sprintf( /* translators: 1: Drop-in constant name, 2: wp-config.php */ __( 'Requires %1$s in %2$s file.' ), "define('" . $dropins[ $plugin_file ][1] . "', true);", 'wp-config.php' ) . '

'; } if ( $plugin_data['Description'] ) { $description .= '

' . $plugin_data['Description'] . '

'; } } else { if ( $screen->in_admin( 'network' ) ) { $is_active = is_plugin_active_for_network( $plugin_file ); } else { $is_active = is_plugin_active( $plugin_file ); $restrict_network_active = ( is_multisite() && is_plugin_active_for_network( $plugin_file ) ); $restrict_network_only = ( is_multisite() && is_network_only_plugin( $plugin_file ) && ! $is_active ); } if ( $screen->in_admin( 'network' ) ) { if ( $is_active ) { if ( current_user_can( 'manage_network_plugins' ) ) { if ( $has_active_dependents ) { $actions['deactivate'] = __( 'Deactivate' ) . '' . __( 'You cannot deactivate this plugin as other plugins require it.' ) . ''; } else { $deactivate_url = 'plugins.php?action=deactivate' . '&plugin=' . urlencode( $plugin_file ) . '&plugin_status=' . $context . '&paged=' . $page . '&s=' . $s; $actions['deactivate'] = sprintf( '%s', wp_nonce_url( $deactivate_url, 'deactivate-plugin_' . $plugin_file ), esc_attr( $plugin_id_attr ), /* translators: %s: Plugin name. */ esc_attr( sprintf( _x( 'Network Deactivate %s', 'plugin' ), $plugin_data['Name'] ) ), _x( 'Network Deactivate', 'plugin' ) ); } } } else { if ( current_user_can( 'manage_network_plugins' ) ) { if ( $compatible_php && $compatible_wp ) { if ( $has_unmet_dependencies ) { $actions['activate'] = _x( 'Network Activate', 'plugin' ) . '' . __( 'You cannot activate this plugin as it has unmet requirements.' ) . ''; } else { $activate_url = 'plugins.php?action=activate' . '&plugin=' . urlencode( $plugin_file ) . '&plugin_status=' . $context . '&paged=' . $page . '&s=' . $s; $actions['activate'] = sprintf( '%s', wp_nonce_url( $activate_url, 'activate-plugin_' . $plugin_file ), esc_attr( $plugin_id_attr ), /* translators: %s: Plugin name. */ esc_attr( sprintf( _x( 'Network Activate %s', 'plugin' ), $plugin_data['Name'] ) ), _x( 'Network Activate', 'plugin' ) ); } } else { $actions['activate'] = sprintf( '%s', _x( 'Cannot Activate', 'plugin' ) ); } } if ( current_user_can( 'delete_plugins' ) && ! is_plugin_active( $plugin_file ) ) { if ( $has_dependents && ! $has_circular_dependency ) { $actions['delete'] = __( 'Delete' ) . '' . __( 'You cannot delete this plugin as other plugins require it.' ) . ''; } else { $delete_url = 'plugins.php?action=delete-selected' . '&checked[]=' . urlencode( $plugin_file ) . '&plugin_status=' . $context . '&paged=' . $page . '&s=' . $s; $actions['delete'] = sprintf( '%s', wp_nonce_url( $delete_url, 'bulk-plugins' ), esc_attr( $plugin_id_attr ), /* translators: %s: Plugin name. */ esc_attr( sprintf( _x( 'Delete %s', 'plugin' ), $plugin_data['Name'] ) ), __( 'Delete' ) ); } } } } else { if ( $restrict_network_active ) { $actions = array( 'network_active' => __( 'Network Active' ), ); } elseif ( $restrict_network_only ) { $actions = array( 'network_only' => __( 'Network Only' ), ); } elseif ( $is_active ) { if ( current_user_can( 'deactivate_plugin', $plugin_file ) ) { if ( $has_active_dependents ) { $actions['deactivate'] = __( 'Deactivate' ) . '' . __( 'You cannot deactivate this plugin as other plugins depend on it.' ) . ''; } else { $deactivate_url = 'plugins.php?action=deactivate' . '&plugin=' . urlencode( $plugin_file ) . '&plugin_status=' . $context . '&paged=' . $page . '&s=' . $s; $actions['deactivate'] = sprintf( '%s', wp_nonce_url( $deactivate_url, 'deactivate-plugin_' . $plugin_file ), esc_attr( $plugin_id_attr ), /* translators: %s: Plugin name. */ esc_attr( sprintf( _x( 'Deactivate %s', 'plugin' ), $plugin_data['Name'] ) ), __( 'Deactivate' ) ); } } if ( current_user_can( 'resume_plugin', $plugin_file ) && is_plugin_paused( $plugin_file ) ) { $resume_url = 'plugins.php?action=resume' . '&plugin=' . urlencode( $plugin_file ) . '&plugin_status=' . $context . '&paged=' . $page . '&s=' . $s; $actions['resume'] = sprintf( '%s', wp_nonce_url( $resume_url, 'resume-plugin_' . $plugin_file ), esc_attr( $plugin_id_attr ), /* translators: %s: Plugin name. */ esc_attr( sprintf( _x( 'Resume %s', 'plugin' ), $plugin_data['Name'] ) ), __( 'Resume' ) ); } } else { if ( current_user_can( 'activate_plugin', $plugin_file ) ) { if ( $compatible_php && $compatible_wp ) { if ( $has_unmet_dependencies ) { $actions['activate'] = _x( 'Activate', 'plugin' ) . '' . __( 'You cannot activate this plugin as it has unmet requirements.' ) . ''; } else { $activate_url = 'plugins.php?action=activate' . '&plugin=' . urlencode( $plugin_file ) . '&plugin_status=' . $context . '&paged=' . $page . '&s=' . $s; $actions['activate'] = sprintf( '%s', wp_nonce_url( $activate_url, 'activate-plugin_' . $plugin_file ), esc_attr( $plugin_id_attr ), /* translators: %s: Plugin name. */ esc_attr( sprintf( _x( 'Activate %s', 'plugin' ), $plugin_data['Name'] ) ), _x( 'Activate', 'plugin' ) ); } } else { $actions['activate'] = sprintf( '%s', _x( 'Cannot Activate', 'plugin' ) ); } } if ( ! is_multisite() && current_user_can( 'delete_plugins' ) ) { if ( $has_dependents && ! $has_circular_dependency ) { $actions['delete'] = __( 'Delete' ) . '' . __( 'You cannot delete this plugin as other plugins require it.' ) . ''; } else { $delete_url = 'plugins.php?action=delete-selected' . '&checked[]=' . urlencode( $plugin_file ) . '&plugin_status=' . $context . '&paged=' . $page . '&s=' . $s; $actions['delete'] = sprintf( '%s', wp_nonce_url( $delete_url, 'bulk-plugins' ), esc_attr( $plugin_id_attr ), /* translators: %s: Plugin name. */ esc_attr( sprintf( _x( 'Delete %s', 'plugin' ), $plugin_data['Name'] ) ), __( 'Delete' ) ); } } } // End if $is_active. } // End if $screen->in_admin( 'network' ). } // End if $context. $actions = array_filter( $actions ); if ( $screen->in_admin( 'network' ) ) { /** * Filters the action links displayed for each plugin in the Network Admin Plugins list table. * * @since 3.1.0 * * @param string[] $actions An array of plugin action links. By default this can include * 'activate', 'deactivate', and 'delete'. * @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 $context The plugin context. By default this can include 'all', * 'active', 'inactive', 'recently_activated', 'upgrade', * 'mustuse', 'dropins', and 'search'. */ $actions = apply_filters( 'network_admin_plugin_action_links', $actions, $plugin_file, $plugin_data, $context ); /** * Filters the list of action links displayed for a specific plugin in the Network Admin 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 3.1.0 * * @param string[] $actions An array of plugin action links. By default this can include * 'activate', 'deactivate', and 'delete'. * @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 $context The plugin context. By default this can include 'all', * 'active', 'inactive', 'recently_activated', 'upgrade', * 'mustuse', 'dropins', and 'search'. */ $actions = apply_filters( "network_admin_plugin_action_links_{$plugin_file}", $actions, $plugin_file, $plugin_data, $context ); } else { /** * Filters the action links displayed for each plugin in the Plugins list table. * * @since 2.5.0 * @since 2.6.0 The `$context` parameter was added. * @since 4.9.0 The 'Edit' link was removed from the list of action links. * * @param string[] $actions An array of plugin action links. By default this can include * 'activate', 'deactivate', and 'delete'. With Multisite active * this can also include 'network_active' and 'network_only' items. * @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 $context The plugin context. By default this can include 'all', * 'active', 'inactive', 'recently_activated', 'upgrade', * 'mustuse', 'dropins', and 'search'. */ $actions = apply_filters( 'plugin_action_links', $actions, $plugin_file, $plugin_data, $context ); /** * Filters the list of action links displayed for a specific plugin 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 4.9.0 The 'Edit' link was removed from the list of action links. * * @param string[] $actions An array of plugin action links. By default this can include * 'activate', 'deactivate', and 'delete'. With Multisite active * this can also include 'network_active' and 'network_only' items. * @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 $context The plugin context. By default this can include 'all', * 'active', 'inactive', 'recently_activated', 'upgrade', * 'mustuse', 'dropins', and 'search'. */ $actions = apply_filters( "plugin_action_links_{$plugin_file}", $actions, $plugin_file, $plugin_data, $context ); } $class = $is_active ? 'active' : 'inactive'; $checkbox_id = 'checkbox_' . md5( $plugin_file ); $disabled = ''; if ( $has_dependents || $has_unmet_dependencies ) { $disabled = 'disabled'; } if ( $restrict_network_active || $restrict_network_only || in_array( $status, array( 'mustuse', 'dropins' ), true ) || ! $compatible_php ) { $checkbox = ''; } else { $checkbox = sprintf( '' . '', $checkbox_id, /* translators: Hidden accessibility text. %s: Plugin name. */ sprintf( __( 'Select %s' ), $plugin_data['Name'] ), esc_attr( $plugin_file ) ); } if ( 'dropins' !== $context ) { $description = '

' . ( $plugin_data['Description'] ? $plugin_data['Description'] : ' ' ) . '

'; $plugin_name = $plugin_data['Name']; } if ( ! empty( $totals['upgrade'] ) && ! empty( $plugin_data['update'] ) || ! $compatible_php || ! $compatible_wp ) { $class .= ' update'; } $paused = ! $screen->in_admin( 'network' ) && is_plugin_paused( $plugin_file ); if ( $paused ) { $class .= ' paused'; } if ( is_uninstallable_plugin( $plugin_file ) ) { $class .= ' is-uninstallable'; } printf( '', esc_attr( $class ), esc_attr( $plugin_slug ), esc_attr( $plugin_file ) ); list( $columns, $hidden, $sortable, $primary ) = $this->get_column_info(); $auto_updates = (array) get_site_option( 'auto_update_plugins', array() ); foreach ( $columns as $column_name => $column_display_name ) { $extra_classes = ''; if ( in_array( $column_name, $hidden, true ) ) { $extra_classes = ' hidden'; } switch ( $column_name ) { case 'cb': echo "$checkbox"; break; case 'name': echo "$plugin_name"; echo $this->row_actions( $actions, true ); echo ''; break; case 'description': $classes = 'column-description desc'; echo "
$description
"; $plugin_meta = array(); if ( ! empty( $plugin_data['Version'] ) ) { /* translators: %s: Plugin version number. */ $plugin_meta[] = sprintf( __( 'Version %s' ), $plugin_data['Version'] ); } if ( ! empty( $plugin_data['Author'] ) ) { $author = $plugin_data['Author']; if ( ! empty( $plugin_data['AuthorURI'] ) ) { $author = '' . $plugin_data['Author'] . ''; } /* translators: %s: Plugin author name. */ $plugin_meta[] = sprintf( __( 'By %s' ), $author ); } // Details link using API info, if available. if ( isset( $plugin_data['slug'] ) && current_user_can( 'install_plugins' ) ) { $plugin_meta[] = sprintf( '%s', esc_url( network_admin_url( 'plugin-install.php?tab=plugin-information&plugin=' . $plugin_data['slug'] . '&TB_iframe=true&width=600&height=550' ) ), /* translators: %s: Plugin name. */ esc_attr( sprintf( __( 'More information about %s' ), $plugin_name ) ), esc_attr( $plugin_name ), __( 'View details' ) ); } elseif ( ! empty( $plugin_data['PluginURI'] ) ) { /* translators: %s: Plugin name. */ $aria_label = sprintf( __( 'Visit plugin site for %s' ), $plugin_name ); $plugin_meta[] = sprintf( '%s', esc_url( $plugin_data['PluginURI'] ), esc_attr( $aria_label ), __( 'Visit plugin site' ) ); } /** * Filters the array of row meta for each plugin in the Plugins list table. * * @since 2.8.0 * * @param string[] $plugin_meta An array of the plugin's metadata, including * the version, author, author URI, and plugin URI. * @param string $plugin_file Path to the plugin file relative to the plugins directory. * @param array $plugin_data { * An array of plugin data. * * @type string $id Plugin ID, e.g. `w.org/plugins/[plugin-name]`. * @type string $slug Plugin slug. * @type string $plugin Plugin basename. * @type string $new_version New plugin version. * @type string $url Plugin URL. * @type string $package Plugin update package URL. * @type string[] $icons An array of plugin icon URLs. * @type string[] $banners An array of plugin banner URLs. * @type string[] $banners_rtl An array of plugin RTL banner URLs. * @type string $requires The version of WordPress which the plugin requires. * @type string $tested The version of WordPress the plugin is tested against. * @type string $requires_php The version of PHP which the plugin requires. * @type string $upgrade_notice The upgrade notice for the new plugin version. * @type bool $update-supported Whether the plugin supports updates. * @type string $Name The human-readable name of the plugin. * @type string $PluginURI Plugin URI. * @type string $Version Plugin version. * @type string $Description Plugin description. * @type string $Author Plugin author. * @type string $AuthorURI Plugin author URI. * @type string $TextDomain Plugin textdomain. * @type string $DomainPath Relative path to the plugin's .mo file(s). * @type bool $Network Whether the plugin can only be activated network-wide. * @type string $RequiresWP The version of WordPress which the plugin requires. * @type string $RequiresPHP The version of PHP which the plugin requires. * @type string $UpdateURI ID of the plugin for update purposes, should be a URI. * @type string $Title The human-readable title of the plugin. * @type string $AuthorName Plugin author's name. * @type bool $update Whether there's an available update. Default null. * } * @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'. */ $plugin_meta = apply_filters( 'plugin_row_meta', $plugin_meta, $plugin_file, $plugin_data, $status ); echo implode( ' | ', $plugin_meta ); echo '
'; if ( $has_dependents ) { $this->add_dependents_to_dependency_plugin_row( $plugin_file ); } if ( WP_Plugin_Dependencies::has_dependencies( $plugin_file ) ) { $this->add_dependencies_to_dependent_plugin_row( $plugin_file ); } /** * Fires after plugin row meta. * * @since 6.5.0 * * @param string $plugin_file Refer to {@see 'plugin_row_meta'} filter. * @param array $plugin_data Refer to {@see 'plugin_row_meta'} filter. */ do_action( 'after_plugin_row_meta', $plugin_file, $plugin_data ); if ( $paused ) { $notice_text = __( 'This plugin failed to load properly and is paused during recovery mode.' ); printf( '

%s

', $notice_text ); $error = wp_get_plugin_error( $plugin_file ); if ( false !== $error ) { printf( '

%s

', wp_get_extension_error_description( $error ) ); } } echo ''; break; case 'auto-updates': if ( ! $this->show_autoupdates || in_array( $status, array( 'mustuse', 'dropins' ), true ) ) { break; } echo ""; $html = array(); if ( isset( $plugin_data['auto-update-forced'] ) ) { if ( $plugin_data['auto-update-forced'] ) { // Forced on. $text = __( 'Auto-updates enabled' ); } else { $text = __( 'Auto-updates disabled' ); } $action = 'unavailable'; $time_class = ' hidden'; } elseif ( empty( $plugin_data['update-supported'] ) ) { $text = ''; $action = 'unavailable'; $time_class = ' hidden'; } elseif ( in_array( $plugin_file, $auto_updates, true ) ) { $text = __( 'Disable auto-updates' ); $action = 'disable'; $time_class = ''; } else { $text = __( 'Enable auto-updates' ); $action = 'enable'; $time_class = ' hidden'; } $query_args = array( 'action' => "{$action}-auto-update", 'plugin' => $plugin_file, 'paged' => $page, 'plugin_status' => $status, ); $url = add_query_arg( $query_args, 'plugins.php' ); if ( 'unavailable' === $action ) { $html[] = '' . $text . ''; } else { $html[] = sprintf( '', wp_nonce_url( $url, 'updates' ), $action ); $html[] = ''; $html[] = '' . $text . ''; $html[] = ''; } if ( ! empty( $plugin_data['update'] ) ) { $html[] = sprintf( '
%s
', $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 ''; break; default: $classes = "$column_name column-$column_name $class"; 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 ''; } } echo ''; if ( ! $compatible_php || ! $compatible_wp ) { printf( '', esc_attr( $this->get_column_count() ) ); $incompatible_message = ''; if ( ! $compatible_php && ! $compatible_wp ) { $incompatible_message .= __( 'This plugin does not work with your versions of WordPress and PHP.' ); if ( current_user_can( 'update_core' ) && current_user_can( 'update_php' ) ) { $incompatible_message .= sprintf( /* translators: 1: URL to WordPress Updates screen, 2: URL to Update PHP page. */ ' ' . __( 'Please update WordPress, and then learn more about updating PHP.' ), self_admin_url( 'update-core.php' ), esc_url( wp_get_update_php_url() ) ); $incompatible_message .= wp_update_php_annotation( '

', '', false ); } elseif ( current_user_can( 'update_core' ) ) { $incompatible_message .= sprintf( /* translators: %s: URL to WordPress Updates screen. */ ' ' . __( 'Please update WordPress.' ), self_admin_url( 'update-core.php' ) ); } elseif ( current_user_can( 'update_php' ) ) { $incompatible_message .= sprintf( /* translators: %s: URL to Update PHP page. */ ' ' . __( 'Learn more about updating PHP.' ), esc_url( wp_get_update_php_url() ) ); $incompatible_message .= wp_update_php_annotation( '

', '', false ); } } elseif ( ! $compatible_wp ) { $incompatible_message .= __( 'This plugin does not work with your version of WordPress.' ); if ( current_user_can( 'update_core' ) ) { $incompatible_message .= sprintf( /* translators: %s: URL to WordPress Updates screen. */ ' ' . __( 'Please update WordPress.' ), self_admin_url( 'update-core.php' ) ); } } elseif ( ! $compatible_php ) { $incompatible_message .= __( 'This plugin does not work with your version of PHP.' ); if ( current_user_can( 'update_php' ) ) { $incompatible_message .= sprintf( /* translators: %s: URL to Update PHP page. */ ' ' . __( 'Learn more about updating PHP.' ), esc_url( wp_get_update_php_url() ) ); $incompatible_message .= wp_update_php_annotation( '

', '', false ); } } wp_admin_notice( $incompatible_message, array( 'type' => 'error', 'additional_classes' => array( 'notice-alt', 'inline', 'update-message' ), ) ); 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-ms-themes-list-table.php000064400000067166146715570560013004 0ustar00 'themes', 'screen' => isset( $args['screen'] ) ? $args['screen'] : null, ) ); $status = isset( $_REQUEST['theme_status'] ) ? $_REQUEST['theme_status'] : 'all'; if ( ! in_array( $status, array( 'all', 'enabled', 'disabled', 'upgrade', 'search', 'broken', 'auto-update-enabled', 'auto-update-disabled' ), true ) ) { $status = 'all'; } $page = $this->get_pagenum(); $this->is_site_themes = ( 'site-themes-network' === $this->screen->id ) ? true : false; if ( $this->is_site_themes ) { $this->site_id = isset( $_REQUEST['id'] ) ? (int) $_REQUEST['id'] : 0; } $this->show_autoupdates = wp_is_auto_update_enabled_for_type( 'theme' ) && ! $this->is_site_themes && current_user_can( 'update_themes' ); } /** * @return array */ protected function get_table_classes() { // @todo Remove and add CSS for .themes. return array( 'widefat', 'plugins' ); } /** * @return bool */ public function ajax_user_can() { if ( $this->is_site_themes ) { return current_user_can( 'manage_sites' ); } else { return current_user_can( 'manage_network_themes' ); } } /** * @global string $status * @global array $totals * @global int $page * @global string $orderby * @global string $order * @global string $s */ public function prepare_items() { global $status, $totals, $page, $orderby, $order, $s; $orderby = ! empty( $_REQUEST['orderby'] ) ? sanitize_text_field( $_REQUEST['orderby'] ) : ''; $order = ! empty( $_REQUEST['order'] ) ? sanitize_text_field( $_REQUEST['order'] ) : ''; $s = ! empty( $_REQUEST['s'] ) ? sanitize_text_field( $_REQUEST['s'] ) : ''; $themes = array( /** * Filters the full array of WP_Theme objects to list in the Multisite * themes list table. * * @since 3.1.0 * * @param WP_Theme[] $all Array of WP_Theme objects to display in the list table. */ 'all' => apply_filters( 'all_themes', wp_get_themes() ), 'search' => array(), 'enabled' => array(), 'disabled' => array(), 'upgrade' => array(), 'broken' => $this->is_site_themes ? array() : wp_get_themes( array( 'errors' => true ) ), ); if ( $this->show_autoupdates ) { $auto_updates = (array) get_site_option( 'auto_update_themes', array() ); $themes['auto-update-enabled'] = array(); $themes['auto-update-disabled'] = array(); } if ( $this->is_site_themes ) { $themes_per_page = $this->get_items_per_page( 'site_themes_network_per_page' ); $allowed_where = 'site'; } else { $themes_per_page = $this->get_items_per_page( 'themes_network_per_page' ); $allowed_where = 'network'; } $current = get_site_transient( 'update_themes' ); $maybe_update = current_user_can( 'update_themes' ) && ! $this->is_site_themes && $current; foreach ( (array) $themes['all'] as $key => $theme ) { if ( $this->is_site_themes && $theme->is_allowed( 'network' ) ) { unset( $themes['all'][ $key ] ); continue; } if ( $maybe_update && isset( $current->response[ $key ] ) ) { $themes['all'][ $key ]->update = true; $themes['upgrade'][ $key ] = $themes['all'][ $key ]; } $filter = $theme->is_allowed( $allowed_where, $this->site_id ) ? 'enabled' : 'disabled'; $themes[ $filter ][ $key ] = $themes['all'][ $key ]; $theme_data = array( 'update_supported' => isset( $theme->update_supported ) ? $theme->update_supported : true, ); // Extra info if known. array_merge() ensures $theme_data has precedence if keys collide. if ( isset( $current->response[ $key ] ) ) { $theme_data = array_merge( (array) $current->response[ $key ], $theme_data ); } elseif ( isset( $current->no_update[ $key ] ) ) { $theme_data = array_merge( (array) $current->no_update[ $key ], $theme_data ); } else { $theme_data['update_supported'] = false; } $theme->update_supported = $theme_data['update_supported']; /* * Create the expected payload for the auto_update_theme filter, this is the same data * as contained within $updates or $no_updates but used when the Theme is not known. */ $filter_payload = array( 'theme' => $key, 'new_version' => '', 'url' => '', 'package' => '', 'requires' => '', 'requires_php' => '', ); $filter_payload = (object) array_merge( $filter_payload, array_intersect_key( $theme_data, $filter_payload ) ); $auto_update_forced = wp_is_auto_update_forced_for_item( 'theme', null, $filter_payload ); if ( ! is_null( $auto_update_forced ) ) { $theme->auto_update_forced = $auto_update_forced; } if ( $this->show_autoupdates ) { $enabled = in_array( $key, $auto_updates, true ) && $theme->update_supported; if ( isset( $theme->auto_update_forced ) ) { $enabled = (bool) $theme->auto_update_forced; } if ( $enabled ) { $themes['auto-update-enabled'][ $key ] = $theme; } else { $themes['auto-update-disabled'][ $key ] = $theme; } } } if ( $s ) { $status = 'search'; $themes['search'] = array_filter( array_merge( $themes['all'], $themes['broken'] ), array( $this, '_search_callback' ) ); } $totals = array(); $js_themes = array(); foreach ( $themes as $type => $list ) { $totals[ $type ] = count( $list ); $js_themes[ $type ] = array_keys( $list ); } if ( empty( $themes[ $status ] ) && ! in_array( $status, array( 'all', 'search' ), true ) ) { $status = 'all'; } $this->items = $themes[ $status ]; WP_Theme::sort_by_name( $this->items ); $this->has_items = ! empty( $themes['all'] ); $total_this_page = $totals[ $status ]; wp_localize_script( 'updates', '_wpUpdatesItemCounts', array( 'themes' => $js_themes, 'totals' => wp_get_update_data(), ) ); if ( $orderby ) { $orderby = ucfirst( $orderby ); $order = strtoupper( $order ); if ( 'Name' === $orderby ) { if ( 'ASC' === $order ) { $this->items = array_reverse( $this->items ); } } else { uasort( $this->items, array( $this, '_order_callback' ) ); } } $start = ( $page - 1 ) * $themes_per_page; if ( $total_this_page > $themes_per_page ) { $this->items = array_slice( $this->items, $start, $themes_per_page, true ); } $this->set_pagination_args( array( 'total_items' => $total_this_page, 'per_page' => $themes_per_page, ) ); } /** * @param WP_Theme $theme * @return bool */ public function _search_callback( $theme ) { static $term = null; if ( is_null( $term ) ) { $term = wp_unslash( $_REQUEST['s'] ); } foreach ( array( 'Name', 'Description', 'Author', 'Author', 'AuthorURI' ) as $field ) { // Don't mark up; Do translate. if ( false !== stripos( $theme->display( $field, false, true ), $term ) ) { return true; } } if ( false !== stripos( $theme->get_stylesheet(), $term ) ) { return true; } if ( false !== stripos( $theme->get_template(), $term ) ) { return true; } return false; } // Not used by any core columns. /** * @global string $orderby * @global string $order * @param array $theme_a * @param array $theme_b * @return int */ public function _order_callback( $theme_a, $theme_b ) { global $orderby, $order; $a = $theme_a[ $orderby ]; $b = $theme_b[ $orderby ]; if ( $a === $b ) { return 0; } if ( 'DESC' === $order ) { return ( $a < $b ) ? 1 : -1; } else { return ( $a < $b ) ? -1 : 1; } } /** */ public function no_items() { if ( $this->has_items ) { _e( 'No themes found.' ); } else { _e( 'No themes are currently available.' ); } } /** * @return string[] Array of column titles keyed by their column name. */ public function get_columns() { $columns = array( 'cb' => '', 'name' => __( 'Theme' ), 'description' => __( 'Description' ), ); if ( $this->show_autoupdates ) { $columns['auto-updates'] = __( 'Automatic Updates' ); } return $columns; } /** * @return array */ protected function get_sortable_columns() { return array( 'name' => array( 'name', false, __( 'Theme' ), __( 'Table ordered by Theme Name.' ), 'asc' ), ); } /** * Gets the name of the primary column. * * @since 4.3.0 * * @return string Unalterable name of the primary column name, in this case, 'name'. */ protected function get_primary_column_name() { return 'name'; } /** * @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 themes. */ $text = _nx( 'All (%s)', 'All (%s)', $count, 'themes' ); break; case 'enabled': /* translators: %s: Number of themes. */ $text = _nx( 'Enabled (%s)', 'Enabled (%s)', $count, 'themes' ); break; case 'disabled': /* translators: %s: Number of themes. */ $text = _nx( 'Disabled (%s)', 'Disabled (%s)', $count, 'themes' ); break; case 'upgrade': /* translators: %s: Number of themes. */ $text = _nx( 'Update Available (%s)', 'Update Available (%s)', $count, 'themes' ); break; case 'broken': /* translators: %s: Number of themes. */ $text = _nx( 'Broken (%s)', 'Broken (%s)', $count, 'themes' ); break; case 'auto-update-enabled': /* translators: %s: Number of themes. */ $text = _n( 'Auto-updates Enabled (%s)', 'Auto-updates Enabled (%s)', $count ); break; case 'auto-update-disabled': /* translators: %s: Number of themes. */ $text = _n( 'Auto-updates Disabled (%s)', 'Auto-updates Disabled (%s)', $count ); break; } if ( $this->is_site_themes ) { $url = 'site-themes.php?id=' . $this->site_id; } else { $url = 'themes.php'; } if ( 'search' !== $type ) { $status_links[ $type ] = array( 'url' => esc_url( add_query_arg( 'theme_status', $type, $url ) ), '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 ( 'enabled' !== $status ) { $actions['enable-selected'] = $this->is_site_themes ? __( 'Enable' ) : __( 'Network Enable' ); } if ( 'disabled' !== $status ) { $actions['disable-selected'] = $this->is_site_themes ? __( 'Disable' ) : __( 'Network Disable' ); } if ( ! $this->is_site_themes ) { if ( current_user_can( 'update_themes' ) ) { $actions['update-selected'] = __( 'Update' ); } if ( current_user_can( 'delete_themes' ) ) { $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; } /** */ public function display_rows() { foreach ( $this->items as $theme ) { $this->single_row( $theme ); } } /** * Handles the checkbox column output. * * @since 4.3.0 * @since 5.9.0 Renamed `$theme` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_Theme $item The current WP_Theme object. */ public function column_cb( $item ) { // Restores the more descriptive, specific name for use within this method. $theme = $item; $checkbox_id = 'checkbox_' . md5( $theme->get( 'Name' ) ); ?> is_site_themes ) { $url = "site-themes.php?id={$this->site_id}&"; $allowed = $theme->is_allowed( 'site', $this->site_id ); } else { $url = 'themes.php?'; $allowed = $theme->is_allowed( 'network' ); } // Pre-order. $actions = array( 'enable' => '', 'disable' => '', 'delete' => '', ); $stylesheet = $theme->get_stylesheet(); $theme_key = urlencode( $stylesheet ); if ( ! $allowed ) { if ( ! $theme->errors() ) { $url = add_query_arg( array( 'action' => 'enable', 'theme' => $theme_key, 'paged' => $page, 's' => $s, ), $url ); if ( $this->is_site_themes ) { /* translators: %s: Theme name. */ $aria_label = sprintf( __( 'Enable %s' ), $theme->display( 'Name' ) ); } else { /* translators: %s: Theme name. */ $aria_label = sprintf( __( 'Network Enable %s' ), $theme->display( 'Name' ) ); } $actions['enable'] = sprintf( '%s', esc_url( wp_nonce_url( $url, 'enable-theme_' . $stylesheet ) ), esc_attr( $aria_label ), ( $this->is_site_themes ? __( 'Enable' ) : __( 'Network Enable' ) ) ); } } else { $url = add_query_arg( array( 'action' => 'disable', 'theme' => $theme_key, 'paged' => $page, 's' => $s, ), $url ); if ( $this->is_site_themes ) { /* translators: %s: Theme name. */ $aria_label = sprintf( __( 'Disable %s' ), $theme->display( 'Name' ) ); } else { /* translators: %s: Theme name. */ $aria_label = sprintf( __( 'Network Disable %s' ), $theme->display( 'Name' ) ); } $actions['disable'] = sprintf( '%s', esc_url( wp_nonce_url( $url, 'disable-theme_' . $stylesheet ) ), esc_attr( $aria_label ), ( $this->is_site_themes ? __( 'Disable' ) : __( 'Network Disable' ) ) ); } if ( ! $allowed && ! $this->is_site_themes && current_user_can( 'delete_themes' ) && get_option( 'stylesheet' ) !== $stylesheet && get_option( 'template' ) !== $stylesheet ) { $url = add_query_arg( array( 'action' => 'delete-selected', 'checked[]' => $theme_key, 'theme_status' => $context, 'paged' => $page, 's' => $s, ), 'themes.php' ); /* translators: %s: Theme name. */ $aria_label = sprintf( _x( 'Delete %s', 'theme' ), $theme->display( 'Name' ) ); $actions['delete'] = sprintf( '%s', esc_url( wp_nonce_url( $url, 'bulk-themes' ) ), esc_attr( $aria_label ), __( 'Delete' ) ); } /** * Filters the action links displayed for each theme in the Multisite * themes list table. * * The action links displayed are determined by the theme's status, and * which Multisite themes list table is being displayed - the Network * themes list table (themes.php), which displays all installed themes, * or the Site themes list table (site-themes.php), which displays the * non-network enabled themes when editing a site in the Network admin. * * The default action links for the Network themes list table include * 'Network Enable', 'Network Disable', and 'Delete'. * * The default action links for the Site themes list table include * 'Enable', and 'Disable'. * * @since 2.8.0 * * @param string[] $actions An array of action links. * @param WP_Theme $theme The current WP_Theme object. * @param string $context Status of the theme, one of 'all', 'enabled', or 'disabled'. */ $actions = apply_filters( 'theme_action_links', array_filter( $actions ), $theme, $context ); /** * Filters the action links of a specific theme in the Multisite themes * list table. * * The dynamic portion of the hook name, `$stylesheet`, refers to the * directory name of the theme, which in most cases is synonymous * with the template name. * * @since 3.1.0 * * @param string[] $actions An array of action links. * @param WP_Theme $theme The current WP_Theme object. * @param string $context Status of the theme, one of 'all', 'enabled', or 'disabled'. */ $actions = apply_filters( "theme_action_links_{$stylesheet}", $actions, $theme, $context ); echo $this->row_actions( $actions, true ); } /** * Handles the description column output. * * @since 4.3.0 * * @global string $status * @global array $totals * * @param WP_Theme $theme The current WP_Theme object. */ public function column_description( $theme ) { global $status, $totals; if ( $theme->errors() ) { $pre = 'broken' === $status ? __( 'Broken Theme:' ) . ' ' : ''; echo '

' . $pre . $theme->errors()->get_error_message() . '

'; } if ( $this->is_site_themes ) { $allowed = $theme->is_allowed( 'site', $this->site_id ); } else { $allowed = $theme->is_allowed( 'network' ); } $class = ! $allowed ? 'inactive' : 'active'; if ( ! empty( $totals['upgrade'] ) && ! empty( $theme->update ) ) { $class .= ' update'; } echo "

" . $theme->display( 'Description' ) . "

"; $stylesheet = $theme->get_stylesheet(); $theme_meta = array(); if ( $theme->get( 'Version' ) ) { /* translators: %s: Theme version. */ $theme_meta[] = sprintf( __( 'Version %s' ), $theme->display( 'Version' ) ); } /* translators: %s: Theme author. */ $theme_meta[] = sprintf( __( 'By %s' ), $theme->display( 'Author' ) ); if ( $theme->get( 'ThemeURI' ) ) { /* translators: %s: Theme name. */ $aria_label = sprintf( __( 'Visit theme site for %s' ), $theme->display( 'Name' ) ); $theme_meta[] = sprintf( '%s', $theme->display( 'ThemeURI' ), esc_attr( $aria_label ), __( 'Visit Theme Site' ) ); } if ( $theme->parent() ) { $theme_meta[] = sprintf( /* translators: %s: Theme name. */ __( 'Child theme of %s' ), '' . $theme->parent()->display( 'Name' ) . '' ); } /** * Filters the array of row meta for each theme in the Multisite themes * list table. * * @since 3.1.0 * * @param string[] $theme_meta An array of the theme's metadata, including * the version, author, and theme URI. * @param string $stylesheet Directory name of the theme. * @param WP_Theme $theme WP_Theme object. * @param string $status Status of the theme. */ $theme_meta = apply_filters( 'theme_row_meta', $theme_meta, $stylesheet, $theme, $status ); echo implode( ' | ', $theme_meta ); echo '
'; } /** * Handles the auto-updates column output. * * @since 5.5.0 * * @global string $status * @global int $page * * @param WP_Theme $theme The current WP_Theme object. */ public function column_autoupdates( $theme ) { global $status, $page; static $auto_updates, $available_updates; if ( ! $auto_updates ) { $auto_updates = (array) get_site_option( 'auto_update_themes', array() ); } if ( ! $available_updates ) { $available_updates = get_site_transient( 'update_themes' ); } $stylesheet = $theme->get_stylesheet(); if ( isset( $theme->auto_update_forced ) ) { if ( $theme->auto_update_forced ) { // Forced on. $text = __( 'Auto-updates enabled' ); } else { $text = __( 'Auto-updates disabled' ); } $action = 'unavailable'; $time_class = ' hidden'; } elseif ( empty( $theme->update_supported ) ) { $text = ''; $action = 'unavailable'; $time_class = ' hidden'; } elseif ( in_array( $stylesheet, $auto_updates, true ) ) { $text = __( 'Disable auto-updates' ); $action = 'disable'; $time_class = ''; } else { $text = __( 'Enable auto-updates' ); $action = 'enable'; $time_class = ' hidden'; } $query_args = array( 'action' => "{$action}-auto-update", 'theme' => $stylesheet, 'paged' => $page, 'theme_status' => $status, ); $url = add_query_arg( $query_args, 'themes.php' ); if ( 'unavailable' === $action ) { $html[] = '' . $text . ''; } else { $html[] = sprintf( '', wp_nonce_url( $url, 'updates' ), $action ); $html[] = ''; $html[] = '' . $text . ''; $html[] = ''; } if ( isset( $available_updates->response[ $stylesheet ] ) ) { $html[] = sprintf( '
%s
', $time_class, wp_get_auto_update_message() ); } $html = implode( '', $html ); /** * Filters the HTML of the auto-updates setting for each theme in the Themes list table. * * @since 5.5.0 * * @param string $html The HTML for theme's auto-update setting, including * toggle auto-update action link and time to next update. * @param string $stylesheet Directory name of the theme. * @param WP_Theme $theme WP_Theme object. */ echo apply_filters( 'theme_auto_update_setting_html', $html, $stylesheet, $theme ); wp_admin_notice( '', array( 'type' => 'error', 'additional_classes' => array( 'notice-alt', 'inline', 'hidden' ), ) ); } /** * Handles default column output. * * @since 4.3.0 * @since 5.9.0 Renamed `$theme` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_Theme $item The current WP_Theme 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. $theme = $item; $stylesheet = $theme->get_stylesheet(); /** * Fires inside each custom column of the Multisite themes list table. * * @since 3.1.0 * * @param string $column_name Name of the column. * @param string $stylesheet Directory name of the theme. * @param WP_Theme $theme Current WP_Theme object. */ do_action( 'manage_themes_custom_column', $column_name, $stylesheet, $theme ); } /** * Handles the output for a single table row. * * @since 4.3.0 * * @param WP_Theme $item The current WP_Theme object. */ public function single_row_columns( $item ) { list( $columns, $hidden, $sortable, $primary ) = $this->get_column_info(); foreach ( $columns as $column_name => $column_display_name ) { $extra_classes = ''; if ( in_array( $column_name, $hidden, true ) ) { $extra_classes .= ' hidden'; } switch ( $column_name ) { case 'cb': echo ''; $this->column_cb( $item ); echo ''; break; case 'name': $active_theme_label = ''; /* The presence of the site_id property means that this is a subsite view and a label for the active theme needs to be added */ if ( ! empty( $this->site_id ) ) { $stylesheet = get_blog_option( $this->site_id, 'stylesheet' ); $template = get_blog_option( $this->site_id, 'template' ); /* Add a label for the active template */ if ( $item->get_template() === $template ) { $active_theme_label = ' — ' . __( 'Active Theme' ); } /* In case this is a child theme, label it properly */ if ( $stylesheet !== $template && $item->get_stylesheet() === $stylesheet ) { $active_theme_label = ' — ' . __( 'Active Child Theme' ); } } echo "" . $item->display( 'Name' ) . $active_theme_label . ''; $this->column_name( $item ); echo ''; break; case 'description': echo ""; $this->column_description( $item ); echo ''; break; case 'auto-updates': echo ""; $this->column_autoupdates( $item ); echo ''; break; default: echo ""; $this->column_default( $item, $column_name ); echo ''; break; } } } /** * @global string $status * @global array $totals * * @param WP_Theme $theme */ public function single_row( $theme ) { global $status, $totals; if ( $this->is_site_themes ) { $allowed = $theme->is_allowed( 'site', $this->site_id ); } else { $allowed = $theme->is_allowed( 'network' ); } $stylesheet = $theme->get_stylesheet(); $class = ! $allowed ? 'inactive' : 'active'; if ( ! empty( $totals['upgrade'] ) && ! empty( $theme->update ) ) { $class .= ' update'; } printf( '', esc_attr( $class ), esc_attr( $stylesheet ) ); $this->single_row_columns( $theme ); echo ''; if ( $this->is_site_themes ) { remove_action( "after_theme_row_$stylesheet", 'wp_theme_update_row' ); } /** * Fires after each row in the Multisite themes list table. * * @since 3.1.0 * * @param string $stylesheet Directory name of the theme. * @param WP_Theme $theme Current WP_Theme object. * @param string $status Status of the theme. */ do_action( 'after_theme_row', $stylesheet, $theme, $status ); /** * Fires after each specific row in the Multisite themes list table. * * The dynamic portion of the hook name, `$stylesheet`, refers to the * directory name of the theme, most often synonymous with the template * name of the theme. * * @since 3.5.0 * * @param string $stylesheet Directory name of the theme. * @param WP_Theme $theme Current WP_Theme object. * @param string $status Status of the theme. */ do_action( "after_theme_row_{$stylesheet}", $stylesheet, $theme, $status ); } } class-walker-nav-menu-checklist.php000064400000012774146715570560013373 0ustar00db_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"; } /** * 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 . '
  • '; $output .= ''; // Menu item hidden fields. $output .= ''; $output .= ''; $output .= ''; $output .= ''; $output .= ''; $output .= ''; $output .= ''; $output .= ''; $output .= ''; $output .= ''; } } class-wp-privacy-policy-content.php000064400000100002146715570560013437 0ustar00 $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 ); } 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 ); ?>

    ' . __( 'Suggested text:' ) . ' '; $content = ''; $strings = array(); // Start of the suggested privacy policy text. if ( $description ) { $strings[] = '
    '; } /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'Who we are' ) . '

    '; if ( $description ) { /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( '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.' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( '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.' ) . '

    '; } else { /* translators: Default privacy policy text. %s: Site URL. */ $strings[] = '

    ' . $suggested_text . sprintf( __( 'Our website address is: %s.' ), get_bloginfo( 'url', 'display' ) ) . '

    '; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'What personal data we collect and why we collect it' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( '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.' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'You should also note any collection and retention of sensitive personal data, such as data concerning health.' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( '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.' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( '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.' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( '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.' ) . '

    '; } /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'Comments' ) . '

    '; if ( $description ) { /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'In this subsection you should note what information is captured through comments. We have noted the data which WordPress collects by default.' ) . '

    '; } else { /* translators: Default privacy policy text. */ $strings[] = '

    ' . $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.' ) . '

    '; /* translators: Default privacy policy text. */ $strings[] = '

    ' . __( '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.' ) . '

    '; } /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'Media' ) . '

    '; if ( $description ) { /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( '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.' ) . '

    '; } else { /* translators: Default privacy policy text. */ $strings[] = '

    ' . $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.' ) . '

    '; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'Contact forms' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( '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.' ) . '

    '; } /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'Cookies' ) . '

    '; if ( $description ) { /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( '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.' ) . '

    '; } else { /* translators: Default privacy policy text. */ $strings[] = '

    ' . $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.' ) . '

    '; /* translators: Default privacy policy text. */ $strings[] = '

    ' . __( '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.' ) . '

    '; /* translators: Default privacy policy text. */ $strings[] = '

    ' . __( '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.' ) . '

    '; /* translators: Default privacy policy text. */ $strings[] = '

    ' . __( '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.' ) . '

    '; } if ( ! $description ) { /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'Embedded content from other websites' ) . '

    '; /* translators: Default privacy policy text. */ $strings[] = '

    ' . $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.' ) . '

    '; /* translators: Default privacy policy text. */ $strings[] = '

    ' . __( '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.' ) . '

    '; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'Analytics' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( '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.' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( '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.' ) . '

    '; } /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'Who we share your data with' ) . '

    '; if ( $description ) { /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( '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.' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'By default WordPress does not share any personal data with anyone.' ) . '

    '; } else { /* translators: Default privacy policy text. */ $strings[] = '

    ' . $suggested_text . __( 'If you request a password reset, your IP address will be included in the reset email.' ) . '

    '; } /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'How long we retain your data' ) . '

    '; if ( $description ) { /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( '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.' ) . '

    '; } else { /* translators: Default privacy policy text. */ $strings[] = '

    ' . $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.' ) . '

    '; /* translators: Default privacy policy text. */ $strings[] = '

    ' . __( '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.' ) . '

    '; } /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'What rights you have over your data' ) . '

    '; if ( $description ) { /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'In this section you should explain what rights your users have over their data and how they can invoke those rights.' ) . '

    '; } else { /* translators: Default privacy policy text. */ $strings[] = '

    ' . $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.' ) . '

    '; } /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'Where your data is sent' ) . '

    '; if ( $description ) { /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( '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.' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( '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.' ) . '

    '; } else { /* translators: Default privacy policy text. */ $strings[] = '

    ' . $suggested_text . __( 'Visitor comments may be checked through an automated spam detection service.' ) . '

    '; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'Contact information' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( '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 ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'Additional information' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( '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.' ) . '

    '; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'How we protect your data' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( '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.' ) . '

    '; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'What data breach procedures we have in place' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( '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 ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'What third parties we receive data from' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( '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 ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'What automated decision making and/or profiling we do with user data' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( '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 ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'Industry regulatory disclosure requirements' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( '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, '

    ' ) ) { $strings[ $key ] = "\n" . $string . "\n\n"; } if ( str_starts_with( $string, '

    \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-language-pack-upgrader.php000064400000036311146715570560012712 0ustar00is_vcs_checkout( WP_CONTENT_DIR ) ) { return; } foreach ( $language_updates as $key => $language_update ) { $update = ! empty( $language_update->autoupdate ); /** * Filters whether to asynchronously update translation for core, a plugin, or a theme. * * @since 4.0.0 * * @param bool $update Whether to update. * @param object $language_update The update offer. */ $update = apply_filters( 'async_update_translation', $update, $language_update ); if ( ! $update ) { unset( $language_updates[ $key ] ); } } if ( empty( $language_updates ) ) { return; } // Re-use the automatic upgrader skin if the parent upgrader is using it. if ( $upgrader && $upgrader->skin instanceof Automatic_Upgrader_Skin ) { $skin = $upgrader->skin; } else { $skin = new Language_Pack_Upgrader_Skin( array( 'skip_header_footer' => true, ) ); } $lp_upgrader = new Language_Pack_Upgrader( $skin ); $lp_upgrader->bulk_upgrade( $language_updates ); } /** * Initializes the upgrade strings. * * @since 3.7.0 */ public function upgrade_strings() { $this->strings['starting_upgrade'] = __( 'Some of your translations need updating. Sit tight for a few more seconds while they are updated as well.' ); $this->strings['up_to_date'] = __( 'Your translations are all up to date.' ); $this->strings['no_package'] = __( 'Update package not available.' ); /* translators: %s: Package URL. */ $this->strings['downloading_package'] = sprintf( __( 'Downloading translation from %s…' ), '%s' ); $this->strings['unpack_package'] = __( 'Unpacking the update…' ); $this->strings['process_failed'] = __( 'Translation update failed.' ); $this->strings['process_success'] = __( 'Translation updated successfully.' ); $this->strings['remove_old'] = __( 'Removing the old version of the translation…' ); $this->strings['remove_old_failed'] = __( 'Could not remove the old translation.' ); } /** * Upgrades a language pack. * * @since 3.7.0 * * @param string|false $update Optional. Whether an update offer is available. Default false. * @param array $args Optional. Other optional arguments, see * Language_Pack_Upgrader::bulk_upgrade(). Default empty array. * @return array|bool|WP_Error The result of the upgrade, or a WP_Error object instead. */ public function upgrade( $update = false, $args = array() ) { if ( $update ) { $update = array( $update ); } $results = $this->bulk_upgrade( $update, $args ); if ( ! is_array( $results ) ) { return $results; } return $results[0]; } /** * Upgrades several language packs at once. * * @since 3.7.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * * @param object[] $language_updates Optional. Array of language packs to update. See {@see wp_get_translation_updates()}. * Default empty array. * @param array $args { * Other arguments for upgrading multiple language packs. Default empty array. * * @type bool $clear_update_cache Whether to clear the update cache when done. * Default true. * } * @return array|bool|WP_Error Will return an array of results, or true if there are no updates, * false or WP_Error for initial errors. */ public function bulk_upgrade( $language_updates = array(), $args = array() ) { global $wp_filesystem; $defaults = array( 'clear_update_cache' => true, ); $parsed_args = wp_parse_args( $args, $defaults ); $this->init(); $this->upgrade_strings(); if ( ! $language_updates ) { $language_updates = wp_get_translation_updates(); } if ( empty( $language_updates ) ) { $this->skin->header(); $this->skin->set_result( true ); $this->skin->feedback( 'up_to_date' ); $this->skin->bulk_footer(); $this->skin->footer(); return true; } if ( 'upgrader_process_complete' === current_filter() ) { $this->skin->feedback( 'starting_upgrade' ); } // Remove any existing upgrade filters from the plugin/theme upgraders #WP29425 & #WP29230. remove_all_filters( 'upgrader_pre_install' ); remove_all_filters( 'upgrader_clear_destination' ); remove_all_filters( 'upgrader_post_install' ); remove_all_filters( 'upgrader_source_selection' ); add_filter( 'upgrader_source_selection', array( $this, 'check_package' ), 10, 2 ); $this->skin->header(); // Connect to the filesystem first. $res = $this->fs_connect( array( WP_CONTENT_DIR, WP_LANG_DIR ) ); if ( ! $res ) { $this->skin->footer(); return false; } $results = array(); $this->update_count = count( $language_updates ); $this->update_current = 0; /* * The filesystem's mkdir() is not recursive. Make sure WP_LANG_DIR exists, * as we then may need to create a /plugins or /themes directory inside of it. */ $remote_destination = $wp_filesystem->find_folder( WP_LANG_DIR ); if ( ! $wp_filesystem->exists( $remote_destination ) ) { if ( ! $wp_filesystem->mkdir( $remote_destination, FS_CHMOD_DIR ) ) { return new WP_Error( 'mkdir_failed_lang_dir', $this->strings['mkdir_failed'], $remote_destination ); } } $language_updates_results = array(); foreach ( $language_updates as $language_update ) { $this->skin->language_update = $language_update; $destination = WP_LANG_DIR; if ( 'plugin' === $language_update->type ) { $destination .= '/plugins'; } elseif ( 'theme' === $language_update->type ) { $destination .= '/themes'; } ++$this->update_current; $options = array( 'package' => $language_update->package, 'destination' => $destination, 'clear_destination' => true, 'abort_if_destination_exists' => false, // We expect the destination to exist. 'clear_working' => true, 'is_multi' => true, 'hook_extra' => array( 'language_update_type' => $language_update->type, 'language_update' => $language_update, ), ); $result = $this->run( $options ); $results[] = $this->result; // Prevent credentials auth screen from displaying multiple times. if ( false === $result ) { break; } $language_updates_results[] = array( 'language' => $language_update->language, 'type' => $language_update->type, 'slug' => isset( $language_update->slug ) ? $language_update->slug : 'default', 'version' => $language_update->version, ); } // Remove upgrade hooks which are not required for translation updates. remove_action( 'upgrader_process_complete', array( 'Language_Pack_Upgrader', 'async_upgrade' ), 20 ); remove_action( 'upgrader_process_complete', 'wp_version_check' ); remove_action( 'upgrader_process_complete', 'wp_update_plugins' ); remove_action( 'upgrader_process_complete', 'wp_update_themes' ); /** This action is documented in wp-admin/includes/class-wp-upgrader.php */ do_action( 'upgrader_process_complete', $this, array( 'action' => 'update', 'type' => 'translation', 'bulk' => true, 'translations' => $language_updates_results, ) ); // Re-add upgrade hooks. add_action( 'upgrader_process_complete', array( 'Language_Pack_Upgrader', 'async_upgrade' ), 20 ); add_action( 'upgrader_process_complete', 'wp_version_check', 10, 0 ); add_action( 'upgrader_process_complete', 'wp_update_plugins', 10, 0 ); add_action( 'upgrader_process_complete', 'wp_update_themes', 10, 0 ); $this->skin->bulk_footer(); $this->skin->footer(); // Clean up our hooks, in case something else does an upgrade on this connection. remove_filter( 'upgrader_source_selection', array( $this, 'check_package' ) ); if ( $parsed_args['clear_update_cache'] ) { wp_clean_update_cache(); } return $results; } /** * Checks that the package source contains .mo and .po files. * * Hooked to the {@see 'upgrader_source_selection'} filter by * Language_Pack_Upgrader::bulk_upgrade(). * * @since 3.7.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * * @param string|WP_Error $source The path to the downloaded package source. * @param string $remote_source Remote file source location. * @return string|WP_Error The source as passed, or a WP_Error object on failure. */ public function check_package( $source, $remote_source ) { global $wp_filesystem; if ( is_wp_error( $source ) ) { return $source; } // Check that the folder contains a valid language. $files = $wp_filesystem->dirlist( $remote_source ); // Check to see if the expected files exist in the folder. $po = false; $mo = false; $php = false; foreach ( (array) $files as $file => $filedata ) { if ( str_ends_with( $file, '.po' ) ) { $po = true; } elseif ( str_ends_with( $file, '.mo' ) ) { $mo = true; } elseif ( str_ends_with( $file, '.l10n.php' ) ) { $php = true; } } if ( $php ) { return $source; } if ( ! $mo || ! $po ) { return new WP_Error( 'incompatible_archive_pomo', $this->strings['incompatible_archive'], sprintf( /* translators: 1: .po, 2: .mo, 3: .l10n.php */ __( 'The language pack is missing either the %1$s, %2$s, or %3$s files.' ), '.po', '.mo', '.l10n.php' ) ); } return $source; } /** * Gets the name of an item being updated. * * @since 3.7.0 * * @param object $update The data for an update. * @return string The name of the item being updated. */ public function get_name_for_update( $update ) { switch ( $update->type ) { case 'core': return 'WordPress'; // Not translated. case 'theme': $theme = wp_get_theme( $update->slug ); if ( $theme->exists() ) { return $theme->Get( 'Name' ); } break; case 'plugin': $plugin_data = get_plugins( '/' . $update->slug ); $plugin_data = reset( $plugin_data ); if ( $plugin_data ) { return $plugin_data['Name']; } break; } return ''; } /** * Clears existing translations where this item is going to be installed into. * * @since 5.1.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress 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; $language_update = $this->skin->language_update; $language_directory = WP_LANG_DIR . '/'; // Local path for use with glob(). if ( 'core' === $language_update->type ) { $files = array( $remote_destination . $language_update->language . '.po', $remote_destination . $language_update->language . '.mo', $remote_destination . $language_update->language . '.l10n.php', $remote_destination . 'admin-' . $language_update->language . '.po', $remote_destination . 'admin-' . $language_update->language . '.mo', $remote_destination . 'admin-' . $language_update->language . '.l10n.php', $remote_destination . 'admin-network-' . $language_update->language . '.po', $remote_destination . 'admin-network-' . $language_update->language . '.mo', $remote_destination . 'admin-network-' . $language_update->language . '.l10n.php', $remote_destination . 'continents-cities-' . $language_update->language . '.po', $remote_destination . 'continents-cities-' . $language_update->language . '.mo', $remote_destination . 'continents-cities-' . $language_update->language . '.l10n.php', ); $json_translation_files = glob( $language_directory . $language_update->language . '-*.json' ); if ( $json_translation_files ) { foreach ( $json_translation_files as $json_translation_file ) { $files[] = str_replace( $language_directory, $remote_destination, $json_translation_file ); } } } else { $files = array( $remote_destination . $language_update->slug . '-' . $language_update->language . '.po', $remote_destination . $language_update->slug . '-' . $language_update->language . '.mo', $remote_destination . $language_update->slug . '-' . $language_update->language . '.l10n.php', ); $language_directory = $language_directory . $language_update->type . 's/'; $json_translation_files = glob( $language_directory . $language_update->slug . '-' . $language_update->language . '-*.json' ); if ( $json_translation_files ) { foreach ( $json_translation_files as $json_translation_file ) { $files[] = str_replace( $language_directory, $remote_destination, $json_translation_file ); } } } $files = array_filter( $files, array( $wp_filesystem, 'exists' ) ); // No files to delete. if ( ! $files ) { return true; } // Check all files are writable before attempting to clear the destination. $unwritable_files = array(); // Check writability. foreach ( $files as $file ) { if ( ! $wp_filesystem->is_writable( $file ) ) { // Attempt to alter permissions to allow writes and try again. $wp_filesystem->chmod( $file, FS_CHMOD_FILE ); if ( ! $wp_filesystem->is_writable( $file ) ) { $unwritable_files[] = $file; } } } if ( ! empty( $unwritable_files ) ) { return new WP_Error( 'files_not_writable', $this->strings['files_not_writable'], implode( ', ', $unwritable_files ) ); } foreach ( $files as $file ) { if ( ! $wp_filesystem->delete( $file ) ) { return new WP_Error( 'remove_old_failed', $this->strings['remove_old_failed'] ); } } return true; } } comment.php000064400000013751146715570560006746 0ustar00get_var( $wpdb->prepare( "SELECT comment_post_ID FROM $wpdb->comments WHERE comment_author = %s AND $date_field = %s", stripslashes( $comment_author ), stripslashes( $comment_date ) ) ); } /** * Updates a comment with values provided in $_POST. * * @since 2.0.0 * @since 5.5.0 A return value was added. * * @return int|WP_Error The value 1 if the comment was updated, 0 if not updated. * A WP_Error object on failure. */ function edit_comment() { if ( ! current_user_can( 'edit_comment', (int) $_POST['comment_ID'] ) ) { wp_die( __( 'Sorry, you are not allowed to edit comments on this post.' ) ); } if ( isset( $_POST['newcomment_author'] ) ) { $_POST['comment_author'] = $_POST['newcomment_author']; } if ( isset( $_POST['newcomment_author_email'] ) ) { $_POST['comment_author_email'] = $_POST['newcomment_author_email']; } if ( isset( $_POST['newcomment_author_url'] ) ) { $_POST['comment_author_url'] = $_POST['newcomment_author_url']; } if ( isset( $_POST['comment_status'] ) ) { $_POST['comment_approved'] = $_POST['comment_status']; } if ( isset( $_POST['content'] ) ) { $_POST['comment_content'] = $_POST['content']; } if ( isset( $_POST['comment_ID'] ) ) { $_POST['comment_ID'] = (int) $_POST['comment_ID']; } foreach ( array( 'aa', 'mm', 'jj', 'hh', 'mn' ) as $timeunit ) { if ( ! empty( $_POST[ 'hidden_' . $timeunit ] ) && $_POST[ 'hidden_' . $timeunit ] !== $_POST[ $timeunit ] ) { $_POST['edit_date'] = '1'; break; } } if ( ! empty( $_POST['edit_date'] ) ) { $aa = $_POST['aa']; $mm = $_POST['mm']; $jj = $_POST['jj']; $hh = $_POST['hh']; $mn = $_POST['mn']; $ss = $_POST['ss']; $jj = ( $jj > 31 ) ? 31 : $jj; $hh = ( $hh > 23 ) ? $hh - 24 : $hh; $mn = ( $mn > 59 ) ? $mn - 60 : $mn; $ss = ( $ss > 59 ) ? $ss - 60 : $ss; $_POST['comment_date'] = "$aa-$mm-$jj $hh:$mn:$ss"; } return wp_update_comment( $_POST, true ); } /** * Returns a WP_Comment object based on comment ID. * * @since 2.0.0 * * @param int $id ID of comment to retrieve. * @return WP_Comment|false Comment if found. False on failure. */ function get_comment_to_edit( $id ) { $comment = get_comment( $id ); if ( ! $comment ) { return false; } $comment->comment_ID = (int) $comment->comment_ID; $comment->comment_post_ID = (int) $comment->comment_post_ID; $comment->comment_content = format_to_edit( $comment->comment_content ); /** * Filters the comment content before editing. * * @since 2.0.0 * * @param string $comment_content Comment content. */ $comment->comment_content = apply_filters( 'comment_edit_pre', $comment->comment_content ); $comment->comment_author = format_to_edit( $comment->comment_author ); $comment->comment_author_email = format_to_edit( $comment->comment_author_email ); $comment->comment_author_url = format_to_edit( $comment->comment_author_url ); $comment->comment_author_url = esc_url( $comment->comment_author_url ); return $comment; } /** * Gets the number of pending comments on a post or posts. * * @since 2.3.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param int|int[] $post_id Either a single Post ID or an array of Post IDs * @return int|int[] Either a single Posts pending comments as an int or an array of ints keyed on the Post IDs */ function get_pending_comments_num( $post_id ) { global $wpdb; $single = false; if ( ! is_array( $post_id ) ) { $post_id_array = (array) $post_id; $single = true; } else { $post_id_array = $post_id; } $post_id_array = array_map( 'intval', $post_id_array ); $post_id_in = "'" . implode( "', '", $post_id_array ) . "'"; $pending = $wpdb->get_results( "SELECT comment_post_ID, COUNT(comment_ID) as num_comments FROM $wpdb->comments WHERE comment_post_ID IN ( $post_id_in ) AND comment_approved = '0' GROUP BY comment_post_ID", ARRAY_A ); if ( $single ) { if ( empty( $pending ) ) { return 0; } else { return absint( $pending[0]['num_comments'] ); } } $pending_keyed = array(); // Default to zero pending for all posts in request. foreach ( $post_id_array as $id ) { $pending_keyed[ $id ] = 0; } if ( ! empty( $pending ) ) { foreach ( $pending as $pend ) { $pending_keyed[ $pend['comment_post_ID'] ] = absint( $pend['num_comments'] ); } } return $pending_keyed; } /** * Adds avatars to relevant places in admin. * * @since 2.5.0 * * @param string $name User name. * @return string Avatar with the user name. */ function floated_admin_avatar( $name ) { $avatar = get_avatar( get_comment(), 32, 'mystery' ); return "$avatar $name"; } /** * Enqueues comment shortcuts jQuery script. * * @since 2.7.0 */ function enqueue_comment_hotkeys_js() { if ( 'true' === get_user_option( 'comment_shortcuts' ) ) { wp_enqueue_script( 'jquery-table-hotkeys' ); } } /** * Displays error message at bottom of comments. * * @param string $msg Error Message. Assumed to contain HTML and be sanitized. */ function comment_footer_die( $msg ) { echo "

    $msg

    "; require_once ABSPATH . 'wp-admin/admin-footer.php'; die; } bookmark.php000064400000026537146715570560007117 0ustar00' . __( 'You need a higher level of permission.' ) . '

    ' . '

    ' . __( 'Sorry, you are not allowed to edit the links for this site.' ) . '

    ', 403 ); } $_POST['link_url'] = esc_url( $_POST['link_url'] ); $_POST['link_name'] = esc_html( $_POST['link_name'] ); $_POST['link_image'] = esc_html( $_POST['link_image'] ); $_POST['link_rss'] = esc_url( $_POST['link_rss'] ); if ( ! isset( $_POST['link_visible'] ) || 'N' !== $_POST['link_visible'] ) { $_POST['link_visible'] = 'Y'; } if ( ! empty( $link_id ) ) { $_POST['link_id'] = $link_id; return wp_update_link( $_POST ); } else { return wp_insert_link( $_POST ); } } /** * Retrieves the default link for editing. * * @since 2.0.0 * * @return stdClass Default link object. */ function get_default_link_to_edit() { $link = new stdClass(); if ( isset( $_GET['linkurl'] ) ) { $link->link_url = esc_url( wp_unslash( $_GET['linkurl'] ) ); } else { $link->link_url = ''; } if ( isset( $_GET['name'] ) ) { $link->link_name = esc_attr( wp_unslash( $_GET['name'] ) ); } else { $link->link_name = ''; } $link->link_visible = 'Y'; return $link; } /** * Deletes a specified link from the database. * * @since 2.0.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param int $link_id ID of the link to delete. * @return true Always true. */ function wp_delete_link( $link_id ) { global $wpdb; /** * Fires before a link is deleted. * * @since 2.0.0 * * @param int $link_id ID of the link to delete. */ do_action( 'delete_link', $link_id ); wp_delete_object_term_relationships( $link_id, 'link_category' ); $wpdb->delete( $wpdb->links, array( 'link_id' => $link_id ) ); /** * Fires after a link has been deleted. * * @since 2.2.0 * * @param int $link_id ID of the deleted link. */ do_action( 'deleted_link', $link_id ); clean_bookmark_cache( $link_id ); return true; } /** * Retrieves the link category IDs associated with the link specified. * * @since 2.1.0 * * @param int $link_id Link ID to look up. * @return int[] The IDs of the requested link's categories. */ function wp_get_link_cats( $link_id = 0 ) { $cats = wp_get_object_terms( $link_id, 'link_category', array( 'fields' => 'ids' ) ); return array_unique( $cats ); } /** * Retrieves link data based on its ID. * * @since 2.0.0 * * @param int|stdClass $link Link ID or object to retrieve. * @return object Link object for editing. */ function get_link_to_edit( $link ) { return get_bookmark( $link, OBJECT, 'edit' ); } /** * Inserts a link into the database, or updates an existing link. * * Runs all the necessary sanitizing, provides default values if arguments are missing, * and finally saves the link. * * @since 2.0.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param array $linkdata { * Elements that make up the link to insert. * * @type int $link_id Optional. The ID of the existing link if updating. * @type string $link_url The URL the link points to. * @type string $link_name The title of the link. * @type string $link_image Optional. A URL of an image. * @type string $link_target Optional. The target element for the anchor tag. * @type string $link_description Optional. A short description of the link. * @type string $link_visible Optional. 'Y' means visible, anything else means not. * @type int $link_owner Optional. A user ID. * @type int $link_rating Optional. A rating for the link. * @type string $link_rel Optional. A relationship of the link to you. * @type string $link_notes Optional. An extended description of or notes on the link. * @type string $link_rss Optional. A URL of an associated RSS feed. * @type int $link_category Optional. The term ID of the link category. * If empty, uses default link category. * } * @param bool $wp_error Optional. Whether to return a WP_Error object on failure. Default false. * @return int|WP_Error Value 0 or WP_Error on failure. The link ID on success. */ function wp_insert_link( $linkdata, $wp_error = false ) { global $wpdb; $defaults = array( 'link_id' => 0, 'link_name' => '', 'link_url' => '', 'link_rating' => 0, ); $parsed_args = wp_parse_args( $linkdata, $defaults ); $parsed_args = wp_unslash( sanitize_bookmark( $parsed_args, 'db' ) ); $link_id = $parsed_args['link_id']; $link_name = $parsed_args['link_name']; $link_url = $parsed_args['link_url']; $update = false; if ( ! empty( $link_id ) ) { $update = true; } if ( '' === trim( $link_name ) ) { if ( '' !== trim( $link_url ) ) { $link_name = $link_url; } else { return 0; } } if ( '' === trim( $link_url ) ) { return 0; } $link_rating = ( ! empty( $parsed_args['link_rating'] ) ) ? $parsed_args['link_rating'] : 0; $link_image = ( ! empty( $parsed_args['link_image'] ) ) ? $parsed_args['link_image'] : ''; $link_target = ( ! empty( $parsed_args['link_target'] ) ) ? $parsed_args['link_target'] : ''; $link_visible = ( ! empty( $parsed_args['link_visible'] ) ) ? $parsed_args['link_visible'] : 'Y'; $link_owner = ( ! empty( $parsed_args['link_owner'] ) ) ? $parsed_args['link_owner'] : get_current_user_id(); $link_notes = ( ! empty( $parsed_args['link_notes'] ) ) ? $parsed_args['link_notes'] : ''; $link_description = ( ! empty( $parsed_args['link_description'] ) ) ? $parsed_args['link_description'] : ''; $link_rss = ( ! empty( $parsed_args['link_rss'] ) ) ? $parsed_args['link_rss'] : ''; $link_rel = ( ! empty( $parsed_args['link_rel'] ) ) ? $parsed_args['link_rel'] : ''; $link_category = ( ! empty( $parsed_args['link_category'] ) ) ? $parsed_args['link_category'] : array(); // Make sure we set a valid category. if ( ! is_array( $link_category ) || 0 === count( $link_category ) ) { $link_category = array( get_option( 'default_link_category' ) ); } if ( $update ) { if ( false === $wpdb->update( $wpdb->links, compact( 'link_url', 'link_name', 'link_image', 'link_target', 'link_description', 'link_visible', 'link_owner', 'link_rating', 'link_rel', 'link_notes', 'link_rss' ), compact( 'link_id' ) ) ) { if ( $wp_error ) { return new WP_Error( 'db_update_error', __( 'Could not update link in the database.' ), $wpdb->last_error ); } else { return 0; } } } else { if ( false === $wpdb->insert( $wpdb->links, compact( 'link_url', 'link_name', 'link_image', 'link_target', 'link_description', 'link_visible', 'link_owner', 'link_rating', 'link_rel', 'link_notes', 'link_rss' ) ) ) { if ( $wp_error ) { return new WP_Error( 'db_insert_error', __( 'Could not insert link into the database.' ), $wpdb->last_error ); } else { return 0; } } $link_id = (int) $wpdb->insert_id; } wp_set_link_cats( $link_id, $link_category ); if ( $update ) { /** * Fires after a link was updated in the database. * * @since 2.0.0 * * @param int $link_id ID of the link that was updated. */ do_action( 'edit_link', $link_id ); } else { /** * Fires after a link was added to the database. * * @since 2.0.0 * * @param int $link_id ID of the link that was added. */ do_action( 'add_link', $link_id ); } clean_bookmark_cache( $link_id ); return $link_id; } /** * Updates link with the specified link categories. * * @since 2.1.0 * * @param int $link_id ID of the link to update. * @param int[] $link_categories Array of link category IDs to add the link to. */ function wp_set_link_cats( $link_id = 0, $link_categories = array() ) { // If $link_categories isn't already an array, make it one: if ( ! is_array( $link_categories ) || 0 === count( $link_categories ) ) { $link_categories = array( get_option( 'default_link_category' ) ); } $link_categories = array_map( 'intval', $link_categories ); $link_categories = array_unique( $link_categories ); wp_set_object_terms( $link_id, $link_categories, 'link_category' ); clean_bookmark_cache( $link_id ); } /** * Updates a link in the database. * * @since 2.0.0 * * @param array $linkdata Link data to update. See wp_insert_link() for accepted arguments. * @return int|WP_Error Value 0 or WP_Error on failure. The updated link ID on success. */ function wp_update_link( $linkdata ) { $link_id = (int) $linkdata['link_id']; $link = get_bookmark( $link_id, ARRAY_A ); // Escape data pulled from DB. $link = wp_slash( $link ); // Passed link category list overwrites existing category list if not empty. if ( isset( $linkdata['link_category'] ) && is_array( $linkdata['link_category'] ) && count( $linkdata['link_category'] ) > 0 ) { $link_cats = $linkdata['link_category']; } else { $link_cats = $link['link_category']; } // Merge old and new fields with new fields overwriting old ones. $linkdata = array_merge( $link, $linkdata ); $linkdata['link_category'] = $link_cats; return wp_insert_link( $linkdata ); } /** * Outputs the 'disabled' message for the WordPress Link Manager. * * @since 3.5.0 * @access private * * @global string $pagenow The filename of the current screen. */ function wp_link_manager_disabled_message() { global $pagenow; if ( ! in_array( $pagenow, array( 'link-manager.php', 'link-add.php', 'link.php' ), true ) ) { return; } add_filter( 'pre_option_link_manager_enabled', '__return_true', 100 ); $really_can_manage_links = current_user_can( 'manage_links' ); remove_filter( 'pre_option_link_manager_enabled', '__return_true', 100 ); if ( $really_can_manage_links ) { $plugins = get_plugins(); if ( empty( $plugins['link-manager/link-manager.php'] ) ) { if ( current_user_can( 'install_plugins' ) ) { $install_url = wp_nonce_url( self_admin_url( 'update.php?action=install-plugin&plugin=link-manager' ), 'install-plugin_link-manager' ); wp_die( sprintf( /* translators: %s: A link to install the Link Manager plugin. */ __( 'If you are looking to use the link manager, please install the Link Manager plugin.' ), esc_url( $install_url ) ) ); } } elseif ( is_plugin_inactive( 'link-manager/link-manager.php' ) ) { if ( current_user_can( 'activate_plugins' ) ) { $activate_url = wp_nonce_url( self_admin_url( 'plugins.php?action=activate&plugin=link-manager/link-manager.php' ), 'activate-plugin_link-manager/link-manager.php' ); wp_die( sprintf( /* translators: %s: A link to activate the Link Manager plugin. */ __( 'Please activate the Link Manager plugin to use the link manager.' ), esc_url( $activate_url ) ) ); } } } wp_die( __( 'Sorry, you are not allowed to edit the links for this site.' ) ); } class-bulk-theme-upgrader-skin.php000064400000005144146715570560013212 0ustar00upgrader->strings['skin_before_update_header'] = __( 'Updating Theme %1$s (%2$d/%3$d)' ); } /** * Performs an action before a bulk theme update. * * @since 3.0.0 * * @param string $title */ public function before( $title = '' ) { parent::before( $this->theme_info->display( 'Name' ) ); } /** * Performs an action following a bulk theme update. * * @since 3.0.0 * * @param string $title */ public function after( $title = '' ) { parent::after( $this->theme_info->display( 'Name' ) ); $this->decrement_update_count( 'theme' ); } /** * Displays the footer following the bulk update process. * * @since 3.0.0 */ public function bulk_footer() { parent::bulk_footer(); $update_actions = array( 'themes_page' => sprintf( '%s', self_admin_url( 'themes.php' ), __( 'Go to Themes page' ) ), 'updates_page' => sprintf( '%s', self_admin_url( 'update-core.php' ), __( 'Go to WordPress Updates page' ) ), ); if ( ! current_user_can( 'switch_themes' ) && ! current_user_can( 'edit_theme_options' ) ) { unset( $update_actions['themes_page'] ); } /** * Filters the list of action links available following bulk theme updates. * * @since 3.0.0 * * @param string[] $update_actions Array of theme action links. * @param WP_Theme $theme_info Theme object for the last-updated theme. */ $update_actions = apply_filters( 'update_bulk_theme_complete_actions', $update_actions, $this->theme_info ); if ( ! empty( $update_actions ) ) { $this->feedback( implode( ' | ', (array) $update_actions ) ); } } } ms-admin-filters.php000064400000002420146715570560010446 0ustar00options['context'] = $context; } /* * TODO: Fix up request_filesystem_credentials(), or split it, to allow us to request a no-output version. * This will output a credentials form in event of failure. We don't want that, so just hide with a buffer. */ ob_start(); $result = parent::request_filesystem_credentials( $error, $context, $allow_relaxed_file_ownership ); ob_end_clean(); return $result; } /** * Retrieves the upgrade messages. * * @since 3.7.0 * * @return string[] Messages during an upgrade. */ public function get_upgrade_messages() { return $this->messages; } /** * Stores a message about the upgrade. * * @since 3.7.0 * @since 5.9.0 Renamed `$data` to `$feedback` for PHP 8 named parameter support. * * @param string|array|WP_Error $feedback Message data. * @param mixed ...$args Optional text replacements. */ public function feedback( $feedback, ...$args ) { if ( is_wp_error( $feedback ) ) { $string = $feedback->get_error_message(); } elseif ( is_array( $feedback ) ) { return; } else { $string = $feedback; } if ( ! empty( $this->upgrader->strings[ $string ] ) ) { $string = $this->upgrader->strings[ $string ]; } if ( str_contains( $string, '%' ) ) { if ( ! empty( $args ) ) { $string = vsprintf( $string, $args ); } } $string = trim( $string ); // Only allow basic HTML in the messages, as it'll be used in emails/logs rather than direct browser output. $string = wp_kses( $string, array( 'a' => array( 'href' => true, ), 'br' => true, 'em' => true, 'strong' => true, ) ); if ( empty( $string ) ) { return; } $this->messages[] = $string; } /** * Creates a new output buffer. * * @since 3.7.0 */ public function header() { ob_start(); } /** * Retrieves the buffered content, deletes the buffer, and processes the output. * * @since 3.7.0 */ public function footer() { $output = ob_get_clean(); if ( ! empty( $output ) ) { $this->feedback( $output ); } } } class-file-upload-upgrader.php000064400000010103146715570560012403 0ustar00 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; } } theme.php000064400000135301146715570560006402 0ustar00errors ) && $wp_filesystem->errors->has_errors() ) { return new WP_Error( 'fs_error', __( 'Filesystem error.' ), $wp_filesystem->errors ); } // Get the base theme folder. $themes_dir = $wp_filesystem->wp_themes_dir(); if ( empty( $themes_dir ) ) { return new WP_Error( 'fs_no_themes_dir', __( 'Unable to locate WordPress theme directory.' ) ); } /** * Fires immediately before a theme deletion attempt. * * @since 5.8.0 * * @param string $stylesheet Stylesheet of the theme to delete. */ do_action( 'delete_theme', $stylesheet ); $theme = wp_get_theme( $stylesheet ); $themes_dir = trailingslashit( $themes_dir ); $theme_dir = trailingslashit( $themes_dir . $stylesheet ); $deleted = $wp_filesystem->delete( $theme_dir, true ); /** * Fires immediately after a theme deletion attempt. * * @since 5.8.0 * * @param string $stylesheet Stylesheet of the theme to delete. * @param bool $deleted Whether the theme deletion was successful. */ do_action( 'deleted_theme', $stylesheet, $deleted ); if ( ! $deleted ) { return new WP_Error( 'could_not_remove_theme', /* translators: %s: Theme name. */ sprintf( __( 'Could not fully remove the theme %s.' ), $stylesheet ) ); } $theme_translations = wp_get_installed_translations( 'themes' ); // Remove language files, silently. if ( ! empty( $theme_translations[ $stylesheet ] ) ) { $translations = $theme_translations[ $stylesheet ]; foreach ( $translations as $translation => $data ) { $wp_filesystem->delete( WP_LANG_DIR . '/themes/' . $stylesheet . '-' . $translation . '.po' ); $wp_filesystem->delete( WP_LANG_DIR . '/themes/' . $stylesheet . '-' . $translation . '.mo' ); $wp_filesystem->delete( WP_LANG_DIR . '/themes/' . $stylesheet . '-' . $translation . '.l10n.php' ); $json_translation_files = glob( WP_LANG_DIR . '/themes/' . $stylesheet . '-' . $translation . '-*.json' ); if ( $json_translation_files ) { array_map( array( $wp_filesystem, 'delete' ), $json_translation_files ); } } } // Remove the theme from allowed themes on the network. if ( is_multisite() ) { WP_Theme::network_disable_theme( $stylesheet ); } // Clear theme caches. $theme->cache_delete(); // Force refresh of theme update information. delete_site_transient( 'update_themes' ); return true; } /** * Gets the page templates available in this theme. * * @since 1.5.0 * @since 4.7.0 Added the `$post_type` parameter. * * @param WP_Post|null $post Optional. The post being edited, provided for context. * @param string $post_type Optional. Post type to get the templates for. Default 'page'. * @return string[] Array of template file names keyed by the template header name. */ function get_page_templates( $post = null, $post_type = 'page' ) { return array_flip( wp_get_theme()->get_page_templates( $post, $post_type ) ); } /** * Tidies a filename for url display by the theme file editor. * * @since 2.9.0 * @access private * * @param string $fullpath Full path to the theme file * @param string $containingfolder Path of the theme parent folder * @return string */ function _get_template_edit_filename( $fullpath, $containingfolder ) { return str_replace( dirname( $containingfolder, 2 ), '', $fullpath ); } /** * Check if there is an update for a theme available. * * Will display link, if there is an update available. * * @since 2.7.0 * * @see get_theme_update_available() * * @param WP_Theme $theme Theme data object. */ function theme_update_available( $theme ) { echo get_theme_update_available( $theme ); } /** * Retrieves the update link if there is a theme update available. * * Will return a link if there is an update available. * * @since 3.8.0 * * @param WP_Theme $theme WP_Theme object. * @return string|false HTML for the update link, or false if invalid info was passed. */ function get_theme_update_available( $theme ) { static $themes_update = null; if ( ! current_user_can( 'update_themes' ) ) { return false; } if ( ! isset( $themes_update ) ) { $themes_update = get_site_transient( 'update_themes' ); } if ( ! ( $theme instanceof WP_Theme ) ) { return false; } $stylesheet = $theme->get_stylesheet(); $html = ''; if ( isset( $themes_update->response[ $stylesheet ] ) ) { $update = $themes_update->response[ $stylesheet ]; $theme_name = $theme->display( 'Name' ); $details_url = add_query_arg( array( 'TB_iframe' => 'true', 'width' => 1024, 'height' => 800, ), $update['url'] ); // Theme browser inside WP? Replace this. Also, theme preview JS will override this on the available list. $update_url = wp_nonce_url( admin_url( 'update.php?action=upgrade-theme&theme=' . urlencode( $stylesheet ) ), 'upgrade-theme_' . $stylesheet ); if ( ! is_multisite() ) { if ( ! current_user_can( 'update_themes' ) ) { $html = sprintf( /* translators: 1: Theme name, 2: Theme details URL, 3: Additional link attributes, 4: Version number. */ '

    ' . __( 'There is a new version of %1$s available. View version %4$s details.' ) . '

    ', $theme_name, esc_url( $details_url ), sprintf( 'class="thickbox open-plugin-details-modal" aria-label="%s"', /* translators: 1: Theme name, 2: Version number. */ esc_attr( sprintf( __( 'View %1$s version %2$s details' ), $theme_name, $update['new_version'] ) ) ), $update['new_version'] ); } elseif ( empty( $update['package'] ) ) { $html = sprintf( /* translators: 1: Theme name, 2: Theme details URL, 3: Additional link attributes, 4: Version number. */ '

    ' . __( 'There is a new version of %1$s available. View version %4$s details. Automatic update is unavailable for this theme.' ) . '

    ', $theme_name, esc_url( $details_url ), sprintf( 'class="thickbox open-plugin-details-modal" aria-label="%s"', /* translators: 1: Theme name, 2: Version number. */ esc_attr( sprintf( __( 'View %1$s version %2$s details' ), $theme_name, $update['new_version'] ) ) ), $update['new_version'] ); } else { $html = sprintf( /* translators: 1: Theme name, 2: Theme details URL, 3: Additional link attributes, 4: Version number, 5: Update URL, 6: Additional link attributes. */ '

    ' . __( 'There is a new version of %1$s available. View version %4$s details or update now.' ) . '

    ', $theme_name, esc_url( $details_url ), sprintf( 'class="thickbox open-plugin-details-modal" aria-label="%s"', /* translators: 1: Theme name, 2: Version number. */ esc_attr( sprintf( __( 'View %1$s version %2$s details' ), $theme_name, $update['new_version'] ) ) ), $update['new_version'], $update_url, sprintf( 'aria-label="%s" id="update-theme" data-slug="%s"', /* translators: %s: Theme name. */ esc_attr( sprintf( _x( 'Update %s now', 'theme' ), $theme_name ) ), $stylesheet ) ); } } } return $html; } /** * Retrieves list of WordPress theme features (aka theme tags). * * @since 3.1.0 * @since 3.2.0 Added 'Gray' color and 'Featured Image Header', 'Featured Images', * 'Full Width Template', and 'Post Formats' features. * @since 3.5.0 Added 'Flexible Header' feature. * @since 3.8.0 Renamed 'Width' filter to 'Layout'. * @since 3.8.0 Renamed 'Fixed Width' and 'Flexible Width' options * to 'Fixed Layout' and 'Fluid Layout'. * @since 3.8.0 Added 'Accessibility Ready' feature and 'Responsive Layout' option. * @since 3.9.0 Combined 'Layout' and 'Columns' filters. * @since 4.6.0 Removed 'Colors' filter. * @since 4.6.0 Added 'Grid Layout' option. * Removed 'Fixed Layout', 'Fluid Layout', and 'Responsive Layout' options. * @since 4.6.0 Added 'Custom Logo' and 'Footer Widgets' features. * Removed 'Blavatar' feature. * @since 4.6.0 Added 'Blog', 'E-Commerce', 'Education', 'Entertainment', 'Food & Drink', * 'Holiday', 'News', 'Photography', and 'Portfolio' subjects. * Removed 'Photoblogging' and 'Seasonal' subjects. * @since 4.9.0 Reordered the filters from 'Layout', 'Features', 'Subject' * to 'Subject', 'Features', 'Layout'. * @since 4.9.0 Removed 'BuddyPress', 'Custom Menu', 'Flexible Header', * 'Front Page Posting', 'Microformats', 'RTL Language Support', * 'Threaded Comments', and 'Translation Ready' features. * @since 5.5.0 Added 'Block Editor Patterns', 'Block Editor Styles', * and 'Full Site Editing' features. * @since 5.5.0 Added 'Wide Blocks' layout option. * @since 5.8.1 Added 'Template Editing' feature. * @since 6.1.1 Replaced 'Full Site Editing' feature name with 'Site Editor'. * @since 6.2.0 Added 'Style Variations' feature. * * @param bool $api Optional. Whether try to fetch tags from the WordPress.org API. Defaults to true. * @return array Array of features keyed by category with translations keyed by slug. */ function get_theme_feature_list( $api = true ) { // Hard-coded list is used if API is not accessible. $features = array( __( 'Subject' ) => array( 'blog' => __( 'Blog' ), 'e-commerce' => __( 'E-Commerce' ), 'education' => __( 'Education' ), 'entertainment' => __( 'Entertainment' ), 'food-and-drink' => __( 'Food & Drink' ), 'holiday' => __( 'Holiday' ), 'news' => __( 'News' ), 'photography' => __( 'Photography' ), 'portfolio' => __( 'Portfolio' ), ), __( 'Features' ) => array( 'accessibility-ready' => __( 'Accessibility Ready' ), 'block-patterns' => __( 'Block Editor Patterns' ), 'block-styles' => __( 'Block Editor Styles' ), 'custom-background' => __( 'Custom Background' ), 'custom-colors' => __( 'Custom Colors' ), 'custom-header' => __( 'Custom Header' ), 'custom-logo' => __( 'Custom Logo' ), 'editor-style' => __( 'Editor Style' ), 'featured-image-header' => __( 'Featured Image Header' ), 'featured-images' => __( 'Featured Images' ), 'footer-widgets' => __( 'Footer Widgets' ), 'full-site-editing' => __( 'Site Editor' ), 'full-width-template' => __( 'Full Width Template' ), 'post-formats' => __( 'Post Formats' ), 'sticky-post' => __( 'Sticky Post' ), 'style-variations' => __( 'Style Variations' ), 'template-editing' => __( 'Template Editing' ), 'theme-options' => __( 'Theme Options' ), ), __( 'Layout' ) => array( 'grid-layout' => __( 'Grid Layout' ), 'one-column' => __( 'One Column' ), 'two-columns' => __( 'Two Columns' ), 'three-columns' => __( 'Three Columns' ), 'four-columns' => __( 'Four Columns' ), 'left-sidebar' => __( 'Left Sidebar' ), 'right-sidebar' => __( 'Right Sidebar' ), 'wide-blocks' => __( 'Wide Blocks' ), ), ); if ( ! $api || ! current_user_can( 'install_themes' ) ) { return $features; } $feature_list = get_site_transient( 'wporg_theme_feature_list' ); if ( ! $feature_list ) { set_site_transient( 'wporg_theme_feature_list', array(), 3 * HOUR_IN_SECONDS ); } if ( ! $feature_list ) { $feature_list = themes_api( 'feature_list', array() ); if ( is_wp_error( $feature_list ) ) { return $features; } } if ( ! $feature_list ) { return $features; } set_site_transient( 'wporg_theme_feature_list', $feature_list, 3 * HOUR_IN_SECONDS ); $category_translations = array( 'Layout' => __( 'Layout' ), 'Features' => __( 'Features' ), 'Subject' => __( 'Subject' ), ); $wporg_features = array(); // Loop over the wp.org canonical list and apply translations. foreach ( (array) $feature_list as $feature_category => $feature_items ) { if ( isset( $category_translations[ $feature_category ] ) ) { $feature_category = $category_translations[ $feature_category ]; } $wporg_features[ $feature_category ] = array(); foreach ( $feature_items as $feature ) { if ( isset( $features[ $feature_category ][ $feature ] ) ) { $wporg_features[ $feature_category ][ $feature ] = $features[ $feature_category ][ $feature ]; } else { $wporg_features[ $feature_category ][ $feature ] = $feature; } } } return $wporg_features; } /** * Retrieves theme installer pages from the WordPress.org Themes API. * * It is possible for a theme to override the Themes API result with three * filters. Assume this is for themes, which can extend on the Theme Info to * offer more choices. This is very powerful and must be used with care, when * overriding the filters. * * The first filter, {@see 'themes_api_args'}, is for the args and gives the action * as the second parameter. The hook for {@see 'themes_api_args'} must ensure that * an object is returned. * * The second filter, {@see 'themes_api'}, allows a plugin to override the WordPress.org * Theme API entirely. If `$action` is 'query_themes', 'theme_information', or 'feature_list', * an object MUST be passed. If `$action` is 'hot_tags', an array should be passed. * * Finally, the third filter, {@see 'themes_api_result'}, makes it possible to filter the * response object or array, depending on the `$action` type. * * Supported arguments per action: * * | Argument Name | 'query_themes' | 'theme_information' | 'hot_tags' | 'feature_list' | * | -------------------| :------------: | :-----------------: | :--------: | :--------------: | * | `$slug` | No | Yes | No | No | * | `$per_page` | Yes | No | No | No | * | `$page` | Yes | No | No | No | * | `$number` | No | No | Yes | No | * | `$search` | Yes | No | No | No | * | `$tag` | Yes | No | No | No | * | `$author` | Yes | No | No | No | * | `$user` | Yes | No | No | No | * | `$browse` | Yes | No | No | No | * | `$locale` | Yes | Yes | No | No | * | `$fields` | Yes | Yes | No | No | * * @since 2.8.0 * * @param string $action API action to perform: Accepts 'query_themes', 'theme_information', * 'hot_tags' or 'feature_list'. * @param array|object $args { * Optional. Array or object of arguments to serialize for the Themes API. Default empty array. * * @type string $slug The theme slug. Default empty. * @type int $per_page Number of themes per page. Default 24. * @type int $page Number of current page. Default 1. * @type int $number Number of tags to be queried. * @type string $search A search term. Default empty. * @type string $tag Tag to filter themes. Default empty. * @type string $author Username of an author to filter themes. Default empty. * @type string $user Username to query for their favorites. Default empty. * @type string $browse Browse view: 'featured', 'popular', 'updated', 'favorites'. * @type string $locale Locale to provide context-sensitive results. Default is the value of get_locale(). * @type array $fields { * Array of fields which should or should not be returned. * * @type bool $description Whether to return the theme full description. Default false. * @type bool $sections Whether to return the theme readme sections: description, installation, * FAQ, screenshots, other notes, and changelog. Default false. * @type bool $rating Whether to return the rating in percent and total number of ratings. * Default false. * @type bool $ratings Whether to return the number of rating for each star (1-5). Default false. * @type bool $downloaded Whether to return the download count. Default false. * @type bool $downloadlink Whether to return the download link for the package. Default false. * @type bool $last_updated Whether to return the date of the last update. Default false. * @type bool $tags Whether to return the assigned tags. Default false. * @type bool $homepage Whether to return the theme homepage link. Default false. * @type bool $screenshots Whether to return the screenshots. Default false. * @type int $screenshot_count Number of screenshots to return. Default 1. * @type bool $screenshot_url Whether to return the URL of the first screenshot. Default false. * @type bool $photon_screenshots Whether to return the screenshots via Photon. Default false. * @type bool $template Whether to return the slug of the parent theme. Default false. * @type bool $parent Whether to return the slug, name and homepage of the parent theme. Default false. * @type bool $versions Whether to return the list of all available versions. Default false. * @type bool $theme_url Whether to return theme's URL. Default false. * @type bool $extended_author Whether to return nicename or nicename and display name. Default false. * } * } * @return object|array|WP_Error Response object or array on success, WP_Error on failure. See the * {@link https://developer.wordpress.org/reference/functions/themes_api/ function reference article} * for more information on the make-up of possible return objects depending on the value of `$action`. */ function themes_api( $action, $args = array() ) { // Include an unmodified $wp_version. require ABSPATH . WPINC . '/version.php'; if ( is_array( $args ) ) { $args = (object) $args; } if ( 'query_themes' === $action ) { if ( ! isset( $args->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_version, 0, 3 ); // x.y } /** * Filters arguments used to query for installer pages from the WordPress.org Themes API. * * Important: An object MUST be returned to this filter. * * @since 2.8.0 * * @param object $args Arguments used to query for installer pages from the WordPress.org Themes API. * @param string $action Requested action. Likely values are 'theme_information', * 'feature_list', or 'query_themes'. */ $args = apply_filters( 'themes_api_args', $args, $action ); /** * Filters whether to override the WordPress.org Themes API. * * Returning a non-false value will effectively short-circuit the WordPress.org API request. * * If `$action` is 'query_themes', 'theme_information', or 'feature_list', an object MUST * be passed. If `$action` is 'hot_tags', an array should be passed. * * @since 2.8.0 * * @param false|object|array $override Whether to override the WordPress.org Themes API. Default false. * @param string $action Requested action. Likely values are 'theme_information', * 'feature_list', or 'query_themes'. * @param object $args Arguments used to query for installer pages from the Themes API. */ $res = apply_filters( 'themes_api', false, $action, $args ); if ( ! $res ) { $url = 'http://api.wordpress.org/themes/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_version . '; ' . home_url( '/' ), ); $request = wp_remote_get( $url, $http_args ); if ( $ssl && is_wp_error( $request ) ) { if ( ! wp_doing_ajax() ) { 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( 'themes_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( 'themes_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( 'themes_api_failed', $res->error ); } } if ( ! is_wp_error( $res ) ) { // Back-compat for info/1.2 API, upgrade the theme objects in query_themes to objects. if ( 'query_themes' === $action ) { foreach ( $res->themes as $i => $theme ) { $res->themes[ $i ] = (object) $theme; } } // Back-compat for info/1.2 API, downgrade the feature_list result back to an array. if ( 'feature_list' === $action ) { $res = (array) $res; } } } /** * Filters the returned WordPress.org Themes API response. * * @since 2.8.0 * * @param array|stdClass|WP_Error $res WordPress.org Themes API response. * @param string $action Requested action. Likely values are 'theme_information', * 'feature_list', or 'query_themes'. * @param stdClass $args Arguments used to query for installer pages from the WordPress.org Themes API. */ return apply_filters( 'themes_api_result', $res, $action, $args ); } /** * Prepares themes for JavaScript. * * @since 3.8.0 * * @param WP_Theme[] $themes Optional. Array of theme objects to prepare. * Defaults to all allowed themes. * * @return array An associative array of theme data, sorted by name. */ function wp_prepare_themes_for_js( $themes = null ) { $current_theme = get_stylesheet(); /** * Filters theme data before it is prepared for JavaScript. * * Passing a non-empty array will result in wp_prepare_themes_for_js() returning * early with that value instead. * * @since 4.2.0 * * @param array $prepared_themes An associative array of theme data. Default empty array. * @param WP_Theme[]|null $themes An array of theme objects to prepare, if any. * @param string $current_theme The active theme slug. */ $prepared_themes = (array) apply_filters( 'pre_prepare_themes_for_js', array(), $themes, $current_theme ); if ( ! empty( $prepared_themes ) ) { return $prepared_themes; } // Make sure the active theme is listed first. $prepared_themes[ $current_theme ] = array(); if ( null === $themes ) { $themes = wp_get_themes( array( 'allowed' => true ) ); if ( ! isset( $themes[ $current_theme ] ) ) { $themes[ $current_theme ] = wp_get_theme(); } } $updates = array(); $no_updates = array(); if ( ! is_multisite() && current_user_can( 'update_themes' ) ) { $updates_transient = get_site_transient( 'update_themes' ); if ( isset( $updates_transient->response ) ) { $updates = $updates_transient->response; } if ( isset( $updates_transient->no_update ) ) { $no_updates = $updates_transient->no_update; } } WP_Theme::sort_by_name( $themes ); $parents = array(); $auto_updates = (array) get_site_option( 'auto_update_themes', array() ); foreach ( $themes as $theme ) { $slug = $theme->get_stylesheet(); $encoded_slug = urlencode( $slug ); $parent = false; if ( $theme->parent() ) { $parent = $theme->parent(); $parents[ $slug ] = $parent->get_stylesheet(); $parent = $parent->display( 'Name' ); } $customize_action = null; $can_edit_theme_options = current_user_can( 'edit_theme_options' ); $can_customize = current_user_can( 'customize' ); $is_block_theme = $theme->is_block_theme(); if ( $is_block_theme && $can_edit_theme_options ) { $customize_action = admin_url( 'site-editor.php' ); if ( $current_theme !== $slug ) { $customize_action = add_query_arg( 'wp_theme_preview', $slug, $customize_action ); } } elseif ( ! $is_block_theme && $can_customize && $can_edit_theme_options ) { $customize_action = wp_customize_url( $slug ); } if ( null !== $customize_action ) { $customize_action = add_query_arg( array( 'return' => urlencode( sanitize_url( remove_query_arg( wp_removable_query_args(), wp_unslash( $_SERVER['REQUEST_URI'] ) ) ) ), ), $customize_action ); $customize_action = esc_url( $customize_action ); } $update_requires_wp = isset( $updates[ $slug ]['requires'] ) ? $updates[ $slug ]['requires'] : null; $update_requires_php = isset( $updates[ $slug ]['requires_php'] ) ? $updates[ $slug ]['requires_php'] : null; $auto_update = in_array( $slug, $auto_updates, true ); $auto_update_action = $auto_update ? 'disable-auto-update' : 'enable-auto-update'; if ( isset( $updates[ $slug ] ) ) { $auto_update_supported = true; $auto_update_filter_payload = (object) $updates[ $slug ]; } elseif ( isset( $no_updates[ $slug ] ) ) { $auto_update_supported = true; $auto_update_filter_payload = (object) $no_updates[ $slug ]; } else { $auto_update_supported = false; /* * Create the expected payload for the auto_update_theme filter, this is the same data * as contained within $updates or $no_updates but used when the Theme is not known. */ $auto_update_filter_payload = (object) array( 'theme' => $slug, 'new_version' => $theme->get( 'Version' ), 'url' => '', 'package' => '', 'requires' => $theme->get( 'RequiresWP' ), 'requires_php' => $theme->get( 'RequiresPHP' ), ); } $auto_update_forced = wp_is_auto_update_forced_for_item( 'theme', null, $auto_update_filter_payload ); $prepared_themes[ $slug ] = array( 'id' => $slug, 'name' => $theme->display( 'Name' ), 'screenshot' => array( $theme->get_screenshot() ), // @todo Multiple screenshots. 'description' => $theme->display( 'Description' ), 'author' => $theme->display( 'Author', false, true ), 'authorAndUri' => $theme->display( 'Author' ), 'tags' => $theme->display( 'Tags' ), 'version' => $theme->get( 'Version' ), 'compatibleWP' => is_wp_version_compatible( $theme->get( 'RequiresWP' ) ), 'compatiblePHP' => is_php_version_compatible( $theme->get( 'RequiresPHP' ) ), 'updateResponse' => array( 'compatibleWP' => is_wp_version_compatible( $update_requires_wp ), 'compatiblePHP' => is_php_version_compatible( $update_requires_php ), ), 'parent' => $parent, 'active' => $slug === $current_theme, 'hasUpdate' => isset( $updates[ $slug ] ), 'hasPackage' => isset( $updates[ $slug ] ) && ! empty( $updates[ $slug ]['package'] ), 'update' => get_theme_update_available( $theme ), 'autoupdate' => array( 'enabled' => $auto_update || $auto_update_forced, 'supported' => $auto_update_supported, 'forced' => $auto_update_forced, ), 'actions' => array( 'activate' => current_user_can( 'switch_themes' ) ? wp_nonce_url( admin_url( 'themes.php?action=activate&stylesheet=' . $encoded_slug ), 'switch-theme_' . $slug ) : null, 'customize' => $customize_action, 'delete' => ( ! is_multisite() && current_user_can( 'delete_themes' ) ) ? wp_nonce_url( admin_url( 'themes.php?action=delete&stylesheet=' . $encoded_slug ), 'delete-theme_' . $slug ) : null, 'autoupdate' => wp_is_auto_update_enabled_for_type( 'theme' ) && ! is_multisite() && current_user_can( 'update_themes' ) ? wp_nonce_url( admin_url( 'themes.php?action=' . $auto_update_action . '&stylesheet=' . $encoded_slug ), 'updates' ) : null, ), 'blockTheme' => $theme->is_block_theme(), ); } // Remove 'delete' action if theme has an active child. if ( ! empty( $parents ) && array_key_exists( $current_theme, $parents ) ) { unset( $prepared_themes[ $parents[ $current_theme ] ]['actions']['delete'] ); } /** * Filters the themes prepared for JavaScript, for themes.php. * * Could be useful for changing the order, which is by name by default. * * @since 3.8.0 * * @param array $prepared_themes Array of theme data. */ $prepared_themes = apply_filters( 'wp_prepare_themes_for_js', $prepared_themes ); $prepared_themes = array_values( $prepared_themes ); return array_filter( $prepared_themes ); } /** * Prints JS templates for the theme-browsing UI in the Customizer. * * @since 4.2.0 */ function customize_themes_print_templates() { ?> delete( $extension ); if ( ! $result ) { return new WP_Error( 'could_not_resume_theme', __( 'Could not resume the theme.' ) ); } return true; } /** * Renders an admin notice in case some themes 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_themes */ function paused_themes_notice() { if ( 'themes.php' === $GLOBALS['pagenow'] ) { return; } if ( ! current_user_can( 'resume_themes' ) ) { return; } if ( ! isset( $GLOBALS['_paused_themes'] ) || empty( $GLOBALS['_paused_themes'] ) ) { return; } $message = sprintf( '

    %s
    %s

    %s

    ', __( 'One or more themes failed to load properly.' ), __( 'You can find more details and make changes on the Themes screen.' ), esc_url( admin_url( 'themes.php' ) ), __( 'Go to the Themes screen' ) ); wp_admin_notice( $message, array( 'type' => 'error', 'paragraph_wrap' => false, ) ); } plugin.php000064400000265357146715570560006615 0ustar00 '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 . '

    ' ); } elseif ( ! $compatible_php ) { return new WP_Error( 'plugin_php_incompatible', '

    ' . sprintf( /* translators: 1: Current PHP version, 2: Plugin name, 3: Required PHP version. */ _x( 'Error: Current PHP version (%1$s) does not meet minimum requirements for %2$s. The plugin requires PHP %3$s.', 'plugin' ), PHP_VERSION, $plugin_headers['Name'], $requirements['requires_php'] ) . $php_update_message . '

    ' ); } elseif ( ! $compatible_wp ) { return new WP_Error( 'plugin_wp_incompatible', '

    ' . 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() ); } 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() ); if ( is_multisite() ) { update_site_option( 'wp_force_deactivated_plugins', array() ); } } class-theme-installer-skin.php000064400000030670146715570560012445 0ustar00 'web', 'url' => '', 'theme' => '', 'nonce' => '', 'title' => '', 'overwrite' => '', ); $args = wp_parse_args( $args, $defaults ); $this->type = $args['type']; $this->url = $args['url']; $this->api = isset( $args['api'] ) ? $args['api'] : array(); $this->overwrite = $args['overwrite']; parent::__construct( $args ); } /** * Performs an action before installing a theme. * * @since 2.8.0 */ public function before() { if ( ! empty( $this->api ) ) { $this->upgrader->strings['process_success'] = sprintf( $this->upgrader->strings['process_success_specific'], $this->api->name, $this->api->version ); } } /** * Hides the `process_failed` error when updating a theme by uploading a zip file. * * @since 5.5.0 * * @param WP_Error $wp_error WP_Error object. * @return bool True if the error should be hidden, false otherwise. */ public function hide_process_failed( $wp_error ) { if ( 'upload' === $this->type && '' === $this->overwrite && $wp_error->get_error_code() === 'folder_exists' ) { return true; } return false; } /** * Performs an action following a single theme install. * * @since 2.8.0 */ public function after() { if ( $this->do_overwrite() ) { return; } if ( empty( $this->upgrader->result['destination_name'] ) ) { return; } $theme_info = $this->upgrader->theme_info(); if ( empty( $theme_info ) ) { return; } $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 ); $install_actions = array(); if ( current_user_can( 'edit_theme_options' ) && current_user_can( 'customize' ) && ! $theme_info->is_block_theme() ) { $customize_url = add_query_arg( array( 'theme' => urlencode( $stylesheet ), 'return' => urlencode( admin_url( 'web' === $this->type ? 'theme-install.php' : 'themes.php' ) ), ), admin_url( 'customize.php' ) ); $install_actions['preview'] = sprintf( '' . '%s', esc_url( $customize_url ), __( 'Live Preview' ), /* translators: Hidden accessibility text. %s: Theme name. */ sprintf( __( 'Live Preview “%s”' ), $name ) ); } $install_actions['activate'] = sprintf( '' . '%s', esc_url( $activate_link ), _x( 'Activate', 'theme' ), /* translators: Hidden accessibility text. %s: Theme name. */ sprintf( _x( 'Activate “%s”', 'theme' ), $name ) ); if ( is_network_admin() && current_user_can( 'manage_network_themes' ) ) { $install_actions['network_enable'] = sprintf( '%s', esc_url( wp_nonce_url( 'themes.php?action=enable&theme=' . urlencode( $stylesheet ), 'enable-theme_' . $stylesheet ) ), __( 'Network Enable' ) ); } if ( 'web' === $this->type ) { $install_actions['themes_page'] = sprintf( '%s', self_admin_url( 'theme-install.php' ), __( 'Go to Theme Installer' ) ); } elseif ( current_user_can( 'switch_themes' ) || current_user_can( 'edit_theme_options' ) ) { $install_actions['themes_page'] = sprintf( '%s', self_admin_url( 'themes.php' ), __( 'Go to Themes page' ) ); } if ( ! $this->result || is_wp_error( $this->result ) || is_network_admin() || ! current_user_can( 'switch_themes' ) ) { unset( $install_actions['activate'], $install_actions['preview'] ); } elseif ( get_option( 'template' ) === $stylesheet ) { unset( $install_actions['activate'] ); } /** * Filters the list of action links available following a single theme installation. * * @since 2.8.0 * * @param string[] $install_actions Array of theme action links. * @param object $api Object containing WordPress.org API theme data. * @param string $stylesheet Theme directory name. * @param WP_Theme $theme_info Theme object. */ $install_actions = apply_filters( 'install_theme_complete_actions', $install_actions, $this->api, $stylesheet, $theme_info ); if ( ! empty( $install_actions ) ) { $this->feedback( implode( ' | ', (array) $install_actions ) ); } } /** * Checks if the theme can be overwritten and outputs the HTML for overwriting a theme on upload. * * @since 5.5.0 * * @return bool Whether the theme can be overwritten and HTML was outputted. */ private function do_overwrite() { if ( 'upload' !== $this->type || ! is_wp_error( $this->result ) || 'folder_exists' !== $this->result->get_error_code() ) { return false; } $folder = $this->result->get_error_data( 'folder_exists' ); $folder = rtrim( $folder, '/' ); $current_theme_data = false; $all_themes = wp_get_themes( array( 'errors' => null ) ); foreach ( $all_themes as $theme ) { $stylesheet_dir = wp_normalize_path( $theme->get_stylesheet_directory() ); if ( rtrim( $stylesheet_dir, '/' ) !== $folder ) { continue; } $current_theme_data = $theme; } $new_theme_data = $this->upgrader->new_theme_data; if ( ! $current_theme_data || ! $new_theme_data ) { return false; } echo '

    ' . esc_html__( 'This theme is already installed.' ) . '

    '; // Check errors for active theme. if ( is_wp_error( $current_theme_data->errors() ) ) { $this->feedback( 'current_theme_has_errors', $current_theme_data->errors()->get_error_message() ); } $this->is_downgrading = version_compare( $current_theme_data['Version'], $new_theme_data['Version'], '>' ); $is_invalid_parent = false; if ( ! empty( $new_theme_data['Template'] ) ) { $is_invalid_parent = ! in_array( $new_theme_data['Template'], array_keys( $all_themes ), true ); } $rows = array( 'Name' => __( 'Theme name' ), 'Version' => __( 'Version' ), 'Author' => __( 'Author' ), 'RequiresWP' => __( 'Required WordPress version' ), 'RequiresPHP' => __( 'Required PHP version' ), 'Template' => __( 'Parent theme' ), ); $table = ''; $table .= ''; $is_same_theme = true; // Let's consider only these rows. foreach ( $rows as $field => $label ) { $old_value = $current_theme_data->display( $field, false ); $old_value = $old_value ? (string) $old_value : '-'; $new_value = ! empty( $new_theme_data[ $field ] ) ? (string) $new_theme_data[ $field ] : '-'; if ( $old_value === $new_value && '-' === $new_value && 'Template' === $field ) { continue; } $is_same_theme = $is_same_theme && ( $old_value === $new_value ); $diff_field = ( 'Version' !== $field && $new_value !== $old_value ); $diff_version = ( 'Version' === $field && $this->is_downgrading ); $invalid_parent = false; if ( 'Template' === $field && $is_invalid_parent ) { $invalid_parent = true; $new_value .= ' ' . __( '(not found)' ); } $table .= ''; $table .= ( $diff_field || $diff_version || $invalid_parent ) ? ''; } $table .= '
    ' . esc_html_x( 'Active', 'theme' ) . '' . esc_html_x( 'Uploaded', 'theme' ) . '
    ' . $label . '' . wp_strip_all_tags( $old_value ) . '' : ''; $table .= wp_strip_all_tags( $new_value ) . '
    '; /** * 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.' ), get_bloginfo( '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( '', __( 'The uploaded file has expired. Please go back and upload it again.' ) ); echo '

    ' . implode( ' ', (array) $install_actions ) . '

    '; } return true; } } class-wp-theme-install-list-table.php000064400000036570146715570560013643 0ustar00features = $_REQUEST['features']; } $paged = $this->get_pagenum(); $per_page = 36; // These are the tabs which are shown on the page, $tabs = array(); $tabs['dashboard'] = __( 'Search' ); if ( 'search' === $tab ) { $tabs['search'] = __( 'Search Results' ); } $tabs['upload'] = __( 'Upload' ); $tabs['featured'] = _x( 'Featured', 'themes' ); //$tabs['popular'] = _x( 'Popular', 'themes' ); $tabs['new'] = _x( 'Latest', 'themes' ); $tabs['updated'] = _x( 'Recently Updated', 'themes' ); $nonmenu_tabs = array( 'theme-information' ); // Valid actions to perform which do not have a Menu item. /** This filter is documented in wp-admin/theme-install.php */ $tabs = apply_filters( 'install_themes_tabs', $tabs ); /** * Filters tabs not associated with a menu item on the Install Themes screen. * * @since 2.8.0 * * @param string[] $nonmenu_tabs The tabs that don't have a menu item on * the Install Themes screen. */ $nonmenu_tabs = apply_filters( 'install_themes_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 ); } $args = array( 'page' => $paged, 'per_page' => $per_page, 'fields' => $theme_field_defaults, ); switch ( $tab ) { case 'search': $type = isset( $_REQUEST['type'] ) ? wp_unslash( $_REQUEST['type'] ) : 'term'; switch ( $type ) { case 'tag': $args['tag'] = array_map( 'sanitize_key', $search_terms ); break; case 'term': $args['search'] = $search_string; break; case 'author': $args['author'] = $search_string; break; } if ( ! empty( $this->features ) ) { $args['tag'] = $this->features; $_REQUEST['s'] = implode( ',', $this->features ); $_REQUEST['type'] = 'tag'; } add_action( 'install_themes_table_header', 'install_theme_search_form', 10, 0 ); break; case 'featured': // case 'popular': case 'new': case 'updated': $args['browse'] = $tab; break; default: $args = false; break; } /** * Filters API request arguments for each Install Themes screen tab. * * The dynamic portion of the hook name, `$tab`, refers to the theme install * tab. * * Possible hook names include: * * - `install_themes_table_api_args_dashboard` * - `install_themes_table_api_args_featured` * - `install_themes_table_api_args_new` * - `install_themes_table_api_args_search` * - `install_themes_table_api_args_updated` * - `install_themes_table_api_args_upload` * * @since 3.7.0 * * @param array|false $args Theme install API arguments. */ $args = apply_filters( "install_themes_table_api_args_{$tab}", $args ); if ( ! $args ) { return; } $api = themes_api( 'query_themes', $args ); if ( is_wp_error( $api ) ) { wp_die( '

    ' . $api->get_error_message() . '

    ' . __( 'Try Again' ) . '

    ' ); } $this->items = $api->themes; $this->set_pagination_args( array( 'total_items' => $api->info['results'], 'per_page' => $args['per_page'], 'infinite_scroll' => true, ) ); } /** */ public function no_items() { _e( 'No themes match your request.' ); } /** * @global array $tabs * @global string $tab * @return array */ protected function get_views() { global $tabs, $tab; $display_tabs = array(); foreach ( (array) $tabs as $action => $text ) { $display_tabs[ 'theme-install-' . $action ] = array( 'url' => self_admin_url( 'theme-install.php?tab=' . $action ), 'label' => $text, 'current' => $action === $tab, ); } return $this->get_views_links( $display_tabs ); } /** * Displays the theme install table. * * Overrides the parent display() method to provide a different container. * * @since 3.1.0 */ public function display() { wp_nonce_field( 'fetch-list-' . get_class( $this ), '_ajax_fetch_list_nonce' ); ?>
    pagination( 'top' ); ?>
    display_rows_or_placeholder(); ?>
    tablenav( 'bottom' ); } /** */ public function display_rows() { $themes = $this->items; foreach ( $themes as $theme ) { ?>
    single_row( $theme ); ?>
    theme_installer(); } /** * Prints a theme from the WordPress.org API. * * @since 3.1.0 * * @global array $themes_allowedtags * * @param stdClass $theme { * An object that contains theme data returned by the WordPress.org API. * * @type string $name Theme name, e.g. 'Twenty Twenty-One'. * @type string $slug Theme slug, e.g. 'twentytwentyone'. * @type string $version Theme version, e.g. '1.1'. * @type string $author Theme author username, e.g. 'melchoyce'. * @type string $preview_url Preview URL, e.g. 'https://2021.wordpress.net/'. * @type string $screenshot_url Screenshot URL, e.g. 'https://wordpress.org/themes/twentytwentyone/'. * @type float $rating Rating score. * @type int $num_ratings The number of ratings. * @type string $homepage Theme homepage, e.g. 'https://wordpress.org/themes/twentytwentyone/'. * @type string $description Theme description. * @type string $download_link Theme ZIP download URL. * } */ public function single_row( $theme ) { global $themes_allowedtags; if ( empty( $theme ) ) { return; } $name = wp_kses( $theme->name, $themes_allowedtags ); $author = wp_kses( $theme->author, $themes_allowedtags ); /* translators: %s: Theme name. */ $preview_title = sprintf( __( 'Preview “%s”' ), $name ); $preview_url = add_query_arg( array( 'tab' => 'theme-information', 'theme' => $theme->slug, ), self_admin_url( 'theme-install.php' ) ); $actions = array(); $install_url = add_query_arg( array( 'action' => 'install-theme', 'theme' => $theme->slug, ), self_admin_url( 'update.php' ) ); $update_url = add_query_arg( array( 'action' => 'upgrade-theme', 'theme' => $theme->slug, ), self_admin_url( 'update.php' ) ); $status = $this->_get_theme_status( $theme ); switch ( $status ) { case 'update_available': $actions[] = sprintf( '%s', esc_url( wp_nonce_url( $update_url, 'upgrade-theme_' . $theme->slug ) ), /* translators: %s: Theme version. */ esc_attr( sprintf( __( 'Update to version %s' ), $theme->version ) ), __( 'Update' ) ); break; case 'newer_installed': case 'latest_installed': $actions[] = sprintf( '%s', esc_attr__( 'This theme is already installed and is up to date' ), _x( 'Installed', 'theme' ) ); break; case 'install': default: $actions[] = sprintf( '%s', esc_url( wp_nonce_url( $install_url, 'install-theme_' . $theme->slug ) ), /* translators: %s: Theme name. */ esc_attr( sprintf( _x( 'Install %s', 'theme' ), $name ) ), _x( 'Install Now', 'theme' ) ); break; } $actions[] = sprintf( '%s', esc_url( $preview_url ), /* translators: %s: Theme name. */ esc_attr( sprintf( __( 'Preview %s' ), $name ) ), __( 'Preview' ) ); /** * Filters the install action links for a theme in the Install Themes list table. * * @since 3.4.0 * * @param string[] $actions An array of theme action links. Defaults are * links to Install Now, Preview, and Details. * @param stdClass $theme An object that contains theme data returned by the * WordPress.org API. */ $actions = apply_filters( 'theme_install_actions', $actions, $theme ); ?>

    install_theme_info( $theme ); } /** * Prints the wrapper for the theme installer. */ public function theme_installer() { ?>
    install_theme_info( $theme ); ?>
    name, $themes_allowedtags ); $author = wp_kses( $theme->author, $themes_allowedtags ); $install_url = add_query_arg( array( 'action' => 'install-theme', 'theme' => $theme->slug, ), self_admin_url( 'update.php' ) ); $update_url = add_query_arg( array( 'action' => 'upgrade-theme', 'theme' => $theme->slug, ), self_admin_url( 'update.php' ) ); $status = $this->_get_theme_status( $theme ); ?>
    %s', esc_url( wp_nonce_url( $update_url, 'upgrade-theme_' . $theme->slug ) ), /* translators: %s: Theme version. */ esc_attr( sprintf( __( 'Update to version %s' ), $theme->version ) ), __( 'Update' ) ); break; case 'newer_installed': case 'latest_installed': printf( '%s', esc_attr__( 'This theme is already installed and is up to date' ), _x( 'Installed', 'theme' ) ); break; case 'install': default: printf( '%s', esc_url( wp_nonce_url( $install_url, 'install-theme_' . $theme->slug ) ), __( 'Install' ) ); break; } ?>

    screenshot_url ) ) : ?>
    $theme->rating, 'type' => 'percent', 'number' => $theme->num_ratings, ) ); ?>
    version, $themes_allowedtags ); ?>
    description, $themes_allowedtags ); ?>
    Install screen * @global string $type Type of search. * * @param array $extra_args Unused. */ public function _js_vars( $extra_args = array() ) { global $tab, $type; parent::_js_vars( compact( 'tab', 'type' ) ); } /** * Checks to see if the theme is already installed. * * @since 3.4.0 * * @param stdClass $theme A WordPress.org Theme API object. * @return string Theme status. */ private function _get_theme_status( $theme ) { $status = 'install'; $installed_theme = wp_get_theme( $theme->slug ); if ( $installed_theme->exists() ) { if ( version_compare( $installed_theme->get( 'Version' ), $theme->version, '=' ) ) { $status = 'latest_installed'; } elseif ( version_compare( $installed_theme->get( 'Version' ), $theme->version, '>' ) ) { $status = 'newer_installed'; } else { $status = 'update_available'; } } return $status; } } class-bulk-plugin-upgrader-skin.php000064400000005036146715570560013406 0ustar00upgrader->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 ) ); } } } template.php000064400000300011146715570560007103 0ustar00 '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 ' '; } /** * 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' ); } } ?>
    ' . _x( 'Name', 'meta name' ) . ' ' . __( 'Value' ) . ' '; // TBODY needed for list-manipulation JS. return; } $count = 0; ?>
    . $entry['meta_id'] = (int) $entry['meta_id']; $delete_nonce = wp_create_nonce( 'delete-meta_' . $entry['meta_id'] ); $r .= "\n\t"; $r .= "\n\t\t"; $r .= "\n\t\t
    "; $r .= get_submit_button( __( 'Delete' ), 'deletemeta small', "deletemeta[{$entry['meta_id']}]", false, array( 'data-wp-lists' => "delete:the-list:meta-{$entry['meta_id']}::_ajax_nonce=$delete_nonce" ) ); $r .= "\n\t\t"; $r .= get_submit_button( __( 'Update' ), 'updatemeta small', "meta-{$entry['meta_id']}-submit", false, array( 'data-wp-lists' => "add:the-list:meta-{$entry['meta_id']}::_ajax_nonce-add-meta=$update_nonce" ) ); $r .= '
    '; $r .= wp_nonce_field( 'change-meta', '_ajax_nonce', false, false ); $r .= ''; $r .= "\n\t\t\n\t"; 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 ); } ?>

    'newmeta-submit', 'data-wp-lists' => 'add:the-list:newmeta', ) ); ?>
    post_status, array( 'draft', 'pending' ), true ) && ( ! $post->post_date_gmt || '0000-00-00 00:00:00' === $post->post_date_gmt ) ); } $tab_index_attribute = ''; if ( (int) $tab_index > 0 ) { $tab_index_attribute = " tabindex=\"$tab_index\""; } // @todo Remove this? // echo '
    '; $post_date = ( $for_post ) ? $post->post_date : get_comment()->comment_date; $jj = ( $edit ) ? mysql2date( 'd', $post_date, false ) : current_time( 'd' ); $mm = ( $edit ) ? mysql2date( 'm', $post_date, false ) : current_time( 'm' ); $aa = ( $edit ) ? mysql2date( 'Y', $post_date, false ) : current_time( 'Y' ); $hh = ( $edit ) ? mysql2date( 'H', $post_date, false ) : current_time( 'H' ); $mn = ( $edit ) ? mysql2date( 'i', $post_date, false ) : current_time( 'i' ); $ss = ( $edit ) ? mysql2date( 's', $post_date, false ) : current_time( 's' ); $cur_jj = current_time( 'd' ); $cur_mm = current_time( 'm' ); $cur_aa = current_time( 'Y' ); $cur_hh = current_time( 'H' ); $cur_mn = current_time( 'i' ); $month = ''; $day = ''; $year = ''; $hour = ''; $minute = ''; echo '
    '; /* translators: 1: Month, 2: Day, 3: Year, 4: Hour, 5: Minute. */ printf( __( '%1$s %2$s, %3$s at %4$s:%5$s' ), $month, $day, $year, $hour, $minute ); echo '
    '; if ( $multi ) { return; } echo "\n\n"; $map = array( 'mm' => array( $mm, $cur_mm ), 'jj' => array( $jj, $cur_jj ), 'aa' => array( $aa, $cur_aa ), 'hh' => array( $hh, $cur_hh ), 'mn' => array( $mn, $cur_mn ), ); foreach ( $map as $timeunit => $value ) { list( $unit, $curr ) = $value; echo '' . "\n"; $cur_timeunit = 'cur_' . $timeunit; echo '' . "\n"; } ?>

    " . 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 : ?>

    %s (%s)', __( 'Choose a file from your computer:' ), /* translators: %s: Maximum allowed file size. */ sprintf( __( 'Maximum size: %s' ), $size ) ); ?>

    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 '

    '; if ( empty( $plugins['classic-editor/classic-editor.php'] ) ) { if ( current_user_can( 'install_plugins' ) ) { $install_url = wp_nonce_url( self_admin_url( 'plugin-install.php?tab=favorites&user=wordpressdotorg&save=0' ), 'save_wporg_username_' . get_current_user_id() ); 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 '

    '; } } elseif ( is_plugin_inactive( 'classic-editor/classic-editor.php' ) ) { if ( current_user_can( 'activate_plugins' ) ) { $activate_url = wp_nonce_url( self_admin_url( 'plugins.php?action=activate&plugin=classic-editor/classic-editor.php' ), 'activate-plugin_classic-editor/classic-editor.php' ); 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 '

    '; } } elseif ( $data_object instanceof WP_Post ) { $edit_url = add_query_arg( array( 'classic-editor' => '', 'classic-editor__forget' => '', ), get_edit_post_link( $data_object ) ); 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"; echo '
    '; echo '

    '; if ( 'dashboard_php_nag' === $box['id'] ) { echo ''; echo '' . /* translators: Hidden accessibility text. */ __( 'Warning:' ) . ' '; } echo $box['title']; echo "

    \n"; if ( 'dashboard_browser_nag' !== $box['id'] ) { $widget_title = $box['title']; if ( is_array( $box['args'] ) && isset( $box['args']['__widget_basename'] ) ) { $widget_title = $box['args']['__widget_basename']; // Do not pass this parameter to the user callback function. unset( $box['args']['__widget_basename'] ); } echo '
    '; echo ''; echo ''; echo ''; echo ''; echo ''; echo '
    '; } echo '
    '; 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 `