all repos — wp-webmention-again @ f8bee3dfb07769ffc8900051c28c73f4f1e2623f

wp-webmention-again.php (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
<?php
/*
Plugin Name: wp-webmention-again
Plugin URI: https://github.com/petermolnar/wp-webmention-again
Description:
Version: 0.3
Author: Peter Molnar <hello@petermolnar.eu>
Author URI: http://petermolnar.eu/
License: GPLv3
Required minimum PHP version: 5.3
*/

if ( ! class_exists( 'WP_Webmention_Again' ) ):

// something else might have loaded this already
if ( ! class_exists( 'Mf2\Parser' ) ) {
	require ( __DIR__ . '/vendor/autoload.php' );
}

// if something has loaded Mf2 already, the autoload won't kick in,
// and we need this
if ( ! class_exists( 'EmojiRecognizer' ) ) {
	require ( __DIR__ . '/vendor/dissolve/single-emoji-recognizer/src/emoji.php' );
}

class WP_Webmention_Again {

	// WP cache expiration seconds
	const expire = 10;
	// queue & history table name
	const tablename = 'webmentions';

	/**
	 * regular cron interval for processing incoming
	 *
	 * use 'wp-webmention-again_interval_received' to filter this integer
	 *
	 * @return int cron interval in seconds
	 *
	 */
	protected static function remote_timeout () {
		return apply_filters( 'wp-webmention-again_remote_timeout', 100 );
	}

	/**
	 * runs on plugin load
	 */
	public function __construct() {

		add_action( 'init', array( &$this, 'init' ) );

		// this is mostly for debugging reasons
		register_activation_hook( __FILE__ , array( __CLASS__ , 'plugin_activate' ) );

		// clear schedules if there's any on deactivation
		register_deactivation_hook( __FILE__ , array( __CLASS__ , 'plugin_deactivate' ) );

		// extend current cron schedules with our entry
		add_filter( 'cron_schedules', array(&$this, 'add_cron_schedule' ) );

	}

	/**
	 * plugin activation hook
	 *
	 * dies if PHP version is too low
	 *
	 */
	public static function plugin_activate() {
		if ( version_compare( phpversion(), 5.3, '<' ) ) {
			die( 'The minimum PHP version required for this plugin is 5.3' );
		}

		global $wpdb;
		$dbname = $wpdb->prefix . static::tablename;

		//Use the character set and collation that's configured for WP tables
		$charset_collate = '';

		if ( !empty($wpdb->charset) ){
			$charset = str_replace('-', '', $wpdb->charset);
			$charset_collate = "DEFAULT CHARACTER SET {$charset}";
		}

		if ( !empty($wpdb->collate) ){
			$charset_collate .= " COLLATE {$wpdb->collate}";
		}

		$db_command = "CREATE TABLE IF NOT EXISTS `{$dbname}` (
			`id` char(160) CHARACTER SET ascii NOT NULL,
			`date` datetime NOT NULL,
			`direction` varchar(12) NOT NULL DEFAULT 'in',
			`tries` int(4) NOT NULL DEFAULT '0',
			`source` text NOT NULL,
			`target` text NOT NULL,
			`object_type` varchar(255) NOT NULL DEFAULT 'post',
			`object_id` bigint(20) NOT NULL,
			`status` tinyint(4) NOT NULL DEFAULT '0',
			`note` text NOT NULL,
			PRIMARY KEY (`id`),
			KEY `time` (`date`),
			KEY `key` (`direction`)
		) {$charset_collate};";

		static::debug("Initiating DB {$dbname}");
		try {
			$wpdb->query( $db_command );
		}
		catch (Exception $e) {
			static::debug('Something went wrong: ' . $e->getMessage());
		}

	}

	/**
	 * plugin deactivation hook
	 *
	 * makes sure there are no scheduled cron hooks left
	 *
	 */
	public static function plugin_deactivate () {

		global $wpdb;
		$dbname = $wpdb->prefix . static::tablename;

		$db_command = "DROP TABLE IF EXISTS `{$dbname}`;";

		static::debug("Deleting DB {$dbname}");
		try {
			$wpdb->query( $db_command );
		}
		catch (Exception $e) {
			static::debug('Something went wrong: ' . $e->getMessage());
		}
	}


	/**
	 * add our own schedule
	 *
	 * @param array $schedules - current schedules list
	 *
	 * @return array $schedules - extended schedules list
	 */
	public function add_cron_schedule ( $schedules ) {

		$schedules[ static::cron ] = array (
			'interval' => static::interval(),
			'display' => sprintf(__( 'every %d seconds' ), static::interval() )
		);

		return $schedules;
	}

	/**
	 * get plugin options
	 *
	 * use 'wp-webmention-again_comment_types' to filter registered comment types
	 * before being applied
	 *
	 * @return array plugin options
	 *
	 */
	public static function get_options () {
		$options = get_option( __CLASS__ );

		if ( isset( $options['comment_types'] ) && is_array( $options['comment_types'] ) )
			$options['comment_types'] = array_merge($options['comment_types'], static::mftypes());
		else
			$options['comment_types'] = static::mftypes();

		$options['comment_types'] = apply_filters( 'wp-webmention-again_comment_types', $options['comment_types'] );

		return $options;
	}

	/**
	 * insert a webmention to the queue
	 *
	 * @param string $direction - 'in' or 'out'
	 * @param string $source - source URL
	 * @param string $target - target URL
	 * @param string $object - object type: post, comment, etc.
	 * @param int $object_id - ID of object
	 *
	 * @return false|string - false on failure, inserted ID on success
	 *
	 */
	public static function queue_add ( $direction, $source, $target, $object = '', $object_id = 0 ) {
		global $wpdb;
		$dbname = $wpdb->prefix . static::tablename;

		$direction = strtolower($direction);
		$valid_directions = array ( 'in', 'out' );
		if ( ! in_array ( $direction, $valid_directions ) )
			return false;

		$id = sha1($source . $target);

		if ( static::queue_exists ( $direction, $source, $target ) )
			return true;

		$q = $wpdb->prepare( "INSERT INTO `{$dbname}`
			(`id`,`date`,`direction`, `tries`,`source`, `target`, `object_type`, `object_id`, `status`, `note` ) VALUES
			( '%s', NOW(), '%s', 0, '%s', '%s', '%s', %d, 0, '' );",
			$id, $direction, $source, $target, $object, $object_id );

		try {
			$req = $wpdb->query( $q );
		}
		catch (Exception $e) {
			static::debug('Something went wrong: ' . $e->getMessage());
		}

		return $id;
	}

	/**
	 * increment tries counter for a queue element
	 *
	 * @param string $id - ID of queue element
	 *
	 * @return bool - query success/failure
	 *
	 */
	public static function queue_inc ( $id ) {

		if ( empty( $id ) )
			return false;

		global $wpdb;
		$dbname = $wpdb->prefix . static::tablename;

		$q = $wpdb->prepare( "UPDATE `{$dbname}` SET `tries` = `tries` + 1 WHERE `id` = '%s'; ", $id );

		try {
			$req = $wpdb->query( $q );
		}
		catch (Exception $e) {
			static::debug('Something went wrong: ' . $e->getMessage());
		}

		return $req;
	}

	/**
	 * delete an entry from the webmentions queue
	 *
	 * @param string $id - ID of webmention queue element
	 *
	 * @return bool - query success/failure
	 *
	 */
	public static function queue_del ( $id ) {

		if ( empty( $id ) )
			return false;

		global $wpdb;
		$dbname = $wpdb->prefix . static::tablename;

		$q = $wpdb->prepare( "DELETE FROM `{$dbname}` WHERE `id` = '%s' LIMIT 1;", $id );

		try {
			$req = $wpdb->query( $q );
		}
		catch (Exception $e) {
			static::debug('Something went wrong: ' . $e->getMessage());
		}

		return $req;
	}

	/**
	 * delete an entry from the webmentions queue
	 *
	 * @param string $id - ID of webmention queue element
	 *
	 * @return bool - query success/failure
	 *
	 */
	public static function queue_done ( $id, $note = '' ) {

		if ( empty( $id ) )
			return false;

		if ( ! empty ( $note ) && ! is_string ( $note ) )
			$note = json_encode ( $note );

		global $wpdb;
		$dbname = $wpdb->prefix . static::tablename;

		if ( empty( $note ) )
			$q = $wpdb->prepare( "UPDATE `{$dbname}` SET `status` = 1 WHERE `id` = '%s'; ", $id );
		else
			$q = $wpdb->prepare( "UPDATE `{$dbname}` SET `status` = 1, `note`='%s' WHERE `id` = '%s'; ", $id, $node );

		try {
			$req = $wpdb->query( $q );
		}
		catch (Exception $e) {
			static::debug('Something went wrong: ' . $e->getMessage());
		}

		return $req;
	}

	/**
	 * get a batch of elements according to direction
	 *
	 * @param string $direction - 'in' or 'out'
	 * @param int $limit - max number of items to get
	 *
	 * @return array of queue objects
	 *
	 */
	public static function queue_get ( $direction, $limit = 1 ) {

		$direction = strtolower($direction);
		$valid_directions = array ( 'in', 'out' );
		if ( ! in_array ( $direction, $valid_directions ) )
			return false;

		global $wpdb;
		$dbname = $wpdb->prefix . static::tablename;

		$q = $wpdb->prepare( "SELECT * FROM `{$dbname}` WHERE `direction` = '%s' and `status` = 0 LIMIT %d;", $direction, $limit );

		try {
			$req = $wpdb->get_results( $q );
		}
		catch (Exception $e) {
			static::debug('Something went wrong: ' . $e->getMessage());
		}

		if ( ! empty ( $req ) )
			return $req;

		return false;
	}

	/**
	 * checks existence of a queue element
	 *
	 * @param string $direction - 'in' or 'out'
	 * @param string $source - source URL
	 * @param string $target - target URL
	 *
	 * @return bool true on existing element, false on not found
	 */
	public static function queue_exists ( $direction, $source, $target ) {

		global $wpdb;
		$dbname = $wpdb->prefix . static::tablename;

		$direction = strtolower($direction);
		$valid_directions = array ( 'in', 'out' );
		if ( ! in_array ( $direction, $valid_directions ) )
			return false;

		$id = sha1($source . $target);

		$q = $wpdb->prepare( "SELECT date FROM `{$dbname}` WHERE `direction` = '%s' and `id` = '%s';", $direction, $id );

		try {
			$req = $wpdb->get_results( $q );
		}
		catch (Exception $e) {
			static::debug('Something went wrong: ' . $e->getMessage());
		}

		if ( ! empty ( $req ) )
			return true;

		return false;
	}

	/**
	 * extended wp_remote_get with debugging
	 *
	 * @param string $source URL to pull
	 *
	 * @return array wp_remote_get array
	 */
	protected static function _wp_remote_get ( &$source ) {
		$content = false;
		static::debug( "    fetching {$source}" );
		$url = htmlspecialchars_decode( $source );
		$q = wp_remote_get( $source );

		if ( is_wp_error( $q ) ) {
			static::debug( "    something went wrong: " . $q->get_error_message() );
			return false;
		}

		if ( !is_array( $q ) ) {
			static::debug( "    $q is not an array. It should be one." );
			return false;
		}

		if ( ! isset( $q['headers'] ) || ! is_array( $q['headers'] ) ) {
			static::debug( "    missing response headers." );
			return false;
		}

		if ( ! isset( $q['body'] ) || empty( $q['body'] ) ) {
			static::debug( "    missing body" );
			return false;
		}

		static::debug('Headers: ' . json_encode($q['headers']));

		return $q;
	}

	/**
	 * validated a URL that is supposed to be on our site
	 *
	 * @param string $url URL to check against
	 *
	 * @return bool|int false on not found, int post_id on found
	 */
	protected static function validate_local ( $url ) {
		// normalize url scheme, url_to_postid will take care of it anyway
		$url = preg_replace( '/^https?:\/\//i', 'http://', $url );
		return url_to_postid( $url );
	}

	/**
	 * recursive walker for an mf2 array: if it find an element which has a value
	 * of a single element array, flatten the array to the element
	 *
	 * @param array $mf2 Mf2 array to flatten
	 *
	 * @return array flattened Mf2 array
	 *
	 */
	protected static function flatten_mf2_array ( $mf2 ) {

		if (is_array($mf2) && count($mf2) == 1) {
			$mf2 = array_pop($mf2);
		}

		if (is_array($mf2)) {
			foreach($mf2 as $key => $value) {
				$mf2[$key] = static::flatten_mf2_array($value);
			}
		}

		return $mf2;
	}

	/**
	 * find all urls in a text
	 *
	 * @param string $text - text to parse
	 *
	 * @return array array of URLS found in the test
	 */
	protected static function extract_urls( &$text ) {
		$matches = array();
		preg_match_all("/\b(?:http|https)\:\/\/?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.[a-zA-Z0-9\.\/\?\:@\-_=#]*/i", $text, $matches);

		$matches = $matches[0];

		$matches = array_unique($matches);

		return $matches;
	}

	/**
	 * validates a post object if it really is a post
	 *
	 * @param $post object Wordpress Post Object to check
	 *
	 * @return bool true if it's a post, false if not
	 */
	protected static function is_post ( &$post ) {
		if ( !empty($post) && is_object($post) && isset($post->ID) && !empty($post->ID) )
			return true;

		return false;
	}



	/**
	 * Converts relative to absolute urls
	 *
	 * code from [webmention](https://github.com/pfefferle/wordpress-webmention)
	 * which is based on the code of 99webtools.com
	 *
	 * @link http://99webtools.com/relative-path-into-absolute-url.php
	 *
	 * @param string $base the base url
	 * @param string $rel the relative url
	 *
	 * @return string the absolute url
	 */
	protected static function make_url_absolute( $base, $rel ) {
		if ( 0 === strpos( $rel, '//' ) ) {
			return parse_url( $base, PHP_URL_SCHEME ) . ':' . $rel;
		}
		// return if already absolute URL
		if ( parse_url( $rel, PHP_URL_SCHEME ) != '' ) {
			return $rel;
		}
		// queries and	anchors
		if ( '#' == $rel[0]  || '?' == $rel[0] ) {
			return $base . $rel;
		}
		// parse base URL and convert to local variables:
		// $scheme, $host, $path
		extract( parse_url( $base ) );
		// remove	non-directory element from path
		$path = preg_replace( '#/[^/]*$#', '', $path );
		// destroy path if relative url points to root
		if ( '/' == $rel[0] ) {
			$path = '';
		}
		// dirty absolute URL
		$abs = "$host";
		// check port
		if ( isset( $port ) && ! empty( $port ) ) {
			$abs .= ":$port";
		}
		// add path + rel
		$abs .= "$path/$rel";
		// replace '//' or '/./' or '/foo/../' with '/'
		$re = array( '#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#' );
		for ( $n = 1; $n > 0; $abs = preg_replace( $re, '/', $abs, -1, $n ) ) { }
		// absolute URL is ready!
		return $scheme . '://' . $abs;
	}

	/**
	 * get content like the_content
	 *
	 * @param object $post - WP Post object
	 *
	 * @return string the_content
	 */
	protected static function get_the_content( &$post ){

		if ( ! static::is_post( $post ) )
			return false;

		if ( $cached = wp_cache_get ( $post->ID, __CLASS__ . __FUNCTION__ ) )
			return $cached;

		$r = apply_filters( 'the_content', $post->post_content );

		wp_cache_set ( $post->ID, $r, __CLASS__ . __FUNCTION__, static::expire );

		return $r;
	}

	/**
	 * debug messages; will only work if WP_DEBUG is on
	 * or if the level is LOG_ERR, but that will kill the process
	 *
	 * @param string $message
	 * @param int $level
	 */
	protected static function debug( $message, $level = LOG_NOTICE ) {
		if ( @is_array( $message ) || @is_object ( $message ) )
			$message = json_encode( $message );


		switch ( $level ) {
			case LOG_ERR :
				wp_die( '<h1>Error:</h1>' . '<p>' . $message . '</p>' );
				exit;
			default:
				if ( ! defined( 'WP_DEBUG' ) || true != WP_DEBUG )
					return;
				break;
		}

		error_log(  __CLASS__ . ": " . $message );
	}

}

require ( __DIR__ . '/sender.php' );
$WP_Webmention_Again_Sender = new WP_Webmention_Again_Sender();

require ( __DIR__ . '/receiver.php' );
$WP_Webmention_Again_Receiver = new WP_Webmention_Again_Receiver();


// global send_webmention function
if ( ! function_exists( 'send_webmention' ) ) {
	function send_webmention( $source, $target ) {
		return WP_Webmention_Again_Sender::queue ( 'out', $source, $target );
	}
}


endif;