Advertisement
Guest User

permalink-manager-helper-functions.php

a guest
May 6th, 2020
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 23.13 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4. * Additional functions used in classes and another subclasses
  5. */
  6. class Permalink_Manager_Helper_Functions extends Permalink_Manager_Class {
  7.  
  8.     public function __construct() {
  9.         add_action('plugins_loaded', array($this, 'init'), 5);
  10.     }
  11.  
  12.     public function init() {
  13.         // Replace empty placeholder tags & remove BOM
  14.         add_filter( 'permalink_manager_filter_default_post_uri', array($this, 'replace_empty_placeholder_tags'), 10, 5);
  15.         add_filter( 'permalink_manager_filter_default_term_uri', array($this, 'replace_empty_placeholder_tags'), 10, 5);
  16.  
  17.         // Clear the final default URIs
  18.         add_filter( 'permalink_manager_filter_default_term_uri', array($this, 'clear_single_uri'), 20);
  19.         add_filter( 'permalink_manager_filter_default_post_uri', array($this, 'clear_single_uri'), 20);
  20.  
  21.         // Reload the globals when the blog is switched (multisite)
  22.         add_action('switch_blog', array($this, 'reload_globals_in_network'), 9);
  23.     }
  24.  
  25.     /**
  26.      * Support for multidimensional arrays - array_map()
  27.      */
  28.     static function multidimensional_array_map($function, $input) {
  29.         $output = array();
  30.  
  31.         if(is_array($input)) {
  32.             foreach ($input as $key => $val) {
  33.                 $output[$key] = (is_array($val) ? self::multidimensional_array_map($function, $val) : $function($val));
  34.             }
  35.         } else {
  36.             $output = $function($input);
  37.         }
  38.  
  39.         return $output;
  40.     }
  41.  
  42.     /**
  43.      * Get primary term
  44.      */
  45.     static function get_primary_term($post_id, $taxonomy, $slug_only = true) {
  46.         global $permalink_manager_options;
  47.  
  48.         $primary_term_enabled = apply_filters('permalink_manager_primary_term', true);
  49.  
  50.         if(!$primary_term_enabled) { return; }
  51.  
  52.         // A. Yoast SEO
  53.         if(class_exists('WPSEO_Primary_Term')) {
  54.             $primary_term = new WPSEO_Primary_Term($taxonomy, $post_id);
  55.             $primary_term = get_term($primary_term->get_primary_term());
  56.         }
  57.         // B. The SEO Framework
  58.         else if(function_exists('the_seo_framework')) {
  59.             $primary_term = the_seo_framework()->get_primary_term($post_id, $taxonomy);
  60.         }
  61.         // C. RankMath
  62.         else if(class_exists('RankMath')) {
  63.             $primary_cat_id = get_post_meta($post_id, "rank_math_primary_{$taxonomy}", true);
  64.             $primary_term = (!empty($primary_cat_id)) ? get_term($primary_cat_id, $taxonomy) : '';
  65.         }
  66.         // D. SEOPress
  67.         else if(function_exists('seopress_init') && $taxonomy == 'category') {
  68.             $primary_cat_id = get_post_meta($post_id, '_seopress_robots_primary_cat', true);
  69.             $primary_term = (!empty($primary_cat_id)) ? get_term($primary_cat_id, 'category') : '';
  70.         }
  71.  
  72.         if(!empty($primary_term) && !is_wp_error($primary_term)) {
  73.             return ($slug_only) ? $primary_term->slug : $primary_term;
  74.         } else {
  75.             return;
  76.         }
  77.     }
  78.  
  79.     /**
  80.      * Get lowest level term/post
  81.      */
  82.     static function get_lowest_element($first_element, $elements) {
  83.         if(!empty($elements) && !empty($first_element)) {
  84.             // Get the ID of first element
  85.             if(!empty($first_element->term_id)) {
  86.                 $first_element_id = $first_element->term_id;
  87.                 $parent_key = 'parent';
  88.             } else if(!empty($first_element->ID)) {
  89.                 $first_element_id = $first_element->ID;
  90.                 $parent_key = 'post_parent';
  91.             } else if(is_numeric($first_element)) {
  92.                 $first_element_id = $first_element;
  93.                 $parent_key = 'post_parent';
  94.             } else {
  95.                 return false;
  96.             }
  97.  
  98.             $children = wp_filter_object_list($elements, array($parent_key => $first_element_id));
  99.             if(!empty($children)) {
  100.                 // Get the first term
  101.                 $child_term = reset($children);
  102.                 $first_element = self::get_lowest_element($child_term, $elements);
  103.             }
  104.         }
  105.         return $first_element;
  106.     }
  107.  
  108.     /**
  109.      * Get term full slug
  110.      */
  111.     static function get_term_full_slug($term, $terms, $mode = false, $native_uri = false) {
  112.         global $permalink_manager_uris;
  113.  
  114.         // Check if term is not empty
  115.         if(empty($term->taxonomy)) { return ''; }
  116.  
  117.         // Get taxonomy
  118.         $taxonomy = $term->taxonomy;
  119.  
  120.         // Check if mode is set
  121.         if(empty($mode)) {
  122.             $mode = (is_taxonomy_hierarchical($taxonomy)) ? 2 : 4;
  123.         }
  124.  
  125.         // A. Get permalink base from the term's custom URI
  126.         if($mode == 1) {
  127.             $term_slug = $permalink_manager_uris["tax-{$term->term_id}"];
  128.         }
  129.         // B. Hierarhcical taxonomy base
  130.         else if($mode == 2) {
  131.             $ancestors = get_ancestors($term->term_id, $taxonomy, 'taxonomy');
  132.             $hierarchical_slugs = array();
  133.  
  134.             foreach((array) $ancestors as $ancestor) {
  135.                 $ancestor_term = get_term($ancestor, $taxonomy);
  136.                 $hierarchical_slugs[] = ($native_uri) ? $ancestor_term->slug : self::force_custom_slugs($ancestor_term->slug, $ancestor_term);
  137.             }
  138.             $hierarchical_slugs = array_reverse($hierarchical_slugs);
  139.             $term_slug = implode('/', $hierarchical_slugs);
  140.  
  141.             // Append the term slug now
  142.             $last_term_slug = ($native_uri) ? $term->slug : self::force_custom_slugs($term->slug, $term);
  143.             $term_slug = "{$term_slug}/{$last_term_slug}";
  144.         }
  145.         // C. Force flat taxonomy base - get highgest level term (if %taxonomy_flat% tag is used)
  146.         else if($mode == 4) {
  147.             foreach($terms as $single_term) {
  148.                 if($single_term->parent == 0) {
  149.                     $term_slug = self::force_custom_slugs($single_term->slug, $single_term);
  150.                     break;
  151.                 }
  152.             }
  153.         }
  154.         // D. Flat/non-hierarchical taxonomy base - get primary term (if set) or first term
  155.         else if(!empty($term->slug)) {
  156.             $term_slug = ($native_uri) ? $term->slug : Permalink_Manager_Helper_Functions::force_custom_slugs($term->slug, $term);
  157.         }
  158.  
  159.         return (!empty($term_slug)) ? $term_slug : "";
  160.     }
  161.  
  162.     /**
  163.      * Allow to disable post types and taxonomies
  164.      */
  165.     static function get_disabled_post_types($include_user_excluded = true) {
  166.         global $wp_post_types, $permalink_manager_options;
  167.  
  168.         $disabled_post_types = array('revision', 'algolia_task', 'fl_builder', 'fl-builder', 'fl-builder-template', 'fl-theme-layout', 'wc_product_tab', 'wc_voucher', 'wc_voucher_template', 'sliders', 'thirstylink', 'elementor_library', 'cms_block');
  169.  
  170.         // 1. Disable post types that are not publicly_queryable
  171.         foreach($wp_post_types as $post_type) {
  172.             $is_publicly_queryable = (!empty($post_type->publicly_queryable) || (!empty($post_type->public) && !empty($post_type->rewrite))) ? true : false;
  173.  
  174.             if(!$is_publicly_queryable && !in_array($post_type->name, array('post', 'page', 'attachment'))) {
  175.                 $disabled_post_types[] = $post_type->name;
  176.             }
  177.         }
  178.  
  179.         // 2. Add post types disabled by user
  180.         if($include_user_excluded) {
  181.             $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;
  182.         }
  183.  
  184.         return apply_filters('permalink_manager_disabled_post_types', $disabled_post_types);
  185.     }
  186.  
  187.     static function get_disabled_taxonomies($include_user_excluded = true) {
  188.         global $wp_taxonomies, $permalink_manager_options;
  189.  
  190.         $disabled_taxonomies = array('product_shipping_class', 'post_status', 'fl-builder-template-category', 'post_format', 'nav_menu');
  191.  
  192.         // 1. Disable taxonomies that are not publicly_queryable
  193.         foreach($wp_taxonomies as $taxonomy) {
  194.             $is_publicly_queryable = (!empty($taxonomy->publicly_queryable) || (!empty($taxonomy->public) && !empty($taxonomy->rewrite))) ? true : false;
  195.  
  196.             if(!$is_publicly_queryable && !in_array($taxonomy->name, array('category', 'post_tag'))) {
  197.                 $disabled_taxonomies[] = $taxonomy->name;
  198.             }
  199.         }
  200.  
  201.         // 2. Add taxonomies disabled by user
  202.         if($include_user_excluded) {
  203.             $disabled_taxonomies = (!empty($permalink_manager_options['general']['partial_disable']['taxonomies'])) ? array_merge((array) $permalink_manager_options['general']['partial_disable']['taxonomies'], $disabled_taxonomies) : $disabled_taxonomies;
  204.         }
  205.  
  206.         return apply_filters('permalink_manager_disabled_taxonomies', $disabled_taxonomies);
  207.     }
  208.  
  209.     static public function is_disabled($content_name, $content_type = 'post_type', $check_if_exists = true) {
  210.         $out = false;
  211.  
  212.         if($content_type == 'post_type') {
  213.             $disabled_post_types = self::get_disabled_post_types();
  214.             $post_type_exists = ($check_if_exists) ? post_type_exists($content_name) : true;
  215.             $out = ((is_array($disabled_post_types) && in_array($content_name, $disabled_post_types)) || empty($post_type_exists)) ? true : false;
  216.         } else {
  217.             $disabled_taxonomies = self::get_disabled_taxonomies();
  218.             $taxonomy_exists = ($check_if_exists) ? taxonomy_exists($content_name) : true;
  219.             $out = ((is_array($disabled_taxonomies) && in_array($content_name, $disabled_taxonomies)) || empty($taxonomy_exists)) ? true : false;
  220.         }
  221.  
  222.         return $out;
  223.     }
  224.  
  225.     /**
  226.      * Get all post types supported by Permalink Manager
  227.      */
  228.     static function get_post_types_array($format = null, $cpt = null, $include_user_excluded = false) {
  229.         global $wp_post_types;
  230.  
  231.         $post_types_array = array();
  232.         $disabled_post_types = self::get_disabled_post_types(!$include_user_excluded);
  233.  
  234.         foreach($wp_post_types as $post_type) {
  235.             $post_types_array[$post_type->name] = ($format == 'full') ? array('label' => $post_type->labels->name, 'name' => $post_type->name) : $post_type->labels->name;
  236.         }
  237.  
  238.         if(is_array($disabled_post_types)) {
  239.             foreach($disabled_post_types as $post_type) {
  240.                 if(!empty($post_types_array[$post_type])) {
  241.                     unset($post_types_array[$post_type]);
  242.                 }
  243.             }
  244.         }
  245.  
  246.         return (empty($cpt)) ? $post_types_array : $post_types_array[$cpt];
  247.     }
  248.  
  249.     /**
  250.      * Get all taxonomies supported by Permalink Manager
  251.      */
  252.     static function get_taxonomies_array($format = null, $tax = null, $prefix = false, $include_user_excluded = false, $settings = false) {
  253.         global $wp_taxonomies;
  254.  
  255.         $taxonomies_array = array();
  256.         $disabled_taxonomies = self::get_disabled_taxonomies(!$include_user_excluded);
  257.  
  258.         foreach($wp_taxonomies as $taxonomy) {
  259.             $key = ($prefix) ? "tax-{$taxonomy->name}" : $taxonomy->name;
  260.             $taxonomies_array[$taxonomy->name] = ($format == 'full') ? array('label' => $taxonomy->labels->name, 'name' => $taxonomy->name) : $taxonomy->labels->name;
  261.         }
  262.  
  263.         if(is_array($disabled_taxonomies)) {
  264.             foreach($disabled_taxonomies as $taxonomy) {
  265.                 if(!empty($taxonomies_array[$taxonomy])) {
  266.                     unset($taxonomies_array[$taxonomy]);
  267.                 }
  268.             }
  269.         }
  270.  
  271.         ksort($taxonomies_array);
  272.  
  273.         return (empty($tax)) ? $taxonomies_array : $taxonomies_array[$tax];
  274.     }
  275.  
  276.     /**
  277.      * Get all post statuses supported by Permalink Manager
  278.      */
  279.     static function get_post_statuses() {
  280.         $post_statuses = get_post_statuses();
  281.  
  282.         return apply_filters('permalink_manager_post_statuses', $post_statuses);
  283.     }
  284.  
  285.     /**
  286.     * Get permastruct
  287.     */
  288.     static function get_default_permastruct($post_type = 'page', $remove_post_tag = false) {
  289.         global $wp_rewrite;
  290.  
  291.         // Get default permastruct
  292.         if($post_type == 'page') {
  293.             $permastruct = $wp_rewrite->get_page_permastruct();
  294.         } else if($post_type == 'post') {
  295.             $permastruct = get_option('permalink_structure');
  296.         } else {
  297.             $permastruct = $wp_rewrite->get_extra_permastruct($post_type);
  298.         }
  299.  
  300.         return ($remove_post_tag) ? trim(str_replace(array("%postname%", "%pagename%", "%{$post_type}%"), "", $permastruct), "/") : $permastruct;
  301.     }
  302.  
  303.     /**
  304.      * Get all endpoints
  305.      */
  306.     static function get_endpoints() {
  307.         global $wp_rewrite;
  308.  
  309.         $pagination_endpoint = (!empty($wp_rewrite->pagination_base)) ? $wp_rewrite->pagination_base : 'page';
  310.  
  311.         // Start with default endpoints
  312.         $endpoints = "{$pagination_endpoint}|feed|embed|attachment|trackback|filter";
  313.  
  314.         if(!empty($wp_rewrite->endpoints)) {
  315.             foreach($wp_rewrite->endpoints as $endpoint) {
  316.                 $endpoints .= "|{$endpoint[1]}";
  317.             }
  318.         }
  319.  
  320.         return apply_filters("permalink_manager_endpoints", str_replace("/", "\/", $endpoints));
  321.     }
  322.  
  323.     /**
  324.     * Structure Tags & Rewrite functions
  325.     */
  326.     static function get_all_structure_tags($code = true, $seperator = ', ', $hide_slug_tags = true) {
  327.         global $wp_rewrite;
  328.  
  329.         $tags = $wp_rewrite->rewritecode;
  330.  
  331.         // Hide slug tags
  332.         if($hide_slug_tags) {
  333.             $post_types = Permalink_Manager_Helper_Functions::get_post_types_array();
  334.             foreach($post_types as $post_type => $post_type_name) {
  335.                 $post_type_tag = Permalink_Manager_Helper_Functions::get_post_tag($post_type);
  336.                 // Find key with post type tag from rewritecode
  337.                 $key = array_search($post_type_tag, $tags);
  338.                 if($key) { unset($tags[$key]); }
  339.             }
  340.         }
  341.  
  342.         // Extra tags
  343.         $tags[] = '%taxonomy%';
  344.         $tags[] = '%post_type%';
  345.         $tags[] = '%term_id%';
  346.         $tags[] = '%monthname%';
  347.  
  348.         foreach($tags as &$tag) {
  349.             $tag = ($code) ? "<code>{$tag}</code>" : "{$tag}";
  350.         }
  351.         $output = implode($seperator, $tags);
  352.  
  353.         return "<span class=\"structure-tags-list\">{$output}</span>";
  354.     }
  355.  
  356.     /**
  357.     * Get endpoint used to mark the postname or its equivalent for custom post types and pages in permastructures
  358.     */
  359.     static function get_post_tag($post_type) {
  360.         // Get the post type (with fix for posts & pages)
  361.         if($post_type == 'page') {
  362.             $post_type_tag = '%pagename%';
  363.         } else if ($post_type == 'post') {
  364.             $post_type_tag = '%postname%';
  365.         } else {
  366.             $post_type_tag = "%{$post_type}%";
  367.         }
  368.         return $post_type_tag;
  369.     }
  370.  
  371.     /**
  372.     * Find taxonomy name using "term_id"
  373.     */
  374.     static function get_tax_name($term, $term_by = 'id') {
  375.         $term_object = get_term_by($term_by, $term);
  376.         return (isset($term_object->taxonomy)) ? $term_object->taxonomy : '';
  377.     }
  378.  
  379.     /**
  380.      * Get permalink base (home URL)
  381.      */
  382.     public static function get_permalink_base($element = null) {
  383.         return apply_filters('permalink_manager_filter_permalink_base', trim(get_option('home'), "/"), $element);
  384.     }
  385.  
  386.     /**
  387.      * Remove post tag from permastructure
  388.      */
  389.     static function remove_post_tag($permastruct) {
  390.         $post_types = self::get_post_types_array('full');
  391.  
  392.         // Get all post tags
  393.         $post_tags = array("%postname%", "%pagename%");
  394.         foreach($post_types as $post_type) {
  395.             $post_tags[] = "%{$post_type['name']}%";
  396.         }
  397.  
  398.         $permastruct = str_replace($post_tags, "", $permastruct);
  399.         return trim($permastruct, "/");
  400.     }
  401.  
  402.     /**
  403.      * Get front-page ID
  404.      */
  405.     static function is_front_page($page_id) {
  406.         $front_page_id = get_option('page_on_front');
  407.         $bool = (!empty($front_page_id) && $page_id == $front_page_id) ? true : false;
  408.  
  409.         return apply_filters('permalink_manager_is_front_page', $bool, $page_id, $front_page_id);
  410.     }
  411.  
  412.     /**
  413.      * Sanitize multidimensional array
  414.      */
  415.     static function sanitize_array($data = array()) {
  416.         if (!is_array($data) || !count($data)) {
  417.             return array();
  418.         }
  419.  
  420.         foreach ($data as $k => $v) {
  421.             if (!is_array($v) && !is_object($v)) {
  422.                 $data[$k] = htmlspecialchars(trim($v));
  423.             }
  424.             if (is_array($v)) {
  425.                 $data[$k] = self::sanitize_array($v);
  426.             }
  427.         }
  428.         return $data;
  429.     }
  430.  
  431.     /**
  432.      * Encode URI and keep special characters
  433.      */
  434.     static function encode_uri($uri) {
  435.         return str_replace(array('%2F', '%2C', '%7C', '%2B'), array('/', ',', '|', '+'), urlencode($uri));
  436.     }
  437.  
  438.     /**
  439.      * Slugify function
  440.      */
  441.     public static function sanitize_title($str, $keep_percent_sign = false, $force_lowercase = null, $sanitize_slugs = null) {
  442.         global $permalink_manager_options;
  443.  
  444.         // Foree lowercase & hyphens
  445.         $force_lowercase = (!is_null($force_lowercase)) ? $force_lowercase : apply_filters('permalink_manager_force_lowercase_uris', true);
  446.  
  447.         if(is_null($sanitize_slugs)) {
  448.             $sanitize_slugs = (!empty($permalink_manager_options['general']['disable_slug_sanitization'])) ? false : true;
  449.         }
  450.  
  451.         // Trim slashes & whitespaces
  452.         $clean = trim($str, " /");
  453.  
  454.         // Remove accents
  455.         $clean = (empty($permalink_manager_options['general']['keep_accents'])) ? remove_accents($clean) : $clean;
  456.  
  457.         $percent_sign = ($keep_percent_sign) ? "\%" : "";
  458.         //$sanitize_regex = apply_filters("permalink_manager_sanitize_regex", "/[^\p{Thai}\p{Greek}\p{Hebrew}\p{Arabic}\p{Cyrillic}a-zA-Z0-9{$percent_sign}\/_\.|+, -]/u", $percent_sign);
  459.         $sanitize_regex = apply_filters("permalink_manager_sanitize_regex", "/[^\p{Xan}a-zA-Z0-9{$percent_sign}\/_\.|+, -]/ui", $percent_sign);
  460.         $clean = preg_replace($sanitize_regex, '', $clean);
  461.         $clean = ($force_lowercase) ? strtolower(trim($clean, '-')) : trim($clean, '-');
  462.  
  463.         // Remove amperand
  464.         $clean = str_replace(array('%26', '&'), '', $clean);
  465.  
  466.         // Remove special characters
  467.         if($sanitize_slugs !== false) {
  468.             $clean = preg_replace("/[\s_|+-]+/", "-", $clean);
  469.             $clean = preg_replace("/[,]+/", "", $clean);
  470.             $clean = preg_replace('/([\.]+)(?![a-z]{3,4}$)/i', '', $clean);
  471.             $clean = preg_replace('/([-\s+]\/[-\s+])/', '-', $clean);
  472.         } else {
  473.             $clean = preg_replace("/[\s]+/", "-", $clean);
  474.         }
  475.  
  476.         // Remove trailing slashes
  477.         $clean = str_replace(array('-/', '/-', '//'), '/', $clean);
  478.  
  479.         return $clean;
  480.     }
  481.  
  482.     /**
  483.      * Replace empty placeholder tags & remove BOM
  484.      */
  485.     public static function replace_empty_placeholder_tags($default_uri, $native_slug = "", $element = "", $slug = "", $native_uri = "") {
  486.         // Do not affect native URIs
  487.         if($native_uri == true) { return $default_uri; }
  488.  
  489.         // Remove the BOM
  490.         $default_uri = str_replace(array("\xEF\xBB\xBF", "%ef%bb%bf"), '', $default_uri);
  491.  
  492.         // Encode the URI before placeholders are removed
  493.         $chunks = explode('/', $default_uri);
  494.         foreach ($chunks as &$chunk) {
  495.             if(preg_match("/^(%.+?%)$/", $chunk) == false) {
  496.                 $chunk = rawurldecode($chunk);
  497.             }
  498.         }
  499.         $default_uri = implode("/", $chunks);
  500.  
  501.         $empty_tag_replacement = apply_filters('permalink_manager_empty_tag_replacement', null, $element);
  502.         $default_uri = ($empty_tag_replacement || is_null($empty_tag_replacement)) ? str_replace("//", "/", preg_replace("/%(.+?)%/", $empty_tag_replacement, $default_uri)) : $default_uri;
  503.  
  504.         return trim($default_uri, "/");
  505.     }
  506.  
  507.     /**
  508.      * Clear/Sanitize the URI
  509.      */
  510.     public static function clear_single_uri($uri) {
  511.         return self::sanitize_title($uri, true);
  512.     }
  513.  
  514.     /**
  515.      * Remove all slashes
  516.      */
  517.     public static function remove_slashes($uri) {
  518.         return preg_replace("/[\/]+/", "", $uri);
  519.     }
  520.  
  521.     /**
  522.      * Force custom slugs
  523.      */
  524.     public static function force_custom_slugs($slug, $object, $flat = false) {
  525.         global $permalink_manager_options, $permalink_manager_uris;
  526.  
  527.         $force_custom_slugs = (!empty($permalink_manager_options['general']['force_custom_slugs'])) ? $permalink_manager_options['general']['force_custom_slugs'] : false;
  528.         $force_custom_slugs = apply_filters('permalink_manager_force_custom_slugs', $force_custom_slugs, $slug, $object);
  529.  
  530.         if($force_custom_slugs) {
  531.             // A. Custom slug (title)
  532.             if($force_custom_slugs == 1) {
  533.                 $title = (!empty($object->name)) ? $object->name : $object->post_title;
  534.                 $title = self::remove_slashes($title);
  535.  
  536.                 $new_slug = self::sanitize_title($title, false, null, null);
  537.             }
  538.             // B. Custom slug (custom permalink)
  539.             else {
  540.                 $object_id = (!empty($object->term_id)) ? "tax-{$object->term_id}" : $object->ID;
  541.                 $new_slug = (!empty($permalink_manager_uris[$object_id])) ? basename($permalink_manager_uris[$object_id]) : '';
  542.             }
  543.  
  544.             $slug = (!empty($new_slug)) ? preg_replace('/([^\/]+)$/', $new_slug, $slug) : $slug;
  545.         }
  546.  
  547.         if($flat) {
  548.             $slug = preg_replace("/([^\/]+)(.*)/", "$1", $slug);
  549.         }
  550.  
  551.         return $slug;
  552.     }
  553.  
  554.     public static function element_exists($element_id) {
  555.         global $wpdb;
  556.  
  557.         if(strpos($element_id, 'tax-') !== false) {
  558.             $term_id = intval(preg_replace("/[^0-9]/", "", $element_id));
  559.             $element_exists = $wpdb->get_var( "SELECT * FROM {$wpdb->prefix}terms WHERE term_id = {$term_id}" );
  560.         } else {
  561.             $element_exists = $wpdb->get_var( "SELECT * FROM {$wpdb->prefix}posts WHERE ID = {$element_id} AND post_status NOT IN ('auto-draft', 'trash') AND post_type != 'nav_menu_item'" );
  562.         }
  563.  
  564.         return (!empty($element_exists)) ? $element_exists : false;
  565.     }
  566.  
  567.     /**
  568.      * Detect duplicates
  569.      */
  570.     public static function get_all_duplicates($include_custom_uris = true) {
  571.         global $permalink_manager_uris, $permalink_manager_redirects, $permalink_manager_options, $wpdb;
  572.  
  573.         // Make sure that both variables are arrays
  574.         $all_uris = ($include_custom_uris && is_array($permalink_manager_uris)) ? $permalink_manager_uris : array();
  575.         $permalink_manager_redirects = (is_array($permalink_manager_redirects)) ? $permalink_manager_redirects : array();
  576.  
  577.         // Convert redirects list, so it can be merged with $permalink_manager_uris
  578.         foreach($permalink_manager_redirects as $element_id => $redirects) {
  579.             if(is_array($redirects)) {
  580.                 foreach($redirects as $index => $uri) {
  581.                     $all_uris["redirect-{$index}_{$element_id}"] = $uri;
  582.                 }
  583.             }
  584.         }
  585.  
  586.         // Count duplicates
  587.         $duplicates_removed = 0;
  588.         $duplicates_groups = array();
  589.         $duplicates_list = array_count_values($all_uris);
  590.         $duplicates_list = array_filter($duplicates_list, function ($x) { return $x >= 2; });
  591.  
  592.         // Assign keys to duplicates (group them)
  593.         if(count($duplicates_list) > 0) {
  594.             foreach($duplicates_list as $duplicated_uri => $count) {
  595.                 $duplicated_ids = array_keys($all_uris, $duplicated_uri);
  596.  
  597.                 // Ignore duplicates in different langauges
  598.                 if(self::is_uri_duplicated($duplicated_uri, $duplicated_ids[0])) {
  599.                     $duplicates_groups[$duplicated_uri] = $duplicated_ids;
  600.                 }
  601.             }
  602.         }
  603.  
  604.         return $duplicates_groups;
  605.     }
  606.  
  607.     /**
  608.      * Check if a single URI is duplicated
  609.      */
  610.     public static function is_uri_duplicated($uri, $element_id) {
  611.         global $permalink_manager_uris;
  612.  
  613.         if(empty($uri) || empty($element_id)) { return false; }
  614.  
  615.         $uri = trim(trim(sanitize_text_field($uri)), "/");
  616.         $element_id = sanitize_text_field($element_id);
  617.  
  618.         // Keep the URIs in a separate array just here & unset the URI for requested element to prevent false alert
  619.         $all_uris = $permalink_manager_uris;
  620.         unset($all_uris[$element_id]);
  621.  
  622.         if(in_array($uri, $all_uris)) {
  623.             $all_duplicates = (array) array_keys($all_uris, $uri);
  624.             $this_uri_lang = Permalink_Manager_Language_Plugins::get_language_code($element_id);
  625.  
  626.             if($this_uri_lang) {
  627.                 foreach($all_duplicates as $key => $duplicated_id) {
  628.                     $duplicated_uri_lang = Permalink_Manager_Language_Plugins::get_language_code($duplicated_id);
  629.  
  630.                     if($duplicated_uri_lang !== $this_uri_lang) {
  631.                         unset($all_duplicates[$key]);
  632.                     }
  633.                 }
  634.  
  635.                 return (count($all_duplicates) > 0) ? true : false;
  636.             } else {
  637.                 return true;
  638.             }
  639.         } else {
  640.             return false;
  641.         }
  642.     }
  643.  
  644.     /**
  645.      * URI Search
  646.      */
  647.     public static function search_uri($search_query, $content_type = null) {
  648.         global $permalink_manager_uris;
  649.  
  650.         $found = array();
  651.         $search_query = preg_quote($search_query, '/');
  652.  
  653.         foreach($permalink_manager_uris as $id => $uri) {
  654.             if(preg_match("/\b$search_query\b/i", $uri)) {
  655.                 if($content_type && $content_type == 'taxonomies' && (strpos($id, 'tax-') !== false)) {
  656.                     $found[] = (int) abs(filter_var($id, FILTER_SANITIZE_NUMBER_INT));
  657.                 } else if($content_type && $content_type == 'posts' && is_numeric($id)) {
  658.                     $found[] = (int) filter_var($id, FILTER_SANITIZE_NUMBER_INT);
  659.                 } else {
  660.                     $found[] = $id;
  661.                 }
  662.             }
  663.         }
  664.  
  665.         return $found;
  666.     }
  667.  
  668.     /**
  669.      * Reload the globals when the blog is switched (multisite)
  670.      */
  671.     public function reload_globals_in_network($new_blog_id) {
  672.       global $permalink_manager_uris, $permalink_manager_redirects, $permalink_manager_external_redirects;
  673.  
  674.         if(function_exists('get_blog_option')) {
  675.           $permalink_manager_uris = get_blog_option($new_blog_id, 'permalink-manager-uris');
  676.           $permalink_manager_redirects = get_blog_option($new_blog_id, 'permalink-manager-redirects');
  677.           $permalink_manager_external_redirects = get_blog_option($new_blog_id, 'permalink-manager-external-redirects');
  678.         }
  679.     }
  680.  
  681.  
  682. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement