| 1 |
<?php |
| 2 |
namespace Activitypub\Handler; |
| 3 |
|
| 4 |
use Activitypub\Http; |
| 5 |
use Activitypub\Activity\Activity; |
| 6 |
use Activitypub\Collection\Users; |
| 7 |
use Activitypub\Collection\Followers; |
| 8 |
|
| 9 |
/** |
| 10 |
* Handle Follow requests |
| 11 |
*/ |
| 12 |
class Follow { |
| 13 |
/** |
| 14 |
* Initialize the class, registering WordPress hooks |
| 15 |
*/ |
| 16 |
public static function init() { |
| 17 |
\add_action( 'activitypub_inbox_follow', array( self::class, 'handle_follow' ), 10, 2 ); |
| 18 |
\add_action( 'activitypub_followers_post_follow', array( self::class, 'send_follow_response' ), 10, 4 ); |
| 19 |
} |
| 20 |
|
| 21 |
/** |
| 22 |
* Handle "Follow" requests |
| 23 |
* |
| 24 |
* @param array $activity The activity object |
| 25 |
* @param int $user_id The user ID |
| 26 |
*/ |
| 27 |
public static function handle_follow( $activity, $user_id ) { |
| 28 |
// save follower |
| 29 |
$follower = Followers::add_follower( $user_id, $activity['actor'] ); |
| 30 |
|
| 31 |
do_action( 'activitypub_followers_post_follow', $activity['actor'], $activity, $user_id, $follower ); |
| 32 |
} |
| 33 |
|
| 34 |
/** |
| 35 |
* Send Accept response |
| 36 |
* |
| 37 |
* @param string $actor The Actor URL |
| 38 |
* @param array $object The Activity object |
| 39 |
* @param int $user_id The ID of the WordPress User |
| 40 |
* @param Activitypub\Model\Follower $follower The Follower object |
| 41 |
* |
| 42 |
* @return void |
| 43 |
*/ |
| 44 |
public static function send_follow_response( $actor, $object, $user_id, $follower ) { |
| 45 |
if ( \is_wp_error( $follower ) ) { |
| 46 |
// it is not even possible to send a "Reject" because |
| 47 |
// we can not get the Remote-Inbox |
| 48 |
return; |
| 49 |
} |
| 50 |
|
| 51 |
// only send minimal data |
| 52 |
$object = array_intersect_key( |
| 53 |
$object, |
| 54 |
array_flip( |
| 55 |
array( |
| 56 |
'id', |
| 57 |
'type', |
| 58 |
'actor', |
| 59 |
'object', |
| 60 |
) |
| 61 |
) |
| 62 |
); |
| 63 |
|
| 64 |
$user = Users::get_by_id( $user_id ); |
| 65 |
|
| 66 |
// get inbox |
| 67 |
$inbox = $follower->get_shared_inbox(); |
| 68 |
|
| 69 |
// send "Accept" activity |
| 70 |
$activity = new Activity(); |
| 71 |
$activity->set_type( 'Accept' ); |
| 72 |
$activity->set_object( $object ); |
| 73 |
$activity->set_actor( $user->get_id() ); |
| 74 |
$activity->set_to( $actor ); |
| 75 |
$activity->set_id( $user->get_id() . '#follow-' . \preg_replace( '~^https?://~', '', $actor ) . '-' . \time() ); |
| 76 |
|
| 77 |
$activity = $activity->to_json(); |
| 78 |
|
| 79 |
Http::post( $inbox, $activity, $user_id ); |
| 80 |
} |
| 81 |
} |
| 82 |
|