initial
This commit is contained in:
@@ -0,0 +1,775 @@
|
||||
<?php
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) exit;
|
||||
|
||||
/**
|
||||
* Additional hooks for "Permalink Manager Pro"
|
||||
*/
|
||||
class Permalink_Manager_Actions {
|
||||
|
||||
public function __construct() {
|
||||
add_action( 'admin_init', array( $this, 'trigger_action' ), 9 );
|
||||
add_action( 'admin_init', array( $this, 'extra_actions' ) );
|
||||
|
||||
// Ajax-based functions
|
||||
if ( is_admin() ) {
|
||||
add_action( 'wp_ajax_pm_bulk_tools', array( $this, 'ajax_bulk_tools' ) );
|
||||
add_action( 'wp_ajax_pm_save_permalink', array( $this, 'ajax_save_permalink' ) );
|
||||
add_action( 'wp_ajax_pm_detect_duplicates', array( $this, 'ajax_detect_duplicates' ) );
|
||||
add_action( 'wp_ajax_pm_dismissed_notice_handler', array( $this, 'ajax_hide_global_notice' ) );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Route the requests to functions that save datasets with associated callbacks
|
||||
*/
|
||||
public function trigger_action() {
|
||||
global $permalink_manager_after_sections_html;
|
||||
|
||||
// 1. Check if the form was submitted
|
||||
if ( empty( $_POST ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. Do nothing if search query is not empty
|
||||
if ( isset( $_POST['uri_editor_nonce'] ) && ( isset( $_REQUEST['search-submit'] ) || isset( $_REQUEST['filter-button'] ) ) ) {
|
||||
$this->trigger_filter_action();
|
||||
}
|
||||
|
||||
$actions_map = array(
|
||||
'uri_editor_nonce' => array( 'function' => 'update_all_permalinks', 'display_uri_table' => true ),
|
||||
'permalink_manager_options' => array( 'function' => 'save_settings' ),
|
||||
'permalink_manager_permastructs' => array( 'function' => 'save_permastructures' ),
|
||||
'import' => array( 'function' => 'import_custom_permalinks_uris' ),
|
||||
);
|
||||
|
||||
// 3. Find the action
|
||||
foreach ( $actions_map as $action => $map ) {
|
||||
$nonce = ( isset( $_POST[ $action ] ) ) ? sanitize_key( $_POST[ $action ] ) : '';
|
||||
|
||||
if ( ! empty( $nonce ) && wp_verify_nonce( $nonce, 'permalink-manager' ) ) {
|
||||
// Execute the function
|
||||
$output = call_user_func( array( $this, $map['function'] ) );
|
||||
|
||||
// Get list of updated URIs
|
||||
if ( ! empty( $map['display_uri_table'] ) ) {
|
||||
$updated_slugs_count = ( isset( $output['updated_count'] ) && $output['updated_count'] > 0 ) ? $output['updated_count'] : false;
|
||||
$updated_slugs_array = ( $updated_slugs_count ) ? $output['updated'] : '';
|
||||
}
|
||||
|
||||
// Trigger only one function
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Display the slugs table (and append the globals)
|
||||
if ( isset( $updated_slugs_count ) && isset( $updated_slugs_array ) ) {
|
||||
$permalink_manager_after_sections_html .= Permalink_Manager_UI_Elements::display_updated_slugs( $updated_slugs_array );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adjust the Bulk URI Editor filter URL
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function trigger_filter_action() {
|
||||
if ( empty( $_POST['uri_editor_nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['uri_editor_nonce'] ), 'permalink-manager' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$query_args = array(
|
||||
'langcode' => ! empty( $_REQUEST['langcode'] ) ? sanitize_key( $_REQUEST['langcode'] ) : null,
|
||||
'month' => ! empty( $_REQUEST['month'] ) ? sanitize_key( $_REQUEST['month'] ) : null,
|
||||
's' => ! empty( $_REQUEST['s'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['s'] ) ) : null,
|
||||
);
|
||||
|
||||
if ( ! empty( $query_args ) ) {
|
||||
$sendback = remove_query_arg( array_keys( $query_args ), wp_get_referer() );
|
||||
$sendback = add_query_arg( array_filter( $query_args ), $sendback );
|
||||
|
||||
wp_safe_redirect( $sendback );
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Route the requests to the additional tools-related functions with the relevant callbacks
|
||||
*/
|
||||
public static function extra_actions() {
|
||||
global $permalink_manager_before_sections_html;
|
||||
|
||||
if ( current_user_can( 'manage_options' ) && ! empty( $_GET['permalink-manager-nonce'] ) ) {
|
||||
// Check if the nonce field is correct
|
||||
$nonce = sanitize_key( $_GET['permalink-manager-nonce'] );
|
||||
|
||||
if ( ! wp_verify_nonce( $nonce, 'permalink-manager' ) ) {
|
||||
$permalink_manager_before_sections_html = Permalink_Manager_UI_Elements::get_alert_message( __( 'You are not allowed to remove Permalink Manager data!', 'permalink-manager' ), 'error updated_slugs' );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ( isset( $_GET['clear-permalink-manager-uris'] ) ) {
|
||||
self::clear_all_uris();
|
||||
} else if ( isset( $_GET['remove-permalink-manager-settings'] ) ) {
|
||||
$option_name = sanitize_key( $_GET['remove-permalink-manager-settings'] );
|
||||
self::remove_plugin_data( $option_name );
|
||||
} else if ( ! empty( $_REQUEST['remove-uri'] ) ) {
|
||||
$uri_key = sanitize_key( $_REQUEST['remove-uri'] );
|
||||
self::force_clear_single_element_uris_and_redirects( $uri_key );
|
||||
} else if ( ! empty( $_REQUEST['remove-redirect'] ) ) {
|
||||
$redirect_key = sanitize_key( $_REQUEST['remove-redirect'] );
|
||||
self::force_clear_single_redirect( $redirect_key );
|
||||
}
|
||||
} else if ( ! empty( $_POST['screen-options-apply'] ) ) {
|
||||
self::save_screen_options();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulk remove obsolete custom permalinks and redirects
|
||||
*/
|
||||
public static function clear_all_uris() {
|
||||
global $permalink_manager_redirects, $permalink_manager_before_sections_html;
|
||||
|
||||
// Get all custom permalinks & redirects
|
||||
$custom_permalinks = Permalink_Manager_URI_Functions::get_all_uris();
|
||||
$custom_redirects = (array) $permalink_manager_redirects;
|
||||
|
||||
// Check if array with custom URIs exists
|
||||
if ( empty( $custom_permalinks ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Count removed URIs & redirects
|
||||
$removed_uris = 0;
|
||||
$removed_redirects = 0;
|
||||
|
||||
// Get all element IDs
|
||||
$element_ids = array_merge( array_keys( $custom_permalinks ), array_keys( $custom_redirects ) );
|
||||
|
||||
// 1. Remove unused custom URI & redirects for deleted post or term
|
||||
foreach ( $element_ids as $element_id ) {
|
||||
$count = self::clear_single_element_uris_and_redirects( $element_id, true );
|
||||
|
||||
$removed_uris = ( ! empty( $count[0] ) ) ? $count[0] + $removed_uris : $removed_uris;
|
||||
$removed_redirects = ( ! empty( $count[1] ) ) ? $count[1] + $removed_redirects : $removed_redirects;
|
||||
}
|
||||
|
||||
// 2. Keep only a single redirect
|
||||
$removed_redirects += self::clear_redirects_array();
|
||||
|
||||
// 3. Save cleared URIs & Redirects
|
||||
if ( $removed_uris > 0 || $removed_redirects > 0 ) {
|
||||
Permalink_Manager_URI_Functions::save_all_uris();
|
||||
update_option( 'permalink-manager-redirects', array_filter( $permalink_manager_redirects ) );
|
||||
|
||||
// Translators: 1: Number of custom URIs, 2: Number of custom redirects.
|
||||
$permalink_manager_before_sections_html .= Permalink_Manager_UI_Elements::get_alert_message( sprintf( __( '%1$d Custom URIs and %2$d Custom Redirects were removed!', 'permalink-manager' ), $removed_uris, $removed_redirects ), 'updated updated_slugs' );
|
||||
} else {
|
||||
$permalink_manager_before_sections_html .= Permalink_Manager_UI_Elements::get_alert_message( __( 'No Custom URIs or Custom Redirects were removed!', 'permalink-manager' ), 'error updated_slugs' );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove obsolete custom permalink & redirects for specific post or term
|
||||
*
|
||||
* @param string|int $element_id
|
||||
* @param bool $count_removed
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function clear_single_element_uris_and_redirects( $element_id, $count_removed = false ) {
|
||||
global $wpdb, $permalink_manager_redirects, $permalink_manager_options;
|
||||
|
||||
// Count removed URIs & redirects
|
||||
$removed_uris = 0;
|
||||
$removed_redirects = 0;
|
||||
|
||||
// Only admin users can remove the broken URIs for removed post types & taxonomies
|
||||
$check_if_admin = is_admin();
|
||||
|
||||
// Check if the advanced mode is turned on
|
||||
$advanced_mode = Permalink_Manager_Helper_Functions::is_advanced_mode_on();
|
||||
|
||||
// If "Disable URI Editor to disallow Permalink changes" is set globally, the pages that follow the global settings should also be removed
|
||||
if ( $advanced_mode && ! empty( $permalink_manager_options["general"]["auto_update_uris"] ) && $permalink_manager_options["general"]["auto_update_uris"] == 2 ) {
|
||||
$strict_mode = true;
|
||||
} else {
|
||||
$strict_mode = false;
|
||||
}
|
||||
|
||||
// 1. Check if element exists
|
||||
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Direct SQL query is needed to join multiple tables
|
||||
if ( strpos( $element_id, 'tax-' ) !== false ) {
|
||||
$term_id = preg_replace( "/[^0-9]/", "", $element_id );
|
||||
$term_info = $wpdb->get_row( $wpdb->prepare( "SELECT taxonomy, meta_value FROM {$wpdb->term_taxonomy} AS t LEFT JOIN {$wpdb->termmeta} AS tm ON tm.term_id = t.term_id AND tm.meta_key = 'auto_update_uri' WHERE t.term_id = %d", $term_id ) );
|
||||
|
||||
// Custom URIs for disabled taxonomies may only be deleted via the admin dashboard, although they will always be removed if the term no longer exists in the database
|
||||
$remove = ( ! empty( $term_info->taxonomy ) ) ? Permalink_Manager_Helper_Functions::is_taxonomy_disabled( $term_info->taxonomy, $check_if_admin ) : true;
|
||||
|
||||
// Remove custom URIs for URIs disabled in URI Editor
|
||||
if ( $strict_mode ) {
|
||||
$remove = ( empty( $term_info->meta_value ) || $term_info->meta_value == 2 ) ? true : $remove;
|
||||
} else {
|
||||
$remove = ( ! empty( $term_info->meta_value ) && $term_info->meta_value == 2 ) ? true : $remove;
|
||||
}
|
||||
} else if ( is_numeric( $element_id ) ) {
|
||||
$post_info = $wpdb->get_row( $wpdb->prepare( "SELECT post_type, meta_value FROM {$wpdb->posts} AS p LEFT JOIN {$wpdb->postmeta} AS pm ON pm.post_ID = p.ID AND pm.meta_key = 'auto_update_uri' WHERE ID = %d AND post_status NOT IN ('auto-draft', 'trash') AND post_type != 'nav_menu_item'", $element_id ) );
|
||||
|
||||
// Custom URIs for disabled post types may only be deleted via the admin dashboard, although they will always be removed if the post no longer exists in the database
|
||||
$remove = ( ! empty( $post_info->post_type ) ) ? Permalink_Manager_Helper_Functions::is_post_type_disabled( $post_info->post_type, $check_if_admin ) : true;
|
||||
|
||||
// Remove custom URIs for URIs disabled in URI Editor
|
||||
if ( $strict_mode ) {
|
||||
$remove = ( empty( $post_info->meta_value ) || $post_info->meta_value == 2 ) ? true : $remove;
|
||||
} else {
|
||||
$remove = ( ! empty( $post_info->meta_value ) && $post_info->meta_value == 2 ) ? true : $remove;
|
||||
}
|
||||
|
||||
// Remove custom URIs for attachments redirected with Yoast's SEO Premium
|
||||
$yoast_permalink_options = ( class_exists( 'WPSEO_Premium' ) ) ? get_option( 'wpseo_permalinks' ) : array();
|
||||
|
||||
if ( ! empty( $yoast_permalink_options['redirectattachment'] ) && $post_info->post_type == 'attachment' ) {
|
||||
$attachment_parent = $wpdb->get_var( $wpdb->prepare( "SELECT post_parent FROM {$wpdb->prefix}posts WHERE ID = %d AND post_type = %s", $element_id, 'attachment' ) );
|
||||
if ( ! empty( $attachment_parent ) ) {
|
||||
$remove = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
|
||||
|
||||
// 2A. Remove ALL unused custom permalinks & redirects
|
||||
if ( ! empty( $remove ) ) {
|
||||
$current_uri = Permalink_Manager_URI_Functions::get_single_uri( $element_id, false, true, null );
|
||||
|
||||
// Remove URI
|
||||
if ( ! empty( $current_uri ) ) {
|
||||
$removed_uris = 1;
|
||||
Permalink_Manager_URI_Functions::remove_single_uri( $element_id, null, false );
|
||||
}
|
||||
|
||||
// Remove all custom redirects
|
||||
if ( ! empty( $permalink_manager_redirects[ $element_id ] ) && is_array( $permalink_manager_redirects[ $element_id ] ) ) {
|
||||
$removed_redirects = count( $permalink_manager_redirects[ $element_id ] );
|
||||
unset( $permalink_manager_redirects[ $element_id ] );
|
||||
}
|
||||
} // 2B. Check if the post/term uses the same URI for both permalink & custom redirects
|
||||
else {
|
||||
$removed_redirect = self::clear_single_element_duplicated_redirect( $element_id, false );
|
||||
$removed_redirects = ( ! empty( $removed_redirect ) ) ? 1 : 0;
|
||||
}
|
||||
|
||||
// Check if function should only return the counts or update
|
||||
if ( $count_removed ) {
|
||||
return array( $removed_uris, $removed_redirects );
|
||||
} else if ( ! empty( $removed_uris ) || ! empty( $removed_redirects ) ) {
|
||||
Permalink_Manager_URI_Functions::save_all_uris();
|
||||
update_option( 'permalink-manager-redirects', array_filter( $permalink_manager_redirects ) );
|
||||
}
|
||||
|
||||
return array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the duplicated custom redirect if the post/term has the same URI for both custom permalink and custom redirect
|
||||
*
|
||||
* @param string|int $element_id
|
||||
* @param bool $save_redirects
|
||||
* @param string $uri
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public static function clear_single_element_duplicated_redirect( $element_id, $save_redirects = true, $uri = null ) {
|
||||
global $permalink_manager_redirects;
|
||||
|
||||
// If the custom permalink is not changed ($uri) use the one that is currently used
|
||||
if ( ! empty( $uri ) ) {
|
||||
$current_uri = $uri;
|
||||
} else {
|
||||
$current_uri = Permalink_Manager_URI_Functions::get_single_uri( $element_id, false, true, null );
|
||||
}
|
||||
|
||||
if ( ! empty( $current_uri ) && ! empty( $permalink_manager_redirects[ $element_id ] ) && in_array( $current_uri, $permalink_manager_redirects[ $element_id ] ) ) {
|
||||
$duplicated_redirect_id = array_search( $current_uri, $permalink_manager_redirects[ $element_id ] );
|
||||
unset( $permalink_manager_redirects[ $element_id ][ $duplicated_redirect_id ] );
|
||||
}
|
||||
|
||||
// Update the redirects array in the database if the duplicated redirect was unset
|
||||
if ( isset( $duplicated_redirect_id ) && $save_redirects ) {
|
||||
update_option( 'permalink-manager-redirects', array_filter( $permalink_manager_redirects ) );
|
||||
}
|
||||
|
||||
return ( isset( $duplicated_redirect_id ) ) ? 1 : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the duplicated if the same URI is used for multiple custom redirects and return the removed redirects count
|
||||
*
|
||||
* @param bool $save_redirects
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public static function clear_redirects_array( $save_redirects = false ) {
|
||||
global $permalink_manager_redirects;
|
||||
|
||||
$removed_redirects = 0;
|
||||
|
||||
$all_redirect_duplicates = Permalink_Manager_Admin_Functions::get_all_duplicates();
|
||||
|
||||
foreach ( $all_redirect_duplicates as $single_redirect_duplicate ) {
|
||||
$last_element = reset( $single_redirect_duplicate );
|
||||
|
||||
foreach ( $single_redirect_duplicate as $redirect_key ) {
|
||||
// Keep a single redirect
|
||||
if ( $last_element == $redirect_key ) {
|
||||
continue;
|
||||
}
|
||||
preg_match( "/redirect-(\d+)_(tax-\d+|\d+)/", $redirect_key, $ids );
|
||||
|
||||
if ( ! empty( $ids[2] ) && ! empty( $permalink_manager_redirects[ $ids[2] ][ $ids[1] ] ) ) {
|
||||
$removed_redirects ++;
|
||||
unset( $permalink_manager_redirects[ $ids[2] ][ $ids[1] ] );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update the redirects array in the database if the duplicated redirect was unset
|
||||
if ( isset( $duplicated_redirect_id ) && $save_redirects ) {
|
||||
update_option( 'permalink-manager-redirects', array_filter( $permalink_manager_redirects ) );
|
||||
}
|
||||
|
||||
return $removed_redirects;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove custom permalinks & custom redirects for requested post or term
|
||||
*
|
||||
* @param $uri_key
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function force_clear_single_element_uris_and_redirects( $uri_key ) {
|
||||
global $permalink_manager_redirects, $permalink_manager_before_sections_html;
|
||||
|
||||
$custom_uri = Permalink_Manager_URI_Functions::get_single_uri( $uri_key, false, true, null );
|
||||
|
||||
// Check if custom URI is set
|
||||
if ( ! empty( $custom_uri ) ) {
|
||||
Permalink_Manager_URI_Functions::remove_single_uri( $uri_key, null, true );
|
||||
// translators: %s is the custom URI that was removed.
|
||||
$updated = Permalink_Manager_UI_Elements::get_alert_message( sprintf( __( 'URI "%s" was removed successfully!', 'permalink-manager' ), $custom_uri ), 'updated' );
|
||||
}
|
||||
|
||||
// Check if custom redirects are set
|
||||
if ( isset( $permalink_manager_redirects[ $uri_key ] ) ) {
|
||||
unset( $permalink_manager_redirects[ $uri_key ] );
|
||||
update_option( 'permalink-manager-redirects', $permalink_manager_redirects );
|
||||
}
|
||||
|
||||
if ( empty( $updated ) ) {
|
||||
$permalink_manager_before_sections_html .= Permalink_Manager_UI_Elements::get_alert_message( __( 'URI and/or custom redirects does not exist or were already removed!', 'permalink-manager' ), 'error' );
|
||||
} else {
|
||||
// Display the alert in admin panel
|
||||
if ( isset( $permalink_manager_before_sections_html ) && is_admin() ) {
|
||||
$permalink_manager_before_sections_html .= $updated;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove only custom redirects for requested post or term
|
||||
*
|
||||
* @param string $redirect_key
|
||||
*/
|
||||
public static function force_clear_single_redirect( $redirect_key ) {
|
||||
global $permalink_manager_redirects, $permalink_manager_before_sections_html;
|
||||
|
||||
preg_match( "/redirect-(\d+)_(tax-\d+|\d+)/", $redirect_key, $ids );
|
||||
|
||||
if ( ! empty( $permalink_manager_redirects[ $ids[2] ][ $ids[1] ] ) ) {
|
||||
unset( $permalink_manager_redirects[ $ids[2] ][ $ids[1] ] );
|
||||
|
||||
update_option( 'permalink-manager-redirects', array_filter( $permalink_manager_redirects ) );
|
||||
|
||||
$permalink_manager_before_sections_html = Permalink_Manager_UI_Elements::get_alert_message( __( 'The redirect was removed successfully!', 'permalink-manager' ), 'updated' );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save "Screen Options"
|
||||
*/
|
||||
public static function save_screen_options() {
|
||||
check_admin_referer( 'screen-options-nonce', 'screenoptionnonce' );
|
||||
|
||||
$screen_options = ( isset( $_POST['screen-options'] ) ) ? map_deep( wp_unslash( $_POST['screen-options'] ), 'sanitize_text_field' ) : array();
|
||||
|
||||
if ( ! empty( $screen_options ) ) {
|
||||
self::save_settings( 'screen-options', $screen_options );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the plugin settings
|
||||
*
|
||||
* @param bool $field
|
||||
* @param bool $value
|
||||
* @param bool $display_alert
|
||||
*/
|
||||
public static function save_settings( $field = false, $value = false, $display_alert = true ) {
|
||||
global $permalink_manager_options, $permalink_manager_before_sections_html;
|
||||
|
||||
// Info: The settings array is used also by "Screen Options"
|
||||
$new_options = $permalink_manager_options;
|
||||
|
||||
// Save only selected field/sections
|
||||
if ( $field && $value ) {
|
||||
$new_options[ $field ] = $value;
|
||||
} else {
|
||||
$post_fields = $_POST; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- The nonce is already validated in enclosing function
|
||||
|
||||
foreach ( $post_fields as $option_name => $option_value ) {
|
||||
$new_options[ $option_name ] = $option_value;
|
||||
}
|
||||
}
|
||||
|
||||
// Allow only white-listed option groups
|
||||
foreach ( $new_options as $group => $group_options ) {
|
||||
if ( ! in_array( $group, array( 'licence', 'screen-options', 'general', 'permastructure-settings', 'stop-words' ) ) ) {
|
||||
unset( $new_options[ $group ] );
|
||||
}
|
||||
}
|
||||
|
||||
// Sanitize & override the global with new settings
|
||||
$new_options = Permalink_Manager_Helper_Functions::sanitize_array( $new_options );
|
||||
$permalink_manager_options = $new_options = array_filter( $new_options );
|
||||
|
||||
// Save the settings in database
|
||||
update_option( 'permalink-manager', $new_options );
|
||||
|
||||
// Display the message
|
||||
$permalink_manager_before_sections_html .= ( $display_alert ) ? Permalink_Manager_UI_Elements::get_alert_message( __( 'The settings are saved!', 'permalink-manager' ), 'updated' ) : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the permastructures
|
||||
*/
|
||||
public static function save_permastructures() {
|
||||
global $permalink_manager_permastructs;
|
||||
|
||||
$permastructure_options = $permastructures = array();
|
||||
$permastructure_types = array( 'post_types', 'taxonomies' );
|
||||
|
||||
// Split permastructures & sanitize them
|
||||
// phpcs:disable WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- The nonce is already validated in enclosing function
|
||||
foreach ( $permastructure_types as $type ) {
|
||||
if ( empty( $_POST[ $type ] ) || ! is_array( $_POST[ $type ] ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$permastructures[ $type ] = $_POST[ $type ];
|
||||
|
||||
foreach ( $permastructures[ $type ] as &$single_permastructure ) {
|
||||
$single_permastructure = Permalink_Manager_Helper_Functions::sanitize_title( $single_permastructure, true, false, false );
|
||||
$single_permastructure = trim( $single_permastructure, '\/ ' );
|
||||
}
|
||||
}
|
||||
|
||||
if ( ! empty( $_POST['permastructure-settings'] ) ) {
|
||||
$permastructure_options = $_POST['permastructure-settings'];
|
||||
}
|
||||
// phpcs:enable WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
|
||||
|
||||
// A. Permastructures
|
||||
if ( ! empty( $permastructures['post_types'] ) || ! empty( $permastructures['taxonomies'] ) ) {
|
||||
// Override the global with settings
|
||||
$permalink_manager_permastructs = $permastructures;
|
||||
|
||||
// Save the settings in database
|
||||
update_option( 'permalink-manager-permastructs', $permastructures );
|
||||
}
|
||||
|
||||
// B. Permastructure settings
|
||||
if ( ! empty( $permastructure_options ) ) {
|
||||
self::save_settings( 'permastructure-settings', $permastructure_options );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update all permalinks in "Bulk URI Editor"
|
||||
*/
|
||||
function update_all_permalinks() {
|
||||
// Check if posts or terms should be updated
|
||||
if ( ! empty( $_POST['content_type'] ) && $_POST['content_type'] == 'taxonomies' ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- The nonce is already validated in enclosing function
|
||||
return Permalink_Manager_URI_Functions_Tax::update_all_permalinks();
|
||||
} else {
|
||||
return Permalink_Manager_URI_Functions_Post::update_all_permalinks();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a specific section of the plugin data stored in the database
|
||||
*
|
||||
* @param $field_name
|
||||
*/
|
||||
public static function remove_plugin_data( $field_name ) {
|
||||
global $permalink_manager, $permalink_manager_before_sections_html;
|
||||
|
||||
// Make sure that the user is allowed to remove the plugin data
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
$permalink_manager_before_sections_html .= Permalink_Manager_UI_Elements::get_alert_message( __( 'You are not allowed to remove Permalink Manager data!', 'permalink-manager' ), 'error updated_slugs' );
|
||||
}
|
||||
|
||||
switch ( $field_name ) {
|
||||
case 'uris' :
|
||||
$option_name = 'permalink-manager-uris';
|
||||
$alert = __( 'Custom permalinks', 'permalink-manager' );
|
||||
break;
|
||||
case 'redirects' :
|
||||
$option_name = 'permalink-manager-redirects';
|
||||
$alert = __( 'Custom redirects', 'permalink-manager' );
|
||||
break;
|
||||
case 'external-redirects' :
|
||||
$option_name = 'permalink-manager-external-redirects';
|
||||
$alert = __( 'External redirects', 'permalink-manager' );
|
||||
break;
|
||||
case 'permastructs' :
|
||||
$option_name = 'permalink-manager-permastructs';
|
||||
$alert = __( 'Permastructure settings', 'permalink-manager' );
|
||||
break;
|
||||
case 'settings' :
|
||||
$option_name = 'permalink-manager';
|
||||
$alert = __( 'Permastructure settings', 'permalink-manager' );
|
||||
break;
|
||||
default :
|
||||
$alert = '';
|
||||
}
|
||||
|
||||
if ( ! empty( $option_name ) ) {
|
||||
// Remove the option from DB
|
||||
delete_option( $option_name );
|
||||
|
||||
// Reload globals
|
||||
$permalink_manager->get_options_and_globals();
|
||||
|
||||
// Translators: %s is the name of the data field that was removed
|
||||
$alert_message = sprintf( __( '%s were removed!', 'permalink-manager' ), $alert );
|
||||
$permalink_manager_before_sections_html .= Permalink_Manager_UI_Elements::get_alert_message( $alert_message, 'updated updated_slugs' );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger bulk tools ("Regenerate & reset", "Find & replace") via AJAX
|
||||
*/
|
||||
function ajax_bulk_tools() {
|
||||
global $sitepress, $wpdb;
|
||||
|
||||
// Define variables
|
||||
$return = array( 'alert' => Permalink_Manager_UI_Elements::get_alert_message( __( '<strong>No items</strong> were processed!', 'permalink-manager' ), 'error updated_slugs' ) );
|
||||
|
||||
// Get the name of the function
|
||||
if ( isset( $_POST['regenerate'] ) ) {
|
||||
$nonce_name = sanitize_key( $_POST['regenerate'] );
|
||||
$operation = 'regenerate';
|
||||
} else if ( isset( $_POST['find_and_replace'] ) ) {
|
||||
$nonce_name = sanitize_key( $_POST['find_and_replace'] );
|
||||
$operation = ( ! empty( $_POST['old_string'] ) && ! empty( $_POST['new_string'] ) ) ? 'find_and_replace' : '';
|
||||
}
|
||||
|
||||
// Validate the nonce
|
||||
if ( empty( $nonce_name ) || ! wp_verify_nonce( $nonce_name, 'permalink-manager' ) ) {
|
||||
$error = true;
|
||||
$return = array( 'alert' => Permalink_Manager_UI_Elements::get_alert_message( __( 'Nonce is invalid!', 'permalink-manager' ), 'error updated_slugs' ) );
|
||||
}
|
||||
|
||||
// Get the session ID
|
||||
$uniq_id = ( ! empty( $_POST['pm_session_id'] ) ) ? sanitize_key( $_POST['pm_session_id'] ) : '';
|
||||
|
||||
// Get content type & post statuses
|
||||
if ( ! empty( $_POST['content_type'] ) && $_POST['content_type'] == 'taxonomies' ) {
|
||||
$content_type = 'taxonomies';
|
||||
|
||||
if ( empty( $_POST['taxonomies'] ) ) {
|
||||
$error = true;
|
||||
$return = array( 'alert' => Permalink_Manager_UI_Elements::get_alert_message( __( '<strong>No taxonomy</strong> selected!', 'permalink-manager' ), 'error updated_slugs' ) );
|
||||
}
|
||||
} else {
|
||||
$content_type = 'post_types';
|
||||
|
||||
// Check if any post type was selected
|
||||
if ( empty( $_POST['post_types'] ) ) {
|
||||
$error = true;
|
||||
$return = array( 'alert' => Permalink_Manager_UI_Elements::get_alert_message( __( '<strong>No post type</strong> selected!', 'permalink-manager' ), 'error updated_slugs' ) );
|
||||
}
|
||||
|
||||
// Check post status
|
||||
if ( empty( $_POST['post_statuses'] ) ) {
|
||||
$error = true;
|
||||
$return = array( 'alert' => Permalink_Manager_UI_Elements::get_alert_message( __( '<strong>No post status</strong> selected!', 'permalink-manager' ), 'error updated_slugs' ) );
|
||||
}
|
||||
}
|
||||
|
||||
if ( ! empty( $operation ) && empty( $error ) ) {
|
||||
// Hotfix for WPML (start)
|
||||
if ( $sitepress ) {
|
||||
remove_filter( 'get_terms_args', array( $sitepress, 'get_terms_args_filter' ), 10 );
|
||||
remove_filter( 'get_term', array( $sitepress, 'get_term_adjust_id' ), 1 );
|
||||
remove_filter( 'terms_clauses', array( $sitepress, 'terms_clauses' ), 10 );
|
||||
remove_filter( 'get_pages', array( $sitepress, 'get_pages_adjust_ids' ), 1 );
|
||||
}
|
||||
|
||||
// Get the mode
|
||||
$mode = ( isset( $_POST['mode'] ) ) ? sanitize_key( $_POST['mode'] ) : 'custom_uris';
|
||||
$preview_mode = ( ! empty( $_POST['preview_mode'] ) ) ? true : false;
|
||||
|
||||
// Get items (try to get them from transient)
|
||||
$items = get_transient( "pm_{$uniq_id}" );
|
||||
|
||||
// Get the iteration count and chunk size
|
||||
$iteration = isset( $_POST['iteration'] ) ? intval( $_POST['iteration'] ) : 1;
|
||||
$chunk_size = apply_filters( 'permalink_manager_chunk_size', 50 );
|
||||
|
||||
if ( empty( $items ) && ! empty ( $chunk_size ) ) {
|
||||
if ( $content_type == 'taxonomies' ) {
|
||||
$items = Permalink_Manager_URI_Functions_Tax::get_items();
|
||||
} else {
|
||||
$items = Permalink_Manager_URI_Functions_Post::get_items();
|
||||
}
|
||||
|
||||
if ( ! empty( $items ) ) {
|
||||
// Count how many items need to be processed
|
||||
$total = count( $items );
|
||||
|
||||
// Split items array into chunks and save them to transient
|
||||
$items = array_chunk( $items, $chunk_size );
|
||||
|
||||
set_transient( "pm_{$uniq_id}", $items, 600 );
|
||||
|
||||
// Check for MySQL errors
|
||||
if ( ! empty( $wpdb->last_error ) ) {
|
||||
printf( '%s (%sMB)', esc_html( $wpdb->last_error ), esc_html( number_format( strlen( serialize( $items ) ) / 1000000, 2 ) ) );
|
||||
http_response_code( 500 );
|
||||
die();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Get homepage URL and ensure that it ends with slash
|
||||
$home_url = Permalink_Manager_Permastructure_Functions::get_permalink_base() . "/";
|
||||
|
||||
// Process the variables from $_POST object
|
||||
// phpcs:disable WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- The escaped slashes can be a part of REGEX formula
|
||||
$old_string = ( ! empty( $_POST['old_string'] ) ) ? str_replace( $home_url, '', esc_sql( sanitize_text_field( $_POST['old_string'] ) ) ) : '';
|
||||
$new_string = ( ! empty( $_POST['new_string'] ) ) ? str_replace( $home_url, '', esc_sql( sanitize_text_field( $_POST['new_string'] ) ) ) : '';
|
||||
// phpcs:enable WordPress.Security.ValidatedSanitizedInput.MissingUnslash
|
||||
|
||||
// Process only one subarray
|
||||
if ( ! empty( $items[ $iteration - 1 ] ) ) {
|
||||
$chunk = $items[ $iteration - 1 ];
|
||||
|
||||
// Check how many iterations are needed
|
||||
$total_iterations = count( $items );
|
||||
|
||||
if ( $content_type == 'taxonomies' ) {
|
||||
$output = Permalink_Manager_URI_Functions_Tax::bulk_process_items( $chunk, $mode, $operation, $old_string, $new_string, $preview_mode );
|
||||
} else {
|
||||
$output = Permalink_Manager_URI_Functions_Post::bulk_process_items( $chunk, $mode, $operation, $old_string, $new_string, $preview_mode );
|
||||
}
|
||||
|
||||
if ( ! empty( $output['updated_count'] ) ) {
|
||||
$return = array_merge( $return, (array) Permalink_Manager_UI_Elements::display_updated_slugs( $output['updated'], true, true, $preview_mode ) );
|
||||
$return['updated_count'] = $output['updated_count'];
|
||||
}
|
||||
|
||||
// Send total number of processed items with a first chunk
|
||||
if ( ! empty( $total ) && ! empty( $total_iterations ) && $iteration == 1 ) {
|
||||
$return['total'] = $total;
|
||||
$return['items'] = $items;
|
||||
}
|
||||
|
||||
$return['iteration'] = $iteration;
|
||||
$return['total_iterations'] = $total_iterations;
|
||||
$return['progress'] = $chunk_size * $iteration;
|
||||
$return['chunk'] = $chunk;
|
||||
|
||||
// After all chunks are processed remove the transient
|
||||
if ( $iteration == $total_iterations ) {
|
||||
delete_transient( "pm_{$uniq_id}" );
|
||||
}
|
||||
}
|
||||
|
||||
// Hotfix for WPML (end)
|
||||
if ( $sitepress ) {
|
||||
add_filter( 'terms_clauses', array( $sitepress, 'terms_clauses' ), 10, 4 );
|
||||
add_filter( 'get_term', array( $sitepress, 'get_term_adjust_id' ), 1, 1 );
|
||||
add_filter( 'get_terms_args', array( $sitepress, 'get_terms_args_filter' ), 10, 2 );
|
||||
add_filter( 'get_pages', array( $sitepress, 'get_pages_adjust_ids' ), 1, 2 );
|
||||
}
|
||||
}
|
||||
|
||||
wp_send_json( $return );
|
||||
die();
|
||||
}
|
||||
|
||||
/**
|
||||
* Save permalink via AJAX
|
||||
*/
|
||||
public function ajax_save_permalink() {
|
||||
$element_id = ( ! empty( $_POST['permalink-manager-edit-uri-element-id'] ) ) ? sanitize_key( $_POST['permalink-manager-edit-uri-element-id'] ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce is validated inside update_post_hook
|
||||
|
||||
if ( ! empty( $element_id ) && is_numeric( $element_id ) && current_user_can( 'edit_post', $element_id ) ) {
|
||||
Permalink_Manager_URI_Functions_Post::update_post_hook( $element_id );
|
||||
|
||||
// Reload URI Editor & clean post cache
|
||||
clean_post_cache( $element_id );
|
||||
die();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if URI was used before
|
||||
*/
|
||||
function ajax_detect_duplicates() {
|
||||
$duplicate_alert = __( "Permalink is already in use, please select another one!", "permalink-manager" );
|
||||
$duplicates_data = array();
|
||||
$custom_uris = ( ! empty( $_REQUEST['custom_uris'] ) ) ? Permalink_Manager_Helper_Functions::sanitize_array( $_REQUEST['custom_uris'] ) : array(); // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended -- No data is saved here
|
||||
|
||||
if ( ! empty( $custom_uris ) ) {
|
||||
// Check each URI
|
||||
foreach ( $custom_uris as $raw_element_id => $element_uri ) {
|
||||
$element_id = sanitize_key( $raw_element_id );
|
||||
$duplicates_data[ $element_id ] = Permalink_Manager_URI_Functions::is_uri_duplicated( $element_uri, $element_id ) ? $duplicate_alert : 0;
|
||||
}
|
||||
} else if ( ! empty( $_REQUEST['custom_uri'] ) && ! empty( $_REQUEST['element_id'] ) ) {
|
||||
$duplicates_data = Permalink_Manager_URI_Functions::is_uri_duplicated( $_REQUEST['custom_uri'], sanitize_key( $_REQUEST['element_id'] ) );
|
||||
}
|
||||
|
||||
wp_send_json( $duplicates_data );
|
||||
}
|
||||
|
||||
/**
|
||||
* Hide global notices (AJAX)
|
||||
*/
|
||||
function ajax_hide_global_notice() {
|
||||
global $permalink_manager_alerts;
|
||||
|
||||
// Get the ID of the alert
|
||||
$alert_id = ( ! empty( $_REQUEST['alert_id'] ) ) ? sanitize_title( $_REQUEST['alert_id'] ) : "";
|
||||
if ( ! empty( $permalink_manager_alerts[ $alert_id ] ) ) {
|
||||
$dismissed_transient_name = sprintf( 'permalink-manager-notice_%s', $alert_id );
|
||||
$dismissed_time = ( ! empty( $permalink_manager_alerts[ $alert_id ]['dismissed_time'] ) ) ? (int) $permalink_manager_alerts[ $alert_id ]['dismissed_time'] : DAY_IN_SECONDS;
|
||||
|
||||
set_transient( $dismissed_transient_name, 1, $dismissed_time );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Import old URIs from "Custom Permalinks" (Pro)
|
||||
*/
|
||||
function import_custom_permalinks_uris() {
|
||||
Permalink_Manager_Third_Parties::import_custom_permalinks_uris();
|
||||
}
|
||||
|
||||
}
|
||||
+329
@@ -0,0 +1,329 @@
|
||||
<?php
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Additional functions related to WordPress Admin Dashboard UI
|
||||
*/
|
||||
class Permalink_Manager_Admin_Functions {
|
||||
|
||||
public $sections, $active_section, $active_subsection;
|
||||
|
||||
public function __construct() {
|
||||
add_action( 'admin_menu', array( $this, 'add_menu_page' ) );
|
||||
add_action( 'admin_init', array( $this, 'init' ) );
|
||||
add_action( 'admin_bar_menu', array( $this, 'fix_customize_url' ), 41 );
|
||||
|
||||
add_action( 'admin_notices', array( $this, 'display_plugin_notices' ) );
|
||||
add_action( 'admin_notices', array( $this, 'display_global_notices' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Hooks that should be triggered with "admin_init"
|
||||
*/
|
||||
public function init() {
|
||||
// Additional links in "Plugins" page
|
||||
add_filter( "plugin_action_links_" . PERMALINK_MANAGER_BASENAME, array( $this, "plugins_page_links" ) );
|
||||
add_filter( "plugin_row_meta", array( $this, "plugins_page_meta" ), 10, 2 );
|
||||
|
||||
// Detect current section
|
||||
$this->sections = apply_filters( 'permalink_manager_sections', array() );
|
||||
$this->get_current_section();
|
||||
}
|
||||
|
||||
/**
|
||||
* Use the native URL for "Customize" button in the admin bar
|
||||
*
|
||||
* @param WP_Admin_Bar $wp_admin_bar
|
||||
*/
|
||||
public function fix_customize_url( $wp_admin_bar ) {
|
||||
global $permalink_manager_ignore_permalink_filters;
|
||||
|
||||
$object = get_queried_object();
|
||||
$customize = $wp_admin_bar->get_node( 'customize' );
|
||||
|
||||
if ( empty( $customize->href ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$permalink_manager_ignore_permalink_filters = true;
|
||||
if ( ! empty( $object->ID ) && is_a( $object, 'WP_Post' ) ) {
|
||||
$new_url = get_permalink( $object->ID );
|
||||
} else if ( ! empty( $object->taxonomy ) && is_a( $object, 'WP_Term' ) ) {
|
||||
$new_url = get_term_link( $object, $object->taxonomy );
|
||||
}
|
||||
$permalink_manager_ignore_permalink_filters = false;
|
||||
|
||||
if ( ! empty( $new_url ) ) {
|
||||
// The original permalink should be already encoded via "utf8_uri_encode()" in "sanitize_title_with_dashes()" function, so there is no need to encode them once again
|
||||
$new_url = filter_var( $new_url, FILTER_SANITIZE_URL );
|
||||
$customize_url = preg_replace( '/url=([^&]+)/', "url={$new_url}", $customize->href );
|
||||
|
||||
$wp_admin_bar->add_node( array(
|
||||
'id' => 'customize',
|
||||
'href' => $customize_url,
|
||||
) );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current section of Permalink Manager admin panel
|
||||
*/
|
||||
public function get_current_section() {
|
||||
global $active_section, $active_subsection, $current_admin_tax;
|
||||
|
||||
// 1. Get current section
|
||||
if ( isset( $_GET['page'] ) && $_GET['page'] == PERMALINK_MANAGER_PLUGIN_SLUG ) {
|
||||
if ( isset( $_POST['section'] ) ) {
|
||||
$this->active_section = sanitize_title_with_dashes( $_POST['section'] );
|
||||
} else if ( isset( $_GET['section'] ) ) {
|
||||
$this->active_section = sanitize_title_with_dashes( $_GET['section'] );
|
||||
} else {
|
||||
$sections_names = array_keys( $this->sections );
|
||||
$this->active_section = $sections_names[0];
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Get current subsection
|
||||
if ( $this->active_section && isset( $this->sections[ $this->active_section ]['subsections'] ) ) {
|
||||
if ( isset( $_POST['subsection'] ) ) {
|
||||
$this->active_subsection = sanitize_title_with_dashes( $_POST['subsection'] );
|
||||
} else if ( isset( $_GET['subsection'] ) ) {
|
||||
$this->active_subsection = sanitize_title_with_dashes( $_GET['subsection'] );
|
||||
} else {
|
||||
$subsections_names = array_keys( $this->sections[ $this->active_section ]['subsections'] );
|
||||
$this->active_subsection = $subsections_names[0];
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Check if current admin page is related to taxonomies
|
||||
if ( ! empty( $this->active_subsection ) && substr( $this->active_subsection, 0, 4 ) == 'tax_' ) {
|
||||
$current_admin_tax = substr( $this->active_subsection, 4, strlen( $this->active_subsection ) );
|
||||
} else {
|
||||
$current_admin_tax = false;
|
||||
}
|
||||
|
||||
// Set globals
|
||||
$active_section = $this->active_section;
|
||||
$active_subsection = $this->active_subsection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add "Tools -> Permalink Manager" to the admin sidebar menu
|
||||
*/
|
||||
public function add_menu_page() {
|
||||
add_management_page( __( 'Permalink Manager', 'permalink-manager' ), __( 'Permalink Manager', 'permalink-manager' ), 'manage_options', PERMALINK_MANAGER_PLUGIN_SLUG, array( $this, 'display_section' ) );
|
||||
|
||||
add_action( 'admin_init', array( $this, 'enqueue_cssjs' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the plugin sections
|
||||
*/
|
||||
public function display_section() {
|
||||
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
|
||||
echo Permalink_Manager_UI_Elements::get_plugin_sections_html( $this->sections, $this->active_section, $this->active_subsection );
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the CSS & JS files for the plugin's dashboard
|
||||
*/
|
||||
public function enqueue_cssjs() {
|
||||
wp_enqueue_style( 'permalink-manager-plugins', PERMALINK_MANAGER_URL . '/out/permalink-manager-plugins.css', array(), PERMALINK_MANAGER_VERSION );
|
||||
wp_enqueue_style( 'permalink-manager', PERMALINK_MANAGER_URL . '/out/permalink-manager-admin.css', array( 'permalink-manager-plugins' ), PERMALINK_MANAGER_VERSION );
|
||||
|
||||
wp_enqueue_script( 'permalink-manager-plugins', PERMALINK_MANAGER_URL . '/out/permalink-manager-plugins.js', array( 'jquery', ), PERMALINK_MANAGER_VERSION, array( 'in_footer' => false ) );
|
||||
wp_enqueue_script( 'permalink-manager', PERMALINK_MANAGER_URL . '/out/permalink-manager-admin.js', array( 'jquery', 'permalink-manager-plugins' ), PERMALINK_MANAGER_VERSION, array( 'in_footer' => false ) );
|
||||
|
||||
if ( isset( $_GET['section'] ) && $_GET['section'] === 'permastructs' ) {
|
||||
wp_enqueue_script( 'thickbox' );
|
||||
wp_enqueue_style( 'thickbox' );
|
||||
}
|
||||
|
||||
wp_localize_script( 'permalink-manager', 'permalink_manager', array(
|
||||
'ajax_url' => admin_url( 'admin-ajax.php' ),
|
||||
'url' => PERMALINK_MANAGER_URL,
|
||||
'confirm' => __( 'Are you sure? This action cannot be undone!', 'permalink-manager' ),
|
||||
'spinners' => admin_url( 'images' )
|
||||
) );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the URL of the plugin's dashboard
|
||||
*
|
||||
* @param string $append
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function get_admin_url( $append = '' ) {
|
||||
//return menu_page_url(PERMALINK_MANAGER_PLUGIN_SLUG, false) . $append;
|
||||
$admin_page = sprintf( "tools.php?page=%s", PERMALINK_MANAGER_PLUGIN_SLUG . $append );
|
||||
|
||||
return admin_url( $admin_page );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add shortcut links for Permalink Manager on "Plugins" page
|
||||
*
|
||||
* @param array $links
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function plugins_page_links( $links ) {
|
||||
$new_links = array(
|
||||
sprintf( '<a href="%s">%s</a>', $this->get_admin_url(), __( 'URI Editor', 'permalink-manager' ) ),
|
||||
sprintf( '<a href="%s">%s</a>', $this->get_admin_url( '§ion=settings' ), __( 'Settings', 'permalink-manager' ) ),
|
||||
);
|
||||
|
||||
return array_merge( $links, $new_links );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add shortcut meta links for Permalink Manager on "Plugins" page
|
||||
*
|
||||
* @param array $links
|
||||
* @param string $file
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function plugins_page_meta( $links, $file ) {
|
||||
if ( $file == PERMALINK_MANAGER_BASENAME ) {
|
||||
$new_links = array(
|
||||
'doc' => sprintf( '<a href="%s?utm_source=plugin_admin_page" target="_blank">%s</a>', 'https://permalinkmanager.pro/docs/', __( 'Documentation', 'permalink-manager' ) )
|
||||
);
|
||||
|
||||
if ( ! defined( 'PERMALINK_MANAGER_PRO' ) ) {
|
||||
$new_links['upgrade'] = sprintf( '<a href="%s" target="_blank"><strong>%s</strong></a>', PERMALINK_MANAGER_PROMO, __( 'Buy Permalink Manager Pro', 'permalink-manager' ) );
|
||||
}
|
||||
|
||||
$links = array_merge( $links, $new_links );
|
||||
}
|
||||
|
||||
return $links;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if URI Editor should be displayed for current user
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function current_user_can_edit_uris() {
|
||||
global $permalink_manager_options;
|
||||
|
||||
$edit_uris_cap = ( ! empty( $permalink_manager_options['general']['edit_uris_cap'] ) ) ? $permalink_manager_options['general']['edit_uris_cap'] : 'publish_posts';
|
||||
|
||||
return current_user_can( $edit_uris_cap );
|
||||
}
|
||||
|
||||
/**
|
||||
* Display global notices (throughout wp-admin dashboard)
|
||||
*/
|
||||
function display_global_notices() {
|
||||
global $permalink_manager_alerts, $active_section;
|
||||
|
||||
$html = "";
|
||||
if ( ! empty( $permalink_manager_alerts ) && is_array( $permalink_manager_alerts ) ) {
|
||||
foreach ( $permalink_manager_alerts as $alert_id => $alert ) {
|
||||
$dismissed_transient_name = sprintf( 'permalink-manager-notice_%s', sanitize_title( $alert_id ) );
|
||||
$dismissed = get_transient( $dismissed_transient_name );
|
||||
|
||||
// Check if alert was dismissed
|
||||
if ( empty( $dismissed ) ) {
|
||||
// Hide notice in Permalink Manager Pro
|
||||
if ( defined( 'PERMALINK_MANAGER_PRO' ) && $alert['show'] == 'pro_hide' ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Display the notice only on the plugin pages
|
||||
if ( empty( $active_section ) && ! empty( $alert['plugin_only'] ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check if the notice did not expire
|
||||
if ( isset( $alert['until'] ) && ( time() > strtotime( $alert['until'] ) ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$html .= Permalink_Manager_UI_Elements::get_alert_message( $alert['txt'], $alert['type'], true, $alert_id );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
echo wp_kses_post( $html );
|
||||
}
|
||||
|
||||
/**
|
||||
* Display notices generated by Permalink Manager tools
|
||||
*/
|
||||
function display_plugin_notices() {
|
||||
global $permalink_manager_before_sections_html;
|
||||
|
||||
echo wp_kses_post( $permalink_manager_before_sections_html );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of all duplicated redirects and custom permalinks
|
||||
*
|
||||
* @param bool $include_custom_uris
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function get_all_duplicates( $include_custom_uris = true ) {
|
||||
global $permalink_manager_redirects;
|
||||
|
||||
// Make sure that both variables are arrays
|
||||
$all_uris = ( $include_custom_uris ) ? Permalink_Manager_URI_Functions::get_all_uris() : array();
|
||||
$permalink_manager_redirects = ( is_array( $permalink_manager_redirects ) ) ? $permalink_manager_redirects : array();
|
||||
|
||||
// Convert redirects list, so it can be merged with custom permalinks array
|
||||
foreach ( $permalink_manager_redirects as $element_id => $redirects ) {
|
||||
if ( is_array( $redirects ) ) {
|
||||
foreach ( $redirects as $index => $uri ) {
|
||||
$all_uris["redirect-{$index}_{$element_id}"] = $uri;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Count duplicates
|
||||
$duplicates_groups = array();
|
||||
$duplicates_list = array_count_values( $all_uris );
|
||||
$duplicates_list = array_filter( $duplicates_list, function ( $x ) {
|
||||
return $x >= 2;
|
||||
} );
|
||||
|
||||
// Assign keys to duplicates (group them)
|
||||
if ( count( $duplicates_list ) > 0 ) {
|
||||
foreach ( $duplicates_list as $duplicated_uri => $count ) {
|
||||
$duplicated_ids = array_keys( $all_uris, $duplicated_uri );
|
||||
|
||||
// Ignore duplicates in different langauges
|
||||
if ( Permalink_Manager_URI_Functions::is_uri_duplicated( $duplicated_uri, $duplicated_ids[0], $duplicated_ids ) ) {
|
||||
$duplicates_groups[ $duplicated_uri ] = $duplicated_ids;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $duplicates_groups;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if Permalink Manager Pro is active
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function is_pro_active() {
|
||||
if ( defined( 'PERMALINK_MANAGER_PRO' ) && class_exists( 'Permalink_Manager_Pro_License' ) ) {
|
||||
// Check if license is active
|
||||
$exp_date = Permalink_Manager_Pro_License::get_expiration_date( true );
|
||||
|
||||
$is_pro = ( $exp_date > 2 ) ? false : true;
|
||||
} else {
|
||||
$is_pro = false;
|
||||
}
|
||||
|
||||
return $is_pro;
|
||||
}
|
||||
}
|
||||
+980
@@ -0,0 +1,980 @@
|
||||
<?php
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) exit;
|
||||
|
||||
/**
|
||||
* Core functions
|
||||
*/
|
||||
class Permalink_Manager_Core_Functions {
|
||||
|
||||
public function __construct() {
|
||||
add_action( 'init', array( $this, 'init_hooks' ), 99 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add hooks used by plugin to change the way the permalinks are detected
|
||||
*
|
||||
* @return false|void
|
||||
*/
|
||||
function init_hooks() {
|
||||
global $permalink_manager_options;
|
||||
|
||||
// Trailing slashes
|
||||
add_filter( 'permalink_manager_filter_final_term_permalink', array( $this, 'control_trailing_slashes' ), 9 );
|
||||
add_filter( 'permalink_manager_filter_final_post_permalink', array( $this, 'control_trailing_slashes' ), 9 );
|
||||
add_filter( 'permalink_manager_filter_post_sample_uri', array( $this, 'control_trailing_slashes' ), 9 );
|
||||
add_filter( 'wpseo_canonical', array( $this, 'control_trailing_slashes' ), 9 );
|
||||
add_filter( 'wpseo_opengraph_url', array( $this, 'control_trailing_slashes' ), 9 );
|
||||
add_filter( 'paginate_links', array( $this, 'control_trailing_slashes' ), 9 );
|
||||
|
||||
/**
|
||||
* Detect & canonical URL/redirect functions
|
||||
*/
|
||||
// Do not trigger in back-end
|
||||
if ( is_admin() && ! wp_doing_ajax() ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Do not trigger if Customizer is loaded
|
||||
if ( function_exists( 'is_customize_preview' ) && is_customize_preview() ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Use the URIs set in this plugin
|
||||
add_filter( 'request', array( $this, 'detect_post' ), 0, 1 );
|
||||
|
||||
if ( ! is_admin() ) {
|
||||
// Redirect from old URIs to new URIs + adjust canonical redirect settings
|
||||
add_action( 'template_redirect', array( $this, 'new_uri_redirect_and_404' ), 1 );
|
||||
add_action( 'wp', array( $this, 'adjust_canonical_redirect' ), 1 );
|
||||
|
||||
// Case-insensitive permalinks
|
||||
if ( ! empty( $permalink_manager_options['general']['case_insensitive_permalinks'] ) ) {
|
||||
add_action( 'parse_request', array( $this, 'case_insensitive_permalinks' ), 0 );
|
||||
}
|
||||
// Force 404 on non-existing pagination pages
|
||||
if ( ! empty( $permalink_manager_options['general']['pagination_redirect'] ) ) {
|
||||
add_action( 'wp', array( $this, 'fix_pagination_pages' ), 0 );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the request array used by WordPress to load specific content item (post, term, archive, etc.)
|
||||
*
|
||||
* @param array $query
|
||||
* @param bool $request_url
|
||||
* @param bool $return_object
|
||||
*
|
||||
* @return array|WP_Post|WP_Term
|
||||
*/
|
||||
public static function detect_post( $query, $request_url = false, $return_object = false ) {
|
||||
global $wp, $wp_rewrite, $permalink_manager_uris, $permalink_manager_options, $pm_query;
|
||||
|
||||
// Check if the array with custom URIs is set
|
||||
if ( ! ( is_array( $permalink_manager_uris ) ) ) {
|
||||
return $query;
|
||||
}
|
||||
|
||||
// Used in debug mode & endpoints
|
||||
$old_query = ( ! empty( $request_url ) && empty( $query ) ) ? false : $query;
|
||||
|
||||
/**
|
||||
* 1. Prepare URL and check if it is correct (make sure that both requested URL & home_url share the same protocol and get rid of www prefix)
|
||||
*/
|
||||
$request_url = ( ! empty( $request_url ) ) ? parse_url( $request_url, PHP_URL_PATH ) : $_SERVER['REQUEST_URI'];
|
||||
$request_url = ( ! empty( $request_url ) ) ? strtok( $request_url, "?" ) : $request_url;
|
||||
|
||||
// Make sure that either $_SERVER['SERVER_NAME'] or $_SERVER['HTTP_HOST'] are set
|
||||
if ( empty( $_SERVER['HTTP_HOST'] ) && empty( $_SERVER['SERVER_NAME'] ) ) {
|
||||
return $query;
|
||||
}
|
||||
|
||||
$http_host = ( ! empty( $_SERVER['HTTP_HOST'] ) ) ? $_SERVER['HTTP_HOST'] : preg_replace( '/www\./i', '', $_SERVER['SERVER_NAME'] );
|
||||
$request_url = sprintf( "http://%s%s", str_replace( "www.", "", $http_host ), $request_url );
|
||||
$raw_home_url = trim( get_option( 'home' ) );
|
||||
$home_url = preg_replace( "/http(s)?:\/\/(www\.)?(.+?)\/?$/", "http://$3", $raw_home_url );
|
||||
|
||||
if ( parse_url( $request_url, PHP_URL_HOST ) ) {
|
||||
// Check if "Deep Detect" is enabled
|
||||
$deep_detect_enabled = apply_filters( 'permalink_manager_deep_uri_detect', true );
|
||||
|
||||
// Sanitize the URL
|
||||
// $request_url = filter_var($request_url, FILTER_SANITIZE_URL);
|
||||
|
||||
// Keep only the URI
|
||||
$request_url = str_replace( $home_url, "", $request_url );
|
||||
|
||||
// Hotfix for language plugins
|
||||
if ( filter_var( $request_url, FILTER_VALIDATE_URL ) ) {
|
||||
$request_url = parse_url( $request_url, PHP_URL_PATH );
|
||||
}
|
||||
|
||||
$request_url = trim( $request_url, "/" );
|
||||
|
||||
// Get all the endpoints & pattern
|
||||
$endpoints = Permalink_Manager_Helper_Functions::get_endpoints();
|
||||
$pattern = "/^(.+?)(?|\/({$endpoints})(?|\/(.*)|$)|\/()([\d]+)\/?)?$/i";
|
||||
|
||||
// Use default REGEX to detect post
|
||||
preg_match( $pattern, $request_url, $regex_parts );
|
||||
$uri_parts['lang'] = false;
|
||||
$uri_parts['uri'] = ( ! empty( $regex_parts[1] ) ) ? $regex_parts[1] : "";
|
||||
$uri_parts['endpoint'] = ( ! empty( $regex_parts[2] ) ) ? $regex_parts[2] : "";
|
||||
$uri_parts['endpoint_value'] = ( ! empty( $regex_parts[3] ) ) ? $regex_parts[3] : "";
|
||||
|
||||
// Allow to filter the results by third-parties + store the URI parts with $pm_query global
|
||||
$uri_parts = apply_filters( 'permalink_manager_detect_uri', $uri_parts, $request_url, $endpoints );
|
||||
|
||||
// Support comment pages
|
||||
preg_match( "/(.*)\/{$wp_rewrite->comments_pagination_base}-([\d]+)/", $uri_parts['uri'], $regex_parts );
|
||||
if ( ! empty( $regex_parts[2] ) ) {
|
||||
$uri_parts['uri'] = $regex_parts[1];
|
||||
$uri_parts['endpoint'] = 'cpage';
|
||||
$uri_parts['endpoint_value'] = $regex_parts[2];
|
||||
}
|
||||
|
||||
// Support pagination endpoint
|
||||
if ( ! empty( $wp_rewrite->pagination_base ) && $uri_parts['endpoint'] == $wp_rewrite->pagination_base ) {
|
||||
$uri_parts['endpoint'] = 'page';
|
||||
}
|
||||
|
||||
// Stop the function if $uri_parts is empty
|
||||
if ( empty( $uri_parts ) ) {
|
||||
return $query;
|
||||
}
|
||||
|
||||
// Store the URI parts in a separate global variable
|
||||
$pm_query = $uri_parts;
|
||||
|
||||
// Get the URI parts from REGEX parts
|
||||
// $lang = $uri_parts['lang'];
|
||||
$uri = $uri_parts['uri'];
|
||||
$endpoint = $uri_parts['endpoint'];
|
||||
$endpoint_value = $uri_parts['endpoint_value'];
|
||||
|
||||
// Trim slashes
|
||||
$uri = trim( $uri, "/" );
|
||||
|
||||
// Ignore URLs with no URI grabbed
|
||||
if ( empty( $uri ) ) {
|
||||
return $query;
|
||||
}
|
||||
|
||||
// Check what content type should be loaded in case of duplicate ("posts" or "terms")
|
||||
$duplicates_priority = apply_filters( 'permalink_manager_duplicates_priority', false );
|
||||
|
||||
/**
|
||||
* 2. Check if the requested URI matches any custom permalink assigned to a post or term
|
||||
*/
|
||||
$uri_query_iteration = 1;
|
||||
$element_object = '';
|
||||
$excluded_ids = array();
|
||||
|
||||
do {
|
||||
// Store an array with custom permalinks in a separate variable
|
||||
$all_uris = $permalink_manager_uris;
|
||||
|
||||
// Remove empty rows
|
||||
$all_uris = array_filter( $all_uris );
|
||||
|
||||
// In case of multiple elements using the same URI, the function will follow the "permalink_manager_duplicates_priority" filter value to determine whether terms or posts should be ignored
|
||||
if ( $duplicates_priority ) {
|
||||
$duplicated_uris = array_keys( $all_uris, $uri );
|
||||
$duplicates_removed = 0;
|
||||
$duplicates_count = count( $duplicated_uris );
|
||||
|
||||
if ( $duplicates_count > 1 ) {
|
||||
foreach ( $duplicated_uris as $duplicated_uri_id ) {
|
||||
if ( ( $duplicates_priority == 'posts' && ! is_numeric( $duplicated_uri_id ) ) || ( $duplicates_priority !== 'posts' && is_numeric( $duplicated_uri_id ) ) ) {
|
||||
$duplicates_removed ++;
|
||||
|
||||
if ( $duplicates_removed < $duplicates_count ) {
|
||||
$excluded_ids[] = $duplicated_uri_id;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If the element was excluded in the previous iteration add it to the array
|
||||
if ( ! empty( $excluded ) ) {
|
||||
$excluded_ids[] = $excluded;
|
||||
}
|
||||
$excluded = '';
|
||||
|
||||
// Exclude all the element detected in the previous iterations
|
||||
if ( ! empty( $excluded_ids ) ) {
|
||||
$excluded_ids = array_unique( $excluded_ids );
|
||||
foreach ( $excluded_ids as $excluded_element ) {
|
||||
unset( $all_uris[ $excluded_element ] );
|
||||
}
|
||||
}
|
||||
|
||||
// Flip array for better performance
|
||||
$all_uris = array_flip( $all_uris );
|
||||
|
||||
// Attempt 1.
|
||||
// Find the element ID
|
||||
$element_id = isset( $all_uris[ $uri ] ) ? $all_uris[ $uri ] : false;
|
||||
|
||||
// Attempt 2.
|
||||
// Decode both request URI & URIs array & make them lowercase (and save in a separate variable)
|
||||
if ( empty( $element_id ) ) {
|
||||
$uri = strtolower( urldecode( $uri ) );
|
||||
|
||||
foreach ( $all_uris as $raw_uri => $uri_id ) {
|
||||
$raw_uri = strtolower( urldecode( $raw_uri ) );
|
||||
$all_uris[ $raw_uri ] = $uri_id;
|
||||
}
|
||||
|
||||
$element_id = isset( $all_uris[ $uri ] ) ? $all_uris[ $uri ] : $element_id;
|
||||
}
|
||||
|
||||
// Attempt 3.
|
||||
// Check custom permalinks with endpoints included
|
||||
if ( $deep_detect_enabled && ! empty( $uri_parts['endpoint_value'] ) ) {
|
||||
// Check again in case someone used post/tax IDs instead of slugs
|
||||
if ( empty( $uri_parts['endpoint'] ) && is_numeric( $uri_parts['endpoint_value'] ) ) {
|
||||
$uri_alt = sprintf( '%s/%s', $uri, $uri_parts['endpoint_value'] );
|
||||
} // Check again for attachments' custom permalinks
|
||||
else if ( ! empty( $uri_parts['endpoint'] ) && $uri_parts['endpoint'] == 'attachment' ) {
|
||||
$uri_alt = sprintf( '%s/%s/%s', $uri, $uri_parts['endpoint'], $uri_parts['endpoint_value'] );
|
||||
}
|
||||
|
||||
if ( ! empty( $uri_alt ) && isset( $all_uris[ $uri_alt ] ) ) {
|
||||
$element_id = $all_uris[ $uri_alt ];
|
||||
$endpoint_value = $endpoint = "";
|
||||
}
|
||||
}
|
||||
|
||||
// Allow to filter the item_id by third-parties after initial detection
|
||||
$element_id = apply_filters( 'permalink_manager_detected_element_id', $element_id, $uri_parts, $request_url );
|
||||
|
||||
// Clear the original query before it is filtered
|
||||
$query = ( $element_id ) ? array() : $query;
|
||||
|
||||
/**
|
||||
* 2A. Custom URI assigned to taxonomy
|
||||
*/
|
||||
if ( strpos( $element_id, 'tax-' ) !== false ) {
|
||||
// Remove the "tax-" prefix
|
||||
$term_element_id = intval( preg_replace( "/[^0-9]/", "", $element_id ) );
|
||||
|
||||
// Filter detected post ID
|
||||
$term_element_id = apply_filters( 'permalink_manager_detected_term_id', $term_element_id, $uri_parts, true, $old_query );
|
||||
|
||||
// Get the variables to filter wp_query and double-check if taxonomy exists
|
||||
$term = $element_object = ( ! empty( $term_element_id ) && is_numeric( $term_element_id ) ) ? get_term( $term_element_id ) : false;
|
||||
$term_taxonomy = ( ! empty( $term->taxonomy ) ) ? $term->taxonomy : false;
|
||||
$term_taxonomy_object = ( ! empty( $term_taxonomy ) ) ? get_taxonomy( $term_taxonomy ) : '';
|
||||
|
||||
// Check if term is allowed
|
||||
$disabled = ( $term_taxonomy_object && Permalink_Manager_Helper_Functions::is_term_excluded( $term ) ) ? true : false;
|
||||
|
||||
// Proceed only if the term is not removed and its taxonomy is not disabled
|
||||
if ( ! $disabled && $term_taxonomy_object ) {
|
||||
$term_ancestors = get_ancestors( $element_id, $term_taxonomy );
|
||||
$final_uri = $term->slug;
|
||||
|
||||
// Fix for hierarchical terms
|
||||
if ( ! empty( $term_ancestors ) ) {
|
||||
foreach ( $term_ancestors as $parent_id ) {
|
||||
$parent = get_term( $parent_id, $term_taxonomy );
|
||||
if ( ! empty( $parent->slug ) ) {
|
||||
$final_uri = $parent->slug . '/' . $final_uri;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ( empty( $term_taxonomy_object->query_var ) ) {
|
||||
$query["taxonomy"] = $term_taxonomy;
|
||||
$query["term"] = $term->slug;
|
||||
} else {
|
||||
$query[ $term_taxonomy_object->query_var ] = $term->slug;
|
||||
}
|
||||
} else if ( $disabled ) {
|
||||
$broken_uri = true;
|
||||
$query = $old_query;
|
||||
$excluded = $element_id;
|
||||
} else {
|
||||
$query = $old_query;
|
||||
$excluded = $element_id;
|
||||
}
|
||||
} /**
|
||||
* 2B. Custom URI assigned to post/page/CPT item
|
||||
*/ else if ( isset( $element_id ) && is_numeric( $element_id ) ) {
|
||||
// Fix for revisions
|
||||
$is_revision = wp_is_post_revision( $element_id );
|
||||
if ( $is_revision ) {
|
||||
$revision_id = $element_id;
|
||||
$element_id = $is_revision;
|
||||
}
|
||||
|
||||
// Filter detected post ID
|
||||
$post_element_id = apply_filters( 'permalink_manager_detected_post_id', $element_id, $uri_parts, false, $old_query );
|
||||
|
||||
$post_to_load = $element_object = ( ! empty( $post_element_id ) && is_numeric( $post_element_id ) ) ? get_post( $post_element_id ) : false;
|
||||
$final_uri = ( ! empty( $post_to_load->post_name ) ) ? $post_to_load->post_name : false;
|
||||
$post_type = ( ! empty( $post_to_load->post_type ) ) ? $post_to_load->post_type : false;
|
||||
|
||||
// Check if post is allowed
|
||||
$disabled = ( $post_type && Permalink_Manager_Helper_Functions::is_post_excluded( $post_to_load, true ) ) ? true : false;
|
||||
|
||||
// Proceed only if the term is not removed and its taxonomy is not disabled
|
||||
if ( ! $disabled && $post_type ) {
|
||||
$post_type_object = get_post_type_object( $post_type );
|
||||
|
||||
// Fix for hierarchical CPT & pages
|
||||
if ( ! ( empty( $post_to_load->ancestors ) ) && ! empty( $post_type_object->hierarchical ) ) {
|
||||
foreach ( $post_to_load->ancestors as $parent ) {
|
||||
$parent = get_post( $parent );
|
||||
if ( $parent && $parent->post_name ) {
|
||||
$final_uri = $parent->post_name . '/' . $final_uri;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Alter the final query array
|
||||
if ( $post_to_load->post_status == 'private' && ( ! is_user_logged_in() || current_user_can( 'read_private_posts', $element_id ) !== true ) ) {
|
||||
$element_id = 0;
|
||||
$query = $old_query;
|
||||
} else if ( $post_to_load->post_status == 'draft' || empty( $final_uri ) ) {
|
||||
// A. The draft permalinks should be allowed for logged-in users
|
||||
if ( is_user_logged_in() ) {
|
||||
if ( $post_type == 'page' ) {
|
||||
$query['page_id'] = $element_id;
|
||||
} else {
|
||||
$query['p'] = $element_id;
|
||||
}
|
||||
|
||||
$query['preview'] = true;
|
||||
$query['post_type'] = $post_type;
|
||||
} // B. The draft permalinks should be disabled for non-logged-in visitors
|
||||
else if ( $post_to_load->post_status == 'draft' ) {
|
||||
$query['pagename'] = '-';
|
||||
$query['error'] = '404';
|
||||
|
||||
$element_id = 0;
|
||||
} else {
|
||||
$query = $old_query;
|
||||
$excluded = $element_id;
|
||||
}
|
||||
} else if ( $post_type == 'page' ) {
|
||||
$query['pagename'] = $final_uri;
|
||||
// $query['post_type'] = $post_type;
|
||||
} else if ( $post_type == 'post' ) {
|
||||
$query['name'] = $final_uri;
|
||||
} else if ( $post_type == 'attachment' ) {
|
||||
$query['attachment'] = $final_uri;
|
||||
} else {
|
||||
// Get the query var
|
||||
$query_var = ( ! empty( $post_type_object->query_var ) ) ? $post_type_object->query_var : $post_type;
|
||||
|
||||
$query['name'] = $final_uri;
|
||||
$query['post_type'] = $post_type;
|
||||
$query[ $query_var ] = $final_uri;
|
||||
}
|
||||
} else if ( $disabled ) {
|
||||
$broken_uri = true;
|
||||
$query = $old_query;
|
||||
$excluded = $element_id;
|
||||
} else {
|
||||
$query = $old_query;
|
||||
$excluded = $element_id;
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-remove removed term custom URI & redirects (works if enabled in plugin settings)
|
||||
if ( ! empty( $broken_uri ) && ( ! empty( $permalink_manager_options['general']['auto_fix_duplicates'] ) ) && $permalink_manager_options['general']['auto_fix_duplicates'] == 1 ) {
|
||||
// Do not trigger if WP Rocket cache plugin is turned on
|
||||
if ( ! defined( 'WP_ROCKET_VERSION' ) && is_array( $permalink_manager_uris ) ) {
|
||||
$broken_element_id = ( ! empty( $revision_id ) ) ? $revision_id : $element_id;
|
||||
$remove_broken_uri = ( ! empty( $broken_element_id ) ) ? Permalink_Manager_Actions::force_clear_single_element_uris_and_redirects( $broken_element_id ) : '';
|
||||
|
||||
// Reload page if success
|
||||
if ( $remove_broken_uri && ! headers_sent() ) {
|
||||
header( "Refresh:0" );
|
||||
exit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Overwrite the detect function and decide whether to exclude the detected item
|
||||
$excluded = apply_filters( 'permalink_manager_excluded_element_id', $excluded, $element_object, $old_query, $pm_query );
|
||||
|
||||
// Make sure the loop does not execute infinitely (limit it to 20 iterations)
|
||||
$uri_query_iteration ++;
|
||||
if ( $uri_query_iteration === 25 ) {
|
||||
break;
|
||||
}
|
||||
} // If the detected element was excluded repeat the URI query and try to find a new one
|
||||
while ( ! empty( $excluded ) );
|
||||
|
||||
/**
|
||||
* 3A. Endpoints
|
||||
*/
|
||||
if ( ! empty( $element_id ) && empty( $disabled ) && ( ! empty( $endpoint ) || ! empty( $endpoint_value ) ) ) {
|
||||
if ( is_array( $endpoint ) ) {
|
||||
foreach ( $endpoint as $endpoint_name => $endpoint_value ) {
|
||||
$query[ $endpoint_name ] = $endpoint_value;
|
||||
}
|
||||
} else if ( $endpoint == 'feed' ) {
|
||||
$feed_rewrite = true;
|
||||
|
||||
// Check if /feed/ endpoint is allowed for selected post type or taxonomy
|
||||
if ( ! empty( $post_type_object ) && is_array( $post_type_object->rewrite ) && empty( $post_type_object->rewrite['feeds'] ) ) {
|
||||
$feed_rewrite = false;
|
||||
}
|
||||
|
||||
if ( $feed_rewrite ) {
|
||||
$query[ $endpoint ] = 'feed';
|
||||
} else {
|
||||
$element_id = '';
|
||||
$query = array(
|
||||
'error' => 404
|
||||
);
|
||||
}
|
||||
} else if ( $endpoint == 'embed' ) {
|
||||
$query[ $endpoint ] = true;
|
||||
} else if ( $endpoint == 'page' ) {
|
||||
$endpoint = 'paged';
|
||||
if ( is_numeric( $endpoint_value ) ) {
|
||||
$query[ $endpoint ] = $endpoint_value;
|
||||
} else {
|
||||
$query = $old_query;
|
||||
}
|
||||
} else if ( $endpoint == 'trackback' ) {
|
||||
$endpoint = 'tb';
|
||||
$query[ $endpoint ] = 1;
|
||||
} else if ( empty( $endpoint ) && is_numeric( $endpoint_value ) ) {
|
||||
$query['page'] = $endpoint_value;
|
||||
} else {
|
||||
$query[ $endpoint ] = $endpoint_value;
|
||||
}
|
||||
|
||||
// Fix for attachments
|
||||
if ( ! empty( $query['attachment'] ) ) {
|
||||
$query = array( 'attachment' => $query['attachment'], 'do_not_redirect' => 1 );
|
||||
} else if ( isset( $query['attachment'] ) ) {
|
||||
$query = $old_query;
|
||||
$element_id = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 3B. Endpoints - check if any endpoint is set with $_GET parameter
|
||||
*/
|
||||
if ( ! empty( $element_id ) && $deep_detect_enabled && ! empty( $_GET ) ) {
|
||||
$get_endpoints = array_intersect( $wp->public_query_vars, array_keys( $_GET ) );
|
||||
|
||||
if ( ! empty( $get_endpoints ) ) {
|
||||
// Append query vars from $_GET parameters
|
||||
foreach ( $get_endpoints as $endpoint ) {
|
||||
// Numeric endpoints
|
||||
$endpoint_value = ( in_array( $endpoint, array( 'page', 'paged', 'attachment_id' ) ) ) ? filter_var( $_GET[ $endpoint ], FILTER_SANITIZE_NUMBER_INT ) : $_GET[ $endpoint ];
|
||||
|
||||
// Ignore page endpoint if its value is empty or equal to 1
|
||||
if ( in_array( $endpoint, array( 'page', 'paged' ) ) && ( empty( $endpoint_value ) || $endpoint_value == 1 ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Replace whitespaces with '+' (for YITH WooCommerce Ajax Product Filter URLs only) and sanitize the value
|
||||
$endpoint_value = ( isset( $_GET['yith_wcan'] ) ) ? preg_replace( '/\s+/', '+', $endpoint_value ) : $endpoint_value;
|
||||
$query[ $endpoint ] = sanitize_text_field( $endpoint_value );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 4. Set global with detected item id
|
||||
*/
|
||||
if ( ! empty( $element_id ) && empty( $disabled ) && empty( $excluded ) ) {
|
||||
if ( ! empty( $element_object->taxonomy ) ) {
|
||||
$pm_query['id'] = $element_object->term_id;
|
||||
$content_type = "Taxonomy: {$element_object->taxonomy}";
|
||||
} else if ( ! empty( $element_object->post_type ) ) {
|
||||
$pm_query['id'] = $element_object->ID;
|
||||
$content_type = "Post type: {$element_object->post_type}";
|
||||
}
|
||||
|
||||
// If language mismatch is detected do not set 'do_not_redirect' to allow canonical redirect
|
||||
if ( is_array( $query ) && ( empty( $pm_query['flag'] ) || $pm_query['flag'] !== 'language_mismatch' ) ) {
|
||||
$query['do_not_redirect'] = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 5. Debug data
|
||||
*/
|
||||
if ( empty ( $element_object ) || empty ( $content_type ) ) {
|
||||
$content_type = $element_object = '';
|
||||
}
|
||||
|
||||
$uri_parts = ( ! empty( $uri_parts ) ) ? $uri_parts : '';
|
||||
$query = apply_filters( 'permalink_manager_filter_query', $query, $old_query, $uri_parts, $pm_query, $content_type, $element_object );
|
||||
|
||||
if ( $return_object && ! empty( $element_object ) ) {
|
||||
return $element_object;
|
||||
} else {
|
||||
return $query;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Trailing slash & remove BOM and double slashes
|
||||
*
|
||||
* @param string $permalink
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
static function control_trailing_slashes( $permalink ) {
|
||||
global $permalink_manager_options;
|
||||
|
||||
// Ignore empty & numeric permalinks
|
||||
if ( empty( $permalink ) || is_numeric( $permalink ) ) {
|
||||
return $permalink;
|
||||
}
|
||||
|
||||
// Keep the original permalink in a separate variable
|
||||
$original_permalink = $permalink;
|
||||
$permalink_path = parse_url( $original_permalink, PHP_URL_PATH );
|
||||
$permalink_path = ( ! empty( $permalink_path ) ) ? trim( $permalink_path, '/' ) : $permalink_path;
|
||||
|
||||
$trailing_slash_mode = ( ! empty( $permalink_manager_options['general']['trailing_slashes'] ) ) ? $permalink_manager_options['general']['trailing_slashes'] : "";
|
||||
|
||||
// Ignore homepage URLs
|
||||
if ( filter_var( $permalink, FILTER_VALIDATE_URL ) && empty( $permalink_path ) ) {
|
||||
return $permalink;
|
||||
}
|
||||
|
||||
// Always remove trailing slashes from URLs/URIs that end with file extension (e.g. html)
|
||||
if ( preg_match( '/(http(?:s)\:\/\/[^\/]+\/)?.*\.([a-zA-Z]{3,4})[\/]*(\?[^\/]+|$)/', $permalink ) ) {
|
||||
$trailing_slash_mode = 2;
|
||||
}
|
||||
|
||||
// Add trailing slashes
|
||||
if ( in_array( $trailing_slash_mode, array( 1, 10 ) ) ) {
|
||||
$permalink = preg_replace( '/(.+?)([\/]*)([\?\#][^\/]+|$)/', '$1/$3', $permalink ); // Instead of trailingslashit()
|
||||
} // Remove trailing slashes
|
||||
else if ( in_array( $trailing_slash_mode, array( 2, 20 ) ) ) {
|
||||
$permalink = preg_replace( '/(.+?)([\/]*)([\?\#][^\/]+|$)/', '$1$3', $permalink ); // Instead of untrailingslashit()
|
||||
} // Default settings
|
||||
else {
|
||||
$permalink = user_trailingslashit( $permalink );
|
||||
}
|
||||
|
||||
// Remove double slashes
|
||||
$permalink = preg_replace( '/(?<!:)(\/{2,})/', '/', $permalink );
|
||||
|
||||
// Remove trailing slashes from URLs that end with query string or anchors
|
||||
$permalink = preg_replace( '/([\?\#]{1}[^\/]+)([\/]+)$/', '$1', $permalink );
|
||||
|
||||
return apply_filters( 'permalink_manager_control_trailing_slashes', $permalink, $original_permalink );
|
||||
}
|
||||
|
||||
/**
|
||||
* Display 404 if requested page does not exist in pagination or the pagination format is incorrect
|
||||
*/
|
||||
function fix_pagination_pages() {
|
||||
global $wp_query, $pm_query, $post, $permalink_manager_options;
|
||||
|
||||
// 1. Check if the custom permalink was detected
|
||||
if ( empty( $pm_query['id'] ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. Get the queried object
|
||||
$object = get_queried_object();
|
||||
|
||||
if ( ! empty( $object ) && ! empty( $object->taxonomy ) ) {
|
||||
$term = $object;
|
||||
} else if ( ! empty( $object->post_type ) ) {
|
||||
$post = $object;
|
||||
} else if ( empty( $object ) && ! empty( $wp_query->post ) ) {
|
||||
$post = $wp_query->post;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
// 3.1. Validate the pages count
|
||||
if ( ( ! empty( $post->post_type ) && isset( $post->post_content ) ) || ( isset( $wp_query->max_num_pages ) && ! empty( $term->taxonomy ) ) ) {
|
||||
$current_page = ( ! empty( $wp_query->query_vars['page'] ) ) ? $wp_query->query_vars['page'] : 1;
|
||||
$current_page = ( empty( $wp_query->query_vars['page'] ) && ! empty( $wp_query->query_vars['paged'] ) ) ? $wp_query->query_vars['paged'] : $current_page;
|
||||
|
||||
// 2.1B. Count post pages
|
||||
$post_content = ( ! empty( $post->post_content ) ) ? $post->post_content : '';
|
||||
$num_pages = ( is_home() || is_archive() || is_search() ) ? $wp_query->max_num_pages : substr_count( strtolower( $post_content ), '<!--nextpage-->' ) + 1;
|
||||
|
||||
$is_404 = ( $current_page > 1 && ( $current_page > $num_pages ) ) ? true : false;
|
||||
} // 3.2. Force 404 if no posts are loaded
|
||||
else if ( ! empty( $wp_query->query['paged'] ) && $wp_query->post_count == 0 ) {
|
||||
$is_404 = true;
|
||||
}
|
||||
|
||||
// 3.4. Force 404 if endpoint value is not set or not numeric
|
||||
if ( ! empty( $pm_query['endpoint'] ) && $pm_query['endpoint'] == 'page' && ( empty( $pm_query['endpoint_value'] ) || ! is_numeric( $pm_query['endpoint_value'] ) ) ) {
|
||||
$is_404 = true;
|
||||
}
|
||||
|
||||
// 4. Block non-existent pages (Force 404 error or allow canonical redirect)
|
||||
if ( ! empty( $is_404 ) ) {
|
||||
$pagination_mode = ( ! empty( $permalink_manager_options['general']['pagination_redirect'] ) ) ? $permalink_manager_options['general']['pagination_redirect'] : false;
|
||||
|
||||
// Make sure that canonical redirect is not disabled in adjust_canonical_redirect() method
|
||||
if ( $pagination_mode == 2 ) {
|
||||
$wp_query->query_vars['do_not_redirect'] = 0;
|
||||
} else {
|
||||
$wp_query->query = $wp_query->queried_object = $wp_query->queried_object_id = $pm_query = $post = null;
|
||||
$wp_query->set_404();
|
||||
status_header( 404 );
|
||||
nocache_headers();
|
||||
}
|
||||
|
||||
$pm_query = '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enhance the existing canonical redirect functionality, allowing users define custom redirects and support custom permalinks
|
||||
*/
|
||||
function new_uri_redirect_and_404() {
|
||||
global $wp_query, $wp, $wp_rewrite, $wpdb, $permalink_manager_uris, $permalink_manager_redirects, $permalink_manager_external_redirects, $permalink_manager_options, $pm_query;
|
||||
|
||||
// Get the redirection mode & trailing slashes settings
|
||||
$redirect_mode = ( ! empty( $permalink_manager_options['general']['redirect'] ) ) ? $permalink_manager_options['general']['redirect'] : false;
|
||||
$trailing_slashes_mode = ( ! empty( $permalink_manager_options['general']['trailing_slashes'] ) ) ? $permalink_manager_options['general']['trailing_slashes'] : false;
|
||||
$trailing_slashes_redirect = ( ! empty( $permalink_manager_options['general']['trailing_slashes_redirect'] ) ) ? $permalink_manager_options['general']['trailing_slashes_redirect'] : false;
|
||||
$extra_redirects = ( ! empty( $permalink_manager_options['general']['extra_redirects'] ) ) ? $permalink_manager_options['general']['extra_redirects'] : false;
|
||||
$canonical_redirect = ( ! empty( $permalink_manager_options['general']['canonical_redirect'] ) ) ? $permalink_manager_options['general']['canonical_redirect'] : false;
|
||||
$old_slug_redirect = ( ! empty( $permalink_manager_options['general']['old_slug_redirect'] ) ) ? $permalink_manager_options['general']['old_slug_redirect'] : false;
|
||||
$endpoint_redirect = ( ! empty( $permalink_manager_options['general']['endpoint_redirect'] ) ) ? $permalink_manager_options['general']['endpoint_redirect'] : false;
|
||||
$copy_query_redirect = ( ! empty( $permalink_manager_options['general']['copy_query_redirect'] ) ) ? $permalink_manager_options['general']['copy_query_redirect'] : false;
|
||||
$redirect_type = '-';
|
||||
|
||||
// Get home URL
|
||||
$home_url = rtrim( get_option( 'home' ), "/" );
|
||||
$home_dir = parse_url( $home_url, PHP_URL_PATH );
|
||||
|
||||
// Set up $correct_permalink variable
|
||||
$correct_permalink = '';
|
||||
|
||||
// Get query string & URI
|
||||
if ( empty( $_SERVER['REQUEST_URI'] ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$query_string = ( $copy_query_redirect && ! empty( $_SERVER['QUERY_STRING'] ) ) ? $_SERVER['QUERY_STRING'] : '';
|
||||
$old_uri = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH );
|
||||
$old_uri = $old_uri_abs = ( empty( $old_uri ) ) ? strtok( $_SERVER["REQUEST_URI"], '?' ) : $old_uri;
|
||||
|
||||
// Fix for WP installed in directories (remove the directory name from the URI)
|
||||
if ( ! empty( $home_dir ) ) {
|
||||
$home_dir_regex = preg_quote( trim( $home_dir ), "/" );
|
||||
$old_uri = preg_replace( "/{$home_dir_regex}/", "", $old_uri, 1 );
|
||||
}
|
||||
|
||||
if ( is_front_page() || ( is_page() && get_option( 'show_on_front' ) === 'page' && get_queried_object_id() === (int) get_option( 'page_on_front' ) ) ) {
|
||||
$is_front_page = true;
|
||||
} else {
|
||||
$is_front_page = false;
|
||||
}
|
||||
|
||||
// Do not use custom redirects on author pages, search & front page
|
||||
if ( ! is_author() && ! $is_front_page && ! is_home() && ! is_feed() && ! is_search() && empty( $_GET['s'] ) ) {
|
||||
// Sometimes $wp_query indicates the wrong object if requested directly
|
||||
$queried_object = get_queried_object();
|
||||
|
||||
// Unset 404 if custom URI is detected
|
||||
if ( ! empty( $pm_query['id'] ) && ! empty( $queried_object->post_status ) ) {
|
||||
$wp_query->is_404 = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1A. External redirect
|
||||
*/
|
||||
if ( ! empty( $pm_query['id'] ) ) {
|
||||
if ( ! empty( $queried_object->ID ) && ! empty( $permalink_manager_external_redirects[ $queried_object->ID ] ) ) {
|
||||
$external_url = $permalink_manager_external_redirects[ $queried_object->ID ];
|
||||
} else if ( ! empty( $queried_object->term_id ) && ! empty( $permalink_manager_external_redirects["tax-{$queried_object->term_id}"] ) ) {
|
||||
$external_url = $permalink_manager_external_redirects["tax-{$queried_object->term_id}"];
|
||||
}
|
||||
|
||||
if ( ! empty( $external_url ) && filter_var( $external_url, FILTER_VALIDATE_URL ) ) {
|
||||
// Allow redirect
|
||||
$wp_query->query_vars['do_not_redirect'] = 0;
|
||||
|
||||
wp_redirect( $external_url, 301, PERMALINK_MANAGER_PLUGIN_NAME ); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- By design, the users can redirect the post/term to any external URL here
|
||||
exit();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 1B. Custom redirects
|
||||
*/
|
||||
if ( empty( $wp_query->query_vars['do_not_redirect'] ) && $extra_redirects && ! empty( $permalink_manager_redirects ) && is_array( $permalink_manager_redirects ) && ! empty( $wp->request ) && ! empty( $pm_query['uri'] ) ) {
|
||||
$uri = $pm_query['uri'];
|
||||
$endpoint_value = $pm_query['endpoint_value'];
|
||||
|
||||
// Make sure that URIs with non-ASCII characters are also detected + Check the URLs that end with number
|
||||
$decoded_url = urldecode( $uri );
|
||||
$endpoint_url = "{$uri}/{$endpoint_value}";
|
||||
|
||||
// Convert to lowercase to make case-insensitive
|
||||
$force_lowercase = apply_filters( 'permalink_manager_force_lowercase_uris', true );
|
||||
|
||||
if ( $force_lowercase ) {
|
||||
$uri = strtolower( $uri );
|
||||
$decoded_url = strtolower( $decoded_url );
|
||||
$endpoint_url = strtolower( $endpoint_url );
|
||||
}
|
||||
|
||||
// Check if the URI is not assigned to any post/term's redirects
|
||||
foreach ( $permalink_manager_redirects as $element => $redirects ) {
|
||||
if ( ! is_array( $redirects ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( in_array( $uri, $redirects ) || in_array( $decoded_url, $redirects ) || ( is_numeric( $endpoint_value ) && in_array( $endpoint_url, $redirects ) ) ) {
|
||||
// Post is detected
|
||||
if ( is_numeric( $element ) ) {
|
||||
$correct_permalink = get_permalink( $element );
|
||||
} // Term is detected
|
||||
else {
|
||||
$term_id = intval( preg_replace( "/[^0-9]/", "", $element ) );
|
||||
$correct_permalink = get_term_link( $term_id );
|
||||
}
|
||||
|
||||
// The custom redirect is found so there is no need to query the rest of array
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
$redirect_type = ( ! empty( $correct_permalink ) ) ? 'custom_redirect' : $redirect_type;
|
||||
}
|
||||
|
||||
// Ignore WP-Content links
|
||||
if ( strpos( $_SERVER['REQUEST_URI'], '/wp-content' ) !== false ) {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1C. Enhance native redirect
|
||||
*/
|
||||
if ( $canonical_redirect && empty( $wp_query->query_vars['do_not_redirect'] ) && ! empty( $queried_object ) && empty( $correct_permalink ) ) {
|
||||
// Affect only posts with custom URI and old URIs
|
||||
if ( ! empty( $queried_object->ID ) && isset( $permalink_manager_uris[ $queried_object->ID ] ) && empty( $wp_query->query['preview'] ) ) {
|
||||
// Ignore posts with specific statuses
|
||||
if ( ! ( empty( $queried_object->post_status ) ) && in_array( $queried_object->post_status, array( 'draft', 'pending', 'auto-draft', 'future' ) ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if the post is excluded
|
||||
if ( Permalink_Manager_Helper_Functions::is_post_excluded( $queried_object ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the real URL
|
||||
$correct_permalink = get_permalink( $queried_object->ID );
|
||||
} // Affect only terms with custom URI and old URIs
|
||||
else if ( ! empty( $queried_object->term_id ) && isset( $permalink_manager_uris["tax-{$queried_object->term_id}"] ) && defined( 'PERMALINK_MANAGER_PRO' ) ) {
|
||||
// Check if the term is excluded
|
||||
if ( Permalink_Manager_Helper_Functions::is_term_excluded( $queried_object ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the real URL
|
||||
$correct_permalink = get_term_link( $queried_object->term_id, $queried_object->taxonomy );
|
||||
}
|
||||
|
||||
$redirect_type = ( ! empty( $correct_permalink ) ) ? 'native_redirect' : $redirect_type;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1D. Old slug redirect
|
||||
*/
|
||||
if ( $old_slug_redirect && ! empty( $pm_query['uri'] ) && empty( $wp_query->query_vars['do_not_redirect'] ) && is_404() && empty( $correct_permalink ) ) {
|
||||
$slug = basename( $pm_query['uri'] );
|
||||
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Direct SQL query is faster here
|
||||
$post_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id from {$wpdb->postmeta} WHERE meta_key = '_wp_old_slug' AND meta_value = %s", $slug ) );
|
||||
if ( ! empty( $post_id ) && Permalink_Manager_Helper_Functions::is_post_excluded( $post_id, true, true ) !== true ) {
|
||||
$correct_permalink = get_permalink( $post_id );
|
||||
$redirect_type = 'old_slug_redirect';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 2. Prevent redirect loop
|
||||
*/
|
||||
if ( ! empty( $correct_permalink ) && is_string( $correct_permalink ) && ! empty( $wp->request ) && $redirect_type != 'slash_redirect' ) {
|
||||
$current_uri = trim( $wp->request, "/" );
|
||||
$redirect_uri = trim( parse_url( $correct_permalink, PHP_URL_PATH ), "/" );
|
||||
|
||||
$correct_permalink = ( $redirect_uri == $current_uri ) ? null : $correct_permalink;
|
||||
}
|
||||
|
||||
/**
|
||||
* 3. Add endpoints to redirect URL
|
||||
*/
|
||||
if ( ! empty( $correct_permalink ) && $endpoint_redirect && ( ! empty( $pm_query['endpoint_value'] ) || ! empty( $pm_query['endpoint'] ) ) ) {
|
||||
$endpoint_value = $pm_query['endpoint_value'];
|
||||
|
||||
if ( empty( $pm_query['endpoint'] ) && is_numeric( $endpoint_value ) ) {
|
||||
$correct_permalink = sprintf( "%s/%d", trim( $correct_permalink, "/" ), $endpoint_value );
|
||||
} else if ( isset( $pm_query['endpoint'] ) && ! empty( $endpoint_value ) ) {
|
||||
if ( $pm_query['endpoint'] == 'cpage' ) {
|
||||
$correct_permalink = sprintf( "%s/%s-%s", trim( $correct_permalink, "/" ), $wp_rewrite->comments_pagination_base, $endpoint_value );
|
||||
} else {
|
||||
$correct_permalink = sprintf( "%s/%s/%s", trim( $correct_permalink, "/" ), $pm_query['endpoint'], $endpoint_value );
|
||||
}
|
||||
} else {
|
||||
$correct_permalink = sprintf( "%s/%s", trim( $correct_permalink, "/" ), $pm_query['endpoint'] );
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$queried_object = '-';
|
||||
}
|
||||
|
||||
/**
|
||||
* 4. Check trailing & duplicated slashes (ignore links with query parameters)
|
||||
*/
|
||||
if ( ( ( $trailing_slashes_mode && $trailing_slashes_redirect ) || preg_match( '/\/{2,}/', $old_uri ) ) && empty( $is_front_page ) && empty( $_POST ) && empty( $correct_permalink ) && empty( $query_string ) && ! empty( $old_uri ) && $old_uri !== "/" ) {
|
||||
$trailing_slash = ( substr( $old_uri, - 1 ) == "/" ) ? true : false;
|
||||
$obsolete_slash = ( preg_match( '/\/{2,}/', $old_uri ) || preg_match( "/.*\.([a-zA-Z]{3,4})\/$/", $old_uri ) );
|
||||
|
||||
if ( ( $trailing_slashes_mode == 1 && ! $trailing_slash ) || ( $trailing_slashes_mode == 2 && $trailing_slash ) || $obsolete_slash ) {
|
||||
$new_uri = self::control_trailing_slashes( $old_uri );
|
||||
|
||||
if ( $new_uri !== $old_uri ) {
|
||||
$correct_permalink = sprintf( "%s/%s", $home_url, ltrim( $new_uri, '/' ) );
|
||||
$redirect_type = 'slash_redirect';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 5. WWW prefix | SSL mismatch redirect
|
||||
*/
|
||||
if ( ! empty( $permalink_manager_options['general']['sslwww_redirect'] ) && ! empty( $_SERVER['HTTP_HOST'] ) ) {
|
||||
$home_url_has_www = ( strpos( $home_url, 'www.' ) !== false ) ? true : false;
|
||||
$requested_url_has_www = ( strpos( $_SERVER['HTTP_HOST'], 'www.' ) !== false ) ? true : false;
|
||||
$home_url_has_ssl = ( strpos( $home_url, 'https' ) !== false ) ? true : false;
|
||||
|
||||
if ( ( $home_url_has_www !== $requested_url_has_www ) || ( ! is_ssl() && $home_url_has_ssl !== false ) ) {
|
||||
$new_uri = ltrim( $old_uri, '/' );
|
||||
$correct_permalink = sprintf( "%s/%s", $home_url, $new_uri );
|
||||
|
||||
$redirect_type = 'www_redirect';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 6. Debug redirect
|
||||
*/
|
||||
$correct_permalink = apply_filters( 'permalink_manager_filter_redirect', $correct_permalink, $redirect_type, $queried_object, $old_uri );
|
||||
|
||||
/**
|
||||
* 7. Ignore default URIs (or do nothing if redirects are disabled)
|
||||
*/
|
||||
if ( ! empty( $correct_permalink ) && is_string( $correct_permalink ) && ! empty( $redirect_mode ) ) {
|
||||
// Allow redirect
|
||||
$wp_query->query_vars['do_not_redirect'] = 0;
|
||||
|
||||
// Adjust trailing slashes
|
||||
$correct_permalink = self::control_trailing_slashes( $correct_permalink );
|
||||
|
||||
// Prevent redirect loop
|
||||
$rel_old_uri = wp_make_link_relative( $old_uri_abs );
|
||||
$rel_new_uri = wp_make_link_relative( $correct_permalink );
|
||||
|
||||
// Append query string
|
||||
$correct_permalink = ( ! empty( $query_string ) ) ? sprintf( "%s?%s", strtok( $correct_permalink, "?" ), $query_string ) : $correct_permalink;
|
||||
|
||||
if ( filter_var( $correct_permalink, FILTER_VALIDATE_URL ) && ( $redirect_type === 'www_redirect' || $rel_old_uri !== $rel_new_uri ) ) {
|
||||
wp_safe_redirect( $correct_permalink, $redirect_mode, PERMALINK_MANAGER_PLUGIN_NAME );
|
||||
exit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Control how the canonical redirect function in WordPress and other popular plugins works
|
||||
*/
|
||||
function adjust_canonical_redirect() {
|
||||
global $permalink_manager_options, $wp, $wp_query, $wp_rewrite;
|
||||
|
||||
// Adjust rewrite settings for trailing slashes
|
||||
$trailing_slash_setting = ( ! empty( $permalink_manager_options['general']['trailing_slashes'] ) ) ? $permalink_manager_options['general']['trailing_slashes'] : "";
|
||||
if ( in_array( $trailing_slash_setting, array( 1, 10 ) ) ) {
|
||||
$wp_rewrite->use_trailing_slashes = true;
|
||||
} else if ( in_array( $trailing_slash_setting, array( 2, 20 ) ) ) {
|
||||
$wp_rewrite->use_trailing_slashes = false;
|
||||
}
|
||||
|
||||
// Get endpoints
|
||||
$endpoints = Permalink_Manager_Helper_Functions::get_endpoints();
|
||||
$endpoints_array = ( $endpoints ) ? explode( "|", $endpoints ) : array();
|
||||
|
||||
// Check if any endpoint is called (fix for endpoints)
|
||||
foreach ( $endpoints_array as $endpoint ) {
|
||||
if ( ! empty( $wp->query_vars[ $endpoint ] ) && ! in_array( $endpoint, array( 'attachment', 'page', 'paged', 'feed' ) ) ) {
|
||||
$wp_query->query_vars['do_not_redirect'] = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Allow canonical redirect for ../1/ and ../page/1/
|
||||
if ( ( ! empty( $wp->query_vars['paged'] ) && $wp->query_vars['paged'] == 1 ) || ( ! empty( $wp->query_vars['page'] ) && $wp->query_vars['page'] == 1 ) ) {
|
||||
$wp_query->query_vars['do_not_redirect'] = 0;
|
||||
} // Allow canonical redirect for URL with specific query parameters
|
||||
else if ( ( is_single() && ( ! empty( $_GET['p'] ) || ! empty( $_GET['name'] ) ) ) || ( is_page() && ! empty( $_GET['page_id'] ) ) ) {
|
||||
$wp_query->query_vars['do_not_redirect'] = 0;
|
||||
}
|
||||
|
||||
if ( empty( $permalink_manager_options['general']['canonical_redirect'] ) ) {
|
||||
remove_action( 'template_redirect', 'redirect_canonical' );
|
||||
}
|
||||
|
||||
if ( empty( $permalink_manager_options['general']['old_slug_redirect'] ) ) {
|
||||
remove_action( 'template_redirect', 'wp_old_slug_redirect' );
|
||||
}
|
||||
|
||||
if ( ! empty( $wp_query->query_vars['do_not_redirect'] ) ) {
|
||||
if ( function_exists( 'rank_math' ) && ! empty( $permalink_manager_options['general']['rankmath_redirect'] ) ) {
|
||||
$rank_math_instance = rank_math();
|
||||
|
||||
if ( ! empty( $rank_math_instance->manager ) && is_object( $rank_math_instance->manager ) && method_exists( $rank_math_instance->manager, 'get_module' ) ) {
|
||||
$rank_math_redirections_module = $rank_math_instance->manager->get_module( 'redirections' );
|
||||
|
||||
if ( ! empty( $rank_math_redirections_module ) ) {
|
||||
remove_action( 'template_redirect', array( $rank_math_redirections_module, 'do_redirection' ), 11 );
|
||||
remove_action( 'wp', array( $rank_math_redirections_module, 'do_redirection' ), 11 );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SEOPress
|
||||
remove_action( 'template_redirect', 'seopress_category_redirect', 1 );
|
||||
|
||||
remove_action( 'template_redirect', 'wp_old_slug_redirect' );
|
||||
remove_action( 'template_redirect', 'redirect_canonical' );
|
||||
add_filter( 'wpml_is_redirected', '__return_false', 99, 2 );
|
||||
add_filter( 'pll_check_canonical_url', '__return_false', 99, 2 );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable case-insensitive permalinks mode
|
||||
*/
|
||||
function case_insensitive_permalinks() {
|
||||
global $permalink_manager_uris;
|
||||
|
||||
if ( ! empty( $_SERVER['REQUEST_URI'] ) ) {
|
||||
$_SERVER['REQUEST_URI'] = strtolower( $_SERVER['REQUEST_URI'] );
|
||||
$permalink_manager_uris = array_map( 'strtolower', $permalink_manager_uris );
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
<?php
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) exit;
|
||||
|
||||
/**
|
||||
* Additional debug functions for "Permalink Manager Pro"
|
||||
*/
|
||||
class Permalink_Manager_Debug_Functions {
|
||||
|
||||
public function __construct() {
|
||||
add_action( 'init', array( $this, 'debug_data' ), 99 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Map the debug functions to specific hooks
|
||||
*/
|
||||
public function debug_data() {
|
||||
global $permalink_manager_options;
|
||||
|
||||
if ( ! empty( $permalink_manager_options['general']['debug_mode'] ) || current_user_can( 'manage_options' ) ) {
|
||||
add_filter( 'permalink_manager_filter_query', array( $this, 'debug_query' ), 9, 5 );
|
||||
add_filter( 'permalink_manager_filter_redirect', array( $this, 'debug_redirect' ), 9, 3 );
|
||||
add_filter( 'wp_redirect', array( $this, 'debug_wp_redirect' ), 9, 2 );
|
||||
|
||||
if ( current_user_can( 'manage_options' ) ) {
|
||||
self::debug_custom_fields();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Debug the WordPress query filtered in the Permalink_Manager_Core_Functions::detect_post(); function
|
||||
*
|
||||
* @param array $query
|
||||
* @param array $old_query
|
||||
* @param array $uri_parts
|
||||
* @param array $pm_query
|
||||
* @param string $content_type
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function debug_query( $query, $old_query = null, $uri_parts = null, $pm_query = null, $content_type = null ) {
|
||||
global $permalink_manager;
|
||||
|
||||
if ( isset( $_REQUEST['debug_url'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- No data is saved here
|
||||
$debug_info['uri_parts'] = $uri_parts;
|
||||
$debug_info['old_query_vars'] = $old_query;
|
||||
$debug_info['new_query_vars'] = $query;
|
||||
$debug_info['pm_query'] = ( ! empty( $pm_query['id'] ) ) ? $pm_query['id'] : "-";
|
||||
$debug_info['content_type'] = ( ! empty( $content_type ) ) ? $content_type : "-";
|
||||
|
||||
// License key info
|
||||
if ( class_exists( 'Permalink_Manager_Pro_License' ) ) {
|
||||
$license_key = $permalink_manager->functions['pro-license']->get_license_key();
|
||||
|
||||
// Mask the license key
|
||||
$debug_info['license_key'] = preg_replace( '/([^-]+)-([^-]+)-([^-]+)-([^-]+)$/', '***-***-$3', $license_key );
|
||||
}
|
||||
|
||||
// Plugin version
|
||||
$debug_info['version'] = PERMALINK_MANAGER_VERSION;
|
||||
|
||||
self::display_debug_data( $debug_info );
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Debug the redirect controlled by Permalink_Manager_Core_Functions::new_uri_redirect_and_404();
|
||||
*
|
||||
* @param string $correct_permalink
|
||||
* @param string $redirect_type
|
||||
* @param mixed $queried_object
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function debug_redirect( $correct_permalink, $redirect_type, $queried_object ) {
|
||||
if ( isset( $_REQUEST['debug_redirect'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- No data is saved here
|
||||
$debug_info['redirect_url'] = ( ! empty( $correct_permalink ) ) ? $correct_permalink : '-';
|
||||
$debug_info['redirect_type'] = ( ! empty( $redirect_type ) ) ? $redirect_type : "-";
|
||||
|
||||
self::display_debug_data( $debug_info );
|
||||
}
|
||||
|
||||
return $correct_permalink;
|
||||
}
|
||||
|
||||
/**
|
||||
* Debug wp_redirect() function used in 3rd party plugins
|
||||
*
|
||||
* @param string $url
|
||||
* @param string $status
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function debug_wp_redirect( $url, $status ) {
|
||||
if ( isset( $_GET['debug_wp_redirect'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- No data is saved here
|
||||
$debug_info['url'] = $url;
|
||||
$debug_info['status'] = $status;
|
||||
$debug_info['backtrace'] = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 10 ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace -- Backtrace is a part of debug tools
|
||||
|
||||
self::display_debug_data( $debug_info );
|
||||
}
|
||||
|
||||
return $url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the list of all custom fields assigned to specific post
|
||||
*/
|
||||
public static function debug_custom_fields() {
|
||||
global $pagenow;
|
||||
|
||||
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- No data is saved here
|
||||
if ( ! isset( $_GET['debug_custom_fields'] ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( $pagenow == 'post.php' && isset( $_GET['post'] ) ) {
|
||||
$post_id = intval( $_GET['post'] );
|
||||
$custom_fields = get_post_meta( $post_id );
|
||||
}
|
||||
|
||||
if ( $pagenow == 'term.php' && isset( $_GET['tag_ID'] ) ) {
|
||||
$term_id = intval( $_GET['tag_ID'] );
|
||||
|
||||
$custom_fields = get_term_meta( $term_id );
|
||||
}
|
||||
// phpcs:enable WordPress.Security.NonceVerification.Recommended
|
||||
|
||||
if ( isset ( $custom_fields ) ) {
|
||||
self::display_debug_data( $custom_fields );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A helper function used to display the debug data in various functions
|
||||
*
|
||||
* @param mixed $debug_info
|
||||
*/
|
||||
public static function display_debug_data( $debug_info ) {
|
||||
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_print_r -- print_r() is a part of debug tool
|
||||
$debug_txt = print_r( $debug_info, true );
|
||||
$debug_txt = sprintf( "<pre style=\"display:block;\">%s</pre>", esc_html( $debug_txt ) );
|
||||
|
||||
wp_die( wp_kses_post( $debug_txt ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a CSV file from array
|
||||
*
|
||||
* @param array $array
|
||||
* @param string $filename
|
||||
*/
|
||||
public static function output_csv( $array, $filename = 'debug.csv', $delimiter = ',' ) {
|
||||
if ( count( $array ) == 0 ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Disable caching
|
||||
$now = gmdate( "D, d M Y H:i:s" );
|
||||
header( "Expires: Tue, 03 Jul 2001 06:00:00 GMT" );
|
||||
header( "Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate" );
|
||||
header( "Last-Modified: {$now} GMT" );
|
||||
|
||||
// Force download
|
||||
header( "Content-Type: application/force-download" );
|
||||
header( "Content-Type: application/octet-stream" );
|
||||
header( "Content-Type: application/download" );
|
||||
header( 'Content-Type: text/csv; charset=utf-8' );
|
||||
|
||||
// Disposition / encoding on response body
|
||||
header( "Content-Disposition: attachment;filename={$filename}" );
|
||||
header( "Content-Transfer-Encoding: binary" );
|
||||
|
||||
$df = fopen( "php://output", 'w' );
|
||||
|
||||
// Use the same delimiter for headers and data
|
||||
fputcsv( $df, array_keys( reset( $array ) ), $delimiter );
|
||||
foreach ( $array as $row ) {
|
||||
fputcsv( $df, $row, $delimiter );
|
||||
}
|
||||
|
||||
fclose( $df ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
|
||||
|
||||
die();
|
||||
}
|
||||
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) exit;
|
||||
|
||||
/**
|
||||
* Support for Gutenberg editor
|
||||
*/
|
||||
class Permalink_Manager_Gutenberg {
|
||||
|
||||
public function __construct() {
|
||||
add_action( 'enqueue_block_editor_assets', array( $this, 'init' ) );
|
||||
|
||||
add_action( 'wp_ajax_pm_get_uri_editor', array( $this, 'get_uri_editor' ) );
|
||||
add_action( 'wp_ajax_nopriv_pm_get_uri_editor', array( $this, 'get_uri_editor' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add URI Editor meta box to Gutenberg editor
|
||||
*/
|
||||
public function init() {
|
||||
global $current_screen, $post;
|
||||
|
||||
// Get displayed post type
|
||||
if ( empty( $current_screen->post_type ) || empty( $post->post_type ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Stop the hook (if needed)
|
||||
$show_uri_editor = apply_filters( "permalink_manager_show_uri_editor_post", true, $post, $post->post_type );
|
||||
if ( ! $show_uri_editor ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check the user capabilities
|
||||
if ( Permalink_Manager_Admin_Functions::current_user_can_edit_uris() === false ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if the post is excluded
|
||||
if ( ! empty( $post->ID ) && Permalink_Manager_Helper_Functions::is_post_excluded( $post ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
add_meta_box( 'permalink-manager', __( 'Permalink Manager', 'permalink-manager' ), array( $this, 'get_uri_editor' ), '', 'side', 'high' );
|
||||
|
||||
// wp_enqueue_script( 'permalink-manager-gutenberg', PERMALINK_MANAGER_URL . '/out/permalink-manager-gutenberg.js', array( 'wp-plugins', 'wp-edit-post', 'wp-i18n', 'wp-element' ) );
|
||||
// wp_enqueue_style( 'permalink-manager-gutenberg', PERMALINK_MANAGER_URL . '/out/permalink-manager-gutenberg.css', array(), PERMALINK_MANAGER_VERSION );
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the URI Editor for specific post
|
||||
*
|
||||
* @param WP_Post|int $post
|
||||
*/
|
||||
public function get_uri_editor( $post = null ) {
|
||||
if ( empty( $post->ID ) && empty( $_REQUEST['post_id'] ) ) {
|
||||
return;
|
||||
} else if ( ! empty( $_REQUEST['post_id'] ) && is_numeric( $_REQUEST['post_id'] ) ) {
|
||||
$post = get_post( $_REQUEST['post_id'] );
|
||||
}
|
||||
|
||||
// Check if the user can edit this post
|
||||
if ( ! empty( $post->ID ) && current_user_can( 'edit_post', $post->ID ) ) {
|
||||
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
|
||||
echo ( $post ) ? Permalink_Manager_UI_Elements::display_uri_box( $post, true ) : '';
|
||||
}
|
||||
|
||||
if ( wp_doing_ajax() && isset( $_GET['action'] ) && $_GET['action'] == 'pm_get_uri_editor' ) {
|
||||
die();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+984
@@ -0,0 +1,984 @@
|
||||
<?php
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper functions used in classes and another subclasses
|
||||
*/
|
||||
class Permalink_Manager_Helper_Functions {
|
||||
|
||||
public function __construct() {
|
||||
add_action( 'plugins_loaded', array( $this, 'early_init' ), 5 );
|
||||
add_action( 'plugins_loaded', array( $this, 'init' ), 20 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add early hooks used by plugin to filter the custom permalinks
|
||||
*/
|
||||
public function early_init() {
|
||||
// Reload the globals when the blog is switched (multisite)
|
||||
add_action( 'switch_blog', array( $this, 'reload_globals_in_network' ), 9 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add hooks used by plugin to filter the custom permalinks
|
||||
*/
|
||||
public function init() {
|
||||
global $permalink_manager_options;
|
||||
|
||||
// Clear the final default URIs
|
||||
add_filter( 'permalink_manager_filter_default_term_uri', array( $this, 'clear_single_uri' ), 20 );
|
||||
add_filter( 'permalink_manager_filter_default_post_uri', array( $this, 'clear_single_uri' ), 20 );
|
||||
|
||||
// Force unique URIs when saving them
|
||||
if ( ! empty( $permalink_manager_options['general']['force_unique_uris'] ) ) {
|
||||
add_filter( 'permalink_manager_pre_update_post_uri', array( $this, 'force_unique_uri' ), 100, 3 );
|
||||
add_filter( 'permalink_manager_filter_default_post_uri', array( $this, 'force_unique_uri' ), 100, 3 );
|
||||
add_filter( 'permalink_manager_pre_update_term_uri', array( $this, 'force_unique_uri' ), 100, 3 );
|
||||
add_filter( 'permalink_manager_filter_default_term_uri', array( $this, 'force_unique_uri' ), 100, 3 );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the primary term for the specific post
|
||||
*
|
||||
* @param int $post_id
|
||||
* @param string $taxonomy
|
||||
* @param bool $slug_only
|
||||
*
|
||||
* @return array|string|WP_Term
|
||||
*/
|
||||
static function get_primary_term( $post_id, $taxonomy, $slug_only = true ) {
|
||||
global $permalink_manager_options;
|
||||
|
||||
$primary_term_enabled = ( isset( $permalink_manager_options['general']['primary_category'] ) ) ? (bool) $permalink_manager_options['general']['primary_category'] : true;
|
||||
$primary_term_enabled = apply_filters( 'permalink_manager_primary_term', $primary_term_enabled );
|
||||
|
||||
if ( ! $primary_term_enabled ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// A. Yoast SEO
|
||||
if ( class_exists( 'WPSEO_Primary_Term' ) ) {
|
||||
$yoast_primary_term_label = sprintf( 'yoast_wpseo_primary_%s_term', $taxonomy );
|
||||
|
||||
// Hotfix: Yoast SEO saves the primary term using 'save_post' hook with the highest priority, so the primary term ID is taken directly from $_POST
|
||||
if ( ! empty( $_POST[ $yoast_primary_term_label ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
|
||||
$yoast_primary_term_id = filter_input( INPUT_POST, $yoast_primary_term_label, FILTER_SANITIZE_NUMBER_INT );
|
||||
} else {
|
||||
$yoast_primary_term = new WPSEO_Primary_Term( $taxonomy, $post_id );
|
||||
$yoast_primary_term_id = $yoast_primary_term->get_primary_term();
|
||||
}
|
||||
|
||||
$primary_term = ( is_numeric( $yoast_primary_term_id ) ) ? get_term( $yoast_primary_term_id, $taxonomy ) : '';
|
||||
} // B. The SEO Framework
|
||||
else if ( function_exists( 'the_seo_framework' ) || function_exists( 'tsf' ) ) {
|
||||
if ( class_exists( 'The_SEO_Framework\Data\Plugin\Post' ) ) {
|
||||
$primary_term = The_SEO_Framework\Data\Plugin\Post::get_primary_term( $post_id, $taxonomy );
|
||||
} elseif ( function_exists( 'the_seo_framework' ) && method_exists( the_seo_framework(), 'get_primary_term' ) ) {
|
||||
$primary_term = the_seo_framework()->get_primary_term( $post_id, $taxonomy );
|
||||
}
|
||||
} // C. RankMath
|
||||
else if ( class_exists( 'RankMath' ) ) {
|
||||
$primary_cat_id = get_post_meta( $post_id, "rank_math_primary_{$taxonomy}", true );
|
||||
$primary_term = ( ! empty( $primary_cat_id ) ) ? get_term( $primary_cat_id, $taxonomy ) : '';
|
||||
} // D. SEOPress
|
||||
else if ( function_exists( 'seopress_init' ) && $taxonomy == 'category' ) {
|
||||
$primary_cat_id = get_post_meta( $post_id, '_seopress_robots_primary_cat', true );
|
||||
$primary_term = ( ! empty( $primary_cat_id ) ) ? get_term( $primary_cat_id, 'category' ) : '';
|
||||
} // E. SmartCrawler
|
||||
else if ( class_exists( '\SmartCrawl\SmartCrawl' ) ) {
|
||||
$primary_cat_id = get_post_meta( $post_id, "wds_primary_{$taxonomy}", true );
|
||||
$primary_term = ( ! empty( $primary_cat_id ) ) ? get_term( $primary_cat_id, $taxonomy ) : '';
|
||||
} // F. All In One SEO Pro
|
||||
else if ( class_exists( '\AIOSEO\Plugin\Pro\Standalone\PrimaryTerm' ) ) {
|
||||
$primary_term_class = new \AIOSEO\Plugin\Pro\Standalone\PrimaryTerm();
|
||||
$primary_term = ( method_exists( $primary_term_class, 'getPrimaryTerm' ) ) ? $primary_term_class->getPrimaryTerm( $post_id, $taxonomy ) : '';
|
||||
}
|
||||
|
||||
if ( ! empty( $primary_term ) && ! is_wp_error( $primary_term ) ) {
|
||||
return ( $slug_only ) ? $primary_term->slug : $primary_term;
|
||||
} else {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the lowest level term/post in the specific array
|
||||
*
|
||||
* @param WP_Post|WP_Term|int $first_element
|
||||
* @param array $elements
|
||||
*
|
||||
* @return WP_Post|WP_Term|int
|
||||
*/
|
||||
static function get_lowest_element( $first_element, $elements ) {
|
||||
if ( ! empty( $elements ) && ! empty( $first_element ) ) {
|
||||
// Get the ID of first element
|
||||
if ( ! empty( $first_element->term_id ) ) {
|
||||
$first_element_id = $first_element->term_id;
|
||||
$parent_key = 'parent';
|
||||
} else if ( ! empty( $first_element->ID ) ) {
|
||||
$first_element_id = $first_element->ID;
|
||||
$parent_key = 'post_parent';
|
||||
} else if ( is_numeric( $first_element ) ) {
|
||||
$first_element_id = $first_element;
|
||||
$parent_key = 'post_parent';
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
$children = wp_filter_object_list( $elements, array( $parent_key => $first_element_id ) );
|
||||
if ( ! empty( $children ) ) {
|
||||
// Get the first term
|
||||
$child_term = reset( $children );
|
||||
$first_element = self::get_lowest_element( $child_term, $elements );
|
||||
}
|
||||
}
|
||||
|
||||
return $first_element;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the full (hierarchical) slug for specific term object
|
||||
*
|
||||
* @param WP_Term $term
|
||||
* @param mixed|WP_Term[] $terms
|
||||
* @param bool $mode
|
||||
* @param bool $native_uri
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
static function get_term_full_slug( $term, $terms, $mode = false, $native_uri = false ) {
|
||||
global $permalink_manager_uris;
|
||||
|
||||
// Check if term is not empty
|
||||
if ( empty( $term->taxonomy ) ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// Get taxonomy
|
||||
$taxonomy = $term->taxonomy;
|
||||
|
||||
// Check if mode is set
|
||||
if ( empty( $mode ) ) {
|
||||
$mode = ( is_taxonomy_hierarchical( $taxonomy ) ) ? 2 : 4;
|
||||
}
|
||||
|
||||
// A. Inherit the custom permalink from the term
|
||||
if ( $mode == 1 ) {
|
||||
$term_slug = ( ! empty( $permalink_manager_uris["tax-{$term->term_id}"] ) ) ? $permalink_manager_uris["tax-{$term->term_id}"] : '';
|
||||
} // B. Hierarchical taxonomy base
|
||||
else if ( $mode == 2 ) {
|
||||
$ancestors = get_ancestors( $term->term_id, $taxonomy, 'taxonomy' );
|
||||
$hierarchical_slugs = array();
|
||||
|
||||
foreach ( $ancestors as $ancestor ) {
|
||||
$ancestor_term = get_term( $ancestor, $taxonomy );
|
||||
$hierarchical_slugs[] = ( $native_uri ) ? $ancestor_term->slug : self::force_custom_slugs( $ancestor_term->slug, $ancestor_term );
|
||||
}
|
||||
$hierarchical_slugs = array_reverse( $hierarchical_slugs );
|
||||
$term_slug = implode( '/', $hierarchical_slugs );
|
||||
|
||||
// Append the term slug now
|
||||
$last_term_slug = ( $native_uri ) ? $term->slug : self::force_custom_slugs( $term->slug, $term );
|
||||
$term_slug = "{$term_slug}/{$last_term_slug}";
|
||||
} // C. Force flat taxonomy base - get the highest level term (if %taxonomy_top% tag is used)
|
||||
else if ( $mode == 3 ) {
|
||||
if ( ! empty( $term->parent ) ) {
|
||||
$ancestors = get_ancestors( $term->term_id, $taxonomy, 'taxonomy' );
|
||||
|
||||
if ( is_array( $ancestors ) ) {
|
||||
$top_ancestor = end( $ancestors );
|
||||
$top_ancestor_term = get_term( $top_ancestor, $taxonomy );
|
||||
$single_term = ( ! empty( $top_ancestor_term->slug ) ) ? $top_ancestor_term : $term;
|
||||
}
|
||||
}
|
||||
|
||||
$term_slug = ( ! empty( $single_term->slug ) ) ? self::force_custom_slugs( $single_term->slug, $single_term ) : $term->slug;
|
||||
} // D. Force flat taxonomy base - get primary or lowest level term (if term is non-hierarchical or %taxonomy_flat% tag is used)
|
||||
else {
|
||||
if ( ! empty( $term->slug ) ) {
|
||||
$term_slug = ( $native_uri ) ? $term->slug : Permalink_Manager_Helper_Functions::force_custom_slugs( $term->slug, $term );
|
||||
} else if ( ! empty ( $terms ) ) {
|
||||
foreach ( $terms as $single_term ) {
|
||||
if ( $single_term->parent == 0 ) {
|
||||
$term_slug = self::force_custom_slugs( $single_term->slug, $single_term );
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ( ! empty( $term_slug ) ) ? $term_slug : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the full (hierarchical) slug for specific post object
|
||||
*
|
||||
* @param WP_Post|int $post
|
||||
* @param bool $slugs_mode
|
||||
* @param bool $native_uri
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
static function get_post_full_slug( $post, $slugs_mode = false, $native_uri = false ) {
|
||||
$post = ( ! empty( $post->ID ) ) ? $post : get_post( $post );
|
||||
|
||||
if ( ! empty( $post->post_type ) ) {
|
||||
$full_native_slug = $post->post_name;
|
||||
$full_custom_slug = Permalink_Manager_Helper_Functions::force_custom_slugs( $post->post_name, $post, false, $slugs_mode );
|
||||
|
||||
if ( $post->ancestors && is_post_type_hierarchical( $post->post_type ) ) {
|
||||
foreach ( $post->ancestors as $parent ) {
|
||||
$parent = get_post( $parent );
|
||||
if ( $parent && $parent->post_name ) {
|
||||
$full_native_slug = $parent->post_name . '/' . $full_native_slug;
|
||||
$full_custom_slug = Permalink_Manager_Helper_Functions::force_custom_slugs( $parent->post_name, $parent, false, $slugs_mode ) . '/' . $full_custom_slug;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$post_slug = ( $native_uri ) ? $full_native_slug : $full_custom_slug;
|
||||
}
|
||||
|
||||
return ( ! empty( $post_slug ) ) ? $post_slug : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Allow to disable post types and taxonomies
|
||||
*/
|
||||
static function get_disabled_post_types( $include_user_excluded = true ) {
|
||||
global $wp_post_types, $permalink_manager_options;
|
||||
|
||||
$allowed_post_types = array(
|
||||
'shop_coupon'
|
||||
);
|
||||
|
||||
$disabled_post_types = array(
|
||||
'revision',
|
||||
'nav_menu_item',
|
||||
'algolia_task',
|
||||
'fl_builder',
|
||||
'fl-builder',
|
||||
'fl-builder-template',
|
||||
'fl-theme-layout',
|
||||
'fusion_tb_layout',
|
||||
'fusion_tb_section',
|
||||
'fusion_template',
|
||||
'fusion_element',
|
||||
'wc_product_tab',
|
||||
'wc_voucher',
|
||||
'wc_voucher_template',
|
||||
'sliders',
|
||||
'thirstylink',
|
||||
'elementor_library',
|
||||
'elementor_menu_item',
|
||||
'cms_block',
|
||||
'nooz_coverage',
|
||||
'bricks_template'
|
||||
);
|
||||
|
||||
// 1. Disable post types that are not publicly_queryable
|
||||
foreach ( $wp_post_types as $post_type ) {
|
||||
if ( in_array( $post_type->name, $allowed_post_types ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( ! is_post_type_viewable( $post_type ) || ( empty( $post_type->query_var ) && empty( $post_type->rewrite ) && empty( $post_type->_builtin ) && ! empty( $permalink_manager_options['general']['partial_disable_strict'] ) ) ) {
|
||||
$disabled_post_types[] = $post_type->name;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Add post types disabled by user
|
||||
if ( $include_user_excluded ) {
|
||||
$disabled_post_types = ( ! empty( $permalink_manager_options['general']['partial_disable']['post_types'] ) ) ? array_merge( (array) $permalink_manager_options['general']['partial_disable']['post_types'], $disabled_post_types ) : $disabled_post_types;
|
||||
}
|
||||
|
||||
return apply_filters( 'permalink_manager_disabled_post_types', $disabled_post_types );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the array of all (including/excluding user selected) disabled taxonomies
|
||||
*
|
||||
* @param bool $include_user_excluded
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
static function get_disabled_taxonomies( $include_user_excluded = true ) {
|
||||
global $wp_taxonomies, $permalink_manager_options;
|
||||
|
||||
$disabled_taxonomies = array(
|
||||
'product_shipping_class',
|
||||
'post_status',
|
||||
'fl-builder-template-category',
|
||||
'post_format',
|
||||
'nav_menu',
|
||||
'language',
|
||||
'template_bundle'
|
||||
);
|
||||
|
||||
// 1. Disable taxonomies that are not publicly_queryable
|
||||
foreach ( $wp_taxonomies as $taxonomy ) {
|
||||
if ( ! is_taxonomy_viewable( $taxonomy ) || ( empty( $taxonomy->query_var ) && empty( $taxonomy->rewrite ) && empty( $taxonomy->_builtin ) && ! empty( $permalink_manager_options['general']['partial_disable_strict'] ) ) ) {
|
||||
$disabled_taxonomies[] = $taxonomy->name;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Add taxonomies disabled by user
|
||||
if ( $include_user_excluded ) {
|
||||
$disabled_taxonomies = ( ! empty( $permalink_manager_options['general']['partial_disable']['taxonomies'] ) ) ? array_merge( (array) $permalink_manager_options['general']['partial_disable']['taxonomies'], $disabled_taxonomies ) : $disabled_taxonomies;
|
||||
}
|
||||
|
||||
return apply_filters( 'permalink_manager_disabled_taxonomies', $disabled_taxonomies );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the post type should be ignored by Permalink Manager
|
||||
*
|
||||
* @param string $post_type
|
||||
* @param bool $check_if_exists
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
static public function is_post_type_disabled( $post_type, $check_if_exists = true ) {
|
||||
$disabled_post_types = self::get_disabled_post_types();
|
||||
$post_type_exists = ( $check_if_exists ) ? post_type_exists( $post_type ) : true;
|
||||
|
||||
return ( ( is_array( $disabled_post_types ) && in_array( $post_type, $disabled_post_types ) ) || empty( $post_type_exists ) ) ? true : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the taxonomy should be ignored by Permalink Manager
|
||||
*
|
||||
* @param string $taxonomy
|
||||
* @param bool $check_if_exists
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
static public function is_taxonomy_disabled( $taxonomy, $check_if_exists = true ) {
|
||||
$disabled_taxonomies = self::get_disabled_taxonomies();
|
||||
$taxonomy_exists = ( $check_if_exists ) ? taxonomy_exists( $taxonomy ) : true;
|
||||
|
||||
return ( ( is_array( $disabled_taxonomies ) && in_array( $taxonomy, $disabled_taxonomies ) ) || empty( $taxonomy_exists ) ) ? true : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of all excluded posts' IDs
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function get_excluded_post_ids() {
|
||||
global $permalink_manager_options;
|
||||
|
||||
if ( ! empty( $permalink_manager_options["general"]["exclude_post_ids"] ) ) {
|
||||
$excluded_post_ids_raw = $permalink_manager_options["general"]["exclude_post_ids"];
|
||||
|
||||
$excluded_post_ids = self::get_ids_from_string( $excluded_post_ids_raw );
|
||||
} else {
|
||||
$excluded_post_ids = array();
|
||||
}
|
||||
|
||||
// Allow to filter the array via filter
|
||||
$excluded_post_ids = apply_filters( 'permalink_manager_excluded_post_ids', $excluded_post_ids );
|
||||
|
||||
// Only numeric IDs are allowed
|
||||
return ( ! empty( $excluded_post_ids ) ) ? array_filter( $excluded_post_ids, 'is_numeric' ) : array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if specific post should be ignored by Permalink Manager
|
||||
*
|
||||
* @param WP_Post|int $post
|
||||
* @param bool $draft_check
|
||||
* @param bool $strict_draft_check
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function is_post_excluded( $post = null, $draft_check = false, $strict_draft_check = false ) {
|
||||
$post = ( is_numeric( $post ) ) ? get_post( $post ) : $post;
|
||||
|
||||
// 1. Check if post type is disabled
|
||||
if ( ! empty( $post->post_type ) && self::is_post_type_disabled( $post->post_type ) ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 2. Get list of post IDs excluded in the plugin settings or via the filter
|
||||
$excluded_post_ids = self::get_excluded_post_ids();
|
||||
|
||||
// 3. Exclude post IDs excluded via the filter or in the plugin settings
|
||||
if ( is_array( $excluded_post_ids ) && ! empty( $post->ID ) && in_array( $post->ID, $excluded_post_ids ) ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// D. Check if post is a "draft", "pending", removed
|
||||
if ( $draft_check ) {
|
||||
return self::is_draft_excluded( $post, $strict_draft_check );
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if specific post is a draft (or pending)
|
||||
*
|
||||
* @param WP_Post|int $post
|
||||
* @param bool $strict_draft_check
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function is_draft_excluded( $post = null, $strict_draft_check = false ) {
|
||||
global $permalink_manager_options;
|
||||
|
||||
$post = ( is_numeric( $post ) ) ? get_post( $post ) : $post;
|
||||
|
||||
// Check if post is a "draft", "pending" or moved to trash
|
||||
if ( ! empty( $post->post_status ) ) {
|
||||
if ( ! empty( $permalink_manager_options["general"]["ignore_drafts"] ) || $strict_draft_check ) {
|
||||
$post_statuses = ( $permalink_manager_options["general"]["ignore_drafts"] == 2 ) ? array( 'draft', 'pending' ) : array( 'draft' );
|
||||
|
||||
if ( in_array( $post->post_status, $post_statuses ) ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if ( in_array( $post->post_status, array( 'auto-draft', 'trash' ) ) || ( strpos( $post->post_name, 'revision-v1' ) !== false ) || ( ! empty( $post->post_name ) && $post->post_name == 'auto-draft' ) ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of all excluded terms' IDs
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function get_excluded_term_ids() {
|
||||
global $permalink_manager_options;
|
||||
|
||||
if ( ! empty( $permalink_manager_options["general"]["exclude_term_ids"] ) ) {
|
||||
$excluded_term_ids_raw = $permalink_manager_options["general"]["exclude_term_ids"];
|
||||
|
||||
$excluded_term_ids = self::get_ids_from_string( $excluded_term_ids_raw );
|
||||
} else {
|
||||
$excluded_term_ids = array();
|
||||
}
|
||||
|
||||
// Allow to filter the array via filter
|
||||
$excluded_term_ids = apply_filters( 'permalink_manager_excluded_term_ids', $excluded_term_ids );
|
||||
|
||||
// Only numeric IDs are allowed
|
||||
return ( ! empty( $excluded_term_ids ) ) ? array_filter( $excluded_term_ids, 'is_numeric' ) : array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if specific term should be ignored by Permalink Manager
|
||||
*
|
||||
* @param WP_Term $term
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function is_term_excluded( $term = null ) {
|
||||
$term = ( is_numeric( $term ) ) ? get_term( $term ) : $term;
|
||||
|
||||
// 1. Check if taxonomy is disabled
|
||||
if ( ! empty( $term->taxonomy ) && self::is_taxonomy_disabled( $term->taxonomy ) ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 2. Get list of term IDs excluded in the plugin settings or via the filter
|
||||
$excluded_term_ids = self::get_excluded_term_ids();
|
||||
|
||||
// 3. Exclude term IDs excluded via the filter or in the plugin settings
|
||||
if ( is_array( $excluded_term_ids ) && ! empty( $term->term_id ) && in_array( $term->term_id, $excluded_term_ids ) ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all post types supported by Permalink Manager
|
||||
*
|
||||
* @param string $format
|
||||
* @param string $cpt
|
||||
* @param bool $include_user_excluded
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
static function get_post_types_array( $format = null, $cpt = null, $include_user_excluded = false ) {
|
||||
global $wp_post_types;
|
||||
|
||||
$post_types_array = array();
|
||||
$disabled_post_types = self::get_disabled_post_types( ! $include_user_excluded );
|
||||
|
||||
foreach ( $wp_post_types as $post_type ) {
|
||||
if ( $format == 'full' ) {
|
||||
$post_types_array[ $post_type->name ] = array( 'label' => $post_type->labels->name, 'name' => $post_type->name );
|
||||
} else if ( $format == 'archive_slug' ) {
|
||||
// Ignore non-public post types
|
||||
if ( ! is_post_type_viewable( $post_type ) || empty( $post_type->has_archive ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( ! $post_type->has_archive ) {
|
||||
$archive_slug = $post_type->has_archive;
|
||||
} else if ( is_array( $post_type->rewrite ) && ! empty( $post_type->rewrite['slug'] ) ) {
|
||||
$archive_slug = $post_type->rewrite['slug'];
|
||||
} else {
|
||||
$archive_slug = $post_type->name;
|
||||
}
|
||||
|
||||
$post_types_array[ $post_type->name ] = $archive_slug;
|
||||
} else {
|
||||
$post_types_array[ $post_type->name ] = $post_type->labels->name;
|
||||
}
|
||||
}
|
||||
|
||||
if ( is_array( $disabled_post_types ) ) {
|
||||
foreach ( $disabled_post_types as $post_type ) {
|
||||
if ( ! empty( $post_types_array[ $post_type ] ) ) {
|
||||
unset( $post_types_array[ $post_type ] );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ( empty( $cpt ) ) ? $post_types_array : $post_types_array[ $cpt ];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all taxonomies supported by Permalink Manager
|
||||
*
|
||||
* @param string $format
|
||||
* @param string $tax
|
||||
* @param bool $include_user_excluded
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
static function get_taxonomies_array( $format = null, $tax = null, $include_user_excluded = false ) {
|
||||
global $wp_taxonomies;
|
||||
|
||||
$taxonomies_array = array();
|
||||
$disabled_taxonomies = self::get_disabled_taxonomies( ! $include_user_excluded );
|
||||
|
||||
foreach ( $wp_taxonomies as $taxonomy ) {
|
||||
$taxonomy_name = ( ! empty( $taxonomy->labels->name ) ) ? $taxonomy->labels->name : '-';
|
||||
|
||||
$taxonomies_array[ $taxonomy->name ] = ( $format == 'full' ) ? array( 'label' => $taxonomy->labels->name, 'name' => $taxonomy->name ) : $taxonomy_name;
|
||||
}
|
||||
|
||||
if ( is_array( $disabled_taxonomies ) ) {
|
||||
foreach ( $disabled_taxonomies as $taxonomy ) {
|
||||
if ( ! empty( $taxonomies_array[ $taxonomy ] ) ) {
|
||||
unset( $taxonomies_array[ $taxonomy ] );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ksort( $taxonomies_array );
|
||||
|
||||
return ( empty( $tax ) ) ? $taxonomies_array : $taxonomies_array[ $tax ];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all post statuses supported by Permalink Manager
|
||||
*/
|
||||
static function get_post_statuses() {
|
||||
$post_statuses = get_post_statuses();
|
||||
|
||||
if ( is_array( $post_statuses ) ) {
|
||||
$post_statuses['future'] = __( 'Scheduled', 'permalink-manager' );
|
||||
}
|
||||
|
||||
return apply_filters( 'permalink_manager_post_statuses', $post_statuses );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all the endpoints registered for WP_Rewrite object
|
||||
*/
|
||||
static function get_endpoints() {
|
||||
global $wp_rewrite;
|
||||
|
||||
$pagination_endpoint = ( ! empty( $wp_rewrite->pagination_base ) ) ? $wp_rewrite->pagination_base : 'page';
|
||||
|
||||
// Start with default endpoints
|
||||
$endpoints = "{$pagination_endpoint}|feed|embed|attachment|trackback";
|
||||
|
||||
if ( ! empty( $wp_rewrite->endpoints ) ) {
|
||||
foreach ( $wp_rewrite->endpoints as $endpoint ) {
|
||||
$endpoints .= "|{$endpoint[1]}";
|
||||
}
|
||||
}
|
||||
|
||||
return apply_filters( "permalink_manager_endpoints", str_replace( "/", "\/", $endpoints ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the specific post is selected as a front-page
|
||||
*
|
||||
* @param int $page_id
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
static function is_front_page( $page_id ) {
|
||||
$front_page_id = get_option( 'page_on_front' );
|
||||
$bool = ( ! empty( $front_page_id ) && $page_id == $front_page_id ) ? true : false;
|
||||
|
||||
return apply_filters( 'permalink_manager_is_front_page', $bool, $page_id, $front_page_id );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the advanced mode is turned on
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
static function is_advanced_mode_on() {
|
||||
global $permalink_manager_options;
|
||||
|
||||
$bool = ( ! empty( $permalink_manager_options["general"]["advanced_mode"] ) && $permalink_manager_options["general"]["advanced_mode"] == 1 ) ? true : false;
|
||||
|
||||
return apply_filters( 'permalink_manager_advanced_mode_on', $bool );
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize the multidimensional array
|
||||
*
|
||||
* @param array $data
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
static function sanitize_array( $data = array(), $sanitize = false ) {
|
||||
if ( ! is_array( $data ) || ! count( $data ) ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
foreach ( $data as $k => $v ) {
|
||||
if ( ! is_array( $v ) && ! is_object( $v ) ) {
|
||||
$data[ $k ] = ( $sanitize ) ? sanitize_text_field( trim( $v ) ) : htmlspecialchars( trim( $v ) );
|
||||
}
|
||||
if ( is_array( $v ) ) {
|
||||
$data[ $k ] = self::sanitize_array( $v );
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare an array of strings for use in SQL IN clause
|
||||
*
|
||||
* @param array $array Array of strings to prepare
|
||||
* @param bool $sanitize
|
||||
*
|
||||
* @return string Comma-separated string with quoted values, e.g., "'value1','value2','value3'"
|
||||
*/
|
||||
static function prepare_array_for_sql_in( $array, $sanitize = true ) {
|
||||
// Ensure we have an array
|
||||
if ( ! is_array( $array ) ) {
|
||||
$array = (array) $array;
|
||||
}
|
||||
|
||||
// Remove empty values and sanitize
|
||||
$array = array_filter( $array );
|
||||
$array = ( $sanitize ) ? array_map( 'sanitize_text_field', $array ) : $array;
|
||||
|
||||
// Return empty string if array is empty
|
||||
if ( empty( $array ) ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// Escape and wrap each value with quotes
|
||||
$escaped = array_map( function ( $value ) {
|
||||
return "'" . esc_sql( $value ) . "'";
|
||||
}, $array );
|
||||
|
||||
// Join with comma
|
||||
return implode( ',', $escaped );
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert the text containing IDs and/or ID ranges to an array
|
||||
*
|
||||
* @param string $data
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
static function get_ids_from_string( $data ) {
|
||||
// Remove whitespaces and other invalid characters
|
||||
$raw_ids = esc_sql( preg_replace( '/[^\d,-]/', '', $data ) );
|
||||
|
||||
// Convert the string into the array with IDs and/or ranges
|
||||
preg_match_all( "/([\d]+(?:-?[\d]+)?)/x", $raw_ids, $groups );
|
||||
|
||||
$ids = array();
|
||||
|
||||
if ( ! empty( $groups[1] ) ) {
|
||||
foreach ( $groups[1] as $group ) {
|
||||
if ( is_numeric( $group ) ) {
|
||||
$ids[] = $group;
|
||||
} else if ( preg_match( '/([\d]+)-([\d]+)/', $group, $range_limits ) ) {
|
||||
$range_start = (int) $range_limits[1];
|
||||
$range_end = (int) $range_limits[2];
|
||||
|
||||
if ( $range_start < $range_end ) {
|
||||
$ids = array_merge( $ids, range( $range_start, $range_end ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$ids = array_unique( $ids );
|
||||
}
|
||||
|
||||
return $ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode URI and keep special characters
|
||||
*
|
||||
* @param string $uri
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
static function encode_uri( $uri ) {
|
||||
return str_replace( array( '%2F', '%2C', '%7C', '%2B' ), array( '/', ',', '|', '+' ), urlencode( $uri ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize the given string to URI-safe format
|
||||
*
|
||||
* @param string $str
|
||||
* @param bool $keep_percent_sign
|
||||
* @param bool $force_lowercase
|
||||
* @param bool $sanitize_slugs
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function sanitize_title( $str, $keep_percent_sign = false, $force_lowercase = null, $sanitize_slugs = null ) {
|
||||
global $permalink_manager_options;
|
||||
|
||||
// Force lowercase & hyphens
|
||||
$force_lowercase = ( ! is_null( $force_lowercase ) ) ? $force_lowercase : apply_filters( 'permalink_manager_force_lowercase_uris', true );
|
||||
|
||||
if ( is_null( $sanitize_slugs ) ) {
|
||||
$sanitize_slugs = ( ! empty( $permalink_manager_options['general']['disable_slug_sanitization'] ) ) ? false : true;
|
||||
}
|
||||
|
||||
// Allow to filter the slug before it is sanitized
|
||||
$str = apply_filters( 'permalink_manager_pre_sanitize_title', $str, $keep_percent_sign, $force_lowercase, $sanitize_slugs );
|
||||
|
||||
// Remove accents & entities
|
||||
$clean = ( empty( $permalink_manager_options['general']['keep_accents'] ) ) ? remove_accents( $str ) : $str;
|
||||
$clean = str_replace( array( '<', '>', '&' ), '', $clean );
|
||||
|
||||
$percent_sign = ( $keep_percent_sign ) ? "\%" : "";
|
||||
$sanitize_regex = apply_filters( "permalink_manager_sanitize_regex", "/[^\p{Xan}a-zA-Z0-9{$percent_sign}\/_\.|+, -]/ui", $percent_sign );
|
||||
$clean = preg_replace( $sanitize_regex, '', $clean );
|
||||
|
||||
if ( empty( $clean ) ) {
|
||||
return $str;
|
||||
}
|
||||
|
||||
// Lowercase with non-ASCII characters support
|
||||
if ( $force_lowercase && function_exists( 'mb_strtolower' ) && function_exists( 'wp_is_valid_utf8' ) && wp_is_valid_utf8( $clean ) ) {
|
||||
$clean = mb_strtolower( $clean, 'UTF-8' );
|
||||
} else if ( $force_lowercase ) {
|
||||
$clean = strtolower( $clean );
|
||||
}
|
||||
|
||||
// Remove ampersand
|
||||
$clean = str_replace( array( '%26', '&' ), '', $clean );
|
||||
|
||||
// Remove special characters
|
||||
if ( $sanitize_slugs !== false ) {
|
||||
$clean = preg_replace( "/[\s|+-]+/", "-", $clean );
|
||||
$clean = preg_replace( "/[,]+/", "", $clean );
|
||||
$clean = preg_replace( '/([\.]+)(?![a-z]{3,4}$)/i', '', $clean );
|
||||
$clean = preg_replace( '/([-\s+]\/[-\s+])/', '-', $clean );
|
||||
$clean = preg_replace( '|-+|', '-', $clean );
|
||||
} else {
|
||||
$clean = preg_replace( "/[\s]+/", "-", $clean );
|
||||
}
|
||||
|
||||
// Remove widow & duplicated slashes
|
||||
$clean = preg_replace( '/([-]*[\/]+[-]*)/', '/', $clean );
|
||||
$clean = preg_replace( '/([\/]+)/', '/', $clean );
|
||||
|
||||
// Trim slashes, dashes and whitespaces
|
||||
$clean = trim( $clean, " /-" );
|
||||
|
||||
// Allow to filter the slug after it is sanitized
|
||||
return apply_filters( 'permalink_manager_sanitize_title', $clean, $str, $keep_percent_sign, $force_lowercase, $sanitize_slugs );
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the string in custom permalink or native slug
|
||||
*
|
||||
* @param string $old_string
|
||||
* @param string $new_string
|
||||
* @param string $old_slug
|
||||
* @param string $old_uri
|
||||
* @param string $mode
|
||||
*
|
||||
* @return array|void
|
||||
*/
|
||||
public static function replace_uri_slug( $old_string, $new_string, $old_slug, $old_uri, $mode ) {
|
||||
if ( preg_match( "/^\#.+\#$/i", $old_string ) ) {
|
||||
$old_string = trim( $old_string, '#' );
|
||||
|
||||
$allowed_in_chars = '/[\w\d\s\.\*\+\-\?\!\/\|\(\)\{\}\[\]^$]/';
|
||||
$allowed_out_chars = '/^[a-zA-Z0-9\.\/\$\-\_]+$/';
|
||||
|
||||
if ( ! preg_match( $allowed_in_chars, $old_string ) || ! preg_match( $allowed_out_chars, $new_string ) ) {
|
||||
die( 'Invalid characters in REGEX formula.' );
|
||||
}
|
||||
|
||||
$pattern = "#{$old_string}#";
|
||||
|
||||
$new_slug = ( $mode == 'slugs' ) ? preg_replace( $pattern, $new_string, $old_slug ) : $old_slug;
|
||||
$new_uri = ( $mode != 'slugs' ) ? preg_replace( $pattern, $new_string, $old_uri ) : $old_uri;
|
||||
} else {
|
||||
$new_slug = ( $mode == 'slugs' ) ? str_replace( $old_string, $new_string, $old_slug ) : $old_slug;
|
||||
$new_uri = ( $mode != 'slugs' ) ? str_replace( $old_string, $new_string, $old_uri ) : $old_uri;
|
||||
}
|
||||
|
||||
return array( $new_slug, $new_uri );
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize the final custom permalink URI
|
||||
*
|
||||
* @param string $uri
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function clear_single_uri( $uri ) {
|
||||
return self::sanitize_title( $uri, true );
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all slashes from given string
|
||||
*
|
||||
* @param string $uri
|
||||
* @param string $replacement
|
||||
*
|
||||
* @return array|string|string[]|null
|
||||
*/
|
||||
public static function remove_slashes( $uri, $replacement = '' ) {
|
||||
return preg_replace( "/[\/]+/", $replacement, $uri );
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the given slug with the actual title or custom permalink of specific post or term
|
||||
*
|
||||
* @param string $slug
|
||||
* @param WP_Post|WP_Term $object
|
||||
* @param bool $flat
|
||||
* @param null $force_custom_slugs
|
||||
* @param bool $allow_inherit
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function force_custom_slugs( $slug, $object, $flat = false, $force_custom_slugs = null, $allow_inherit = true ) {
|
||||
global $permalink_manager_options;
|
||||
|
||||
if ( empty( $force_custom_slugs ) ) {
|
||||
$force_custom_slugs = ( ! empty( $permalink_manager_options['general']['force_custom_slugs'] ) ) ? $permalink_manager_options['general']['force_custom_slugs'] : false;
|
||||
$force_custom_slugs = apply_filters( 'permalink_manager_force_custom_slugs', $force_custom_slugs, $slug, $object );
|
||||
}
|
||||
|
||||
if ( $force_custom_slugs ) {
|
||||
// A. Custom slug (title)
|
||||
if ( $force_custom_slugs == 1 ) {
|
||||
if ( ! empty( $object->name ) && ! empty( $object->taxonomy ) ) {
|
||||
$title = $object->name;
|
||||
} else if ( ! empty( $object->post_title ) && ! empty( $object->post_type ) ) {
|
||||
$title = $object->post_title;
|
||||
} else {
|
||||
return $slug;
|
||||
}
|
||||
|
||||
$title = wp_strip_all_tags( $title );
|
||||
$title = self::remove_slashes( $title, '-' );
|
||||
|
||||
$new_slug = self::sanitize_title( $title );
|
||||
|
||||
} // B. Custom slug (inherit custom permalink from the parent object)
|
||||
else if ( $allow_inherit ) {
|
||||
$new_slug = basename( Permalink_Manager_URI_Functions::get_single_uri( $object, false, true ) );
|
||||
}
|
||||
|
||||
$slug = ( ! empty( $new_slug ) ) ? preg_replace( '/([^\/]+)$/', $new_slug, $slug ) : $slug;
|
||||
}
|
||||
|
||||
if ( $flat ) {
|
||||
$slug = preg_replace( "/([^\/]+)(.*)/", "$1", $slug );
|
||||
}
|
||||
|
||||
return $slug;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that a permalink is unique by appending a numeric suffix if needed
|
||||
*
|
||||
* @param string $new_uri
|
||||
* @param string|int $element_id
|
||||
* @param string|WP_Post|WP_Term $element
|
||||
*
|
||||
* @return string A unique custom permalink string.
|
||||
*/
|
||||
function force_unique_uri( $new_uri, $element_id, $element = '' ) {
|
||||
// Determine the ID based on the object type
|
||||
if ( is_a( $element, 'WP_Term' ) && strpos( current_action(), "_term_" ) !== false ) {
|
||||
$element_id = $element->term_id;
|
||||
$is_tax = true;
|
||||
} elseif ( is_a( $element, 'WP_Post' ) ) {
|
||||
$element_id = $element->ID;
|
||||
}
|
||||
|
||||
if ( empty( $element_id ) || ! is_numeric( $element_id ) ) {
|
||||
return $new_uri;
|
||||
}
|
||||
|
||||
if ( ! empty( $is_tax ) ) {
|
||||
$element_id = "tax-{$element_id}";
|
||||
}
|
||||
|
||||
// Prepare base + extension
|
||||
if ( ! preg_match( '/^(.+?)(?:-([\d]+))?(\.[^\.]+$|$)/', $new_uri, $parts ) ) {
|
||||
return $new_uri; // fallback if regex fails
|
||||
}
|
||||
|
||||
$base = $parts[1];
|
||||
$index = empty( $parts[2] ) ? 1 : (int) $parts[2];
|
||||
$extension = $parts[3];
|
||||
|
||||
$unique_uri = $new_uri;
|
||||
|
||||
// Increment suffix until URI is unique
|
||||
while ( Permalink_Manager_URI_Functions::is_uri_duplicated( $unique_uri, $element_id ) ) {
|
||||
$index ++;
|
||||
$unique_uri = "{$base}-{$index}{$extension}";
|
||||
}
|
||||
|
||||
return $unique_uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reload the globals when the blog is switched (multisite)
|
||||
*
|
||||
* @param int $new_blog_id
|
||||
*/
|
||||
public function reload_globals_in_network( $new_blog_id ) {
|
||||
global $permalink_manager_uris, $permalink_manager_redirects, $permalink_manager_external_redirects;
|
||||
|
||||
if ( function_exists( 'get_blog_option' ) ) {
|
||||
$permalink_manager_uris = get_blog_option( $new_blog_id, 'permalink-manager-uris', array() );
|
||||
$permalink_manager_redirects = get_blog_option( $new_blog_id, 'permalink-manager-redirects', array() );
|
||||
$permalink_manager_external_redirects = get_blog_option( $new_blog_id, 'permalink-manager-external-redirects', array() );
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
<?php
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) exit;
|
||||
|
||||
/**
|
||||
* Helper functions used for Permastructures (permalink formats)
|
||||
*/
|
||||
class Permalink_Manager_Permastructure_Functions {
|
||||
|
||||
public function __construct() {
|
||||
add_action( 'plugins_loaded', array( $this, 'init' ), 5 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add hooks used by plugin to filter the custom permalinks
|
||||
*/
|
||||
function init() {
|
||||
// Replace empty placeholder tags & remove BOM
|
||||
add_filter( 'permalink_manager_filter_default_post_uri', array( $this, 'replace_empty_placeholder_tags' ), 10, 5 );
|
||||
add_filter( 'permalink_manager_filter_default_term_uri', array( $this, 'replace_empty_placeholder_tags' ), 10, 5 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the default permalink format for specific post type
|
||||
*
|
||||
* @param string $post_type
|
||||
* @param bool $remove_post_tag
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
static function get_default_permastruct( $post_type = 'page', $remove_post_tag = false ) {
|
||||
global $wp_rewrite;
|
||||
|
||||
// Get default permastruct
|
||||
if ( $post_type == 'page' ) {
|
||||
$permastruct = $wp_rewrite->get_page_permastruct();
|
||||
} else if ( $post_type == 'post' ) {
|
||||
$permastruct = get_option( 'permalink_structure' );
|
||||
} else {
|
||||
$permastruct = $wp_rewrite->get_extra_permastruct( $post_type );
|
||||
}
|
||||
|
||||
return ( $remove_post_tag ) ? trim( str_replace( array( "%postname%", "%pagename%", "%{$post_type}%" ), "", $permastruct ), "/" ) : $permastruct;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the post name permastructure tag for specific post type
|
||||
*
|
||||
* @param string $post_type
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
static function get_post_tag( $post_type ) {
|
||||
// Get the post type (with fix for posts & pages)
|
||||
if ( $post_type == 'page' ) {
|
||||
$post_type_tag = '%pagename%';
|
||||
} else if ( $post_type == 'post' ) {
|
||||
$post_type_tag = '%postname%';
|
||||
} else {
|
||||
$post_type_tag = "%{$post_type}%";
|
||||
}
|
||||
|
||||
return $post_type_tag;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if any of slug tags is present inside Permastructure settings
|
||||
*
|
||||
* @param $default_uri
|
||||
* @param $slug_tags
|
||||
* @param $content_element
|
||||
*
|
||||
* @return bool|null
|
||||
*/
|
||||
public static function is_slug_tag_present( $default_uri, $slug_tags, $content_element ) {
|
||||
global $permalink_manager_options;
|
||||
|
||||
// Check if any post tag is present in custom permastructure
|
||||
if ( ! empty( $content_element->post_type ) ) {
|
||||
$content_type = $content_element->post_type;
|
||||
$content_type_key = 'post_types';
|
||||
} else if ( ! empty( $content_element->taxonomy ) ) {
|
||||
$content_type = $content_element->taxonomy;
|
||||
$content_type_key = 'taxonomies';
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
$permastructure_settings = ( ! empty( $permalink_manager_options['permastructure-settings'] ) ) ? $permalink_manager_options['permastructure-settings'] : array();
|
||||
$do_not_append_settings = ( ! empty( $permastructure_settings['do_not_append_slug'] ) ) ? $permastructure_settings['do_not_append_slug'] : array();
|
||||
$do_not_append_slug = ( ! empty( $do_not_append_settings[ $content_type_key ] ) && ! empty( $do_not_append_settings[ $content_type_key ][ $content_type ] ) ) ? true : false;
|
||||
$do_not_append_slug = apply_filters( "permalink_manager_do_not_append_slug", $do_not_append_slug, $content_type, $content_element );
|
||||
|
||||
if ( ! $do_not_append_slug ) {
|
||||
foreach ( $slug_tags as $tag ) {
|
||||
if ( strpos( $default_uri, $tag ) !== false ) {
|
||||
$do_not_append_slug = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3F. Replace the post tags with slugs or append the slug if no post tag is defined
|
||||
if ( ! empty( $do_not_append_slug ) ) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace empty placeholder tags & remove BOM
|
||||
*
|
||||
* @param string $default_uri
|
||||
* @param string $native_slug
|
||||
* @param string $element
|
||||
* @param string $slug
|
||||
* @param bool $native_uri
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function replace_empty_placeholder_tags( $default_uri, $native_slug = "", $element = "", $slug = "", $native_uri = false ) {
|
||||
// Remove the BOM
|
||||
$default_uri = str_replace( array( "\xEF\xBB\xBF", "%ef%bb%bf" ), '', $default_uri );
|
||||
|
||||
// Encode the URI before placeholders are removed
|
||||
$chunks = explode( '/', $default_uri );
|
||||
foreach ( $chunks as &$chunk ) {
|
||||
if ( ! preg_match( "/^(%.+?%)$/", $chunk ) && preg_match( '/%[A-F0-9]{2}%[A-F0-9]{2}/i', $chunk ) ) {
|
||||
$chunk = rawurldecode( $chunk );
|
||||
}
|
||||
}
|
||||
$default_uri = implode( "/", $chunks );
|
||||
|
||||
$empty_tag_replacement = apply_filters( 'permalink_manager_empty_tag_replacement', '', $element );
|
||||
$default_uri = preg_replace( "/%(.+?)%/", $empty_tag_replacement, $default_uri );
|
||||
$default_uri = str_replace( "//", "/", $default_uri );
|
||||
|
||||
return trim( $default_uri, "/" );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the permalink base (home URL) for custom permalink
|
||||
*
|
||||
* @param string|int|WP_Post|WP_Term $element
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function get_permalink_base( $element = null ) {
|
||||
$home_url = trim( get_option( 'home' ), "/" );
|
||||
|
||||
// Make sure that the custom permalinks have a valid scheme
|
||||
if ( strpos( $home_url, 'http' ) === false ) {
|
||||
$home_url = set_url_scheme( $home_url );
|
||||
}
|
||||
|
||||
return apply_filters( 'permalink_manager_filter_permalink_base', $home_url, $element );
|
||||
}
|
||||
}
|
||||
+485
@@ -0,0 +1,485 @@
|
||||
<?php
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) exit;
|
||||
|
||||
/**
|
||||
* Additional hooks for "Permalink Manager Pro"
|
||||
*/
|
||||
class Permalink_Manager_Pro_Functions {
|
||||
|
||||
public function __construct() {
|
||||
// Stop words
|
||||
add_filter( 'permalink_manager_filter_default_post_uri', array( $this, 'remove_stop_words' ), 9, 3 );
|
||||
add_filter( 'permalink_manager_filter_default_term_uri', array( $this, 'remove_stop_words' ), 9, 3 );
|
||||
|
||||
// Custom fields in permalinks
|
||||
add_filter( 'permalink_manager_filter_default_post_uri', array( $this, 'replace_custom_field_tags' ), 9, 5 );
|
||||
add_filter( 'permalink_manager_filter_default_term_uri', array( $this, 'replace_custom_field_tags' ), 9, 5 );
|
||||
|
||||
// Save redirects
|
||||
add_action( 'permalink_manager_updated_post_uri', array( $this, 'save_redirects' ), 9, 5 );
|
||||
add_action( 'permalink_manager_updated_term_uri', array( $this, 'save_redirects' ), 9, 5 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of languages where stop words are defined
|
||||
*/
|
||||
static function load_stop_words_languages() {
|
||||
return array(
|
||||
'ar' => __( 'Arabic', 'permalink-manager' ),
|
||||
'zh' => __( 'Chinese', 'permalink-manager' ),
|
||||
'da' => __( 'Danish', 'permalink-manager' ),
|
||||
'nl' => __( 'Dutch', 'permalink-manager' ),
|
||||
'en' => __( 'English', 'permalink-manager' ),
|
||||
'fi' => __( 'Finnish', 'permalink-manager' ),
|
||||
'fr' => __( 'French', 'permalink-manager' ),
|
||||
'de' => __( 'German', 'permalink-manager' ),
|
||||
'he' => __( 'Hebrew', 'permalink-manager' ),
|
||||
'hi' => __( 'Hindi', 'permalink-manager' ),
|
||||
'it' => __( 'Italian', 'permalink-manager' ),
|
||||
'ja' => __( 'Japanese', 'permalink-manager' ),
|
||||
'ko' => __( 'Korean', 'permalink-manager' ),
|
||||
'no' => __( 'Norwegian', 'permalink-manager' ),
|
||||
'fa' => __( 'Persian', 'permalink-manager' ),
|
||||
'pl' => __( 'Polish', 'permalink-manager' ),
|
||||
'pt' => __( 'Portuguese', 'permalink-manager' ),
|
||||
'ru' => __( 'Russian', 'permalink-manager' ),
|
||||
'es' => __( 'Spanish', 'permalink-manager' ),
|
||||
'sv' => __( 'Swedish', 'permalink-manager' ),
|
||||
'tr' => __( 'Turkish', 'permalink-manager' )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load stop words for specific language (using ISO code)
|
||||
*
|
||||
* @param string $iso
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
static function load_stop_words( $iso = '' ) {
|
||||
$json_dir = PERMALINK_MANAGER_DIR . "/includes/vendor/stopwords-json/dist/{$iso}.json";
|
||||
$json_a = array();
|
||||
|
||||
if ( file_exists( $json_dir ) ) {
|
||||
$string = file_get_contents( $json_dir );
|
||||
$json_a = json_decode( $string, true );
|
||||
}
|
||||
|
||||
return $json_a;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the stop words from the default custom permalinks
|
||||
*
|
||||
* @param string $slug The slug that is being generated.
|
||||
* @param stdClass $object The object that the slug is being generated for.
|
||||
* @param string $name The name of the filter.
|
||||
*
|
||||
* @return string The slug.
|
||||
*/
|
||||
public function remove_stop_words( $slug, $object, $name ) {
|
||||
global $permalink_manager_options;
|
||||
|
||||
if ( ! empty( $permalink_manager_options['stop-words']['stop-words-enable'] ) && ! empty( $permalink_manager_options['stop-words']['stop-words-list'] ) ) {
|
||||
$stop_words = explode( ",", strtolower( stripslashes( $permalink_manager_options['stop-words']['stop-words-list'] ) ) );
|
||||
|
||||
foreach ( $stop_words as $stop_word ) {
|
||||
$stop_word = trim( $stop_word );
|
||||
$slug = preg_replace( "/([\/-]|^)({$stop_word})([\/-]|$)/", '$1$3', $slug );
|
||||
}
|
||||
|
||||
// Clear the slug
|
||||
$slug = preg_replace( "/(-+)/", "-", trim( $slug, "-" ) );
|
||||
$slug = preg_replace( "/(-\/-)|(\/-)|(-\/)/", "/", $slug );
|
||||
}
|
||||
|
||||
return $slug;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace custom field tags in the default custom permalinks
|
||||
*
|
||||
* @param string $default_uri
|
||||
* @param string $native_slug
|
||||
* @param WP_Post|WP_Term $element
|
||||
* @param string $slug
|
||||
* @param string $native_uri
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
function replace_custom_field_tags( $default_uri, $native_slug, $element, $slug, $native_uri ) {
|
||||
// Do not affect native URIs
|
||||
if ( $native_uri ) {
|
||||
return $default_uri;
|
||||
}
|
||||
|
||||
preg_match_all( "/%__(.[^\%]+)%/", $default_uri, $custom_fields );
|
||||
|
||||
if ( ! empty( $custom_fields[1] ) ) {
|
||||
foreach ( $custom_fields[1] as $i => $custom_field ) {
|
||||
// Reset custom field value
|
||||
$custom_field_value = "";
|
||||
|
||||
// Check additional arguments (__custom_field.argument_value)
|
||||
if ( strpos( $custom_field, '.' ) !== false ) {
|
||||
$custom_field_split = preg_split( '/[\.]/', $custom_field );
|
||||
|
||||
if ( ! empty( $custom_field_split[1] ) ) {
|
||||
$custom_field_arg = $custom_field_split[1];
|
||||
$custom_field = $custom_field_split[0];
|
||||
}
|
||||
}
|
||||
|
||||
// 1. Use WooCommerce fields (SKU)
|
||||
if ( class_exists( 'WooCommerce' ) && strtolower( $custom_field ) == 'sku' && ! empty( $element->ID ) ) {
|
||||
$product = wc_get_product( $element->ID );
|
||||
|
||||
$custom_field_value = ( is_a( $product, 'WC_Product' ) ) ? $product->get_sku() : '';
|
||||
} // 2. Try to get value using ACF API
|
||||
else if ( function_exists( 'get_field_object' ) ) {
|
||||
$acf_element_id = ( ! empty( $element->ID ) ) ? $element->ID : "{$element->taxonomy}_{$element->term_id}";
|
||||
$field_object = get_field_object( $custom_field, $acf_element_id );
|
||||
|
||||
// A. Relationship field
|
||||
if ( ! empty( $field_object['type'] ) && ( in_array( $field_object['type'], array( 'relationship', 'post_object', 'taxonomy' ) ) ) && ! empty( $field_object['value'] ) ) {
|
||||
$rel_elements = $field_object['value'];
|
||||
|
||||
// B1. Terms
|
||||
if ( $field_object['type'] == 'taxonomy' ) {
|
||||
if ( ( is_array( $rel_elements ) ) ) {
|
||||
if ( is_numeric( $rel_elements[0] ) && ! empty( $field_object['taxonomy'] ) ) {
|
||||
$rel_elements = get_terms( array( 'include' => $rel_elements, 'taxonomy' => $field_object['taxonomy'], 'hide_empty' => false, 'orderby' => 'term_id', 'order' => 'DESC' ) );
|
||||
}
|
||||
|
||||
// Get the lowest term
|
||||
if ( ! is_wp_error( $rel_elements ) && ! empty( $rel_elements ) && is_object( $rel_elements[0] ) ) {
|
||||
$rel_term = Permalink_Manager_Helper_Functions::get_lowest_element( $rel_elements[0], $rel_elements );
|
||||
}
|
||||
}
|
||||
if ( ! empty( $rel_elements->term_id ) ) {
|
||||
$rel_term = $rel_elements;
|
||||
} else if ( ! empty( $rel_elements ) && is_numeric( $rel_elements ) ) {
|
||||
$rel_term = get_term( $rel_elements, $field_object['taxonomy'] );
|
||||
}
|
||||
|
||||
// Get the replacement slug
|
||||
if ( ! empty( $rel_term->term_id ) ) {
|
||||
if ( ! empty( $custom_field_arg ) && is_numeric( $custom_field_arg ) ) {
|
||||
$custom_field_value = Permalink_Manager_Helper_Functions::force_custom_slugs( $rel_term->slug, $rel_term, false, $custom_field_arg );
|
||||
} else if ( ! empty( $custom_field_arg ) && $custom_field_arg == 'id' ) {
|
||||
$custom_field_value = $rel_term->term_id;
|
||||
} else if ( ! empty( $custom_field_arg ) && $custom_field_arg == 'full_slug' ) {
|
||||
$custom_field_value = Permalink_Manager_Helper_Functions::get_term_full_slug( $rel_term, $rel_elements );
|
||||
} else if ( ! empty( $custom_field_arg ) && $custom_field_arg == 'custom_permalink' ) {
|
||||
$custom_field_value = Permalink_Manager_URI_Functions::get_single_uri( $rel_term );
|
||||
} else {
|
||||
$custom_field_value = Permalink_Manager_Helper_Functions::force_custom_slugs( $rel_term->slug, $rel_term );
|
||||
}
|
||||
}
|
||||
} // B2. Posts
|
||||
else {
|
||||
if ( ( is_array( $rel_elements ) ) ) {
|
||||
if ( is_numeric( $rel_elements[0] ) ) {
|
||||
$rel_elements = get_posts( array( 'include' => $rel_elements, 'post_type' => 'any', 'orderby' => 'post__in' ) );
|
||||
}
|
||||
|
||||
// Get lowest element
|
||||
if ( ! is_wp_error( $rel_elements ) && ! empty( $rel_elements ) && is_object( $rel_elements[0] ) ) {
|
||||
$rel_post = Permalink_Manager_Helper_Functions::get_lowest_element( $rel_elements[0], $rel_elements );
|
||||
}
|
||||
} else if ( ! empty( $rel_elements->ID ) ) {
|
||||
$rel_post = $rel_elements;
|
||||
}
|
||||
|
||||
if ( ! empty( $rel_post->ID ) ) {
|
||||
$rel_post_object = $rel_post;
|
||||
} else if ( is_numeric( $rel_elements ) ) {
|
||||
$rel_post_object = get_post( $rel_elements );
|
||||
}
|
||||
|
||||
// Get the replacement slug
|
||||
if ( ! empty( $rel_post_object->ID ) ) {
|
||||
if ( ! empty( $custom_field_arg ) && is_numeric( $custom_field_arg ) ) {
|
||||
$custom_field_value = Permalink_Manager_Helper_Functions::force_custom_slugs( $rel_post_object->post_name, $rel_post_object, false, $custom_field_arg );
|
||||
} else if ( ! empty( $custom_field_arg ) && $custom_field_arg == 'id' ) {
|
||||
$custom_field_value = $rel_post_object->ID;
|
||||
} else if ( ! empty( $custom_field_arg ) && $custom_field_arg == 'full_slug' ) {
|
||||
$custom_field_value = Permalink_Manager_Helper_Functions::get_post_full_slug( $rel_post_object );
|
||||
} else if ( ! empty( $custom_field_arg ) && $custom_field_arg == 'custom_permalink' ) {
|
||||
$custom_field_value = Permalink_Manager_URI_Functions::get_single_uri( $rel_post_object );
|
||||
} else {
|
||||
$custom_field_value = Permalink_Manager_Helper_Functions::force_custom_slugs( $rel_post_object->post_name, $rel_post_object );
|
||||
}
|
||||
}
|
||||
}
|
||||
} // C. Text field
|
||||
else {
|
||||
$custom_field_value = ( ! empty( $field_object['value'] ) ) ? $field_object['value'] : "";
|
||||
$custom_field_value = ( ! empty( $custom_field_value['value'] ) ) ? $custom_field_value['value'] : $custom_field_value;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Use native method
|
||||
if ( empty( $custom_field_value ) ) {
|
||||
if ( ! empty( $element->ID ) ) {
|
||||
$custom_field_value = get_post_meta( $element->ID, $custom_field, true );
|
||||
|
||||
// Toolset
|
||||
if ( empty( $custom_field_value ) && ( defined( 'TYPES_VERSION' ) || defined( 'WPCF_VERSION' ) ) ) {
|
||||
$custom_field_value = get_post_meta( $element->ID, "wpcf-{$custom_field}", true );
|
||||
}
|
||||
} else if ( ! empty( $element->term_id ) ) {
|
||||
$custom_field_value = get_term_meta( $element->term_id, $custom_field, true );
|
||||
} else {
|
||||
$custom_field_value = "";
|
||||
}
|
||||
}
|
||||
|
||||
// Allow to filter the custom field value
|
||||
$custom_field_value = apply_filters( 'permalink_manager_custom_field_value', $custom_field_value, $custom_field, $element );
|
||||
|
||||
// Make sure that custom field is a string
|
||||
if ( ! empty( $custom_field_value ) && is_string( $custom_field_value ) ) {
|
||||
// Do not sanitize the custom field if 'no-sanitize' argument is added (e.g. %__custom-field-name.no-sanitize%)
|
||||
if ( empty( $custom_field_arg ) || strpos( $custom_field_arg, 'no-sanitize' ) === false ) {
|
||||
$custom_field_value = Permalink_Manager_Helper_Functions::sanitize_title( $custom_field_value );
|
||||
}
|
||||
|
||||
$default_uri = str_replace( $custom_fields[0][ $i ], $custom_field_value, $default_uri );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $default_uri;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Save the custom, external redirects for specific post or term
|
||||
*
|
||||
* @param int|string $element_id The ID of the post (e.g. 123) or term (tax-456).
|
||||
* @param string $new_uri The new custom permalink
|
||||
* @param string $old_uri The previous custom permalink
|
||||
* @param string $native_uri The native permalink
|
||||
* @param string $default_uri The default custom permalink
|
||||
*/
|
||||
public function save_redirects( $element_id, $new_uri, $old_uri, $native_uri = '', $default_uri = '' ) {
|
||||
global $permalink_manager_options, $permalink_manager_redirects;
|
||||
|
||||
// Do not trigger if "Extra redirects" option is turned off
|
||||
if ( empty( $permalink_manager_options['general']['redirect'] ) || empty( $permalink_manager_options['general']['extra_redirects'] ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Terms IDs should be prepended with prefix
|
||||
$element_id = ( current_filter() == 'permalink_manager_updated_term_uri' ) ? "tax-{$element_id}" : $element_id;
|
||||
|
||||
// Make sure that $permalink_manager_redirects variable is an array
|
||||
$permalink_manager_redirects = ( is_array( $permalink_manager_redirects ) ) ? $permalink_manager_redirects : array();
|
||||
|
||||
// 1A. Post/term is saved or updated
|
||||
if ( isset( $_POST['permalink-manager-redirects'] ) && is_array( $_POST['permalink-manager-redirects'] ) ) {
|
||||
$permalink_manager_redirects[ $element_id ] = array_filter( $_POST['permalink-manager-redirects'] );
|
||||
$redirects_updated = true;
|
||||
} // 1B. All redirects are removed
|
||||
else if ( isset( $_POST['permalink-manager-redirects'] ) ) {
|
||||
$permalink_manager_redirects[ $element_id ] = array();
|
||||
$redirects_updated = true;
|
||||
}
|
||||
|
||||
// 1C. No longer needed
|
||||
if ( isset( $_POST['permalink-manager-redirects'] ) ) {
|
||||
unset( $_POST['permalink-manager-redirects'] );
|
||||
}
|
||||
|
||||
// 2. Custom URI is updated
|
||||
if ( get_option( 'page_on_front' ) !== $element_id && ! empty( $permalink_manager_options['general']['setup_redirects'] ) && ( $new_uri !== $old_uri ) ) {
|
||||
// Make sure that the array with redirects exists
|
||||
$permalink_manager_redirects[ $element_id ] = ( ! empty( $permalink_manager_redirects[ $element_id ] ) ) ? $permalink_manager_redirects[ $element_id ] : array();
|
||||
|
||||
// Append the old custom URI
|
||||
$permalink_manager_redirects[ $element_id ][] = $old_uri;
|
||||
$redirects_updated = true;
|
||||
}
|
||||
|
||||
// 3. Save the custom redirects
|
||||
if ( ! empty( $redirects_updated ) && is_array( $permalink_manager_redirects[ $element_id ] ) ) {
|
||||
// Remove empty redirects
|
||||
$permalink_manager_redirects[ $element_id ] = array_filter( $permalink_manager_redirects[ $element_id ] );
|
||||
|
||||
// Sanitize the array with redirects
|
||||
foreach ( $permalink_manager_redirects[ $element_id ] as $i => $redirect ) {
|
||||
$redirect = rawurldecode( $redirect );
|
||||
$redirect = Permalink_Manager_Helper_Functions::sanitize_title( $redirect, true );
|
||||
$permalink_manager_redirects[ $element_id ][ $i ] = $redirect;
|
||||
}
|
||||
|
||||
// Reset the keys
|
||||
$permalink_manager_redirects[ $element_id ] = array_values( $permalink_manager_redirects[ $element_id ] );
|
||||
|
||||
// Remove the duplicates
|
||||
$permalink_manager_redirects[ $element_id ] = array_unique( $permalink_manager_redirects[ $element_id ] );
|
||||
|
||||
Permalink_Manager_Actions::clear_single_element_duplicated_redirect( $element_id, false, $new_uri );
|
||||
|
||||
// Remove empty subarray
|
||||
$permalink_manager_redirects = array_filter( $permalink_manager_redirects );
|
||||
|
||||
update_option( 'permalink-manager-redirects', $permalink_manager_redirects );
|
||||
}
|
||||
|
||||
// 4. Save the external redirect
|
||||
if ( isset( $_POST['permalink-manager-external-redirect'] ) ) {
|
||||
self::save_external_redirect( $_POST['permalink-manager-external-redirect'], $element_id );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save external redirect
|
||||
*
|
||||
* @param string $url The full URL saved as external redirect
|
||||
* @param string|int $element_id The ID of the post (e.g. 123) or term (tax-456).
|
||||
*/
|
||||
public static function save_external_redirect( $url, $element_id ) {
|
||||
global $permalink_manager_external_redirects;
|
||||
|
||||
$url = filter_var( $url, FILTER_SANITIZE_URL );
|
||||
|
||||
if ( ( empty( $url ) || filter_var( $url, FILTER_VALIDATE_URL ) === false ) && ! empty( $permalink_manager_external_redirects[ $element_id ] ) && isset( $_POST['permalink-manager-external-redirect'] ) ) {
|
||||
unset( $permalink_manager_external_redirects[ $element_id ] );
|
||||
} else {
|
||||
$permalink_manager_external_redirects[ $element_id ] = esc_url( $url );
|
||||
}
|
||||
|
||||
update_option( 'permalink-manager-external-redirects', $permalink_manager_external_redirects );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a new tab to the WooCommerce coupon edit page
|
||||
*
|
||||
* @param array $tabs The tabs array.
|
||||
*
|
||||
* @return array The tabs array with the new tab added.
|
||||
*/
|
||||
|
||||
public static function woocommerce_coupon_tabs( $tabs = array() ) {
|
||||
$tabs['coupon-url'] = array(
|
||||
'label' => __( 'Coupon Link', 'permalink-manager' ),
|
||||
'target' => 'permalink-manager-coupon-url',
|
||||
'class' => 'permalink-manager-coupon-url',
|
||||
);
|
||||
|
||||
return $tabs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a new panel to the WooCommerce coupon edit page
|
||||
*/
|
||||
public static function woocommerce_coupon_panel() {
|
||||
global $permalink_manager_uris, $post;
|
||||
|
||||
$custom_uri = ( ! empty( $permalink_manager_uris[ $post->ID ] ) ) ? $permalink_manager_uris[ $post->ID ] : "";
|
||||
|
||||
$html = "<div id=\"permalink-manager-coupon-url\" class=\"panel woocommerce_options_panel custom_uri_container permalink-manager\">";
|
||||
|
||||
// URI field
|
||||
ob_start();
|
||||
wp_nonce_field( 'permalink-manager-coupon-uri-box', 'permalink-manager-nonce' );
|
||||
|
||||
woocommerce_wp_text_input( array(
|
||||
'id' => 'custom_uri',
|
||||
'label' => __( 'Coupon URI', 'permalink-manager' ),
|
||||
'description' => '<span class="duplicated_uri_alert"></span>' . __( 'The URIs are case-insensitive, e.g. <strong>BLACKFRIDAY</strong> and <strong>blackfriday</strong> are equivalent.', 'permalink-manager' ),
|
||||
'value' => $custom_uri,
|
||||
'custom_attributes' => array( 'data-element-id' => $post->ID ),
|
||||
//'desc_tip' => true
|
||||
) );
|
||||
|
||||
$html .= ob_get_contents();
|
||||
ob_end_clean();
|
||||
|
||||
// URI preview
|
||||
$html .= "<p class=\"form-field coupon-full-url hidden\">";
|
||||
$html .= sprintf( "<label>%s</label>", __( "Coupon Full URL", "permalink-manager" ) );
|
||||
$html .= sprintf( "<code>%s/<span>%s</span></code>", trim( get_option( 'home' ), "/" ), $custom_uri );
|
||||
$html .= "</p>";
|
||||
|
||||
$html .= "</div>";
|
||||
|
||||
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
|
||||
echo $html;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the custom permalink for specific coupon
|
||||
*
|
||||
* @param int $post_id
|
||||
* @param WC_Coupon $coupon
|
||||
*/
|
||||
public static function woocommerce_save_coupon_uri( $post_id, $coupon ) {
|
||||
// Verify nonce at first
|
||||
if ( ! isset( $_POST['permalink-manager-nonce'] ) || ! wp_verify_nonce( $_POST['permalink-manager-nonce'], 'permalink-manager-coupon-uri-box' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Do not do anything if post is auto-saved
|
||||
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$old_uri = Permalink_Manager_URI_Functions::get_single_uri( $post_id, false, true, false );
|
||||
$new_uri = ( ! empty( $_POST['custom_uri'] ) ) ? $_POST['custom_uri'] : "";
|
||||
|
||||
if ( $old_uri !== $new_uri ) {
|
||||
Permalink_Manager_URI_Functions::save_single_uri( $post_id, $new_uri, false, true );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the URL contains a coupon code, and if it does, it adds the coupon code to the cart and redirects to the cart page
|
||||
*
|
||||
* @param array $query The query array.
|
||||
*
|
||||
* @return array The query array.
|
||||
*/
|
||||
public static function woocommerce_detect_coupon_code( $query ) {
|
||||
global $woocommerce, $pm_query;
|
||||
|
||||
// Check if custom URI with coupon URL is requested
|
||||
if ( ! empty( $query['shop_coupon'] ) && ! empty( $pm_query['id'] ) ) {
|
||||
// Check if cart/shop page is set & redirect to it
|
||||
$shop_page_id = wc_get_page_id( 'shop' );
|
||||
$cart_page_id = wc_get_page_id( 'cart' );
|
||||
|
||||
|
||||
if ( ! empty( $cart_page_id ) && WC()->cart->get_cart_contents_count() > 0 ) {
|
||||
$redirect_page = $cart_page_id;
|
||||
} else if ( ! empty( $shop_page_id ) ) {
|
||||
$redirect_page = $shop_page_id;
|
||||
}
|
||||
|
||||
$coupon_code = get_the_title( $pm_query['id'] );
|
||||
|
||||
// Set-up session
|
||||
if ( ! WC()->session->has_session() ) {
|
||||
WC()->session->set_customer_session_cookie( true );
|
||||
}
|
||||
|
||||
// Add the discount code
|
||||
if ( ! WC()->cart->has_discount( $coupon_code ) ) {
|
||||
$woocommerce->cart->add_discount( sanitize_text_field( $coupon_code ) );
|
||||
}
|
||||
|
||||
// Do redirect
|
||||
if ( ! empty( $redirect_page ) ) {
|
||||
wp_safe_redirect( get_permalink( $redirect_page ) );
|
||||
exit();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
}
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
<?php
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Additional hooks for "Permalink Manager Pro"
|
||||
*/
|
||||
class Permalink_Manager_Pro_License {
|
||||
|
||||
public $update_checker;
|
||||
|
||||
public function __construct() {
|
||||
define( 'PERMALINK_MANAGER_PRO', true );
|
||||
$plugin_name = preg_replace( '/(.*)\/([^\/]+\/[^\/]+.php)$/', '$2', PERMALINK_MANAGER_FILE );
|
||||
|
||||
// Permalink Manager Pro Alerts
|
||||
add_filter( 'permalink_manager_alerts', array( $this, 'pro_alerts' ), 9, 3 );
|
||||
|
||||
// Check for updates
|
||||
add_action( 'plugins_loaded', array( $this, 'check_for_updates' ), 10 );
|
||||
add_action( 'admin_init', array( $this, 'reload_license_key' ), 10 );
|
||||
add_action( 'wp_ajax_pm_get_exp_date', array( $this, 'get_expiration_date' ), 9 );
|
||||
|
||||
// Display License info on "Plugins" page
|
||||
add_action( "after_plugin_row_{$plugin_name}", array( $this, 'license_info_bar' ), 10, 2 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the license key from the database, constant defined in wp-config.php file, or $_POST variable
|
||||
*
|
||||
* @param string $load_from_db If set to true, the function will load the license key from the database, even if it's defined in wp-config.php.
|
||||
*
|
||||
* @return string The license key.
|
||||
*/
|
||||
public static function get_license_key( $load_from_db = false ) {
|
||||
$permalink_manager_options = get_option( 'permalink-manager', array() );
|
||||
|
||||
// phpcs:disable WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.MissingUnslash
|
||||
// Key defined in wp-config.php
|
||||
if ( ( defined( 'PMP_LICENCE_KEY' ) || defined( 'PMP_LICENSE_KEY' ) ) && empty( $load_from_db ) ) {
|
||||
$license_key = defined( 'PMP_LICENCE_KEY' ) ? PMP_LICENCE_KEY : PMP_LICENSE_KEY;
|
||||
} // Network licence key (multisite)
|
||||
else if ( is_multisite() ) {
|
||||
$site_licence_key = get_site_option( 'permalink-manager-licence-key' );
|
||||
|
||||
// A. Move the license key to site options
|
||||
if ( ! empty( $site_licence_key ) && ! is_array( $site_licence_key ) ) {
|
||||
$new_license_key = $site_licence_key;
|
||||
} // B. Save the new license key in the plugin settings
|
||||
else if ( ! empty( $_POST['licence']['licence_key'] ) ) {
|
||||
$new_license_key = sanitize_text_field( $_POST['licence']['licence_key'] );
|
||||
}
|
||||
|
||||
if ( ! empty( $new_license_key ) ) {
|
||||
$site_licence_key = array(
|
||||
'licence_key' => sanitize_text_field( $new_license_key )
|
||||
);
|
||||
|
||||
update_site_option( 'permalink-manager-licence-key', $site_licence_key );
|
||||
}
|
||||
|
||||
$license_key = ( ! empty( $site_licence_key['licence_key'] ) ) ? $site_licence_key['licence_key'] : '';
|
||||
} // Single website license key
|
||||
else if ( ! empty( $_POST['licence']['licence_key'] ) ) {
|
||||
$license_key = sanitize_text_field( $_POST['licence']['licence_key'] );
|
||||
} else {
|
||||
$license_key = ( ! empty( $permalink_manager_options['licence']['licence_key'] ) ) ? $permalink_manager_options['licence']['licence_key'] : "";
|
||||
}
|
||||
|
||||
// phpcs:enable WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.MissingUnslash
|
||||
|
||||
return preg_replace( "/[^a-zA-Z0-9-]/", "", $license_key );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the saved license key matches the "developer" format
|
||||
*
|
||||
* @param $license_key
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function is_dev_license_key( $license_key ) {
|
||||
return preg_match( '/^([A-G0-9]{4,8})-([A-G0-9]{4,8})$/', $license_key ) ? true : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the update checker class and create an instance of it
|
||||
*/
|
||||
public function check_for_updates() {
|
||||
$license_key = self::get_license_key();
|
||||
|
||||
// Load Plugin Update Checker by YahnisElsts
|
||||
require_once PERMALINK_MANAGER_DIR . '/includes/vendor/plugin-update-checker/plugin-update-checker.php';
|
||||
|
||||
$this->update_checker = Puc_v4_Factory::buildUpdateChecker( "https://updates.permalinkmanager.pro/?action=get_metadata&slug=permalink-manager-pro&licence_key={$license_key}", PERMALINK_MANAGER_FILE, "permalink-manager-pro" );
|
||||
|
||||
add_filter( 'puc_request_info_result-permalink-manager-pro', array( $this, 'update_pro_info' ), 99, 2 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the license key was changed and if so, delete the cached license data and get the new license data from the server
|
||||
*/
|
||||
public function reload_license_key() {
|
||||
// phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended
|
||||
if ( ! empty( $_POST['licence']['licence_key'] ) || ( ! empty( $_REQUEST['action'] ) && $_REQUEST['action'] == 'pm_get_exp_date' ) || ( ! empty( $_REQUEST['puc_slug'] ) && $_REQUEST['puc_slug'] == 'permalink-manager-pro' ) ) {
|
||||
delete_site_transient( 'permalink_manager_active' );
|
||||
$this->update_checker->requestInfo();
|
||||
} // Sync the license data saved in DB after license key was set in wp-config.php file
|
||||
else if ( defined( 'PMP_LICENCE_KEY' ) || defined( 'PMP_LICENSE_KEY' ) ) {
|
||||
$db_license_key = self::get_license_key( true );
|
||||
$license_key = self::get_license_key();
|
||||
|
||||
if ( ! empty( $db_license_key ) && ! empty( $license_key ) && $db_license_key !== $license_key ) {
|
||||
delete_site_transient( 'permalink_manager_active' );
|
||||
$this->update_checker->requestInfo();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the cached license key needs to be changed
|
||||
*
|
||||
* @param stdClass $raw The raw response from the server.
|
||||
* @param array $result The response object from the API call.
|
||||
*
|
||||
* @return stdClass The plugin info
|
||||
*/
|
||||
public function update_pro_info( $raw, $result ) {
|
||||
$license_key = self::get_license_key();
|
||||
$permalink_manager_active = ( empty( $_POST['licence']['licence_key'] ) ) ? get_site_transient( 'permalink_manager_active' ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended
|
||||
|
||||
// A. Do not do anything - the license info was saved before
|
||||
if ( ! empty( $license_key ) && ( $permalink_manager_active == $license_key ) ) {
|
||||
return $raw;
|
||||
} // B. The license info was not removed or not downloaded before
|
||||
else if ( empty( $permalink_manager_active ) && is_array( $result ) && ! empty( $result['body'] ) && ! empty( $license_key ) ) {
|
||||
$plugin_info = json_decode( $result['body'] );
|
||||
|
||||
if ( is_object( $plugin_info ) && isset( $plugin_info->version ) ) {
|
||||
$exp_date = ( ! empty( $plugin_info->expiration_date ) && strlen( $plugin_info->expiration_date ) > 6 ) ? strtotime( $plugin_info->expiration_date ) : '-';
|
||||
$websites = ( ! empty( $plugin_info->websites ) ) ? $plugin_info->websites : '';
|
||||
|
||||
$license_info = array(
|
||||
'licence_key' => $license_key,
|
||||
'expiration_date' => $exp_date,
|
||||
'websites' => $websites
|
||||
);
|
||||
|
||||
if ( is_multisite() ) {
|
||||
update_site_option( 'permalink-manager-licence-key', $license_info );
|
||||
} else {
|
||||
Permalink_Manager_Actions::save_settings( 'licence', $license_info, false );
|
||||
}
|
||||
|
||||
set_site_transient( 'permalink_manager_active', $license_key, 12 * HOUR_IN_SECONDS );
|
||||
}
|
||||
}
|
||||
|
||||
return $raw;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get license expiration date
|
||||
*
|
||||
* @param bool $basic_check
|
||||
* @param bool $empty_if_valid
|
||||
* @param bool $update_available
|
||||
*
|
||||
* @return int|string
|
||||
*/
|
||||
public static function get_expiration_date( $basic_check = false, $empty_if_valid = false, $update_available = true ) {
|
||||
global $permalink_manager_options;
|
||||
|
||||
// Get expiration info & the licence key
|
||||
if ( is_multisite() ) {
|
||||
$site_licence_key = get_site_option( 'permalink-manager-licence-key' );
|
||||
|
||||
$exp_date = ( ! empty( $site_licence_key['expiration_date'] ) ) ? $site_licence_key['expiration_date'] : false;
|
||||
$license_key = ( ! empty( $site_licence_key['licence_key'] ) ) ? $site_licence_key['licence_key'] : "";
|
||||
$websites = ( ! empty( $site_licence_key['websites'] ) ) ? $site_licence_key['websites'] : "";
|
||||
} else {
|
||||
$exp_date = ( ! empty( $permalink_manager_options['licence']['expiration_date'] ) ) ? $permalink_manager_options['licence']['expiration_date'] : false;
|
||||
$license_key = ( ! empty( $permalink_manager_options['licence']['licence_key'] ) ) ? $permalink_manager_options['licence']['licence_key'] : "";
|
||||
$websites = ( ! empty( $permalink_manager_options['licence']['websites'] ) ) ? $permalink_manager_options['licence']['websites'] : "";
|
||||
}
|
||||
|
||||
$license_info_page = ( ! empty( $license_key ) ) ? self::get_license_info_link( $license_key ) : "#";
|
||||
|
||||
// There is no license key defined
|
||||
if ( empty( $license_key ) ) {
|
||||
$settings_page_url = Permalink_Manager_Admin_Functions::get_admin_url( "§ion=settings" );
|
||||
// translators: %s is the URL to the settings page where users can manage their license keys.
|
||||
$expiration_info = sprintf( __( 'Please paste the license key to access all Permalink Manager Pro updates & features <a href="%s" target="_blank">on this page</a>.', 'permalink-manager' ), $settings_page_url );
|
||||
$expired = 3;
|
||||
} // License key is invalid
|
||||
else if ( $exp_date == '-' || ! preg_match( '/^([A-Z0-9]{5,8}-){1}[A-Z0-9]{5,8}((-[A-Z0-9]{5,8}){2})?$/i', $license_key ) ) {
|
||||
$expiration_info = __( 'Your Permalink Manager Pro license key is invalid!', 'permalink-manager' );
|
||||
$expired = 3;
|
||||
} else {
|
||||
// Key expired
|
||||
if ( ! empty( $exp_date ) && $exp_date < time() ) {
|
||||
// translators: %s is the URL to the Permalink Manager page where users can manage their license keys.
|
||||
$expiration_info = sprintf( __( '<strong>Your Permalink Manager Pro license has expired.</strong><br />Please renew your license key using <a href="%s" target="_blank">this link</a> to restore access to plugin updates.', 'permalink-manager' ), $license_info_page );
|
||||
$expired = 2;
|
||||
} // License key is abused
|
||||
else if ( ! empty( $exp_date ) && ! empty( $websites ) && $update_available === false ) {
|
||||
$expiration_info = sprintf( __( 'Your Permalink Manager Pro license is already in use on another website and cannot be used to request automatic update for this domain.', 'permalink-manager' ), $license_info_page ) . " ";
|
||||
// translators: %s is the URL to the Permalink Manager page where users can manage their license keys.
|
||||
$expiration_info .= sprintf( __( 'For further information, visit the <a href="%s" target="_blank"> License info</a> page.', 'permalink-manager' ), $license_info_page );
|
||||
$expired = 3;
|
||||
} // Valid lifetime license key
|
||||
else if ( gmdate( "Y", intval( $exp_date ) ) > gmdate( 'Y', strtotime( "+10 years" ) ) ) {
|
||||
$expiration_info = __( 'You own a lifetime license key.', 'permalink-manager' );
|
||||
$expired = 0;
|
||||
} // License key is valid
|
||||
else if ( $exp_date ) {
|
||||
// License key will expire in less than month & do not display the alert if the developer license key is used
|
||||
if ( $exp_date - MONTH_IN_SECONDS < time() && ! preg_match( '/^([A-G0-9]{4,8})-([A-G0-9]{4,8})$/', $license_key ) ) {
|
||||
// translators: %s is the Permalink Manager's license key expiry date.
|
||||
$expiration_info = sprintf( __( 'Your Permalink Manager Pro license key will expire on <strong>%s</strong>. Please renew it to maintain access to plugin updates and technical support!', 'permalink-manager' ), wp_date( get_option( 'date_format' ), $exp_date ) ) . " ";
|
||||
// translators: %s is the URL to the Permalink Manager page where users can manage their license keys.
|
||||
$expiration_info .= sprintf( __( 'For further information, visit the <a href="%s" target="_blank"> License info</a> page.', 'permalink-manager' ), $license_info_page );
|
||||
$expired = 1;
|
||||
} // License key can be used
|
||||
else {
|
||||
// Translators: %1$s is the expiration date, %2$s is the URL to the license info page.
|
||||
$expiration_info = sprintf( __( 'Your license key is valid until %1$s.<br />To prolong it please go to <a href="%2$s" target="_blank">this page</a> for more information.', 'permalink-manager' ), gmdate( get_option( 'date_format' ), $exp_date ), $license_info_page );
|
||||
$expired = 0;
|
||||
}
|
||||
} // Expiration data could not be downloaded
|
||||
else {
|
||||
$expiration_info = __( 'Expiration date could not be downloaded at this moment. Please try again in a few minutes.', 'permalink-manager' );
|
||||
$expired = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Do not return any text alert
|
||||
if ( $basic_check || ( $empty_if_valid && $expired == 0 ) ) {
|
||||
return $expired;
|
||||
}
|
||||
|
||||
// phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended
|
||||
if ( ! empty( $_REQUEST['action'] ) && $_REQUEST['action'] == 'pm_get_exp_date' ) {
|
||||
echo wp_kses_post( $expiration_info );
|
||||
die();
|
||||
} else {
|
||||
return $expiration_info;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the URL to the license info page on the plugin's website
|
||||
*
|
||||
* @param $license_key
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
static function get_license_info_link( $license_key ) {
|
||||
$license_key = ( self::is_dev_license_key( $license_key ) ) ? '' : $license_key;
|
||||
$license_link = ( ! empty( $license_key ) ) ? sprintf( "https://permalinkmanager.pro/license-info/%s/", trim( $license_key ) ) : "https://permalinkmanager.pro/license-info/";
|
||||
|
||||
return esc_url( $license_link );
|
||||
}
|
||||
|
||||
/**
|
||||
* Display license status in the "Plugins" table
|
||||
*
|
||||
* @param string $plugin_file
|
||||
* @param array $plugin_data
|
||||
*/
|
||||
function license_info_bar( $plugin_file, $plugin_data ) {
|
||||
global $wp_list_table;
|
||||
|
||||
$column_count = ( ! empty( $wp_list_table ) ) ? $wp_list_table->get_column_count() : 3;
|
||||
// $update_available = (empty($plugin_data['package']) && !empty($plugin_data['update'])) ? false : true;
|
||||
|
||||
$exp_info_text = self::get_expiration_date( false, true, false );
|
||||
$exp_info_code = self::get_expiration_date( true, true, false );
|
||||
|
||||
if ( ! empty( $exp_info_text ) && $exp_info_code >= 1 ) {
|
||||
printf( '<tr class="plugin-update-tr permalink-manager-pro_license-info active" data-slug="%s" data-plugin="%s"><td colspan="%d" class="plugin-update colspanchange plugin_license_info_row">', esc_attr( $plugin_data['slug'] ), esc_attr( $plugin_file ), esc_attr( $column_count ) );
|
||||
printf( '<div class="update-message notice inline notice-error notice-alt">%s</div>', wp_kses_post( wpautop( $exp_info_text ) ) );
|
||||
printf( '</td></tr>' );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Display license nag inside the URI Editor
|
||||
*
|
||||
*/
|
||||
public static function license_info_uri_editor() {
|
||||
$exp_info_text = self::get_expiration_date( false, true, false );
|
||||
$exp_info_code = self::get_expiration_date( true, true, false );
|
||||
|
||||
if ( ! empty( $exp_info_text ) && $exp_info_code == 2 ) {
|
||||
return sprintf( '<div class="notice inline notice-error notice-alt">%s</div>', wp_kses_post( wpautop( $exp_info_text ) ) );
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Hide "Buy Permalink Manager Pro" alert
|
||||
*
|
||||
* @param array $alerts
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
function pro_alerts( $alerts = array() ) {
|
||||
// Check expiration date
|
||||
$exp_info_text = self::get_expiration_date( false, true, false );
|
||||
$exp_info_code = self::get_expiration_date( true, true, false );
|
||||
|
||||
if ( ! empty( $exp_info_text ) && $exp_info_code >= 2 ) {
|
||||
$alerts['licence_key'] = array( 'txt' => $exp_info_text, 'type' => 'notice-error', 'plugin_only' => true, 'dismissed_time' => DAY_IN_SECONDS * 3 );
|
||||
}
|
||||
|
||||
return $alerts;
|
||||
}
|
||||
}
|
||||
+906
@@ -0,0 +1,906 @@
|
||||
<?php
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) exit;
|
||||
|
||||
/**
|
||||
* A set of functions for processing and applying the custom permalink to posts
|
||||
*/
|
||||
class Permalink_Manager_URI_Functions_Post {
|
||||
|
||||
public function __construct() {
|
||||
add_action( 'admin_init', array( $this, 'admin_init' ), 99, 3 );
|
||||
|
||||
add_filter( '_get_page_link', array( $this, 'custom_post_permalinks' ), 99, 2 );
|
||||
add_filter( 'page_link', array( $this, 'custom_post_permalinks' ), 99, 3 );
|
||||
add_filter( 'post_link', array( $this, 'custom_post_permalinks' ), 99, 3 );
|
||||
add_filter( 'post_type_link', array( $this, 'custom_post_permalinks' ), 99, 3 );
|
||||
add_filter( 'attachment_link', array( $this, 'custom_post_permalinks' ), 99, 2 );
|
||||
|
||||
add_filter( 'permalink_manager_uris', array( $this, 'exclude_homepage' ), 99 );
|
||||
|
||||
add_filter( 'url_to_postid', array( $this, 'url_to_postid' ), 9 );
|
||||
|
||||
add_filter( 'get_sample_permalink_html', array( $this, 'edit_uri_box' ), 20, 5 );
|
||||
|
||||
add_action( 'save_post', array( $this, 'update_post_hook' ), 99, 1 );
|
||||
add_action( 'edit_attachment', array( $this, 'update_post_hook' ), 99, 1 );
|
||||
add_action( 'wp_insert_post', array( $this, 'insert_post_hook' ), 99, 1 );
|
||||
add_action( 'add_attachment', array( $this, 'insert_post_hook' ), 99, 1 );
|
||||
add_action( 'wp_trash_post', array( $this, 'remove_post_hook' ), 100, 1 );
|
||||
add_action( 'delete_post', array( $this, 'remove_post_hook' ), 100, 1 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add "Custom Permalink" input field to "Quick Edit" form
|
||||
*/
|
||||
function admin_init() {
|
||||
$post_types = Permalink_Manager_Helper_Functions::get_post_types_array();
|
||||
|
||||
// Add "URI Editor" to "Quick Edit" for all post_types
|
||||
foreach ( $post_types as $post_type => $label ) {
|
||||
add_filter( "manage_{$post_type}_posts_columns", array( $this, 'quick_edit_column' ) );
|
||||
add_filter( "manage_{$post_type}_posts_custom_column", array( $this, 'quick_edit_column_content' ), 10, 2 );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply the custom permalinks to the posts
|
||||
*
|
||||
* @param string $permalink
|
||||
* @param WP_Post|int $post
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
static function custom_post_permalinks( $permalink, $post, $leavename = false ) {
|
||||
global $permalink_manager_uris, $permalink_manager_options, $permalink_manager_ignore_permalink_filters;
|
||||
|
||||
// Do not filter permalinks in Customizer
|
||||
if ( function_exists( 'is_customize_preview' ) && is_customize_preview() ) {
|
||||
return $permalink;
|
||||
}
|
||||
|
||||
// Do not filter in WPML String Editor
|
||||
if ( ! empty( $_REQUEST['icl_ajx_action'] ) && $_REQUEST['icl_ajx_action'] == 'icl_st_save_translation' ) {
|
||||
return $permalink;
|
||||
}
|
||||
|
||||
// WPML (prevent duplicated posts)
|
||||
if ( ! empty( $_REQUEST['trid'] ) && ! empty( $_REQUEST['skip_sitepress_actions'] ) ) {
|
||||
return $permalink;
|
||||
}
|
||||
|
||||
// Do not run when metaboxes are loaded with Gutenberg
|
||||
/* if ( ! empty( $_REQUEST['meta-box-loader'] ) && empty( $_POST['custom_uri'] ) ) {
|
||||
return $permalink;
|
||||
}*/
|
||||
|
||||
// Do not filter if $permalink_manager_ignore_permalink_filters global is set
|
||||
if ( ! empty( $permalink_manager_ignore_permalink_filters ) ) {
|
||||
return $permalink;
|
||||
}
|
||||
|
||||
$post = ( is_integer( $post ) ) ? get_post( $post ) : $post;
|
||||
|
||||
// Do not run if post object is invalid or the permalink is not string
|
||||
if ( empty( $post ) || empty( $post->ID ) || empty( $post->post_type ) || ! is_string( $permalink ) ) {
|
||||
return $permalink;
|
||||
}
|
||||
|
||||
// Start with homepage URL
|
||||
$home_url = Permalink_Manager_Permastructure_Functions::get_permalink_base( $post );
|
||||
|
||||
// Check if the post is excluded
|
||||
if ( ! empty( $post->post_type ) && Permalink_Manager_Helper_Functions::is_post_excluded( $post ) && $post->post_type !== 'attachment' ) {
|
||||
return $permalink;
|
||||
}
|
||||
|
||||
// 2A. Do not change permalink of frontpage
|
||||
if ( Permalink_Manager_Helper_Functions::is_front_page( $post->ID ) ) {
|
||||
return $permalink;
|
||||
} // 2B. Do not change permalink for drafts and future posts (+ remove trailing slash from them)
|
||||
else if ( in_array( $post->post_status, array( 'draft', 'pending', 'auto-draft', 'future' ) ) ) {
|
||||
return $permalink;
|
||||
}
|
||||
|
||||
// 3. Save the old permalink to a separate variable
|
||||
$old_permalink = $permalink;
|
||||
|
||||
// 4. Filter only the posts with custom permalink assigned
|
||||
if ( isset( $permalink_manager_uris[ $post->ID ] ) ) {
|
||||
// Encode URI?
|
||||
if ( ! empty( $permalink_manager_options['general']['decode_uris'] ) ) {
|
||||
$permalink = "{$home_url}/" . rawurldecode( "/{$permalink_manager_uris[$post->ID]}" );
|
||||
} else {
|
||||
$permalink = "{$home_url}/" . Permalink_Manager_Helper_Functions::encode_uri( "{$permalink_manager_uris[$post->ID]}" );
|
||||
}
|
||||
|
||||
// Keep the slug editor in Block Editor wherever it may help
|
||||
if ( $leavename && is_admin() ) {
|
||||
$placeholder = Permalink_Manager_Permastructure_Functions::get_post_tag( $post->post_type );
|
||||
$post_name_esc = preg_quote( get_page_uri( $post->ID ), '/' );
|
||||
|
||||
$permalink = preg_replace( "/\/({$post_name_esc})\/?$/", "/{$placeholder}/", $permalink );
|
||||
}
|
||||
} else if ( $post->post_type == 'attachment' && $post->post_parent > 0 && $post->post_parent != $post->ID && ! empty( $permalink_manager_uris[ $post->post_parent ] ) ) {
|
||||
$permalink = "{$home_url}/{$permalink_manager_uris[$post->post_parent]}/attachment/{$post->post_name}";
|
||||
}
|
||||
|
||||
return apply_filters( 'permalink_manager_filter_final_post_permalink', $permalink, $post, $old_permalink );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the provided slug is unique and then update it with SQL query.
|
||||
*
|
||||
* @param string $slug
|
||||
* @param int $id
|
||||
* @param bool $preview_mode
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
static function update_slug_by_id( $slug, $id, $preview_mode = false ) {
|
||||
global $wpdb;
|
||||
|
||||
// Update slug and make it unique
|
||||
$slug = ( empty( $slug ) ) ? get_the_title( $id ) : $slug;
|
||||
$slug = sanitize_title( $slug );
|
||||
|
||||
$new_slug = wp_unique_post_slug( $slug, $id, get_post_status( $id ), get_post_type( $id ), 0 );
|
||||
|
||||
if ( ! $preview_mode ) {
|
||||
$wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->posts} SET post_name = %s WHERE ID = %d", $new_slug, $id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
|
||||
clean_post_cache( $id );
|
||||
}
|
||||
|
||||
return $new_slug;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the currently used custom permalink (or default/empty URI)
|
||||
*
|
||||
* @param int $post_id
|
||||
* @param bool $native_uri
|
||||
* @param bool $no_fallback
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function get_post_uri( $post_id, $native_uri = false, $no_fallback = false ) {
|
||||
global $permalink_manager_uris;
|
||||
|
||||
// Check if input is post object
|
||||
$post_id = ( isset( $post_id->ID ) ) ? $post_id->ID : $post_id;
|
||||
|
||||
if ( ! empty( $permalink_manager_uris[ $post_id ] ) ) {
|
||||
$final_uri = $permalink_manager_uris[ $post_id ];
|
||||
} else if ( ! $no_fallback ) {
|
||||
$final_uri = self::get_default_post_uri( $post_id, $native_uri );
|
||||
} else {
|
||||
$final_uri = '';
|
||||
}
|
||||
|
||||
return $final_uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the default custom permalink (not overwritten by the user) or native permalink (unfiltered)
|
||||
*
|
||||
* @param WP_Post|int $post
|
||||
* @param bool $native_uri
|
||||
* @param bool $check_if_disabled
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function get_default_post_uri( $post, $native_uri = false, $check_if_disabled = false ) {
|
||||
global $permalink_manager_uris, $permalink_manager_permastructs, $wp_post_types;
|
||||
|
||||
// Disable WPML adjust ID filter
|
||||
if ( class_exists( 'SitePress' ) ) {
|
||||
add_filter( 'wpml_disable_term_adjust_id', '__return_true', 999 );
|
||||
}
|
||||
|
||||
// Load all bases & post
|
||||
$post = is_object( $post ) ? $post : get_post( $post );
|
||||
|
||||
// Check if post ID is defined (and front page permalinks should be empty)
|
||||
if ( empty( $post->ID ) || Permalink_Manager_Helper_Functions::is_front_page( $post->ID ) ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$post_type = $post->post_type;
|
||||
|
||||
if ( empty( $post->post_name ) ) {
|
||||
$pre_post_name = Permalink_Manager_Helper_Functions::sanitize_title( $post->post_title );
|
||||
$post_name = wp_unique_post_slug( $pre_post_name, $post->ID, 'publish', $post->post_type, $post->post_parent );
|
||||
} else {
|
||||
$post_name = $post->post_name;
|
||||
}
|
||||
|
||||
// 1A. Check if post type is allowed
|
||||
if ( $check_if_disabled && Permalink_Manager_Helper_Functions::is_post_type_disabled( $post_type ) ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// 1A. Get the native permastructure
|
||||
if ( $post_type == 'attachment' ) {
|
||||
$parent_page = ( $post->post_parent > 0 && $post->post_parent != $post->ID ) ? get_post( $post->post_parent ) : false;
|
||||
|
||||
if ( ! empty( $parent_page->ID ) ) {
|
||||
$parent_page_uri = ( ! empty( $permalink_manager_uris[ $parent_page->ID ] ) ) ? $permalink_manager_uris[ $parent_page->ID ] : get_page_uri( $parent_page->ID );
|
||||
} else {
|
||||
$parent_page_uri = "";
|
||||
}
|
||||
|
||||
$native_permastructure = ( $parent_page ) ? trim( $parent_page_uri, "/" ) . "/attachment" : "";
|
||||
} else {
|
||||
$native_permastructure = Permalink_Manager_Permastructure_Functions::get_default_permastruct( $post_type );
|
||||
}
|
||||
|
||||
// 1B. Get the permastructure
|
||||
if ( $native_uri ) {
|
||||
$permastructure = $native_permastructure;
|
||||
} else {
|
||||
$permastructure = ( ! empty( $permalink_manager_permastructs['post_types'][ $post_type ] ) ) ? $permalink_manager_permastructs['post_types'][ $post_type ] : $native_permastructure;
|
||||
$permastructure = apply_filters( 'permalink_manager_filter_permastructure', $permastructure, $post );
|
||||
}
|
||||
|
||||
// 1C. Set the permastructure
|
||||
$default_base = ( ! empty( $permastructure ) ) ? trim( $permastructure, '/' ) : "";
|
||||
|
||||
// 2A. Get the date
|
||||
$date = explode( " ", date( 'Y m d H i s', strtotime( $post->post_date ) ) );
|
||||
$monthname = sanitize_title( date_i18n( 'F', strtotime( $post->post_date ) ) );
|
||||
|
||||
// 2B. Get the author (if needed)
|
||||
$author = '';
|
||||
if ( strpos( $default_base, '%author%' ) !== false ) {
|
||||
$authordata = get_userdata( $post->post_author );
|
||||
$author = $authordata->user_nicename;
|
||||
}
|
||||
|
||||
// 2C. Get the post type slug
|
||||
if ( ! empty( $wp_post_types[ $post_type ] ) ) {
|
||||
if ( ! empty( $wp_post_types[ $post_type ]->rewrite['slug'] ) ) {
|
||||
$post_type_slug = $wp_post_types[ $post_type ]->rewrite['slug'];
|
||||
} else if ( is_string( $wp_post_types[ $post_type ]->rewrite ) ) {
|
||||
$post_type_slug = $wp_post_types[ $post_type ]->rewrite;
|
||||
}
|
||||
}
|
||||
|
||||
$post_type_slug = ( ! empty( $post_type_slug ) ) ? $post_type_slug : $post_type;
|
||||
$post_type_slug = apply_filters( 'permalink_manager_filter_post_type_slug', $post_type_slug, $post, $post_type );
|
||||
$post_type_slug = preg_replace( '/(%([^%]+)%\/?)/', '', $post_type_slug );
|
||||
|
||||
// 3B. Get the full slug
|
||||
$post_name = Permalink_Manager_Helper_Functions::remove_slashes( $post_name );
|
||||
$custom_slug = $full_custom_slug = Permalink_Manager_Helper_Functions::force_custom_slugs( $post_name, $post, true, null, false );
|
||||
$post_title_slug = Permalink_Manager_Helper_Functions::force_custom_slugs( $post_name, $post, true, 1 );
|
||||
$full_native_slug = $post_name;
|
||||
|
||||
// 3A. Fix for hierarchical CPT (start)
|
||||
if ( $post->ancestors && is_post_type_hierarchical( $post_type ) ) {
|
||||
$full_native_slug = Permalink_Manager_Helper_Functions::get_post_full_slug( $post, false, true );
|
||||
$full_custom_slug = Permalink_Manager_Helper_Functions::get_post_full_slug( $post, false, false );
|
||||
}
|
||||
|
||||
// 3B. Allow filter the default slug (only custom permalinks)
|
||||
if ( ! $native_uri ) {
|
||||
$full_slug = apply_filters( 'permalink_manager_filter_default_post_slug', $full_custom_slug, $post, $post_name );
|
||||
} else {
|
||||
$full_slug = $full_native_slug;
|
||||
}
|
||||
|
||||
$post_type_tag = Permalink_Manager_Permastructure_Functions::get_post_tag( $post_type );
|
||||
|
||||
// 3C. Get the standard tags and replace them with their values
|
||||
$tags = array( '%year%', '%monthnum%', '%monthname%', '%day%', '%hour%', '%minute%', '%second%', '%post_id%', '%author%', '%post_type%' );
|
||||
$tags_replacements = array( $date[0], $date[1], $monthname, $date[2], $date[3], $date[4], $date[5], $post->ID, $author, $post_type_slug );
|
||||
$default_uri = str_replace( $tags, $tags_replacements, $default_base );
|
||||
|
||||
// 3D. Get the slug tags
|
||||
$slug_tags = array( $post_type_tag, "%postname%", "%postname_flat%", "%pagename_flat%", "%{$post_type}_flat%", "%native_slug%", '%native_title%' );
|
||||
$slug_tags_replacement = array( $full_slug, $full_slug, $custom_slug, $custom_slug, $custom_slug, $full_native_slug, $post_title_slug );
|
||||
|
||||
$do_not_append_slug = Permalink_Manager_Permastructure_Functions::is_slug_tag_present( $default_uri, $slug_tags, $post );
|
||||
|
||||
// 3E. Replace the post tags with slugs or append the slug if no post tag is defined
|
||||
if ( ! empty( $do_not_append_slug ) ) {
|
||||
$default_uri = str_replace( $slug_tags, $slug_tags_replacement, $default_uri );
|
||||
} else {
|
||||
$default_uri .= "/{$full_slug}";
|
||||
}
|
||||
|
||||
// 4. Replace taxonomies
|
||||
$taxonomies = get_taxonomies();
|
||||
|
||||
if ( $taxonomies ) {
|
||||
foreach ( $taxonomies as $taxonomy ) {
|
||||
// 0. Check if taxonomy tag is present
|
||||
if ( strpos( $default_uri, "%{$taxonomy}" ) === false ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 1. Get terms assigned to this post
|
||||
$terms = wp_get_object_terms( $post->ID, $taxonomy );
|
||||
|
||||
// 2. Sort the terms
|
||||
if ( ! empty( $terms ) ) {
|
||||
$terms = wp_list_sort( $terms, array(
|
||||
'parent' => 'DESC',
|
||||
'term_id' => 'ASC',
|
||||
) );
|
||||
}
|
||||
|
||||
// 3A. Try to use Yoast SEO Primary Term
|
||||
$replacement_term = Permalink_Manager_Helper_Functions::get_primary_term( $post->ID, $taxonomy, false );
|
||||
|
||||
// 3B. Get the first assigned term to this taxonomy
|
||||
if ( empty( $replacement_term ) ) {
|
||||
$replacement_term = ( ! is_wp_error( $terms ) && ! empty( $terms ) && is_object( $terms[0] ) ) ? Permalink_Manager_Helper_Functions::get_lowest_element( $terms[0], $terms ) : '';
|
||||
}
|
||||
|
||||
$replacement_term = apply_filters( 'permalink_manager_filter_post_terms', $replacement_term, $post, $terms, $taxonomy, $native_uri );
|
||||
|
||||
// 4A. Custom URI as term base
|
||||
if ( ! empty( $replacement_term->term_id ) && strpos( $default_uri, "%{$taxonomy}_custom_uri%" ) !== false && ! empty( $permalink_manager_uris["tax-{$replacement_term->term_id}"] ) ) {
|
||||
$mode = 1;
|
||||
} // 4B. Hierarchical term base
|
||||
else if ( ! empty( $replacement_term->term_id ) && strpos( $default_uri, "%{$taxonomy}_flat%" ) === false && strpos( $default_uri, "%{$taxonomy}_top%" ) === false && is_taxonomy_hierarchical( $taxonomy ) ) {
|
||||
$mode = 2;
|
||||
} // 4C. Force flat/non-hierarchical term base - get the highest level term (if %taxonomy_top% tag is used)
|
||||
else if ( strpos( $default_uri, "%{$taxonomy}_top%" ) !== false ) {
|
||||
$mode = 3;
|
||||
} // 4D. Force flat/non-hierarchical term base - get the lowest level term (if %taxonomy_flat% tag is used)
|
||||
else {
|
||||
$mode = 4;
|
||||
}
|
||||
|
||||
// Get the replacement slug (custom + native)
|
||||
$replacement = Permalink_Manager_Helper_Functions::get_term_full_slug( $replacement_term, $terms, $mode, $native_uri );
|
||||
$native_replacement = Permalink_Manager_Helper_Functions::get_term_full_slug( $replacement_term, $terms, $mode, true );
|
||||
|
||||
// Trim slashes
|
||||
$replacement = trim( $replacement, '/' );
|
||||
$native_replacement = trim( $native_replacement, '/' );
|
||||
|
||||
// Filter final category slug
|
||||
$replacement = apply_filters( 'permalink_manager_filter_term_slug', $replacement, $replacement_term, $post, $terms, $taxonomy, $native_uri );
|
||||
|
||||
// 4. Do the replacement
|
||||
$default_uri = ( ! empty( $replacement ) ) ? str_replace( array( "%{$taxonomy}%", "%{$taxonomy}_flat%", "%{$taxonomy}_custom_uri%", "%{$taxonomy}_top%" ), $replacement, $default_uri ) : $default_uri;
|
||||
$default_uri = ( ! empty( $native_replacement ) ) ? str_replace( "%{$taxonomy}_native_slug%", $native_replacement, $default_uri ) : $default_uri;
|
||||
}
|
||||
}
|
||||
|
||||
// Restore WPML adjust ID filter
|
||||
if ( class_exists( 'SitePress' ) ) {
|
||||
remove_filter( 'wpml_disable_term_adjust_id', '__return_true', 999 );
|
||||
}
|
||||
|
||||
return apply_filters( 'permalink_manager_filter_default_post_uri', $default_uri, $post->post_name, $post, $post_name, $native_uri );
|
||||
}
|
||||
|
||||
/**
|
||||
* Exclude the page selected as "Front page"
|
||||
*
|
||||
* @param array $uris
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
function exclude_homepage( $uris ) {
|
||||
// Find the homepage URI
|
||||
$homepage_id = get_option( 'page_on_front' );
|
||||
|
||||
if ( is_array( $uris ) && ! empty( $uris[ $homepage_id ] ) ) {
|
||||
unset( $uris[ $homepage_id ] );
|
||||
}
|
||||
|
||||
return $uris;
|
||||
}
|
||||
|
||||
/**
|
||||
* Support url_to_postid() function
|
||||
*
|
||||
* @param string $url
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function url_to_postid( $url ) {
|
||||
global $pm_query;
|
||||
|
||||
// Filter only defined URLs
|
||||
if ( empty( $url ) ) {
|
||||
return $url;
|
||||
}
|
||||
|
||||
// Make sure that $pm_query global is not changed
|
||||
$old_pm_query = $pm_query;
|
||||
$post = Permalink_Manager_Core_Functions::detect_post( array(), $url, true );
|
||||
$pm_query = $old_pm_query;
|
||||
|
||||
if ( ! empty( $post->ID ) ) {
|
||||
$native_url = "/?p={$post->ID}";
|
||||
}
|
||||
|
||||
return ( ! empty( $native_url ) ) ? $native_url : $url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get array with all post items based on the user-selected settings in the "Bulk tools" form
|
||||
*
|
||||
* @return array|false
|
||||
*/
|
||||
public static function get_items() {
|
||||
global $wpdb, $permalink_manager_options;
|
||||
|
||||
// Check if post types & statuses are not empty
|
||||
if ( empty( $_POST['post_types'] ) || empty( $_POST['post_statuses'] ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$post_types_array = array_map( 'sanitize_key', $_POST['post_types'] );
|
||||
$post_statuses_array = array_map( 'sanitize_key', $_POST['post_statuses'] );
|
||||
$post_types_in = Permalink_Manager_Helper_Functions::prepare_array_for_sql_in( $post_types_array, false );
|
||||
$post_statuses_in = Permalink_Manager_Helper_Functions::prepare_array_for_sql_in( $post_statuses_array, false );
|
||||
|
||||
// Filter the posts by IDs
|
||||
$where = '';
|
||||
if ( ! empty( $_POST['ids'] ) ) {
|
||||
// Remove whitespaces and prepare array with IDs and/or ranges
|
||||
$ids = esc_sql( preg_replace( '/\s*/m', '', $_POST['ids'] ) );
|
||||
preg_match_all( "/([\d]+(?:-?[\d]+)?)/x", $ids, $groups );
|
||||
|
||||
// Prepare the extra ID filters
|
||||
$where .= "AND (";
|
||||
foreach ( $groups[0] as $group ) {
|
||||
$where .= ( $group == reset( $groups[0] ) ) ? "" : " OR ";
|
||||
// A. Single number
|
||||
if ( is_numeric( $group ) ) {
|
||||
$where .= "(ID = {$group})";
|
||||
} // B. Range
|
||||
else if ( substr_count( $group, '-' ) ) {
|
||||
$range_edges = explode( "-", $group );
|
||||
$where .= "(ID BETWEEN {$range_edges[0]} AND {$range_edges[1]})";
|
||||
}
|
||||
}
|
||||
$where .= ")";
|
||||
}
|
||||
|
||||
// Get excluded items
|
||||
$excluded_posts = (array) apply_filters( 'permalink_manager_excluded_post_ids', array() );
|
||||
if ( ! empty( $excluded_posts ) ) {
|
||||
$where .= sprintf( " AND ID NOT IN (%s) ", Permalink_Manager_Helper_Functions::prepare_array_for_sql_in( $excluded_posts ) );
|
||||
}
|
||||
|
||||
// Support for attachments
|
||||
$attachment_support = ( in_array( 'attachment', $post_types_array ) ) ? " OR (post_type = 'attachment')" : "";
|
||||
|
||||
// Check the auto-update mode
|
||||
// A. Allow only user-approved posts
|
||||
if ( ! empty( $permalink_manager_options["general"]["auto_update_uris"] ) && $permalink_manager_options["general"]["auto_update_uris"] == 2 ) {
|
||||
$where .= " AND pm.meta_value IN (1, -1) ";
|
||||
} // B. Allow all posts not disabled by the user
|
||||
else {
|
||||
$where .= " AND (pm.meta_value IS NULL OR pm.meta_value IN (1, -1)) ";
|
||||
}
|
||||
|
||||
// Get the rows before they are altered
|
||||
$query = "SELECT post_type, post_title, post_name, ID FROM {$wpdb->posts} AS p LEFT JOIN {$wpdb->postmeta} AS pm ON pm.post_ID = p.ID AND pm.meta_key = 'auto_update_uri' WHERE ((post_status IN ({$post_statuses_in}) AND post_type IN ({$post_types_in})){$attachment_support}) {$where}";
|
||||
$query = apply_filters( 'permalink_manager_get_items_query', $query, $where, 'post_types' );
|
||||
|
||||
return $wpdb->get_results( $query, ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the permalinks/slugs "Find & replace" & "Regenerate/rest" tool
|
||||
*
|
||||
* @param array $chunk
|
||||
* @param string $mode
|
||||
* @param string $operation
|
||||
* @param string $old_string
|
||||
* @param string $new_string
|
||||
* @param bool $preview_mode
|
||||
*
|
||||
* @return array|false
|
||||
*/
|
||||
public static function bulk_process_items( $chunk = null, $mode = '', $operation = '', $old_string = '', $new_string = '', $preview_mode = false ) {
|
||||
// Reset variables
|
||||
$updated_slugs_count = 0;
|
||||
$updated_array = array();
|
||||
|
||||
// Get the rows before they are altered
|
||||
$posts_to_update = ( ! empty( $chunk ) ) ? $chunk : self::get_items();
|
||||
|
||||
if ( empty( $operation ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Now if the array is not empty use IDs from each subarray as a key
|
||||
if ( $posts_to_update ) {
|
||||
foreach ( $posts_to_update as $row ) {
|
||||
// Get default & native URL
|
||||
$native_uri = self::get_default_post_uri( $row['ID'], true );
|
||||
$default_uri = self::get_default_post_uri( $row['ID'] );
|
||||
$old_custom_uri = Permalink_Manager_URI_Functions::get_single_uri( $row['ID'], true, true );
|
||||
$old_uri = ( ! empty( $old_custom_uri ) ) ? $old_custom_uri : $native_uri;
|
||||
|
||||
$old_post_name = $row['post_name'];
|
||||
|
||||
if ( $operation == 'regenerate' ) {
|
||||
if ( $mode == 'slugs' ) {
|
||||
$new_uri = $old_uri;
|
||||
$new_post_name = Permalink_Manager_Helper_Functions::sanitize_title( $row['post_title'] );
|
||||
} else if ( $mode == 'native' ) {
|
||||
$new_uri = $native_uri;
|
||||
$new_post_name = $old_post_name;
|
||||
} else {
|
||||
$new_uri = $default_uri;
|
||||
$new_post_name = $old_post_name;
|
||||
}
|
||||
} else {
|
||||
list( $new_post_name, $new_uri ) = Permalink_Manager_Helper_Functions::replace_uri_slug( $old_string, $new_string, $old_post_name, $old_uri, $mode );
|
||||
}
|
||||
|
||||
// Check if native slug should be changed
|
||||
if ( $mode == 'slugs' && $old_post_name !== $new_post_name ) {
|
||||
$new_post_name = self::update_slug_by_id( $new_post_name, $row['ID'], $preview_mode );
|
||||
}
|
||||
|
||||
$new_uri = apply_filters( 'permalink_manager_pre_update_post_uri', $new_uri, $row['ID'], $old_uri, $native_uri, $default_uri );
|
||||
|
||||
if ( ! ( empty( $new_uri ) ) && ( $old_custom_uri !== $new_uri ) || ( $old_post_name !== $new_post_name ) ) {
|
||||
if ( ! $preview_mode && ( $old_custom_uri !== $new_uri ) ) {
|
||||
Permalink_Manager_URI_Functions::save_single_uri( $row['ID'], $new_uri, false, false );
|
||||
do_action( 'permalink_manager_updated_post_uri', $row['ID'], $new_uri, $old_uri, $native_uri, $default_uri );
|
||||
}
|
||||
|
||||
$updated_array[] = array( 'item_title' => $row['post_title'], 'ID' => $row['ID'], 'old_uri' => $old_uri, 'new_uri' => $new_uri, 'old_slug' => $old_post_name, 'new_slug' => $new_post_name );
|
||||
$updated_slugs_count ++;
|
||||
}
|
||||
}
|
||||
|
||||
// Save all custom permalinks
|
||||
if ( ! $preview_mode ) {
|
||||
Permalink_Manager_URI_Functions::save_all_uris();
|
||||
}
|
||||
|
||||
$output = array( 'updated' => $updated_array, 'updated_count' => $updated_slugs_count );
|
||||
wp_reset_postdata();
|
||||
}
|
||||
|
||||
return ( ! empty( $output ) ) ? $output : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the custom permalinks in "Bulk URI Editor" tool
|
||||
*
|
||||
* @return array|false
|
||||
*/
|
||||
static public function update_all_permalinks() {
|
||||
// Setup needed variables
|
||||
$updated_slugs_count = 0;
|
||||
$updated_array = array();
|
||||
|
||||
$new_uris = isset( $_POST['uri'] ) ? $_POST['uri'] : array();
|
||||
|
||||
// Double check if the slugs and ids are stored in arrays
|
||||
if ( ! is_array( $new_uris ) ) {
|
||||
$new_uris = explode( ',', $new_uris );
|
||||
}
|
||||
|
||||
if ( ! empty( $new_uris ) ) {
|
||||
foreach ( $new_uris as $id => $new_uri ) {
|
||||
// Prepare variables
|
||||
$this_post = get_post( $id );
|
||||
$old_uri = Permalink_Manager_URI_Functions::get_single_uri( $this_post, false, true );
|
||||
|
||||
$final_uri = self::save_uri( $this_post, $new_uri, false, false, false );
|
||||
|
||||
if ( $final_uri ) {
|
||||
$updated_array[] = array( 'item_title' => get_the_title( $id ), 'ID' => $id, 'old_uri' => $old_uri, 'new_uri' => $final_uri );
|
||||
$updated_slugs_count ++;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Save all custom permalinks
|
||||
Permalink_Manager_URI_Functions::save_all_uris();
|
||||
|
||||
$output = array( 'updated' => $updated_array, 'updated_count' => $updated_slugs_count );
|
||||
}
|
||||
|
||||
return ( ! empty( $output ) ) ? $output : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Allow to edit URIs from "Edit Post" admin pages
|
||||
*
|
||||
* @param string $html
|
||||
* @param int $id
|
||||
* @param string $new_title
|
||||
* @param string $new_slug
|
||||
* @param WP_Post $post
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
function edit_uri_box( $html, $id, $new_title, $new_slug, $post ) {
|
||||
// Detect auto drafts
|
||||
$autosave = ( ! empty( $new_title ) && empty( $new_slug ) ) ? true : false;
|
||||
|
||||
// Check if the post is excluded
|
||||
if ( empty( $post->post_type ) || Permalink_Manager_Helper_Functions::is_post_excluded( $post, true ) ) {
|
||||
$show_uri_editor = false;
|
||||
} else {
|
||||
$show_uri_editor = true;
|
||||
}
|
||||
|
||||
// Stop the hook (if needed)
|
||||
$show_uri_editor = apply_filters( "permalink_manager_show_uri_editor_post", $show_uri_editor, $post, $post->post_type );
|
||||
if ( ! $show_uri_editor ) {
|
||||
return $html;
|
||||
}
|
||||
|
||||
// Make sure that home URL ends with slash
|
||||
$home_url = Permalink_Manager_Permastructure_Functions::get_permalink_base( $post );
|
||||
|
||||
// A. Display the original permalink on the front-page editor
|
||||
if ( Permalink_Manager_Helper_Functions::is_front_page( $id ) ) {
|
||||
preg_match( '/href="([^"]+)"/mi', $html, $matches );
|
||||
$sample_permalink = ( ! empty( $matches[1] ) ) ? $matches[1] : "";
|
||||
} else {
|
||||
// B. Do not change anything if post is not saved yet (display sample permalink instead)
|
||||
if ( $autosave || empty( $post->post_status ) ) {
|
||||
$sample_permalink_uri = self::get_default_post_uri( $id );
|
||||
} // C. Display custom URI (if set) or default custom URI (for drafts)
|
||||
else {
|
||||
$is_draft = ( $post->post_status == 'draft' ) ? true : false;
|
||||
$sample_permalink_uri = Permalink_Manager_URI_Functions::get_single_uri( $post, ! $is_draft, false );
|
||||
}
|
||||
|
||||
if ( empty( $sample_permalink_uri ) && $post->post_type !== 'attachment' ) {
|
||||
return $html;
|
||||
}
|
||||
|
||||
// Decode URI & allow to filter it
|
||||
$sample_permalink_uri = apply_filters( 'permalink_manager_filter_post_sample_uri', rawurldecode( $sample_permalink_uri ), $post );
|
||||
|
||||
// Prepare the sample & default permalink
|
||||
$sample_permalink = sprintf( "%s/<span class=\"editable\">%s</span>", $home_url, str_replace( "//", "/", $sample_permalink_uri ) );
|
||||
}
|
||||
|
||||
$sample_permalink_html = sprintf( "<span id=\"sample-permalink\"><span class=\"sample-permalink-span\"><a id=\"sample-permalink\" href=\"%s\">%s</a></span></span> ", strip_tags( $sample_permalink ), $sample_permalink );
|
||||
|
||||
// 1. Overwrite the sample permalink
|
||||
if ( preg_match( '/(<span id="sample-permalink"><a.*<\/a><\/span>)/m', $html ) ) {
|
||||
$new_html = preg_replace( '/(<span id="sample-permalink"><a.*<\/a><\/span>)/m', $sample_permalink_html, $html );
|
||||
} else if ( preg_match( '/(<a id="sample-permalink"[^<]*>.*<\/a>)/m', $html ) ) {
|
||||
$new_html = preg_replace( '/(<a id="sample-permalink"[^<]*>.*<\/a>)/m', $sample_permalink_html, $html );
|
||||
} else {
|
||||
$new_html = $html;
|
||||
}
|
||||
|
||||
// 2. Append the Permalink Editor
|
||||
$new_html .= Permalink_Manager_UI_Elements::display_uri_box( $post );
|
||||
|
||||
// 3. Hide the "Edit" slug button
|
||||
$new_html = str_replace( 'edit-slug button', 'edit-slug button hidden', $new_html );
|
||||
|
||||
// 4. Append hidden field with native slug
|
||||
$new_html .= ( ! empty( $post->post_name ) && strpos( $new_html, 'editable-post-name-full' ) === false ) ? "<span id=\"editable-post-name-full\">{$post->post_name}</span>" : "";
|
||||
|
||||
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
|
||||
return $new_html;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add "Current URI" input field to "Quick Edit" form
|
||||
*
|
||||
* @param array $columns
|
||||
*
|
||||
* @return array mixed
|
||||
*/
|
||||
function quick_edit_column( $columns ) {
|
||||
global $current_screen;
|
||||
|
||||
// Get post type
|
||||
$post_type = ( ! empty( $current_screen->post_type ) ) ? $current_screen->post_type : false;
|
||||
|
||||
// Check if post type is disabled
|
||||
if ( $post_type && Permalink_Manager_Helper_Functions::is_post_type_disabled( $post_type ) ) {
|
||||
return $columns;
|
||||
}
|
||||
|
||||
return ( is_array( $columns ) ) ? array_merge( $columns, array( 'permalink-manager-col' => __( 'Custom permalink', 'permalink-manager' ) ) ) : $columns;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the URI of the current post in the "Custom Permalink" column
|
||||
*
|
||||
* @param string $column_name The name of the column to display. In this case, we named our column permalink-manager-col.
|
||||
* @param int $post_id The ID of the term.
|
||||
*/
|
||||
function quick_edit_column_content( $column_name, $post_id ) {
|
||||
global $permalink_manager_uris, $permalink_manager_options;
|
||||
|
||||
if ( $column_name == 'permalink-manager-col' ) {
|
||||
$exclude_drafts = ( isset( $permalink_manager_options['general']['ignore_drafts'] ) ) ? $permalink_manager_options['general']['ignore_drafts'] : false;
|
||||
$is_draft = ( get_post_status( $post_id ) == 'draft' ) ? true : false;
|
||||
|
||||
// A. Disable the 'Quick Edit' form for draft posts if 'Exclude drafts' option is turned on
|
||||
if ( $exclude_drafts && $is_draft ) {
|
||||
$disabled = 1;
|
||||
} // B. Get auto-update settings
|
||||
else {
|
||||
$auto_update_val = get_post_meta( $post_id, 'auto_update_uri', true );
|
||||
$disabled = ( ! empty( $auto_update_val ) ) ? $auto_update_val : $permalink_manager_options['general']['auto_update_uris'];
|
||||
}
|
||||
|
||||
$uri = ( ! empty( $permalink_manager_uris[ $post_id ] ) ) ? rawurldecode( $permalink_manager_uris[ $post_id ] ) : self::get_post_uri( $post_id, true, $is_draft );
|
||||
printf( '<span class="permalink-manager-col-uri" data-disabled="%s">%s</span>', esc_attr( intval( $disabled ) ), esc_html( $uri ) );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the custom permalink
|
||||
*
|
||||
* @param int|WP_Post $post
|
||||
* @param string $new_uri
|
||||
* @param bool $is_new_post
|
||||
* @param int|bool $auto_update_mode
|
||||
*
|
||||
* @return bool|string
|
||||
*/
|
||||
static function save_uri( $post, $new_uri = '', $is_new_post = false, $auto_update_mode = false, $db_save = true ) {
|
||||
global $permalink_manager_options;
|
||||
|
||||
// Do not do anything if post is auto-saved
|
||||
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Get the post object
|
||||
if ( is_numeric( $post ) ) {
|
||||
$post_object = get_post( $post );
|
||||
} else if ( is_a( $post, 'WP_Post' ) ) {
|
||||
$post_object = $post;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if post is allowed
|
||||
if ( empty( $post_object->post_type ) || ( $is_new_post && empty( $post_object->post_title ) ) || Permalink_Manager_Helper_Functions::is_post_excluded( $post_object, true, $is_new_post ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Manage 'Auto-update URI' settings
|
||||
if ( ! empty( $auto_update_mode ) ) {
|
||||
$auto_update_uri = $auto_update_mode;
|
||||
update_post_meta( $post_object->ID, 'auto_update_uri', $auto_update_mode );
|
||||
} elseif ( $auto_update_mode === 0 ) {
|
||||
$auto_update_uri = $permalink_manager_options['general']['auto_update_uris'];
|
||||
delete_post_meta( $post_object->ID, 'auto_update_uri' );
|
||||
} else {
|
||||
$auto_update_uri = get_post_meta( $post_object->ID, 'auto_update_uri', true );
|
||||
$auto_update_uri = ( ! empty( $auto_update_uri ) ) ? $auto_update_uri : $permalink_manager_options['general']['auto_update_uris'];
|
||||
}
|
||||
|
||||
$default_uri = self::get_default_post_uri( $post_object );
|
||||
$native_uri = self::get_default_post_uri( $post_object, true );
|
||||
$old_uri = self::get_post_uri( $post_object->ID, false, true );
|
||||
|
||||
if ( $is_new_post ) {
|
||||
$new_uri = $default_uri;
|
||||
$allow_save = apply_filters( 'permalink_manager_allow_new_post_uri', true, $post_object );
|
||||
} else {
|
||||
$new_uri = ( ( $new_uri == '' || $auto_update_uri == 1 ) && ! in_array( $post_object->post_status, array( 'draft', 'auto-draft' ) ) ) ? $default_uri : Permalink_Manager_Helper_Functions::sanitize_title( $new_uri, true );
|
||||
$allow_save = apply_filters( 'permalink_manager_allow_update_post_uri', true, $post_object );
|
||||
}
|
||||
|
||||
$new_uri = apply_filters( 'permalink_manager_pre_update_post_uri', $new_uri, $post_object->ID, $old_uri, $native_uri, $default_uri );
|
||||
|
||||
// The update URI process is stopped by the hook above or disabled in "Auto-update" settings
|
||||
if ( ! $allow_save || ( ! empty( $auto_update_uri ) && $auto_update_uri == 2 ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Save the URI only if $new_uri variable is set
|
||||
if ( ! empty( $new_uri ) && $new_uri !== $old_uri ) {
|
||||
Permalink_Manager_URI_Functions::save_single_uri( $post_object->ID, $new_uri, false, $db_save );
|
||||
$uri_saved = true;
|
||||
} // The $new_uri variable is empty or no change is detected
|
||||
else {
|
||||
$uri_saved = false;
|
||||
}
|
||||
|
||||
do_action( 'permalink_manager_updated_post_uri', $post_object->ID, $new_uri, $old_uri, $native_uri, $default_uri, $uri_saved );
|
||||
|
||||
return ( $uri_saved ) ? $new_uri : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate the custom permalink when 'wp_insert_post' action is triggered
|
||||
*
|
||||
* @param int $post_id Post ID.
|
||||
*/
|
||||
function insert_post_hook( $post_id ) {
|
||||
global $permalink_manager_uris;
|
||||
|
||||
// Do not trigger if post is a revision or imported via WP All Import (URI should be set after the post meta is added)
|
||||
if ( empty( $post_id ) || wp_is_post_revision( $post_id ) || ( ! empty( $_REQUEST['page'] ) && $_REQUEST['page'] == 'pmxi-admin-import' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Stop when products are imported with WooCommerce importer
|
||||
if ( ! empty( $_REQUEST['action'] ) && $_REQUEST['action'] == 'woocommerce_do_ajax_product_import' ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Do not process REST API requests originating from Gutenberg JS functions
|
||||
if ( defined( 'REST_REQUEST' ) && REST_REQUEST && ! empty( $_SERVER['HTTP_X_WP_NONCE'] ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Do not do anything if the custom permalink was generated before or 'custom_uri' field is present in the request
|
||||
if ( isset( $permalink_manager_uris[ $post_id ] ) || ( isset( $_POST['custom_uri'] ) ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
self::save_uri( $post_id, '', true, 0 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the custom permalink when 'save_post' action is triggered
|
||||
*
|
||||
* @param int $post_id Term ID.
|
||||
*/
|
||||
static function update_post_hook( $post_id ) {
|
||||
// Verify nonce at first
|
||||
if ( ! isset( $_POST['permalink-manager-nonce'] ) || ! wp_verify_nonce( $_POST['permalink-manager-nonce'], 'permalink-manager-edit-uri-box' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Do not do anything if the field with URI or element ID are not present or different from the provided post ID
|
||||
if ( ! isset( $_POST['custom_uri'] ) || empty( $_POST['permalink-manager-edit-uri-element-id'] ) || $_POST['permalink-manager-edit-uri-element-id'] != $post_id ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if the user can edit this post
|
||||
if ( ! current_user_can( 'edit_post', $post_id ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Fix for revisions
|
||||
$post_id = wp_is_post_revision( $post_id ) ? wp_is_post_revision( $post_id ) : $post_id;
|
||||
$post = get_post( $post_id );
|
||||
|
||||
// Get auto-update URI setting (if empty use global setting)
|
||||
if ( isset( $_POST["auto_update_uri"] ) && is_numeric( $_POST["auto_update_uri"] ) ) {
|
||||
$auto_update_mode = intval( $_POST["auto_update_uri"] );
|
||||
} else {
|
||||
$auto_update_mode = false;
|
||||
}
|
||||
|
||||
// Update the slug (if changed)
|
||||
if ( isset( $_POST['permalink-manager-edit-uri-element-slug'] ) && isset( $_POST['native_slug'] ) && ( $_POST['native_slug'] !== $post->post_name ) ) {
|
||||
// Make sure that '_wp_old_slug' is saved
|
||||
if ( ! empty( $_POST['post_name'] ) || ( isset( $_POST['action'] ) && in_array( $_POST['action'], array( 'pm_save_permalink', 'editpost' ) ) ) ) {
|
||||
$post_after = clone $post;
|
||||
$post_after->post_name = sanitize_title( $_POST['native_slug'] );
|
||||
|
||||
wp_check_for_changed_slugs( $post_id, $post_after, $post );
|
||||
}
|
||||
|
||||
self::update_slug_by_id( $_POST['native_slug'], $post_id );
|
||||
}
|
||||
|
||||
self::save_uri( $post_id, $_POST['custom_uri'], false, $auto_update_mode );
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove URI from options array after post is moved to the trash
|
||||
*
|
||||
* @param int $post_id
|
||||
*/
|
||||
function remove_post_hook( $post_id ) {
|
||||
Permalink_Manager_URI_Functions::remove_single_uri( $post_id, false, true );
|
||||
}
|
||||
|
||||
}
|
||||
+682
@@ -0,0 +1,682 @@
|
||||
<?php
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* A set of functions for processing and applying the custom permalink to terms.
|
||||
*/
|
||||
class Permalink_Manager_URI_Functions_Tax {
|
||||
|
||||
public function __construct() {
|
||||
add_action( 'init', array( $this, 'init' ), 100 );
|
||||
add_action( 'rest_api_init', array( $this, 'init' ) );
|
||||
|
||||
add_filter( 'term_link', array( $this, 'custom_tax_permalinks' ), 999, 2 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Allow to edit URIs from "Edit Term" admin pages (register hooks)
|
||||
*/
|
||||
public function init() {
|
||||
global $permalink_manager_options;
|
||||
|
||||
$all_taxonomies = Permalink_Manager_Helper_Functions::get_taxonomies_array();
|
||||
|
||||
// Add "URI Editor" to "Quick Edit" for all taxonomies
|
||||
foreach ( $all_taxonomies as $tax => $label ) {
|
||||
// Check if taxonomy is allowed
|
||||
if ( Permalink_Manager_Helper_Functions::is_taxonomy_disabled( $tax ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
add_action( "edited_{$tax}", array( $this, 'update_term_uri' ), 10, 2 );
|
||||
add_action( "create_{$tax}", array( $this, 'update_term_uri' ), 10, 2 );
|
||||
add_action( "delete_{$tax}", array( $this, 'remove_term_uri' ), 10, 2 );
|
||||
|
||||
// Check the user capabilities
|
||||
if ( is_admin() ) {
|
||||
$edit_uris_cap = ( ! empty( $permalink_manager_options['general']['edit_uris_cap'] ) ) ? $permalink_manager_options['general']['edit_uris_cap'] : 'publish_posts';
|
||||
if ( current_user_can( $edit_uris_cap ) ) {
|
||||
add_action( "{$tax}_add_form_fields", array( $this, 'edit_uri_box' ), 10, 1 );
|
||||
add_action( "{$tax}_edit_form_fields", array( $this, 'edit_uri_box' ), 10, 1 );
|
||||
add_filter( "manage_edit-{$tax}_columns", array( $this, 'quick_edit_column' ) );
|
||||
add_filter( "manage_{$tax}_custom_column", array( $this, 'quick_edit_column_content' ), 20, 3 );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply the custom permalinks to the terms
|
||||
*
|
||||
* @param string $permalink
|
||||
* @param WP_Term|int $term
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
function custom_tax_permalinks( $permalink, $term ) {
|
||||
global $permalink_manager_uris, $permalink_manager_options, $permalink_manager_ignore_permalink_filters;
|
||||
|
||||
// Do not filter permalinks in Customizer
|
||||
if ( function_exists( 'is_customize_preview' ) && is_customize_preview() ) {
|
||||
return $permalink;
|
||||
}
|
||||
|
||||
// Do not filter in WPML String Editor
|
||||
if ( ! empty( $_REQUEST['icl_ajx_action'] ) && $_REQUEST['icl_ajx_action'] == 'icl_st_save_translation' ) {
|
||||
return $permalink;
|
||||
}
|
||||
|
||||
// Do not filter if $permalink_manager_ignore_permalink_filters global is set
|
||||
if ( ! empty( $permalink_manager_ignore_permalink_filters ) ) {
|
||||
return $permalink;
|
||||
}
|
||||
|
||||
$term = ( is_numeric( $term ) ) ? get_term( $term ) : $term;
|
||||
|
||||
// Check if the term is allowed
|
||||
if ( empty( $term->term_id ) || Permalink_Manager_Helper_Functions::is_term_excluded( $term ) || ! is_string( $permalink ) ) {
|
||||
return $permalink;
|
||||
}
|
||||
|
||||
// Get term id
|
||||
$term_id = $term->term_id;
|
||||
|
||||
// Save the old permalink to separate variable
|
||||
$old_permalink = $permalink;
|
||||
|
||||
if ( isset( $permalink_manager_uris["tax-{$term_id}"] ) ) {
|
||||
// Start with homepage URL
|
||||
$permalink = Permalink_Manager_Permastructure_Functions::get_permalink_base( $term );
|
||||
|
||||
// Encode URI?
|
||||
if ( ! empty( $permalink_manager_options['general']['decode_uris'] ) ) {
|
||||
$permalink .= rawurldecode( "/{$permalink_manager_uris["tax-{$term_id}"]}" );
|
||||
} else {
|
||||
$permalink .= Permalink_Manager_Helper_Functions::encode_uri( "/{$permalink_manager_uris["tax-{$term_id}"]}" );
|
||||
}
|
||||
} else if ( ! empty( $permalink_manager_options['general']['decode_uris'] ) ) {
|
||||
$permalink = rawurldecode( $permalink );
|
||||
}
|
||||
|
||||
return apply_filters( 'permalink_manager_filter_final_term_permalink', $permalink, $term, $old_permalink );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the provided slug is unique and then update it with SQL query.
|
||||
*
|
||||
* @param string $slug
|
||||
* @param int $id
|
||||
* @param bool $preview_mode
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
static function update_slug_by_id( $slug, $id, $preview_mode = false ) {
|
||||
global $wpdb;
|
||||
|
||||
// Update slug and make it unique
|
||||
$term = get_term( intval( $id ) );
|
||||
$slug = ( empty( $slug ) ) ? get_the_title( $term->name ) : $slug;
|
||||
$slug = sanitize_title( $slug );
|
||||
|
||||
$new_slug = wp_unique_term_slug( $slug, $term );
|
||||
|
||||
if ( ! $preview_mode ) {
|
||||
$wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->terms} SET slug = %s WHERE term_id = %d", $new_slug, $id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
|
||||
}
|
||||
|
||||
return $new_slug;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the currently used custom permalink (or default/empty URI)
|
||||
*
|
||||
* @param int $term_id
|
||||
* @param bool $native_uri
|
||||
* @param bool $no_fallback
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function get_term_uri( $term_id, $native_uri = false, $no_fallback = false ) {
|
||||
global $permalink_manager_uris;
|
||||
|
||||
// Check if input is term object
|
||||
$term = ( isset( $term_id->term_id ) ) ? $term_id->term_id : get_term( $term_id );
|
||||
|
||||
if ( ! empty( $permalink_manager_uris["tax-{$term_id}"] ) ) {
|
||||
$final_uri = $permalink_manager_uris["tax-{$term_id}"];
|
||||
} else if ( ! $no_fallback ) {
|
||||
$final_uri = self::get_default_term_uri( $term->term_id, $native_uri );
|
||||
} else {
|
||||
$final_uri = '';
|
||||
}
|
||||
|
||||
return $final_uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the default custom permalink (not overwritten by the user) or native permalink (unfiltered)
|
||||
*
|
||||
* @param WP_Term|int $term
|
||||
* @param bool $native_uri
|
||||
* @param bool $check_if_disabled
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function get_default_term_uri( $term, $native_uri = false, $check_if_disabled = false ) {
|
||||
global $permalink_manager_permastructs, $wp_taxonomies;
|
||||
|
||||
// Disable WPML adjust ID filter
|
||||
if ( class_exists( 'SitePress' ) ) {
|
||||
add_filter( 'wpml_disable_term_adjust_id', '__return_true', 999 );
|
||||
}
|
||||
|
||||
// 1. Load all bases & term
|
||||
$term = is_object( $term ) ? $term : get_term( $term );
|
||||
// $term_id = $term->term_id;
|
||||
$taxonomy_name = $term->taxonomy;
|
||||
$taxonomy = get_taxonomy( $taxonomy_name );
|
||||
$term_slug = $term->slug;
|
||||
$top_parent_slug = '';
|
||||
|
||||
// 1A. Check if taxonomy is allowed
|
||||
if ( $check_if_disabled && Permalink_Manager_Helper_Functions::is_taxonomy_disabled( $taxonomy ) ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// 2A. Get the native permastructure
|
||||
$native_permastructure = Permalink_Manager_Permastructure_Functions::get_default_permastruct( $taxonomy_name );
|
||||
|
||||
// 2B. Get the permastructure
|
||||
if ( $native_uri || empty( $permalink_manager_permastructs['taxonomies'][ $taxonomy_name ] ) ) {
|
||||
$permastructure = $native_permastructure;
|
||||
} else {
|
||||
$permastructure = apply_filters( 'permalink_manager_filter_permastructure', $permalink_manager_permastructs['taxonomies'][ $taxonomy_name ], $term );
|
||||
}
|
||||
|
||||
// 2C. Set the permastructure
|
||||
$default_base = ( ! empty( $permastructure ) ) ? trim( $permastructure, '/' ) : "";
|
||||
|
||||
// 3A. Check if the taxonomy has custom permastructure set
|
||||
if ( empty( $default_base ) && ! isset( $permalink_manager_permastructs['taxonomies'][ $taxonomy_name ] ) ) {
|
||||
if ( 'category' == $taxonomy_name ) {
|
||||
$default_uri = "?cat={$term->term_id}";
|
||||
} elseif ( $taxonomy->query_var ) {
|
||||
$default_uri = "?{$taxonomy->query_var}={$term_slug}";
|
||||
} else if ( ! empty( $term_slug ) ) {
|
||||
$default_uri = "?taxonomy={$taxonomy_name}&term={$term_slug}";
|
||||
} else {
|
||||
$default_uri = '';
|
||||
}
|
||||
} // 3B. Use custom permastructure
|
||||
else {
|
||||
$default_uri = $default_base;
|
||||
|
||||
// 3B. Get the full slug
|
||||
$term_slug = Permalink_Manager_Helper_Functions::remove_slashes( $term_slug );
|
||||
$custom_slug = $full_custom_slug = Permalink_Manager_Helper_Functions::force_custom_slugs( $term_slug, $term, true, null, false );
|
||||
$term_title_slug = Permalink_Manager_Helper_Functions::force_custom_slugs( $term_slug, $term, true, 1 );
|
||||
$full_native_slug = $term_slug;
|
||||
|
||||
// Add ancestors to hierarchical taxonomy
|
||||
if ( is_taxonomy_hierarchical( $taxonomy_name ) ) {
|
||||
$ancestors = get_ancestors( $term->term_id, $taxonomy_name, 'taxonomy' );
|
||||
|
||||
foreach ( $ancestors as $ancestor ) {
|
||||
$ancestor_term = get_term( $ancestor, $taxonomy_name );
|
||||
|
||||
$full_native_slug = $ancestor_term->slug . '/' . $full_native_slug;
|
||||
$full_custom_slug = Permalink_Manager_Helper_Functions::force_custom_slugs( $ancestor_term->slug, $ancestor_term ) . '/' . $full_custom_slug;
|
||||
}
|
||||
|
||||
// Get top parent term
|
||||
if ( strpos( $default_uri, "%{$taxonomy_name}_top%" ) === false || strpos( $default_uri, "%term_top%" ) === false ) {
|
||||
$top_parent_slug = Permalink_Manager_Helper_Functions::get_term_full_slug( $term, $ancestors, 3, $native_uri );
|
||||
}
|
||||
}
|
||||
|
||||
// Allow filter the default slug (only custom permalinks)
|
||||
if ( ! $native_uri ) {
|
||||
$full_slug = apply_filters( 'permalink_manager_filter_default_term_slug', $full_custom_slug, $term, $term->name );
|
||||
} else {
|
||||
$full_slug = $full_native_slug;
|
||||
}
|
||||
|
||||
// Get the taxonomy slug
|
||||
if ( ! empty( $wp_taxonomies[ $taxonomy_name ]->rewrite['slug'] ) ) {
|
||||
$taxonomy_name_slug = $wp_taxonomies[ $taxonomy_name ]->rewrite['slug'];
|
||||
} else if ( is_string( $wp_taxonomies[ $taxonomy_name ]->rewrite ) ) {
|
||||
$taxonomy_name_slug = $wp_taxonomies[ $taxonomy_name ]->rewrite;
|
||||
} else {
|
||||
$taxonomy_name_slug = $taxonomy_name;
|
||||
}
|
||||
$taxonomy_name_slug = apply_filters( 'permalink_manager_filter_taxonomy_slug', $taxonomy_name_slug, $term, $taxonomy_name );
|
||||
|
||||
$slug_tags = array( "%term_name%", "%term_flat%", "%{$taxonomy_name}%", "%{$taxonomy_name}_flat%", "%term_top%", "%{$taxonomy_name}_top%", "%native_slug%", "%native_title%", "%taxonomy%", "%term_id%" );
|
||||
$slug_tags_replacement = array( $full_slug, $custom_slug, $full_slug, $custom_slug, $top_parent_slug, $top_parent_slug, $full_native_slug, $term_title_slug, $taxonomy_name_slug, $term->term_id );
|
||||
|
||||
// Check if any term tag is present in custom permastructure
|
||||
$do_not_append_slug = Permalink_Manager_Permastructure_Functions::is_slug_tag_present( $default_uri, $slug_tags, $term );
|
||||
|
||||
// Replace the term tags with slugs or append the slug if no term tag is defined
|
||||
if ( ! empty( $do_not_append_slug ) ) {
|
||||
$default_uri = str_replace( $slug_tags, $slug_tags_replacement, $default_uri );
|
||||
} else {
|
||||
$default_uri .= "/{$full_slug}";
|
||||
}
|
||||
}
|
||||
|
||||
// Restore WPML adjust ID filter
|
||||
if ( class_exists( 'SitePress' ) ) {
|
||||
remove_filter( 'wpml_disable_term_adjust_id', '__return_true', 999 );
|
||||
}
|
||||
|
||||
return apply_filters( 'permalink_manager_filter_default_term_uri', $default_uri, $term->slug, $term, $term_slug, $native_uri );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get array with all term items based on the user-selected settings in the "Bulk tools" form
|
||||
*
|
||||
* @return array|false
|
||||
*/
|
||||
public static function get_items() {
|
||||
global $wpdb, $permalink_manager_options;
|
||||
|
||||
// Check if taxonomies are not empty
|
||||
if ( empty( $_POST['taxonomies'] ) || ! is_array( $_POST['taxonomies'] ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$taxonomy_names_array = array_map( 'sanitize_key', $_POST['taxonomies'] );
|
||||
$taxonomy_names_in = Permalink_Manager_Helper_Functions::prepare_array_for_sql_in( $taxonomy_names_array, false );
|
||||
|
||||
// Filter the terms by IDs
|
||||
$where = '';
|
||||
if ( ! empty( $_POST['ids'] ) ) {
|
||||
// Remove whitespaces and prepare array with IDs and/or ranges
|
||||
$ids = esc_sql( preg_replace( '/\s*/m', '', $_POST['ids'] ) );
|
||||
preg_match_all( "/([\d]+(?:-?[\d]+)?)/x", $ids, $groups );
|
||||
|
||||
// Prepare the extra ID filters
|
||||
$where .= "AND (";
|
||||
foreach ( $groups[0] as $group ) {
|
||||
$where .= ( $group == reset( $groups[0] ) ) ? "" : " OR ";
|
||||
// A. Single number
|
||||
if ( is_numeric( $group ) ) {
|
||||
$where .= "(t.term_id = {$group})";
|
||||
} // B. Range
|
||||
else if ( substr_count( $group, '-' ) ) {
|
||||
$range_edges = explode( "-", $group );
|
||||
$where .= "(t.term_id BETWEEN {$range_edges[0]} AND {$range_edges[1]})";
|
||||
}
|
||||
}
|
||||
$where .= ")";
|
||||
}
|
||||
|
||||
// Get excluded items
|
||||
$excluded_terms = (array) apply_filters( 'permalink_manager_excluded_term_ids', array() );
|
||||
if ( ! empty( $excluded_terms ) ) {
|
||||
$where .= sprintf( " AND t.term_id NOT IN (%s) ", Permalink_Manager_Helper_Functions::prepare_array_for_sql_in( $excluded_terms ) );
|
||||
}
|
||||
|
||||
// Check the auto-update mode
|
||||
// A. Allow only user-approved posts
|
||||
if ( ! empty( $permalink_manager_options["general"]["auto_update_uris"] ) && $permalink_manager_options["general"]["auto_update_uris"] == 2 ) {
|
||||
$where .= " AND tm.meta_value IN (1, -1) ";
|
||||
} // B. Allow all posts not disabled by the user
|
||||
else {
|
||||
$where .= " AND (tm.meta_value IS NULL OR tm.meta_value IN (1, -1)) ";
|
||||
}
|
||||
|
||||
// Get the rows before they are altered
|
||||
$query = "SELECT t.slug, t.name, t.term_id, tt.taxonomy FROM {$wpdb->terms} AS t INNER JOIN {$wpdb->term_taxonomy} AS tt ON tt.term_id = t.term_id LEFT JOIN {$wpdb->termmeta} AS tm ON (tm.term_id = t.term_id AND tm.meta_key = 'auto_update_uri') WHERE tt.taxonomy IN ({$taxonomy_names_in}) {$where}";
|
||||
$query = apply_filters( 'permalink_manager_get_items_query', $query, $where, 'taxonomies' );
|
||||
|
||||
return $wpdb->get_results( $query, ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the permalinks/slugs "Find & replace" & "Regenerate/rest" tool
|
||||
*
|
||||
* @param array $chunk
|
||||
* @param string $mode
|
||||
* @param string $operation
|
||||
* @param string $old_string
|
||||
* @param string $new_string
|
||||
* @param bool $preview_mode
|
||||
*
|
||||
* @return array|false
|
||||
*/
|
||||
public static function bulk_process_items( $chunk = null, $mode = '', $operation = '', $old_string = '', $new_string = '', $preview_mode = false ) {
|
||||
// Reset variables
|
||||
$updated_slugs_count = 0;
|
||||
$updated_array = array();
|
||||
|
||||
// Get the rows before they are altered
|
||||
$terms_to_update = ( ! empty( $chunk ) ) ? $chunk : self::get_items();
|
||||
|
||||
if ( empty( $operation ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Now if the array is not empty use IDs from each subarray as a key
|
||||
if ( $terms_to_update ) {
|
||||
foreach ( $terms_to_update as $row ) {
|
||||
$this_term = get_term( $row['term_id'] );
|
||||
|
||||
// Get default & native URL
|
||||
$native_uri = self::get_default_term_uri( $this_term, true );
|
||||
$default_uri = self::get_default_term_uri( $this_term );
|
||||
$old_custom_uri = Permalink_Manager_URI_Functions::get_single_uri( $row['term_id'], true, true, true );
|
||||
$old_uri = ( ! empty( $old_custom_uri ) ) ? $old_custom_uri : $native_uri;
|
||||
|
||||
$old_term_name = $row['slug'];
|
||||
|
||||
if ( $operation == 'regenerate' ) {
|
||||
if ( $mode == 'slugs' ) {
|
||||
$new_uri = $old_uri;
|
||||
$new_term_name = Permalink_Manager_Helper_Functions::sanitize_title( $row['name'] );
|
||||
} else if ( $mode == 'native' ) {
|
||||
$new_uri = $native_uri;
|
||||
$new_term_name = $old_term_name;
|
||||
} else {
|
||||
$new_uri = $default_uri;
|
||||
$new_term_name = $old_term_name;
|
||||
}
|
||||
} else {
|
||||
list( $new_term_name, $new_uri ) = Permalink_Manager_Helper_Functions::replace_uri_slug( $old_string, $new_string, $old_term_name, $old_uri, $mode );
|
||||
}
|
||||
|
||||
// Check if native slug should be changed
|
||||
if ( $mode == 'slugs' && $old_term_name !== $new_term_name ) {
|
||||
$new_term_name = self::update_slug_by_id( $new_term_name, $row['term_id'], $preview_mode );
|
||||
}
|
||||
|
||||
$new_uri = apply_filters( 'permalink_manager_pre_update_term_uri', $new_uri, $row['term_id'], $old_uri, $native_uri, $default_uri );
|
||||
|
||||
if ( ! ( empty( $new_uri ) ) && ( $old_custom_uri !== $new_uri ) || ( $old_term_name !== $new_term_name ) ) {
|
||||
if ( ! $preview_mode && ( $old_custom_uri !== $new_uri ) ) {
|
||||
Permalink_Manager_URI_Functions::save_single_uri( $row['term_id'], $new_uri, true, false );
|
||||
do_action( 'permalink_manager_updated_term_uri', $row['term_id'], $new_uri, $old_uri, $native_uri, $default_uri );
|
||||
}
|
||||
|
||||
$updated_array[] = array( 'item_title' => $row['name'], 'ID' => $row['term_id'], 'old_uri' => $old_uri, 'new_uri' => $new_uri, 'old_slug' => $old_term_name, 'new_slug' => $new_term_name, 'tax' => $this_term->taxonomy );
|
||||
$updated_slugs_count ++;
|
||||
}
|
||||
}
|
||||
|
||||
// Save all custom permalinks
|
||||
if ( ! $preview_mode ) {
|
||||
Permalink_Manager_URI_Functions::save_all_uris();
|
||||
}
|
||||
|
||||
$output = array( 'updated' => $updated_array, 'updated_count' => $updated_slugs_count );
|
||||
wp_reset_postdata();
|
||||
}
|
||||
|
||||
return ( ! empty( $output ) ) ? $output : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the custom permalinks in "Bulk URI Editor" tool
|
||||
*
|
||||
* @return array|false
|
||||
*/
|
||||
static public function update_all_permalinks() {
|
||||
// Setup needed variables
|
||||
$updated_slugs_count = 0;
|
||||
$updated_array = array();
|
||||
|
||||
$new_uris = isset( $_POST['uri'] ) ? $_POST['uri'] : array();
|
||||
|
||||
// Double check if the slugs and ids are stored in arrays
|
||||
if ( ! is_array( $new_uris ) ) {
|
||||
$new_uris = explode( ',', $new_uris );
|
||||
}
|
||||
|
||||
if ( ! empty( $new_uris ) ) {
|
||||
foreach ( $new_uris as $id => $new_uri ) {
|
||||
// Remove prefix from field name to obtain term id
|
||||
$term_id = filter_var( str_replace( 'tax-', '', $id ), FILTER_SANITIZE_NUMBER_INT );
|
||||
|
||||
$this_term = get_term( $term_id );
|
||||
$old_uri = Permalink_Manager_URI_Functions::get_single_uri( $term_id, false, true, true );
|
||||
$new_uri = ( empty( $new_uri ) ) ? null : $new_uri; // If the string is empty, convert it to null to force the default permalink
|
||||
|
||||
$final_uri = self::save_uri( $this_term, $new_uri, false, false, false );
|
||||
|
||||
if ( $final_uri ) {
|
||||
$updated_array[] = array( 'item_title' => $this_term->name, 'ID' => $term_id, 'old_uri' => $old_uri, 'new_uri' => $final_uri, 'tax' => $this_term->taxonomy );
|
||||
$updated_slugs_count ++;
|
||||
}
|
||||
}
|
||||
|
||||
// Save all custom permalinks
|
||||
Permalink_Manager_URI_Functions::save_all_uris();
|
||||
|
||||
$output = array( 'updated' => $updated_array, 'updated_count' => $updated_slugs_count );
|
||||
}
|
||||
|
||||
return ( ! empty( $output ) ) ? $output : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Allow to edit URIs from "New Term" & "Edit Term" admin pages
|
||||
*
|
||||
* @param WP_Term $term
|
||||
*/
|
||||
public function edit_uri_box( $term = '' ) {
|
||||
// Check if the term is excluded
|
||||
if ( empty( $term ) || Permalink_Manager_Helper_Functions::is_term_excluded( $term ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Stop the hook (if needed)
|
||||
if ( ! empty( $term->taxonomy ) ) {
|
||||
$show_uri_editor = apply_filters( "permalink_manager_show_uri_editor_term", true, $term, $term->taxonomy );
|
||||
|
||||
if ( ! $show_uri_editor ) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
$label = __( "Custom URI", "permalink-manager" );
|
||||
$description = __( "Clear/leave the field empty to use the default permalink.", "permalink-manager" );
|
||||
|
||||
// A. New term
|
||||
if ( empty( $term->term_id ) ) {
|
||||
$html = "<div class=\"form-field\">";
|
||||
$html .= sprintf( "<label for=\"term_meta[uri]\">%s</label>", $label );
|
||||
$html .= "<input type=\"text\" name=\"custom_uri\" id=\"custom_uri\" value=\"\">";
|
||||
$html .= sprintf( "<p class=\"description\">%s</p>", $description );
|
||||
$html .= "</div>";
|
||||
|
||||
// Append nonce field
|
||||
$html .= wp_nonce_field( 'permalink-manager-edit-uri-box', 'permalink-manager-nonce', true, false );
|
||||
} // B. Edit term
|
||||
else {
|
||||
$html = "<tr id=\"permalink-manager\" class=\"form-field permalink-manager-edit-term permalink-manager\">";
|
||||
$html .= sprintf( "<th scope=\"row\"><label for=\"custom_uri\">%s</label></th>", $label );
|
||||
$html .= "<td><div>";
|
||||
$html .= Permalink_Manager_UI_Elements::display_uri_box( $term );
|
||||
$html .= "</div></td>";
|
||||
$html .= "</tr>";
|
||||
}
|
||||
|
||||
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
|
||||
echo $html;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add "Custom permalink" input field to "Quick Edit" form
|
||||
*
|
||||
* @param array $columns
|
||||
*
|
||||
* @return array mixed
|
||||
*/
|
||||
function quick_edit_column( $columns ) {
|
||||
return ( is_array( $columns ) ) ? array_merge( $columns, array( 'permalink-manager-col' => __( 'Custom permalink', 'permalink-manager' ) ) ) : $columns;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the URI of the current term in the "Custom permalink" column
|
||||
*
|
||||
* @param string $content The column content.
|
||||
* @param string $column_name The name of the column to display. In this case, we named our column permalink-manager-col.
|
||||
* @param int $term_id The ID of the term.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
function quick_edit_column_content( $content, $column_name, $term_id ) {
|
||||
global $permalink_manager_uris, $permalink_manager_options;
|
||||
|
||||
if ( $column_name == "permalink-manager-col" ) {
|
||||
$auto_update_val = get_term_meta( $term_id, "auto_update_uri", true );
|
||||
$disabled = ( ! empty( $auto_update_val ) ) ? $auto_update_val : $permalink_manager_options["general"]["auto_update_uris"];
|
||||
|
||||
$uri = ( ! empty( $permalink_manager_uris["tax-{$term_id}"] ) ) ? self::get_term_uri( $term_id ) : self::get_term_uri( $term_id, true );
|
||||
|
||||
$content = sprintf( '<span class="permalink-manager-col-uri" data-disabled="%s">%s</span>', intval( $disabled ), $uri );
|
||||
}
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update URI from "Edit Term" admin page / Set the custom permalink for new term item
|
||||
*
|
||||
* @param int $term_id Term ID.
|
||||
* @param int $tt_term_id Term taxonomy ID.
|
||||
*/
|
||||
function update_term_uri( $term_id, $tt_term_id ) {
|
||||
// Term ID must be defined
|
||||
if ( empty( $term_id ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$current_filter = current_filter();
|
||||
|
||||
// Validate the nonce (if the permalink editor is displayed)
|
||||
if ( isset( $_POST['custom_uri'] ) && ( ! isset( $_POST['permalink-manager-nonce'] ) || ! wp_verify_nonce( $_POST['permalink-manager-nonce'], 'permalink-manager-edit-uri-box' ) ) ) {
|
||||
return;
|
||||
} // If term was added via "Edit Post" page, use the default URI
|
||||
else if ( ! empty( $current_filter ) && strpos( $current_filter, 'wp_ajax_add' ) !== false && empty( $_POST['custom_uri'] ) ) {
|
||||
$is_new_term = true;
|
||||
} else if ( ! empty( $current_filter ) && strpos( $current_filter, 'create_' ) !== false ) {
|
||||
$is_new_term = true;
|
||||
} else {
|
||||
$is_new_term = false;
|
||||
}
|
||||
|
||||
// Get auto-update URI setting
|
||||
if ( isset( $_POST["auto_update_uri"] ) ) {
|
||||
$auto_update_mode = intval( $_POST["auto_update_uri"] );
|
||||
} else {
|
||||
$auto_update_mode = false;
|
||||
}
|
||||
|
||||
// Check if the URI is provided in the input field
|
||||
if ( isset( $_POST['custom_uri'] ) && empty( $is_new_term ) && empty( $_POST['post_ID'] ) ) {
|
||||
$new_uri = ( ! empty( $_POST['custom_uri'] ) ) ? Permalink_Manager_Helper_Functions::sanitize_title( $_POST['custom_uri'] ) : '';
|
||||
} else if ( ! empty( $is_new_term ) ) {
|
||||
$new_uri = '';
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
self::save_uri( $term_id, $new_uri, $is_new_term, $auto_update_mode );
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the custom permalink
|
||||
*
|
||||
* @param int|WP_Term $term
|
||||
* @param string $new_uri
|
||||
* @param bool $is_new_term
|
||||
* @param int|bool $auto_update_mode
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
static function save_uri( $term, $new_uri = '', $is_new_term = false, $auto_update_mode = false, $db_save = true ) {
|
||||
global $permalink_manager_options;
|
||||
|
||||
// Get the term object
|
||||
if ( is_numeric( $term ) ) {
|
||||
$term_object = get_term( $term );
|
||||
} else if ( is_a( $term, 'WP_Term' ) ) {
|
||||
$term_object = $term;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
$term_id = $term_object->term_id;
|
||||
|
||||
// Check if the term is allowed
|
||||
if ( empty( $term_object->taxonomy ) || Permalink_Manager_Helper_Functions::is_term_excluded( $term_object ) || empty( $term_id ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Manage 'Auto-update URI' settings
|
||||
if ( ! empty( $auto_update_mode ) ) {
|
||||
$auto_update_uri = $auto_update_mode;
|
||||
update_term_meta( $term_id, "auto_update_uri", $auto_update_mode );
|
||||
} else if ( $auto_update_mode === 0 ) {
|
||||
$auto_update_uri = $permalink_manager_options['general']['auto_update_uris'];
|
||||
delete_term_meta( $term_id, "auto_update_uri" );
|
||||
} else {
|
||||
$auto_update_uri = get_term_meta( $term_id, "auto_update_uri", true );
|
||||
$auto_update_uri = ( ! empty( $auto_update_uri ) ) ? $auto_update_uri : $permalink_manager_options['general']['auto_update_uris'];
|
||||
}
|
||||
|
||||
// Get default & native & user-submitted URIs
|
||||
$native_uri = self::get_default_term_uri( $term_object, true );
|
||||
$default_uri = self::get_default_term_uri( $term_object );
|
||||
$old_uri = self::get_term_uri( $term_id, false, true );
|
||||
|
||||
if ( ! empty( $new_uri ) && $auto_update_uri != 1 ) {
|
||||
$new_uri = Permalink_Manager_Helper_Functions::sanitize_title( $new_uri, true );
|
||||
} else if ( $is_new_term || $auto_update_uri == 1 || empty( $new_uri ) ) {
|
||||
$new_uri = $default_uri;
|
||||
} else {
|
||||
$new_uri = '';
|
||||
}
|
||||
|
||||
if ( $is_new_term ) {
|
||||
$allow_save = apply_filters( 'permalink_manager_allow_new_term_uri', true, $term_object );
|
||||
} else {
|
||||
$allow_save = apply_filters( 'permalink_manager_allow_update_term_uri', true, $term_object );
|
||||
}
|
||||
|
||||
$new_uri = apply_filters( 'permalink_manager_pre_update_term_uri', $new_uri, $term_id, $old_uri, $native_uri, $default_uri );
|
||||
|
||||
// The update URI process is stopped by the hook above or disabled in "Auto-update" settings
|
||||
if ( ! $allow_save || ( ! empty( $auto_update_uri ) && $auto_update_uri == 2 ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Save the URI only if $new_uri variable is set
|
||||
if ( ! empty( $new_uri ) && $new_uri !== $old_uri ) {
|
||||
Permalink_Manager_URI_Functions::save_single_uri( $term_id, $new_uri, true, $db_save );
|
||||
$uri_saved = true;
|
||||
} // The $new_uri variable is empty or no change is detected
|
||||
else {
|
||||
$uri_saved = false;
|
||||
}
|
||||
|
||||
do_action( 'permalink_manager_updated_term_uri', $term_id, $new_uri, $old_uri, $native_uri, $default_uri, $uri_saved );
|
||||
|
||||
return ( $uri_saved ) ? $new_uri : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove URI from options array after term is moved to the trash
|
||||
*
|
||||
* @param int $term_id
|
||||
*/
|
||||
function remove_term_uri( $term_id ) {
|
||||
Permalink_Manager_URI_Functions::remove_single_uri( $term_id, true, true );
|
||||
}
|
||||
|
||||
}
|
||||
+236
@@ -0,0 +1,236 @@
|
||||
<?php
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Functions used to create, edit and remove custom permalinks
|
||||
*/
|
||||
class Permalink_Manager_URI_Functions {
|
||||
|
||||
public function __construct() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the custom permalink's array key for specific post or term
|
||||
*
|
||||
* @param WP_Post|WP_Term|int|string $element
|
||||
* @param bool $is_tax
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function get_single_uri_key( $element, $is_tax = false ) {
|
||||
if ( ! empty( $element->term_id ) ) {
|
||||
$is_term = true;
|
||||
$element_id = $element->term_id;
|
||||
} else if ( ! empty( $element->ID ) ) {
|
||||
$is_term = false;
|
||||
$element_id = $element->ID;
|
||||
} else if ( is_string( $element ) || is_numeric( $element ) ) {
|
||||
$is_term = ( strpos( $element, 'tax-' ) !== false ) ? true : $is_tax;
|
||||
$element_id = preg_replace( '/[^0-9]/', '', $element );
|
||||
} else {
|
||||
$element_id = "";
|
||||
$is_term = null;
|
||||
}
|
||||
|
||||
$array_index = ( $is_term && ! empty( $element_id ) ) ? sprintf( 'tax-%s', $element_id ) : $element_id;
|
||||
|
||||
return array( $element_id, $is_term, $array_index );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the single custom permalink
|
||||
*
|
||||
* @param WP_Post|WP_Term|int $element
|
||||
* @param bool $native_uri
|
||||
* @param bool $no_fallback
|
||||
*/
|
||||
public static function get_single_uri( $element, $native_uri = false, $no_fallback = false, $is_tax = false ) {
|
||||
// Get the element key
|
||||
list( $element_id, $is_term, $array_index ) = self::get_single_uri_key( $element, $is_tax );
|
||||
|
||||
if ( $is_term ) {
|
||||
$final_uri = ( class_exists( 'Permalink_Manager_URI_Functions_Tax' ) ) ? Permalink_Manager_URI_Functions_Tax::get_term_uri( $element_id, $native_uri, $no_fallback ) : '';
|
||||
} else {
|
||||
$final_uri = Permalink_Manager_URI_Functions_Post::get_post_uri( $element_id, $native_uri, $no_fallback );
|
||||
}
|
||||
|
||||
return $final_uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save single custom permalink to the custom permalinks array
|
||||
*
|
||||
* @param int|string $element
|
||||
* @param string $element_uri
|
||||
* @param bool $is_tax
|
||||
* @param bool $db_save
|
||||
*/
|
||||
public static function save_single_uri( $element, $element_uri = null, $is_tax = false, $db_save = false ) {
|
||||
global $permalink_manager_uris;
|
||||
|
||||
// Get the element key
|
||||
list( $element_id, $is_term, $array_index ) = self::get_single_uri_key( $element, $is_tax );
|
||||
|
||||
// Save the custom permalink if the URI is not empty
|
||||
if ( ! empty( $array_index ) && ! empty( $element_uri ) ) {
|
||||
$permalink_manager_uris[ $array_index ] = Permalink_Manager_Helper_Functions::sanitize_title( $element_uri, true );
|
||||
|
||||
if ( $db_save ) {
|
||||
self::save_all_uris( $permalink_manager_uris );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove single custom permalink from the custom permalinks array
|
||||
*
|
||||
* @param int|string $element
|
||||
* @param bool $is_tax
|
||||
* @param bool $db_save
|
||||
*/
|
||||
public static function remove_single_uri( $element, $is_tax = false, $db_save = false ) {
|
||||
global $permalink_manager_uris;
|
||||
|
||||
// Get the element key
|
||||
list( $element_id, $is_term, $array_index ) = self::get_single_uri_key( $element, $is_tax );
|
||||
|
||||
// Check if the custom permalink is assigned to this element
|
||||
if ( ! empty( $array_index ) && isset( $permalink_manager_uris[ $array_index ] ) ) {
|
||||
unset( $permalink_manager_uris[ $array_index ] );
|
||||
}
|
||||
|
||||
if ( $db_save ) {
|
||||
self::save_all_uris( $permalink_manager_uris );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the ID(s) of the element(s) by its custom permalink
|
||||
*
|
||||
* @param string $search_query
|
||||
* @param bool $strict_search
|
||||
* @param string $content_type
|
||||
*
|
||||
* @return bool|string|array
|
||||
*/
|
||||
public static function find_uri( $search_query, $strict_search = true, $content_type = null ) {
|
||||
$custom_permalinks = self::get_all_uris();
|
||||
$found = false;
|
||||
|
||||
if ( $strict_search ) {
|
||||
$all_uris = array_flip( $custom_permalinks );
|
||||
|
||||
$found = ( ! empty( $all_uris[ $search_query ] ) ) ? $all_uris[ $search_query ] : false;
|
||||
} else {
|
||||
$found = array();
|
||||
$search_query = preg_quote( $search_query, '/' );
|
||||
|
||||
foreach ( $custom_permalinks as $id => $uri ) {
|
||||
if ( preg_match( "/\b$search_query\b/i", $uri ) ) {
|
||||
if ( $content_type == 'taxonomies' && ( strpos( $id, 'tax-' ) !== false ) ) {
|
||||
$found[] = (int) abs( filter_var( $id, FILTER_SANITIZE_NUMBER_INT ) );
|
||||
} else if ( $content_type == 'posts' && is_numeric( $id ) ) {
|
||||
$found[] = (int) filter_var( $id, FILTER_SANITIZE_NUMBER_INT );
|
||||
} else if ( empty( $content_type ) ) {
|
||||
$found[] = $id;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $found;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a single URI is duplicated
|
||||
*
|
||||
* @param string $uri
|
||||
* @param int $element_id
|
||||
* @param array $duplicated_ids
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function is_uri_duplicated( $uri, $element_id, $duplicated_ids = array() ) {
|
||||
$custom_permalinks = Permalink_Manager_URI_Functions::get_all_uris();
|
||||
|
||||
if ( empty( $uri ) || empty( $element_id ) || empty( $custom_permalinks ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$uri = trim( trim( sanitize_text_field( $uri ) ), "/" );
|
||||
$element_id = sanitize_text_field( $element_id );
|
||||
|
||||
// Keep the URIs in a separate array just here
|
||||
if ( ! empty( $duplicated_ids ) ) {
|
||||
$all_duplicates = $duplicated_ids;
|
||||
} else if ( in_array( $uri, $custom_permalinks ) ) {
|
||||
$all_duplicates = array_keys( $custom_permalinks, $uri );
|
||||
}
|
||||
|
||||
if ( ! empty( $all_duplicates ) ) {
|
||||
// Get the language code of current element
|
||||
$this_uri_lang = apply_filters( 'permalink_manager_get_language_code', '', $element_id );
|
||||
|
||||
foreach ( $all_duplicates as $key => $duplicated_id ) {
|
||||
// Ignore custom redirects
|
||||
if ( strpos( $key, 'redirect-' ) !== false ) {
|
||||
unset( $all_duplicates[ $key ] );
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( $this_uri_lang ) {
|
||||
$duplicated_uri_lang = apply_filters( 'permalink_manager_get_language_code', '', $duplicated_id );
|
||||
}
|
||||
|
||||
// Ignore the URI for requested element and other elements in other languages to prevent the false alert
|
||||
if ( ( ! empty( $duplicated_uri_lang ) && $duplicated_uri_lang !== $this_uri_lang ) || $element_id == $duplicated_id ) {
|
||||
unset( $all_duplicates[ $key ] );
|
||||
}
|
||||
}
|
||||
|
||||
return ( count( $all_duplicates ) > 0 ) ? true : false;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the array (or statistics) with custom permalinks
|
||||
*
|
||||
* @param bool $stats
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function get_all_uris( $stats = false ) {
|
||||
global $permalink_manager_uris;
|
||||
|
||||
if ( $stats ) {
|
||||
$custom_permalinks_size = strlen( serialize( $permalink_manager_uris ) );
|
||||
$custom_permalinks_count = count( $permalink_manager_uris );
|
||||
|
||||
return array( $custom_permalinks_size, $custom_permalinks_count );
|
||||
} else {
|
||||
return array_filter( $permalink_manager_uris );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the array with custom permalinks
|
||||
*
|
||||
* @param array $updated_uris
|
||||
*/
|
||||
public static function save_all_uris( $updated_uris = null ) {
|
||||
if ( is_null( $updated_uris ) ) {
|
||||
global $permalink_manager_uris;
|
||||
$updated_uris = $permalink_manager_uris;
|
||||
}
|
||||
|
||||
if ( is_array( $updated_uris ) && ! empty( $updated_uris ) ) {
|
||||
update_option( 'permalink-manager-uris', $updated_uris, false );
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+1211
File diff suppressed because it is too large
Load Diff
+345
@@ -0,0 +1,345 @@
|
||||
<?php
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) exit;
|
||||
|
||||
/**
|
||||
* SEO plugins integration
|
||||
*/
|
||||
class Permalink_Manager_SEO_Plugins {
|
||||
|
||||
public function __construct() {
|
||||
add_action( 'init', array( $this, 'init_hooks' ), 99 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add support for SEO plugins using their hooks
|
||||
*/
|
||||
function init_hooks() {
|
||||
// Yoast SEO
|
||||
add_filter( 'wpseo_xml_sitemap_post_url', array( $this, 'yoast_fix_sitemap_urls' ), 9 );
|
||||
if ( defined( 'WPSEO_VERSION' ) && version_compare( WPSEO_VERSION, '14.0', '>=' ) ) {
|
||||
add_action( 'permalink_manager_updated_post_uri', array( $this, 'yoast_update_indexable_permalink' ), 10, 3 );
|
||||
add_action( 'permalink_manager_updated_term_uri', array( $this, 'yoast_update_indexable_permalink' ), 10, 3 );
|
||||
add_filter( 'wpseo_canonical', array( $this, 'yoast_fix_canonical' ), 10 );
|
||||
add_filter( 'wpseo_opengraph_url', array( $this, 'yoast_fix_canonical' ), 10 );
|
||||
add_filter( 'wpseo_dynamic_permalinks_enabled', '__return_true', 5 );
|
||||
}
|
||||
|
||||
// Breadcrumbs
|
||||
add_filter( 'wpseo_breadcrumb_links', array( $this, 'filter_breadcrumbs' ), 9 );
|
||||
add_filter( 'rank_math/frontend/breadcrumb/items', array( $this, 'filter_breadcrumbs' ), 9 );
|
||||
add_filter( 'seopress_pro_breadcrumbs_crumbs', array( $this, 'filter_breadcrumbs' ), 9 );
|
||||
add_filter( 'woocommerce_get_breadcrumb', array( $this, 'filter_breadcrumbs' ), 9 );
|
||||
add_filter( 'slim_seo_breadcrumbs_links', array( $this, 'filter_breadcrumbs' ), 9 );
|
||||
add_filter( 'aioseo_breadcrumbs_trail', array( $this, 'filter_breadcrumbs' ), 9 );
|
||||
add_filter( 'avia_breadcrumbs_trail', array( $this, 'filter_breadcrumbs' ), 100 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the HTTP protocol of the home URL and use it in Yoast SEO sitemap permalinks
|
||||
*
|
||||
* @param string $permalink The permalink in the sitemap
|
||||
*
|
||||
* @return string The sitemap's permalink
|
||||
*/
|
||||
function yoast_fix_sitemap_urls( $permalink ) {
|
||||
if ( class_exists( 'WPSEO_Utils' ) ) {
|
||||
$home_url = WPSEO_Utils::home_url();
|
||||
$home_protocol = parse_url( $home_url, PHP_URL_SCHEME );
|
||||
|
||||
$permalink = preg_replace( "/^http(s)?/", $home_protocol, $permalink );
|
||||
}
|
||||
|
||||
return $permalink;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the permalink in the Yoast SEO indexable table when the permalink is changed
|
||||
*
|
||||
* @param int $element_id The ID of the post/term element that was updated.
|
||||
* @param string $new_uri The new URI of the element.
|
||||
* @param string $old_uri The old URI of the element.
|
||||
*/
|
||||
function yoast_update_indexable_permalink( $element_id, $new_uri, $old_uri ) {
|
||||
global $wpdb;
|
||||
|
||||
if ( ! empty( $new_uri ) && ! empty( $old_uri ) && $new_uri !== $old_uri ) {
|
||||
if ( current_filter() == 'permalink_manager_updated_term_uri' ) {
|
||||
$permalink = get_term_link( (int) $element_id );
|
||||
$object_type = 'term';
|
||||
} else {
|
||||
$permalink = get_permalink( $element_id );
|
||||
$object_type = 'post';
|
||||
}
|
||||
|
||||
if ( ! empty( $permalink ) ) {
|
||||
$permalink_hash = strlen( $permalink ) . ':' . md5( $permalink );
|
||||
$wpdb->update( "{$wpdb->prefix}yoast_indexable", array( 'permalink' => $permalink, 'permalink_hash' => $permalink_hash ), array( 'object_id' => $element_id, 'object_type' => $object_type ), array( '%s', '%s' ), array( '%d', '%s' ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter the canonical permalink used by SEO using 'wpseo_canonical' & 'wpseo_opengraph_url' hooks
|
||||
*
|
||||
* @param string $url The canonical URL that Yoast SEO has generated.
|
||||
*
|
||||
* @return string the URL.
|
||||
*/
|
||||
function yoast_fix_canonical( $url ) {
|
||||
global $pm_query, $wp_rewrite;
|
||||
|
||||
if ( ! empty( $pm_query['id'] ) ) {
|
||||
$element = get_queried_object();
|
||||
|
||||
if ( ! empty( $element->ID ) && ! empty( $element->post_type ) ) {
|
||||
$new_url = get_permalink( $element->ID );
|
||||
|
||||
// Do not filter if custom canonical URL is set
|
||||
$yoast_canonical_url = get_post_meta( $element->ID, '_yoast_wpseo_canonical', true );
|
||||
if ( ! empty( $yoast_canonical_url ) ) {
|
||||
return $url;
|
||||
}
|
||||
|
||||
if ( is_home() ) {
|
||||
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
|
||||
$new_url = ( $paged > 1 ) ? sprintf( '%s/%s/%d', trim( $new_url, '/' ), $wp_rewrite->pagination_base, $paged ) : $new_url;
|
||||
} else {
|
||||
$paged = ( get_query_var( 'page' ) ) ? get_query_var( 'page' ) : 1;
|
||||
$new_url = ( $paged > 1 ) ? sprintf( '%s/%d', trim( $new_url, '/' ), $paged ) : $new_url;
|
||||
}
|
||||
} else if ( ! empty( $element->taxonomy ) && ! empty( $element->term_id ) ) {
|
||||
$new_url = get_term_link( $element, $element->taxonomy );
|
||||
|
||||
// Do not filter if custom canonical URL is set
|
||||
if ( class_exists( 'WPSEO_Taxonomy_Meta' ) ) {
|
||||
$yoast_canonical_url = WPSEO_Taxonomy_Meta::get_term_meta( $element, $element->taxonomy, 'canonical' );
|
||||
if ( ! empty( $yoast_canonical_url ) ) {
|
||||
return $url;
|
||||
}
|
||||
}
|
||||
|
||||
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
|
||||
if ( $paged > 1 ) {
|
||||
$new_url = sprintf( '%s/%s/%d', trim( $new_url, '/' ), $wp_rewrite->pagination_base, $paged );
|
||||
}
|
||||
}
|
||||
|
||||
$url = ( ! empty( $new_url ) ) ? $new_url : $url;
|
||||
$url = Permalink_Manager_Core_Functions::control_trailing_slashes( $url );
|
||||
}
|
||||
|
||||
return $url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter the breadcrumbs array to match the structure of currently requested URL
|
||||
*
|
||||
* @param array $links The current breadcrumb links.
|
||||
*
|
||||
* @return array The $links array.
|
||||
*/
|
||||
function filter_breadcrumbs( $links ) {
|
||||
// Get post type permastructure settings
|
||||
global $permalink_manager_options, $post, $wpdb, $wp, $wp_current_filter;
|
||||
|
||||
// Check if the filter should be activated
|
||||
if ( empty( $permalink_manager_options['general']['yoast_breadcrumbs'] ) ) {
|
||||
return $links;
|
||||
}
|
||||
|
||||
// Get current post/page/term (if available)
|
||||
$queried_element = get_queried_object();
|
||||
if ( ! empty( $queried_element->ID ) ) {
|
||||
$element_id = $queried_element->ID;
|
||||
} else if ( ! empty( $queried_element->term_id ) ) {
|
||||
$element_id = "tax-{$queried_element->term_id}";
|
||||
} else if ( defined( 'REST_REQUEST' ) && ! empty( $post->ID ) ) {
|
||||
$element_id = $post->ID;
|
||||
}
|
||||
|
||||
// Get the custom permalink (if available) or the current request URL (if unavailable)
|
||||
$custom_uri = ( ! empty( $element_id ) ) ? Permalink_Manager_URI_Functions::get_single_uri( $element_id, false, true, null ) : '';
|
||||
|
||||
if ( ! empty( $custom_uri ) ) {
|
||||
$custom_uri = preg_replace( "/([^\/]+)$/", '', $custom_uri );
|
||||
} else {
|
||||
return $links;
|
||||
}
|
||||
|
||||
$custom_uri_parts = explode( '/', trim( $custom_uri ) );
|
||||
$breadcrumbs = array();
|
||||
$snowball = '';
|
||||
$available_taxonomies = Permalink_Manager_Helper_Functions::get_taxonomies_array( null, null, true );
|
||||
$available_post_types = Permalink_Manager_Helper_Functions::get_post_types_array( null, null, true );
|
||||
$available_post_types_archive = Permalink_Manager_Helper_Functions::get_post_types_array( 'archive_slug', null, true );
|
||||
$current_filter = end( $wp_current_filter );
|
||||
|
||||
// Get Yoast Meta (the breadcrumbs titles can be changed in Yoast metabox)
|
||||
$yoast_meta_terms = get_option( 'wpseo_taxonomy_meta' );
|
||||
|
||||
// Check what array keys should be used for breadcrumbs ("All In One SEO" uses a more complicated schema)
|
||||
if ( $current_filter == 'aioseo_breadcrumbs_trail' ) {
|
||||
$breadcrumb_key_text = 'label';
|
||||
$breadcrumb_key_url = 'link';
|
||||
$is_aioseo = true;
|
||||
} else if ( in_array( $current_filter, array( 'wpseo_breadcrumb_links', 'slim_seo_breadcrumbs_links' ) ) ) {
|
||||
$breadcrumb_key_text = 'text';
|
||||
$breadcrumb_key_url = 'url';
|
||||
$is_aioseo = false;
|
||||
} else {
|
||||
$breadcrumb_key_text = 0;
|
||||
$breadcrumb_key_url = 1;
|
||||
$is_aioseo = false;
|
||||
}
|
||||
|
||||
// Get internal breadcrumb elements
|
||||
foreach ( $custom_uri_parts as $slug ) {
|
||||
if ( empty( $slug ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$snowball = ( empty( $snowball ) ) ? $slug : "{$snowball}/{$slug}";
|
||||
|
||||
// 1A. Try to match any custom URI
|
||||
$uri = trim( $snowball, "/" );
|
||||
$element = Permalink_Manager_URI_Functions::find_uri( $uri, true );
|
||||
|
||||
if ( ! empty( $element ) && strpos( $element, 'tax-' ) !== false ) {
|
||||
$element_id = intval( preg_replace( "/[^0-9]/", "", $element ) );
|
||||
$element = get_term( $element_id );
|
||||
} else if ( is_numeric( $element ) ) {
|
||||
$element = get_post( $element );
|
||||
}
|
||||
|
||||
// 1B. Try to get term
|
||||
if ( empty( $element ) && ! empty( $available_taxonomies ) ) {
|
||||
$sql = sprintf( "SELECT t.term_id, t.name, tt.taxonomy FROM {$wpdb->terms} AS t LEFT JOIN {$wpdb->term_taxonomy} AS tt ON t.term_id = tt.term_id WHERE slug = '%s' AND tt.taxonomy IN ('%s') LIMIT 1", esc_sql( $slug ), implode( "','", array_keys( $available_taxonomies ) ) );
|
||||
|
||||
$element = $wpdb->get_row( $sql );
|
||||
}
|
||||
|
||||
// 1C. Try to get page/post
|
||||
if ( empty( $element ) && ! empty( $available_post_types ) ) {
|
||||
$sql = sprintf( "SELECT ID, post_title, post_type FROM {$wpdb->posts} WHERE post_name = '%s' AND post_status = 'publish' AND post_type IN ('%s') AND post_type != 'attachment' LIMIT 1", esc_sql( $slug ), implode( "','", array_keys( $available_post_types ) ) );
|
||||
|
||||
$element = $wpdb->get_row( $sql );
|
||||
}
|
||||
|
||||
// 1D. Try to get post type archive
|
||||
if ( empty( $element ) && ! empty( $available_post_types_archive ) && in_array( $snowball, $available_post_types_archive ) ) {
|
||||
$post_type_slug = array_search( $snowball, $available_post_types_archive );
|
||||
$element = get_post_type_object( $post_type_slug );
|
||||
}
|
||||
|
||||
// 2A. When the term is found, we can add it to the breadcrumbs
|
||||
if ( ! empty( $element->term_id ) ) {
|
||||
$term_id = apply_filters( 'wpml_object_id', $element->term_id, $element->taxonomy, true );
|
||||
$term = ( ( $element->term_id !== $term_id ) || $is_aioseo ) ? get_term( $term_id ) : $element;
|
||||
|
||||
// Alternative title
|
||||
if ( $current_filter == 'wpseo_breadcrumb_links' ) {
|
||||
$alt_title = ( ! empty( $yoast_meta_terms[ $term->taxonomy ][ $term->term_id ]['wpseo_bctitle'] ) ) ? $yoast_meta_terms[ $term->taxonomy ][ $term->term_id ]['wpseo_bctitle'] : '';
|
||||
} else if ( $current_filter == 'seopress_pro_breadcrumbs_crumbs' ) {
|
||||
$alt_title = get_term_meta( $term->term_id, '_seopress_robots_breadcrumbs', true );
|
||||
} else if ( $current_filter == 'rank_math/frontend/breadcrumb/items' ) {
|
||||
$alt_title = get_term_meta( $term->term_id, 'rank_math_breadcrumb_title', true );
|
||||
}
|
||||
|
||||
$title = ( ! empty( $alt_title ) ) ? $alt_title : $term->name;
|
||||
|
||||
if ( $is_aioseo ) {
|
||||
$breadcrumbs[] = array(
|
||||
$breadcrumb_key_text => wp_strip_all_tags( $title ),
|
||||
$breadcrumb_key_url => get_term_link( (int) $term->term_id, $term->taxonomy ),
|
||||
'type' => 'taxonomy',
|
||||
'subType' => 'parent',
|
||||
'reference' => $term,
|
||||
);
|
||||
} else {
|
||||
$breadcrumbs[] = array(
|
||||
$breadcrumb_key_text => wp_strip_all_tags( $title ),
|
||||
$breadcrumb_key_url => get_term_link( (int) $term->term_id, $term->taxonomy )
|
||||
);
|
||||
}
|
||||
} // 2B. When the post/page is found, we can add it to the breadcrumbs
|
||||
else if ( ! empty( $element->ID ) ) {
|
||||
$page_id = apply_filters( 'wpml_object_id', $element->ID, $element->post_type, true );
|
||||
$page = ( ( $element->ID !== $page_id ) || $is_aioseo ) ? get_post( $page_id ) : $element;
|
||||
|
||||
// Alternative title
|
||||
if ( $current_filter == 'wpseo_breadcrumb_links' ) {
|
||||
$alt_title = get_post_meta( $page->ID, '_yoast_wpseo_bctitle', true );
|
||||
} else if ( $current_filter == 'seopress_pro_breadcrumbs_crumbs' ) {
|
||||
$alt_title = get_post_meta( $page->ID, '_seopress_robots_breadcrumbs', true );
|
||||
} else if ( $current_filter == 'rank_math/frontend/breadcrumb/items' ) {
|
||||
$alt_title = get_post_meta( $page->ID, 'rank_math_breadcrumb_title', true );
|
||||
}
|
||||
|
||||
$title = ( ! empty( $alt_title ) ) ? $alt_title : $page->post_title;
|
||||
|
||||
if ( $is_aioseo ) {
|
||||
$breadcrumbs[] = array(
|
||||
$breadcrumb_key_text => wp_strip_all_tags( $title ),
|
||||
$breadcrumb_key_url => get_permalink( $page->ID ),
|
||||
'type' => 'single',
|
||||
'subType' => '',
|
||||
'reference' => $page
|
||||
);
|
||||
} else {
|
||||
$breadcrumbs[] = array(
|
||||
$breadcrumb_key_text => wp_strip_all_tags( $title ),
|
||||
$breadcrumb_key_url => get_permalink( $page->ID )
|
||||
);
|
||||
}
|
||||
} // 2C. When the post archive is found, we can add it to the breadcrumbs
|
||||
else if ( ! empty( $element->rewrite ) && ( ! empty( $element->labels->name ) ) ) {
|
||||
if ( $is_aioseo ) {
|
||||
$breadcrumbs[] = array(
|
||||
$breadcrumb_key_text => apply_filters( 'post_type_archive_title', $element->labels->name, $element->name ),
|
||||
$breadcrumb_key_url => get_post_type_archive_link( $element->name ),
|
||||
'type' => 'postTypeArchive',
|
||||
'subType' => '',
|
||||
'reference' => $element
|
||||
);
|
||||
} else {
|
||||
$breadcrumbs[] = array(
|
||||
$breadcrumb_key_text => apply_filters( 'post_type_archive_title', $element->labels->name, $element->name ),
|
||||
$breadcrumb_key_url => get_post_type_archive_link( $element->name )
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add new links to current breadcrumbs array
|
||||
if ( ! empty( $links ) && is_array( $links ) ) {
|
||||
$first_element = reset( $links );
|
||||
$last_element = end( $links );
|
||||
$b_last_element = ( count( $links ) > 2 && ( ! is_singular() || is_home() ) ) ? prev( $links ) : "";
|
||||
$breadcrumbs = ( ! empty( $breadcrumbs ) ) ? $breadcrumbs : array();
|
||||
|
||||
// Support RankMath/SEOPress/WooCommerce/Slim SEO/AIOSEO breadcrumbs
|
||||
if ( in_array( $current_filter, array( 'wpseo_breadcrumb_links', 'rank_math/frontend/breadcrumb/items', 'seopress_pro_breadcrumbs_crumbs', 'woocommerce_get_breadcrumb', 'slim_seo_breadcrumbs_links', 'aioseo_breadcrumbs_trail' ) ) ) {
|
||||
if ( $current_filter == 'slim_seo_breadcrumbs_links' ) {
|
||||
$links = array_merge( array( $first_element ), $breadcrumbs );
|
||||
} // Append the element before the last element if the last breadcrumb does not have a URL set (e.g. if the /page/ endpoint is used)
|
||||
else if ( ! in_array( $current_filter, array( 'aioseo_breadcrumbs_trail', 'slim_seo_breadcrumbs_links' ) ) && ! empty( $wp->query_vars['paged'] ) && $wp->query_vars['paged'] > 1 && ! empty( $b_last_element[ $breadcrumb_key_url ] ) ) {
|
||||
$links = array_merge( array( $first_element ), $breadcrumbs, array( $b_last_element ), array( $last_element ) );
|
||||
} else {
|
||||
$links = array_merge( array( $first_element ), $breadcrumbs, array( $last_element ) );
|
||||
}
|
||||
} // Support Avia/Enfold breadcrumbs
|
||||
else if ( $current_filter == 'avia_breadcrumbs_trail' ) {
|
||||
foreach ( $breadcrumbs as &$breadcrumb ) {
|
||||
if ( isset( $breadcrumb[ $breadcrumb_key_text ] ) ) {
|
||||
$breadcrumb = sprintf( '<a href="%s" title="%2$s">%2$s</a>', esc_attr( $breadcrumb[ $breadcrumb_key_url ] ), esc_attr( $breadcrumb[ $breadcrumb_key_text ] ) );
|
||||
}
|
||||
}
|
||||
|
||||
$links = array_merge( array( $first_element ), $breadcrumbs, array( 'trail_end' => $last_element ) );
|
||||
}
|
||||
}
|
||||
|
||||
return array_filter( $links );
|
||||
}
|
||||
}
|
||||
+1260
File diff suppressed because it is too large
Load Diff
+444
@@ -0,0 +1,444 @@
|
||||
<?php
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* WooCommerce plugins integration
|
||||
*/
|
||||
class Permalink_Manager_WooCommerce {
|
||||
|
||||
public function __construct() {
|
||||
add_action( 'init', array( $this, 'init_hooks' ), 99 );
|
||||
add_action( 'plugins_loaded', array( $this, 'init_early_hooks' ), 99 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add support for SEO plugins using their hooks
|
||||
*/
|
||||
function init_hooks() {
|
||||
if ( class_exists( 'WooCommerce' ) ) {
|
||||
add_filter( 'permalink_manager_filter_query', array( $this, 'woocommerce_detect' ), 8, 5 );
|
||||
add_filter( 'template_redirect', array( $this, 'woocommerce_checkout_fix' ), 9 );
|
||||
add_filter( 'permalink_manager_permastructs_fields', array( $this, 'woocommerce_permastructs_fields' ), 9 );
|
||||
|
||||
if ( class_exists( 'Permalink_Manager_Pro_Functions' ) ) {
|
||||
if ( empty( $permalink_manager_options['general']['partial_disable']['post_types'] ) || ! in_array( 'shop_coupon', $permalink_manager_options['general']['partial_disable']['post_types'] ) ) {
|
||||
if ( is_admin() ) {
|
||||
add_filter( 'woocommerce_coupon_data_tabs', 'Permalink_Manager_Pro_Functions::woocommerce_coupon_tabs' );
|
||||
add_action( 'woocommerce_coupon_data_panels', 'Permalink_Manager_Pro_Functions::woocommerce_coupon_panel' );
|
||||
add_action( 'woocommerce_coupon_options_save', 'Permalink_Manager_Pro_Functions::woocommerce_save_coupon_uri', 9, 2 );
|
||||
}
|
||||
|
||||
add_filter( 'request', 'Permalink_Manager_Pro_Functions::woocommerce_detect_coupon_code', 1, 1 );
|
||||
}
|
||||
} else {
|
||||
add_filter( 'permalink_manager_disabled_post_types', array( $this, 'woocommerce_coupon_uris' ), 9, 1 );
|
||||
}
|
||||
|
||||
// WooCommerce Import/Export
|
||||
add_filter( 'woocommerce_product_export_product_default_columns', array( $this, 'woocommerce_csv_custom_uri_column' ), 9 );
|
||||
add_filter( 'woocommerce_product_export_product_column_custom_uri', array( $this, 'woocommerce_export_custom_uri_value' ), 9, 3 );
|
||||
|
||||
add_filter( 'woocommerce_csv_product_import_mapping_options', array( $this, 'woocommerce_csv_custom_uri_column' ), 9 );
|
||||
add_filter( 'woocommerce_csv_product_import_mapping_default_columns', array( $this, 'woocommerce_csv_custom_uri_column' ), 9 );
|
||||
add_action( 'woocommerce_product_import_inserted_product_object', array( $this, 'woocommerce_csv_import_custom_uri' ), 9, 2 );
|
||||
|
||||
add_action( 'woocommerce_product_duplicate', array( $this, 'woocommerce_generate_permalinks_after_duplicate' ), 9, 2 );
|
||||
add_filter( 'permalink_manager_filter_default_post_uri', array( $this, 'woocommerce_product_attributes' ), 5, 5 );
|
||||
|
||||
if ( wp_doing_ajax() && class_exists( 'SitePress' ) ) {
|
||||
add_filter( 'permalink_manager_filter_final_post_permalink', array( $this, 'woocommerce_translate_ajax_fragments_urls' ), 9999, 3 );
|
||||
}
|
||||
|
||||
// Make sure that the custom permalinks are not generated prematurely
|
||||
add_filter( 'woocommerce_rest_pre_insert_product_object', array( $this, 'woocommerce_delay_product_custom_permalink' ), 10, 3 );
|
||||
add_action( 'woocommerce_rest_insert_product_object', array( $this, 'woocommerce_set_custom_uri_after_rest_insert' ), 20, 3 );
|
||||
}
|
||||
|
||||
// WooCommerce Wishlist Plugin
|
||||
if ( function_exists( 'tinv_get_option' ) ) {
|
||||
add_filter( 'permalink_manager_detect_uri', array( $this, 'ti_woocommerce_wishlist_uris' ), 15, 3 );
|
||||
}
|
||||
|
||||
// WooCommerce Subscriptions
|
||||
if ( class_exists( 'WC_Subscriptions' ) ) {
|
||||
add_filter( 'permalink_manager_filter_final_post_permalink', array( $this, 'wcs_fix_subscription_links' ), 10, 3 );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Some hooks must be called shortly after all the plugins are loaded
|
||||
*/
|
||||
public function init_early_hooks() {
|
||||
if ( class_exists( 'WooCommerce' ) ) {
|
||||
add_filter( 'woocommerce_get_endpoint_url', array( 'Permalink_Manager_Core_Functions', 'control_trailing_slashes' ), 9 );
|
||||
add_action( 'before_woocommerce_init', array( $this, 'woocommerce_declare_compatibility' ) );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fix query on WooCommerce shop page & disable the canonical redirect if WooCommerce query variables are set
|
||||
*/
|
||||
function woocommerce_detect( $query, $old_query, $uri_parts, $pm_query, $content_type ) {
|
||||
global $woocommerce, $pm_query;
|
||||
|
||||
$shop_page_id = get_option( 'woocommerce_shop_page_id' );
|
||||
|
||||
// WPML - translate shop page id
|
||||
$shop_page_id = apply_filters( 'wpml_object_id', $shop_page_id, 'page', true );
|
||||
|
||||
// Fix shop page
|
||||
if ( get_theme_support( 'woocommerce' ) && ! empty( $pm_query['id'] ) && is_numeric( $pm_query['id'] ) && $shop_page_id == $pm_query['id'] ) {
|
||||
$query['post_type'] = 'product';
|
||||
unset( $query['pagename'] );
|
||||
}
|
||||
|
||||
// Fix WooCommerce pages
|
||||
if ( ! empty( $woocommerce->query->query_vars ) ) {
|
||||
$query_vars = $woocommerce->query->query_vars;
|
||||
|
||||
foreach ( $query_vars as $key => $val ) {
|
||||
if ( isset( $query[ $key ] ) ) {
|
||||
$query['do_not_redirect'] = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirects the user from the Shop archive to the Shop page if the user is not searching for anything
|
||||
* Disable canonical redirect on "thank you" & another WooCommerce pages
|
||||
*/
|
||||
function woocommerce_checkout_fix() {
|
||||
global $wp_query, $pm_query, $permalink_manager_options;
|
||||
|
||||
// Redirect from Shop archive to selected page
|
||||
if ( is_shop() && empty( $pm_query['id'] ) ) {
|
||||
$redirect_mode = ( ! empty( $permalink_manager_options['general']['redirect'] ) ) ? $permalink_manager_options['general']['redirect'] : false;
|
||||
$redirect_shop = apply_filters( 'permalink_manager_redirect_shop_archive', false );
|
||||
$shop_page = get_option( 'woocommerce_shop_page_id' );
|
||||
|
||||
if ( $redirect_mode && $redirect_shop && $shop_page && empty( $wp_query->query_vars['s'] ) ) {
|
||||
$shop_url = get_permalink( $shop_page );
|
||||
wp_safe_redirect( $shop_url, $redirect_mode );
|
||||
exit();
|
||||
}
|
||||
}
|
||||
|
||||
if ( is_checkout() || ( function_exists( 'is_wc_endpoint_url' ) && is_wc_endpoint_url() ) ) {
|
||||
$wp_query->query_vars['do_not_redirect'] = 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Separate WooCommerce custom post types & taxonomies in "Permastructures" screen
|
||||
*
|
||||
* @param array $fields
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function woocommerce_permastructs_fields( $fields ) {
|
||||
if ( is_array( $fields ) ) {
|
||||
$woocommerce_fields = array( 'product' => 'post_types', 'product_tag' => 'taxonomies', 'product_cat' => 'taxonomies', 'product_brand' => 'taxonomies' );
|
||||
$woocommerce_attributes = wc_get_attribute_taxonomies();
|
||||
|
||||
foreach ( $woocommerce_attributes as $woocommerce_attribute ) {
|
||||
$woocommerce_fields["pa_{$woocommerce_attribute->attribute_name}"] = 'taxonomies';
|
||||
}
|
||||
|
||||
foreach ( $woocommerce_fields as $field => $field_type ) {
|
||||
if ( empty( $fields[ $field_type ]["fields"][ $field ] ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$fields["woocommerce"]["fields"][ $field ] = $fields[ $field_type ]["fields"][ $field ];
|
||||
unset( $fields[ $field_type ]["fields"][ $field ] );
|
||||
}
|
||||
}
|
||||
|
||||
return $fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add "Coupons" to the list of excluded post types
|
||||
*
|
||||
* @param array $post_types
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function woocommerce_coupon_uris( $post_types ) {
|
||||
if ( is_array( $post_types ) ) {
|
||||
$post_types[] = 'shop_coupon';
|
||||
}
|
||||
|
||||
return $post_types;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a new custom permalink for duplicated product
|
||||
*
|
||||
* @param WC_Product $new_product The new product object.
|
||||
* @param WC_Product $old_product The product that was duplicated.
|
||||
*/
|
||||
function woocommerce_generate_permalinks_after_duplicate( $new_product, $old_product ) {
|
||||
if ( ! empty( $new_product ) ) {
|
||||
$product_id = $new_product->get_id();
|
||||
|
||||
// Ignore variations
|
||||
if ( $new_product->get_type() === 'variation' || Permalink_Manager_Helper_Functions::is_post_excluded( $product_id, true ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$custom_uri = Permalink_Manager_URI_Functions_Post::get_default_post_uri( $product_id, false, true );
|
||||
Permalink_Manager_URI_Functions::save_single_uri( $product_id, $custom_uri, false, true );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* If the URI contains %pa_attribute_name% tag, replace it with the value of the attribute
|
||||
*
|
||||
* @param string $default_uri The default custom permalink that WordPress would use for the post.
|
||||
* @param string $slug The post slug.
|
||||
* @param WP_Post $post The post object.
|
||||
* @param string $post_name The post slug.
|
||||
* @param bool $native_uri true if the URI is a native URI, false if it's a custom URI
|
||||
*
|
||||
* @return string The default custom permalink
|
||||
*/
|
||||
function woocommerce_product_attributes( $default_uri, $slug, $post, $post_name, $native_uri ) {
|
||||
// Do not affect native URIs
|
||||
if ( $native_uri ) {
|
||||
return $default_uri;
|
||||
}
|
||||
|
||||
// Use only for products
|
||||
if ( empty( $post->post_type ) || $post->post_type !== 'product' ) {
|
||||
return $default_uri;
|
||||
}
|
||||
|
||||
preg_match_all( "/%pa_(.[^\%]+)%/", $default_uri, $custom_fields );
|
||||
|
||||
if ( ! empty( $custom_fields[1] ) ) {
|
||||
$product = wc_get_product( $post->ID );
|
||||
|
||||
foreach ( $custom_fields[1] as $i => $custom_field ) {
|
||||
$attribute_name = sanitize_title( $custom_field );
|
||||
$attribute_value = $product->get_attribute( $attribute_name );
|
||||
|
||||
$default_uri = str_replace( $custom_fields[0][ $i ], Permalink_Manager_Helper_Functions::sanitize_title( $attribute_value ), $default_uri );
|
||||
}
|
||||
}
|
||||
|
||||
return $default_uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop the plugin from generating the custom permalink for new WooCommerce product prematurely.
|
||||
*
|
||||
* @param WC_Data $data The product object.
|
||||
* @param WP_REST_Request $request The REST API request object.
|
||||
* @param bool $is_new_post Whether the product is newly created.
|
||||
*/
|
||||
function woocommerce_delay_product_custom_permalink( $data, $request, $is_new_post ) {
|
||||
add_filter( 'permalink_manager_pre_update_post_uri', '__return_null', 100 );
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a custom permalink for a WooCommerce product after it is inserted via the REST API.
|
||||
*
|
||||
* @param WC_Product $product The product object.
|
||||
* @param WP_REST_Request $request The REST API request object.
|
||||
* @param bool $is_new_post Whether the product is newly created.
|
||||
*/
|
||||
function woocommerce_set_custom_uri_after_rest_insert( $product, $request, $is_new_post ) {
|
||||
if ( $is_new_post && class_exists( 'Permalink_Manager_URI_Functions_Post' ) && method_exists( $product, 'get_id' ) ) {
|
||||
$product_id = $product->get_id();
|
||||
|
||||
remove_filter( 'permalink_manager_pre_update_post_uri', '__return_null', 100 );
|
||||
|
||||
$new_uri = Permalink_Manager_URI_Functions_Post::get_default_post_uri( $product_id );
|
||||
Permalink_Manager_URI_Functions_Post::save_uri( $product_id, $new_uri, $is_new_post );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the current request is a WooCommerce AJAX request. If it is, check the translated page's URL should be returned
|
||||
*
|
||||
* @param string $permalink The full URL of the post
|
||||
* @param WP_Post $post The post object
|
||||
* @param string $old_permalink The original URL of the post.
|
||||
*
|
||||
* @return string The permalink is being returned.
|
||||
*/
|
||||
function woocommerce_translate_ajax_fragments_urls( $permalink, $post, $old_permalink ) {
|
||||
// Use it only if the permalinks are different
|
||||
if ( $permalink == $old_permalink || $post->post_type !== 'page' ) {
|
||||
return $permalink;
|
||||
}
|
||||
|
||||
// A. Native WooCommerce AJAX events
|
||||
if ( ! empty( $_REQUEST['wc-ajax'] ) ) {
|
||||
$action = sanitize_title( $_REQUEST['wc-ajax'] );
|
||||
} // B. Shoptimizer theme
|
||||
else if ( ! empty( $_REQUEST['action'] ) ) {
|
||||
$action = sanitize_title( $_REQUEST['action'] );
|
||||
}
|
||||
|
||||
// Allowed action names
|
||||
$allowed_actions = array( 'shoptimizer_pdp_ajax_atc', 'get_refreshed_fragments' );
|
||||
|
||||
if ( ! empty( $action ) && in_array( $action, $allowed_actions ) ) {
|
||||
$translated_post_id = apply_filters( 'wpml_object_id', $post->ID, 'page' );
|
||||
$permalink = ( $translated_post_id !== $post->ID ) ? get_permalink( $translated_post_id ) : $permalink;
|
||||
}
|
||||
|
||||
return $permalink;
|
||||
}
|
||||
|
||||
/**
|
||||
* 4FA. Add a new column to the WooCommerce CSV Import/Export tool
|
||||
*
|
||||
* @param array $columns The array of columns to be displayed.
|
||||
*
|
||||
* @return array The $columns array.
|
||||
*/
|
||||
function woocommerce_csv_custom_uri_column( $columns ) {
|
||||
if ( ! is_array( $columns ) ) {
|
||||
return $columns;
|
||||
}
|
||||
|
||||
$label = __( 'Custom URI', 'permalink-manager' );
|
||||
$key = 'custom_uri';
|
||||
|
||||
if ( current_filter() == 'woocommerce_csv_product_import_mapping_default_columns' ) {
|
||||
$columns[ $label ] = $key;
|
||||
} else {
|
||||
$columns[ $key ] = $label;
|
||||
}
|
||||
|
||||
return $columns;
|
||||
}
|
||||
|
||||
/**
|
||||
* 4FB. Return the custom permalink of the product if it exists, otherwise return the default URI
|
||||
*
|
||||
* @param string $value The value of the column.
|
||||
* @param WC_Product $product The product object.
|
||||
* @param mixed $column_id The column ID.
|
||||
*
|
||||
* @return string The custom permalink or default permalink
|
||||
*/
|
||||
function woocommerce_export_custom_uri_value( $value, $product, $column_id ) {
|
||||
if ( empty( $value ) && ! empty( $product ) ) {
|
||||
$product_id = $product->get_id();
|
||||
|
||||
// Get custom permalink or default permalink
|
||||
$value = Permalink_Manager_URI_Functions_Post::get_post_uri( $product_id );
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 4FC. Set the custom URI for the product using the value from CSV file, if not set use the default permalink
|
||||
*
|
||||
* @param WC_Product $product The product object.
|
||||
* @param array $data The data array for the current row being imported.
|
||||
*/
|
||||
function woocommerce_csv_import_custom_uri( $product, $data ) {
|
||||
if ( ! empty( $product ) ) {
|
||||
$product_id = $product->get_id();
|
||||
|
||||
// Ignore variations
|
||||
if ( $product->get_type() == 'variation' ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$current_uri = Permalink_Manager_URI_Functions::get_single_uri( $product_id, false, true );
|
||||
|
||||
// A. Use default permalink if "Custom URI" is not set and did not exist before
|
||||
if ( empty( $current_uri ) && empty( $data['custom_uri'] ) ) {
|
||||
$custom_uri = Permalink_Manager_URI_Functions_Post::get_default_post_uri( $product_id, false, true );
|
||||
} else if ( ! empty( $data['custom_uri'] ) ) {
|
||||
$custom_uri = Permalink_Manager_Helper_Functions::sanitize_title( $data['custom_uri'] );
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
Permalink_Manager_URI_Functions::save_single_uri( $product_id, $custom_uri, false, true );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Declare support for 'High-Performance order storage (COT)' and other features in WooCommerce
|
||||
*/
|
||||
function woocommerce_declare_compatibility() {
|
||||
$features_util_class = '\Automattic\WooCommerce\Utilities\FeaturesUtil';
|
||||
|
||||
if ( class_exists( $features_util_class ) && method_exists( $features_util_class, 'declare_compatibility' ) ) {
|
||||
$features = method_exists( $features_util_class, 'get_features' ) ? $features_util_class::get_features( true ) : array();
|
||||
|
||||
foreach ( array_keys( $features ) as $feature ) {
|
||||
$features_util_class::declare_compatibility( $feature, PERMALINK_MANAGER_BASENAME );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the Wishlist ID from the URI and add it to the $uri_parts array (WooCommerce Wishlist Plugin)
|
||||
*
|
||||
* @param array $uri_parts An array of the URI parts.
|
||||
* @param string $request_url The URL that was requested.
|
||||
* @param array $endpoints An array of all the endpoints that are currently registered.
|
||||
*
|
||||
* @return array The URI parts.
|
||||
*/
|
||||
function ti_woocommerce_wishlist_uris( $uri_parts, $request_url, $endpoints ) {
|
||||
$wishlist_pid = function_exists( 'tinv_get_option' ) ? tinv_get_option( 'general', 'page_wishlist' ) : '';
|
||||
|
||||
// Find the Wishlist page URI
|
||||
if ( is_numeric( $wishlist_pid ) ) {
|
||||
$current_uri = Permalink_Manager_URI_Functions::get_single_uri( $wishlist_pid, false, true );
|
||||
|
||||
if ( ! empty( $current_uri ) ) {
|
||||
$wishlist_uri = preg_quote( $current_uri, '/' );
|
||||
|
||||
// Extract the Wishlist ID
|
||||
preg_match( "/^({$wishlist_uri})\/([^\/]+)\/?$/", $uri_parts['uri'], $output_array );
|
||||
|
||||
if ( ! empty( $output_array[2] ) ) {
|
||||
$uri_parts['uri'] = $output_array[1];
|
||||
$uri_parts['endpoint'] = 'tinvwlID';
|
||||
$uri_parts['endpoint_value'] = $output_array[2];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $uri_parts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep the query strings appended to the product permalinks by WooCommerce Subscriptions
|
||||
*
|
||||
* @param string $permalink
|
||||
* @param WP_Post $post
|
||||
* @param string $old_permalink
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
function wcs_fix_subscription_links( $permalink, $post, $old_permalink ) {
|
||||
if ( ! empty( $post->post_type ) && $post->post_type == 'product' && strpos( $old_permalink, 'switch-subscription=' ) !== false ) {
|
||||
$query_arg = parse_url( $old_permalink, PHP_URL_QUERY );
|
||||
$permalink = "{$permalink}?{$query_arg}";
|
||||
}
|
||||
|
||||
return $permalink;
|
||||
}
|
||||
}
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
<?php
|
||||
if ( !class_exists('Puc_v4_Factory', false) ):
|
||||
|
||||
class Puc_v4_Factory extends Puc_v4p11_Factory { }
|
||||
|
||||
endif;
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
if ( !class_exists('Puc_v4p11_Autoloader', false) ):
|
||||
|
||||
class Puc_v4p11_Autoloader {
|
||||
private $prefix = '';
|
||||
private $rootDir = '';
|
||||
private $libraryDir = '';
|
||||
|
||||
private $staticMap;
|
||||
|
||||
public function __construct() {
|
||||
$this->rootDir = dirname(__FILE__) . '/';
|
||||
$nameParts = explode('_', __CLASS__, 3);
|
||||
$this->prefix = $nameParts[0] . '_' . $nameParts[1] . '_';
|
||||
|
||||
$this->libraryDir = $this->rootDir . '../..';
|
||||
if ( !self::isPhar() ) {
|
||||
$this->libraryDir = realpath($this->libraryDir);
|
||||
}
|
||||
$this->libraryDir = $this->libraryDir . '/';
|
||||
|
||||
$this->staticMap = array(
|
||||
'PucReadmeParser' => 'vendor/PucReadmeParser.php',
|
||||
'Parsedown' => 'vendor/Parsedown.php',
|
||||
'Puc_v4_Factory' => 'Puc/v4/Factory.php',
|
||||
);
|
||||
|
||||
spl_autoload_register(array($this, 'autoload'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if this file is running as part of a Phar archive.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private static function isPhar() {
|
||||
//Check if the current file path starts with "phar://".
|
||||
static $pharProtocol = 'phar://';
|
||||
return (substr(__FILE__, 0, strlen($pharProtocol)) === $pharProtocol);
|
||||
}
|
||||
|
||||
public function autoload($className) {
|
||||
if ( isset($this->staticMap[$className]) && file_exists($this->libraryDir . $this->staticMap[$className]) ) {
|
||||
/** @noinspection PhpIncludeInspection */
|
||||
include ($this->libraryDir . $this->staticMap[$className]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (strpos($className, $this->prefix) === 0) {
|
||||
$path = substr($className, strlen($this->prefix));
|
||||
$path = str_replace('_', '/', $path);
|
||||
$path = $this->rootDir . $path . '.php';
|
||||
|
||||
if (file_exists($path)) {
|
||||
/** @noinspection PhpIncludeInspection */
|
||||
include $path;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
<?php
|
||||
if ( !class_exists('Puc_v4p11_DebugBar_Extension', false) ):
|
||||
|
||||
class Puc_v4p11_DebugBar_Extension {
|
||||
const RESPONSE_BODY_LENGTH_LIMIT = 4000;
|
||||
|
||||
/** @var Puc_v4p11_UpdateChecker */
|
||||
protected $updateChecker;
|
||||
protected $panelClass = 'Puc_v4p11_DebugBar_Panel';
|
||||
|
||||
public function __construct($updateChecker, $panelClass = null) {
|
||||
$this->updateChecker = $updateChecker;
|
||||
if ( isset($panelClass) ) {
|
||||
$this->panelClass = $panelClass;
|
||||
}
|
||||
|
||||
if ( version_compare(PHP_VERSION, '5.3', '>=') && (strpos($this->panelClass, '\\') === false) ) {
|
||||
$this->panelClass = __NAMESPACE__ . '\\' . $this->panelClass;
|
||||
}
|
||||
|
||||
add_filter('debug_bar_panels', array($this, 'addDebugBarPanel'));
|
||||
add_action('debug_bar_enqueue_scripts', array($this, 'enqueuePanelDependencies'));
|
||||
|
||||
add_action('wp_ajax_puc_v4_debug_check_now', array($this, 'ajaxCheckNow'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the PUC Debug Bar panel.
|
||||
*
|
||||
* @param array $panels
|
||||
* @return array
|
||||
*/
|
||||
public function addDebugBarPanel($panels) {
|
||||
if ( $this->updateChecker->userCanInstallUpdates() ) {
|
||||
$panels[] = new $this->panelClass($this->updateChecker);
|
||||
}
|
||||
return $panels;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enqueue our Debug Bar scripts and styles.
|
||||
*/
|
||||
public function enqueuePanelDependencies() {
|
||||
wp_enqueue_style(
|
||||
'puc-debug-bar-style-v4',
|
||||
$this->getLibraryUrl("/css/puc-debug-bar.css"),
|
||||
array('debug-bar'),
|
||||
'20171124'
|
||||
);
|
||||
|
||||
wp_enqueue_script(
|
||||
'puc-debug-bar-js-v4',
|
||||
$this->getLibraryUrl("/js/debug-bar.js"),
|
||||
array('jquery'),
|
||||
'20201209'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run an update check and output the result. Useful for making sure that
|
||||
* the update checking process works as expected.
|
||||
*/
|
||||
public function ajaxCheckNow() {
|
||||
if ( $_POST['uid'] !== $this->updateChecker->getUniqueName('uid') ) {
|
||||
return;
|
||||
}
|
||||
$this->preAjaxRequest();
|
||||
$update = $this->updateChecker->checkForUpdates();
|
||||
if ( $update !== null ) {
|
||||
echo "An update is available:";
|
||||
echo '<pre>', htmlentities(print_r($update, true)), '</pre>';
|
||||
} else {
|
||||
echo 'No updates found.';
|
||||
}
|
||||
|
||||
$errors = $this->updateChecker->getLastRequestApiErrors();
|
||||
if ( !empty($errors) ) {
|
||||
printf('<p>The update checker encountered %d API error%s.</p>', count($errors), (count($errors) > 1) ? 's' : '');
|
||||
|
||||
foreach (array_values($errors) as $num => $item) {
|
||||
$wpError = $item['error'];
|
||||
/** @var WP_Error $wpError */
|
||||
printf('<h4>%d) %s</h4>', $num + 1, esc_html($wpError->get_error_message()));
|
||||
|
||||
echo '<dl>';
|
||||
printf('<dt>Error code:</dt><dd><code>%s</code></dd>', esc_html($wpError->get_error_code()));
|
||||
|
||||
if ( isset($item['url']) ) {
|
||||
printf('<dt>Requested URL:</dt><dd><code>%s</code></dd>', esc_html($item['url']));
|
||||
}
|
||||
|
||||
if ( isset($item['httpResponse']) ) {
|
||||
if ( is_wp_error($item['httpResponse']) ) {
|
||||
$httpError = $item['httpResponse'];
|
||||
/** @var WP_Error $httpError */
|
||||
printf(
|
||||
'<dt>WordPress HTTP API error:</dt><dd>%s (<code>%s</code>)</dd>',
|
||||
esc_html($httpError->get_error_message()),
|
||||
esc_html($httpError->get_error_code())
|
||||
);
|
||||
} else {
|
||||
//Status code.
|
||||
printf(
|
||||
'<dt>HTTP status:</dt><dd><code>%d %s</code></dd>',
|
||||
wp_remote_retrieve_response_code($item['httpResponse']),
|
||||
wp_remote_retrieve_response_message($item['httpResponse'])
|
||||
);
|
||||
|
||||
//Headers.
|
||||
echo '<dt>Response headers:</dt><dd><pre>';
|
||||
foreach (wp_remote_retrieve_headers($item['httpResponse']) as $name => $value) {
|
||||
printf("%s: %s\n", esc_html($name), esc_html($value));
|
||||
}
|
||||
echo '</pre></dd>';
|
||||
|
||||
//Body.
|
||||
$body = wp_remote_retrieve_body($item['httpResponse']);
|
||||
if ( $body === '' ) {
|
||||
$body = '(Empty response.)';
|
||||
} else if ( strlen($body) > self::RESPONSE_BODY_LENGTH_LIMIT ) {
|
||||
$length = strlen($body);
|
||||
$body = substr($body, 0, self::RESPONSE_BODY_LENGTH_LIMIT)
|
||||
. sprintf("\n(Long string truncated. Total length: %d bytes.)", $length);
|
||||
}
|
||||
|
||||
printf('<dt>Response body:</dt><dd><pre>%s</pre></dd>', esc_html($body));
|
||||
}
|
||||
}
|
||||
echo '<dl>';
|
||||
}
|
||||
}
|
||||
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check access permissions and enable error display (for debugging).
|
||||
*/
|
||||
protected function preAjaxRequest() {
|
||||
if ( !$this->updateChecker->userCanInstallUpdates() ) {
|
||||
die('Access denied');
|
||||
}
|
||||
check_ajax_referer('puc-ajax');
|
||||
|
||||
error_reporting(E_ALL);
|
||||
@ini_set('display_errors', 'On');
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove hooks that were added by this extension.
|
||||
*/
|
||||
public function removeHooks() {
|
||||
remove_filter('debug_bar_panels', array($this, 'addDebugBarPanel'));
|
||||
remove_action('debug_bar_enqueue_scripts', array($this, 'enqueuePanelDependencies'));
|
||||
remove_action('wp_ajax_puc_v4_debug_check_now', array($this, 'ajaxCheckNow'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $filePath
|
||||
* @return string
|
||||
*/
|
||||
private function getLibraryUrl($filePath) {
|
||||
$absolutePath = realpath(dirname(__FILE__) . '/../../../' . ltrim($filePath, '/'));
|
||||
|
||||
//Where is the library located inside the WordPress directory structure?
|
||||
$absolutePath = Puc_v4p11_Factory::normalizePath($absolutePath);
|
||||
|
||||
$pluginDir = Puc_v4p11_Factory::normalizePath(WP_PLUGIN_DIR);
|
||||
$muPluginDir = Puc_v4p11_Factory::normalizePath(WPMU_PLUGIN_DIR);
|
||||
$themeDir = Puc_v4p11_Factory::normalizePath(get_theme_root());
|
||||
|
||||
if ( (strpos($absolutePath, $pluginDir) === 0) || (strpos($absolutePath, $muPluginDir) === 0) ) {
|
||||
//It's part of a plugin.
|
||||
return plugins_url(basename($absolutePath), $absolutePath);
|
||||
} else if ( strpos($absolutePath, $themeDir) === 0 ) {
|
||||
//It's part of a theme.
|
||||
$relativePath = substr($absolutePath, strlen($themeDir) + 1);
|
||||
$template = substr($relativePath, 0, strpos($relativePath, '/'));
|
||||
$baseUrl = get_theme_root_uri($template);
|
||||
|
||||
if ( !empty($baseUrl) && $relativePath ) {
|
||||
return $baseUrl . '/' . $relativePath;
|
||||
}
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
<?php
|
||||
|
||||
if ( !class_exists('Puc_v4p11_DebugBar_Panel', false) && class_exists('Debug_Bar_Panel', false) ):
|
||||
|
||||
class Puc_v4p11_DebugBar_Panel extends Debug_Bar_Panel {
|
||||
/** @var Puc_v4p11_UpdateChecker */
|
||||
protected $updateChecker;
|
||||
|
||||
private $responseBox = '<div class="puc-ajax-response" style="display: none;"></div>';
|
||||
|
||||
public function __construct($updateChecker) {
|
||||
$this->updateChecker = $updateChecker;
|
||||
$title = sprintf(
|
||||
'<span class="puc-debug-menu-link-%s">PUC (%s)</span>',
|
||||
esc_attr($this->updateChecker->getUniqueName('uid')),
|
||||
$this->updateChecker->slug
|
||||
);
|
||||
parent::__construct($title);
|
||||
}
|
||||
|
||||
public function render() {
|
||||
printf(
|
||||
'<div class="puc-debug-bar-panel-v4" id="%1$s" data-slug="%2$s" data-uid="%3$s" data-nonce="%4$s">',
|
||||
esc_attr($this->updateChecker->getUniqueName('debug-bar-panel')),
|
||||
esc_attr($this->updateChecker->slug),
|
||||
esc_attr($this->updateChecker->getUniqueName('uid')),
|
||||
esc_attr(wp_create_nonce('puc-ajax'))
|
||||
);
|
||||
|
||||
$this->displayConfiguration();
|
||||
$this->displayStatus();
|
||||
$this->displayCurrentUpdate();
|
||||
|
||||
echo '</div>';
|
||||
}
|
||||
|
||||
private function displayConfiguration() {
|
||||
echo '<h3>Configuration</h3>';
|
||||
echo '<table class="puc-debug-data">';
|
||||
$this->displayConfigHeader();
|
||||
$this->row('Slug', htmlentities($this->updateChecker->slug));
|
||||
$this->row('DB option', htmlentities($this->updateChecker->optionName));
|
||||
|
||||
$requestInfoButton = $this->getMetadataButton();
|
||||
$this->row('Metadata URL', htmlentities($this->updateChecker->metadataUrl) . ' ' . $requestInfoButton . $this->responseBox);
|
||||
|
||||
$scheduler = $this->updateChecker->scheduler;
|
||||
if ( $scheduler->checkPeriod > 0 ) {
|
||||
$this->row('Automatic checks', 'Every ' . $scheduler->checkPeriod . ' hours');
|
||||
} else {
|
||||
$this->row('Automatic checks', 'Disabled');
|
||||
}
|
||||
|
||||
if ( isset($scheduler->throttleRedundantChecks) ) {
|
||||
if ( $scheduler->throttleRedundantChecks && ($scheduler->checkPeriod > 0) ) {
|
||||
$this->row(
|
||||
'Throttling',
|
||||
sprintf(
|
||||
'Enabled. If an update is already available, check for updates every %1$d hours instead of every %2$d hours.',
|
||||
$scheduler->throttledCheckPeriod,
|
||||
$scheduler->checkPeriod
|
||||
)
|
||||
);
|
||||
} else {
|
||||
$this->row('Throttling', 'Disabled');
|
||||
}
|
||||
}
|
||||
|
||||
$this->updateChecker->onDisplayConfiguration($this);
|
||||
|
||||
echo '</table>';
|
||||
}
|
||||
|
||||
protected function displayConfigHeader() {
|
||||
//Do nothing. This should be implemented in subclasses.
|
||||
}
|
||||
|
||||
protected function getMetadataButton() {
|
||||
return '';
|
||||
}
|
||||
|
||||
private function displayStatus() {
|
||||
echo '<h3>Status</h3>';
|
||||
echo '<table class="puc-debug-data">';
|
||||
$state = $this->updateChecker->getUpdateState();
|
||||
$checkNowButton = '';
|
||||
if ( function_exists('get_submit_button') ) {
|
||||
$checkNowButton = get_submit_button(
|
||||
'Check Now',
|
||||
'secondary',
|
||||
'puc-check-now-button',
|
||||
false,
|
||||
array('id' => $this->updateChecker->getUniqueName('check-now-button'))
|
||||
);
|
||||
}
|
||||
|
||||
if ( $state->getLastCheck() > 0 ) {
|
||||
$this->row('Last check', $this->formatTimeWithDelta($state->getLastCheck()) . ' ' . $checkNowButton . $this->responseBox);
|
||||
} else {
|
||||
$this->row('Last check', 'Never');
|
||||
}
|
||||
|
||||
$nextCheck = wp_next_scheduled($this->updateChecker->scheduler->getCronHookName());
|
||||
$this->row('Next automatic check', $this->formatTimeWithDelta($nextCheck));
|
||||
|
||||
if ( $state->getCheckedVersion() !== '' ) {
|
||||
$this->row('Checked version', htmlentities($state->getCheckedVersion()));
|
||||
$this->row('Cached update', $state->getUpdate());
|
||||
}
|
||||
$this->row('Update checker class', htmlentities(get_class($this->updateChecker)));
|
||||
echo '</table>';
|
||||
}
|
||||
|
||||
private function displayCurrentUpdate() {
|
||||
$update = $this->updateChecker->getUpdate();
|
||||
if ( $update !== null ) {
|
||||
echo '<h3>An Update Is Available</h3>';
|
||||
echo '<table class="puc-debug-data">';
|
||||
$fields = $this->getUpdateFields();
|
||||
foreach($fields as $field) {
|
||||
if ( property_exists($update, $field) ) {
|
||||
$this->row(ucwords(str_replace('_', ' ', $field)), htmlentities($update->$field));
|
||||
}
|
||||
}
|
||||
echo '</table>';
|
||||
} else {
|
||||
echo '<h3>No updates currently available</h3>';
|
||||
}
|
||||
}
|
||||
|
||||
protected function getUpdateFields() {
|
||||
return array('version', 'download_url', 'slug',);
|
||||
}
|
||||
|
||||
private function formatTimeWithDelta($unixTime) {
|
||||
if ( empty($unixTime) ) {
|
||||
return 'Never';
|
||||
}
|
||||
|
||||
$delta = time() - $unixTime;
|
||||
$result = human_time_diff(time(), $unixTime);
|
||||
if ( $delta < 0 ) {
|
||||
$result = 'after ' . $result;
|
||||
} else {
|
||||
$result = $result . ' ago';
|
||||
}
|
||||
$result .= ' (' . $this->formatTimestamp($unixTime) . ')';
|
||||
return $result;
|
||||
}
|
||||
|
||||
private function formatTimestamp($unixTime) {
|
||||
return gmdate('Y-m-d H:i:s', $unixTime + (get_option('gmt_offset') * 3600));
|
||||
}
|
||||
|
||||
public function row($name, $value) {
|
||||
if ( is_object($value) || is_array($value) ) {
|
||||
$value = '<pre>' . htmlentities(print_r($value, true)) . '</pre>';
|
||||
} else if ($value === null) {
|
||||
$value = '<code>null</code>';
|
||||
}
|
||||
printf('<tr><th scope="row">%1$s</th> <td>%2$s</td></tr>', $name, $value);
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
if ( !class_exists('Puc_v4p11_DebugBar_PluginExtension', false) ):
|
||||
|
||||
class Puc_v4p11_DebugBar_PluginExtension extends Puc_v4p11_DebugBar_Extension {
|
||||
/** @var Puc_v4p11_Plugin_UpdateChecker */
|
||||
protected $updateChecker;
|
||||
|
||||
public function __construct($updateChecker) {
|
||||
parent::__construct($updateChecker, 'Puc_v4p11_DebugBar_PluginPanel');
|
||||
|
||||
add_action('wp_ajax_puc_v4_debug_request_info', array($this, 'ajaxRequestInfo'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Request plugin info and output it.
|
||||
*/
|
||||
public function ajaxRequestInfo() {
|
||||
if ( $_POST['uid'] !== $this->updateChecker->getUniqueName('uid') ) {
|
||||
return;
|
||||
}
|
||||
$this->preAjaxRequest();
|
||||
$info = $this->updateChecker->requestInfo();
|
||||
if ( $info !== null ) {
|
||||
echo 'Successfully retrieved plugin info from the metadata URL:';
|
||||
echo '<pre>', htmlentities(print_r($info, true)), '</pre>';
|
||||
} else {
|
||||
echo 'Failed to retrieve plugin info from the metadata URL.';
|
||||
}
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
if ( !class_exists('Puc_v4p11_DebugBar_PluginPanel', false) ):
|
||||
|
||||
class Puc_v4p11_DebugBar_PluginPanel extends Puc_v4p11_DebugBar_Panel {
|
||||
/**
|
||||
* @var Puc_v4p11_Plugin_UpdateChecker
|
||||
*/
|
||||
protected $updateChecker;
|
||||
|
||||
protected function displayConfigHeader() {
|
||||
$this->row('Plugin file', htmlentities($this->updateChecker->pluginFile));
|
||||
parent::displayConfigHeader();
|
||||
}
|
||||
|
||||
protected function getMetadataButton() {
|
||||
$requestInfoButton = '';
|
||||
if ( function_exists('get_submit_button') ) {
|
||||
$requestInfoButton = get_submit_button(
|
||||
'Request Info',
|
||||
'secondary',
|
||||
'puc-request-info-button',
|
||||
false,
|
||||
array('id' => $this->updateChecker->getUniqueName('request-info-button'))
|
||||
);
|
||||
}
|
||||
return $requestInfoButton;
|
||||
}
|
||||
|
||||
protected function getUpdateFields() {
|
||||
return array_merge(
|
||||
parent::getUpdateFields(),
|
||||
array('homepage', 'upgrade_notice', 'tested',)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
if ( !class_exists('Puc_v4p11_DebugBar_ThemePanel', false) ):
|
||||
|
||||
class Puc_v4p11_DebugBar_ThemePanel extends Puc_v4p11_DebugBar_Panel {
|
||||
/**
|
||||
* @var Puc_v4p11_Theme_UpdateChecker
|
||||
*/
|
||||
protected $updateChecker;
|
||||
|
||||
protected function displayConfigHeader() {
|
||||
$this->row('Theme directory', htmlentities($this->updateChecker->directoryName));
|
||||
parent::displayConfigHeader();
|
||||
}
|
||||
|
||||
protected function getUpdateFields() {
|
||||
return array_merge(parent::getUpdateFields(), array('details_url'));
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
wp-content/plugins/permalink-manager-pro/includes/vendor/plugin-update-checker/Puc/v4p11/Factory.php
Vendored
+365
@@ -0,0 +1,365 @@
|
||||
<?php
|
||||
if ( !class_exists('Puc_v4p11_Factory', false) ):
|
||||
|
||||
/**
|
||||
* A factory that builds update checker instances.
|
||||
*
|
||||
* When multiple versions of the same class have been loaded (e.g. PluginUpdateChecker 4.0
|
||||
* and 4.1), this factory will always use the latest available minor version. Register class
|
||||
* versions by calling {@link PucFactory::addVersion()}.
|
||||
*
|
||||
* At the moment it can only build instances of the UpdateChecker class. Other classes are
|
||||
* intended mainly for internal use and refer directly to specific implementations.
|
||||
*/
|
||||
class Puc_v4p11_Factory {
|
||||
protected static $classVersions = array();
|
||||
protected static $sorted = false;
|
||||
|
||||
protected static $myMajorVersion = '';
|
||||
protected static $latestCompatibleVersion = '';
|
||||
|
||||
/**
|
||||
* A wrapper method for buildUpdateChecker() that reads the metadata URL from the plugin or theme header.
|
||||
*
|
||||
* @param string $fullPath Full path to the main plugin file or the theme's style.css.
|
||||
* @param array $args Optional arguments. Keys should match the argument names of the buildUpdateChecker() method.
|
||||
* @return Puc_v4p11_Plugin_UpdateChecker|Puc_v4p11_Theme_UpdateChecker|Puc_v4p11_Vcs_BaseChecker
|
||||
*/
|
||||
public static function buildFromHeader($fullPath, $args = array()) {
|
||||
$fullPath = self::normalizePath($fullPath);
|
||||
|
||||
//Set up defaults.
|
||||
$defaults = array(
|
||||
'metadataUrl' => '',
|
||||
'slug' => '',
|
||||
'checkPeriod' => 12,
|
||||
'optionName' => '',
|
||||
'muPluginFile' => '',
|
||||
);
|
||||
$args = array_merge($defaults, array_intersect_key($args, $defaults));
|
||||
extract($args, EXTR_SKIP);
|
||||
|
||||
//Check for the service URI
|
||||
if ( empty($metadataUrl) ) {
|
||||
$metadataUrl = self::getServiceURI($fullPath);
|
||||
}
|
||||
|
||||
/** @noinspection PhpUndefinedVariableInspection These variables are created by extract(), above. */
|
||||
return self::buildUpdateChecker($metadataUrl, $fullPath, $slug, $checkPeriod, $optionName, $muPluginFile);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new instance of the update checker.
|
||||
*
|
||||
* This method automatically detects if you're using it for a plugin or a theme and chooses
|
||||
* the appropriate implementation for your update source (JSON file, GitHub, BitBucket, etc).
|
||||
*
|
||||
* @see Puc_v4p11_UpdateChecker::__construct
|
||||
*
|
||||
* @param string $metadataUrl The URL of the metadata file, a GitHub repository, or another supported update source.
|
||||
* @param string $fullPath Full path to the main plugin file or to the theme directory.
|
||||
* @param string $slug Custom slug. Defaults to the name of the main plugin file or the theme directory.
|
||||
* @param int $checkPeriod How often to check for updates (in hours).
|
||||
* @param string $optionName Where to store book-keeping info about update checks.
|
||||
* @param string $muPluginFile The plugin filename relative to the mu-plugins directory.
|
||||
* @return Puc_v4p11_Plugin_UpdateChecker|Puc_v4p11_Theme_UpdateChecker|Puc_v4p11_Vcs_BaseChecker
|
||||
*/
|
||||
public static function buildUpdateChecker($metadataUrl, $fullPath, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = '') {
|
||||
$fullPath = self::normalizePath($fullPath);
|
||||
$id = null;
|
||||
|
||||
//Plugin or theme?
|
||||
$themeDirectory = self::getThemeDirectoryName($fullPath);
|
||||
if ( self::isPluginFile($fullPath) ) {
|
||||
$type = 'Plugin';
|
||||
$id = $fullPath;
|
||||
} else if ( $themeDirectory !== null ) {
|
||||
$type = 'Theme';
|
||||
$id = $themeDirectory;
|
||||
} else {
|
||||
throw new RuntimeException(sprintf(
|
||||
'The update checker cannot determine if "%s" is a plugin or a theme. ' .
|
||||
'This is a bug. Please contact the PUC developer.',
|
||||
htmlentities($fullPath)
|
||||
));
|
||||
}
|
||||
|
||||
//Which hosting service does the URL point to?
|
||||
$service = self::getVcsService($metadataUrl);
|
||||
|
||||
$apiClass = null;
|
||||
if ( empty($service) ) {
|
||||
//The default is to get update information from a remote JSON file.
|
||||
$checkerClass = $type . '_UpdateChecker';
|
||||
} else {
|
||||
//You can also use a VCS repository like GitHub.
|
||||
$checkerClass = 'Vcs_' . $type . 'UpdateChecker';
|
||||
$apiClass = $service . 'Api';
|
||||
}
|
||||
|
||||
$checkerClass = self::getCompatibleClassVersion($checkerClass);
|
||||
if ( $checkerClass === null ) {
|
||||
trigger_error(
|
||||
sprintf(
|
||||
'PUC %s does not support updates for %ss %s',
|
||||
htmlentities(self::$latestCompatibleVersion),
|
||||
strtolower($type),
|
||||
$service ? ('hosted on ' . htmlentities($service)) : 'using JSON metadata'
|
||||
),
|
||||
E_USER_ERROR
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
//Add the current namespace to the class name(s).
|
||||
if ( version_compare(PHP_VERSION, '5.3', '>=') ) {
|
||||
$checkerClass = __NAMESPACE__ . '\\' . $checkerClass;
|
||||
}
|
||||
|
||||
if ( !isset($apiClass) ) {
|
||||
//Plain old update checker.
|
||||
return new $checkerClass($metadataUrl, $id, $slug, $checkPeriod, $optionName, $muPluginFile);
|
||||
} else {
|
||||
//VCS checker + an API client.
|
||||
$apiClass = self::getCompatibleClassVersion($apiClass);
|
||||
if ( $apiClass === null ) {
|
||||
trigger_error(sprintf(
|
||||
'PUC %s does not support %s',
|
||||
htmlentities(self::$latestCompatibleVersion),
|
||||
htmlentities($service)
|
||||
), E_USER_ERROR);
|
||||
return null;
|
||||
}
|
||||
|
||||
if ( version_compare(PHP_VERSION, '5.3', '>=') && (strpos($apiClass, '\\') === false) ) {
|
||||
$apiClass = __NAMESPACE__ . '\\' . $apiClass;
|
||||
}
|
||||
|
||||
return new $checkerClass(
|
||||
new $apiClass($metadataUrl),
|
||||
$id,
|
||||
$slug,
|
||||
$checkPeriod,
|
||||
$optionName,
|
||||
$muPluginFile
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Normalize a filesystem path. Introduced in WP 3.9.
|
||||
* Copying here allows use of the class on earlier versions.
|
||||
* This version adapted from WP 4.8.2 (unchanged since 4.5.0)
|
||||
*
|
||||
* @param string $path Path to normalize.
|
||||
* @return string Normalized path.
|
||||
*/
|
||||
public static function normalizePath($path) {
|
||||
if ( function_exists('wp_normalize_path') ) {
|
||||
return wp_normalize_path($path);
|
||||
}
|
||||
$path = str_replace('\\', '/', $path);
|
||||
$path = preg_replace('|(?<=.)/+|', '/', $path);
|
||||
if ( substr($path, 1, 1) === ':' ) {
|
||||
$path = ucfirst($path);
|
||||
}
|
||||
return $path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the path points to a plugin file.
|
||||
*
|
||||
* @param string $absolutePath Normalized path.
|
||||
* @return bool
|
||||
*/
|
||||
protected static function isPluginFile($absolutePath) {
|
||||
//Is the file inside the "plugins" or "mu-plugins" directory?
|
||||
$pluginDir = self::normalizePath(WP_PLUGIN_DIR);
|
||||
$muPluginDir = self::normalizePath(WPMU_PLUGIN_DIR);
|
||||
if ( (strpos($absolutePath, $pluginDir) === 0) || (strpos($absolutePath, $muPluginDir) === 0) ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
//Is it a file at all? Caution: is_file() can fail if the parent dir. doesn't have the +x permission set.
|
||||
if ( !is_file($absolutePath) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
//Does it have a valid plugin header?
|
||||
//This is a last-ditch check for plugins symlinked from outside the WP root.
|
||||
if ( function_exists('get_file_data') ) {
|
||||
$headers = get_file_data($absolutePath, array('Name' => 'Plugin Name'), 'plugin');
|
||||
return !empty($headers['Name']);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the name of the theme's directory from a full path to a file inside that directory.
|
||||
* E.g. "/abc/public_html/wp-content/themes/foo/whatever.php" => "foo".
|
||||
*
|
||||
* Note that subdirectories are currently not supported. For example,
|
||||
* "/xyz/wp-content/themes/my-theme/includes/whatever.php" => NULL.
|
||||
*
|
||||
* @param string $absolutePath Normalized path.
|
||||
* @return string|null Directory name, or NULL if the path doesn't point to a theme.
|
||||
*/
|
||||
protected static function getThemeDirectoryName($absolutePath) {
|
||||
if ( is_file($absolutePath) ) {
|
||||
$absolutePath = dirname($absolutePath);
|
||||
}
|
||||
|
||||
if ( file_exists($absolutePath . '/style.css') ) {
|
||||
return basename($absolutePath);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the service URI from the file header.
|
||||
*
|
||||
* @param string $fullPath
|
||||
* @return string
|
||||
*/
|
||||
private static function getServiceURI($fullPath) {
|
||||
//Look for the URI
|
||||
if ( is_readable($fullPath) ) {
|
||||
$seek = array(
|
||||
'github' => 'GitHub URI',
|
||||
'gitlab' => 'GitLab URI',
|
||||
'bucket' => 'BitBucket URI',
|
||||
);
|
||||
$seek = apply_filters('puc_get_source_uri', $seek);
|
||||
$data = get_file_data($fullPath, $seek);
|
||||
foreach ($data as $key => $uri) {
|
||||
if ( $uri ) {
|
||||
return $uri;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//URI was not found so throw an error.
|
||||
throw new RuntimeException(
|
||||
sprintf('Unable to locate URI in header of "%s"', htmlentities($fullPath))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the name of the hosting service that the URL points to.
|
||||
*
|
||||
* @param string $metadataUrl
|
||||
* @return string|null
|
||||
*/
|
||||
private static function getVcsService($metadataUrl) {
|
||||
$service = null;
|
||||
|
||||
//Which hosting service does the URL point to?
|
||||
$host = parse_url($metadataUrl, PHP_URL_HOST);
|
||||
$path = parse_url($metadataUrl, PHP_URL_PATH);
|
||||
|
||||
//Check if the path looks like "/user-name/repository".
|
||||
//For GitLab.com it can also be "/user/group1/group2/.../repository".
|
||||
$repoRegex = '@^/?([^/]+?)/([^/#?&]+?)/?$@';
|
||||
if ( $host === 'gitlab.com' ) {
|
||||
$repoRegex = '@^/?(?:[^/#?&]++/){1,20}(?:[^/#?&]++)/?$@';
|
||||
}
|
||||
if ( preg_match($repoRegex, $path) ) {
|
||||
$knownServices = array(
|
||||
'github.com' => 'GitHub',
|
||||
'bitbucket.org' => 'BitBucket',
|
||||
'gitlab.com' => 'GitLab',
|
||||
);
|
||||
if ( isset($knownServices[$host]) ) {
|
||||
$service = $knownServices[$host];
|
||||
}
|
||||
}
|
||||
|
||||
return apply_filters('puc_get_vcs_service', $service, $host, $path, $metadataUrl);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the latest version of the specified class that has the same major version number
|
||||
* as this factory class.
|
||||
*
|
||||
* @param string $class Partial class name.
|
||||
* @return string|null Full class name.
|
||||
*/
|
||||
protected static function getCompatibleClassVersion($class) {
|
||||
if ( isset(self::$classVersions[$class][self::$latestCompatibleVersion]) ) {
|
||||
return self::$classVersions[$class][self::$latestCompatibleVersion];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the specific class name for the latest available version of a class.
|
||||
*
|
||||
* @param string $class
|
||||
* @return null|string
|
||||
*/
|
||||
public static function getLatestClassVersion($class) {
|
||||
if ( !self::$sorted ) {
|
||||
self::sortVersions();
|
||||
}
|
||||
|
||||
if ( isset(self::$classVersions[$class]) ) {
|
||||
return reset(self::$classVersions[$class]);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort available class versions in descending order (i.e. newest first).
|
||||
*/
|
||||
protected static function sortVersions() {
|
||||
foreach ( self::$classVersions as $class => $versions ) {
|
||||
uksort($versions, array(__CLASS__, 'compareVersions'));
|
||||
self::$classVersions[$class] = $versions;
|
||||
}
|
||||
self::$sorted = true;
|
||||
}
|
||||
|
||||
protected static function compareVersions($a, $b) {
|
||||
return -version_compare($a, $b);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a version of a class.
|
||||
*
|
||||
* @access private This method is only for internal use by the library.
|
||||
*
|
||||
* @param string $generalClass Class name without version numbers, e.g. 'PluginUpdateChecker'.
|
||||
* @param string $versionedClass Actual class name, e.g. 'PluginUpdateChecker_1_2'.
|
||||
* @param string $version Version number, e.g. '1.2'.
|
||||
*/
|
||||
public static function addVersion($generalClass, $versionedClass, $version) {
|
||||
if ( empty(self::$myMajorVersion) ) {
|
||||
$nameParts = explode('_', __CLASS__, 3);
|
||||
self::$myMajorVersion = substr(ltrim($nameParts[1], 'v'), 0, 1);
|
||||
}
|
||||
|
||||
//Store the greatest version number that matches our major version.
|
||||
$components = explode('.', $version);
|
||||
if ( $components[0] === self::$myMajorVersion ) {
|
||||
|
||||
if (
|
||||
empty(self::$latestCompatibleVersion)
|
||||
|| version_compare($version, self::$latestCompatibleVersion, '>')
|
||||
) {
|
||||
self::$latestCompatibleVersion = $version;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if ( !isset(self::$classVersions[$generalClass]) ) {
|
||||
self::$classVersions[$generalClass] = array();
|
||||
}
|
||||
self::$classVersions[$generalClass][$version] = $versionedClass;
|
||||
self::$sorted = false;
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
if ( !class_exists('Puc_v4p11_InstalledPackage', false) ):
|
||||
|
||||
/**
|
||||
* This class represents a currently installed plugin or theme.
|
||||
*
|
||||
* Not to be confused with the "package" field in WP update API responses that contains
|
||||
* the download URL of a the new version.
|
||||
*/
|
||||
abstract class Puc_v4p11_InstalledPackage {
|
||||
/**
|
||||
* @var Puc_v4p11_UpdateChecker
|
||||
*/
|
||||
protected $updateChecker;
|
||||
|
||||
public function __construct($updateChecker) {
|
||||
$this->updateChecker = $updateChecker;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the currently installed version of the plugin or theme.
|
||||
*
|
||||
* @return string|null Version number.
|
||||
*/
|
||||
abstract public function getInstalledVersion();
|
||||
|
||||
/**
|
||||
* Get the full path of the plugin or theme directory (without a trailing slash).
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
abstract public function getAbsoluteDirectoryPath();
|
||||
|
||||
/**
|
||||
* Check whether a regular file exists in the package's directory.
|
||||
*
|
||||
* @param string $relativeFileName File name relative to the package directory.
|
||||
* @return bool
|
||||
*/
|
||||
public function fileExists($relativeFileName) {
|
||||
return is_file(
|
||||
$this->getAbsoluteDirectoryPath()
|
||||
. DIRECTORY_SEPARATOR
|
||||
. ltrim($relativeFileName, '/\\')
|
||||
);
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------
|
||||
* File header parsing
|
||||
* -------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/**
|
||||
* Parse plugin or theme metadata from the header comment.
|
||||
*
|
||||
* This is basically a simplified version of the get_file_data() function from /wp-includes/functions.php.
|
||||
* It's intended as a utility for subclasses that detect updates by parsing files in a VCS.
|
||||
*
|
||||
* @param string|null $content File contents.
|
||||
* @return string[]
|
||||
*/
|
||||
public function getFileHeader($content) {
|
||||
$content = (string)$content;
|
||||
|
||||
//WordPress only looks at the first 8 KiB of the file, so we do the same.
|
||||
$content = substr($content, 0, 8192);
|
||||
//Normalize line endings.
|
||||
$content = str_replace("\r", "\n", $content);
|
||||
|
||||
$headers = $this->getHeaderNames();
|
||||
$results = array();
|
||||
foreach ($headers as $field => $name) {
|
||||
$success = preg_match('/^[ \t\/*#@]*' . preg_quote($name, '/') . ':(.*)$/mi', $content, $matches);
|
||||
|
||||
if ( ($success === 1) && $matches[1] ) {
|
||||
$value = $matches[1];
|
||||
if ( function_exists('_cleanup_header_comment') ) {
|
||||
$value = _cleanup_header_comment($value);
|
||||
}
|
||||
$results[$field] = $value;
|
||||
} else {
|
||||
$results[$field] = '';
|
||||
}
|
||||
}
|
||||
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array Format: ['HeaderKey' => 'Header Name']
|
||||
*/
|
||||
abstract protected function getHeaderNames();
|
||||
|
||||
/**
|
||||
* Get the value of a specific plugin or theme header.
|
||||
*
|
||||
* @param string $headerName
|
||||
* @return string Either the value of the header, or an empty string if the header doesn't exist.
|
||||
*/
|
||||
abstract public function getHeaderValue($headerName);
|
||||
|
||||
}
|
||||
endif;
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
if ( !class_exists('Puc_v4p11_Metadata', false) ):
|
||||
|
||||
/**
|
||||
* A base container for holding information about updates and plugin metadata.
|
||||
*
|
||||
* @author Janis Elsts
|
||||
* @copyright 2016
|
||||
* @access public
|
||||
*/
|
||||
abstract class Puc_v4p11_Metadata {
|
||||
|
||||
/**
|
||||
* Create an instance of this class from a JSON document.
|
||||
*
|
||||
* @abstract
|
||||
* @param string $json
|
||||
* @return self
|
||||
*/
|
||||
public static function fromJson(/** @noinspection PhpUnusedParameterInspection */ $json) {
|
||||
throw new LogicException('The ' . __METHOD__ . ' method must be implemented by subclasses');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $json
|
||||
* @param self $target
|
||||
* @return bool
|
||||
*/
|
||||
protected static function createFromJson($json, $target) {
|
||||
/** @var StdClass $apiResponse */
|
||||
$apiResponse = json_decode($json);
|
||||
if ( empty($apiResponse) || !is_object($apiResponse) ){
|
||||
$errorMessage = "Failed to parse update metadata. Try validating your .json file with http://jsonlint.com/";
|
||||
do_action('puc_api_error', new WP_Error('puc-invalid-json', $errorMessage));
|
||||
trigger_error($errorMessage, E_USER_NOTICE);
|
||||
return false;
|
||||
}
|
||||
|
||||
$valid = $target->validateMetadata($apiResponse);
|
||||
if ( is_wp_error($valid) ){
|
||||
do_action('puc_api_error', $valid);
|
||||
trigger_error($valid->get_error_message(), E_USER_NOTICE);
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach(get_object_vars($apiResponse) as $key => $value){
|
||||
$target->$key = $value;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* No validation by default! Subclasses should check that the required fields are present.
|
||||
*
|
||||
* @param StdClass $apiResponse
|
||||
* @return bool|WP_Error
|
||||
*/
|
||||
protected function validateMetadata(/** @noinspection PhpUnusedParameterInspection */ $apiResponse) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new instance by copying the necessary fields from another object.
|
||||
*
|
||||
* @abstract
|
||||
* @param StdClass|self $object The source object.
|
||||
* @return self The new copy.
|
||||
*/
|
||||
public static function fromObject(/** @noinspection PhpUnusedParameterInspection */ $object) {
|
||||
throw new LogicException('The ' . __METHOD__ . ' method must be implemented by subclasses');
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of StdClass that can later be converted back to an
|
||||
* update or info container. Useful for serialization and caching, as it
|
||||
* avoids the "incomplete object" problem if the cached value is loaded
|
||||
* before this class.
|
||||
*
|
||||
* @return StdClass
|
||||
*/
|
||||
public function toStdClass() {
|
||||
$object = new stdClass();
|
||||
$this->copyFields($this, $object);
|
||||
return $object;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform the metadata into the format used by WordPress core.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
abstract public function toWpFormat();
|
||||
|
||||
/**
|
||||
* Copy known fields from one object to another.
|
||||
*
|
||||
* @param StdClass|self $from
|
||||
* @param StdClass|self $to
|
||||
*/
|
||||
protected function copyFields($from, $to) {
|
||||
$fields = $this->getFieldNames();
|
||||
|
||||
if ( property_exists($from, 'slug') && !empty($from->slug) ) {
|
||||
//Let plugins add extra fields without having to create subclasses.
|
||||
$fields = apply_filters($this->getPrefixedFilter('retain_fields') . '-' . $from->slug, $fields);
|
||||
}
|
||||
|
||||
foreach ($fields as $field) {
|
||||
if ( property_exists($from, $field) ) {
|
||||
$to->$field = $from->$field;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
protected function getFieldNames() {
|
||||
return array();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $tag
|
||||
* @return string
|
||||
*/
|
||||
protected function getPrefixedFilter($tag) {
|
||||
return 'puc_' . $tag;
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
|
||||
if ( !class_exists('Puc_v4p11_OAuthSignature', false) ):
|
||||
|
||||
/**
|
||||
* A basic signature generator for zero-legged OAuth 1.0.
|
||||
*/
|
||||
class Puc_v4p11_OAuthSignature {
|
||||
private $consumerKey = '';
|
||||
private $consumerSecret = '';
|
||||
|
||||
public function __construct($consumerKey, $consumerSecret) {
|
||||
$this->consumerKey = $consumerKey;
|
||||
$this->consumerSecret = $consumerSecret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sign a URL using OAuth 1.0.
|
||||
*
|
||||
* @param string $url The URL to be signed. It may contain query parameters.
|
||||
* @param string $method HTTP method such as "GET", "POST" and so on.
|
||||
* @return string The signed URL.
|
||||
*/
|
||||
public function sign($url, $method = 'GET') {
|
||||
$parameters = array();
|
||||
|
||||
//Parse query parameters.
|
||||
$query = parse_url($url, PHP_URL_QUERY);
|
||||
if ( !empty($query) ) {
|
||||
parse_str($query, $parsedParams);
|
||||
if ( is_array($parameters) ) {
|
||||
$parameters = $parsedParams;
|
||||
}
|
||||
//Remove the query string from the URL. We'll replace it later.
|
||||
$url = substr($url, 0, strpos($url, '?'));
|
||||
}
|
||||
|
||||
$parameters = array_merge(
|
||||
$parameters,
|
||||
array(
|
||||
'oauth_consumer_key' => $this->consumerKey,
|
||||
'oauth_nonce' => $this->nonce(),
|
||||
'oauth_signature_method' => 'HMAC-SHA1',
|
||||
'oauth_timestamp' => time(),
|
||||
'oauth_version' => '1.0',
|
||||
)
|
||||
);
|
||||
unset($parameters['oauth_signature']);
|
||||
|
||||
//Parameters must be sorted alphabetically before signing.
|
||||
ksort($parameters);
|
||||
|
||||
//The most complicated part of the request - generating the signature.
|
||||
//The string to sign contains the HTTP method, the URL path, and all of
|
||||
//our query parameters. Everything is URL encoded. Then we concatenate
|
||||
//them with ampersands into a single string to hash.
|
||||
$encodedVerb = urlencode($method);
|
||||
$encodedUrl = urlencode($url);
|
||||
$encodedParams = urlencode(http_build_query($parameters, '', '&'));
|
||||
|
||||
$stringToSign = $encodedVerb . '&' . $encodedUrl . '&' . $encodedParams;
|
||||
|
||||
//Since we only have one OAuth token (the consumer secret) we only have
|
||||
//to use it as our HMAC key. However, we still have to append an & to it
|
||||
//as if we were using it with additional tokens.
|
||||
$secret = urlencode($this->consumerSecret) . '&';
|
||||
|
||||
//The signature is a hash of the consumer key and the base string. Note
|
||||
//that we have to get the raw output from hash_hmac and base64 encode
|
||||
//the binary data result.
|
||||
$parameters['oauth_signature'] = base64_encode(hash_hmac('sha1', $stringToSign, $secret, true));
|
||||
|
||||
return ($url . '?' . http_build_query($parameters));
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a random nonce.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function nonce() {
|
||||
$mt = microtime();
|
||||
|
||||
$rand = null;
|
||||
if ( is_callable('random_bytes') ) {
|
||||
try {
|
||||
$rand = random_bytes(16);
|
||||
} catch (Exception $ex) {
|
||||
//Fall back to mt_rand (below).
|
||||
}
|
||||
}
|
||||
if ( $rand === null ) {
|
||||
$rand = mt_rand();
|
||||
}
|
||||
|
||||
return md5($mt . '_' . $rand);
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
<?php
|
||||
if ( !class_exists('Puc_v4p11_Plugin_Info', false) ):
|
||||
|
||||
/**
|
||||
* A container class for holding and transforming various plugin metadata.
|
||||
*
|
||||
* @author Janis Elsts
|
||||
* @copyright 2016
|
||||
* @access public
|
||||
*/
|
||||
class Puc_v4p11_Plugin_Info extends Puc_v4p11_Metadata {
|
||||
//Most fields map directly to the contents of the plugin's info.json file.
|
||||
//See the relevant docs for a description of their meaning.
|
||||
public $name;
|
||||
public $slug;
|
||||
public $version;
|
||||
public $homepage;
|
||||
public $sections = array();
|
||||
public $download_url;
|
||||
|
||||
public $banners;
|
||||
public $icons = array();
|
||||
public $translations = array();
|
||||
|
||||
public $author;
|
||||
public $author_homepage;
|
||||
|
||||
public $requires;
|
||||
public $tested;
|
||||
public $requires_php;
|
||||
public $upgrade_notice;
|
||||
|
||||
public $rating;
|
||||
public $num_ratings;
|
||||
public $downloaded;
|
||||
public $active_installs;
|
||||
public $last_updated;
|
||||
|
||||
public $licence;
|
||||
public $licence_status;
|
||||
public $expiration_date;
|
||||
public $variant;
|
||||
public $websites;
|
||||
|
||||
public $id = 0; //The native WP.org API returns numeric plugin IDs, but they're not used for anything.
|
||||
|
||||
public $filename; //Plugin filename relative to the plugins directory.
|
||||
|
||||
/**
|
||||
* Create a new instance of Plugin Info from JSON-encoded plugin info
|
||||
* returned by an external update API.
|
||||
*
|
||||
* @param string $json Valid JSON string representing plugin info.
|
||||
* @return self|null New instance of Plugin Info, or NULL on error.
|
||||
*/
|
||||
public static function fromJson($json){
|
||||
$instance = new self();
|
||||
|
||||
if ( !parent::createFromJson($json, $instance) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
//json_decode decodes assoc. arrays as objects. We want them as arrays.
|
||||
$instance->sections = (array)$instance->sections;
|
||||
$instance->icons = (array)$instance->icons;
|
||||
|
||||
return $instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Very, very basic validation.
|
||||
*
|
||||
* @param StdClass $apiResponse
|
||||
* @return bool|WP_Error
|
||||
*/
|
||||
protected function validateMetadata($apiResponse) {
|
||||
if (
|
||||
!isset($apiResponse->name, $apiResponse->version)
|
||||
|| empty($apiResponse->name)
|
||||
|| empty($apiResponse->version)
|
||||
) {
|
||||
return new WP_Error(
|
||||
'puc-invalid-metadata',
|
||||
"The plugin metadata file does not contain the required 'name' and/or 'version' keys."
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Transform plugin info into the format used by the native WordPress.org API
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function toWpFormat(){
|
||||
$info = new stdClass;
|
||||
|
||||
//The custom update API is built so that many fields have the same name and format
|
||||
//as those returned by the native WordPress.org API. These can be assigned directly.
|
||||
$sameFormat = array(
|
||||
'name', 'slug', 'version', 'requires', 'tested', 'rating', 'upgrade_notice',
|
||||
'num_ratings', 'downloaded', 'active_installs', 'homepage', 'last_updated',
|
||||
'requires_php',
|
||||
);
|
||||
foreach($sameFormat as $field){
|
||||
if ( isset($this->$field) ) {
|
||||
$info->$field = $this->$field;
|
||||
} else {
|
||||
$info->$field = null;
|
||||
}
|
||||
}
|
||||
|
||||
//Other fields need to be renamed and/or transformed.
|
||||
$info->download_link = $this->download_url;
|
||||
$info->author = $this->getFormattedAuthor();
|
||||
$info->sections = array_merge(array('description' => ''), $this->sections);
|
||||
|
||||
if ( !empty($this->banners) ) {
|
||||
//WP expects an array with two keys: "high" and "low". Both are optional.
|
||||
//Docs: https://wordpress.org/plugins/about/faq/#banners
|
||||
$info->banners = is_object($this->banners) ? get_object_vars($this->banners) : $this->banners;
|
||||
$info->banners = array_intersect_key($info->banners, array('high' => true, 'low' => true));
|
||||
}
|
||||
|
||||
return $info;
|
||||
}
|
||||
|
||||
protected function getFormattedAuthor() {
|
||||
if ( !empty($this->author_homepage) ){
|
||||
/** @noinspection HtmlUnknownTarget */
|
||||
return sprintf('<a href="%s">%s</a>', $this->author_homepage, $this->author);
|
||||
}
|
||||
return $this->author;
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
<?php
|
||||
if ( !class_exists('Puc_v4p11_Plugin_Package', false) ):
|
||||
|
||||
class Puc_v4p11_Plugin_Package extends Puc_v4p11_InstalledPackage {
|
||||
/**
|
||||
* @var Puc_v4p11_Plugin_UpdateChecker
|
||||
*/
|
||||
protected $updateChecker;
|
||||
|
||||
/**
|
||||
* @var string Full path of the main plugin file.
|
||||
*/
|
||||
protected $pluginAbsolutePath = '';
|
||||
|
||||
/**
|
||||
* @var string Plugin basename.
|
||||
*/
|
||||
private $pluginFile;
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
private $cachedInstalledVersion = null;
|
||||
|
||||
public function __construct($pluginAbsolutePath, $updateChecker) {
|
||||
$this->pluginAbsolutePath = $pluginAbsolutePath;
|
||||
$this->pluginFile = plugin_basename($this->pluginAbsolutePath);
|
||||
|
||||
parent::__construct($updateChecker);
|
||||
|
||||
//Clear the version number cache when something - anything - is upgraded or WP clears the update cache.
|
||||
add_filter('upgrader_post_install', array($this, 'clearCachedVersion'));
|
||||
add_action('delete_site_transient_update_plugins', array($this, 'clearCachedVersion'));
|
||||
}
|
||||
|
||||
public function getInstalledVersion() {
|
||||
if ( isset($this->cachedInstalledVersion) ) {
|
||||
return $this->cachedInstalledVersion;
|
||||
}
|
||||
|
||||
$pluginHeader = $this->getPluginHeader();
|
||||
if ( isset($pluginHeader['Version']) ) {
|
||||
$this->cachedInstalledVersion = $pluginHeader['Version'];
|
||||
return $pluginHeader['Version'];
|
||||
} else {
|
||||
//This can happen if the filename points to something that is not a plugin.
|
||||
$this->updateChecker->triggerError(
|
||||
sprintf(
|
||||
"Can't to read the Version header for '%s'. The filename is incorrect or is not a plugin.",
|
||||
$this->updateChecker->pluginFile
|
||||
),
|
||||
E_USER_WARNING
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the cached plugin version. This method can be set up as a filter (hook) and will
|
||||
* return the filter argument unmodified.
|
||||
*
|
||||
* @param mixed $filterArgument
|
||||
* @return mixed
|
||||
*/
|
||||
public function clearCachedVersion($filterArgument = null) {
|
||||
$this->cachedInstalledVersion = null;
|
||||
return $filterArgument;
|
||||
}
|
||||
|
||||
public function getAbsoluteDirectoryPath() {
|
||||
return dirname($this->pluginAbsolutePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the value of a specific plugin or theme header.
|
||||
*
|
||||
* @param string $headerName
|
||||
* @param string $defaultValue
|
||||
* @return string Either the value of the header, or $defaultValue if the header doesn't exist or is empty.
|
||||
*/
|
||||
public function getHeaderValue($headerName, $defaultValue = '') {
|
||||
$headers = $this->getPluginHeader();
|
||||
if ( isset($headers[$headerName]) && ($headers[$headerName] !== '') ) {
|
||||
return $headers[$headerName];
|
||||
}
|
||||
return $defaultValue;
|
||||
}
|
||||
|
||||
protected function getHeaderNames() {
|
||||
return array(
|
||||
'Name' => 'Plugin Name',
|
||||
'PluginURI' => 'Plugin URI',
|
||||
'Version' => 'Version',
|
||||
'Description' => 'Description',
|
||||
'Author' => 'Author',
|
||||
'AuthorURI' => 'Author URI',
|
||||
'TextDomain' => 'Text Domain',
|
||||
'DomainPath' => 'Domain Path',
|
||||
'Network' => 'Network',
|
||||
|
||||
//The newest WordPress version that this plugin requires or has been tested with.
|
||||
//We support several different formats for compatibility with other libraries.
|
||||
'Tested WP' => 'Tested WP',
|
||||
'Requires WP' => 'Requires WP',
|
||||
'Tested up to' => 'Tested up to',
|
||||
'Requires at least' => 'Requires at least',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the translated plugin title.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getPluginTitle() {
|
||||
$title = '';
|
||||
$header = $this->getPluginHeader();
|
||||
if ( $header && !empty($header['Name']) && isset($header['TextDomain']) ) {
|
||||
$title = translate($header['Name'], $header['TextDomain']);
|
||||
}
|
||||
return $title;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get plugin's metadata from its file header.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getPluginHeader() {
|
||||
if ( !is_file($this->pluginAbsolutePath) ) {
|
||||
//This can happen if the plugin filename is wrong.
|
||||
$this->updateChecker->triggerError(
|
||||
sprintf(
|
||||
"Can't to read the plugin header for '%s'. The file does not exist.",
|
||||
$this->updateChecker->pluginFile
|
||||
),
|
||||
E_USER_WARNING
|
||||
);
|
||||
return array();
|
||||
}
|
||||
|
||||
if ( !function_exists('get_plugin_data') ) {
|
||||
/** @noinspection PhpIncludeInspection */
|
||||
require_once(ABSPATH . '/wp-admin/includes/plugin.php');
|
||||
}
|
||||
return get_plugin_data($this->pluginAbsolutePath, false, false);
|
||||
}
|
||||
|
||||
public function removeHooks() {
|
||||
remove_filter('upgrader_post_install', array($this, 'clearCachedVersion'));
|
||||
remove_action('delete_site_transient_update_plugins', array($this, 'clearCachedVersion'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the plugin file is inside the mu-plugins directory.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isMuPlugin() {
|
||||
static $cachedResult = null;
|
||||
|
||||
if ( $cachedResult === null ) {
|
||||
if ( !defined('WPMU_PLUGIN_DIR') || !is_string(WPMU_PLUGIN_DIR) ) {
|
||||
$cachedResult = false;
|
||||
return $cachedResult;
|
||||
}
|
||||
|
||||
//Convert both paths to the canonical form before comparison.
|
||||
$muPluginDir = realpath(WPMU_PLUGIN_DIR);
|
||||
$pluginPath = realpath($this->pluginAbsolutePath);
|
||||
//If realpath() fails, just normalize the syntax instead.
|
||||
if (($muPluginDir === false) || ($pluginPath === false)) {
|
||||
$muPluginDir = Puc_v4p11_Factory::normalizePath(WPMU_PLUGIN_DIR);
|
||||
$pluginPath = Puc_v4p11_Factory::normalizePath($this->pluginAbsolutePath);
|
||||
}
|
||||
|
||||
$cachedResult = (strpos($pluginPath, $muPluginDir) === 0);
|
||||
}
|
||||
|
||||
return $cachedResult;
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
+278
@@ -0,0 +1,278 @@
|
||||
<?php
|
||||
if ( !class_exists('Puc_v4p11_Plugin_Ui', false) ):
|
||||
/**
|
||||
* Additional UI elements for plugins.
|
||||
*/
|
||||
class Puc_v4p11_Plugin_Ui {
|
||||
private $updateChecker;
|
||||
private $manualCheckErrorTransient = '';
|
||||
|
||||
/**
|
||||
* @param Puc_v4p11_Plugin_UpdateChecker $updateChecker
|
||||
*/
|
||||
public function __construct($updateChecker) {
|
||||
$this->updateChecker = $updateChecker;
|
||||
$this->manualCheckErrorTransient = $this->updateChecker->getUniqueName('manual_check_errors');
|
||||
|
||||
add_action('admin_init', array($this, 'onAdminInit'));
|
||||
}
|
||||
|
||||
public function onAdminInit() {
|
||||
if ( $this->updateChecker->userCanInstallUpdates() ) {
|
||||
$this->handleManualCheck();
|
||||
|
||||
add_filter('plugin_row_meta', array($this, 'addViewDetailsLink'), 10, 3);
|
||||
add_filter('plugin_row_meta', array($this, 'addCheckForUpdatesLink'), 10, 2);
|
||||
add_action('all_admin_notices', array($this, 'displayManualCheckResult'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a "View Details" link to the plugin row in the "Plugins" page. By default,
|
||||
* the new link will appear before the "Visit plugin site" link (if present).
|
||||
*
|
||||
* You can change the link text by using the "puc_view_details_link-$slug" filter.
|
||||
* Returning an empty string from the filter will disable the link.
|
||||
*
|
||||
* You can change the position of the link using the
|
||||
* "puc_view_details_link_position-$slug" filter.
|
||||
* Returning 'before' or 'after' will place the link immediately before/after
|
||||
* the "Visit plugin site" link.
|
||||
* Returning 'append' places the link after any existing links at the time of the hook.
|
||||
* Returning 'replace' replaces the "Visit plugin site" link.
|
||||
* Returning anything else disables the link when there is a "Visit plugin site" link.
|
||||
*
|
||||
* If there is no "Visit plugin site" link 'append' is always used!
|
||||
*
|
||||
* @param array $pluginMeta Array of meta links.
|
||||
* @param string $pluginFile
|
||||
* @param array $pluginData Array of plugin header data.
|
||||
* @return array
|
||||
*/
|
||||
public function addViewDetailsLink($pluginMeta, $pluginFile, $pluginData = array()) {
|
||||
if ( $this->isMyPluginFile($pluginFile) && !isset($pluginData['slug']) ) {
|
||||
$linkText = apply_filters($this->updateChecker->getUniqueName('view_details_link'), __('View details'));
|
||||
if ( !empty($linkText) ) {
|
||||
$viewDetailsLinkPosition = 'append';
|
||||
|
||||
//Find the "Visit plugin site" link (if present).
|
||||
$visitPluginSiteLinkIndex = count($pluginMeta) - 1;
|
||||
if ( $pluginData['PluginURI'] ) {
|
||||
$escapedPluginUri = esc_url($pluginData['PluginURI']);
|
||||
foreach ($pluginMeta as $linkIndex => $existingLink) {
|
||||
if ( strpos($existingLink, $escapedPluginUri) !== false ) {
|
||||
$visitPluginSiteLinkIndex = $linkIndex;
|
||||
$viewDetailsLinkPosition = apply_filters(
|
||||
$this->updateChecker->getUniqueName('view_details_link_position'),
|
||||
'before'
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$viewDetailsLink = sprintf('<a href="%s" class="thickbox open-plugin-details-modal" aria-label="%s" data-title="%s">%s</a>',
|
||||
esc_url(network_admin_url('plugin-install.php?tab=plugin-information&plugin=' . urlencode($this->updateChecker->slug) .
|
||||
'&TB_iframe=true&width=600&height=550')),
|
||||
esc_attr(sprintf(__('More information about %s'), $pluginData['Name'])),
|
||||
esc_attr($pluginData['Name']),
|
||||
$linkText
|
||||
);
|
||||
switch ($viewDetailsLinkPosition) {
|
||||
case 'before':
|
||||
array_splice($pluginMeta, $visitPluginSiteLinkIndex, 0, $viewDetailsLink);
|
||||
break;
|
||||
case 'after':
|
||||
array_splice($pluginMeta, $visitPluginSiteLinkIndex + 1, 0, $viewDetailsLink);
|
||||
break;
|
||||
case 'replace':
|
||||
$pluginMeta[$visitPluginSiteLinkIndex] = $viewDetailsLink;
|
||||
break;
|
||||
case 'append':
|
||||
default:
|
||||
$pluginMeta[] = $viewDetailsLink;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return $pluginMeta;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a "Check for updates" link to the plugin row in the "Plugins" page. By default,
|
||||
* the new link will appear after the "Visit plugin site" link if present, otherwise
|
||||
* after the "View plugin details" link.
|
||||
*
|
||||
* You can change the link text by using the "puc_manual_check_link-$slug" filter.
|
||||
* Returning an empty string from the filter will disable the link.
|
||||
*
|
||||
* @param array $pluginMeta Array of meta links.
|
||||
* @param string $pluginFile
|
||||
* @return array
|
||||
*/
|
||||
public function addCheckForUpdatesLink($pluginMeta, $pluginFile) {
|
||||
if ( $this->isMyPluginFile($pluginFile) ) {
|
||||
$linkUrl = wp_nonce_url(
|
||||
add_query_arg(
|
||||
array(
|
||||
'puc_check_for_updates' => 1,
|
||||
'puc_slug' => $this->updateChecker->slug,
|
||||
),
|
||||
self_admin_url('plugins.php')
|
||||
),
|
||||
'puc_check_for_updates'
|
||||
);
|
||||
|
||||
$linkText = apply_filters(
|
||||
$this->updateChecker->getUniqueName('manual_check_link'),
|
||||
__('Check for updates', 'plugin-update-checker')
|
||||
);
|
||||
if ( !empty($linkText) ) {
|
||||
/** @noinspection HtmlUnknownTarget */
|
||||
$pluginMeta[] = sprintf('<a href="%s">%s</a>', esc_attr($linkUrl), $linkText);
|
||||
}
|
||||
}
|
||||
return $pluginMeta;
|
||||
}
|
||||
|
||||
protected function isMyPluginFile($pluginFile) {
|
||||
return ($pluginFile == $this->updateChecker->pluginFile)
|
||||
|| (!empty($this->updateChecker->muPluginFile) && ($pluginFile == $this->updateChecker->muPluginFile));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for updates when the user clicks the "Check for updates" link.
|
||||
*
|
||||
* @see self::addCheckForUpdatesLink()
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handleManualCheck() {
|
||||
$shouldCheck =
|
||||
isset($_GET['puc_check_for_updates'], $_GET['puc_slug'])
|
||||
&& $_GET['puc_slug'] == $this->updateChecker->slug
|
||||
&& check_admin_referer('puc_check_for_updates');
|
||||
|
||||
if ( $shouldCheck ) {
|
||||
$update = $this->updateChecker->checkForUpdates();
|
||||
$status = ($update === null) ? 'no_update' : 'update_available';
|
||||
$lastRequestApiErrors = $this->updateChecker->getLastRequestApiErrors();
|
||||
|
||||
if ( ($update === null) && !empty($lastRequestApiErrors) ) {
|
||||
//Some errors are not critical. For example, if PUC tries to retrieve the readme.txt
|
||||
//file from GitHub and gets a 404, that's an API error, but it doesn't prevent updates
|
||||
//from working. Maybe the plugin simply doesn't have a readme.
|
||||
//Let's only show important errors.
|
||||
$foundCriticalErrors = false;
|
||||
$questionableErrorCodes = array(
|
||||
'puc-github-http-error',
|
||||
'puc-gitlab-http-error',
|
||||
'puc-bitbucket-http-error',
|
||||
);
|
||||
|
||||
foreach ($lastRequestApiErrors as $item) {
|
||||
$wpError = $item['error'];
|
||||
/** @var WP_Error $wpError */
|
||||
if ( !in_array($wpError->get_error_code(), $questionableErrorCodes) ) {
|
||||
$foundCriticalErrors = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if ( $foundCriticalErrors ) {
|
||||
$status = 'error';
|
||||
set_site_transient($this->manualCheckErrorTransient, $lastRequestApiErrors, 60);
|
||||
}
|
||||
}
|
||||
|
||||
wp_redirect(add_query_arg(
|
||||
array(
|
||||
'puc_update_check_result' => $status,
|
||||
'puc_slug' => $this->updateChecker->slug,
|
||||
),
|
||||
self_admin_url('plugins.php')
|
||||
));
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the results of a manual update check.
|
||||
*
|
||||
* @see self::handleManualCheck()
|
||||
*
|
||||
* You can change the result message by using the "puc_manual_check_message-$slug" filter.
|
||||
*/
|
||||
public function displayManualCheckResult() {
|
||||
if ( isset($_GET['puc_update_check_result'], $_GET['puc_slug']) && ($_GET['puc_slug'] == $this->updateChecker->slug) ) {
|
||||
$status = strval($_GET['puc_update_check_result']);
|
||||
$title = $this->updateChecker->getInstalledPackage()->getPluginTitle();
|
||||
$noticeClass = 'updated notice-success';
|
||||
$details = '';
|
||||
|
||||
if ( $status == 'no_update' ) {
|
||||
$message = sprintf(_x('The %s plugin is up to date.', 'the plugin title', 'plugin-update-checker'), $title);
|
||||
} else if ( $status == 'update_available' ) {
|
||||
$message = sprintf(_x('A new version of the %s plugin is available.', 'the plugin title', 'plugin-update-checker'), $title);
|
||||
} else if ( $status === 'error' ) {
|
||||
$message = sprintf(_x('Could not determine if updates are available for %s.', 'the plugin title', 'plugin-update-checker'), $title);
|
||||
$noticeClass = 'error notice-error';
|
||||
|
||||
$details = $this->formatManualCheckErrors(get_site_transient($this->manualCheckErrorTransient));
|
||||
delete_site_transient($this->manualCheckErrorTransient);
|
||||
} else {
|
||||
$message = sprintf(__('Unknown update checker status "%s"', 'plugin-update-checker'), htmlentities($status));
|
||||
$noticeClass = 'error notice-error';
|
||||
}
|
||||
printf(
|
||||
'<div class="notice %s is-dismissible"><p>%s</p>%s</div>',
|
||||
$noticeClass,
|
||||
apply_filters($this->updateChecker->getUniqueName('manual_check_message'), $message, $status),
|
||||
$details
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the list of errors that were thrown during an update check.
|
||||
*
|
||||
* @param array $errors
|
||||
* @return string
|
||||
*/
|
||||
protected function formatManualCheckErrors($errors) {
|
||||
if ( empty($errors) ) {
|
||||
return '';
|
||||
}
|
||||
$output = '';
|
||||
|
||||
$showAsList = count($errors) > 1;
|
||||
if ( $showAsList ) {
|
||||
$output .= '<ol>';
|
||||
$formatString = '<li>%1$s <code>%2$s</code></li>';
|
||||
} else {
|
||||
$formatString = '<p>%1$s <code>%2$s</code></p>';
|
||||
}
|
||||
foreach ($errors as $item) {
|
||||
$wpError = $item['error'];
|
||||
/** @var WP_Error $wpError */
|
||||
$output .= sprintf(
|
||||
$formatString,
|
||||
$wpError->get_error_message(),
|
||||
$wpError->get_error_code()
|
||||
);
|
||||
}
|
||||
if ( $showAsList ) {
|
||||
$output .= '</ol>';
|
||||
}
|
||||
|
||||
return $output;
|
||||
}
|
||||
|
||||
public function removeHooks() {
|
||||
remove_action('admin_init', array($this, 'onAdminInit'));
|
||||
remove_filter('plugin_row_meta', array($this, 'addViewDetailsLink'), 10);
|
||||
remove_filter('plugin_row_meta', array($this, 'addCheckForUpdatesLink'), 10);
|
||||
remove_action('all_admin_notices', array($this, 'displayManualCheckResult'));
|
||||
}
|
||||
}
|
||||
endif;
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
<?php
|
||||
if ( !class_exists('Puc_v4p11_Plugin_Update', false) ):
|
||||
|
||||
/**
|
||||
* A simple container class for holding information about an available update.
|
||||
*
|
||||
* @author Janis Elsts
|
||||
* @copyright 2016
|
||||
* @access public
|
||||
*/
|
||||
class Puc_v4p11_Plugin_Update extends Puc_v4p11_Update {
|
||||
public $id = 0;
|
||||
public $homepage;
|
||||
public $upgrade_notice;
|
||||
public $tested;
|
||||
public $requires_php = false;
|
||||
public $icons = array();
|
||||
public $filename; //Plugin filename relative to the plugins directory.
|
||||
|
||||
protected static $extraFields = array(
|
||||
'id', 'homepage', 'tested', 'requires_php', 'upgrade_notice', 'icons', 'filename',
|
||||
);
|
||||
|
||||
/**
|
||||
* Create a new instance of PluginUpdate from its JSON-encoded representation.
|
||||
*
|
||||
* @param string $json
|
||||
* @return Puc_v4p11_Plugin_Update|null
|
||||
*/
|
||||
public static function fromJson($json){
|
||||
//Since update-related information is simply a subset of the full plugin info,
|
||||
//we can parse the update JSON as if it was a plugin info string, then copy over
|
||||
//the parts that we care about.
|
||||
$pluginInfo = Puc_v4p11_Plugin_Info::fromJson($json);
|
||||
if ( $pluginInfo !== null ) {
|
||||
return self::fromPluginInfo($pluginInfo);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new instance of PluginUpdate based on an instance of PluginInfo.
|
||||
* Basically, this just copies a subset of fields from one object to another.
|
||||
*
|
||||
* @param Puc_v4p11_Plugin_Info $info
|
||||
* @return Puc_v4p11_Plugin_Update
|
||||
*/
|
||||
public static function fromPluginInfo($info){
|
||||
return self::fromObject($info);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new instance by copying the necessary fields from another object.
|
||||
*
|
||||
* @param StdClass|Puc_v4p11_Plugin_Info|Puc_v4p11_Plugin_Update $object The source object.
|
||||
* @return Puc_v4p11_Plugin_Update The new copy.
|
||||
*/
|
||||
public static function fromObject($object) {
|
||||
$update = new self();
|
||||
$update->copyFields($object, $update);
|
||||
return $update;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
protected function getFieldNames() {
|
||||
return array_merge(parent::getFieldNames(), self::$extraFields);
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform the update into the format used by WordPress native plugin API.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function toWpFormat() {
|
||||
$update = parent::toWpFormat();
|
||||
|
||||
$update->id = $this->id;
|
||||
$update->url = $this->homepage;
|
||||
$update->tested = $this->tested;
|
||||
$update->requires_php = $this->requires_php;
|
||||
$update->plugin = $this->filename;
|
||||
|
||||
if ( !empty($this->upgrade_notice) ) {
|
||||
$update->upgrade_notice = $this->upgrade_notice;
|
||||
}
|
||||
|
||||
if ( !empty($this->icons) && is_array($this->icons) ) {
|
||||
//This should be an array with up to 4 keys: 'svg', '1x', '2x' and 'default'.
|
||||
//Docs: https://developer.wordpress.org/plugins/wordpress-org/plugin-assets/#plugin-icons
|
||||
$icons = array_intersect_key(
|
||||
$this->icons,
|
||||
array('svg' => true, '1x' => true, '2x' => true, 'default' => true)
|
||||
);
|
||||
if ( !empty($icons) ) {
|
||||
$update->icons = $icons;
|
||||
|
||||
//It appears that the 'default' icon isn't used anywhere in WordPress 4.9,
|
||||
//but lets set it just in case a future release needs it.
|
||||
if ( !isset($update->icons['default']) ) {
|
||||
$update->icons['default'] = current($update->icons);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $update;
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
+414
@@ -0,0 +1,414 @@
|
||||
<?php
|
||||
if ( !class_exists('Puc_v4p11_Plugin_UpdateChecker', false) ):
|
||||
|
||||
/**
|
||||
* A custom plugin update checker.
|
||||
*
|
||||
* @author Janis Elsts
|
||||
* @copyright 2018
|
||||
* @access public
|
||||
*/
|
||||
class Puc_v4p11_Plugin_UpdateChecker extends Puc_v4p11_UpdateChecker {
|
||||
protected $updateTransient = 'update_plugins';
|
||||
protected $translationType = 'plugin';
|
||||
|
||||
public $pluginAbsolutePath = ''; //Full path of the main plugin file.
|
||||
public $pluginFile = ''; //Plugin filename relative to the plugins directory. Many WP APIs use this to identify plugins.
|
||||
public $muPluginFile = ''; //For MU plugins, the plugin filename relative to the mu-plugins directory.
|
||||
|
||||
/**
|
||||
* @var Puc_v4p11_Plugin_Package
|
||||
*/
|
||||
protected $package;
|
||||
|
||||
private $extraUi = null;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param string $metadataUrl The URL of the plugin's metadata file.
|
||||
* @param string $pluginFile Fully qualified path to the main plugin file.
|
||||
* @param string $slug The plugin's 'slug'. If not specified, the filename part of $pluginFile sans '.php' will be used as the slug.
|
||||
* @param integer $checkPeriod How often to check for updates (in hours). Defaults to checking every 12 hours. Set to 0 to disable automatic update checks.
|
||||
* @param string $optionName Where to store book-keeping info about update checks. Defaults to 'external_updates-$slug'.
|
||||
* @param string $muPluginFile Optional. The plugin filename relative to the mu-plugins directory.
|
||||
*/
|
||||
public function __construct($metadataUrl, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = ''){
|
||||
$this->pluginAbsolutePath = $pluginFile;
|
||||
$this->pluginFile = plugin_basename($this->pluginAbsolutePath);
|
||||
$this->muPluginFile = $muPluginFile;
|
||||
|
||||
//If no slug is specified, use the name of the main plugin file as the slug.
|
||||
//For example, 'my-cool-plugin/cool-plugin.php' becomes 'cool-plugin'.
|
||||
if ( empty($slug) ){
|
||||
$slug = basename($this->pluginFile, '.php');
|
||||
}
|
||||
|
||||
//Plugin slugs must be unique.
|
||||
$slugCheckFilter = 'puc_is_slug_in_use-' . $slug;
|
||||
$slugUsedBy = apply_filters($slugCheckFilter, false);
|
||||
if ( $slugUsedBy ) {
|
||||
$this->triggerError(sprintf(
|
||||
'Plugin slug "%s" is already in use by %s. Slugs must be unique.',
|
||||
htmlentities($slug),
|
||||
htmlentities($slugUsedBy)
|
||||
), E_USER_ERROR);
|
||||
}
|
||||
add_filter($slugCheckFilter, array($this, 'getAbsolutePath'));
|
||||
|
||||
parent::__construct($metadataUrl, dirname($this->pluginFile), $slug, $checkPeriod, $optionName);
|
||||
|
||||
//Backwards compatibility: If the plugin is a mu-plugin but no $muPluginFile is specified, assume
|
||||
//it's the same as $pluginFile given that it's not in a subdirectory (WP only looks in the base dir).
|
||||
if ( (strpbrk($this->pluginFile, '/\\') === false) && $this->isUnknownMuPlugin() ) {
|
||||
$this->muPluginFile = $this->pluginFile;
|
||||
}
|
||||
|
||||
//To prevent a crash during plugin uninstallation, remove updater hooks when the user removes the plugin.
|
||||
//Details: https://github.com/YahnisElsts/plugin-update-checker/issues/138#issuecomment-335590964
|
||||
add_action('uninstall_' . $this->pluginFile, array($this, 'removeHooks'));
|
||||
|
||||
$this->extraUi = new Puc_v4p11_Plugin_Ui($this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of the scheduler.
|
||||
*
|
||||
* @param int $checkPeriod
|
||||
* @return Puc_v4p11_Scheduler
|
||||
*/
|
||||
protected function createScheduler($checkPeriod) {
|
||||
$scheduler = new Puc_v4p11_Scheduler($this, $checkPeriod, array('load-plugins.php'));
|
||||
register_deactivation_hook($this->pluginFile, array($scheduler, 'removeUpdaterCron'));
|
||||
return $scheduler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Install the hooks required to run periodic update checks and inject update info
|
||||
* into WP data structures.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function installHooks(){
|
||||
//Override requests for plugin information
|
||||
add_filter('plugins_api', array($this, 'injectInfo'), 20, 3);
|
||||
|
||||
parent::installHooks();
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove update checker hooks.
|
||||
*
|
||||
* The intent is to prevent a fatal error that can happen if the plugin has an uninstall
|
||||
* hook. During uninstallation, WP includes the main plugin file (which creates a PUC instance),
|
||||
* the uninstall hook runs, WP deletes the plugin files and then updates some transients.
|
||||
* If PUC hooks are still around at this time, they could throw an error while trying to
|
||||
* autoload classes from files that no longer exist.
|
||||
*
|
||||
* The "site_transient_{$transient}" filter is the main problem here, but let's also remove
|
||||
* most other PUC hooks to be safe.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
public function removeHooks() {
|
||||
parent::removeHooks();
|
||||
$this->extraUi->removeHooks();
|
||||
$this->package->removeHooks();
|
||||
|
||||
remove_filter('plugins_api', array($this, 'injectInfo'), 20);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve plugin info from the configured API endpoint.
|
||||
*
|
||||
* @uses wp_remote_get()
|
||||
*
|
||||
* @param array $queryArgs Additional query arguments to append to the request. Optional.
|
||||
* @return Puc_v4p11_Plugin_Info
|
||||
*/
|
||||
public function requestInfo($queryArgs = array()) {
|
||||
list($pluginInfo, $result) = $this->requestMetadata('Puc_v4p11_Plugin_Info', 'request_info', $queryArgs);
|
||||
|
||||
if ( $pluginInfo !== null ) {
|
||||
/** @var Puc_v4p11_Plugin_Info $pluginInfo */
|
||||
$pluginInfo->filename = $this->pluginFile;
|
||||
$pluginInfo->slug = $this->slug;
|
||||
}
|
||||
|
||||
$pluginInfo = apply_filters($this->getUniqueName('request_info_result'), $pluginInfo, $result);
|
||||
return $pluginInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the latest update (if any) from the configured API endpoint.
|
||||
*
|
||||
* @uses PluginUpdateChecker::requestInfo()
|
||||
*
|
||||
* @return Puc_v4p11_Update|null An instance of Plugin_Update, or NULL when no updates are available.
|
||||
*/
|
||||
public function requestUpdate() {
|
||||
//For the sake of simplicity, this function just calls requestInfo()
|
||||
//and transforms the result accordingly.
|
||||
$pluginInfo = $this->requestInfo(array('checking_for_updates' => '1'));
|
||||
if ( $pluginInfo === null ){
|
||||
return null;
|
||||
}
|
||||
$update = Puc_v4p11_Plugin_Update::fromPluginInfo($pluginInfo);
|
||||
|
||||
$update = $this->filterUpdateResult($update);
|
||||
|
||||
return $update;
|
||||
}
|
||||
|
||||
/**
|
||||
* Intercept plugins_api() calls that request information about our plugin and
|
||||
* use the configured API endpoint to satisfy them.
|
||||
*
|
||||
* @see plugins_api()
|
||||
*
|
||||
* @param mixed $result
|
||||
* @param string $action
|
||||
* @param array|object $args
|
||||
* @return mixed
|
||||
*/
|
||||
public function injectInfo($result, $action = null, $args = null){
|
||||
$relevant = ($action == 'plugin_information') && isset($args->slug) && (
|
||||
($args->slug == $this->slug) || ($args->slug == dirname($this->pluginFile))
|
||||
);
|
||||
if ( !$relevant ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
$pluginInfo = $this->requestInfo();
|
||||
$this->fixSupportedWordpressVersion($pluginInfo);
|
||||
|
||||
$pluginInfo = apply_filters($this->getUniqueName('pre_inject_info'), $pluginInfo);
|
||||
if ( $pluginInfo ) {
|
||||
return $pluginInfo->toWpFormat();
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
protected function shouldShowUpdates() {
|
||||
//No update notifications for mu-plugins unless explicitly enabled. The MU plugin file
|
||||
//is usually different from the main plugin file so the update wouldn't show up properly anyway.
|
||||
return !$this->isUnknownMuPlugin();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param stdClass|null $updates
|
||||
* @param stdClass $updateToAdd
|
||||
* @return stdClass
|
||||
*/
|
||||
protected function addUpdateToList($updates, $updateToAdd) {
|
||||
if ( $this->package->isMuPlugin() ) {
|
||||
//WP does not support automatic update installation for mu-plugins, but we can
|
||||
//still display a notice.
|
||||
$updateToAdd->package = null;
|
||||
}
|
||||
return parent::addUpdateToList($updates, $updateToAdd);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param stdClass|null $updates
|
||||
* @return stdClass|null
|
||||
*/
|
||||
protected function removeUpdateFromList($updates) {
|
||||
$updates = parent::removeUpdateFromList($updates);
|
||||
if ( !empty($this->muPluginFile) && isset($updates, $updates->response) ) {
|
||||
unset($updates->response[$this->muPluginFile]);
|
||||
}
|
||||
return $updates;
|
||||
}
|
||||
|
||||
/**
|
||||
* For plugins, the update array is indexed by the plugin filename relative to the "plugins"
|
||||
* directory. Example: "plugin-name/plugin.php".
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getUpdateListKey() {
|
||||
if ( $this->package->isMuPlugin() ) {
|
||||
return $this->muPluginFile;
|
||||
}
|
||||
return $this->pluginFile;
|
||||
}
|
||||
|
||||
protected function getNoUpdateItemFields() {
|
||||
return array_merge(
|
||||
parent::getNoUpdateItemFields(),
|
||||
array(
|
||||
'id' => $this->pluginFile,
|
||||
'slug' => $this->slug,
|
||||
'plugin' => $this->pluginFile,
|
||||
'icons' => array(),
|
||||
'banners' => array(),
|
||||
'banners_rtl' => array(),
|
||||
'tested' => '',
|
||||
'compatibility' => new stdClass(),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Alias for isBeingUpgraded().
|
||||
*
|
||||
* @deprecated
|
||||
* @param WP_Upgrader|null $upgrader The upgrader that's performing the current update.
|
||||
* @return bool
|
||||
*/
|
||||
public function isPluginBeingUpgraded($upgrader = null) {
|
||||
return $this->isBeingUpgraded($upgrader);
|
||||
}
|
||||
|
||||
/**
|
||||
* Is there an update being installed for this plugin, right now?
|
||||
*
|
||||
* @param WP_Upgrader|null $upgrader
|
||||
* @return bool
|
||||
*/
|
||||
public function isBeingUpgraded($upgrader = null) {
|
||||
return $this->upgraderStatus->isPluginBeingUpgraded($this->pluginFile, $upgrader);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the details of the currently available update, if any.
|
||||
*
|
||||
* If no updates are available, or if the last known update version is below or equal
|
||||
* to the currently installed version, this method will return NULL.
|
||||
*
|
||||
* Uses cached update data. To retrieve update information straight from
|
||||
* the metadata URL, call requestUpdate() instead.
|
||||
*
|
||||
* @return Puc_v4p11_Plugin_Update|null
|
||||
*/
|
||||
public function getUpdate() {
|
||||
$update = parent::getUpdate();
|
||||
if ( isset($update) ) {
|
||||
/** @var Puc_v4p11_Plugin_Update $update */
|
||||
$update->filename = $this->pluginFile;
|
||||
}
|
||||
return $update;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the translated plugin title.
|
||||
*
|
||||
* @deprecated
|
||||
* @return string
|
||||
*/
|
||||
public function getPluginTitle() {
|
||||
return $this->package->getPluginTitle();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the current user has the required permissions to install updates.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function userCanInstallUpdates() {
|
||||
return current_user_can('update_plugins');
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the plugin file is inside the mu-plugins directory.
|
||||
*
|
||||
* @deprecated
|
||||
* @return bool
|
||||
*/
|
||||
protected function isMuPlugin() {
|
||||
return $this->package->isMuPlugin();
|
||||
}
|
||||
|
||||
/**
|
||||
* MU plugins are partially supported, but only when we know which file in mu-plugins
|
||||
* corresponds to this plugin.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function isUnknownMuPlugin() {
|
||||
return empty($this->muPluginFile) && $this->package->isMuPlugin();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get absolute path to the main plugin file.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getAbsolutePath() {
|
||||
return $this->pluginAbsolutePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a callback for filtering query arguments.
|
||||
*
|
||||
* The callback function should take one argument - an associative array of query arguments.
|
||||
* It should return a modified array of query arguments.
|
||||
*
|
||||
* @uses add_filter() This method is a convenience wrapper for add_filter().
|
||||
*
|
||||
* @param callable $callback
|
||||
* @return void
|
||||
*/
|
||||
public function addQueryArgFilter($callback){
|
||||
$this->addFilter('request_info_query_args', $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a callback for filtering arguments passed to wp_remote_get().
|
||||
*
|
||||
* The callback function should take one argument - an associative array of arguments -
|
||||
* and return a modified array or arguments. See the WP documentation on wp_remote_get()
|
||||
* for details on what arguments are available and how they work.
|
||||
*
|
||||
* @uses add_filter() This method is a convenience wrapper for add_filter().
|
||||
*
|
||||
* @param callable $callback
|
||||
* @return void
|
||||
*/
|
||||
public function addHttpRequestArgFilter($callback) {
|
||||
$this->addFilter('request_info_options', $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a callback for filtering the plugin info retrieved from the external API.
|
||||
*
|
||||
* The callback function should take two arguments. If the plugin info was retrieved
|
||||
* successfully, the first argument passed will be an instance of PluginInfo. Otherwise,
|
||||
* it will be NULL. The second argument will be the corresponding return value of
|
||||
* wp_remote_get (see WP docs for details).
|
||||
*
|
||||
* The callback function should return a new or modified instance of PluginInfo or NULL.
|
||||
*
|
||||
* @uses add_filter() This method is a convenience wrapper for add_filter().
|
||||
*
|
||||
* @param callable $callback
|
||||
* @return void
|
||||
*/
|
||||
public function addResultFilter($callback) {
|
||||
$this->addFilter('request_info_result', $callback, 10, 2);
|
||||
}
|
||||
|
||||
protected function createDebugBarExtension() {
|
||||
return new Puc_v4p11_DebugBar_PluginExtension($this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a package instance that represents this plugin or theme.
|
||||
*
|
||||
* @return Puc_v4p11_InstalledPackage
|
||||
*/
|
||||
protected function createInstalledPackage() {
|
||||
return new Puc_v4p11_Plugin_Package($this->pluginAbsolutePath, $this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Puc_v4p11_Plugin_Package
|
||||
*/
|
||||
public function getInstalledPackage() {
|
||||
return $this->package;
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
+266
@@ -0,0 +1,266 @@
|
||||
<?php
|
||||
if ( !class_exists('Puc_v4p11_Scheduler', false) ):
|
||||
|
||||
/**
|
||||
* The scheduler decides when and how often to check for updates.
|
||||
* It calls @see Puc_v4p11_UpdateChecker::checkForUpdates() to perform the actual checks.
|
||||
*/
|
||||
class Puc_v4p11_Scheduler {
|
||||
public $checkPeriod = 12; //How often to check for updates (in hours).
|
||||
public $throttleRedundantChecks = false; //Check less often if we already know that an update is available.
|
||||
public $throttledCheckPeriod = 72;
|
||||
|
||||
protected $hourlyCheckHooks = array('load-update.php');
|
||||
|
||||
/**
|
||||
* @var Puc_v4p11_UpdateChecker
|
||||
*/
|
||||
protected $updateChecker;
|
||||
|
||||
private $cronHook = null;
|
||||
|
||||
/**
|
||||
* Scheduler constructor.
|
||||
*
|
||||
* @param Puc_v4p11_UpdateChecker $updateChecker
|
||||
* @param int $checkPeriod How often to check for updates (in hours).
|
||||
* @param array $hourlyHooks
|
||||
*/
|
||||
public function __construct($updateChecker, $checkPeriod, $hourlyHooks = array('load-plugins.php')) {
|
||||
$this->updateChecker = $updateChecker;
|
||||
$this->checkPeriod = $checkPeriod;
|
||||
|
||||
//Set up the periodic update checks
|
||||
$this->cronHook = $this->updateChecker->getUniqueName('cron_check_updates');
|
||||
if ( $this->checkPeriod > 0 ){
|
||||
|
||||
//Trigger the check via Cron.
|
||||
//Try to use one of the default schedules if possible as it's less likely to conflict
|
||||
//with other plugins and their custom schedules.
|
||||
$defaultSchedules = array(
|
||||
1 => 'hourly',
|
||||
12 => 'twicedaily',
|
||||
24 => 'daily',
|
||||
);
|
||||
if ( array_key_exists($this->checkPeriod, $defaultSchedules) ) {
|
||||
$scheduleName = $defaultSchedules[$this->checkPeriod];
|
||||
} else {
|
||||
//Use a custom cron schedule.
|
||||
$scheduleName = 'every' . $this->checkPeriod . 'hours';
|
||||
add_filter('cron_schedules', array($this, '_addCustomSchedule'));
|
||||
}
|
||||
|
||||
if ( !wp_next_scheduled($this->cronHook) && !defined('WP_INSTALLING') ) {
|
||||
//Randomly offset the schedule to help prevent update server traffic spikes. Without this
|
||||
//most checks may happen during times of day when people are most likely to install new plugins.
|
||||
$firstCheckTime = time() - rand(0, max($this->checkPeriod * 3600 - 15 * 60, 1));
|
||||
$firstCheckTime = apply_filters(
|
||||
$this->updateChecker->getUniqueName('first_check_time'),
|
||||
$firstCheckTime
|
||||
);
|
||||
wp_schedule_event($firstCheckTime, $scheduleName, $this->cronHook);
|
||||
}
|
||||
add_action($this->cronHook, array($this, 'maybeCheckForUpdates'));
|
||||
|
||||
//In case Cron is disabled or unreliable, we also manually trigger
|
||||
//the periodic checks while the user is browsing the Dashboard.
|
||||
add_action( 'admin_init', array($this, 'maybeCheckForUpdates') );
|
||||
|
||||
//Like WordPress itself, we check more often on certain pages.
|
||||
/** @see wp_update_plugins */
|
||||
add_action('load-update-core.php', array($this, 'maybeCheckForUpdates'));
|
||||
//"load-update.php" and "load-plugins.php" or "load-themes.php".
|
||||
$this->hourlyCheckHooks = array_merge($this->hourlyCheckHooks, $hourlyHooks);
|
||||
foreach($this->hourlyCheckHooks as $hook) {
|
||||
add_action($hook, array($this, 'maybeCheckForUpdates'));
|
||||
}
|
||||
//This hook fires after a bulk update is complete.
|
||||
add_action('upgrader_process_complete', array($this, 'upgraderProcessComplete'), 11, 2);
|
||||
|
||||
} else {
|
||||
//Periodic checks are disabled.
|
||||
wp_clear_scheduled_hook($this->cronHook);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs upon the WP action upgrader_process_complete.
|
||||
*
|
||||
* We look at the parameters to decide whether to call maybeCheckForUpdates() or not.
|
||||
* We also check if the update checker has been removed by the update.
|
||||
*
|
||||
* @param WP_Upgrader $upgrader WP_Upgrader instance
|
||||
* @param array $upgradeInfo extra information about the upgrade
|
||||
*/
|
||||
public function upgraderProcessComplete(
|
||||
/** @noinspection PhpUnusedParameterInspection */
|
||||
$upgrader, $upgradeInfo
|
||||
) {
|
||||
//Cancel all further actions if the current version of PUC has been deleted or overwritten
|
||||
//by a different version during the upgrade. If we try to do anything more in that situation,
|
||||
//we could trigger a fatal error by trying to autoload a deleted class.
|
||||
clearstatcache();
|
||||
if ( !file_exists(__FILE__) ) {
|
||||
$this->removeHooks();
|
||||
$this->updateChecker->removeHooks();
|
||||
return;
|
||||
}
|
||||
|
||||
//Sanity check and limitation to relevant types.
|
||||
if (
|
||||
!is_array($upgradeInfo) || !isset($upgradeInfo['type'], $upgradeInfo['action'])
|
||||
|| 'update' !== $upgradeInfo['action'] || !in_array($upgradeInfo['type'], array('plugin', 'theme'))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
//Filter out notifications of upgrades that should have no bearing upon whether or not our
|
||||
//current info is up-to-date.
|
||||
if ( is_a($this->updateChecker, 'Puc_v4p11_Theme_UpdateChecker') ) {
|
||||
if ( 'theme' !== $upgradeInfo['type'] || !isset($upgradeInfo['themes']) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
//Letting too many things going through for checks is not a real problem, so we compare widely.
|
||||
if ( !in_array(
|
||||
strtolower($this->updateChecker->directoryName),
|
||||
array_map('strtolower', $upgradeInfo['themes'])
|
||||
) ) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if ( is_a($this->updateChecker, 'Puc_v4p11_Plugin_UpdateChecker') ) {
|
||||
if ( 'plugin' !== $upgradeInfo['type'] || !isset($upgradeInfo['plugins']) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
//Themes pass in directory names in the information array, but plugins use the relative plugin path.
|
||||
if ( !in_array(
|
||||
strtolower($this->updateChecker->directoryName),
|
||||
array_map('dirname', array_map('strtolower', $upgradeInfo['plugins']))
|
||||
) ) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
$this->maybeCheckForUpdates();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for updates if the configured check interval has already elapsed.
|
||||
* Will use a shorter check interval on certain admin pages like "Dashboard -> Updates" or when doing cron.
|
||||
*
|
||||
* You can override the default behaviour by using the "puc_check_now-$slug" filter.
|
||||
* The filter callback will be passed three parameters:
|
||||
* - Current decision. TRUE = check updates now, FALSE = don't check now.
|
||||
* - Last check time as a Unix timestamp.
|
||||
* - Configured check period in hours.
|
||||
* Return TRUE to check for updates immediately, or FALSE to cancel.
|
||||
*
|
||||
* This method is declared public because it's a hook callback. Calling it directly is not recommended.
|
||||
*/
|
||||
public function maybeCheckForUpdates() {
|
||||
if ( empty($this->checkPeriod) ){
|
||||
return;
|
||||
}
|
||||
|
||||
$state = $this->updateChecker->getUpdateState();
|
||||
$shouldCheck = ($state->timeSinceLastCheck() >= $this->getEffectiveCheckPeriod());
|
||||
|
||||
//Let plugin authors substitute their own algorithm.
|
||||
$shouldCheck = apply_filters(
|
||||
$this->updateChecker->getUniqueName('check_now'),
|
||||
$shouldCheck,
|
||||
$state->getLastCheck(),
|
||||
$this->checkPeriod
|
||||
);
|
||||
|
||||
if ( $shouldCheck ) {
|
||||
$this->updateChecker->checkForUpdates();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the actual check period based on the current status and environment.
|
||||
*
|
||||
* @return int Check period in seconds.
|
||||
*/
|
||||
protected function getEffectiveCheckPeriod() {
|
||||
$currentFilter = current_filter();
|
||||
if ( in_array($currentFilter, array('load-update-core.php', 'upgrader_process_complete')) ) {
|
||||
//Check more often when the user visits "Dashboard -> Updates" or does a bulk update.
|
||||
$period = 60;
|
||||
} else if ( in_array($currentFilter, $this->hourlyCheckHooks) ) {
|
||||
//Also check more often on /wp-admin/update.php and the "Plugins" or "Themes" page.
|
||||
$period = 3600;
|
||||
} else if ( $this->throttleRedundantChecks && ($this->updateChecker->getUpdate() !== null) ) {
|
||||
//Check less frequently if it's already known that an update is available.
|
||||
$period = $this->throttledCheckPeriod * 3600;
|
||||
} else if ( defined('DOING_CRON') && constant('DOING_CRON') ) {
|
||||
//WordPress cron schedules are not exact, so lets do an update check even
|
||||
//if slightly less than $checkPeriod hours have elapsed since the last check.
|
||||
$cronFuzziness = 20 * 60;
|
||||
$period = $this->checkPeriod * 3600 - $cronFuzziness;
|
||||
} else {
|
||||
$period = $this->checkPeriod * 3600;
|
||||
}
|
||||
|
||||
return $period;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add our custom schedule to the array of Cron schedules used by WP.
|
||||
*
|
||||
* @param array $schedules
|
||||
* @return array
|
||||
*/
|
||||
public function _addCustomSchedule($schedules) {
|
||||
if ( $this->checkPeriod && ($this->checkPeriod > 0) ){
|
||||
$scheduleName = 'every' . $this->checkPeriod . 'hours';
|
||||
$schedules[$scheduleName] = array(
|
||||
'interval' => $this->checkPeriod * 3600,
|
||||
'display' => sprintf('Every %d hours', $this->checkPeriod),
|
||||
);
|
||||
}
|
||||
return $schedules;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the scheduled cron event that the library uses to check for updates.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function removeUpdaterCron() {
|
||||
wp_clear_scheduled_hook($this->cronHook);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the name of the update checker's WP-cron hook. Mostly useful for debugging.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getCronHookName() {
|
||||
return $this->cronHook;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove most hooks added by the scheduler.
|
||||
*/
|
||||
public function removeHooks() {
|
||||
remove_filter('cron_schedules', array($this, '_addCustomSchedule'));
|
||||
remove_action('admin_init', array($this, 'maybeCheckForUpdates'));
|
||||
remove_action('load-update-core.php', array($this, 'maybeCheckForUpdates'));
|
||||
|
||||
if ( $this->cronHook !== null ) {
|
||||
remove_action($this->cronHook, array($this, 'maybeCheckForUpdates'));
|
||||
}
|
||||
if ( !empty($this->hourlyCheckHooks) ) {
|
||||
foreach ($this->hourlyCheckHooks as $hook) {
|
||||
remove_action($hook, array($this, 'maybeCheckForUpdates'));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
<?php
|
||||
|
||||
if ( !class_exists('Puc_v4p11_StateStore', false) ):
|
||||
|
||||
class Puc_v4p11_StateStore {
|
||||
/**
|
||||
* @var int Last update check timestamp.
|
||||
*/
|
||||
protected $lastCheck = 0;
|
||||
|
||||
/**
|
||||
* @var string Version number.
|
||||
*/
|
||||
protected $checkedVersion = '';
|
||||
|
||||
/**
|
||||
* @var Puc_v4p11_Update|null Cached update.
|
||||
*/
|
||||
protected $update = null;
|
||||
|
||||
/**
|
||||
* @var string Site option name.
|
||||
*/
|
||||
private $optionName = '';
|
||||
|
||||
/**
|
||||
* @var bool Whether we've already tried to load the state from the database.
|
||||
*/
|
||||
private $isLoaded = false;
|
||||
|
||||
public function __construct($optionName) {
|
||||
$this->optionName = $optionName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get time elapsed since the last update check.
|
||||
*
|
||||
* If there are no recorded update checks, this method returns a large arbitrary number
|
||||
* (i.e. time since the Unix epoch).
|
||||
*
|
||||
* @return int Elapsed time in seconds.
|
||||
*/
|
||||
public function timeSinceLastCheck() {
|
||||
$this->lazyLoad();
|
||||
return time() - $this->lastCheck;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
public function getLastCheck() {
|
||||
$this->lazyLoad();
|
||||
return $this->lastCheck;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the time of the last update check to the current timestamp.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function setLastCheckToNow() {
|
||||
$this->lazyLoad();
|
||||
$this->lastCheck = time();
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return null|Puc_v4p11_Update
|
||||
*/
|
||||
public function getUpdate() {
|
||||
$this->lazyLoad();
|
||||
return $this->update;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Puc_v4p11_Update|null $update
|
||||
* @return $this
|
||||
*/
|
||||
public function setUpdate($update = null) {
|
||||
$this->lazyLoad();
|
||||
$this->update = $update;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getCheckedVersion() {
|
||||
$this->lazyLoad();
|
||||
return $this->checkedVersion;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $version
|
||||
* @return $this
|
||||
*/
|
||||
public function setCheckedVersion($version) {
|
||||
$this->lazyLoad();
|
||||
$this->checkedVersion = strval($version);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get translation updates.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getTranslations() {
|
||||
$this->lazyLoad();
|
||||
if ( isset($this->update, $this->update->translations) ) {
|
||||
return $this->update->translations;
|
||||
}
|
||||
return array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set translation updates.
|
||||
*
|
||||
* @param array $translationUpdates
|
||||
*/
|
||||
public function setTranslations($translationUpdates) {
|
||||
$this->lazyLoad();
|
||||
if ( isset($this->update) ) {
|
||||
$this->update->translations = $translationUpdates;
|
||||
$this->save();
|
||||
}
|
||||
}
|
||||
|
||||
public function save() {
|
||||
$state = new stdClass();
|
||||
|
||||
$state->lastCheck = $this->lastCheck;
|
||||
$state->checkedVersion = $this->checkedVersion;
|
||||
|
||||
if ( isset($this->update)) {
|
||||
$state->update = $this->update->toStdClass();
|
||||
|
||||
$updateClass = get_class($this->update);
|
||||
$state->updateClass = $updateClass;
|
||||
$prefix = $this->getLibPrefix();
|
||||
if ( Puc_v4p11_Utils::startsWith($updateClass, $prefix) ) {
|
||||
$state->updateBaseClass = substr($updateClass, strlen($prefix));
|
||||
}
|
||||
}
|
||||
|
||||
update_site_option($this->optionName, $state);
|
||||
$this->isLoaded = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
public function lazyLoad() {
|
||||
if ( !$this->isLoaded ) {
|
||||
$this->load();
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
protected function load() {
|
||||
$this->isLoaded = true;
|
||||
|
||||
$state = get_site_option($this->optionName, null);
|
||||
|
||||
if ( !is_object($state) ) {
|
||||
$this->lastCheck = 0;
|
||||
$this->checkedVersion = '';
|
||||
$this->update = null;
|
||||
return;
|
||||
}
|
||||
|
||||
$this->lastCheck = intval(Puc_v4p11_Utils::get($state, 'lastCheck', 0));
|
||||
$this->checkedVersion = Puc_v4p11_Utils::get($state, 'checkedVersion', '');
|
||||
$this->update = null;
|
||||
|
||||
if ( isset($state->update) ) {
|
||||
//This mess is due to the fact that the want the update class from this version
|
||||
//of the library, not the version that saved the update.
|
||||
|
||||
$updateClass = null;
|
||||
if ( isset($state->updateBaseClass) ) {
|
||||
$updateClass = $this->getLibPrefix() . $state->updateBaseClass;
|
||||
} else if ( isset($state->updateClass) && class_exists($state->updateClass) ) {
|
||||
$updateClass = $state->updateClass;
|
||||
}
|
||||
|
||||
if ( $updateClass !== null ) {
|
||||
$this->update = call_user_func(array($updateClass, 'fromObject'), $state->update);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function delete() {
|
||||
delete_site_option($this->optionName);
|
||||
|
||||
$this->lastCheck = 0;
|
||||
$this->checkedVersion = '';
|
||||
$this->update = null;
|
||||
}
|
||||
|
||||
private function getLibPrefix() {
|
||||
$parts = explode('_', __CLASS__, 3);
|
||||
return $parts[0] . '_' . $parts[1] . '_';
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
if ( !class_exists('Puc_v4p11_Theme_Package', false) ):
|
||||
|
||||
class Puc_v4p11_Theme_Package extends Puc_v4p11_InstalledPackage {
|
||||
/**
|
||||
* @var string Theme directory name.
|
||||
*/
|
||||
protected $stylesheet;
|
||||
|
||||
/**
|
||||
* @var WP_Theme Theme object.
|
||||
*/
|
||||
protected $theme;
|
||||
|
||||
public function __construct($stylesheet, $updateChecker) {
|
||||
$this->stylesheet = $stylesheet;
|
||||
$this->theme = wp_get_theme($this->stylesheet);
|
||||
|
||||
parent::__construct($updateChecker);
|
||||
}
|
||||
|
||||
public function getInstalledVersion() {
|
||||
return $this->theme->get('Version');
|
||||
}
|
||||
|
||||
public function getAbsoluteDirectoryPath() {
|
||||
if ( method_exists($this->theme, 'get_stylesheet_directory') ) {
|
||||
return $this->theme->get_stylesheet_directory(); //Available since WP 3.4.
|
||||
}
|
||||
return get_theme_root($this->stylesheet) . '/' . $this->stylesheet;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the value of a specific plugin or theme header.
|
||||
*
|
||||
* @param string $headerName
|
||||
* @param string $defaultValue
|
||||
* @return string Either the value of the header, or $defaultValue if the header doesn't exist or is empty.
|
||||
*/
|
||||
public function getHeaderValue($headerName, $defaultValue = '') {
|
||||
$value = $this->theme->get($headerName);
|
||||
if ( ($headerName === false) || ($headerName === '') ) {
|
||||
return $defaultValue;
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
protected function getHeaderNames() {
|
||||
return array(
|
||||
'Name' => 'Theme Name',
|
||||
'ThemeURI' => 'Theme URI',
|
||||
'Description' => 'Description',
|
||||
'Author' => 'Author',
|
||||
'AuthorURI' => 'Author URI',
|
||||
'Version' => 'Version',
|
||||
'Template' => 'Template',
|
||||
'Status' => 'Status',
|
||||
'Tags' => 'Tags',
|
||||
'TextDomain' => 'Text Domain',
|
||||
'DomainPath' => 'Domain Path',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
if ( !class_exists('Puc_v4p11_Theme_Update', false) ):
|
||||
|
||||
class Puc_v4p11_Theme_Update extends Puc_v4p11_Update {
|
||||
public $details_url = '';
|
||||
|
||||
protected static $extraFields = array('details_url');
|
||||
|
||||
/**
|
||||
* Transform the metadata into the format used by WordPress core.
|
||||
* Note the inconsistency: WP stores plugin updates as objects and theme updates as arrays.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function toWpFormat() {
|
||||
$update = array(
|
||||
'theme' => $this->slug,
|
||||
'new_version' => $this->version,
|
||||
'url' => $this->details_url,
|
||||
);
|
||||
|
||||
if ( !empty($this->download_url) ) {
|
||||
$update['package'] = $this->download_url;
|
||||
}
|
||||
|
||||
return $update;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new instance of Theme_Update from its JSON-encoded representation.
|
||||
*
|
||||
* @param string $json Valid JSON string representing a theme information object.
|
||||
* @return self New instance of ThemeUpdate, or NULL on error.
|
||||
*/
|
||||
public static function fromJson($json) {
|
||||
$instance = new self();
|
||||
if ( !parent::createFromJson($json, $instance) ) {
|
||||
return null;
|
||||
}
|
||||
return $instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new instance by copying the necessary fields from another object.
|
||||
*
|
||||
* @param StdClass|Puc_v4p11_Theme_Update $object The source object.
|
||||
* @return Puc_v4p11_Theme_Update The new copy.
|
||||
*/
|
||||
public static function fromObject($object) {
|
||||
$update = new self();
|
||||
$update->copyFields($object, $update);
|
||||
return $update;
|
||||
}
|
||||
|
||||
/**
|
||||
* Basic validation.
|
||||
*
|
||||
* @param StdClass $apiResponse
|
||||
* @return bool|WP_Error
|
||||
*/
|
||||
protected function validateMetadata($apiResponse) {
|
||||
$required = array('version', 'details_url');
|
||||
foreach($required as $key) {
|
||||
if ( !isset($apiResponse->$key) || empty($apiResponse->$key) ) {
|
||||
return new WP_Error(
|
||||
'tuc-invalid-metadata',
|
||||
sprintf('The theme metadata is missing the required "%s" key.', $key)
|
||||
);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function getFieldNames() {
|
||||
return array_merge(parent::getFieldNames(), self::$extraFields);
|
||||
}
|
||||
|
||||
protected function getPrefixedFilter($tag) {
|
||||
return parent::getPrefixedFilter($tag) . '_theme';
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
<?php
|
||||
|
||||
if ( !class_exists('Puc_v4p11_Theme_UpdateChecker', false) ):
|
||||
|
||||
class Puc_v4p11_Theme_UpdateChecker extends Puc_v4p11_UpdateChecker {
|
||||
protected $filterSuffix = 'theme';
|
||||
protected $updateTransient = 'update_themes';
|
||||
protected $translationType = 'theme';
|
||||
|
||||
/**
|
||||
* @var string Theme directory name.
|
||||
*/
|
||||
protected $stylesheet;
|
||||
|
||||
public function __construct($metadataUrl, $stylesheet = null, $customSlug = null, $checkPeriod = 12, $optionName = '') {
|
||||
if ( $stylesheet === null ) {
|
||||
$stylesheet = get_stylesheet();
|
||||
}
|
||||
$this->stylesheet = $stylesheet;
|
||||
|
||||
parent::__construct(
|
||||
$metadataUrl,
|
||||
$stylesheet,
|
||||
$customSlug ? $customSlug : $stylesheet,
|
||||
$checkPeriod,
|
||||
$optionName
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* For themes, the update array is indexed by theme directory name.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getUpdateListKey() {
|
||||
return $this->directoryName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the latest update (if any) from the configured API endpoint.
|
||||
*
|
||||
* @return Puc_v4p11_Update|null An instance of Update, or NULL when no updates are available.
|
||||
*/
|
||||
public function requestUpdate() {
|
||||
list($themeUpdate, $result) = $this->requestMetadata('Puc_v4p11_Theme_Update', 'request_update');
|
||||
|
||||
if ( $themeUpdate !== null ) {
|
||||
/** @var Puc_v4p11_Theme_Update $themeUpdate */
|
||||
$themeUpdate->slug = $this->slug;
|
||||
}
|
||||
|
||||
$themeUpdate = $this->filterUpdateResult($themeUpdate, $result);
|
||||
return $themeUpdate;
|
||||
}
|
||||
|
||||
protected function getNoUpdateItemFields() {
|
||||
return array_merge(
|
||||
parent::getNoUpdateItemFields(),
|
||||
array(
|
||||
'theme' => $this->directoryName,
|
||||
'requires' => '',
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public function userCanInstallUpdates() {
|
||||
return current_user_can('update_themes');
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of the scheduler.
|
||||
*
|
||||
* @param int $checkPeriod
|
||||
* @return Puc_v4p11_Scheduler
|
||||
*/
|
||||
protected function createScheduler($checkPeriod) {
|
||||
return new Puc_v4p11_Scheduler($this, $checkPeriod, array('load-themes.php'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Is there an update being installed right now for this theme?
|
||||
*
|
||||
* @param WP_Upgrader|null $upgrader The upgrader that's performing the current update.
|
||||
* @return bool
|
||||
*/
|
||||
public function isBeingUpgraded($upgrader = null) {
|
||||
return $this->upgraderStatus->isThemeBeingUpgraded($this->stylesheet, $upgrader);
|
||||
}
|
||||
|
||||
protected function createDebugBarExtension() {
|
||||
return new Puc_v4p11_DebugBar_Extension($this, 'Puc_v4p11_DebugBar_ThemePanel');
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a callback for filtering query arguments.
|
||||
*
|
||||
* The callback function should take one argument - an associative array of query arguments.
|
||||
* It should return a modified array of query arguments.
|
||||
*
|
||||
* @param callable $callback
|
||||
* @return void
|
||||
*/
|
||||
public function addQueryArgFilter($callback){
|
||||
$this->addFilter('request_update_query_args', $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a callback for filtering arguments passed to wp_remote_get().
|
||||
*
|
||||
* The callback function should take one argument - an associative array of arguments -
|
||||
* and return a modified array or arguments. See the WP documentation on wp_remote_get()
|
||||
* for details on what arguments are available and how they work.
|
||||
*
|
||||
* @uses add_filter() This method is a convenience wrapper for add_filter().
|
||||
*
|
||||
* @param callable $callback
|
||||
* @return void
|
||||
*/
|
||||
public function addHttpRequestArgFilter($callback) {
|
||||
$this->addFilter('request_update_options', $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a callback for filtering theme updates retrieved from the external API.
|
||||
*
|
||||
* The callback function should take two arguments. If the theme update was retrieved
|
||||
* successfully, the first argument passed will be an instance of Theme_Update. Otherwise,
|
||||
* it will be NULL. The second argument will be the corresponding return value of
|
||||
* wp_remote_get (see WP docs for details).
|
||||
*
|
||||
* The callback function should return a new or modified instance of Theme_Update or NULL.
|
||||
*
|
||||
* @uses add_filter() This method is a convenience wrapper for add_filter().
|
||||
*
|
||||
* @param callable $callback
|
||||
* @return void
|
||||
*/
|
||||
public function addResultFilter($callback) {
|
||||
$this->addFilter('request_update_result', $callback, 10, 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a package instance that represents this plugin or theme.
|
||||
*
|
||||
* @return Puc_v4p11_InstalledPackage
|
||||
*/
|
||||
protected function createInstalledPackage() {
|
||||
return new Puc_v4p11_Theme_Package($this->stylesheet, $this);
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
Vendored
+34
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
if ( !class_exists('Puc_v4p11_Update', false) ):
|
||||
|
||||
/**
|
||||
* A simple container class for holding information about an available update.
|
||||
*
|
||||
* @author Janis Elsts
|
||||
* @access public
|
||||
*/
|
||||
abstract class Puc_v4p11_Update extends Puc_v4p11_Metadata {
|
||||
public $slug;
|
||||
public $version;
|
||||
public $download_url;
|
||||
public $translations = array();
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
protected function getFieldNames() {
|
||||
return array('slug', 'version', 'download_url', 'translations');
|
||||
}
|
||||
|
||||
public function toWpFormat() {
|
||||
$update = new stdClass();
|
||||
|
||||
$update->slug = $this->slug;
|
||||
$update->new_version = $this->version;
|
||||
$update->package = $this->download_url;
|
||||
|
||||
return $update;
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
+997
@@ -0,0 +1,997 @@
|
||||
<?php
|
||||
|
||||
if ( !class_exists('Puc_v4p11_UpdateChecker', false) ):
|
||||
|
||||
abstract class Puc_v4p11_UpdateChecker {
|
||||
protected $filterSuffix = '';
|
||||
protected $updateTransient = '';
|
||||
protected $translationType = ''; //"plugin" or "theme".
|
||||
|
||||
/**
|
||||
* Set to TRUE to enable error reporting. Errors are raised using trigger_error()
|
||||
* and should be logged to the standard PHP error log.
|
||||
* @var bool
|
||||
*/
|
||||
public $debugMode = null;
|
||||
|
||||
/**
|
||||
* @var string Where to store the update info.
|
||||
*/
|
||||
public $optionName = '';
|
||||
|
||||
/**
|
||||
* @var string The URL of the metadata file.
|
||||
*/
|
||||
public $metadataUrl = '';
|
||||
|
||||
/**
|
||||
* @var string Plugin or theme directory name.
|
||||
*/
|
||||
public $directoryName = '';
|
||||
|
||||
/**
|
||||
* @var string The slug that will be used in update checker hooks and remote API requests.
|
||||
* Usually matches the directory name unless the plugin/theme directory has been renamed.
|
||||
*/
|
||||
public $slug = '';
|
||||
|
||||
/**
|
||||
* @var Puc_v4p11_InstalledPackage
|
||||
*/
|
||||
protected $package;
|
||||
|
||||
/**
|
||||
* @var Puc_v4p11_Scheduler
|
||||
*/
|
||||
public $scheduler;
|
||||
|
||||
/**
|
||||
* @var Puc_v4p11_UpgraderStatus
|
||||
*/
|
||||
protected $upgraderStatus;
|
||||
|
||||
/**
|
||||
* @var Puc_v4p11_StateStore
|
||||
*/
|
||||
protected $updateState;
|
||||
|
||||
/**
|
||||
* @var array List of API errors triggered during the last checkForUpdates() call.
|
||||
*/
|
||||
protected $lastRequestApiErrors = array();
|
||||
|
||||
/**
|
||||
* @var string|mixed The default is 0 because parse_url() can return NULL or FALSE.
|
||||
*/
|
||||
protected $cachedMetadataHost = 0;
|
||||
|
||||
/**
|
||||
* @var Puc_v4p11_DebugBar_Extension|null
|
||||
*/
|
||||
protected $debugBarExtension = null;
|
||||
|
||||
public function __construct($metadataUrl, $directoryName, $slug = null, $checkPeriod = 12, $optionName = '') {
|
||||
$this->debugMode = (bool)(constant('WP_DEBUG'));
|
||||
$this->metadataUrl = $metadataUrl;
|
||||
$this->directoryName = $directoryName;
|
||||
$this->slug = !empty($slug) ? $slug : $this->directoryName;
|
||||
|
||||
$this->optionName = $optionName;
|
||||
if ( empty($this->optionName) ) {
|
||||
//BC: Initially the library only supported plugin updates and didn't use type prefixes
|
||||
//in the option name. Lets use the same prefix-less name when possible.
|
||||
if ( $this->filterSuffix === '' ) {
|
||||
$this->optionName = 'external_updates-' . $this->slug;
|
||||
} else {
|
||||
$this->optionName = $this->getUniqueName('external_updates');
|
||||
}
|
||||
}
|
||||
|
||||
$this->package = $this->createInstalledPackage();
|
||||
$this->scheduler = $this->createScheduler($checkPeriod);
|
||||
$this->upgraderStatus = new Puc_v4p11_UpgraderStatus();
|
||||
$this->updateState = new Puc_v4p11_StateStore($this->optionName);
|
||||
|
||||
if ( did_action('init') ) {
|
||||
$this->loadTextDomain();
|
||||
} else {
|
||||
add_action('init', array($this, 'loadTextDomain'));
|
||||
}
|
||||
|
||||
$this->installHooks();
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
public function loadTextDomain() {
|
||||
//We're not using load_plugin_textdomain() or its siblings because figuring out where
|
||||
//the library is located (plugin, mu-plugin, theme, custom wp-content paths) is messy.
|
||||
$domain = 'plugin-update-checker';
|
||||
$locale = apply_filters(
|
||||
'plugin_locale',
|
||||
(is_admin() && function_exists('get_user_locale')) ? get_user_locale() : get_locale(),
|
||||
$domain
|
||||
);
|
||||
|
||||
$moFile = $domain . '-' . $locale . '.mo';
|
||||
$path = realpath(dirname(__FILE__) . '/../../languages');
|
||||
|
||||
if ($path && file_exists($path)) {
|
||||
load_textdomain($domain, $path . '/' . $moFile);
|
||||
}
|
||||
}
|
||||
|
||||
protected function installHooks() {
|
||||
//Insert our update info into the update array maintained by WP.
|
||||
add_filter('site_transient_' . $this->updateTransient, array($this,'injectUpdate'));
|
||||
|
||||
//Insert translation updates into the update list.
|
||||
add_filter('site_transient_' . $this->updateTransient, array($this, 'injectTranslationUpdates'));
|
||||
|
||||
//Clear translation updates when WP clears the update cache.
|
||||
//This needs to be done directly because the library doesn't actually remove obsolete plugin updates,
|
||||
//it just hides them (see getUpdate()). We can't do that with translations - too much disk I/O.
|
||||
add_action(
|
||||
'delete_site_transient_' . $this->updateTransient,
|
||||
array($this, 'clearCachedTranslationUpdates')
|
||||
);
|
||||
|
||||
//Rename the update directory to be the same as the existing directory.
|
||||
if ( $this->directoryName !== '.' ) {
|
||||
add_filter('upgrader_source_selection', array($this, 'fixDirectoryName'), 10, 3);
|
||||
}
|
||||
|
||||
//Allow HTTP requests to the metadata URL even if it's on a local host.
|
||||
add_filter('http_request_host_is_external', array($this, 'allowMetadataHost'), 10, 2);
|
||||
|
||||
//DebugBar integration.
|
||||
if ( did_action('plugins_loaded') ) {
|
||||
$this->maybeInitDebugBar();
|
||||
} else {
|
||||
add_action('plugins_loaded', array($this, 'maybeInitDebugBar'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove hooks that were added by this update checker instance.
|
||||
*/
|
||||
public function removeHooks() {
|
||||
remove_filter('site_transient_' . $this->updateTransient, array($this,'injectUpdate'));
|
||||
remove_filter('site_transient_' . $this->updateTransient, array($this, 'injectTranslationUpdates'));
|
||||
remove_action(
|
||||
'delete_site_transient_' . $this->updateTransient,
|
||||
array($this, 'clearCachedTranslationUpdates')
|
||||
);
|
||||
|
||||
remove_filter('upgrader_source_selection', array($this, 'fixDirectoryName'), 10);
|
||||
remove_filter('http_request_host_is_external', array($this, 'allowMetadataHost'), 10);
|
||||
remove_action('plugins_loaded', array($this, 'maybeInitDebugBar'));
|
||||
|
||||
remove_action('init', array($this, 'loadTextDomain'));
|
||||
|
||||
if ( $this->scheduler ) {
|
||||
$this->scheduler->removeHooks();
|
||||
}
|
||||
|
||||
if ( $this->debugBarExtension ) {
|
||||
$this->debugBarExtension->removeHooks();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the current user has the required permissions to install updates.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
abstract public function userCanInstallUpdates();
|
||||
|
||||
/**
|
||||
* Explicitly allow HTTP requests to the metadata URL.
|
||||
*
|
||||
* WordPress has a security feature where the HTTP API will reject all requests that are sent to
|
||||
* another site hosted on the same server as the current site (IP match), a local host, or a local
|
||||
* IP, unless the host exactly matches the current site.
|
||||
*
|
||||
* This feature is opt-in (at least in WP 4.4). Apparently some people enable it.
|
||||
*
|
||||
* That can be a problem when you're developing your plugin and you decide to host the update information
|
||||
* on the same server as your test site. Update requests will mysteriously fail.
|
||||
*
|
||||
* We fix that by adding an exception for the metadata host.
|
||||
*
|
||||
* @param bool $allow
|
||||
* @param string $host
|
||||
* @return bool
|
||||
*/
|
||||
public function allowMetadataHost($allow, $host) {
|
||||
if ( $this->cachedMetadataHost === 0 ) {
|
||||
$this->cachedMetadataHost = parse_url($this->metadataUrl, PHP_URL_HOST);
|
||||
}
|
||||
|
||||
if ( is_string($this->cachedMetadataHost) && (strtolower($host) === strtolower($this->cachedMetadataHost)) ) {
|
||||
return true;
|
||||
}
|
||||
return $allow;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a package instance that represents this plugin or theme.
|
||||
*
|
||||
* @return Puc_v4p11_InstalledPackage
|
||||
*/
|
||||
abstract protected function createInstalledPackage();
|
||||
|
||||
/**
|
||||
* @return Puc_v4p11_InstalledPackage
|
||||
*/
|
||||
public function getInstalledPackage() {
|
||||
return $this->package;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of the scheduler.
|
||||
*
|
||||
* This is implemented as a method to make it possible for plugins to subclass the update checker
|
||||
* and substitute their own scheduler.
|
||||
*
|
||||
* @param int $checkPeriod
|
||||
* @return Puc_v4p11_Scheduler
|
||||
*/
|
||||
abstract protected function createScheduler($checkPeriod);
|
||||
|
||||
/**
|
||||
* Check for updates. The results are stored in the DB option specified in $optionName.
|
||||
*
|
||||
* @return Puc_v4p11_Update|null
|
||||
*/
|
||||
public function checkForUpdates() {
|
||||
$installedVersion = $this->getInstalledVersion();
|
||||
//Fail silently if we can't find the plugin/theme or read its header.
|
||||
if ( $installedVersion === null ) {
|
||||
$this->triggerError(
|
||||
sprintf('Skipping update check for %s - installed version unknown.', $this->slug),
|
||||
E_USER_WARNING
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
//Start collecting API errors.
|
||||
$this->lastRequestApiErrors = array();
|
||||
add_action('puc_api_error', array($this, 'collectApiErrors'), 10, 4);
|
||||
|
||||
$state = $this->updateState;
|
||||
$state->setLastCheckToNow()
|
||||
->setCheckedVersion($installedVersion)
|
||||
->save(); //Save before checking in case something goes wrong
|
||||
|
||||
$state->setUpdate($this->requestUpdate());
|
||||
$state->save();
|
||||
|
||||
//Stop collecting API errors.
|
||||
remove_action('puc_api_error', array($this, 'collectApiErrors'), 10);
|
||||
|
||||
return $this->getUpdate();
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the update checker state from the DB.
|
||||
*
|
||||
* @return Puc_v4p11_StateStore
|
||||
*/
|
||||
public function getUpdateState() {
|
||||
return $this->updateState->lazyLoad();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset update checker state - i.e. last check time, cached update data and so on.
|
||||
*
|
||||
* Call this when your plugin is being uninstalled, or if you want to
|
||||
* clear the update cache.
|
||||
*/
|
||||
public function resetUpdateState() {
|
||||
$this->updateState->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the details of the currently available update, if any.
|
||||
*
|
||||
* If no updates are available, or if the last known update version is below or equal
|
||||
* to the currently installed version, this method will return NULL.
|
||||
*
|
||||
* Uses cached update data. To retrieve update information straight from
|
||||
* the metadata URL, call requestUpdate() instead.
|
||||
*
|
||||
* @return Puc_v4p11_Update|null
|
||||
*/
|
||||
public function getUpdate() {
|
||||
$update = $this->updateState->getUpdate();
|
||||
|
||||
//Is there an update available?
|
||||
if ( isset($update) ) {
|
||||
//Check if the update is actually newer than the currently installed version.
|
||||
$installedVersion = $this->getInstalledVersion();
|
||||
if ( ($installedVersion !== null) && version_compare($update->version, $installedVersion, '>') ){
|
||||
return $update;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the latest update (if any) from the configured API endpoint.
|
||||
*
|
||||
* Subclasses should run the update through filterUpdateResult before returning it.
|
||||
*
|
||||
* @return Puc_v4p11_Update An instance of Update, or NULL when no updates are available.
|
||||
*/
|
||||
abstract public function requestUpdate();
|
||||
|
||||
/**
|
||||
* Filter the result of a requestUpdate() call.
|
||||
*
|
||||
* @param Puc_v4p11_Update|null $update
|
||||
* @param array|WP_Error|null $httpResult The value returned by wp_remote_get(), if any.
|
||||
* @return Puc_v4p11_Update
|
||||
*/
|
||||
protected function filterUpdateResult($update, $httpResult = null) {
|
||||
//Let plugins/themes modify the update.
|
||||
$update = apply_filters($this->getUniqueName('request_update_result'), $update, $httpResult);
|
||||
|
||||
$this->fixSupportedWordpressVersion($update);
|
||||
|
||||
if ( isset($update, $update->translations) ) {
|
||||
//Keep only those translation updates that apply to this site.
|
||||
$update->translations = $this->filterApplicableTranslations($update->translations);
|
||||
}
|
||||
|
||||
return $update;
|
||||
}
|
||||
|
||||
/**
|
||||
* The "Tested up to" field in the plugin metadata is supposed to be in the form of "major.minor",
|
||||
* while WordPress core's list_plugin_updates() expects the $update->tested field to be an exact
|
||||
* version, e.g. "major.minor.patch", to say it's compatible. In other case it shows
|
||||
* "Compatibility: Unknown".
|
||||
* The function mimics how wordpress.org API crafts the "tested" field out of "Tested up to".
|
||||
*
|
||||
* @param $update
|
||||
*/
|
||||
protected function fixSupportedWordpressVersion($update = null) {
|
||||
if ( !isset($update->tested) || !preg_match('/^\d++\.\d++$/', $update->tested) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$actualWpVersions = array();
|
||||
|
||||
$wpVersion = $GLOBALS['wp_version'];
|
||||
|
||||
if ( function_exists('get_core_updates') ) {
|
||||
$coreUpdates = get_core_updates();
|
||||
if ( is_array($coreUpdates) ) {
|
||||
foreach ($coreUpdates as $coreUpdate) {
|
||||
if ( isset($coreUpdate->current) ) {
|
||||
$actualWpVersions[] = $coreUpdate->current;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$actualWpVersions[] = $wpVersion;
|
||||
|
||||
$actualWpPatchNumber = null;
|
||||
foreach ($actualWpVersions as $version) {
|
||||
if ( preg_match('/^(?P<majorMinor>\d++\.\d++)(?:\.(?P<patch>\d++))?/', $version, $versionParts) ) {
|
||||
if ( $versionParts['majorMinor'] === $update->tested ) {
|
||||
$patch = isset($versionParts['patch']) ? intval($versionParts['patch']) : 0;
|
||||
if ( $actualWpPatchNumber === null ) {
|
||||
$actualWpPatchNumber = $patch;
|
||||
} else {
|
||||
$actualWpPatchNumber = max($actualWpPatchNumber, $patch);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ( $actualWpPatchNumber === null ) {
|
||||
$actualWpPatchNumber = 999;
|
||||
}
|
||||
|
||||
if ( $actualWpPatchNumber > 0 ) {
|
||||
$update->tested .= '.' . $actualWpPatchNumber;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the currently installed version of the plugin or theme.
|
||||
*
|
||||
* @return string|null Version number.
|
||||
*/
|
||||
public function getInstalledVersion() {
|
||||
return $this->package->getInstalledVersion();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the full path of the plugin or theme directory.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getAbsoluteDirectoryPath() {
|
||||
return $this->package->getAbsoluteDirectoryPath();
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger a PHP error, but only when $debugMode is enabled.
|
||||
*
|
||||
* @param string $message
|
||||
* @param int $errorType
|
||||
*/
|
||||
public function triggerError($message, $errorType) {
|
||||
if ( $this->isDebugModeEnabled() ) {
|
||||
trigger_error($message, $errorType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
protected function isDebugModeEnabled() {
|
||||
if ( $this->debugMode === null ) {
|
||||
$this->debugMode = (bool)(constant('WP_DEBUG'));
|
||||
}
|
||||
return $this->debugMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the full name of an update checker filter, action or DB entry.
|
||||
*
|
||||
* This method adds the "puc_" prefix and the "-$slug" suffix to the filter name.
|
||||
* For example, "pre_inject_update" becomes "puc_pre_inject_update-plugin-slug".
|
||||
*
|
||||
* @param string $baseTag
|
||||
* @return string
|
||||
*/
|
||||
public function getUniqueName($baseTag) {
|
||||
$name = 'puc_' . $baseTag;
|
||||
if ( $this->filterSuffix !== '' ) {
|
||||
$name .= '_' . $this->filterSuffix;
|
||||
}
|
||||
return $name . '-' . $this->slug;
|
||||
}
|
||||
|
||||
/**
|
||||
* Store API errors that are generated when checking for updates.
|
||||
*
|
||||
* @internal
|
||||
* @param WP_Error $error
|
||||
* @param array|null $httpResponse
|
||||
* @param string|null $url
|
||||
* @param string|null $slug
|
||||
*/
|
||||
public function collectApiErrors($error, $httpResponse = null, $url = null, $slug = null) {
|
||||
if ( isset($slug) && ($slug !== $this->slug) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->lastRequestApiErrors[] = array(
|
||||
'error' => $error,
|
||||
'httpResponse' => $httpResponse,
|
||||
'url' => $url,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getLastRequestApiErrors() {
|
||||
return $this->lastRequestApiErrors;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------
|
||||
* PUC filters and filter utilities
|
||||
* -------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/**
|
||||
* Register a callback for one of the update checker filters.
|
||||
*
|
||||
* Identical to add_filter(), except it automatically adds the "puc_" prefix
|
||||
* and the "-$slug" suffix to the filter name. For example, "request_info_result"
|
||||
* becomes "puc_request_info_result-your_plugin_slug".
|
||||
*
|
||||
* @param string $tag
|
||||
* @param callable $callback
|
||||
* @param int $priority
|
||||
* @param int $acceptedArgs
|
||||
*/
|
||||
public function addFilter($tag, $callback, $priority = 10, $acceptedArgs = 1) {
|
||||
add_filter($this->getUniqueName($tag), $callback, $priority, $acceptedArgs);
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------
|
||||
* Inject updates
|
||||
* -------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/**
|
||||
* Insert the latest update (if any) into the update list maintained by WP.
|
||||
*
|
||||
* @param stdClass $updates Update list.
|
||||
* @return stdClass Modified update list.
|
||||
*/
|
||||
public function injectUpdate($updates) {
|
||||
//Is there an update to insert?
|
||||
$update = $this->getUpdate();
|
||||
|
||||
if ( !$this->shouldShowUpdates() ) {
|
||||
$update = null;
|
||||
}
|
||||
|
||||
if ( !empty($update) ) {
|
||||
//Let plugins filter the update info before it's passed on to WordPress.
|
||||
$update = apply_filters($this->getUniqueName('pre_inject_update'), $update);
|
||||
$updates = $this->addUpdateToList($updates, $update->toWpFormat());
|
||||
} else {
|
||||
//Clean up any stale update info.
|
||||
$updates = $this->removeUpdateFromList($updates);
|
||||
//Add a placeholder item to the "no_update" list to enable auto-update support.
|
||||
//If we don't do this, the option to enable automatic updates will only show up
|
||||
//when an update is available.
|
||||
$updates = $this->addNoUpdateItem($updates);
|
||||
}
|
||||
|
||||
return $updates;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param stdClass|null $updates
|
||||
* @param stdClass|array $updateToAdd
|
||||
* @return stdClass
|
||||
*/
|
||||
protected function addUpdateToList($updates, $updateToAdd) {
|
||||
if ( !is_object($updates) ) {
|
||||
$updates = new stdClass();
|
||||
$updates->response = array();
|
||||
}
|
||||
|
||||
$updates->response[$this->getUpdateListKey()] = $updateToAdd;
|
||||
return $updates;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param stdClass|null $updates
|
||||
* @return stdClass|null
|
||||
*/
|
||||
protected function removeUpdateFromList($updates) {
|
||||
if ( isset($updates, $updates->response) ) {
|
||||
unset($updates->response[$this->getUpdateListKey()]);
|
||||
}
|
||||
return $updates;
|
||||
}
|
||||
|
||||
/**
|
||||
* See this post for more information:
|
||||
* @link https://make.wordpress.org/core/2020/07/30/recommended-usage-of-the-updates-api-to-support-the-auto-updates-ui-for-plugins-and-themes-in-wordpress-5-5/
|
||||
*
|
||||
* @param stdClass|null $updates
|
||||
* @return stdClass
|
||||
*/
|
||||
protected function addNoUpdateItem($updates) {
|
||||
if ( !is_object($updates) ) {
|
||||
$updates = new stdClass();
|
||||
$updates->response = array();
|
||||
$updates->no_update = array();
|
||||
} else if ( !isset($updates->no_update) ) {
|
||||
$updates->no_update = array();
|
||||
}
|
||||
|
||||
$updates->no_update[$this->getUpdateListKey()] = (object) $this->getNoUpdateItemFields();
|
||||
|
||||
return $updates;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subclasses should override this method to add fields that are specific to plugins or themes.
|
||||
* @return array
|
||||
*/
|
||||
protected function getNoUpdateItemFields() {
|
||||
return array(
|
||||
'new_version' => $this->getInstalledVersion(),
|
||||
'url' => '',
|
||||
'package' => '',
|
||||
'requires_php' => '',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the key that will be used when adding updates to the update list that's maintained
|
||||
* by the WordPress core. The list is always an associative array, but the key is different
|
||||
* for plugins and themes.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
abstract protected function getUpdateListKey();
|
||||
|
||||
/**
|
||||
* Should we show available updates?
|
||||
*
|
||||
* Usually the answer is "yes", but there are exceptions. For example, WordPress doesn't
|
||||
* support automatic updates installation for mu-plugins, so PUC usually won't show update
|
||||
* notifications in that case. See the plugin-specific subclass for details.
|
||||
*
|
||||
* Note: This method only applies to updates that are displayed (or not) in the WordPress
|
||||
* admin. It doesn't affect APIs like requestUpdate and getUpdate.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function shouldShowUpdates() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------
|
||||
* JSON-based update API
|
||||
* -------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/**
|
||||
* Retrieve plugin or theme metadata from the JSON document at $this->metadataUrl.
|
||||
*
|
||||
* @param string $metaClass Parse the JSON as an instance of this class. It must have a static fromJson method.
|
||||
* @param string $filterRoot
|
||||
* @param array $queryArgs Additional query arguments.
|
||||
* @return array [Puc_v4p11_Metadata|null, array|WP_Error] A metadata instance and the value returned by wp_remote_get().
|
||||
*/
|
||||
protected function requestMetadata($metaClass, $filterRoot, $queryArgs = array()) {
|
||||
//Query args to append to the URL. Plugins can add their own by using a filter callback (see addQueryArgFilter()).
|
||||
$queryArgs = array_merge(
|
||||
array(
|
||||
'installed_version' => strval($this->getInstalledVersion()),
|
||||
'php' => phpversion(),
|
||||
'locale' => get_locale(),
|
||||
),
|
||||
$queryArgs
|
||||
);
|
||||
$queryArgs = apply_filters($this->getUniqueName($filterRoot . '_query_args'), $queryArgs);
|
||||
|
||||
//Various options for the wp_remote_get() call. Plugins can filter these, too.
|
||||
$options = array(
|
||||
'timeout' => 10, //seconds
|
||||
'headers' => array(
|
||||
'Accept' => 'application/json',
|
||||
),
|
||||
);
|
||||
$options = apply_filters($this->getUniqueName($filterRoot . '_options'), $options);
|
||||
|
||||
//The metadata file should be at 'http://your-api.com/url/here/$slug/info.json'
|
||||
$url = $this->metadataUrl;
|
||||
if ( !empty($queryArgs) ){
|
||||
$url = add_query_arg($queryArgs, $url);
|
||||
}
|
||||
|
||||
$result = wp_remote_get($url, $options);
|
||||
|
||||
$result = apply_filters($this->getUniqueName('request_metadata_http_result'), $result, $url, $options);
|
||||
|
||||
//Try to parse the response
|
||||
$status = $this->validateApiResponse($result);
|
||||
$metadata = null;
|
||||
if ( !is_wp_error($status) ){
|
||||
if ( version_compare(PHP_VERSION, '5.3', '>=') && (strpos($metaClass, '\\') === false) ) {
|
||||
$metaClass = __NAMESPACE__ . '\\' . $metaClass;
|
||||
}
|
||||
$metadata = call_user_func(array($metaClass, 'fromJson'), $result['body']);
|
||||
} else {
|
||||
do_action('puc_api_error', $status, $result, $url, $this->slug);
|
||||
$this->triggerError(
|
||||
sprintf('The URL %s does not point to a valid metadata file. ', $url)
|
||||
. $status->get_error_message(),
|
||||
E_USER_WARNING
|
||||
);
|
||||
}
|
||||
|
||||
return array($metadata, $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if $result is a successful update API response.
|
||||
*
|
||||
* @param array|WP_Error $result
|
||||
* @return true|WP_Error
|
||||
*/
|
||||
protected function validateApiResponse($result) {
|
||||
if ( is_wp_error($result) ) { /** @var WP_Error $result */
|
||||
return new WP_Error($result->get_error_code(), 'WP HTTP Error: ' . $result->get_error_message());
|
||||
}
|
||||
|
||||
if ( !isset($result['response']['code']) ) {
|
||||
return new WP_Error(
|
||||
'puc_no_response_code',
|
||||
'wp_remote_get() returned an unexpected result.'
|
||||
);
|
||||
}
|
||||
|
||||
if ( $result['response']['code'] !== 200 ) {
|
||||
return new WP_Error(
|
||||
'puc_unexpected_response_code',
|
||||
'HTTP response code is ' . $result['response']['code'] . ' (expected: 200)'
|
||||
);
|
||||
}
|
||||
|
||||
if ( empty($result['body']) ) {
|
||||
return new WP_Error('puc_empty_response', 'The metadata file appears to be empty.');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------
|
||||
* Language packs / Translation updates
|
||||
* -------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/**
|
||||
* Filter a list of translation updates and return a new list that contains only updates
|
||||
* that apply to the current site.
|
||||
*
|
||||
* @param array $translations
|
||||
* @return array
|
||||
*/
|
||||
protected function filterApplicableTranslations($translations) {
|
||||
$languages = array_flip(array_values(get_available_languages()));
|
||||
$installedTranslations = $this->getInstalledTranslations();
|
||||
|
||||
$applicableTranslations = array();
|
||||
foreach ($translations as $translation) {
|
||||
//Does it match one of the available core languages?
|
||||
$isApplicable = array_key_exists($translation->language, $languages);
|
||||
//Is it more recent than an already-installed translation?
|
||||
if ( isset($installedTranslations[$translation->language]) ) {
|
||||
$updateTimestamp = strtotime($translation->updated);
|
||||
$installedTimestamp = strtotime($installedTranslations[$translation->language]['PO-Revision-Date']);
|
||||
$isApplicable = $updateTimestamp > $installedTimestamp;
|
||||
}
|
||||
|
||||
if ( $isApplicable ) {
|
||||
$applicableTranslations[] = $translation;
|
||||
}
|
||||
}
|
||||
|
||||
return $applicableTranslations;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of installed translations for this plugin or theme.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function getInstalledTranslations() {
|
||||
if ( !function_exists('wp_get_installed_translations') ) {
|
||||
return array();
|
||||
}
|
||||
$installedTranslations = wp_get_installed_translations($this->translationType . 's');
|
||||
if ( isset($installedTranslations[$this->directoryName]) ) {
|
||||
$installedTranslations = $installedTranslations[$this->directoryName];
|
||||
} else {
|
||||
$installedTranslations = array();
|
||||
}
|
||||
return $installedTranslations;
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert translation updates into the list maintained by WordPress.
|
||||
*
|
||||
* @param stdClass $updates
|
||||
* @return stdClass
|
||||
*/
|
||||
public function injectTranslationUpdates($updates) {
|
||||
$translationUpdates = $this->getTranslationUpdates();
|
||||
if ( empty($translationUpdates) ) {
|
||||
return $updates;
|
||||
}
|
||||
|
||||
//Being defensive.
|
||||
if ( !is_object($updates) ) {
|
||||
$updates = new stdClass();
|
||||
}
|
||||
if ( !isset($updates->translations) ) {
|
||||
$updates->translations = array();
|
||||
}
|
||||
|
||||
//In case there's a name collision with a plugin or theme hosted on wordpress.org,
|
||||
//remove any preexisting updates that match our thing.
|
||||
$updates->translations = array_values(array_filter(
|
||||
$updates->translations,
|
||||
array($this, 'isNotMyTranslation')
|
||||
));
|
||||
|
||||
//Add our updates to the list.
|
||||
foreach($translationUpdates as $update) {
|
||||
$convertedUpdate = array_merge(
|
||||
array(
|
||||
'type' => $this->translationType,
|
||||
'slug' => $this->directoryName,
|
||||
'autoupdate' => 0,
|
||||
//AFAICT, WordPress doesn't actually use the "version" field for anything.
|
||||
//But lets make sure it's there, just in case.
|
||||
'version' => isset($update->version) ? $update->version : ('1.' . strtotime($update->updated)),
|
||||
),
|
||||
(array)$update
|
||||
);
|
||||
|
||||
$updates->translations[] = $convertedUpdate;
|
||||
}
|
||||
|
||||
return $updates;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of available translation updates.
|
||||
*
|
||||
* This method will return an empty array if there are no updates.
|
||||
* Uses cached update data.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getTranslationUpdates() {
|
||||
return $this->updateState->getTranslations();
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all cached translation updates.
|
||||
*
|
||||
* @see wp_clean_update_cache
|
||||
*/
|
||||
public function clearCachedTranslationUpdates() {
|
||||
$this->updateState->setTranslations(array());
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter callback. Keeps only translations that *don't* match this plugin or theme.
|
||||
*
|
||||
* @param array $translation
|
||||
* @return bool
|
||||
*/
|
||||
protected function isNotMyTranslation($translation) {
|
||||
$isMatch = isset($translation['type'], $translation['slug'])
|
||||
&& ($translation['type'] === $this->translationType)
|
||||
&& ($translation['slug'] === $this->directoryName);
|
||||
|
||||
return !$isMatch;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------
|
||||
* Fix directory name when installing updates
|
||||
* -------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/**
|
||||
* Rename the update directory to match the existing plugin/theme directory.
|
||||
*
|
||||
* When WordPress installs a plugin or theme update, it assumes that the ZIP file will contain
|
||||
* exactly one directory, and that the directory name will be the same as the directory where
|
||||
* the plugin or theme is currently installed.
|
||||
*
|
||||
* GitHub and other repositories provide ZIP downloads, but they often use directory names like
|
||||
* "project-branch" or "project-tag-hash". We need to change the name to the actual plugin folder.
|
||||
*
|
||||
* This is a hook callback. Don't call it from a plugin.
|
||||
*
|
||||
* @access protected
|
||||
*
|
||||
* @param string $source The directory to copy to /wp-content/plugins or /wp-content/themes. Usually a subdirectory of $remoteSource.
|
||||
* @param string $remoteSource WordPress has extracted the update to this directory.
|
||||
* @param WP_Upgrader $upgrader
|
||||
* @return string|WP_Error
|
||||
*/
|
||||
public function fixDirectoryName($source, $remoteSource, $upgrader) {
|
||||
global $wp_filesystem;
|
||||
/** @var WP_Filesystem_Base $wp_filesystem */
|
||||
|
||||
//Basic sanity checks.
|
||||
if ( !isset($source, $remoteSource, $upgrader, $upgrader->skin, $wp_filesystem) ) {
|
||||
return $source;
|
||||
}
|
||||
|
||||
//If WordPress is upgrading anything other than our plugin/theme, leave the directory name unchanged.
|
||||
if ( !$this->isBeingUpgraded($upgrader) ) {
|
||||
return $source;
|
||||
}
|
||||
|
||||
//Rename the source to match the existing directory.
|
||||
$correctedSource = trailingslashit($remoteSource) . $this->directoryName . '/';
|
||||
if ( $source !== $correctedSource ) {
|
||||
//The update archive should contain a single directory that contains the rest of plugin/theme files.
|
||||
//Otherwise, WordPress will try to copy the entire working directory ($source == $remoteSource).
|
||||
//We can't rename $remoteSource because that would break WordPress code that cleans up temporary files
|
||||
//after update.
|
||||
if ( $this->isBadDirectoryStructure($remoteSource) ) {
|
||||
return new WP_Error(
|
||||
'puc-incorrect-directory-structure',
|
||||
sprintf(
|
||||
'The directory structure of the update is incorrect. All files should be inside ' .
|
||||
'a directory named <span class="code">%s</span>, not at the root of the ZIP archive.',
|
||||
htmlentities($this->slug)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/** @var WP_Upgrader_Skin $upgrader ->skin */
|
||||
$upgrader->skin->feedback(sprintf(
|
||||
'Renaming %s to %s…',
|
||||
'<span class="code">' . basename($source) . '</span>',
|
||||
'<span class="code">' . $this->directoryName . '</span>'
|
||||
));
|
||||
|
||||
if ( $wp_filesystem->move($source, $correctedSource, true) ) {
|
||||
$upgrader->skin->feedback('Directory successfully renamed.');
|
||||
return $correctedSource;
|
||||
} else {
|
||||
return new WP_Error(
|
||||
'puc-rename-failed',
|
||||
'Unable to rename the update to match the existing directory.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $source;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is there an update being installed right now, for this plugin or theme?
|
||||
*
|
||||
* @param WP_Upgrader|null $upgrader The upgrader that's performing the current update.
|
||||
* @return bool
|
||||
*/
|
||||
abstract public function isBeingUpgraded($upgrader = null);
|
||||
|
||||
/**
|
||||
* Check for incorrect update directory structure. An update must contain a single directory,
|
||||
* all other files should be inside that directory.
|
||||
*
|
||||
* @param string $remoteSource Directory path.
|
||||
* @return bool
|
||||
*/
|
||||
protected function isBadDirectoryStructure($remoteSource) {
|
||||
global $wp_filesystem;
|
||||
/** @var WP_Filesystem_Base $wp_filesystem */
|
||||
|
||||
$sourceFiles = $wp_filesystem->dirlist($remoteSource);
|
||||
if ( is_array($sourceFiles) ) {
|
||||
$sourceFiles = array_keys($sourceFiles);
|
||||
$firstFilePath = trailingslashit($remoteSource) . $sourceFiles[0];
|
||||
return (count($sourceFiles) > 1) || (!$wp_filesystem->is_dir($firstFilePath));
|
||||
}
|
||||
|
||||
//Assume it's fine.
|
||||
return false;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------
|
||||
* DebugBar integration
|
||||
* -------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/**
|
||||
* Initialize the update checker Debug Bar plugin/add-on thingy.
|
||||
*/
|
||||
public function maybeInitDebugBar() {
|
||||
if ( class_exists('Debug_Bar', false) && file_exists(dirname(__FILE__) . '/DebugBar') ) {
|
||||
$this->debugBarExtension = $this->createDebugBarExtension();
|
||||
}
|
||||
}
|
||||
|
||||
protected function createDebugBarExtension() {
|
||||
return new Puc_v4p11_DebugBar_Extension($this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Display additional configuration details in the Debug Bar panel.
|
||||
*
|
||||
* @param Puc_v4p11_DebugBar_Panel $panel
|
||||
*/
|
||||
public function onDisplayConfiguration($panel) {
|
||||
//Do nothing. Subclasses can use this to add additional info to the panel.
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
endif;
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
<?php
|
||||
if ( !class_exists('Puc_v4p11_UpgraderStatus', false) ):
|
||||
|
||||
/**
|
||||
* A utility class that helps figure out which plugin or theme WordPress is upgrading.
|
||||
*
|
||||
* It may seem strange to have a separate class just for that, but the task is surprisingly complicated.
|
||||
* Core classes like Plugin_Upgrader don't expose the plugin file name during an in-progress update (AFAICT).
|
||||
* This class uses a few workarounds and heuristics to get the file name.
|
||||
*/
|
||||
class Puc_v4p11_UpgraderStatus {
|
||||
private $currentType = null; //"plugin" or "theme".
|
||||
private $currentId = null; //Plugin basename or theme directory name.
|
||||
|
||||
public function __construct() {
|
||||
//Keep track of which plugin/theme WordPress is currently upgrading.
|
||||
add_filter('upgrader_pre_install', array($this, 'setUpgradedThing'), 10, 2);
|
||||
add_filter('upgrader_package_options', array($this, 'setUpgradedPluginFromOptions'), 10, 1);
|
||||
add_filter('upgrader_post_install', array($this, 'clearUpgradedThing'), 10, 1);
|
||||
add_action('upgrader_process_complete', array($this, 'clearUpgradedThing'), 10, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Is there and update being installed RIGHT NOW, for a specific plugin?
|
||||
*
|
||||
* Caution: This method is unreliable. WordPress doesn't make it easy to figure out what it is upgrading,
|
||||
* and upgrader implementations are liable to change without notice.
|
||||
*
|
||||
* @param string $pluginFile The plugin to check.
|
||||
* @param WP_Upgrader|null $upgrader The upgrader that's performing the current update.
|
||||
* @return bool True if the plugin identified by $pluginFile is being upgraded.
|
||||
*/
|
||||
public function isPluginBeingUpgraded($pluginFile, $upgrader = null) {
|
||||
return $this->isBeingUpgraded('plugin', $pluginFile, $upgrader);
|
||||
}
|
||||
|
||||
/**
|
||||
* Is there an update being installed for a specific theme?
|
||||
*
|
||||
* @param string $stylesheet Theme directory name.
|
||||
* @param WP_Upgrader|null $upgrader The upgrader that's performing the current update.
|
||||
* @return bool
|
||||
*/
|
||||
public function isThemeBeingUpgraded($stylesheet, $upgrader = null) {
|
||||
return $this->isBeingUpgraded('theme', $stylesheet, $upgrader);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a specific theme or plugin is being upgraded.
|
||||
*
|
||||
* @param string $type
|
||||
* @param string $id
|
||||
* @param Plugin_Upgrader|WP_Upgrader|null $upgrader
|
||||
* @return bool
|
||||
*/
|
||||
protected function isBeingUpgraded($type, $id, $upgrader = null) {
|
||||
if ( isset($upgrader) ) {
|
||||
list($currentType, $currentId) = $this->getThingBeingUpgradedBy($upgrader);
|
||||
if ( $currentType !== null ) {
|
||||
$this->currentType = $currentType;
|
||||
$this->currentId = $currentId;
|
||||
}
|
||||
}
|
||||
return ($this->currentType === $type) && ($this->currentId === $id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Figure out which theme or plugin is being upgraded by a WP_Upgrader instance.
|
||||
*
|
||||
* Returns an array with two items. The first item is the type of the thing that's being
|
||||
* upgraded: "plugin" or "theme". The second item is either the plugin basename or
|
||||
* the theme directory name. If we can't determine what the upgrader is doing, both items
|
||||
* will be NULL.
|
||||
*
|
||||
* Examples:
|
||||
* ['plugin', 'plugin-dir-name/plugin.php']
|
||||
* ['theme', 'theme-dir-name']
|
||||
*
|
||||
* @param Plugin_Upgrader|WP_Upgrader $upgrader
|
||||
* @return array
|
||||
*/
|
||||
private function getThingBeingUpgradedBy($upgrader) {
|
||||
if ( !isset($upgrader, $upgrader->skin) ) {
|
||||
return array(null, null);
|
||||
}
|
||||
|
||||
//Figure out which plugin or theme is being upgraded.
|
||||
$pluginFile = null;
|
||||
$themeDirectoryName = null;
|
||||
|
||||
$skin = $upgrader->skin;
|
||||
if ( isset($skin->theme_info) && ($skin->theme_info instanceof WP_Theme) ) {
|
||||
$themeDirectoryName = $skin->theme_info->get_stylesheet();
|
||||
} elseif ( $skin instanceof Plugin_Upgrader_Skin ) {
|
||||
if ( isset($skin->plugin) && is_string($skin->plugin) && ($skin->plugin !== '') ) {
|
||||
$pluginFile = $skin->plugin;
|
||||
}
|
||||
} elseif ( $skin instanceof Theme_Upgrader_Skin ) {
|
||||
if ( isset($skin->theme) && is_string($skin->theme) && ($skin->theme !== '') ) {
|
||||
$themeDirectoryName = $skin->theme;
|
||||
}
|
||||
} elseif ( isset($skin->plugin_info) && is_array($skin->plugin_info) ) {
|
||||
//This case is tricky because Bulk_Plugin_Upgrader_Skin (etc) doesn't actually store the plugin
|
||||
//filename anywhere. Instead, it has the plugin headers in $plugin_info. So the best we can
|
||||
//do is compare those headers to the headers of installed plugins.
|
||||
$pluginFile = $this->identifyPluginByHeaders($skin->plugin_info);
|
||||
}
|
||||
|
||||
if ( $pluginFile !== null ) {
|
||||
return array('plugin', $pluginFile);
|
||||
} elseif ( $themeDirectoryName !== null ) {
|
||||
return array('theme', $themeDirectoryName);
|
||||
}
|
||||
return array(null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Identify an installed plugin based on its headers.
|
||||
*
|
||||
* @param array $searchHeaders The plugin file header to look for.
|
||||
* @return string|null Plugin basename ("foo/bar.php"), or NULL if we can't identify the plugin.
|
||||
*/
|
||||
private function identifyPluginByHeaders($searchHeaders) {
|
||||
if ( !function_exists('get_plugins') ){
|
||||
/** @noinspection PhpIncludeInspection */
|
||||
require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
|
||||
}
|
||||
|
||||
$installedPlugins = get_plugins();
|
||||
$matches = array();
|
||||
foreach($installedPlugins as $pluginBasename => $headers) {
|
||||
$diff1 = array_diff_assoc($headers, $searchHeaders);
|
||||
$diff2 = array_diff_assoc($searchHeaders, $headers);
|
||||
if ( empty($diff1) && empty($diff2) ) {
|
||||
$matches[] = $pluginBasename;
|
||||
}
|
||||
}
|
||||
|
||||
//It's possible (though very unlikely) that there could be two plugins with identical
|
||||
//headers. In that case, we can't unambiguously identify the plugin that's being upgraded.
|
||||
if ( count($matches) !== 1 ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return reset($matches);
|
||||
}
|
||||
|
||||
/**
|
||||
* @access private
|
||||
*
|
||||
* @param mixed $input
|
||||
* @param array $hookExtra
|
||||
* @return mixed Returns $input unaltered.
|
||||
*/
|
||||
public function setUpgradedThing($input, $hookExtra) {
|
||||
if ( !empty($hookExtra['plugin']) && is_string($hookExtra['plugin']) ) {
|
||||
$this->currentId = $hookExtra['plugin'];
|
||||
$this->currentType = 'plugin';
|
||||
} elseif ( !empty($hookExtra['theme']) && is_string($hookExtra['theme']) ) {
|
||||
$this->currentId = $hookExtra['theme'];
|
||||
$this->currentType = 'theme';
|
||||
} else {
|
||||
$this->currentType = null;
|
||||
$this->currentId = null;
|
||||
}
|
||||
return $input;
|
||||
}
|
||||
|
||||
/**
|
||||
* @access private
|
||||
*
|
||||
* @param array $options
|
||||
* @return array
|
||||
*/
|
||||
public function setUpgradedPluginFromOptions($options) {
|
||||
if ( isset($options['hook_extra']['plugin']) && is_string($options['hook_extra']['plugin']) ) {
|
||||
$this->currentType = 'plugin';
|
||||
$this->currentId = $options['hook_extra']['plugin'];
|
||||
} else {
|
||||
$this->currentType = null;
|
||||
$this->currentId = null;
|
||||
}
|
||||
return $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* @access private
|
||||
*
|
||||
* @param mixed $input
|
||||
* @return mixed Returns $input unaltered.
|
||||
*/
|
||||
public function clearUpgradedThing($input = null) {
|
||||
$this->currentId = null;
|
||||
$this->currentType = null;
|
||||
return $input;
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
Vendored
+69
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
if ( !class_exists('Puc_v4p11_Utils', false) ):
|
||||
|
||||
class Puc_v4p11_Utils {
|
||||
/**
|
||||
* Get a value from a nested array or object based on a path.
|
||||
*
|
||||
* @param array|object|null $collection Get an entry from this array.
|
||||
* @param array|string $path A list of array keys in hierarchy order, or a string path like "foo.bar.baz".
|
||||
* @param mixed $default The value to return if the specified path is not found.
|
||||
* @param string $separator Path element separator. Only applies to string paths.
|
||||
* @return mixed
|
||||
*/
|
||||
public static function get($collection, $path, $default = null, $separator = '.') {
|
||||
if ( is_string($path) ) {
|
||||
$path = explode($separator, $path);
|
||||
}
|
||||
|
||||
//Follow the $path into $input as far as possible.
|
||||
$currentValue = $collection;
|
||||
foreach ($path as $node) {
|
||||
if ( is_array($currentValue) && isset($currentValue[$node]) ) {
|
||||
$currentValue = $currentValue[$node];
|
||||
} else if ( is_object($currentValue) && isset($currentValue->$node) ) {
|
||||
$currentValue = $currentValue->$node;
|
||||
} else {
|
||||
return $default;
|
||||
}
|
||||
}
|
||||
|
||||
return $currentValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the first array element that is not empty.
|
||||
*
|
||||
* @param array $values
|
||||
* @param mixed|null $default Returns this value if there are no non-empty elements.
|
||||
* @return mixed|null
|
||||
*/
|
||||
public static function findNotEmpty($values, $default = null) {
|
||||
if ( empty($values) ) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
foreach ($values as $value) {
|
||||
if ( !empty($value) ) {
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the input string starts with the specified prefix.
|
||||
*
|
||||
* @param string $input
|
||||
* @param string $prefix
|
||||
* @return bool
|
||||
*/
|
||||
public static function startsWith($input, $prefix) {
|
||||
$length = strlen($prefix);
|
||||
return (substr($input, 0, $length) === $prefix);
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
wp-content/plugins/permalink-manager-pro/includes/vendor/plugin-update-checker/Puc/v4p11/Vcs/Api.php
Vendored
+302
@@ -0,0 +1,302 @@
|
||||
<?php
|
||||
if ( !class_exists('Puc_v4p11_Vcs_Api') ):
|
||||
|
||||
abstract class Puc_v4p11_Vcs_Api {
|
||||
protected $tagNameProperty = 'name';
|
||||
protected $slug = '';
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $repositoryUrl = '';
|
||||
|
||||
/**
|
||||
* @var mixed Authentication details for private repositories. Format depends on service.
|
||||
*/
|
||||
protected $credentials = null;
|
||||
|
||||
/**
|
||||
* @var string The filter tag that's used to filter options passed to wp_remote_get.
|
||||
* For example, "puc_request_info_options-slug" or "puc_request_update_options_theme-slug".
|
||||
*/
|
||||
protected $httpFilterName = '';
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected $localDirectory = null;
|
||||
|
||||
/**
|
||||
* Puc_v4p11_Vcs_Api constructor.
|
||||
*
|
||||
* @param string $repositoryUrl
|
||||
* @param array|string|null $credentials
|
||||
*/
|
||||
public function __construct($repositoryUrl, $credentials = null) {
|
||||
$this->repositoryUrl = $repositoryUrl;
|
||||
$this->setAuthentication($credentials);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getRepositoryUrl() {
|
||||
return $this->repositoryUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Figure out which reference (i.e tag or branch) contains the latest version.
|
||||
*
|
||||
* @param string $configBranch Start looking in this branch.
|
||||
* @return null|Puc_v4p11_Vcs_Reference
|
||||
*/
|
||||
abstract public function chooseReference($configBranch);
|
||||
|
||||
/**
|
||||
* Get the readme.txt file from the remote repository and parse it
|
||||
* according to the plugin readme standard.
|
||||
*
|
||||
* @param string $ref Tag or branch name.
|
||||
* @return array Parsed readme.
|
||||
*/
|
||||
public function getRemoteReadme($ref = 'master') {
|
||||
$fileContents = $this->getRemoteFile($this->getLocalReadmeName(), $ref);
|
||||
if ( empty($fileContents) ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$parser = new PucReadmeParser();
|
||||
return $parser->parse_readme_contents($fileContents);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the case-sensitive name of the local readme.txt file.
|
||||
*
|
||||
* In most cases it should just be called "readme.txt", but some plugins call it "README.txt",
|
||||
* "README.TXT", or even "Readme.txt". Most VCS are case-sensitive so we need to know the correct
|
||||
* capitalization.
|
||||
*
|
||||
* Defaults to "readme.txt" (all lowercase).
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getLocalReadmeName() {
|
||||
static $fileName = null;
|
||||
if ( $fileName !== null ) {
|
||||
return $fileName;
|
||||
}
|
||||
|
||||
$fileName = 'readme.txt';
|
||||
if ( isset($this->localDirectory) ) {
|
||||
$files = scandir($this->localDirectory);
|
||||
if ( !empty($files) ) {
|
||||
foreach ($files as $possibleFileName) {
|
||||
if ( strcasecmp($possibleFileName, 'readme.txt') === 0 ) {
|
||||
$fileName = $possibleFileName;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return $fileName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a branch.
|
||||
*
|
||||
* @param string $branchName
|
||||
* @return Puc_v4p11_Vcs_Reference|null
|
||||
*/
|
||||
abstract public function getBranch($branchName);
|
||||
|
||||
/**
|
||||
* Get a specific tag.
|
||||
*
|
||||
* @param string $tagName
|
||||
* @return Puc_v4p11_Vcs_Reference|null
|
||||
*/
|
||||
abstract public function getTag($tagName);
|
||||
|
||||
/**
|
||||
* Get the tag that looks like the highest version number.
|
||||
* (Implementations should skip pre-release versions if possible.)
|
||||
*
|
||||
* @return Puc_v4p11_Vcs_Reference|null
|
||||
*/
|
||||
abstract public function getLatestTag();
|
||||
|
||||
/**
|
||||
* Check if a tag name string looks like a version number.
|
||||
*
|
||||
* @param string $name
|
||||
* @return bool
|
||||
*/
|
||||
protected function looksLikeVersion($name) {
|
||||
//Tag names may be prefixed with "v", e.g. "v1.2.3".
|
||||
$name = ltrim($name, 'v');
|
||||
|
||||
//The version string must start with a number.
|
||||
if ( !is_numeric(substr($name, 0, 1)) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
//The goal is to accept any SemVer-compatible or "PHP-standardized" version number.
|
||||
return (preg_match('@^(\d{1,5}?)(\.\d{1,10}?){0,4}?($|[abrdp+_\-]|\s)@i', $name) === 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a tag appears to be named like a version number.
|
||||
*
|
||||
* @param stdClass $tag
|
||||
* @return bool
|
||||
*/
|
||||
protected function isVersionTag($tag) {
|
||||
$property = $this->tagNameProperty;
|
||||
return isset($tag->$property) && $this->looksLikeVersion($tag->$property);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort a list of tags as if they were version numbers.
|
||||
* Tags that don't look like version number will be removed.
|
||||
*
|
||||
* @param stdClass[] $tags Array of tag objects.
|
||||
* @return stdClass[] Filtered array of tags sorted in descending order.
|
||||
*/
|
||||
protected function sortTagsByVersion($tags) {
|
||||
//Keep only those tags that look like version numbers.
|
||||
$versionTags = array_filter($tags, array($this, 'isVersionTag'));
|
||||
//Sort them in descending order.
|
||||
usort($versionTags, array($this, 'compareTagNames'));
|
||||
|
||||
return $versionTags;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare two tags as if they were version number.
|
||||
*
|
||||
* @param stdClass $tag1 Tag object.
|
||||
* @param stdClass $tag2 Another tag object.
|
||||
* @return int
|
||||
*/
|
||||
protected function compareTagNames($tag1, $tag2) {
|
||||
$property = $this->tagNameProperty;
|
||||
if ( !isset($tag1->$property) ) {
|
||||
return 1;
|
||||
}
|
||||
if ( !isset($tag2->$property) ) {
|
||||
return -1;
|
||||
}
|
||||
return -version_compare(ltrim($tag1->$property, 'v'), ltrim($tag2->$property, 'v'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the contents of a file from a specific branch or tag.
|
||||
*
|
||||
* @param string $path File name.
|
||||
* @param string $ref
|
||||
* @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error.
|
||||
*/
|
||||
abstract public function getRemoteFile($path, $ref = 'master');
|
||||
|
||||
/**
|
||||
* Get the timestamp of the latest commit that changed the specified branch or tag.
|
||||
*
|
||||
* @param string $ref Reference name (e.g. branch or tag).
|
||||
* @return string|null
|
||||
*/
|
||||
abstract public function getLatestCommitTime($ref);
|
||||
|
||||
/**
|
||||
* Get the contents of the changelog file from the repository.
|
||||
*
|
||||
* @param string $ref
|
||||
* @param string $localDirectory Full path to the local plugin or theme directory.
|
||||
* @return null|string The HTML contents of the changelog.
|
||||
*/
|
||||
public function getRemoteChangelog($ref, $localDirectory) {
|
||||
$filename = $this->findChangelogName($localDirectory);
|
||||
if ( empty($filename) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$changelog = $this->getRemoteFile($filename, $ref);
|
||||
if ( $changelog === null ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @noinspection PhpUndefinedClassInspection */
|
||||
return Parsedown::instance()->text($changelog);
|
||||
}
|
||||
|
||||
/**
|
||||
* Guess the name of the changelog file.
|
||||
*
|
||||
* @param string $directory
|
||||
* @return string|null
|
||||
*/
|
||||
protected function findChangelogName($directory = null) {
|
||||
if ( !isset($directory) ) {
|
||||
$directory = $this->localDirectory;
|
||||
}
|
||||
if ( empty($directory) || !is_dir($directory) || ($directory === '.') ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$possibleNames = array('CHANGES.md', 'CHANGELOG.md', 'changes.md', 'changelog.md');
|
||||
$files = scandir($directory);
|
||||
$foundNames = array_intersect($possibleNames, $files);
|
||||
|
||||
if ( !empty($foundNames) ) {
|
||||
return reset($foundNames);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set authentication credentials.
|
||||
*
|
||||
* @param $credentials
|
||||
*/
|
||||
public function setAuthentication($credentials) {
|
||||
$this->credentials = $credentials;
|
||||
}
|
||||
|
||||
public function isAuthenticationEnabled() {
|
||||
return !empty($this->credentials);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $url
|
||||
* @return string
|
||||
*/
|
||||
public function signDownloadUrl($url) {
|
||||
return $url;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $filterName
|
||||
*/
|
||||
public function setHttpFilterName($filterName) {
|
||||
$this->httpFilterName = $filterName;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $directory
|
||||
*/
|
||||
public function setLocalDirectory($directory) {
|
||||
if ( empty($directory) || !is_dir($directory) || ($directory === '.') ) {
|
||||
$this->localDirectory = null;
|
||||
} else {
|
||||
$this->localDirectory = $directory;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $slug
|
||||
*/
|
||||
public function setSlug($slug) {
|
||||
$this->slug = $slug;
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
if ( !interface_exists('Puc_v4p11_Vcs_BaseChecker', false) ):
|
||||
|
||||
interface Puc_v4p11_Vcs_BaseChecker {
|
||||
/**
|
||||
* Set the repository branch to use for updates. Defaults to 'master'.
|
||||
*
|
||||
* @param string $branch
|
||||
* @return $this
|
||||
*/
|
||||
public function setBranch($branch);
|
||||
|
||||
/**
|
||||
* Set authentication credentials.
|
||||
*
|
||||
* @param array|string $credentials
|
||||
* @return $this
|
||||
*/
|
||||
public function setAuthentication($credentials);
|
||||
|
||||
/**
|
||||
* @return Puc_v4p11_Vcs_Api
|
||||
*/
|
||||
public function getVcsApi();
|
||||
}
|
||||
|
||||
endif;
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
<?php
|
||||
if ( !class_exists('Puc_v4p11_Vcs_BitBucketApi', false) ):
|
||||
|
||||
class Puc_v4p11_Vcs_BitBucketApi extends Puc_v4p11_Vcs_Api {
|
||||
/**
|
||||
* @var Puc_v4p11_OAuthSignature
|
||||
*/
|
||||
private $oauth = null;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $username;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $repository;
|
||||
|
||||
public function __construct($repositoryUrl, $credentials = array()) {
|
||||
$path = parse_url($repositoryUrl, PHP_URL_PATH);
|
||||
if ( preg_match('@^/?(?P<username>[^/]+?)/(?P<repository>[^/#?&]+?)/?$@', $path, $matches) ) {
|
||||
$this->username = $matches['username'];
|
||||
$this->repository = $matches['repository'];
|
||||
} else {
|
||||
throw new InvalidArgumentException('Invalid BitBucket repository URL: "' . $repositoryUrl . '"');
|
||||
}
|
||||
|
||||
parent::__construct($repositoryUrl, $credentials);
|
||||
}
|
||||
|
||||
/**
|
||||
* Figure out which reference (i.e tag or branch) contains the latest version.
|
||||
*
|
||||
* @param string $configBranch Start looking in this branch.
|
||||
* @return null|Puc_v4p11_Vcs_Reference
|
||||
*/
|
||||
public function chooseReference($configBranch) {
|
||||
$updateSource = null;
|
||||
|
||||
//Check if there's a "Stable tag: 1.2.3" header that points to a valid tag.
|
||||
$updateSource = $this->getStableTag($configBranch);
|
||||
|
||||
//Look for version-like tags.
|
||||
if ( !$updateSource && ($configBranch === 'master') ) {
|
||||
$updateSource = $this->getLatestTag();
|
||||
}
|
||||
//If all else fails, use the specified branch itself.
|
||||
if ( !$updateSource ) {
|
||||
$updateSource = $this->getBranch($configBranch);
|
||||
}
|
||||
|
||||
return $updateSource;
|
||||
}
|
||||
|
||||
public function getBranch($branchName) {
|
||||
$branch = $this->api('/refs/branches/' . $branchName);
|
||||
if ( is_wp_error($branch) || empty($branch) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new Puc_v4p11_Vcs_Reference(array(
|
||||
'name' => $branch->name,
|
||||
'updated' => $branch->target->date,
|
||||
'downloadUrl' => $this->getDownloadUrl($branch->name),
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a specific tag.
|
||||
*
|
||||
* @param string $tagName
|
||||
* @return Puc_v4p11_Vcs_Reference|null
|
||||
*/
|
||||
public function getTag($tagName) {
|
||||
$tag = $this->api('/refs/tags/' . $tagName);
|
||||
if ( is_wp_error($tag) || empty($tag) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new Puc_v4p11_Vcs_Reference(array(
|
||||
'name' => $tag->name,
|
||||
'version' => ltrim($tag->name, 'v'),
|
||||
'updated' => $tag->target->date,
|
||||
'downloadUrl' => $this->getDownloadUrl($tag->name),
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the tag that looks like the highest version number.
|
||||
*
|
||||
* @return Puc_v4p11_Vcs_Reference|null
|
||||
*/
|
||||
public function getLatestTag() {
|
||||
$tags = $this->api('/refs/tags?sort=-target.date');
|
||||
if ( !isset($tags, $tags->values) || !is_array($tags->values) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
//Filter and sort the list of tags.
|
||||
$versionTags = $this->sortTagsByVersion($tags->values);
|
||||
|
||||
//Return the first result.
|
||||
if ( !empty($versionTags) ) {
|
||||
$tag = $versionTags[0];
|
||||
return new Puc_v4p11_Vcs_Reference(array(
|
||||
'name' => $tag->name,
|
||||
'version' => ltrim($tag->name, 'v'),
|
||||
'updated' => $tag->target->date,
|
||||
'downloadUrl' => $this->getDownloadUrl($tag->name),
|
||||
));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the tag/ref specified by the "Stable tag" header in the readme.txt of a given branch.
|
||||
*
|
||||
* @param string $branch
|
||||
* @return null|Puc_v4p11_Vcs_Reference
|
||||
*/
|
||||
protected function getStableTag($branch) {
|
||||
$remoteReadme = $this->getRemoteReadme($branch);
|
||||
if ( !empty($remoteReadme['stable_tag']) ) {
|
||||
$tag = $remoteReadme['stable_tag'];
|
||||
|
||||
//You can explicitly opt out of using tags by setting "Stable tag" to
|
||||
//"trunk" or the name of the current branch.
|
||||
if ( ($tag === $branch) || ($tag === 'trunk') ) {
|
||||
return $this->getBranch($branch);
|
||||
}
|
||||
|
||||
return $this->getTag($tag);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $ref
|
||||
* @return string
|
||||
*/
|
||||
protected function getDownloadUrl($ref) {
|
||||
return sprintf(
|
||||
'https://bitbucket.org/%s/%s/get/%s.zip',
|
||||
$this->username,
|
||||
$this->repository,
|
||||
$ref
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the contents of a file from a specific branch or tag.
|
||||
*
|
||||
* @param string $path File name.
|
||||
* @param string $ref
|
||||
* @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error.
|
||||
*/
|
||||
public function getRemoteFile($path, $ref = 'master') {
|
||||
$response = $this->api('src/' . $ref . '/' . ltrim($path));
|
||||
if ( is_wp_error($response) || !is_string($response) ) {
|
||||
return null;
|
||||
}
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the timestamp of the latest commit that changed the specified branch or tag.
|
||||
*
|
||||
* @param string $ref Reference name (e.g. branch or tag).
|
||||
* @return string|null
|
||||
*/
|
||||
public function getLatestCommitTime($ref) {
|
||||
$response = $this->api('commits/' . $ref);
|
||||
if ( isset($response->values, $response->values[0], $response->values[0]->date) ) {
|
||||
return $response->values[0]->date;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform a BitBucket API 2.0 request.
|
||||
*
|
||||
* @param string $url
|
||||
* @param string $version
|
||||
* @return mixed|WP_Error
|
||||
*/
|
||||
public function api($url, $version = '2.0') {
|
||||
$url = ltrim($url, '/');
|
||||
$isSrcResource = Puc_v4p11_Utils::startsWith($url, 'src/');
|
||||
|
||||
$url = implode('/', array(
|
||||
'https://api.bitbucket.org',
|
||||
$version,
|
||||
'repositories',
|
||||
$this->username,
|
||||
$this->repository,
|
||||
$url
|
||||
));
|
||||
$baseUrl = $url;
|
||||
|
||||
if ( $this->oauth ) {
|
||||
$url = $this->oauth->sign($url,'GET');
|
||||
}
|
||||
|
||||
$options = array('timeout' => 10);
|
||||
if ( !empty($this->httpFilterName) ) {
|
||||
$options = apply_filters($this->httpFilterName, $options);
|
||||
}
|
||||
$response = wp_remote_get($url, $options);
|
||||
if ( is_wp_error($response) ) {
|
||||
do_action('puc_api_error', $response, null, $url, $this->slug);
|
||||
return $response;
|
||||
}
|
||||
|
||||
$code = wp_remote_retrieve_response_code($response);
|
||||
$body = wp_remote_retrieve_body($response);
|
||||
if ( $code === 200 ) {
|
||||
if ( $isSrcResource ) {
|
||||
//Most responses are JSON-encoded, but src resources just
|
||||
//return raw file contents.
|
||||
$document = $body;
|
||||
} else {
|
||||
$document = json_decode($body);
|
||||
}
|
||||
return $document;
|
||||
}
|
||||
|
||||
$error = new WP_Error(
|
||||
'puc-bitbucket-http-error',
|
||||
sprintf('BitBucket API error. Base URL: "%s", HTTP status code: %d.', $baseUrl, $code)
|
||||
);
|
||||
do_action('puc_api_error', $error, $response, $url, $this->slug);
|
||||
|
||||
return $error;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $credentials
|
||||
*/
|
||||
public function setAuthentication($credentials) {
|
||||
parent::setAuthentication($credentials);
|
||||
|
||||
if ( !empty($credentials) && !empty($credentials['consumer_key']) ) {
|
||||
$this->oauth = new Puc_v4p11_OAuthSignature(
|
||||
$credentials['consumer_key'],
|
||||
$credentials['consumer_secret']
|
||||
);
|
||||
} else {
|
||||
$this->oauth = null;
|
||||
}
|
||||
}
|
||||
|
||||
public function signDownloadUrl($url) {
|
||||
//Add authentication data to download URLs. Since OAuth signatures incorporate
|
||||
//timestamps, we have to do this immediately before inserting the update. Otherwise
|
||||
//authentication could fail due to a stale timestamp.
|
||||
if ( $this->oauth ) {
|
||||
$url = $this->oauth->sign($url);
|
||||
}
|
||||
return $url;
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
+441
@@ -0,0 +1,441 @@
|
||||
<?php
|
||||
|
||||
if ( !class_exists('Puc_v4p11_Vcs_GitHubApi', false) ):
|
||||
|
||||
class Puc_v4p11_Vcs_GitHubApi extends Puc_v4p11_Vcs_Api {
|
||||
/**
|
||||
* @var string GitHub username.
|
||||
*/
|
||||
protected $userName;
|
||||
/**
|
||||
* @var string GitHub repository name.
|
||||
*/
|
||||
protected $repositoryName;
|
||||
|
||||
/**
|
||||
* @var string Either a fully qualified repository URL, or just "user/repo-name".
|
||||
*/
|
||||
protected $repositoryUrl;
|
||||
|
||||
/**
|
||||
* @var string GitHub authentication token. Optional.
|
||||
*/
|
||||
protected $accessToken;
|
||||
|
||||
/**
|
||||
* @var bool Whether to download release assets instead of the auto-generated source code archives.
|
||||
*/
|
||||
protected $releaseAssetsEnabled = false;
|
||||
|
||||
/**
|
||||
* @var string|null Regular expression that's used to filter release assets by name. Optional.
|
||||
*/
|
||||
protected $assetFilterRegex = null;
|
||||
|
||||
/**
|
||||
* @var string|null The unchanging part of a release asset URL. Used to identify download attempts.
|
||||
*/
|
||||
protected $assetApiBaseUrl = null;
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
private $downloadFilterAdded = false;
|
||||
|
||||
public function __construct($repositoryUrl, $accessToken = null) {
|
||||
$path = parse_url($repositoryUrl, PHP_URL_PATH);
|
||||
if ( preg_match('@^/?(?P<username>[^/]+?)/(?P<repository>[^/#?&]+?)/?$@', $path, $matches) ) {
|
||||
$this->userName = $matches['username'];
|
||||
$this->repositoryName = $matches['repository'];
|
||||
} else {
|
||||
throw new InvalidArgumentException('Invalid GitHub repository URL: "' . $repositoryUrl . '"');
|
||||
}
|
||||
|
||||
parent::__construct($repositoryUrl, $accessToken);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the latest release from GitHub.
|
||||
*
|
||||
* @return Puc_v4p11_Vcs_Reference|null
|
||||
*/
|
||||
public function getLatestRelease() {
|
||||
$release = $this->api('/repos/:user/:repo/releases/latest');
|
||||
if ( is_wp_error($release) || !is_object($release) || !isset($release->tag_name) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$reference = new Puc_v4p11_Vcs_Reference(array(
|
||||
'name' => $release->tag_name,
|
||||
'version' => ltrim($release->tag_name, 'v'), //Remove the "v" prefix from "v1.2.3".
|
||||
'downloadUrl' => $release->zipball_url,
|
||||
'updated' => $release->created_at,
|
||||
'apiResponse' => $release,
|
||||
));
|
||||
|
||||
if ( isset($release->assets[0]) ) {
|
||||
$reference->downloadCount = $release->assets[0]->download_count;
|
||||
}
|
||||
|
||||
if ( $this->releaseAssetsEnabled && isset($release->assets, $release->assets[0]) ) {
|
||||
//Use the first release asset that matches the specified regular expression.
|
||||
$matchingAssets = array_filter($release->assets, array($this, 'matchesAssetFilter'));
|
||||
if ( !empty($matchingAssets) ) {
|
||||
if ( $this->isAuthenticationEnabled() ) {
|
||||
/**
|
||||
* Keep in mind that we'll need to add an "Accept" header to download this asset.
|
||||
*
|
||||
* @see setUpdateDownloadHeaders()
|
||||
*/
|
||||
$reference->downloadUrl = $matchingAssets[0]->url;
|
||||
} else {
|
||||
//It seems that browser_download_url only works for public repositories.
|
||||
//Using an access_token doesn't help. Maybe OAuth would work?
|
||||
$reference->downloadUrl = $matchingAssets[0]->browser_download_url;
|
||||
}
|
||||
|
||||
$reference->downloadCount = $matchingAssets[0]->download_count;
|
||||
}
|
||||
}
|
||||
|
||||
if ( !empty($release->body) ) {
|
||||
/** @noinspection PhpUndefinedClassInspection */
|
||||
$reference->changelog = Parsedown::instance()->text($release->body);
|
||||
}
|
||||
|
||||
return $reference;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the tag that looks like the highest version number.
|
||||
*
|
||||
* @return Puc_v4p11_Vcs_Reference|null
|
||||
*/
|
||||
public function getLatestTag() {
|
||||
$tags = $this->api('/repos/:user/:repo/tags');
|
||||
|
||||
if ( is_wp_error($tags) || !is_array($tags) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$versionTags = $this->sortTagsByVersion($tags);
|
||||
if ( empty($versionTags) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$tag = $versionTags[0];
|
||||
return new Puc_v4p11_Vcs_Reference(array(
|
||||
'name' => $tag->name,
|
||||
'version' => ltrim($tag->name, 'v'),
|
||||
'downloadUrl' => $tag->zipball_url,
|
||||
'apiResponse' => $tag,
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a branch by name.
|
||||
*
|
||||
* @param string $branchName
|
||||
* @return null|Puc_v4p11_Vcs_Reference
|
||||
*/
|
||||
public function getBranch($branchName) {
|
||||
$branch = $this->api('/repos/:user/:repo/branches/' . $branchName);
|
||||
if ( is_wp_error($branch) || empty($branch) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$reference = new Puc_v4p11_Vcs_Reference(array(
|
||||
'name' => $branch->name,
|
||||
'downloadUrl' => $this->buildArchiveDownloadUrl($branch->name),
|
||||
'apiResponse' => $branch,
|
||||
));
|
||||
|
||||
if ( isset($branch->commit, $branch->commit->commit, $branch->commit->commit->author->date) ) {
|
||||
$reference->updated = $branch->commit->commit->author->date;
|
||||
}
|
||||
|
||||
return $reference;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the latest commit that changed the specified file.
|
||||
*
|
||||
* @param string $filename
|
||||
* @param string $ref Reference name (e.g. branch or tag).
|
||||
* @return StdClass|null
|
||||
*/
|
||||
public function getLatestCommit($filename, $ref = 'master') {
|
||||
$commits = $this->api(
|
||||
'/repos/:user/:repo/commits',
|
||||
array(
|
||||
'path' => $filename,
|
||||
'sha' => $ref,
|
||||
)
|
||||
);
|
||||
if ( !is_wp_error($commits) && isset($commits[0]) ) {
|
||||
return $commits[0];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the timestamp of the latest commit that changed the specified branch or tag.
|
||||
*
|
||||
* @param string $ref Reference name (e.g. branch or tag).
|
||||
* @return string|null
|
||||
*/
|
||||
public function getLatestCommitTime($ref) {
|
||||
$commits = $this->api('/repos/:user/:repo/commits', array('sha' => $ref));
|
||||
if ( !is_wp_error($commits) && isset($commits[0]) ) {
|
||||
return $commits[0]->commit->author->date;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform a GitHub API request.
|
||||
*
|
||||
* @param string $url
|
||||
* @param array $queryParams
|
||||
* @return mixed|WP_Error
|
||||
*/
|
||||
protected function api($url, $queryParams = array()) {
|
||||
$baseUrl = $url;
|
||||
$url = $this->buildApiUrl($url, $queryParams);
|
||||
|
||||
$options = array('timeout' => 10);
|
||||
if ( $this->isAuthenticationEnabled() ) {
|
||||
$options['headers'] = array('Authorization' => $this->getAuthorizationHeader());
|
||||
}
|
||||
|
||||
if ( !empty($this->httpFilterName) ) {
|
||||
$options = apply_filters($this->httpFilterName, $options);
|
||||
}
|
||||
$response = wp_remote_get($url, $options);
|
||||
if ( is_wp_error($response) ) {
|
||||
do_action('puc_api_error', $response, null, $url, $this->slug);
|
||||
return $response;
|
||||
}
|
||||
|
||||
$code = wp_remote_retrieve_response_code($response);
|
||||
$body = wp_remote_retrieve_body($response);
|
||||
if ( $code === 200 ) {
|
||||
$document = json_decode($body);
|
||||
return $document;
|
||||
}
|
||||
|
||||
$error = new WP_Error(
|
||||
'puc-github-http-error',
|
||||
sprintf('GitHub API error. Base URL: "%s", HTTP status code: %d.', $baseUrl, $code)
|
||||
);
|
||||
do_action('puc_api_error', $error, $response, $url, $this->slug);
|
||||
|
||||
return $error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a fully qualified URL for an API request.
|
||||
*
|
||||
* @param string $url
|
||||
* @param array $queryParams
|
||||
* @return string
|
||||
*/
|
||||
protected function buildApiUrl($url, $queryParams) {
|
||||
$variables = array(
|
||||
'user' => $this->userName,
|
||||
'repo' => $this->repositoryName,
|
||||
);
|
||||
foreach ($variables as $name => $value) {
|
||||
$url = str_replace('/:' . $name, '/' . urlencode($value), $url);
|
||||
}
|
||||
$url = 'https://api.github.com' . $url;
|
||||
|
||||
if ( !empty($queryParams) ) {
|
||||
$url = add_query_arg($queryParams, $url);
|
||||
}
|
||||
|
||||
return $url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the contents of a file from a specific branch or tag.
|
||||
*
|
||||
* @param string $path File name.
|
||||
* @param string $ref
|
||||
* @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error.
|
||||
*/
|
||||
public function getRemoteFile($path, $ref = 'master') {
|
||||
$apiUrl = '/repos/:user/:repo/contents/' . $path;
|
||||
$response = $this->api($apiUrl, array('ref' => $ref));
|
||||
|
||||
if ( is_wp_error($response) || !isset($response->content) || ($response->encoding !== 'base64') ) {
|
||||
return null;
|
||||
}
|
||||
return base64_decode($response->content);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a URL to download a ZIP archive of the specified branch/tag/etc.
|
||||
*
|
||||
* @param string $ref
|
||||
* @return string
|
||||
*/
|
||||
public function buildArchiveDownloadUrl($ref = 'master') {
|
||||
$url = sprintf(
|
||||
'https://api.github.com/repos/%1$s/%2$s/zipball/%3$s',
|
||||
urlencode($this->userName),
|
||||
urlencode($this->repositoryName),
|
||||
urlencode($ref)
|
||||
);
|
||||
return $url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a specific tag.
|
||||
*
|
||||
* @param string $tagName
|
||||
* @return void
|
||||
*/
|
||||
public function getTag($tagName) {
|
||||
//The current GitHub update checker doesn't use getTag, so I didn't bother to implement it.
|
||||
throw new LogicException('The ' . __METHOD__ . ' method is not implemented and should not be used.');
|
||||
}
|
||||
|
||||
public function setAuthentication($credentials) {
|
||||
parent::setAuthentication($credentials);
|
||||
$this->accessToken = is_string($credentials) ? $credentials : null;
|
||||
|
||||
//Optimization: Instead of filtering all HTTP requests, let's do it only when
|
||||
//WordPress is about to download an update.
|
||||
add_filter('upgrader_pre_download', array($this, 'addHttpRequestFilter'), 10, 1); //WP 3.7+
|
||||
}
|
||||
|
||||
/**
|
||||
* Figure out which reference (i.e tag or branch) contains the latest version.
|
||||
*
|
||||
* @param string $configBranch Start looking in this branch.
|
||||
* @return null|Puc_v4p11_Vcs_Reference
|
||||
*/
|
||||
public function chooseReference($configBranch) {
|
||||
$updateSource = null;
|
||||
|
||||
if ( $configBranch === 'master' ) {
|
||||
//Use the latest release.
|
||||
$updateSource = $this->getLatestRelease();
|
||||
if ( $updateSource === null ) {
|
||||
//Failing that, use the tag with the highest version number.
|
||||
$updateSource = $this->getLatestTag();
|
||||
}
|
||||
}
|
||||
//Alternatively, just use the branch itself.
|
||||
if ( empty($updateSource) ) {
|
||||
$updateSource = $this->getBranch($configBranch);
|
||||
}
|
||||
|
||||
return $updateSource;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable updating via release assets.
|
||||
*
|
||||
* If the latest release contains no usable assets, the update checker
|
||||
* will fall back to using the automatically generated ZIP archive.
|
||||
*
|
||||
* Private repositories will only work with WordPress 3.7 or later.
|
||||
*
|
||||
* @param string|null $fileNameRegex Optional. Use only those assets where the file name matches this regex.
|
||||
*/
|
||||
public function enableReleaseAssets($fileNameRegex = null) {
|
||||
$this->releaseAssetsEnabled = true;
|
||||
$this->assetFilterRegex = $fileNameRegex;
|
||||
$this->assetApiBaseUrl = sprintf(
|
||||
'//api.github.com/repos/%1$s/%2$s/releases/assets/',
|
||||
$this->userName,
|
||||
$this->repositoryName
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Does this asset match the file name regex?
|
||||
*
|
||||
* @param stdClass $releaseAsset
|
||||
* @return bool
|
||||
*/
|
||||
protected function matchesAssetFilter($releaseAsset) {
|
||||
if ( $this->assetFilterRegex === null ) {
|
||||
//The default is to accept all assets.
|
||||
return true;
|
||||
}
|
||||
return isset($releaseAsset->name) && preg_match($this->assetFilterRegex, $releaseAsset->name);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
* @param bool $result
|
||||
* @return bool
|
||||
*/
|
||||
public function addHttpRequestFilter($result) {
|
||||
if ( !$this->downloadFilterAdded && $this->isAuthenticationEnabled() ) {
|
||||
add_filter('http_request_args', array($this, 'setUpdateDownloadHeaders'), 10, 2);
|
||||
add_action('requests-requests.before_redirect', array($this, 'removeAuthHeaderFromRedirects'), 10, 4);
|
||||
$this->downloadFilterAdded = true;
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the HTTP headers that are necessary to download updates from private repositories.
|
||||
*
|
||||
* See GitHub docs:
|
||||
* @link https://developer.github.com/v3/repos/releases/#get-a-single-release-asset
|
||||
* @link https://developer.github.com/v3/auth/#basic-authentication
|
||||
*
|
||||
* @internal
|
||||
* @param array $requestArgs
|
||||
* @param string $url
|
||||
* @return array
|
||||
*/
|
||||
public function setUpdateDownloadHeaders($requestArgs, $url = '') {
|
||||
//Is WordPress trying to download one of our release assets?
|
||||
if ( $this->releaseAssetsEnabled && (strpos($url, $this->assetApiBaseUrl) !== false) ) {
|
||||
$requestArgs['headers']['Accept'] = 'application/octet-stream';
|
||||
}
|
||||
//Use Basic authentication, but only if the download is from our repository.
|
||||
$repoApiBaseUrl = $this->buildApiUrl('/repos/:user/:repo/', array());
|
||||
if ( $this->isAuthenticationEnabled() && (strpos($url, $repoApiBaseUrl)) === 0 ) {
|
||||
$requestArgs['headers']['Authorization'] = $this->getAuthorizationHeader();
|
||||
}
|
||||
return $requestArgs;
|
||||
}
|
||||
|
||||
/**
|
||||
* When following a redirect, the Requests library will automatically forward
|
||||
* the authorization header to other hosts. We don't want that because it breaks
|
||||
* AWS downloads and can leak authorization information.
|
||||
*
|
||||
* @internal
|
||||
* @param string $location
|
||||
* @param array $headers
|
||||
*/
|
||||
public function removeAuthHeaderFromRedirects(&$location, &$headers) {
|
||||
$repoApiBaseUrl = $this->buildApiUrl('/repos/:user/:repo/', array());
|
||||
if ( strpos($location, $repoApiBaseUrl) === 0 ) {
|
||||
return; //This request is going to GitHub, so it's fine.
|
||||
}
|
||||
//Remove the header.
|
||||
if ( isset($headers['Authorization']) ) {
|
||||
unset($headers['Authorization']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate the value of the "Authorization" header.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getAuthorizationHeader() {
|
||||
return 'Basic ' . base64_encode($this->userName . ':' . $this->accessToken);
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
+309
@@ -0,0 +1,309 @@
|
||||
<?php
|
||||
|
||||
if ( !class_exists('Puc_v4p11_Vcs_GitLabApi', false) ):
|
||||
|
||||
class Puc_v4p11_Vcs_GitLabApi extends Puc_v4p11_Vcs_Api {
|
||||
/**
|
||||
* @var string GitLab username.
|
||||
*/
|
||||
protected $userName;
|
||||
|
||||
/**
|
||||
* @var string GitLab server host.
|
||||
*/
|
||||
protected $repositoryHost;
|
||||
|
||||
/**
|
||||
* @var string Protocol used by this GitLab server: "http" or "https".
|
||||
*/
|
||||
protected $repositoryProtocol = 'https';
|
||||
|
||||
/**
|
||||
* @var string GitLab repository name.
|
||||
*/
|
||||
protected $repositoryName;
|
||||
|
||||
/**
|
||||
* @var string GitLab authentication token. Optional.
|
||||
*/
|
||||
protected $accessToken;
|
||||
|
||||
public function __construct($repositoryUrl, $accessToken = null, $subgroup = null) {
|
||||
//Parse the repository host to support custom hosts.
|
||||
$port = parse_url($repositoryUrl, PHP_URL_PORT);
|
||||
if ( !empty($port) ) {
|
||||
$port = ':' . $port;
|
||||
}
|
||||
$this->repositoryHost = parse_url($repositoryUrl, PHP_URL_HOST) . $port;
|
||||
|
||||
if ( $this->repositoryHost !== 'gitlab.com' ) {
|
||||
$this->repositoryProtocol = parse_url($repositoryUrl, PHP_URL_SCHEME);
|
||||
}
|
||||
|
||||
//Find the repository information
|
||||
$path = parse_url($repositoryUrl, PHP_URL_PATH);
|
||||
if ( preg_match('@^/?(?P<username>[^/]+?)/(?P<repository>[^/#?&]+?)/?$@', $path, $matches) ) {
|
||||
$this->userName = $matches['username'];
|
||||
$this->repositoryName = $matches['repository'];
|
||||
} elseif ( ($this->repositoryHost === 'gitlab.com') ) {
|
||||
//This is probably a repository in a subgroup, e.g. "/organization/category/repo".
|
||||
$parts = explode('/', trim($path, '/'));
|
||||
if ( count($parts) < 3 ) {
|
||||
throw new InvalidArgumentException('Invalid GitLab.com repository URL: "' . $repositoryUrl . '"');
|
||||
}
|
||||
$lastPart = array_pop($parts);
|
||||
$this->userName = implode('/', $parts);
|
||||
$this->repositoryName = $lastPart;
|
||||
} else {
|
||||
//There could be subgroups in the URL: gitlab.domain.com/group/subgroup/subgroup2/repository
|
||||
if ( $subgroup !== null ) {
|
||||
$path = str_replace(trailingslashit($subgroup), '', $path);
|
||||
}
|
||||
|
||||
//This is not a traditional url, it could be gitlab is in a deeper subdirectory.
|
||||
//Get the path segments.
|
||||
$segments = explode('/', untrailingslashit(ltrim($path, '/')));
|
||||
|
||||
//We need at least /user-name/repository-name/
|
||||
if ( count($segments) < 2 ) {
|
||||
throw new InvalidArgumentException('Invalid GitLab repository URL: "' . $repositoryUrl . '"');
|
||||
}
|
||||
|
||||
//Get the username and repository name.
|
||||
$usernameRepo = array_splice($segments, -2, 2);
|
||||
$this->userName = $usernameRepo[0];
|
||||
$this->repositoryName = $usernameRepo[1];
|
||||
|
||||
//Append the remaining segments to the host if there are segments left.
|
||||
if ( count($segments) > 0 ) {
|
||||
$this->repositoryHost = trailingslashit($this->repositoryHost) . implode('/', $segments);
|
||||
}
|
||||
|
||||
//Add subgroups to username.
|
||||
if ( $subgroup !== null ) {
|
||||
$this->userName = $usernameRepo[0] . '/' . untrailingslashit($subgroup);
|
||||
}
|
||||
}
|
||||
|
||||
parent::__construct($repositoryUrl, $accessToken);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the latest release from GitLab.
|
||||
*
|
||||
* @return Puc_v4p11_Vcs_Reference|null
|
||||
*/
|
||||
public function getLatestRelease() {
|
||||
return $this->getLatestTag();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the tag that looks like the highest version number.
|
||||
*
|
||||
* @return Puc_v4p11_Vcs_Reference|null
|
||||
*/
|
||||
public function getLatestTag() {
|
||||
$tags = $this->api('/:id/repository/tags');
|
||||
if ( is_wp_error($tags) || empty($tags) || !is_array($tags) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$versionTags = $this->sortTagsByVersion($tags);
|
||||
if ( empty($versionTags) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$tag = $versionTags[0];
|
||||
return new Puc_v4p11_Vcs_Reference(array(
|
||||
'name' => $tag->name,
|
||||
'version' => ltrim($tag->name, 'v'),
|
||||
'downloadUrl' => $this->buildArchiveDownloadUrl($tag->name),
|
||||
'apiResponse' => $tag,
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a branch by name.
|
||||
*
|
||||
* @param string $branchName
|
||||
* @return null|Puc_v4p11_Vcs_Reference
|
||||
*/
|
||||
public function getBranch($branchName) {
|
||||
$branch = $this->api('/:id/repository/branches/' . $branchName);
|
||||
if ( is_wp_error($branch) || empty($branch) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$reference = new Puc_v4p11_Vcs_Reference(array(
|
||||
'name' => $branch->name,
|
||||
'downloadUrl' => $this->buildArchiveDownloadUrl($branch->name),
|
||||
'apiResponse' => $branch,
|
||||
));
|
||||
|
||||
if ( isset($branch->commit, $branch->commit->committed_date) ) {
|
||||
$reference->updated = $branch->commit->committed_date;
|
||||
}
|
||||
|
||||
return $reference;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the timestamp of the latest commit that changed the specified branch or tag.
|
||||
*
|
||||
* @param string $ref Reference name (e.g. branch or tag).
|
||||
* @return string|null
|
||||
*/
|
||||
public function getLatestCommitTime($ref) {
|
||||
$commits = $this->api('/:id/repository/commits/', array('ref_name' => $ref));
|
||||
if ( is_wp_error($commits) || !is_array($commits) || !isset($commits[0]) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $commits[0]->committed_date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform a GitLab API request.
|
||||
*
|
||||
* @param string $url
|
||||
* @param array $queryParams
|
||||
* @return mixed|WP_Error
|
||||
*/
|
||||
protected function api($url, $queryParams = array()) {
|
||||
$baseUrl = $url;
|
||||
$url = $this->buildApiUrl($url, $queryParams);
|
||||
|
||||
$options = array('timeout' => 10);
|
||||
if ( !empty($this->httpFilterName) ) {
|
||||
$options = apply_filters($this->httpFilterName, $options);
|
||||
}
|
||||
|
||||
$response = wp_remote_get($url, $options);
|
||||
if ( is_wp_error($response) ) {
|
||||
do_action('puc_api_error', $response, null, $url, $this->slug);
|
||||
return $response;
|
||||
}
|
||||
|
||||
$code = wp_remote_retrieve_response_code($response);
|
||||
$body = wp_remote_retrieve_body($response);
|
||||
if ( $code === 200 ) {
|
||||
return json_decode($body);
|
||||
}
|
||||
|
||||
$error = new WP_Error(
|
||||
'puc-gitlab-http-error',
|
||||
sprintf('GitLab API error. URL: "%s", HTTP status code: %d.', $baseUrl, $code)
|
||||
);
|
||||
do_action('puc_api_error', $error, $response, $url, $this->slug);
|
||||
|
||||
return $error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a fully qualified URL for an API request.
|
||||
*
|
||||
* @param string $url
|
||||
* @param array $queryParams
|
||||
* @return string
|
||||
*/
|
||||
protected function buildApiUrl($url, $queryParams) {
|
||||
$variables = array(
|
||||
'user' => $this->userName,
|
||||
'repo' => $this->repositoryName,
|
||||
'id' => $this->userName . '/' . $this->repositoryName,
|
||||
);
|
||||
|
||||
foreach ($variables as $name => $value) {
|
||||
$url = str_replace("/:{$name}", '/' . urlencode($value), $url);
|
||||
}
|
||||
|
||||
$url = substr($url, 1);
|
||||
$url = sprintf('%1$s://%2$s/api/v4/projects/%3$s', $this->repositoryProtocol, $this->repositoryHost, $url);
|
||||
|
||||
if ( !empty($this->accessToken) ) {
|
||||
$queryParams['private_token'] = $this->accessToken;
|
||||
}
|
||||
|
||||
if ( !empty($queryParams) ) {
|
||||
$url = add_query_arg($queryParams, $url);
|
||||
}
|
||||
|
||||
return $url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the contents of a file from a specific branch or tag.
|
||||
*
|
||||
* @param string $path File name.
|
||||
* @param string $ref
|
||||
* @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error.
|
||||
*/
|
||||
public function getRemoteFile($path, $ref = 'master') {
|
||||
$response = $this->api('/:id/repository/files/' . $path, array('ref' => $ref));
|
||||
if ( is_wp_error($response) || !isset($response->content) || $response->encoding !== 'base64' ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return base64_decode($response->content);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a URL to download a ZIP archive of the specified branch/tag/etc.
|
||||
*
|
||||
* @param string $ref
|
||||
* @return string
|
||||
*/
|
||||
public function buildArchiveDownloadUrl($ref = 'master') {
|
||||
$url = sprintf(
|
||||
'%1$s://%2$s/api/v4/projects/%3$s/repository/archive.zip',
|
||||
$this->repositoryProtocol,
|
||||
$this->repositoryHost,
|
||||
urlencode($this->userName . '/' . $this->repositoryName)
|
||||
);
|
||||
$url = add_query_arg('sha', urlencode($ref), $url);
|
||||
|
||||
if ( !empty($this->accessToken) ) {
|
||||
$url = add_query_arg('private_token', $this->accessToken, $url);
|
||||
}
|
||||
|
||||
return $url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a specific tag.
|
||||
*
|
||||
* @param string $tagName
|
||||
* @return void
|
||||
*/
|
||||
public function getTag($tagName) {
|
||||
throw new LogicException('The ' . __METHOD__ . ' method is not implemented and should not be used.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Figure out which reference (i.e tag or branch) contains the latest version.
|
||||
*
|
||||
* @param string $configBranch Start looking in this branch.
|
||||
* @return null|Puc_v4p11_Vcs_Reference
|
||||
*/
|
||||
public function chooseReference($configBranch) {
|
||||
$updateSource = null;
|
||||
|
||||
// GitLab doesn't handle releases the same as GitHub so just use the latest tag
|
||||
if ( $configBranch === 'master' ) {
|
||||
$updateSource = $this->getLatestTag();
|
||||
}
|
||||
|
||||
if ( empty($updateSource) ) {
|
||||
$updateSource = $this->getBranch($configBranch);
|
||||
}
|
||||
|
||||
return $updateSource;
|
||||
}
|
||||
|
||||
public function setAuthentication($credentials) {
|
||||
parent::setAuthentication($credentials);
|
||||
$this->accessToken = is_string($credentials) ? $credentials : null;
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
<?php
|
||||
if ( !class_exists('Puc_v4p11_Vcs_PluginUpdateChecker') ):
|
||||
|
||||
class Puc_v4p11_Vcs_PluginUpdateChecker extends Puc_v4p11_Plugin_UpdateChecker implements Puc_v4p11_Vcs_BaseChecker {
|
||||
/**
|
||||
* @var string The branch where to look for updates. Defaults to "master".
|
||||
*/
|
||||
protected $branch = 'master';
|
||||
|
||||
/**
|
||||
* @var Puc_v4p11_Vcs_Api Repository API client.
|
||||
*/
|
||||
protected $api = null;
|
||||
|
||||
/**
|
||||
* Puc_v4p11_Vcs_PluginUpdateChecker constructor.
|
||||
*
|
||||
* @param Puc_v4p11_Vcs_Api $api
|
||||
* @param string $pluginFile
|
||||
* @param string $slug
|
||||
* @param int $checkPeriod
|
||||
* @param string $optionName
|
||||
* @param string $muPluginFile
|
||||
*/
|
||||
public function __construct($api, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = '') {
|
||||
$this->api = $api;
|
||||
$this->api->setHttpFilterName($this->getUniqueName('request_info_options'));
|
||||
|
||||
parent::__construct($api->getRepositoryUrl(), $pluginFile, $slug, $checkPeriod, $optionName, $muPluginFile);
|
||||
|
||||
$this->api->setSlug($this->slug);
|
||||
}
|
||||
|
||||
public function requestInfo($unusedParameter = null) {
|
||||
//We have to make several remote API requests to gather all the necessary info
|
||||
//which can take a while on slow networks.
|
||||
if ( function_exists('set_time_limit') ) {
|
||||
@set_time_limit(60);
|
||||
}
|
||||
|
||||
$api = $this->api;
|
||||
$api->setLocalDirectory($this->package->getAbsoluteDirectoryPath());
|
||||
|
||||
$info = new Puc_v4p11_Plugin_Info();
|
||||
$info->filename = $this->pluginFile;
|
||||
$info->slug = $this->slug;
|
||||
|
||||
$this->setInfoFromHeader($this->package->getPluginHeader(), $info);
|
||||
|
||||
//Pick a branch or tag.
|
||||
$updateSource = $api->chooseReference($this->branch);
|
||||
if ( $updateSource ) {
|
||||
$ref = $updateSource->name;
|
||||
$info->version = $updateSource->version;
|
||||
$info->last_updated = $updateSource->updated;
|
||||
$info->download_url = $updateSource->downloadUrl;
|
||||
|
||||
if ( !empty($updateSource->changelog) ) {
|
||||
$info->sections['changelog'] = $updateSource->changelog;
|
||||
}
|
||||
if ( isset($updateSource->downloadCount) ) {
|
||||
$info->downloaded = $updateSource->downloadCount;
|
||||
}
|
||||
} else {
|
||||
//There's probably a network problem or an authentication error.
|
||||
do_action(
|
||||
'puc_api_error',
|
||||
new WP_Error(
|
||||
'puc-no-update-source',
|
||||
'Could not retrieve version information from the repository. '
|
||||
. 'This usually means that the update checker either can\'t connect '
|
||||
. 'to the repository or it\'s configured incorrectly.'
|
||||
),
|
||||
null, null, $this->slug
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
//Get headers from the main plugin file in this branch/tag. Its "Version" header and other metadata
|
||||
//are what the WordPress install will actually see after upgrading, so they take precedence over releases/tags.
|
||||
$mainPluginFile = basename($this->pluginFile);
|
||||
$remotePlugin = $api->getRemoteFile($mainPluginFile, $ref);
|
||||
if ( !empty($remotePlugin) ) {
|
||||
$remoteHeader = $this->package->getFileHeader($remotePlugin);
|
||||
$this->setInfoFromHeader($remoteHeader, $info);
|
||||
}
|
||||
|
||||
//Try parsing readme.txt. If it's formatted according to WordPress.org standards, it will contain
|
||||
//a lot of useful information like the required/tested WP version, changelog, and so on.
|
||||
if ( $this->readmeTxtExistsLocally() ) {
|
||||
$this->setInfoFromRemoteReadme($ref, $info);
|
||||
}
|
||||
|
||||
//The changelog might be in a separate file.
|
||||
if ( empty($info->sections['changelog']) ) {
|
||||
$info->sections['changelog'] = $api->getRemoteChangelog($ref, $this->package->getAbsoluteDirectoryPath());
|
||||
if ( empty($info->sections['changelog']) ) {
|
||||
$info->sections['changelog'] = __('There is no changelog available.', 'plugin-update-checker');
|
||||
}
|
||||
}
|
||||
|
||||
if ( empty($info->last_updated) ) {
|
||||
//Fetch the latest commit that changed the tag or branch and use it as the "last_updated" date.
|
||||
$latestCommitTime = $api->getLatestCommitTime($ref);
|
||||
if ( $latestCommitTime !== null ) {
|
||||
$info->last_updated = $latestCommitTime;
|
||||
}
|
||||
}
|
||||
|
||||
$info = apply_filters($this->getUniqueName('request_info_result'), $info, null);
|
||||
return $info;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the currently installed version has a readme.txt file.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function readmeTxtExistsLocally() {
|
||||
return $this->package->fileExists($this->api->getLocalReadmeName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy plugin metadata from a file header to a Plugin Info object.
|
||||
*
|
||||
* @param array $fileHeader
|
||||
* @param Puc_v4p11_Plugin_Info $pluginInfo
|
||||
*/
|
||||
protected function setInfoFromHeader($fileHeader, $pluginInfo) {
|
||||
$headerToPropertyMap = array(
|
||||
'Version' => 'version',
|
||||
'Name' => 'name',
|
||||
'PluginURI' => 'homepage',
|
||||
'Author' => 'author',
|
||||
'AuthorName' => 'author',
|
||||
'AuthorURI' => 'author_homepage',
|
||||
|
||||
'Requires WP' => 'requires',
|
||||
'Tested WP' => 'tested',
|
||||
'Requires at least' => 'requires',
|
||||
'Tested up to' => 'tested',
|
||||
|
||||
'Requires PHP' => 'requires_php',
|
||||
);
|
||||
foreach ($headerToPropertyMap as $headerName => $property) {
|
||||
if ( isset($fileHeader[$headerName]) && !empty($fileHeader[$headerName]) ) {
|
||||
$pluginInfo->$property = $fileHeader[$headerName];
|
||||
}
|
||||
}
|
||||
|
||||
if ( !empty($fileHeader['Description']) ) {
|
||||
$pluginInfo->sections['description'] = $fileHeader['Description'];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy plugin metadata from the remote readme.txt file.
|
||||
*
|
||||
* @param string $ref GitHub tag or branch where to look for the readme.
|
||||
* @param Puc_v4p11_Plugin_Info $pluginInfo
|
||||
*/
|
||||
protected function setInfoFromRemoteReadme($ref, $pluginInfo) {
|
||||
$readme = $this->api->getRemoteReadme($ref);
|
||||
if ( empty($readme) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( isset($readme['sections']) ) {
|
||||
$pluginInfo->sections = array_merge($pluginInfo->sections, $readme['sections']);
|
||||
}
|
||||
if ( !empty($readme['tested_up_to']) ) {
|
||||
$pluginInfo->tested = $readme['tested_up_to'];
|
||||
}
|
||||
if ( !empty($readme['requires_at_least']) ) {
|
||||
$pluginInfo->requires = $readme['requires_at_least'];
|
||||
}
|
||||
if ( !empty($readme['requires_php']) ) {
|
||||
$pluginInfo->requires_php = $readme['requires_php'];
|
||||
}
|
||||
|
||||
if ( isset($readme['upgrade_notice'], $readme['upgrade_notice'][$pluginInfo->version]) ) {
|
||||
$pluginInfo->upgrade_notice = $readme['upgrade_notice'][$pluginInfo->version];
|
||||
}
|
||||
}
|
||||
|
||||
public function setBranch($branch) {
|
||||
$this->branch = $branch;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setAuthentication($credentials) {
|
||||
$this->api->setAuthentication($credentials);
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getVcsApi() {
|
||||
return $this->api;
|
||||
}
|
||||
|
||||
public function getUpdate() {
|
||||
$update = parent::getUpdate();
|
||||
|
||||
if ( isset($update) && !empty($update->download_url) ) {
|
||||
$update->download_url = $this->api->signDownloadUrl($update->download_url);
|
||||
}
|
||||
|
||||
return $update;
|
||||
}
|
||||
|
||||
public function onDisplayConfiguration($panel) {
|
||||
parent::onDisplayConfiguration($panel);
|
||||
$panel->row('Branch', $this->branch);
|
||||
$panel->row('Authentication enabled', $this->api->isAuthenticationEnabled() ? 'Yes' : 'No');
|
||||
$panel->row('API client', get_class($this->api));
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
if ( !class_exists('Puc_v4p11_Vcs_Reference', false) ):
|
||||
|
||||
/**
|
||||
* This class represents a VCS branch or tag. It's intended as a read only, short-lived container
|
||||
* that only exists to provide a limited degree of type checking.
|
||||
*
|
||||
* @property string $name
|
||||
* @property string|null version
|
||||
* @property string $downloadUrl
|
||||
* @property string $updated
|
||||
*
|
||||
* @property string|null $changelog
|
||||
* @property int|null $downloadCount
|
||||
*/
|
||||
class Puc_v4p11_Vcs_Reference {
|
||||
private $properties = array();
|
||||
|
||||
public function __construct($properties = array()) {
|
||||
$this->properties = $properties;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @return mixed|null
|
||||
*/
|
||||
public function __get($name) {
|
||||
return array_key_exists($name, $this->properties) ? $this->properties[$name] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @param mixed $value
|
||||
*/
|
||||
public function __set($name, $value) {
|
||||
$this->properties[$name] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @return bool
|
||||
*/
|
||||
public function __isset($name) {
|
||||
return isset($this->properties[$name]);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
endif;
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
if ( !class_exists('Puc_v4p11_Vcs_ThemeUpdateChecker', false) ):
|
||||
|
||||
class Puc_v4p11_Vcs_ThemeUpdateChecker extends Puc_v4p11_Theme_UpdateChecker implements Puc_v4p11_Vcs_BaseChecker {
|
||||
/**
|
||||
* @var string The branch where to look for updates. Defaults to "master".
|
||||
*/
|
||||
protected $branch = 'master';
|
||||
|
||||
/**
|
||||
* @var Puc_v4p11_Vcs_Api Repository API client.
|
||||
*/
|
||||
protected $api = null;
|
||||
|
||||
/**
|
||||
* Puc_v4p11_Vcs_ThemeUpdateChecker constructor.
|
||||
*
|
||||
* @param Puc_v4p11_Vcs_Api $api
|
||||
* @param null $stylesheet
|
||||
* @param null $customSlug
|
||||
* @param int $checkPeriod
|
||||
* @param string $optionName
|
||||
*/
|
||||
public function __construct($api, $stylesheet = null, $customSlug = null, $checkPeriod = 12, $optionName = '') {
|
||||
$this->api = $api;
|
||||
$this->api->setHttpFilterName($this->getUniqueName('request_update_options'));
|
||||
|
||||
parent::__construct($api->getRepositoryUrl(), $stylesheet, $customSlug, $checkPeriod, $optionName);
|
||||
|
||||
$this->api->setSlug($this->slug);
|
||||
}
|
||||
|
||||
public function requestUpdate() {
|
||||
$api = $this->api;
|
||||
$api->setLocalDirectory($this->package->getAbsoluteDirectoryPath());
|
||||
|
||||
$update = new Puc_v4p11_Theme_Update();
|
||||
$update->slug = $this->slug;
|
||||
|
||||
//Figure out which reference (tag or branch) we'll use to get the latest version of the theme.
|
||||
$updateSource = $api->chooseReference($this->branch);
|
||||
if ( $updateSource ) {
|
||||
$ref = $updateSource->name;
|
||||
$update->download_url = $updateSource->downloadUrl;
|
||||
} else {
|
||||
do_action(
|
||||
'puc_api_error',
|
||||
new WP_Error(
|
||||
'puc-no-update-source',
|
||||
'Could not retrieve version information from the repository. '
|
||||
. 'This usually means that the update checker either can\'t connect '
|
||||
. 'to the repository or it\'s configured incorrectly.'
|
||||
),
|
||||
null, null, $this->slug
|
||||
);
|
||||
$ref = $this->branch;
|
||||
}
|
||||
|
||||
//Get headers from the main stylesheet in this branch/tag. Its "Version" header and other metadata
|
||||
//are what the WordPress install will actually see after upgrading, so they take precedence over releases/tags.
|
||||
$remoteHeader = $this->package->getFileHeader($api->getRemoteFile('style.css', $ref));
|
||||
$update->version = Puc_v4p11_Utils::findNotEmpty(array(
|
||||
$remoteHeader['Version'],
|
||||
Puc_v4p11_Utils::get($updateSource, 'version'),
|
||||
));
|
||||
|
||||
//The details URL defaults to the Theme URI header or the repository URL.
|
||||
$update->details_url = Puc_v4p11_Utils::findNotEmpty(array(
|
||||
$remoteHeader['ThemeURI'],
|
||||
$this->package->getHeaderValue('ThemeURI'),
|
||||
$this->metadataUrl,
|
||||
));
|
||||
|
||||
if ( empty($update->version) ) {
|
||||
//It looks like we didn't find a valid update after all.
|
||||
$update = null;
|
||||
}
|
||||
|
||||
$update = $this->filterUpdateResult($update);
|
||||
return $update;
|
||||
}
|
||||
|
||||
//FIXME: This is duplicated code. Both theme and plugin subclasses that use VCS share these methods.
|
||||
|
||||
public function setBranch($branch) {
|
||||
$this->branch = $branch;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setAuthentication($credentials) {
|
||||
$this->api->setAuthentication($credentials);
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getVcsApi() {
|
||||
return $this->api;
|
||||
}
|
||||
|
||||
public function getUpdate() {
|
||||
$update = parent::getUpdate();
|
||||
|
||||
if ( isset($update) && !empty($update->download_url) ) {
|
||||
$update->download_url = $this->api->signDownloadUrl($update->download_url);
|
||||
}
|
||||
|
||||
return $update;
|
||||
}
|
||||
|
||||
public function onDisplayConfiguration($panel) {
|
||||
parent::onDisplayConfiguration($panel);
|
||||
$panel->row('Branch', $this->branch);
|
||||
$panel->row('Authentication enabled', $this->api->isAuthenticationEnabled() ? 'Yes' : 'No');
|
||||
$panel->row('API client', get_class($this->api));
|
||||
}
|
||||
}
|
||||
|
||||
endif;
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
Copyright (c) 2017 Jānis Elsts
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
Vendored
+28
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
require dirname(__FILE__) . '/Puc/v4p11/Autoloader.php';
|
||||
new Puc_v4p11_Autoloader();
|
||||
|
||||
require dirname(__FILE__) . '/Puc/v4p11/Factory.php';
|
||||
require dirname(__FILE__) . '/Puc/v4/Factory.php';
|
||||
|
||||
//Register classes defined in this version with the factory.
|
||||
foreach (
|
||||
array(
|
||||
'Plugin_UpdateChecker' => 'Puc_v4p11_Plugin_UpdateChecker',
|
||||
'Theme_UpdateChecker' => 'Puc_v4p11_Theme_UpdateChecker',
|
||||
|
||||
'Vcs_PluginUpdateChecker' => 'Puc_v4p11_Vcs_PluginUpdateChecker',
|
||||
'Vcs_ThemeUpdateChecker' => 'Puc_v4p11_Vcs_ThemeUpdateChecker',
|
||||
|
||||
'GitHubApi' => 'Puc_v4p11_Vcs_GitHubApi',
|
||||
'BitBucketApi' => 'Puc_v4p11_Vcs_BitBucketApi',
|
||||
'GitLabApi' => 'Puc_v4p11_Vcs_GitLabApi',
|
||||
)
|
||||
as $pucGeneralClass => $pucVersionedClass
|
||||
) {
|
||||
Puc_v4_Factory::addVersion($pucGeneralClass, $pucVersionedClass, '4.11');
|
||||
//Also add it to the minor-version factory in case the major-version factory
|
||||
//was already defined by another, older version of the update checker.
|
||||
Puc_v4p11_Factory::addVersion($pucGeneralClass, $pucVersionedClass, '4.11');
|
||||
}
|
||||
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
/**
|
||||
* Plugin Update Checker Library 4.11
|
||||
* http://w-shadow.com/
|
||||
*
|
||||
* Copyright 2021 Janis Elsts
|
||||
* Released under the MIT license. See license.txt for details.
|
||||
*/
|
||||
|
||||
require dirname(__FILE__) . '/load-v4p11.php';
|
||||
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
if ( !class_exists('Parsedown', false) ) {
|
||||
//Load the Parsedown version that's compatible with the current PHP version.
|
||||
if ( version_compare(PHP_VERSION, '5.3.0', '>=') ) {
|
||||
require __DIR__ . '/ParsedownModern.php';
|
||||
} else {
|
||||
require __DIR__ . '/ParsedownLegacy.php';
|
||||
}
|
||||
}
|
||||
+1535
File diff suppressed because it is too large
Load Diff
+1538
File diff suppressed because it is too large
Load Diff
+348
@@ -0,0 +1,348 @@
|
||||
<?php
|
||||
|
||||
if ( !class_exists('PucReadmeParser', false) ):
|
||||
|
||||
/**
|
||||
* This is a slightly modified version of github.com/markjaquith/WordPress-Plugin-Readme-Parser
|
||||
* It uses Parsedown instead of the "Markdown Extra" parser.
|
||||
*/
|
||||
|
||||
class PucReadmeParser {
|
||||
|
||||
function __construct() {
|
||||
// This space intentionally blank
|
||||
}
|
||||
|
||||
function parse_readme( $file ) {
|
||||
$file_contents = @implode('', @file($file));
|
||||
return $this->parse_readme_contents( $file_contents );
|
||||
}
|
||||
|
||||
function parse_readme_contents( $file_contents ) {
|
||||
$file_contents = str_replace(array("\r\n", "\r"), "\n", $file_contents);
|
||||
$file_contents = trim($file_contents);
|
||||
if ( 0 === strpos( $file_contents, "\xEF\xBB\xBF" ) )
|
||||
$file_contents = substr( $file_contents, 3 );
|
||||
|
||||
// Markdown transformations
|
||||
$file_contents = preg_replace( "|^###([^#]+)#*?\s*?\n|im", '=$1='."\n", $file_contents );
|
||||
$file_contents = preg_replace( "|^##([^#]+)#*?\s*?\n|im", '==$1=='."\n", $file_contents );
|
||||
$file_contents = preg_replace( "|^#([^#]+)#*?\s*?\n|im", '===$1==='."\n", $file_contents );
|
||||
|
||||
// === Plugin Name ===
|
||||
// Must be the very first thing.
|
||||
if ( !preg_match('|^===(.*)===|', $file_contents, $_name) )
|
||||
return array(); // require a name
|
||||
$name = trim($_name[1], '=');
|
||||
$name = $this->sanitize_text( $name );
|
||||
|
||||
$file_contents = $this->chop_string( $file_contents, $_name[0] );
|
||||
|
||||
|
||||
// Requires at least: 1.5
|
||||
if ( preg_match('|Requires at least:(.*)|i', $file_contents, $_requires_at_least) )
|
||||
$requires_at_least = $this->sanitize_text($_requires_at_least[1]);
|
||||
else
|
||||
$requires_at_least = NULL;
|
||||
|
||||
|
||||
// Tested up to: 2.1
|
||||
if ( preg_match('|Tested up to:(.*)|i', $file_contents, $_tested_up_to) )
|
||||
$tested_up_to = $this->sanitize_text( $_tested_up_to[1] );
|
||||
else
|
||||
$tested_up_to = NULL;
|
||||
|
||||
// Requires PHP: 5.2.4
|
||||
if ( preg_match('|Requires PHP:(.*)|i', $file_contents, $_requires_php) ) {
|
||||
$requires_php = $this->sanitize_text( $_requires_php[1] );
|
||||
} else {
|
||||
$requires_php = null;
|
||||
}
|
||||
|
||||
// Stable tag: 10.4-ride-the-fire-eagle-danger-day
|
||||
if ( preg_match('|Stable tag:(.*)|i', $file_contents, $_stable_tag) )
|
||||
$stable_tag = $this->sanitize_text( $_stable_tag[1] );
|
||||
else
|
||||
$stable_tag = NULL; // we assume trunk, but don't set it here to tell the difference between specified trunk and default trunk
|
||||
|
||||
|
||||
// Tags: some tag, another tag, we like tags
|
||||
if ( preg_match('|Tags:(.*)|i', $file_contents, $_tags) ) {
|
||||
$tags = preg_split('|,[\s]*?|', trim($_tags[1]));
|
||||
foreach ( array_keys($tags) as $t )
|
||||
$tags[$t] = $this->sanitize_text( $tags[$t] );
|
||||
} else {
|
||||
$tags = array();
|
||||
}
|
||||
|
||||
|
||||
// Contributors: markjaquith, mdawaffe, zefrank
|
||||
$contributors = array();
|
||||
if ( preg_match('|Contributors:(.*)|i', $file_contents, $_contributors) ) {
|
||||
$temp_contributors = preg_split('|,[\s]*|', trim($_contributors[1]));
|
||||
foreach ( array_keys($temp_contributors) as $c ) {
|
||||
$tmp_sanitized = $this->user_sanitize( $temp_contributors[$c] );
|
||||
if ( strlen(trim($tmp_sanitized)) > 0 )
|
||||
$contributors[$c] = $tmp_sanitized;
|
||||
unset($tmp_sanitized);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Donate Link: URL
|
||||
if ( preg_match('|Donate link:(.*)|i', $file_contents, $_donate_link) )
|
||||
$donate_link = esc_url( $_donate_link[1] );
|
||||
else
|
||||
$donate_link = NULL;
|
||||
|
||||
|
||||
// togs, conts, etc are optional and order shouldn't matter. So we chop them only after we've grabbed their values.
|
||||
foreach ( array('tags', 'contributors', 'requires_at_least', 'tested_up_to', 'stable_tag', 'donate_link') as $chop ) {
|
||||
if ( $$chop ) {
|
||||
$_chop = '_' . $chop;
|
||||
$file_contents = $this->chop_string( $file_contents, ${$_chop}[0] );
|
||||
}
|
||||
}
|
||||
|
||||
$file_contents = trim($file_contents);
|
||||
|
||||
|
||||
// short-description fu
|
||||
if ( !preg_match('/(^(.*?))^[\s]*=+?[\s]*.+?[\s]*=+?/ms', $file_contents, $_short_description) )
|
||||
$_short_description = array( 1 => &$file_contents, 2 => &$file_contents );
|
||||
$short_desc_filtered = $this->sanitize_text( $_short_description[2] );
|
||||
$short_desc_length = strlen($short_desc_filtered);
|
||||
$short_description = substr($short_desc_filtered, 0, 150);
|
||||
if ( $short_desc_length > strlen($short_description) )
|
||||
$truncated = true;
|
||||
else
|
||||
$truncated = false;
|
||||
if ( $_short_description[1] )
|
||||
$file_contents = $this->chop_string( $file_contents, $_short_description[1] ); // yes, the [1] is intentional
|
||||
|
||||
// == Section ==
|
||||
// Break into sections
|
||||
// $_sections[0] will be the title of the first section, $_sections[1] will be the content of the first section
|
||||
// the array alternates from there: title2, content2, title3, content3... and so forth
|
||||
$_sections = preg_split('/^[\s]*==[\s]*(.+?)[\s]*==/m', $file_contents, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
|
||||
|
||||
$sections = array();
|
||||
for ( $i=0; $i < count($_sections); $i +=2 ) {
|
||||
$title = $this->sanitize_text( $_sections[$i] );
|
||||
if ( isset($_sections[$i+1]) ) {
|
||||
$content = preg_replace('/(^[\s]*)=[\s]+(.+?)[\s]+=/m', '$1<h4>$2</h4>', $_sections[$i+1]);
|
||||
$content = $this->filter_text( $content, true );
|
||||
} else {
|
||||
$content = '';
|
||||
}
|
||||
$sections[str_replace(' ', '_', strtolower($title))] = array('title' => $title, 'content' => $content);
|
||||
}
|
||||
|
||||
|
||||
// Special sections
|
||||
// This is where we nab our special sections, so we can enforce their order and treat them differently, if needed
|
||||
// upgrade_notice is not a section, but parse it like it is for now
|
||||
$final_sections = array();
|
||||
foreach ( array('description', 'installation', 'frequently_asked_questions', 'screenshots', 'changelog', 'change_log', 'upgrade_notice') as $special_section ) {
|
||||
if ( isset($sections[$special_section]) ) {
|
||||
$final_sections[$special_section] = $sections[$special_section]['content'];
|
||||
unset($sections[$special_section]);
|
||||
}
|
||||
}
|
||||
if ( isset($final_sections['change_log']) && empty($final_sections['changelog']) )
|
||||
$final_sections['changelog'] = $final_sections['change_log'];
|
||||
|
||||
|
||||
$final_screenshots = array();
|
||||
if ( isset($final_sections['screenshots']) ) {
|
||||
preg_match_all('|<li>(.*?)</li>|s', $final_sections['screenshots'], $screenshots, PREG_SET_ORDER);
|
||||
if ( $screenshots ) {
|
||||
foreach ( (array) $screenshots as $ss )
|
||||
$final_screenshots[] = $ss[1];
|
||||
}
|
||||
}
|
||||
|
||||
// Parse the upgrade_notice section specially:
|
||||
// 1.0 => blah, 1.1 => fnord
|
||||
$upgrade_notice = array();
|
||||
if ( isset($final_sections['upgrade_notice']) ) {
|
||||
$split = preg_split( '#<h4>(.*?)</h4>#', $final_sections['upgrade_notice'], -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
|
||||
if ( count($split) >= 2 ) {
|
||||
for ( $i = 0; $i < count( $split ); $i += 2 ) {
|
||||
$upgrade_notice[$this->sanitize_text( $split[$i] )] = substr( $this->sanitize_text( $split[$i + 1] ), 0, 300 );
|
||||
}
|
||||
}
|
||||
unset( $final_sections['upgrade_notice'] );
|
||||
}
|
||||
|
||||
// No description?
|
||||
// No problem... we'll just fall back to the old style of description
|
||||
// We'll even let you use markup this time!
|
||||
$excerpt = false;
|
||||
if ( !isset($final_sections['description']) ) {
|
||||
$final_sections = array_merge(array('description' => $this->filter_text( $_short_description[2], true )), $final_sections);
|
||||
$excerpt = true;
|
||||
}
|
||||
|
||||
|
||||
// dump the non-special sections into $remaining_content
|
||||
// their order will be determined by their original order in the readme.txt
|
||||
$remaining_content = '';
|
||||
foreach ( $sections as $s_name => $s_data ) {
|
||||
$remaining_content .= "\n<h3>{$s_data['title']}</h3>\n{$s_data['content']}";
|
||||
}
|
||||
$remaining_content = trim($remaining_content);
|
||||
|
||||
|
||||
// All done!
|
||||
// $r['tags'] and $r['contributors'] are simple arrays
|
||||
// $r['sections'] is an array with named elements
|
||||
$r = array(
|
||||
'name' => $name,
|
||||
'tags' => $tags,
|
||||
'requires_at_least' => $requires_at_least,
|
||||
'tested_up_to' => $tested_up_to,
|
||||
'requires_php' => $requires_php,
|
||||
'stable_tag' => $stable_tag,
|
||||
'contributors' => $contributors,
|
||||
'donate_link' => $donate_link,
|
||||
'short_description' => $short_description,
|
||||
'screenshots' => $final_screenshots,
|
||||
'is_excerpt' => $excerpt,
|
||||
'is_truncated' => $truncated,
|
||||
'sections' => $final_sections,
|
||||
'remaining_content' => $remaining_content,
|
||||
'upgrade_notice' => $upgrade_notice
|
||||
);
|
||||
|
||||
return $r;
|
||||
}
|
||||
|
||||
function chop_string( $string, $chop ) { // chop a "prefix" from a string: Agressive! uses strstr not 0 === strpos
|
||||
if ( $_string = strstr($string, $chop) ) {
|
||||
$_string = substr($_string, strlen($chop));
|
||||
return trim($_string);
|
||||
} else {
|
||||
return trim($string);
|
||||
}
|
||||
}
|
||||
|
||||
function user_sanitize( $text, $strict = false ) { // whitelisted chars
|
||||
if ( function_exists('user_sanitize') ) // bbPress native
|
||||
return user_sanitize( $text, $strict );
|
||||
|
||||
if ( $strict ) {
|
||||
$text = preg_replace('/[^a-z0-9-]/i', '', $text);
|
||||
$text = preg_replace('|-+|', '-', $text);
|
||||
} else {
|
||||
$text = preg_replace('/[^a-z0-9_-]/i', '', $text);
|
||||
}
|
||||
return $text;
|
||||
}
|
||||
|
||||
function sanitize_text( $text ) { // not fancy
|
||||
$text = strip_tags($text);
|
||||
$text = esc_html($text);
|
||||
$text = trim($text);
|
||||
return $text;
|
||||
}
|
||||
|
||||
function filter_text( $text, $markdown = false ) { // fancy, Markdown
|
||||
$text = trim($text);
|
||||
|
||||
$text = call_user_func( array( __CLASS__, 'code_trick' ), $text, $markdown ); // A better parser than Markdown's for: backticks -> CODE
|
||||
|
||||
if ( $markdown ) { // Parse markdown.
|
||||
if ( !class_exists('Parsedown', false) ) {
|
||||
/** @noinspection PhpIncludeInspection */
|
||||
require_once(dirname(__FILE__) . '/Parsedown' . (version_compare(PHP_VERSION, '5.3.0', '>=') ? '' : 'Legacy') . '.php');
|
||||
}
|
||||
$instance = Parsedown::instance();
|
||||
$text = $instance->text($text);
|
||||
}
|
||||
|
||||
$allowed = array(
|
||||
'a' => array(
|
||||
'href' => array(),
|
||||
'title' => array(),
|
||||
'rel' => array()),
|
||||
'blockquote' => array('cite' => array()),
|
||||
'br' => array(),
|
||||
'p' => array(),
|
||||
'code' => array(),
|
||||
'pre' => array(),
|
||||
'em' => array(),
|
||||
'strong' => array(),
|
||||
'ul' => array(),
|
||||
'ol' => array(),
|
||||
'li' => array(),
|
||||
'h3' => array(),
|
||||
'h4' => array()
|
||||
);
|
||||
|
||||
$text = balanceTags($text);
|
||||
|
||||
$text = wp_kses( $text, $allowed );
|
||||
$text = trim($text);
|
||||
return $text;
|
||||
}
|
||||
|
||||
function code_trick( $text, $markdown ) { // Don't use bbPress native function - it's incompatible with Markdown
|
||||
// If doing markdown, first take any user formatted code blocks and turn them into backticks so that
|
||||
// markdown will preserve things like underscores in code blocks
|
||||
if ( $markdown )
|
||||
$text = preg_replace_callback("!(<pre><code>|<code>)(.*?)(</code></pre>|</code>)!s", array( __CLASS__,'decodeit'), $text);
|
||||
|
||||
$text = str_replace(array("\r\n", "\r"), "\n", $text);
|
||||
if ( !$markdown ) {
|
||||
// This gets the "inline" code blocks, but can't be used with Markdown.
|
||||
$text = preg_replace_callback("|(`)(.*?)`|", array( __CLASS__, 'encodeit'), $text);
|
||||
// This gets the "block level" code blocks and converts them to PRE CODE
|
||||
$text = preg_replace_callback("!(^|\n)`(.*?)`!s", array( __CLASS__, 'encodeit'), $text);
|
||||
} else {
|
||||
// Markdown can do inline code, we convert bbPress style block level code to Markdown style
|
||||
$text = preg_replace_callback("!(^|\n)([ \t]*?)`(.*?)`!s", array( __CLASS__, 'indent'), $text);
|
||||
}
|
||||
return $text;
|
||||
}
|
||||
|
||||
function indent( $matches ) {
|
||||
$text = $matches[3];
|
||||
$text = preg_replace('|^|m', $matches[2] . ' ', $text);
|
||||
return $matches[1] . $text;
|
||||
}
|
||||
|
||||
function encodeit( $matches ) {
|
||||
if ( function_exists('encodeit') ) // bbPress native
|
||||
return encodeit( $matches );
|
||||
|
||||
$text = trim($matches[2]);
|
||||
$text = htmlspecialchars($text, ENT_QUOTES);
|
||||
$text = str_replace(array("\r\n", "\r"), "\n", $text);
|
||||
$text = preg_replace("|\n\n\n+|", "\n\n", $text);
|
||||
$text = str_replace('&lt;', '<', $text);
|
||||
$text = str_replace('&gt;', '>', $text);
|
||||
$text = "<code>$text</code>";
|
||||
if ( "`" != $matches[1] )
|
||||
$text = "<pre>$text</pre>";
|
||||
return $text;
|
||||
}
|
||||
|
||||
function decodeit( $matches ) {
|
||||
if ( function_exists('decodeit') ) // bbPress native
|
||||
return decodeit( $matches );
|
||||
|
||||
$text = $matches[2];
|
||||
$trans_table = array_flip(get_html_translation_table(HTML_ENTITIES));
|
||||
$text = strtr($text, $trans_table);
|
||||
$text = str_replace('<br />', '', $text);
|
||||
$text = str_replace('&', '&', $text);
|
||||
$text = str_replace(''', "'", $text);
|
||||
if ( '<pre><code>' == $matches[1] )
|
||||
$text = "\n$text\n";
|
||||
return "`$text`";
|
||||
}
|
||||
|
||||
} // end class
|
||||
|
||||
endif;
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
# stopwords-json [](https://travis-ci.org/6/stopwords-json) [](https://www.npmjs.com/package/stopwords-json) [](https://bower.io/)
|
||||
|
||||
Stopwords for various languages in JSON format. Per [Wikipedia](http://en.wikipedia.org/wiki/Stop_words):
|
||||
|
||||
> Stop words are words which are filtered out prior to, or after, processing of natural language data [...] these are some of the most common, short function words, such as *the*, *is*, *at*, *which*, and *on*.
|
||||
|
||||
You can use all stopwords with [stopwords-all.json](stopwords-all.json) (keyed by language ISO 639-1 code), or see the below table for individual language stopword files.
|
||||
|
||||
## Languages
|
||||
There are a total of 50 supported languages:
|
||||
|
||||
Language | Stopword count | Filename
|
||||
--- | --- | ---
|
||||
Afrikaans | 51 | [af.json](dist/af.json)
|
||||
Arabic | 162 | [ar.json](dist/ar.json)
|
||||
Armenian | 45 | [hy.json](dist/hy.json)
|
||||
Basque | 98 | [eu.json](dist/eu.json)
|
||||
Bengali | 116 | [bn.json](dist/bn.json)
|
||||
Breton | 126 | [br.json](dist/br.json)
|
||||
Bulgarian | 259 | [bg.json](dist/bg.json)
|
||||
Catalan | 218 | [ca.json](dist/ca.json)
|
||||
Chinese | 542 | [zh.json](dist/zh.json)
|
||||
Croatian | 179 | [hr.json](dist/hr.json)
|
||||
Czech | 346 | [cs.json](dist/cs.json)
|
||||
Danish | 101 | [da.json](dist/da.json)
|
||||
Dutch | 275 | [nl.json](dist/nl.json)
|
||||
English | 570 | [en.json](dist/en.json)
|
||||
Esperanto | 173 | [eo.json](dist/eo.json)
|
||||
Estonian | 35 | [et.json](dist/et.json)
|
||||
Finnish | 772 | [fi.json](dist/fi.json)
|
||||
French | 606 | [fr.json](dist/fr.json)
|
||||
Galician | 160 | [gl.json](dist/gl.json)
|
||||
German | 596 | [de.json](dist/de.json)
|
||||
Greek | 75 | [el.json](dist/el.json)
|
||||
Hausa | 39 | [ha.json](dist/ha.json)
|
||||
Hebrew | 194 | [he.json](dist/he.json)
|
||||
Hindi | 225 | [hi.json](dist/hi.json)
|
||||
Hungarian | 781 | [hu.json](dist/hu.json)
|
||||
Indonesian | 355 | [id.json](dist/id.json)
|
||||
Irish | 109 | [ga.json](dist/ga.json)
|
||||
Italian | 619 | [it.json](dist/it.json)
|
||||
Japanese | 109 | [ja.json](dist/ja.json)
|
||||
Korean | 679 | [ko.json](dist/ko.json)
|
||||
Latin | 49 | [la.json](dist/la.json)
|
||||
Latvian | 161 | [lv.json](dist/lv.json)
|
||||
Marathi | 99 | [mr.json](dist/mr.json)
|
||||
Norwegian | 172 | [no.json](dist/no.json)
|
||||
Persian | 332 | [fa.json](dist/fa.json)
|
||||
Polish | 260 | [pl.json](dist/pl.json)
|
||||
Portuguese | 408 | [pt.json](dist/pt.json)
|
||||
Romanian | 282 | [ro.json](dist/ro.json)
|
||||
Russian | 539 | [ru.json](dist/ru.json)
|
||||
Slovak | 110 | [sk.json](dist/sk.json)
|
||||
Slovenian | 446 | [sl.json](dist/sl.json)
|
||||
Somalia | 30 | [so.json](dist/so.json)
|
||||
Southern Sotho | 31 | [st.json](dist/st.json)
|
||||
Spanish | 577 | [es.json](dist/es.json)
|
||||
Swahili | 74 | [sw.json](dist/sw.json)
|
||||
Swedish | 401 | [sv.json](dist/sv.json)
|
||||
Thai | 115 | [th.json](dist/th.json)
|
||||
Turkish | 279 | [tr.json](dist/tr.json)
|
||||
Yoruba | 60 | [yo.json](dist/yo.json)
|
||||
Zulu | 29 | [zu.json](dist/zu.json)
|
||||
|
||||
|
||||
## Sources
|
||||
|
||||
- [Apache Lucene](http://lucene.apache.org/) - [Apache 2.0 License](http://www.apache.org/licenses/LICENSE-2.0)
|
||||
- [Carrot2](https://github.com/carrot2/carrot2) - [License](http://project.carrot2.org/license.html)
|
||||
- [cue.language](https://github.com/vcl/cue.language) - [Apache 2.0 License](https://github.com/vcl/cue.language/blob/master/license.txt)
|
||||
- [Jacques Savoy](http://members.unine.ch/jacques.savoy/clef/index.html) - BSD License
|
||||
- SMART Information Retrieval System: ftp://ftp.cs.cornell.edu/pub/smart/
|
||||
- [ASP Stoplist Project](https://github.com/dohliam/more-stoplists) - CC-BY and Apache 2.0
|
||||
|
||||
## License and Copyright
|
||||
Copyright (c) 2017 Peter Graham, contributors.
|
||||
Released under the Apache-2.0 license.
|
||||
+1
@@ -0,0 +1 @@
|
||||
["'n","aan","af","al","as","baie","by","daar","dag","dat","die","dit","een","ek","en","gaan","gesê","haar","het","hom","hulle","hy","in","is","jou","jy","kan","kom","ma","maar","met","my","na","nie","om","ons","op","saam","sal","se","sien","so","sy","te","toe","uit","van","vir","was","wat","ʼn"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["،","أ","ا","اثر","اجل","احد","اخرى","اذا","اربعة","اطار","اعادة","اعلنت","اف","اكثر","اكد","الا","الاخيرة","الان","الاول","الاولى","التى","التي","الثاني","الثانية","الذاتي","الذى","الذي","الذين","السابق","الف","الماضي","المقبل","الوقت","الى","اليوم","اما","امام","امس","ان","انه","انها","او","اول","اي","ايار","ايام","ايضا","ب","باسم","بان","برس","بسبب","بشكل","بعد","بعض","بن","به","بها","بين","تم","ثلاثة","ثم","جميع","حاليا","حتى","حوالى","حول","حيث","حين","خلال","دون","ذلك","زيارة","سنة","سنوات","شخصا","صباح","صفر","ضد","ضمن","عام","عاما","عدة","عدد","عدم","عشر","عشرة","على","عليه","عليها","عن","عند","عندما","غدا","غير","ـ","ف","فان","فى","في","فيه","فيها","قال","قبل","قد","قوة","كان","كانت","كل","كلم","كما","لا","لدى","لقاء","لكن","للامم","لم","لن","له","لها","لوكالة","ما","مايو","مساء","مع","مقابل","مليار","مليون","من","منذ","منها","نحو","نفسه","نهاية","هذا","هذه","هناك","هو","هي","و","و6","واحد","واضاف","واضافت","واكد","وان","واوضح","وفي","وقال","وقالت","وقد","وقف","وكان","وكانت","ولا","ولم","ومن","وهو","وهي","يكون","يمكن","يوم"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["а","автентичен","аз","ако","ала","бе","без","беше","би","бивш","бивша","бившо","бил","била","били","било","благодаря","близо","бъдат","бъде","бяха","в","вас","ваш","ваша","вероятно","вече","взема","ви","вие","винаги","внимава","време","все","всеки","всички","всичко","всяка","във","въпреки","върху","г","ги","главен","главна","главно","глас","го","година","години","годишен","д","да","дали","два","двама","двамата","две","двете","ден","днес","дни","до","добра","добре","добро","добър","докато","докога","дори","досега","доста","друг","друга","други","е","евтин","едва","един","една","еднаква","еднакви","еднакъв","едно","екип","ето","живот","за","забавям","зад","заедно","заради","засега","заспал","затова","защо","защото","и","из","или","им","има","имат","иска","й","каза","как","каква","какво","както","какъв","като","кога","когато","което","които","кой","който","колко","която","къде","където","към","лесен","лесно","ли","лош","м","май","малко","ме","между","мек","мен","месец","ми","много","мнозина","мога","могат","може","мокър","моля","момента","му","н","на","над","назад","най","направи","напред","например","нас","не","него","нещо","нея","ни","ние","никой","нито","нищо","но","нов","нова","нови","новина","някои","някой","няколко","няма","обаче","около","освен","особено","от","отгоре","отново","още","пак","по","повече","повечето","под","поне","поради","после","почти","прави","пред","преди","през","при","пък","първата","първи","първо","пъти","равен","равна","с","са","сам","само","се","сега","си","син","скоро","след","следващ","сме","смях","според","сред","срещу","сте","съм","със","също","т","т.н.","тази","така","такива","такъв","там","твой","те","тези","ти","то","това","тогава","този","той","толкова","точно","три","трябва","тук","тъй","тя","тях","у","утре","харесва","хиляди","ч","часа","че","често","чрез","ще","щом","юмрук","я","як"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["অনেক","অন্য","অবশ্য","আগে","আছে","আজ","আবার","আমরা","আমাদের","আর","ই","উত্তর","উপর","উপরে","এ","এই","এক্","এখন","এত","এব","এমন","এমনি","এর","এস","এসে","ও","ওই","কমনে","করা","করে","কাছে","কাজ","কাজে","কারণ","কি","কিছু","কে","কেউ","কেখা","কেন","কোটি","কোনো","কয়েক","খুব","গিয়ে","গেল","চার","চালু","চেষ্টা","ছিল","জানা","জ্নজন","টি","তখন","তবে","তা","তাই","তো","থাকা","থেকে","দিন","দু","দুই","দেওয়া","ধামার","নতুন","না","নাগাদ","নিয়ে","নেওয়া","নয়","পর","পরে","পাচ","পি","পেয়্র্","প্রতি","প্রথম","প্রযন্ত","প্রাথমিক","প্রায়","বক্তব্য","বন","বলা","বলে","বলেন","বহু","বা","বি","বিভিন্ন","বেশ","বেশি","মতো","মধ্যে","মনে","যখন","যদি","যা","যাওয়া","যে","র","রকম","লক্ষ","শুধু","শুরু","সঙ্গে","সব","সহ","সাধারণ","সামনে","সি","সে","সেই","হতে","হাজার","হয়"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["a","ainda","alem","ambas","ambos","antes","ao","aonde","aos","apos","aquele","aqueles","as","assim","com","como","contra","contudo","cuja","cujas","cujo","cujos","da","das","de","dela","dele","deles","demais","depois","desde","desta","deste","dispoe","dispoem","diversa","diversas","diversos","do","dos","durante","e","ela","elas","ele","eles","em","entao","entre","essa","essas","esse","esses","esta","estas","este","estes","ha","isso","isto","logo","mais","mas","mediante","menos","mesma","mesmas","mesmo","mesmos","na","nao","nas","nem","nesse","neste","nos","o","os","ou","outra","outras","outro","outros","pelas","pelo","pelos","perante","pois","por","porque","portanto","propios","proprio","quais","qual","qualquer","quando","quanto","que","quem","quer","se","seja","sem","sendo","seu","seus","sob","sobre","sua","suas","tal","tambem","teu","teus","toda","todas","todo","todos","tua","tuas","tudo","um","uma","umas","uns"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["a","abans","ací","ah","així","això","al","aleshores","algun","alguna","algunes","alguns","alhora","allà","allí","allò","als","altra","altre","altres","amb","ambdues","ambdós","apa","aquell","aquella","aquelles","aquells","aquest","aquesta","aquestes","aquests","aquí","baix","cada","cadascuna","cadascunes","cadascuns","cadascú","com","contra","d'un","d'una","d'unes","d'uns","dalt","de","del","dels","des","després","dins","dintre","donat","doncs","durant","e","eh","el","els","em","en","encara","ens","entre","eren","es","esta","estaven","esteu","està","estàvem","estàveu","et","etc","ets","fins","fora","gairebé","ha","han","has","havia","he","hem","heu","hi","ho","i","igual","iguals","ja","l'hi","la","les","li","li'n","llavors","m'he","ma","mal","malgrat","mateix","mateixa","mateixes","mateixos","me","mentre","meu","meus","meva","meves","molt","molta","moltes","molts","mon","mons","més","n'he","n'hi","ne","ni","no","nogensmenys","només","nosaltres","nostra","nostre","nostres","o","oh","oi","on","pas","pel","pels","per","perquè","però","poc","poca","pocs","poques","potser","propi","qual","quals","quan","quant","que","quelcom","qui","quin","quina","quines","quins","què","s'ha","s'han","sa","semblant","semblants","ses","seu","seus","seva","seves","si","sobre","sobretot","solament","sols","son","sons","sota","sou","sóc","són","t'ha","t'han","t'he","ta","tal","també","tampoc","tan","tant","tanta","tantes","teu","teus","teva","teves","ton","tons","tot","tota","totes","tots","un","una","unes","uns","us","va","vaig","vam","van","vas","veu","vosaltres","vostra","vostre","vostres","érem","éreu","és"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["a","aby","ahoj","aj","ale","anebo","ani","ano","asi","aspoň","atd","atp","ačkoli","až","bez","beze","blízko","bohužel","brzo","bude","budem","budeme","budete","budeš","budou","budu","by","byl","byla","byli","bylo","byly","bys","být","během","chce","chceme","chcete","chceš","chci","chtít","chtějí","chut'","chuti","co","což","cz","daleko","další","den","deset","devatenáct","devět","dnes","do","dobrý","docela","dva","dvacet","dvanáct","dvě","dál","dále","děkovat","děkujeme","děkuji","ho","hodně","i","jak","jakmile","jako","jakož","jde","je","jeden","jedenáct","jedna","jedno","jednou","jedou","jeho","jehož","jej","jejich","její","jelikož","jemu","jen","jenom","jestli","jestliže","ještě","jež","ji","jich","jimi","jinak","jiné","již","jsem","jseš","jsi","jsme","jsou","jste","já","jí","jím","jíž","k","kam","kde","kdo","kdy","když","ke","kolik","kromě","kterou","která","které","který","kteří","kvůli","mají","mezi","mi","mne","mnou","mně","moc","mohl","mohou","moje","moji","možná","musí","my","má","málo","mám","máme","máte","máš","mé","mí","mít","mě","můj","může","na","nad","nade","napište","naproti","načež","naše","naši","ne","nebo","nebyl","nebyla","nebyli","nebyly","nedělají","nedělá","nedělám","neděláme","neděláte","neděláš","neg","nejsi","nejsou","nemají","nemáme","nemáte","neměl","není","nestačí","nevadí","než","nic","nich","nimi","nové","nový","nula","nám","námi","nás","náš","ním","ně","něco","nějak","někde","někdo","němu","němuž","o","od","ode","on","ona","oni","ono","ony","osm","osmnáct","pak","patnáct","po","pod","podle","pokud","potom","pouze","pozdě","pořád","pravé","pro","prostě","prosím","proti","proto","protože","proč","první","pta","pět","před","přes","přese","při","přičemž","re","rovně","s","se","sedm","sedmnáct","si","skoro","smí","smějí","snad","spolu","sta","sto","strana","sté","své","svých","svým","svými","ta","tady","tak","takhle","taky","také","takže","tam","tamhle","tamhleto","tamto","tato","tebe","tebou","ted'","tedy","ten","tento","teto","ti","tipy","tisíc","tisíce","to","tobě","tohle","toho","tohoto","tom","tomto","tomu","tomuto","toto","trošku","tu","tuto","tvoje","tvá","tvé","tvůj","ty","tyto","téma","tím","tímto","tě","těm","těmu","třeba","tři","třináct","u","určitě","už","v","vaše","vaši","ve","vedle","večer","vlastně","vy","vám","vámi","vás","váš","více","však","všechno","všichni","vůbec","vždy","z","za","zatímco","zač","zda","zde","ze","zprávy","zpět","čau","či","článku","články","čtrnáct","čtyři","šest","šestnáct","že"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["af","alle","andet","andre","at","begge","da","de","den","denne","der","deres","det","dette","dig","din","dog","du","ej","eller","en","end","ene","eneste","enhver","et","fem","fire","flere","fleste","for","fordi","forrige","fra","få","før","god","han","hans","har","hendes","her","hun","hvad","hvem","hver","hvilken","hvis","hvor","hvordan","hvorfor","hvornår","i","ikke","ind","ingen","intet","jeg","jeres","kan","kom","kommer","lav","lidt","lille","man","mand","mange","med","meget","men","mens","mere","mig","ned","ni","nogen","noget","ny","nyt","nær","næste","næsten","og","op","otte","over","på","se","seks","ses","som","stor","store","syv","ti","til","to","tre","ud","var"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["Ernst","Ordnung","Schluss","a","ab","aber","ach","acht","achte","achten","achter","achtes","ag","alle","allein","allem","allen","aller","allerdings","alles","allgemeinen","als","also","am","an","andere","anderen","andern","anders","au","auch","auf","aus","ausser","ausserdem","außer","außerdem","b","bald","bei","beide","beiden","beim","beispiel","bekannt","bereits","besonders","besser","besten","bin","bis","bisher","bist","c","d","d.h","da","dabei","dadurch","dafür","dagegen","daher","dahin","dahinter","damals","damit","danach","daneben","dank","dann","daran","darauf","daraus","darf","darfst","darin","darum","darunter","darüber","das","dasein","daselbst","dass","dasselbe","davon","davor","dazu","dazwischen","daß","dein","deine","deinem","deiner","dem","dementsprechend","demgegenüber","demgemäss","demgemäß","demselben","demzufolge","den","denen","denn","denselben","der","deren","derjenige","derjenigen","dermassen","dermaßen","derselbe","derselben","des","deshalb","desselben","dessen","deswegen","dich","die","diejenige","diejenigen","dies","diese","dieselbe","dieselben","diesem","diesen","dieser","dieses","dir","doch","dort","drei","drin","dritte","dritten","dritter","drittes","du","durch","durchaus","durfte","durften","dürfen","dürft","e","eben","ebenso","ehrlich","ei","ei,","eigen","eigene","eigenen","eigener","eigenes","ein","einander","eine","einem","einen","einer","eines","einige","einigen","einiger","einiges","einmal","eins","elf","en","ende","endlich","entweder","er","erst","erste","ersten","erster","erstes","es","etwa","etwas","euch","euer","eure","f","folgende","früher","fünf","fünfte","fünften","fünfter","fünftes","für","g","gab","ganz","ganze","ganzen","ganzer","ganzes","gar","gedurft","gegen","gegenüber","gehabt","gehen","geht","gekannt","gekonnt","gemacht","gemocht","gemusst","genug","gerade","gern","gesagt","geschweige","gewesen","gewollt","geworden","gibt","ging","gleich","gott","gross","grosse","grossen","grosser","grosses","groß","große","großen","großer","großes","gut","gute","guter","gutes","h","habe","haben","habt","hast","hat","hatte","hatten","hattest","hattet","heisst","her","heute","hier","hin","hinter","hoch","hätte","hätten","i","ich","ihm","ihn","ihnen","ihr","ihre","ihrem","ihren","ihrer","ihres","im","immer","in","indem","infolgedessen","ins","irgend","ist","j","ja","jahr","jahre","jahren","je","jede","jedem","jeden","jeder","jedermann","jedermanns","jedes","jedoch","jemand","jemandem","jemanden","jene","jenem","jenen","jener","jenes","jetzt","k","kam","kann","kannst","kaum","kein","keine","keinem","keinen","keiner","kleine","kleinen","kleiner","kleines","kommen","kommt","konnte","konnten","kurz","können","könnt","könnte","l","lang","lange","leicht","leide","lieber","los","m","machen","macht","machte","mag","magst","mahn","mal","man","manche","manchem","manchen","mancher","manches","mann","mehr","mein","meine","meinem","meinen","meiner","meines","mensch","menschen","mich","mir","mit","mittel","mochte","mochten","morgen","muss","musst","musste","mussten","muß","mußt","möchte","mögen","möglich","mögt","müssen","müsst","müßt","n","na","nach","nachdem","nahm","natürlich","neben","nein","neue","neuen","neun","neunte","neunten","neunter","neuntes","nicht","nichts","nie","niemand","niemandem","niemanden","noch","nun","nur","o","ob","oben","oder","offen","oft","ohne","p","q","r","recht","rechte","rechten","rechter","rechtes","richtig","rund","s","sa","sache","sagt","sagte","sah","satt","schlecht","schon","sechs","sechste","sechsten","sechster","sechstes","sehr","sei","seid","seien","sein","seine","seinem","seinen","seiner","seines","seit","seitdem","selbst","sich","sie","sieben","siebente","siebenten","siebenter","siebentes","sind","so","solang","solche","solchem","solchen","solcher","solches","soll","sollen","sollst","sollt","sollte","sollten","sondern","sonst","soweit","sowie","später","startseite","statt","steht","suche","t","tag","tage","tagen","tat","teil","tel","tritt","trotzdem","tun","u","uhr","um","und","und?","uns","unser","unsere","unserer","unter","v","vergangenen","viel","viele","vielem","vielen","vielleicht","vier","vierte","vierten","vierter","viertes","vom","von","vor","w","wahr?","wann","war","waren","wart","warum","was","wegen","weil","weit","weiter","weitere","weiteren","weiteres","welche","welchem","welchen","welcher","welches","wem","wen","wenig","wenige","weniger","weniges","wenigstens","wenn","wer","werde","werden","werdet","weshalb","wessen","wie","wieder","wieso","will","willst","wir","wird","wirklich","wirst","wissen","wo","wohl","wollen","wollt","wollte","wollten","worden","wurde","wurden","während","währenddem","währenddessen","wäre","würde","würden","x","y","z","z.b","zehn","zehnte","zehnten","zehnter","zehntes","zeit","zu","zuerst","zugleich","zum","zunächst","zur","zurück","zusammen","zwanzig","zwar","zwei","zweite","zweiten","zweiter","zweites","zwischen","zwölf","über","überhaupt","übrigens"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["αλλα","αν","αντι","απο","αυτα","αυτεσ","αυτη","αυτο","αυτοι","αυτοσ","αυτουσ","αυτων","για","δε","δεν","εαν","ειμαι","ειμαστε","ειναι","εισαι","ειστε","εκεινα","εκεινεσ","εκεινη","εκεινο","εκεινοι","εκεινοσ","εκεινουσ","εκεινων","ενω","επι","η","θα","ισωσ","κ","και","κατα","κι","μα","με","μετα","μη","μην","να","ο","οι","ομωσ","οπωσ","οσο","οτι","παρα","ποια","ποιεσ","ποιο","ποιοι","ποιοσ","ποιουσ","ποιων","που","προσ","πωσ","σε","στη","στην","στο","στον","τα","την","τησ","το","τον","τοτε","του","των","ωσ"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["a","a's","able","about","above","according","accordingly","across","actually","after","afterwards","again","against","ain't","all","allow","allows","almost","alone","along","already","also","although","always","am","among","amongst","an","and","another","any","anybody","anyhow","anyone","anything","anyway","anyways","anywhere","apart","appear","appreciate","appropriate","are","aren't","around","as","aside","ask","asking","associated","at","available","away","awfully","b","be","became","because","become","becomes","becoming","been","before","beforehand","behind","being","believe","below","beside","besides","best","better","between","beyond","both","brief","but","by","c","c'mon","c's","came","can","can't","cannot","cant","cause","causes","certain","certainly","changes","clearly","co","com","come","comes","concerning","consequently","consider","considering","contain","containing","contains","corresponding","could","couldn't","course","currently","d","definitely","described","despite","did","didn't","different","do","does","doesn't","doing","don't","done","down","downwards","during","e","each","edu","eg","eight","either","else","elsewhere","enough","entirely","especially","et","etc","even","ever","every","everybody","everyone","everything","everywhere","ex","exactly","example","except","f","far","few","fifth","first","five","followed","following","follows","for","former","formerly","forth","four","from","further","furthermore","g","get","gets","getting","given","gives","go","goes","going","gone","got","gotten","greetings","h","had","hadn't","happens","hardly","has","hasn't","have","haven't","having","he","he's","hello","help","hence","her","here","here's","hereafter","hereby","herein","hereupon","hers","herself","hi","him","himself","his","hither","hopefully","how","howbeit","however","i","i'd","i'll","i'm","i've","ie","if","ignored","immediate","in","inasmuch","inc","indeed","indicate","indicated","indicates","inner","insofar","instead","into","inward","is","isn't","it","it'd","it'll","it's","its","itself","j","just","k","keep","keeps","kept","know","known","knows","l","last","lately","later","latter","latterly","least","less","lest","let","let's","like","liked","likely","little","look","looking","looks","ltd","m","mainly","many","may","maybe","me","mean","meanwhile","merely","might","more","moreover","most","mostly","much","must","my","myself","n","name","namely","nd","near","nearly","necessary","need","needs","neither","never","nevertheless","new","next","nine","no","nobody","non","none","noone","nor","normally","not","nothing","novel","now","nowhere","o","obviously","of","off","often","oh","ok","okay","old","on","once","one","ones","only","onto","or","other","others","otherwise","ought","our","ours","ourselves","out","outside","over","overall","own","p","particular","particularly","per","perhaps","placed","please","plus","possible","presumably","probably","provides","q","que","quite","qv","r","rather","rd","re","really","reasonably","regarding","regardless","regards","relatively","respectively","right","s","said","same","saw","say","saying","says","second","secondly","see","seeing","seem","seemed","seeming","seems","seen","self","selves","sensible","sent","serious","seriously","seven","several","shall","she","should","shouldn't","since","six","so","some","somebody","somehow","someone","something","sometime","sometimes","somewhat","somewhere","soon","sorry","specified","specify","specifying","still","sub","such","sup","sure","t","t's","take","taken","tell","tends","th","than","thank","thanks","thanx","that","that's","thats","the","their","theirs","them","themselves","then","thence","there","there's","thereafter","thereby","therefore","therein","theres","thereupon","these","they","they'd","they'll","they're","they've","think","third","this","thorough","thoroughly","those","though","three","through","throughout","thru","thus","to","together","too","took","toward","towards","tried","tries","truly","try","trying","twice","two","u","un","under","unfortunately","unless","unlikely","until","unto","up","upon","us","use","used","useful","uses","using","usually","uucp","v","value","various","very","via","viz","vs","w","want","wants","was","wasn't","way","we","we'd","we'll","we're","we've","welcome","well","went","were","weren't","what","what's","whatever","when","whence","whenever","where","where's","whereafter","whereas","whereby","wherein","whereupon","wherever","whether","which","while","whither","who","who's","whoever","whole","whom","whose","why","will","willing","wish","with","within","without","won't","wonder","would","wouldn't","x","y","yes","yet","you","you'd","you'll","you're","you've","your","yours","yourself","yourselves","z","zero"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["adiaŭ","ajn","al","ankoraŭ","antaŭ","aŭ","bonan","bonvole","bonvolu","bv","ci","cia","cian","cin","d-ro","da","de","dek","deka","do","doktor'","doktoro","du","dua","dum","eble","ekz","ekzemple","en","estas","estis","estos","estu","estus","eĉ","f-no","feliĉan","for","fraŭlino","ha","havas","havis","havos","havu","havus","he","ho","hu","ili","ilia","ilian","ilin","inter","io","ion","iu","iujn","iun","ja","jam","je","jes","k","kaj","ke","kio","kion","kiu","kiujn","kiun","kvankam","kvar","kvara","kvazaŭ","kvin","kvina","la","li","lia","lian","lin","malantaŭ","male","malgraŭ","mem","mi","mia","mian","min","minus","naŭ","naŭa","ne","nek","nenio","nenion","neniu","neniun","nepre","ni","nia","nian","nin","nu","nun","nur","ok","oka","oni","onia","onian","onin","plej","pli","plu","plus","por","post","preter","s-no","s-ro","se","sed","sep","sepa","ses","sesa","si","sia","sian","sin","sinjor'","sinjorino","sinjoro","sub","super","supren","sur","tamen","tio","tion","tiu","tiujn","tiun","tra","tri","tria","tuj","tute","unu","unua","ve","verŝajne","vi","via","vian","vin","ĉi","ĉio","ĉion","ĉiu","ĉiujn","ĉiun","ĉu","ĝi","ĝia","ĝian","ĝin","ĝis","ĵus","ŝi","ŝia","ŝin"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["a","actualmente","acuerdo","adelante","ademas","además","adrede","afirmó","agregó","ahi","ahora","ahí","al","algo","alguna","algunas","alguno","algunos","algún","alli","allí","alrededor","ambos","ampleamos","antano","antaño","ante","anterior","antes","apenas","aproximadamente","aquel","aquella","aquellas","aquello","aquellos","aqui","aquél","aquélla","aquéllas","aquéllos","aquí","arriba","arribaabajo","aseguró","asi","así","atras","aun","aunque","ayer","añadió","aún","b","bajo","bastante","bien","breve","buen","buena","buenas","bueno","buenos","c","cada","casi","cerca","cierta","ciertas","cierto","ciertos","cinco","claro","comentó","como","con","conmigo","conocer","conseguimos","conseguir","considera","consideró","consigo","consigue","consiguen","consigues","contigo","contra","cosas","creo","cual","cuales","cualquier","cuando","cuanta","cuantas","cuanto","cuantos","cuatro","cuenta","cuál","cuáles","cuándo","cuánta","cuántas","cuánto","cuántos","cómo","d","da","dado","dan","dar","de","debajo","debe","deben","debido","decir","dejó","del","delante","demasiado","demás","dentro","deprisa","desde","despacio","despues","después","detras","detrás","dia","dias","dice","dicen","dicho","dieron","diferente","diferentes","dijeron","dijo","dio","donde","dos","durante","día","días","dónde","e","ejemplo","el","ella","ellas","ello","ellos","embargo","empleais","emplean","emplear","empleas","empleo","en","encima","encuentra","enfrente","enseguida","entonces","entre","era","eramos","eran","eras","eres","es","esa","esas","ese","eso","esos","esta","estaba","estaban","estado","estados","estais","estamos","estan","estar","estará","estas","este","esto","estos","estoy","estuvo","está","están","ex","excepto","existe","existen","explicó","expresó","f","fin","final","fue","fuera","fueron","fui","fuimos","g","general","gran","grandes","gueno","h","ha","haber","habia","habla","hablan","habrá","había","habían","hace","haceis","hacemos","hacen","hacer","hacerlo","haces","hacia","haciendo","hago","han","hasta","hay","haya","he","hecho","hemos","hicieron","hizo","horas","hoy","hubo","i","igual","incluso","indicó","informo","informó","intenta","intentais","intentamos","intentan","intentar","intentas","intento","ir","j","junto","k","l","la","lado","largo","las","le","lejos","les","llegó","lleva","llevar","lo","los","luego","lugar","m","mal","manera","manifestó","mas","mayor","me","mediante","medio","mejor","mencionó","menos","menudo","mi","mia","mias","mientras","mio","mios","mis","misma","mismas","mismo","mismos","modo","momento","mucha","muchas","mucho","muchos","muy","más","mí","mía","mías","mío","míos","n","nada","nadie","ni","ninguna","ningunas","ninguno","ningunos","ningún","no","nos","nosotras","nosotros","nuestra","nuestras","nuestro","nuestros","nueva","nuevas","nuevo","nuevos","nunca","o","ocho","os","otra","otras","otro","otros","p","pais","para","parece","parte","partir","pasada","pasado","paìs","peor","pero","pesar","poca","pocas","poco","pocos","podeis","podemos","poder","podria","podriais","podriamos","podrian","podrias","podrá","podrán","podría","podrían","poner","por","porque","posible","primer","primera","primero","primeros","principalmente","pronto","propia","propias","propio","propios","proximo","próximo","próximos","pudo","pueda","puede","pueden","puedo","pues","q","qeu","que","quedó","queremos","quien","quienes","quiere","quiza","quizas","quizá","quizás","quién","quiénes","qué","r","raras","realizado","realizar","realizó","repente","respecto","s","sabe","sabeis","sabemos","saben","saber","sabes","salvo","se","sea","sean","segun","segunda","segundo","según","seis","ser","sera","será","serán","sería","señaló","si","sido","siempre","siendo","siete","sigue","siguiente","sin","sino","sobre","sois","sola","solamente","solas","solo","solos","somos","son","soy","soyos","su","supuesto","sus","suya","suyas","suyo","sé","sí","sólo","t","tal","tambien","también","tampoco","tan","tanto","tarde","te","temprano","tendrá","tendrán","teneis","tenemos","tener","tenga","tengo","tenido","tenía","tercera","ti","tiempo","tiene","tienen","toda","todas","todavia","todavía","todo","todos","total","trabaja","trabajais","trabajamos","trabajan","trabajar","trabajas","trabajo","tras","trata","través","tres","tu","tus","tuvo","tuya","tuyas","tuyo","tuyos","tú","u","ultimo","un","una","unas","uno","unos","usa","usais","usamos","usan","usar","usas","uso","usted","ustedes","v","va","vais","valor","vamos","van","varias","varios","vaya","veces","ver","verdad","verdadera","verdadero","vez","vosotras","vosotros","voy","vuestra","vuestras","vuestro","vuestros","w","x","y","ya","yo","z","él","ésa","ésas","ése","ésos","ésta","éstas","éste","éstos","última","últimas","último","últimos"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["aga","ei","et","ja","jah","kas","kui","kõik","ma","me","mida","midagi","mind","minu","mis","mu","mul","mulle","nad","nii","oled","olen","oli","oma","on","pole","sa","seda","see","selle","siin","siis","ta","te","ära"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["al","anitz","arabera","asko","baina","bat","batean","batek","bati","batzuei","batzuek","batzuetan","batzuk","bera","beraiek","berau","berauek","bere","berori","beroriek","beste","bezala","da","dago","dira","ditu","du","dute","edo","egin","ere","eta","eurak","ez","gainera","gu","gutxi","guzti","haiei","haiek","haietan","hainbeste","hala","han","handik","hango","hara","hari","hark","hartan","hau","hauei","hauek","hauetan","hemen","hemendik","hemengo","hi","hona","honek","honela","honetan","honi","hor","hori","horiei","horiek","horietan","horko","horra","horrek","horrela","horretan","horri","hortik","hura","izan","ni","noiz","nola","non","nondik","nongo","nor","nora","ze","zein","zen","zenbait","zenbat","zer","zergatik","ziren","zituen","zu","zuek","zuen","zuten"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["آباد","آره","آری","آمد","آمده","آن","آنان","آنجا","آنكه","آنها","آنچه","آورد","آورده","آيد","آیا","اثرِ","از","است","استفاده","اش","اكنون","البته","البتّه","ام","اما","امروز","امسال","اند","انکه","او","اول","اي","ايشان","ايم","اين","اينكه","اگر","با","بار","بارة","باره","باشد","باشند","باشيم","بالا","بالایِ","بايد","بدون","بر","برابرِ","براساس","براي","برایِ","برخوردار","برخي","برداري","بروز","بسيار","بسياري","بعد","بعری","بعضي","بلكه","بله","بلکه","بلی","بنابراين","بندي","به","بهترين","بود","بودن","بودند","بوده","بي","بيست","بيش","بيشتر","بيشتري","بين","بی","بیرونِ","تا","تازه","تاكنون","تان","تحت","تر","ترين","تمام","تمامي","تنها","تواند","توانند","توسط","تولِ","تویِ","جا","جاي","جايي","جدا","جديد","جريان","جز","جلوگيري","جلویِ","حتي","حدودِ","حق","خارجِ","خدمات","خواست","خواهد","خواهند","خواهيم","خود","خويش","خیاه","داد","دادن","دادند","داده","دارد","دارند","داريم","داشت","داشتن","داشتند","داشته","دانست","دانند","در","درباره","دنبالِ","ده","دهد","دهند","دو","دوم","ديده","ديروز","ديگر","ديگران","ديگري","دیگر","را","راه","رفت","رفته","روب","روزهاي","روي","رویِ","ريزي","زياد","زير","زيرا","زیرِ","سابق","ساخته","سازي","سراسر","سریِ","سعي","سمتِ","سوم","سوي","سویِ","سپس","شان","شايد","شد","شدن","شدند","شده","شش","شما","شناسي","شود","شوند","صورت","ضدِّ","ضمن","طبقِ","طريق","طور","طي","عقبِ","علّتِ","عنوانِ","غير","فقط","فكر","فوق","قابل","قبل","قصدِ","كرد","كردم","كردن","كردند","كرده","كسي","كل","كمتر","كند","كنم","كنند","كنيد","كنيم","كه","لطفاً","ما","مان","مانند","مانندِ","مثل","مثلِ","مختلف","مدّتی","مردم","مرسی","مقابل","من","مورد","مي","ميليارد","ميليون","مگر","ناشي","نام","نبايد","نبود","نخست","نخستين","نخواهد","ندارد","ندارند","نداشته","نزديك","نزدِ","نزدیکِ","نشان","نشده","نظير","نكرده","نمايد","نمي","نه","نوعي","نيز","نيست","ها","هاي","هايي","هر","هرگز","هزار","هست","هستند","هستيم","هفت","هم","همان","همه","همواره","همين","همچنان","همچنين","همچون","همین","هنوز","هنگام","هنگامِ","هنگامی","هيچ","هیچ","و","وسطِ","وقتي","وقتیکه","ولی","وي","وگو","يا","يابد","يك","يكديگر","يكي","ّه","پاعینِ","پس","پنج","پيش","پیش","پیشِ","چرا","چطور","چند","چندین","چنين","چه","چهار","چون","چيزي","چگونه","چیز","چیزی","چیست","کجا","کجاست","کدام","کس","کسی","کنارِ","که","کَی","کی","گذاري","گذاشته","گردد","گرفت","گرفته","گروهي","گفت","گفته","گويد","گويند","گيرد","گيري","یا","یک"]
|
||||
+1
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+1
@@ -0,0 +1 @@
|
||||
["a","ach","ag","agus","an","aon","ar","arna","as","b'","ba","beirt","bhúr","caoga","ceathair","ceathrar","chomh","chtó","chuig","chun","cois","céad","cúig","cúigear","d'","daichead","dar","de","deich","deichniúr","den","dhá","do","don","dtí","dá","dár","dó","faoi","faoin","faoina","faoinár","fara","fiche","gach","gan","go","gur","haon","hocht","i","iad","idir","in","ina","ins","inár","is","le","leis","lena","lenár","m'","mar","mo","mé","na","nach","naoi","naonúr","ná","ní","níor","nó","nócha","ocht","ochtar","os","roimh","sa","seacht","seachtar","seachtó","seasca","seisear","siad","sibh","sinn","sna","sé","sí","tar","thar","thú","triúr","trí","trína","trínár","tríocha","tú","um","ár","é","éis","í","ó","ón","óna","ónár"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["a","alí","ao","aos","aquel","aquela","aquelas","aqueles","aquilo","aquí","as","así","aínda","ben","cando","che","co","coa","coas","comigo","con","connosco","contigo","convosco","cos","cun","cunha","cunhas","cuns","da","dalgunha","dalgunhas","dalgún","dalgúns","das","de","del","dela","delas","deles","desde","deste","do","dos","dun","dunha","dunhas","duns","e","el","ela","elas","eles","en","era","eran","esa","esas","ese","eses","esta","estaba","estar","este","estes","estiven","estou","está","están","eu","facer","foi","foron","fun","había","hai","iso","isto","la","las","lle","lles","lo","los","mais","me","meu","meus","min","miña","miñas","moi","na","nas","neste","nin","no","non","nos","nosa","nosas","noso","nosos","nun","nunha","nunhas","nuns","nós","o","os","ou","para","pero","pode","pois","pola","polas","polo","polos","por","que","se","senón","ser","seu","seus","sexa","sido","sobre","súa","súas","tamén","tan","te","ten","ter","teu","teus","teñen","teño","ti","tido","tiven","tiña","túa","túas","un","unha","unhas","uns","vos","vosa","vosas","voso","vosos","vós","á","é","ó","ós"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["a","amma","ba","ban","ce","cikin","da","don","ga","in","ina","ita","ji","ka","ko","kuma","lokacin","ma","mai","na","ne","ni","sai","shi","su","suka","sun","ta","tafi","take","tana","wani","wannan","wata","ya","yake","yana","yi","za"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["אבל","או","אולי","אותה","אותו","אותי","אותך","אותם","אותן","אותנו","אז","אחר","אחרות","אחרי","אחריכן","אחרים","אחרת","אי","איזה","איך","אין","איפה","איתה","איתו","איתי","איתך","איתכם","איתכן","איתם","איתן","איתנו","אך","אל","אלה","אלו","אם","אנחנו","אני","אס","אף","אצל","אשר","את","אתה","אתכם","אתכן","אתם","אתן","באיזומידה","באמצע","באמצעות","בגלל","בין","בלי","במידה","במקוםשבו","ברם","בשביל","בשעהש","בתוך","גם","דרך","הוא","היא","היה","היכן","היתה","היתי","הם","הן","הנה","הסיבהשבגללה","הרי","ואילו","ואת","זאת","זה","זות","יהיה","יוכל","יוכלו","יותרמדי","יכול","יכולה","יכולות","יכולים","יכל","יכלה","יכלו","יש","כאן","כאשר","כולם","כולן","כזה","כי","כיצד","כך","ככה","כל","כלל","כמו","כן","כפי","כש","לא","לאו","לאיזותכלית","לאן","לבין","לה","להיות","להם","להן","לו","לי","לכם","לכן","למה","למטה","למעלה","למקוםשבו","למרות","לנו","לעבר","לעיכן","לפיכך","לפני","מאד","מאחורי","מאיזוסיבה","מאין","מאיפה","מבלי","מבעד","מדוע","מה","מהיכן","מול","מחוץ","מי","מכאן","מכיוון","מלבד","מן","מנין","מסוגל","מעט","מעטים","מעל","מצד","מקוםבו","מתחת","מתי","נגד","נגר","נו","עד","עז","על","עלי","עליה","עליהם","עליהן","עליו","עליך","עליכם","עלינו","עם","עצמה","עצמהם","עצמהן","עצמו","עצמי","עצמם","עצמן","עצמנו","פה","רק","שוב","של","שלה","שלהם","שלהן","שלו","שלי","שלך","שלכה","שלכם","שלכן","שלנו","שם","תהיה","תחת"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["अंदर","अत","अदि","अप","अपना","अपनि","अपनी","अपने","अभि","अभी","आदि","आप","इंहिं","इंहें","इंहों","इतयादि","इत्यादि","इन","इनका","इन्हीं","इन्हें","इन्हों","इस","इसका","इसकि","इसकी","इसके","इसमें","इसि","इसी","इसे","उंहिं","उंहें","उंहों","उन","उनका","उनकि","उनकी","उनके","उनको","उन्हीं","उन्हें","उन्हों","उस","उसके","उसि","उसी","उसे","एक","एवं","एस","एसे","ऐसे","ओर","और","कइ","कई","कर","करता","करते","करना","करने","करें","कहते","कहा","का","काफि","काफ़ी","कि","किंहें","किंहों","कितना","किन्हें","किन्हों","किया","किर","किस","किसि","किसी","किसे","की","कुछ","कुल","के","को","कोइ","कोई","कोन","कोनसा","कौन","कौनसा","गया","घर","जब","जहाँ","जहां","जा","जिंहें","जिंहों","जितना","जिधर","जिन","जिन्हें","जिन्हों","जिस","जिसे","जीधर","जेसा","जेसे","जैसा","जैसे","जो","तक","तब","तरह","तिंहें","तिंहों","तिन","तिन्हें","तिन्हों","तिस","तिसे","तो","था","थि","थी","थे","दबारा","दवारा","दिया","दुसरा","दुसरे","दूसरे","दो","द्वारा","न","नहिं","नहीं","ना","निचे","निहायत","नीचे","ने","पर","पहले","पुरा","पूरा","पे","फिर","बनि","बनी","बहि","बही","बहुत","बाद","बाला","बिलकुल","भि","भितर","भी","भीतर","मगर","मानो","मे","में","यदि","यह","यहाँ","यहां","यहि","यही","या","यिह","ये","रखें","रवासा","रहा","रहे","ऱ्वासा","लिए","लिये","लेकिन","व","वगेरह","वरग","वर्ग","वह","वहाँ","वहां","वहिं","वहीं","वाले","वुह","वे","वग़ैरह","संग","सकता","सकते","सबसे","सभि","सभी","साथ","साबुत","साभ","सारा","से","सो","हि","ही","हुअ","हुआ","हुइ","हुई","हुए","हे","हें","है","हैं","हो","होता","होति","होती","होते","होना","होने"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["a","ako","ali","bi","bih","bila","bili","bilo","bio","bismo","biste","biti","bumo","da","do","duž","ga","hoće","hoćemo","hoćete","hoćeš","hoću","i","iako","ih","ili","iz","ja","je","jedna","jedne","jedno","jer","jesam","jesi","jesmo","jest","jeste","jesu","jim","joj","još","ju","kada","kako","kao","koja","koje","koji","kojima","koju","kroz","li","me","mene","meni","mi","mimo","moj","moja","moje","mu","na","nad","nakon","nam","nama","nas","naš","naša","naše","našeg","ne","nego","neka","neki","nekog","neku","nema","netko","neće","nećemo","nećete","nećeš","neću","nešto","ni","nije","nikoga","nikoje","nikoju","nisam","nisi","nismo","niste","nisu","njega","njegov","njegova","njegovo","njemu","njezin","njezina","njezino","njih","njihov","njihova","njihovo","njim","njima","njoj","nju","no","o","od","odmah","on","ona","oni","ono","ova","pa","pak","po","pod","pored","prije","s","sa","sam","samo","se","sebe","sebi","si","smo","ste","su","sve","svi","svog","svoj","svoja","svoje","svom","ta","tada","taj","tako","te","tebe","tebi","ti","to","toj","tome","tu","tvoj","tvoja","tvoje","u","uz","vam","vama","vas","vaš","vaša","vaše","već","vi","vrlo","za","zar","će","ćemo","ćete","ćeš","ću","što"]
|
||||
+1
File diff suppressed because one or more lines are too long
+1
@@ -0,0 +1 @@
|
||||
["այդ","այլ","այն","այս","դու","դուք","եմ","են","ենք","ես","եք","է","էի","էին","էինք","էիր","էիք","էր","ըստ","թ","ի","ին","իսկ","իր","կամ","համար","հետ","հետո","մենք","մեջ","մի","ն","նա","նաև","նրա","նրանք","որ","որը","որոնք","որպես","ու","ում","պիտի","վրա","և"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["ada","adalah","adanya","adapun","agak","agaknya","agar","akan","akankah","akhirnya","aku","akulah","amat","amatlah","anda","andalah","antar","antara","antaranya","apa","apaan","apabila","apakah","apalagi","apatah","atau","ataukah","ataupun","bagai","bagaikan","bagaimana","bagaimanakah","bagaimanapun","bagi","bahkan","bahwa","bahwasanya","banyak","beberapa","begini","beginian","beginikah","beginilah","begitu","begitukah","begitulah","begitupun","belum","belumlah","berapa","berapakah","berapalah","berapapun","bermacam","bersama","betulkah","biasa","biasanya","bila","bilakah","bisa","bisakah","boleh","bolehkah","bolehlah","buat","bukan","bukankah","bukanlah","bukannya","cuma","dahulu","dalam","dan","dapat","dari","daripada","dekat","demi","demikian","demikianlah","dengan","depan","di","dia","dialah","diantara","diantaranya","dikarenakan","dini","diri","dirinya","disini","disinilah","dong","dulu","enggak","enggaknya","entah","entahlah","hal","hampir","hanya","hanyalah","harus","haruslah","harusnya","hendak","hendaklah","hendaknya","hingga","ia","ialah","ibarat","ingin","inginkah","inginkan","ini","inikah","inilah","itu","itukah","itulah","jangan","jangankan","janganlah","jika","jikalau","juga","justru","kala","kalau","kalaulah","kalaupun","kalian","kami","kamilah","kamu","kamulah","kan","kapan","kapankah","kapanpun","karena","karenanya","ke","kecil","kemudian","kenapa","kepada","kepadanya","ketika","khususnya","kini","kinilah","kiranya","kita","kitalah","kok","lagi","lagian","lah","lain","lainnya","lalu","lama","lamanya","lebih","macam","maka","makanya","makin","malah","malahan","mampu","mampukah","mana","manakala","manalagi","masih","masihkah","masing","mau","maupun","melainkan","melalui","memang","mengapa","mereka","merekalah","merupakan","meski","meskipun","mungkin","mungkinkah","nah","namun","nanti","nantinya","nyaris","oleh","olehnya","pada","padahal","padanya","paling","pantas","para","pasti","pastilah","per","percuma","pernah","pula","pun","rupanya","saat","saatnya","saja","sajalah","saling","sama","sambil","sampai","sana","sangat","sangatlah","saya","sayalah","se","sebab","sebabnya","sebagai","sebagaimana","sebagainya","sebaliknya","sebanyak","sebegini","sebegitu","sebelum","sebelumnya","sebenarnya","seberapa","sebetulnya","sebisanya","sebuah","sedang","sedangkan","sedemikian","sedikit","sedikitnya","segala","segalanya","segera","seharusnya","sehingga","sejak","sejenak","sekali","sekalian","sekaligus","sekalipun","sekarang","seketika","sekiranya","sekitar","sekitarnya","sela","selagi","selain","selaku","selalu","selama","selamanya","seluruh","seluruhnya","semacam","semakin","semasih","semaunya","sementara","sempat","semua","semuanya","semula","sendiri","sendirinya","seolah","seorang","sepanjang","sepantasnya","sepantasnyalah","seperti","sepertinya","sering","seringnya","serta","serupa","sesaat","sesama","sesegera","sesekali","seseorang","sesuatu","sesuatunya","sesudah","sesudahnya","setelah","seterusnya","setiap","setidaknya","sewaktu","siapa","siapakah","siapapun","sini","sinilah","suatu","sudah","sudahkah","sudahlah","supaya","tadi","tadinya","tak","tanpa","tapi","telah","tentang","tentu","tentulah","tentunya","terdiri","terhadap","terhadapnya","terlalu","terlebih","tersebut","tersebutlah","tertentu","tetapi","tiap","tidak","tidakkah","tidaklah","toh","waduh","wah","wahai","walau","walaupun","wong","yaitu","yakni","yang"]
|
||||
+1
File diff suppressed because one or more lines are too long
+1
@@ -0,0 +1 @@
|
||||
["あっ","あり","ある","い","いう","いる","う","うち","お","および","おり","か","かつて","から","が","き","ここ","こと","この","これ","これら","さ","さらに","し","しかし","する","ず","せ","せる","そして","その","その他","その後","それ","それぞれ","た","ただし","たち","ため","たり","だ","だっ","つ","て","で","でき","できる","です","では","でも","と","という","といった","とき","ところ","として","とともに","とも","と共に","な","ない","なお","なかっ","ながら","なく","なっ","など","なら","なり","なる","に","において","における","について","にて","によって","により","による","に対して","に対する","に関する","の","ので","のみ","は","ば","へ","ほか","ほとんど","ほど","ます","また","または","まで","も","もの","ものの","や","よう","より","ら","られ","られる","れ","れる","を","ん","及び","特に"]
|
||||
+1
File diff suppressed because one or more lines are too long
+1
@@ -0,0 +1 @@
|
||||
["a","ab","ac","ad","at","atque","aut","autem","cum","de","dum","e","erant","erat","est","et","etiam","ex","haec","hic","hoc","in","ita","me","nec","neque","non","per","qua","quae","quam","qui","quibus","quidem","quo","quod","re","rebus","rem","res","sed","si","sic","sunt","tamen","tandem","te","ut","vel"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["aiz","ap","apakš","apakšpus","ar","arī","augšpus","bet","bez","bija","biji","biju","bijām","bijāt","būs","būsi","būsiet","būsim","būt","būšu","caur","diemžēl","diezin","droši","dēļ","esam","esat","esi","esmu","gan","gar","iekam","iekams","iekām","iekāms","iekš","iekšpus","ik","ir","it","itin","iz","ja","jau","jeb","jebšu","jel","jo","jā","ka","kamēr","kaut","kolīdz","kopš","kā","kļuva","kļuvi","kļuvu","kļuvām","kļuvāt","kļūs","kļūsi","kļūsiet","kļūsim","kļūst","kļūstam","kļūstat","kļūsti","kļūstu","kļūt","kļūšu","labad","lai","lejpus","līdz","līdzko","ne","nebūt","nedz","nekā","nevis","nezin","no","nu","nē","otrpus","pa","par","pat","pie","pirms","pret","priekš","pār","pēc","starp","tad","tak","tapi","taps","tapsi","tapsiet","tapsim","tapt","tapāt","tapšu","taču","te","tiec","tiek","tiekam","tiekat","tieku","tik","tika","tikai","tiki","tikko","tiklab","tiklīdz","tiks","tiksiet","tiksim","tikt","tiku","tikvien","tikām","tikāt","tikšu","tomēr","topat","turpretim","turpretī","tā","tādēļ","tālab","tāpēc","un","uz","vai","var","varat","varēja","varēji","varēju","varējām","varējāt","varēs","varēsi","varēsiet","varēsim","varēt","varēšu","vien","virs","virspus","vis","viņpus","zem","ārpus","šaipus"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["अधिक","अनेक","अशी","असलयाचे","असलेल्या","असा","असून","असे","आज","आणि","आता","आपल्या","आला","आली","आले","आहे","आहेत","एक","एका","कमी","करणयात","करून","का","काम","काय","काही","किवा","की","केला","केली","केले","कोटी","गेल्या","घेऊन","जात","झाला","झाली","झाले","झालेल्या","टा","डॉ","तर","तरी","तसेच","ता","ती","तीन","ते","तो","त्या","त्याचा","त्याची","त्याच्या","त्याना","त्यानी","त्यामुळे","त्री","दिली","दोन","न","नाही","निर्ण्य","पण","पम","परयतन","पाटील","म","मात्र","माहिती","मी","मुबी","म्हणजे","म्हणाले","म्हणून","या","याचा","याची","याच्या","याना","यानी","येणार","येत","येथील","येथे","लाख","व","व्यकत","सर्व","सागित्ले","सुरू","हजार","हा","ही","हे","होणार","होत","होता","होती","होते"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["aan","achte","achter","af","al","alle","alleen","alles","als","ander","anders","beetje","behalve","beide","beiden","ben","beneden","bent","bij","bijna","bijv","blijkbaar","blijken","boven","bv","daar","daardoor","daarin","daarna","daarom","daaruit","dan","dat","de","deden","deed","derde","derhalve","dertig","deze","dhr","die","dit","doe","doen","doet","door","drie","duizend","echter","een","eens","eerst","eerste","eigen","eigenlijk","elk","elke","en","enige","er","erg","ergens","etc","etcetera","even","geen","genoeg","geweest","haar","haarzelf","had","hadden","heb","hebben","hebt","hedden","heeft","heel","hem","hemzelf","hen","het","hetzelfde","hier","hierin","hierna","hierom","hij","hijzelf","hoe","honderd","hun","ieder","iedere","iedereen","iemand","iets","ik","in","inderdaad","intussen","is","ja","je","jij","jijzelf","jou","jouw","jullie","kan","kon","konden","kun","kunnen","kunt","laatst","later","lijken","lijkt","maak","maakt","maakte","maakten","maar","mag","maken","me","meer","meest","meestal","men","met","mevr","mij","mijn","minder","miss","misschien","missen","mits","mocht","mochten","moest","moesten","moet","moeten","mogen","mr","mrs","mw","na","naar","nam","namelijk","nee","neem","negen","nemen","nergens","niemand","niet","niets","niks","noch","nochtans","nog","nooit","nu","nv","of","om","omdat","ondanks","onder","ondertussen","ons","onze","onzeker","ooit","ook","op","over","overal","overige","paar","per","recent","redelijk","samen","sinds","steeds","te","tegen","tegenover","thans","tien","tiende","tijdens","tja","toch","toe","tot","totdat","tussen","twee","tweede","u","uit","uw","vaak","van","vanaf","veel","veertig","verder","verscheidene","verschillende","via","vier","vierde","vijf","vijfde","vijftig","volgend","volgens","voor","voordat","voorts","waar","waarom","waarschijnlijk","wanneer","waren","was","wat","we","wederom","weer","weinig","wel","welk","welke","werd","werden","werder","whatever","wie","wij","wijzelf","wil","wilden","willen","word","worden","wordt","zal","ze","zei","zeker","zelf","zelfde","zes","zeven","zich","zij","zijn","zijzelf","zo","zoals","zodat","zou","zouden","zulk","zullen"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["alle","at","av","bare","begge","ble","blei","bli","blir","blitt","både","båe","da","de","deg","dei","deim","deira","deires","dem","den","denne","der","dere","deres","det","dette","di","din","disse","ditt","du","dykk","dykkar","då","eg","ein","eit","eitt","eller","elles","en","enn","er","et","ett","etter","for","fordi","fra","før","ha","hadde","han","hans","har","hennar","henne","hennes","her","hjå","ho","hoe","honom","hoss","hossen","hun","hva","hvem","hver","hvilke","hvilken","hvis","hvor","hvordan","hvorfor","i","ikke","ikkje","ingen","ingi","inkje","inn","inni","ja","jeg","kan","kom","korleis","korso","kun","kunne","kva","kvar","kvarhelst","kven","kvi","kvifor","man","mange","me","med","medan","meg","meget","mellom","men","mi","min","mine","mitt","mot","mykje","ned","no","noe","noen","noka","noko","nokon","nokor","nokre","nå","når","og","også","om","opp","oss","over","på","samme","seg","selv","si","sia","sidan","siden","sin","sine","sitt","sjøl","skal","skulle","slik","so","som","somme","somt","så","sånn","til","um","upp","ut","uten","var","vart","varte","ved","vere","verte","vi","vil","ville","vore","vors","vort","vår","være","vært","å"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["aby","ach","aj","albo","ale","ani","aż","bardzo","bez","bo","bowiem","by","byli","bym","być","był","była","było","były","będzie","będą","chce","choć","ci","ciebie","cię","co","coraz","coś","czy","czyli","często","daleko","dla","dlaczego","dlatego","do","dobrze","dokąd","dość","dr","dużo","dwa","dwaj","dwie","dwoje","dzisiaj","dziś","gdy","gdyby","gdyż","gdzie","go","godz","hab","i","ich","ii","iii","ile","im","inne","inny","inż","iv","ix","iż","ja","jak","jakby","jaki","jakie","jako","je","jeden","jedna","jednak","jedno","jednym","jedynie","jego","jej","jemu","jest","jestem","jeszcze","jeśli","jeżeli","już","ją","każdy","kiedy","kierunku","kilku","kto","która","które","którego","której","który","których","którym","którzy","ku","lat","lecz","lub","ma","mają","mam","mamy","mgr","mi","miał","mimo","mnie","mną","mogą","moi","moja","moje","może","można","mu","musi","my","mój","na","nad","nam","nami","nas","nasi","nasz","nasza","nasze","natychmiast","nawet","nic","nich","nie","niego","niej","niemu","nigdy","nim","nimi","nią","niż","no","nowe","np","nr","o","o.o.","obok","od","ok","około","on","ona","one","oni","ono","oraz","owszem","pan","pl","po","pod","ponad","ponieważ","poza","prof","przed","przede","przedtem","przez","przy","raz","razie","roku","również","sam","sama","się","skąd","sobie","sposób","swoje","są","ta","tak","taki","takich","takie","także","tam","te","tego","tej","tel","temu","ten","teraz","też","to","tobie","tobą","trzeba","tu","tutaj","twoi","twoja","twoje","twój","ty","tych","tylko","tym","tys","tzw","tę","u","ul","vi","vii","viii","vol","w","wam","wami","was","wasi","wasz","wasza","wasze","we","wie","więc","wszystko","wtedy","www","wy","właśnie","wśród","xi","xii","xiii","xiv","xv","z","za","zawsze","zaś","ze","zł","żaden","że","żeby"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["a","acerca","adeus","agora","ainda","algmas","algo","algumas","alguns","ali","além","ambos","ano","anos","antes","ao","aos","apenas","apoio","apontar","após","aquela","aquelas","aquele","aqueles","aqui","aquilo","as","assim","através","atrás","até","aí","baixo","bastante","bem","bom","breve","cada","caminho","catorze","cedo","cento","certamente","certeza","cima","cinco","coisa","com","como","comprido","conhecido","conselho","contra","corrente","custa","cá","da","daquela","daquele","dar","das","de","debaixo","demais","dentro","depois","desde","desligado","dessa","desse","desta","deste","deve","devem","deverá","dez","dezanove","dezasseis","dezassete","dezoito","dia","diante","direita","diz","dizem","dizer","do","dois","dos","doze","duas","dá","dão","dúvida","e","ela","elas","ele","eles","em","embora","enquanto","entre","então","era","essa","essas","esse","esses","esta","estado","estar","estará","estas","estava","este","estes","esteve","estive","estivemos","estiveram","estiveste","estivestes","estou","está","estás","estão","eu","exemplo","falta","fará","favor","faz","fazeis","fazem","fazemos","fazer","fazes","fazia","faço","fez","fim","final","foi","fomos","for","fora","foram","forma","foste","fostes","fui","geral","grande","grandes","grupo","hoje","horas","há","iniciar","inicio","ir","irá","isso","ista","iste","isto","já","lado","ligado","local","logo","longe","lugar","lá","maior","maioria","maiorias","mais","mal","mas","me","meio","menor","menos","meses","mesmo","meu","meus","mil","minha","minhas","momento","muito","muitos","máximo","mês","na","nada","naquela","naquele","nas","nem","nenhuma","nessa","nesse","nesta","neste","no","noite","nome","nos","nossa","nossas","nosso","nossos","nova","nove","novo","novos","num","numa","nunca","não","nível","nós","número","o","obra","obrigada","obrigado","oitava","oitavo","oito","onde","ontem","onze","os","ou","outra","outras","outro","outros","para","parece","parte","partir","pegar","pela","pelas","pelo","pelos","perto","pessoas","pode","podem","poder","poderá","podia","ponto","pontos","por","porque","porquê","posição","possivelmente","posso","possível","pouca","pouco","povo","primeira","primeiro","promeiro","próprio","próximo","puderam","pôde","põe","põem","qual","qualquer","quando","quanto","quarta","quarto","quatro","que","quem","quer","quero","questão","quieto","quinta","quinto","quinze","quê","relação","sabe","saber","se","segunda","segundo","sei","seis","sem","sempre","ser","seria","sete","seu","seus","sexta","sexto","sim","sistema","sob","sobre","sois","somente","somos","sou","sua","suas","são","sétima","sétimo","tal","talvez","também","tanto","tarde","te","tem","temos","tempo","tendes","tenho","tens","tentar","tentaram","tente","tentei","ter","terceira","terceiro","teu","teus","teve","tipo","tive","tivemos","tiveram","tiveste","tivestes","toda","todas","todo","todos","trabalhar","trabalho","treze","três","tu","tua","tuas","tudo","tão","têm","um","uma","umas","uns","usa","usar","vai","vais","valor","veja","vem","vens","ver","verdade","verdadeiro","vez","vezes","viagem","vindo","vinte","você","vocês","vos","vossa","vossas","vosso","vossos","vários","vão","vêm","vós","zero","à","às","área","é","és","último"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["acea","aceasta","această","aceea","acei","aceia","acel","acela","acele","acelea","acest","acesta","aceste","acestea","aceşti","aceştia","acolo","acord","acum","ai","aia","aibă","aici","al","ale","alea","altceva","altcineva","am","ar","are","asemenea","asta","astea","astăzi","asupra","au","avea","avem","aveţi","azi","aş","aşadar","aţi","bine","bucur","bună","ca","care","caut","ce","cel","ceva","chiar","cinci","cine","cineva","contra","cu","cum","cumva","curând","curînd","când","cât","câte","câtva","câţi","cînd","cît","cîte","cîtva","cîţi","că","căci","cărei","căror","cărui","către","da","dacă","dar","datorită","dată","dau","de","deci","deja","deoarece","departe","deşi","din","dinaintea","dintr-","dintre","doi","doilea","două","drept","după","dă","ea","ei","el","ele","eram","este","eu","eşti","face","fata","fi","fie","fiecare","fii","fim","fiu","fiţi","frumos","fără","graţie","halbă","iar","ieri","la","le","li","lor","lui","lângă","lîngă","mai","mea","mei","mele","mereu","meu","mi","mie","mine","mult","multă","mulţi","mulţumesc","mâine","mîine","mă","ne","nevoie","nici","nicăieri","nimeni","nimeri","nimic","nişte","noastre","noastră","noi","noroc","nostru","nouă","noştri","nu","opt","ori","oricare","orice","oricine","oricum","oricând","oricât","oricînd","oricît","oriunde","patra","patru","patrulea","pe","pentru","peste","pic","poate","pot","prea","prima","primul","prin","printr-","puţin","puţina","puţină","până","pînă","rog","sa","sale","sau","se","spate","spre","sub","sunt","suntem","sunteţi","sută","sînt","sîntem","sînteţi","să","săi","său","ta","tale","te","timp","tine","toate","toată","tot","totuşi","toţi","trei","treia","treilea","tu","tăi","tău","un","una","unde","undeva","unei","uneia","unele","uneori","unii","unor","unora","unu","unui","unuia","unul","vi","voastre","voastră","voi","vostru","vouă","voştri","vreme","vreo","vreun","vă","zece","zero","zi","zice","îi","îl","îmi","împotriva","în","înainte","înaintea","încotro","încât","încît","între","întrucât","întrucît","îţi","ăla","ălea","ăsta","ăstea","ăştia","şapte","şase","şi","ştiu","ţi","ţie"]
|
||||
+1
File diff suppressed because one or more lines are too long
+1
@@ -0,0 +1 @@
|
||||
["a","aby","aj","ako","aký","ale","alebo","ani","avšak","ba","bez","buï","cez","do","ho","hoci","i","ich","im","ja","jeho","jej","jemu","ju","k","kam","kde","kedže","keï","kto","ktorý","ku","lebo","ma","mi","mne","mnou","mu","my","mòa","môj","na","nad","nami","neho","nej","nemu","nich","nielen","nim","no","nám","nás","náš","ním","o","od","on","ona","oni","ono","ony","po","pod","pre","pred","pri","s","sa","seba","sem","so","svoj","taký","tam","teba","tebe","tebou","tej","ten","ti","tie","to","toho","tomu","tou","tvoj","ty","tá","tým","v","vami","veï","vo","vy","vám","vás","váš","však","z","za","zo","a","èi","èo","èí","òom","òou","òu","že"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["a","ali","april","avgust","b","bi","bil","bila","bile","bili","bilo","biti","blizu","bo","bodo","bojo","bolj","bom","bomo","boste","bova","boš","brez","c","cel","cela","celi","celo","d","da","daleč","dan","danes","datum","december","deset","deseta","deseti","deseto","devet","deveta","deveti","deveto","do","dober","dobra","dobri","dobro","dokler","dol","dolg","dolga","dolgi","dovolj","drug","druga","drugi","drugo","dva","dve","e","eden","en","ena","ene","eni","enkrat","eno","etc.","f","februar","g","g.","ga","ga.","gor","gospa","gospod","h","halo","i","idr.","ii","iii","in","iv","ix","iz","j","januar","jaz","je","ji","jih","jim","jo","julij","junij","jutri","k","kadarkoli","kaj","kajti","kako","kakor","kamor","kamorkoli","kar","karkoli","katerikoli","kdaj","kdo","kdorkoli","ker","ki","kje","kjer","kjerkoli","ko","koder","koderkoli","koga","komu","kot","kratek","kratka","kratke","kratki","l","lahka","lahke","lahki","lahko","le","lep","lepa","lepe","lepi","lepo","leto","m","maj","majhen","majhna","majhni","malce","malo","manj","marec","me","med","medtem","mene","mesec","mi","midva","midve","mnogo","moj","moja","moje","mora","morajo","moram","moramo","morate","moraš","morem","mu","n","na","nad","naj","najina","najino","najmanj","naju","največ","nam","narobe","nas","nato","nazaj","naš","naša","naše","ne","nedavno","nedelja","nek","neka","nekaj","nekatere","nekateri","nekatero","nekdo","neke","nekega","neki","nekje","neko","nekoga","nekoč","ni","nikamor","nikdar","nikjer","nikoli","nič","nje","njega","njegov","njegova","njegovo","njej","njemu","njen","njena","njeno","nji","njih","njihov","njihova","njihovo","njiju","njim","njo","njun","njuna","njuno","no","nocoj","november","npr.","o","ob","oba","obe","oboje","od","odprt","odprta","odprti","okoli","oktober","on","onadva","one","oni","onidve","osem","osma","osmi","osmo","oz.","p","pa","pet","peta","petek","peti","peto","po","pod","pogosto","poleg","poln","polna","polni","polno","ponavadi","ponedeljek","ponovno","potem","povsod","pozdravljen","pozdravljeni","prav","prava","prave","pravi","pravo","prazen","prazna","prazno","prbl.","precej","pred","prej","preko","pri","pribl.","približno","primer","pripravljen","pripravljena","pripravljeni","proti","prva","prvi","prvo","r","ravno","redko","res","reč","s","saj","sam","sama","same","sami","samo","se","sebe","sebi","sedaj","sedem","sedma","sedmi","sedmo","sem","september","seveda","si","sicer","skoraj","skozi","slab","smo","so","sobota","spet","sreda","srednja","srednji","sta","ste","stran","stvar","sva","t","ta","tak","taka","take","taki","tako","takoj","tam","te","tebe","tebi","tega","težak","težka","težki","težko","ti","tista","tiste","tisti","tisto","tj.","tja","to","toda","torek","tretja","tretje","tretji","tri","tu","tudi","tukaj","tvoj","tvoja","tvoje","u","v","vaju","vam","vas","vaš","vaša","vaše","ve","vedno","velik","velika","veliki","veliko","vendar","ves","več","vi","vidva","vii","viii","visok","visoka","visoke","visoki","vsa","vsaj","vsak","vsaka","vsakdo","vsake","vsaki","vsakomur","vse","vsega","vsi","vso","včasih","včeraj","x","z","za","zadaj","zadnji","zakaj","zaprta","zaprti","zaprto","zdaj","zelo","zunaj","č","če","često","četrta","četrtek","četrti","četrto","čez","čigav","š","šest","šesta","šesti","šesto","štiri","ž","že"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
["aad","albaabkii","atabo","ay","ayaa","ayee","ayuu","dhan","hadana","in","inuu","isku","jiray","jirtay","ka","kale","kasoo","ku","kuu","lakin","markii","oo","si","soo","uga","ugu","uu","waa","waxa","waxuu"]
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user