| 1 |
<?php |
| 2 |
/** |
| 3 |
* Module Name: WP.me Shortlinks |
| 4 |
* Module Description: Create short and simple links for all posts and pages. |
| 5 |
* Sort Order: 8 |
| 6 |
* First Introduced: 1.1 |
| 7 |
* Requires Connection: Yes |
| 8 |
* Auto Activate: Yes |
| 9 |
* Module Tags: Social |
| 10 |
* Feature: Writing |
| 11 |
* Additional Search Queries: shortlinks, wp.me |
| 12 |
*/ |
| 13 |
|
| 14 |
add_filter( 'pre_get_shortlink', 'wpme_get_shortlink_handler', 1, 4 ); |
| 15 |
|
| 16 |
if ( !function_exists( 'wpme_dec2sixtwo' ) ) { |
| 17 |
function wpme_dec2sixtwo( $num ) { |
| 18 |
$index = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; |
| 19 |
$out = ""; |
| 20 |
|
| 21 |
if ( $num < 0 ) { |
| 22 |
$out = '-'; |
| 23 |
$num = abs( $num ); |
| 24 |
} |
| 25 |
|
| 26 |
for ( $t = floor( log10( $num ) / log10( 62 ) ); $t >= 0; $t-- ) { |
| 27 |
$a = floor( $num / pow( 62, $t ) ); |
| 28 |
$out = $out . substr( $index, $a, 1 ); |
| 29 |
$num = $num - ( $a * pow( 62, $t ) ); |
| 30 |
} |
| 31 |
|
| 32 |
return $out; |
| 33 |
} |
| 34 |
} |
| 35 |
|
| 36 |
function wpme_get_shortlink( $id = 0, $context = 'post', $allow_slugs = true ) { |
| 37 |
global $wp_query; |
| 38 |
|
| 39 |
$blog_id = Jetpack_Options::get_option( 'id' ); |
| 40 |
|
| 41 |
if ( 'query' == $context ) { |
| 42 |
if ( is_singular() ) { |
| 43 |
$id = $wp_query->get_queried_object_id(); |
| 44 |
$context = 'post'; |
| 45 |
} elseif ( is_front_page() ) { |
| 46 |
$context = 'blog'; |
| 47 |
} else { |
| 48 |
return ''; |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
if ( 'blog' == $context ) { |
| 53 |
if ( empty( $id ) ) |
| 54 |
$id = $blog_id; |
| 55 |
|
| 56 |
$wpme_url = 'http://wp.me/' . wpme_dec2sixtwo( $id ); |
| 57 |
return set_url_scheme( $wpme_url ); |
| 58 |
} |
| 59 |
|
| 60 |
$post = get_post( $id ); |
| 61 |
|
| 62 |
if ( empty( $post ) ) |
| 63 |
return ''; |
| 64 |
|
| 65 |
$post_id = $post->ID; |
| 66 |
$type = ''; |
| 67 |
|
| 68 |
if ( $allow_slugs && 'publish' == $post->post_status && 'post' == $post->post_type && strlen( $post->post_name ) <= 8 && false === strpos( $post->post_name, '%' ) |
| 69 |
&& false === strpos( $post->post_name, '-' ) ) { |
| 70 |
$id = $post->post_name; |
| 71 |
$type = 's'; |
| 72 |
} else { |
| 73 |
$id = wpme_dec2sixtwo( $post_id ); |
| 74 |
if ( 'page' == $post->post_type ) |
| 75 |
$type = 'P'; |
| 76 |
elseif ( 'post' == $post->post_type || post_type_supports( $post->post_type, 'shortlinks' ) ) |
| 77 |
$type= 'p'; |
| 78 |
elseif ( 'attachment' == $post->post_type ) |
| 79 |
$type = 'a'; |
| 80 |
} |
| 81 |
|
| 82 |
if ( empty( $type ) ) |
| 83 |
return ''; |
| 84 |
|
| 85 |
$url = 'http://wp.me/' . $type . wpme_dec2sixtwo( $blog_id ) . '-' . $id; |
| 86 |
return set_url_scheme( $url ); |
| 87 |
} |
| 88 |
|
| 89 |
function wpme_get_shortlink_handler( $shortlink, $id, $context, $allow_slugs ) { |
| 90 |
return wpme_get_shortlink( $id, $context, $allow_slugs ); |
| 91 |
} |
| 92 |
|