code refactor

This commit is contained in:
Peter Molnar 2016-06-28 14:50:34 +00:00
parent 1c3b0f9dd6
commit 71bffea8dc
2 changed files with 378 additions and 392 deletions

View file

@ -4,7 +4,7 @@ Donate link: https://paypal.me/petermolnar/3
Tags: shortlink, shorturl, slug
Requires at least: 3.0
Tested up to: 4.4
Stable tag: 0.3
Stable tag: 0.4
License: GPLv3
License URI: http://www.gnu.org/licenses/gpl-3.0.html
Required minimum PHP version: 5.3
@ -32,6 +32,11 @@ Version numbering logic:
* every .B version indicates new features.
* every ..C indicates bugfixes for A.B version.
= 0.4 =
*2016-06-28*
* code refactor from static:: hell to namespace
= 0.3 =
*2016-03-01*

View file

@ -3,7 +3,7 @@
Plugin Name: wp-shortslug
Plugin URI: https://github.com/petermolnar/wp-shortslug
Description: reversible automatic short slug based on post pubdate epoch for WordPress
Version: 0.3
Version: 0.4
Author: Peter Molnar <hello@petermolnar.eu>
Author URI: http://petermolnar.eu/
License: GPLv3
@ -26,49 +26,36 @@ Required minimum PHP version: 5.3
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
if (!class_exists('WP_SHORTSLUG')):
namespace WP_SHORTSLUG;
class WP_SHORTSLUG {
const base = '0123456789abcdefghijklmnopqrstuvwxyz';
const base_camel = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
define ( 'base', '0123456789abcdefghijklmnopqrstuvwxyz' );
define ( 'base_camel', '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' );
public function __construct () {
register_activation_hook( __FILE__ , array( &$this, 'plugin_activate' ) );
\register_activation_hook( __FILE__ , 'WP_SHORTSLUG\plugin_activate' );
// init all the things!
add_action( 'init', array( &$this, 'init'));
\add_action( 'init', 'WP_SHORTSLUG\init' );
// replace shortlink
add_action( 'wp_head', array(&$this, 'shortlink'));
\add_action( 'wp_head', 'WP_SHORTSLUG\shortlink');
// trigger fallback redirection by _wp_old_slug
add_action( 'wp_head', array(&$this, 'try_redirect'));
\add_action( 'wp_head', 'WP_SHORTSLUG\try_redirect' );
// register new posts
add_action( "transition_post_status", array(&$this, "maybe_generate_slug"), 1, 3 );
add_action( "transition_post_status", array( &$this, 'check_shorturl' ), 2, 3 );
\add_action( "transition_post_status", 'WP_SHORTSLUG\maybe_generate_slug', 1, 3 );
\add_action( "transition_post_status", 'WP_SHORTSLUG\check_shorturl', 2, 3 );
/*
if (function_exists('is_admin') && is_admin() && !defined('DOING_AJAX')) {
$statuses = array ('new', 'draft', 'auto-draft', 'pending', 'private', 'future' );
foreach ($statuses as $status) {
add_action("{$status}_to_publish", array(&$this, "check_shorturl"), 2);
add_action("{$status}_to_publish", array(&$this, "maybe_generate_slug"), 1);
}
}
*/
}
public function init() {
function init() {
// shortlink replacement
add_filter( 'get_shortlink', array(&$this, 'shorturl'), 1, 4 );
\add_filter( 'get_shortlink', 'WP_SHORTSLUG\shorturl', 1, 4 );
}
/**
* activate hook
*/
public static function plugin_activate() {
function plugin_activate() {
if ( version_compare( phpversion(), 5.3, '<' ) ) {
die( 'The minimum PHP version required for this plugin is 5.3' );
}
@ -78,10 +65,10 @@ class WP_SHORTSLUG {
* try to redirect by old slug in case the current result is 404
*
*/
public static function try_redirect () {
function try_redirect () {
global $wp_query;
if ($wp_query->is_404 == true) {
wp_old_slug_redirect();
\wp_old_slug_redirect();
}
}
@ -89,19 +76,19 @@ class WP_SHORTSLUG {
* absolute short url
*
*/
public static function shorturl ( $shortlink = '', $id = '', $context = '', $allow_slugs = '' ) {
function shorturl ( $shortlink = '', $id = '', $context = '', $allow_slugs = '' ) {
global $post;
$post = static::fix_post($post);
$post = fix_post($post);
if ($post === false )
return $shortlink;
$url = static::shortslug($post);
$url = shortslug($post);
if ( defined ('SHORTSLUG_BASE') )
$base = SHORTSLUG_BASE . '/';
if ( defined ('\SHORTSLUG_BASE') )
$base = \SHORTSLUG_BASE . '/';
else
$base = rtrim( get_bloginfo('url'), '/' ) . '/';
$base = rtrim( \get_bloginfo('url'), '/' ) . '/';
return $base.$url;
}
@ -110,11 +97,11 @@ class WP_SHORTSLUG {
* print meta shortlink
*
*/
public function shortlink () {
if (function_exists('is_singular') && is_singular()) {
$url = static::shorturl();
function shortlink () {
if ( function_exists('\is_singular') && \is_singular() ) {
$url = shorturl();
if ( !empty($url) ) {
printf ('<link rel="shortlink" href="%s" />%s', static::shorturl() , "\n");
printf ('<link rel="shortlink" href="%s" />%s', shorturl() , "\n");
}
}
}
@ -122,14 +109,14 @@ class WP_SHORTSLUG {
/**
*
*/
public static function shortslug ( &$post ) {
$post = static::fix_post($post);
function shortslug ( &$post ) {
$post = fix_post($post);
if ($post === false)
return false;
$epoch = get_the_time('U', $post->ID);
$url36 = static::epoch2url($epoch);
$epoch = \get_the_time('U', $post->ID);
$url36 = epoch2url($epoch);
return $url36;
}
@ -138,21 +125,21 @@ class WP_SHORTSLUG {
* since WordPress has it's built-in rewrite engine, it's eaiser to use
* that for adding the short urls
*/
public static function check_shorturl( $new_status = false, $old_status = false, $post = null ) {
$post = static::fix_post($post);
function check_shorturl( $new_status = false, $old_status = false, $post = null ) {
$post = fix_post($post);
if ($post === false)
return false;
$meta = get_post_meta( $post->ID, '_wp_old_slug', false);
$url36 = static::shortslug($post);
$epoch = get_the_time('U', $post->ID);
$meta = \get_post_meta( $post->ID, '_wp_old_slug', false);
$url36 = shortslug($post);
$epoch = \get_the_time('U', $post->ID);
$checked = array();
foreach ($meta as $key => $slug ) {
if ( empty ($slug) ) {
static::debug( "there was an empty slug for '{$key}', deleting it early", 4 );
delete_post_meta($post->ID, '_wp_old_slug', $slug);
debug( "there was an empty slug for '{$key}', deleting it early", 4 );
\delete_post_meta($post->ID, '_wp_old_slug', $slug);
continue;
}
@ -160,20 +147,20 @@ class WP_SHORTSLUG {
array_push ( $checked, $slug );
}
else {
static::debug( "deleting slug '{$slug}' from #{$post->ID} - duplicate", 4 );
delete_post_meta($post->ID, '_wp_old_slug', $slug);
debug( "deleting slug '{$slug}' from #{$post->ID} - duplicate", 4 );
\delete_post_meta($post->ID, '_wp_old_slug', $slug);
unset($meta[$key]);
}
$decoded = static::url2epoch( $slug );
$decoded = url2epoch( $slug );
if ( ! is_numeric( $decoded ) || empty( $decoded ) || $decoded > time() ) {
continue;
}
// base36 matches which are older than the publish date should be deleted
if (preg_match('/^[0-9a-z]{5,6}$/', $slug) && $decoded < $epoch && $slug != $url36 ) {
static::debug( "deleting slug '{$slug}' from #{$post->ID} - it's older than publish date so it can't be in use", 4 );
delete_post_meta($post->ID, '_wp_old_slug', $slug);
debug( "deleting slug '{$slug}' from #{$post->ID} - it's older than publish date so it can't be in use", 4 );
\delete_post_meta( $post->ID, '_wp_old_slug', $slug );
unset($meta[$key]);
}
}
@ -201,18 +188,18 @@ class WP_SHORTSLUG {
foreach ($meta as $key => $slug ) {
// base36 matches
if (preg_match('/^[0-9a-z]{5,6}$/', $slug)) {
static::debug('deleting slug ' . $slug . ' from ' . $post->ID );
debug('deleting slug ' . $slug . ' from ' . $post->ID );
delete_post_meta($post->ID, '_wp_old_slug', $slug);
unset($meta[$key]);
}
}
}
*/
static::debug("generated slug for #{$post->ID}: '{$url36}'", 6 );
debug("generated slug for #{$post->ID}: '{$url36}'", 6 );
// if we somehow deleted the actual slug, fix it
if ( !in_array($url36,$meta)) {
static::debug('adding slug ' . $url36 . ' to ' . $post->ID, 6 );
add_post_meta($post->ID, '_wp_old_slug', $url36);
debug( "adding slug {$url36} to {$post->ID}", 6 );
\add_post_meta($post->ID, '_wp_old_slug', $url36);
}
return true;
@ -222,8 +209,8 @@ class WP_SHORTSLUG {
* since WordPress has it's built-in rewrite engine, it's eaiser to use
* that for adding the short urls
*/
public static function maybe_generate_slug( $new_status, $old_status, $post ) {
$post = static::fix_post($post);
function maybe_generate_slug( $new_status, $old_status, $post ) {
$post = fix_post($post);
if ($post === false)
return false;
@ -235,15 +222,15 @@ class WP_SHORTSLUG {
return false;
}
else {
static::debug( 'post '. $post->ID .' name is ' . $post->post_name . ' which matches pattern ' . $pattern .' or the post_title is empty, so shortslug is required.', 6 );
debug( "post {$post->ID} name is {$post->post_name} which matches pattern {$pattern} or the post_title is empty, so shortslug is required.", 6 );
}
// generate new
$url36 = static::shortslug($post);
static::debug( 'replacing slug of '. $post->ID .' with shortslug: ' . $url36, 5 );
$url36 = shortslug($post);
debug( "replacing slug of {$post->ID} with shortslug: {$url36}", 5 );
// save old, just in case
add_post_meta( $post->ID, '_wp_old_slug', $post->post_name );
\add_post_meta( $post->ID, '_wp_old_slug', $post->post_name );
/*
* this is depricated, but I'll leave it in the code for the future me:
@ -263,7 +250,7 @@ class WP_SHORTSLUG {
if (is_wp_error($wp_error)) {
$errors = json_encode($post_id->get_error_messages());
static::debug( $errors );
debug( $errors );
}
*/
@ -271,7 +258,7 @@ class WP_SHORTSLUG {
$dbname = "{$wpdb->prefix}posts";
$req = false;
static::debug("Updating post slug for #{$post->ID}", 5);
debug( "Updating post slug for #{$post->ID}", 5);
$q = $wpdb->prepare( "UPDATE `{$dbname}` SET `post_name`='%s' WHERE `ID`='{$post->ID}' LIMIT 1", $url36 );
@ -279,14 +266,14 @@ class WP_SHORTSLUG {
$req = $wpdb->query( $q );
}
catch (Exception $e) {
static::debug('Something went wrong: ' . $e->getMessage(), 4);
debug('Something went wrong: ' . $e->getMessage(), 4);
}
$meta = get_post_meta( $post->ID, '_wp_old_slug', false);
$meta = \get_post_meta( $post->ID, '_wp_old_slug', false);
if ( in_array( $url36, $meta ) ) {
static::debug('removing slug ' . $url36 . ' from ' . $post->ID, 5 );
delete_post_meta($post->ID, '_wp_old_slug', $url36);
debug( "removing slug {$url36} from {$post->ID}", 5 );
\delete_post_meta($post->ID, '_wp_old_slug', $url36);
}
return true;
@ -297,17 +284,17 @@ class WP_SHORTSLUG {
* decode short string and covert it back to UNIX EPOCH
*
*/
public static function url2epoch( $str, $b = 36 ) {
function url2epoch( $str, $b = 36 ) {
if ( empty ( $str ) ) {
static::debug( 'url2epoch to empty string to match; trace: ' . json_encode( debug_backtrace() ) );
debug( 'url2epoch to empty string to match; trace: ' . json_encode( debug_backtrace() ) );
return false;
}
if ($b <= 36 )
$base = static::base;
$base = base;
else
$base = static::base_camel;
$base = base_camel;
$limit = strlen($str);
$res=strpos($base,$str[0]);
@ -323,12 +310,12 @@ class WP_SHORTSLUG {
*
* thanks to https://stackoverflow.com/questions/4964197/converting-a-number-base-10-to-base-62-a-za-z0-9
*/
public static function epoch2url($num, $b = 36 ) {
function epoch2url($num, $b = 36 ) {
if ($b <= 36 )
$base = static::base;
$base = base;
else
$base = static::base_camel;
$base = base_camel;
$r = $num % $b ;
$res = $base[$r];
@ -345,11 +332,11 @@ class WP_SHORTSLUG {
/**
* do everything to get the Post object
*/
public static function fix_post ( &$post = null ) {
if ($post === null || !static::is_post($post))
function fix_post ( &$post = null ) {
if ($post === null || !is_post($post))
global $post;
if (static::is_post($post))
if (is_post($post))
return $post;
return false;
@ -358,7 +345,7 @@ class WP_SHORTSLUG {
/**
* test if an object is actually a post
*/
public static function is_post ( &$post ) {
function is_post ( &$post ) {
if ( !empty($post) && is_object($post) && isset($post->ID) && !empty($post->ID) )
return true;
@ -376,7 +363,7 @@ class WP_SHORTSLUG {
* @output log to syslog | wp_die on high level
* @return false on not taking action, true on log sent
*/
public static function debug( $message, $level = LOG_NOTICE ) {
function debug( $message, $level = LOG_NOTICE ) {
if ( empty( $message ) )
return false;
@ -399,8 +386,8 @@ class WP_SHORTSLUG {
$level_ = $levels [ $level ];
// in case WordPress debug log has a minimum level
if ( defined ( 'WP_DEBUG_LEVEL' ) ) {
$wp_level = $levels [ WP_DEBUG_LEVEL ];
if ( defined ( '\WP_DEBUG_LEVEL' ) ) {
$wp_level = $levels [ \WP_DEBUG_LEVEL ];
if ( $level_ > $wp_level ) {
return false;
}
@ -408,7 +395,7 @@ class WP_SHORTSLUG {
// ERR, CRIT, ALERT and EMERG
if ( 3 >= $level_ ) {
wp_die( '<h1>Error:</h1>' . '<p>' . $message . '</p>' );
\wp_die( '<h1>Error:</h1>' . '<p>' . $message . '</p>' );
exit;
}
@ -421,9 +408,3 @@ class WP_SHORTSLUG {
return error_log( "{$parent}: {$message}" );
}
}
$WP_SHORTSLUG = new WP_SHORTSLUG();
endif;