diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..3c72a86 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,90 @@ +name: Bug Report +description: Helps us improve our product! +labels: "Needs triage, [Type] Bug" +body: + - type: markdown + attributes: + value: | + ### Thanks for contributing! + + Please write a clear title, then fill in the fields below and submit. + + Please **do not** link to image hosting services such as Cloudup, Droplr, Imgur, etc… + Instead, directly embed screenshot(s) or recording(s) in any of the text areas below: click, then drag and drop. + - type: markdown + attributes: + value: | + --- + ## Core Information + - type: textarea + id: summary + attributes: + label: Quick summary + - type: textarea + id: steps + attributes: + label: Steps to reproduce + placeholder: | + 1. Start at `site-domain.com/blog`. + 2. Click on any blog post. + 3. ... + validations: + required: true + - type: textarea + id: expected + attributes: + label: What you expected to happen + placeholder: | + e.g. The post should appear. + validations: + required: true + - type: textarea + id: actual + attributes: + label: What actually happened + placeholder: | + e.g. The post did not appear. + validations: + required: true + - type: dropdown + id: users-affected + attributes: + label: Impact + description: Approximately how many users are impacted? + options: + - One + - Some (< 50%) + - Most (> 50%) + - All + validations: + required: true + - type: dropdown + id: workarounds + attributes: + label: Available workarounds? + options: + - No and the platform is unusable + - No but the platform is still usable + - Yes, difficult to implement + - Yes, easy to implement + - There is no user impact + validations: + required: true + + - type: markdown + attributes: + value: | +
+ + ## Optional Information + + The following section is optional. + - type: textarea + id: logs + attributes: + label: Logs or notes + placeholder: | + Add any information that may be relevant, such as: + - Browser/Platform + - Theme + - Logs/Errors diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..2fc3601 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,34 @@ +name: Feature Request +description: Suggest an idea for the ActivityPub plugin! +title: "Feature Request:" +labels: ["[Type] Feature Request"] +body: + - type: markdown + attributes: + value: | + Please, be as descriptive as possible. Issues lacking detail, or for any other reason than to request a feature, may be closed without action. + + - type: textarea + id: what + attributes: + label: What + description: Add a concise description of the feature being requested. + placeholder: eg. I would like a new dropdown at ... + validations: + required: true + + - type: textarea + id: why + attributes: + label: Why + description: Add a description of the problem this feature solves. + placeholder: | + eg. This will solve my accessibility needs. + validations: + required: true + + - type: textarea + id: how + attributes: + label: How + description: If applicable, add screenshots, mockup, animations and/or videos to help illustrate how the feature could be done. diff --git a/.github/stale.yml b/.github/stale.yml deleted file mode 100644 index e6e3287..0000000 --- a/.github/stale.yml +++ /dev/null @@ -1,17 +0,0 @@ -# Number of days of inactivity before an issue becomes stale -daysUntilStale: 120 -# Number of days of inactivity before a stale issue is closed -daysUntilClose: 7 -# Issues with these labels will never be considered stale -exemptLabels: - - pinned - - security -# Label to use when marking an issue as stale -staleLabel: wontfix -# Comment to post when marking an issue as stale. Set to `false` to disable -markComment: > - This issue has been automatically marked as stale because it has not had - recent activity. It will be closed if no further activity occurs. Thank you - for your contributions. -# Comment to post when closing a stale issue. Set to `false` to disable -closeComment: false diff --git a/.github/workflows/gardening.yml b/.github/workflows/gardening.yml new file mode 100644 index 0000000..2055d66 --- /dev/null +++ b/.github/workflows/gardening.yml @@ -0,0 +1,50 @@ +# Repo gardening. Automate some of the triage tasks in the repo. +name: Repo Gardening + +on: + pull_request_target: # When a PR is opened, edited, updated, closed, or a label is added. + types: [opened, reopened, synchronize, edited, labeled, closed] + issues: # For auto-triage of issues. + types: [opened, labeled, reopened, edited, closed] + issue_comment: # To gather support references in issue comments. + types: [created] +concurrency: + # For pull_request_target, cancel any concurrent jobs with the same type (e.g. "opened", "labeled") and branch. + # Don't cancel any for other events, accomplished by grouping on the unique run_id. + group: gardening-${{ github.event_name }}-${{ github.event.action }}-${{ github.event_name == 'pull_request_target' && github.event.pull_request.head.ref || github.run_id }} + cancel-in-progress: true + +jobs: + repo-gardening: + name: 'Automated repo gardening.' + runs-on: ubuntu-latest + if: github.event_name == 'pull_request_target' || github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name + timeout-minutes: 10 + + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Setup Node + uses: actions/setup-node@v3 + with: + node-version: lts/* + + - name: Wait for prior instances of the workflow to finish + uses: softprops/turnstyle@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: 'Automate triage (add labels, clean labels, ...).' + uses: automattic/action-repo-gardening@trunk + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + slack_token: ${{ secrets.SLACK_TOKEN }} + slack_team_channel: ${{ secrets.SLACK_TEAM_CHANNEL }} + slack_he_triage_channel: ${{ secrets.SLACK_HE_TRIAGE_CHANNEL }} + slack_quality_channel: ${{ secrets.SLACK_QUALITY_CHANNEL }} + tasks: 'addLabels,cleanLabels,assignIssues,flagOss,gatherSupportReferences,replyToCustomersReminder' + add_labels: '[ + {"path": "src/followers", "label": "[Block] Followers"}, + {"path": "src/follow-me", "label": "[Block] Follow Me"} + ]' diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml new file mode 100644 index 0000000..03882cb --- /dev/null +++ b/.github/workflows/stale.yml @@ -0,0 +1,19 @@ +name: 'Close stale issues and PRs' +on: + schedule: + - cron: '30 1 * * *' + +jobs: + stale: + runs-on: ubuntu-latest + steps: + - uses: actions/stale@v8 + with: + stale-issue-message: 'This issue is stale because it has been open 120 days with no activity. Remove stale label or comment or this will be closed in 5 days.' + days-before-stale: 120 + days-before-close: 7 + exempt-all-pr-assignees: true + exempt-all-assignees: true + exempt-all-pr-milestones: true + exempt-all-issue-milestones: true + start-date: '2019-02-01T00:00:00Z' diff --git a/.php_cs b/.php_cs deleted file mode 100644 index 7f81780..0000000 --- a/.php_cs +++ /dev/null @@ -1,15 +0,0 @@ -exclude('vendor') - ->exclude('node_modules') - ->exclude('bin') - ->in(__DIR__) -; - -return PhpCsFixer\Config::create() - ->setRules([ - 'native_function_invocation' => ['include' => ['@all']], - 'native_constant_invocation' => true, - ]) - ->setFinder($finder) -; diff --git a/README.md b/README.md index cdc6d62..eef27a0 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ # ActivityPub # -**Contributors:** [automattic](https://profiles.wordpress.org/automattic/), [pfefferle](https://profiles.wordpress.org/pfefferle/), [mediaformat](https://profiles.wordpress.org/mediaformat/), [mattwiebe](https://profiles.wordpress.org/mattwiebe/), [akirk](https://profiles.wordpress.org/akirk/), [jeherve](https://profiles.wordpress.org/jeherve/), [nuriapena](https://profiles.wordpress.org/nuriapena/) +**Contributors:** [automattic](https://profiles.wordpress.org/automattic/), [pfefferle](https://profiles.wordpress.org/pfefferle/), [mediaformat](https://profiles.wordpress.org/mediaformat/), [mattwiebe](https://profiles.wordpress.org/mattwiebe/), [akirk](https://profiles.wordpress.org/akirk/), [jeherve](https://profiles.wordpress.org/jeherve/), [nuriapena](https://profiles.wordpress.org/nuriapena/), [cavalierlife](https://profiles.wordpress.org/cavalierlife/) **Tags:** OStatus, fediverse, activitypub, activitystream **Requires at least:** 4.7 **Tested up to:** 6.3 -**Stable tag:** 1.0.0 +**Stable tag:** 1.0.1 **Requires PHP:** 5.6 **License:** MIT **License URI:** http://opensource.org/licenses/MIT @@ -12,39 +12,39 @@ The ActivityPub protocol is a decentralized social networking protocol based upo ## Description ## -This is BETA software, see the FAQ to see the current feature set or rather what is still planned. +Enter the fediverse with **ActivityPub**, broadcasting your blog to a wider audience! Attract followers, deliver updates, and receive comments from a diverse user base of **ActivityPub**\-compliant platforms. -The plugin implements the ActivityPub protocol for your blog, which means that your readers will be able to follow your blog posts on Mastodon and other federated platforms that support ActivityPub. In addition, replies to your posts on Mastodon and related platforms will automatically become comments on your blog post. +With the ActivityPub plugin installed, your WordPress blog itself function as a federated profile, along with profiles for each author. For instance, if your website is `example.com`, then the blog-wide profile can be found at `@example.com@example.com`, and authors like Jane and Bob would have their individual profiles at `@jane@example.com` and `@bobz@example.com`, respectively. + +An example: I give you my Mastodon profile name: `@pfefferle@mastodon.social`. You search, see my profile, and hit follow. Now, any post I make appears in your Home feed. Similarly, with the ActivityPub plugin, you can find and follow Jane's profile at `@jane@example.com`. + +Once you follow Jane's `@jane@example.com` profile, any blog post she crafts on `example.com` will land in your Home feed. Simultaneously, by following the blog-wide profile `@example.com@example.com`, you'll receive updates from all authors. + +**Note**: if no one follows your author or blog instance, your posts remain unseen. The simplest method to verify the plugin's operation is by following your profile. If you possess a Mastodon profile, initiate by following your new one. The plugin works with the following tested federated platforms, but there may be more that it works with as well: * [Mastodon](https://joinmastodon.org/) -* [Pleroma](https://pleroma.social/) +* [Pleroma](https://pleroma.social/)/[Akkoma](https://akkoma.social/) * [friendica](https://friendi.ca/) * [Hubzilla](https://hubzilla.org/) * [Pixelfed](https://pixelfed.org/) * [Socialhome](https://socialhome.network/) * [Misskey](https://join.misskey.page/) -* [Calckey](https://calckey.org/) - -Here’s what that means and what you can expect. - -Once the ActivityPub plugin is installed, each author’s page on your WordPress blog will become its own federated instance. In other words, if you have two authors, Jane and Bob, on your website, `example.com`, then your authors would have their own author pages at `example.com/author/jane` and `example.com/author/bob`. Each of those author pages would now be available to Mastodon users (and all other federated platform users) as a profile that can be followed. Let’s break that down further. Let’s say you have a friend on Mastodon who tells you to follow them and they give you their profile name `@janelivesheresomeofthetime@mastodon.social`. You search for her name, see her profile, and click the follow button, right? From then on, everything Jane posts on her profile shows up in your Home feed. Okay, similarly, now that Jane has installed the ActivityPub plugin on her `example.com` site, her friends can also follow her on Mastodon by searching for `@jane@example.com` and clicking the Follow button on that profile. - -From now on, every blog post Jane publishes on example.com will show up on your Home feed because you follow her `@jane@example.com` profile. -Of course, if no one follows your author instance, then no one will ever see the posts - including you! So the easiest way to even know if the plugin is working is to follow your new profile yourself. If you already have a Mastodon profile, just follow your new one from there. +* [Firefish](https://joinfirefish.org/) (rebrand of Calckey) Some things to note: -1. Many single-author blogs have chosen to turn off or redirect their author profile pages, usually via an SEO plugin like Yoast or Rank Math. This is usually done to avoid duplicate content with your blog’s home page. If your author page has been deactivated in this way, then ActivityPub won’t work for you. Instead, you can turn your author profile page back on, and then use the option in your SEO plugin to noindex the author page. This will enable the page to be live and ActivityPub will now work, but the live page won’t cause any duplicate content issues with search engines. -1. Once ActivityPub is installed, only new posts going forward will be available in the fediverse. Likewise, even if you’ve been using ActivityPub for a while, anyone who follows your site, will only see new posts you publish from that moment on. They will never see previously-published posts in their Home feed. This process is very similar to subscribing to a newsletter. If you subscribe to a newsletter, you will only receive future emails, but not the old archived ones. With ActivityPub, if someone follows your site, they will only receive new blog posts you publish from then on. +1. The blog-wide profile is only compatible with sites with rewrite rules enabled. If your site does not have rewrite rules enabled, the author-specific profiles may still work. +1. Many single-author blogs have chosen to turn off or redirect their author profile pages, usually via an SEO plugin like Yoast or Rank Math. This is usually done to avoid duplicate content with your blog’s home page. If your author page has been deactivated in this way, then ActivityPub author profiles won’t work for you. Instead, you can turn your author profile page back on, and then use the option in your SEO plugin to noindex the author page. This will duplicate content issues with search engines and will enable ActivityPub author profiles to work. +1. Once ActivityPub is installed, *only new posts going forward* will be available in the fediverse. Likewise, even if you’ve been using ActivityPub for a while, anyone who follows your site, will only see new posts you publish from that moment on. They will never see previously-published posts in their Home feed. This process is very similar to subscribing to a newsletter. If you subscribe to a newsletter, you will only receive future emails, but not the old archived ones. With ActivityPub, if someone follows your site, they will only receive new blog posts you publish from then on. So what’s the process? 1. Install the ActivityPub plugin. 1. Go to the plugin’s settings page and adjust the settings to your liking. Click the Save button when ready. -1. Make sure your blog’s author profile page is active. -1. Go to Mastodon or any other federated platform, search for your author’s new federated profile, and follow it. Your new profile will be in the form of @yourauthorname@yourwebsite.com, so that is what you’ll search for. +1. Make sure your blog’s author profile page is active if you are using author profiles. +1. Go to Mastodon or any other federated platform, and search for your profile, and follow it. Your new profile will be in the form of either `@your_username@example.com` or `@example.com@example.com`, so that is what you’ll search for. 1. On your blog, publish a new post. 1. From Mastodon, check to see if the new post appears in your Home feed. @@ -54,22 +54,14 @@ Please note that it may take up to 15 minutes or so for the new post to show up ### tl;dr ### -This plugin connects your WordPress blog to popular social platforms like Mastodon, making your posts more accessible to a wider audience. Once installed, your blog's author pages can be followed by users on these platforms, allowing them to receive your new posts in their feeds. - -Here's how it works: - -1. Install the plugin and adjust settings as needed. -1. Ensure your blog's author profile page is active. -1. On Mastodon or other supported platforms, search for and follow your author's new profile (e.g., `@yourauthorname@yourwebsite.com`). -1. Publish a new post on your blog and check if it appears in your Mastodon feed. - -Please note that it may take up to 15 minutes for a new post to appear in your feed, as messages are sent on a delay to avoid overwhelming your followers. Be patient and give it some time. +This plugin connects your WordPress blog to popular social platforms like Mastodon, making your posts more accessible to a wider audience. Once installed, your blog can be followed by users on these platforms, allowing them to receive your new posts in their feeds. ### What is the status of this plugin? ### Implemented: -* profile pages (JSON representation) +* blog profile pages (JSON representation) +* author profile pages (JSON representation) * custom links * functional inbox/outbox * follow (accept follows) @@ -79,8 +71,8 @@ Implemented: To implement: -* better configuration possibilities * threaded comments support +* replace shortcodes with blocks for layout ### What is "ActivityPub for WordPress" ### @@ -94,7 +86,7 @@ In order for webfinger to work, it must be mapped to the root directory of the U Add the following to the .htaccess file in the root directory: - RedirectMatch "^\/\.well-known/(webfinger|nodeinfo|x-nodeinfo2)(.*)$" "\/blog\/\.well-known$1$2" + RedirectMatch "^\/\.well-known/(webfinger|nodeinfo|x-nodeinfo2)(.*)$" /blog/.well-known/$1$2 Where 'blog' is the path to the subdirectory at which your blog resides. @@ -113,20 +105,36 @@ Where 'blog' is the path to the subdirectory at which your blog resides. Project maintained on GitHub at [automattic/wordpress-activitypub](https://github.com/automattic/wordpress-activitypub). +### 1.0.1 ### + +* Update: improve image attachment detection using the block editor +* Update: better error code handling for API responses +* Update: use a tag stack instead of regex for protecting tags for Hashtags and @-Mentions +* Compatibility: better signature support for subpath-installations +* Compatibility: allow deactivating blocks registered by the plugin +* Compatibility: avoid Fatal Errors when using ClassicPress +* Compatibility: improve the Group-Actor to play nicely with existing implementations +* Fixed: truncate long blog titles and handles for the "Follow me" block +* Fixed: ensure that only a valid user can be selected for the "Follow me" block +* Fixed: fix a typo in a hook name +* Fixed: a problem with signatures when running WordPress in a sub-path + ### 1.0.0 ### -* Add: blog-wide Account (catchall, like `mydomain.com@mydomain.com`) -* Add: Signature Verification: https://docs.joinmastodon.org/spec/security/ . -* Add: a Followers Block. +* Add: blog-wide Account (catchall, like `example.com@example.com`) +* Add: a Follow Me block (help visitors to follow your Profile) +* Add: Signature Verification: https://docs.joinmastodon.org/spec/security/ +* Add: a Followers Block (show off your Followers) * Add: Simple caching * Add: Collection endpoints for Featured Tags and Featured Posts -* Update: Complete rewrite of the Follower-System based on Custom Post Types. +* Add: Better handling of Hashtags in mobile apps +* Update: Complete rewrite of the Follower-System based on Custom Post Types * Update: Improved linter (PHPCS) -* Compatibility: Add a new conditional, `\Activitypub\is_activitypub_request()`, to allow third-party plugins to detect ActivityPub requests. -* Compatibility: Add hooks to allow modifying images returned in ActivityPub requests. -* Compatibility: Indicate that the plugin is compatible and has been tested with the latest version of WordPress, 6.3. -* Compatibility: Avoid PHP notice on sites using PHP 8.2. -* Fixed: Load the plugin later in the WordPress code lifecycle to avoid errors in some requests. +* Compatibility: Add a new conditional, `\Activitypub\is_activitypub_request()`, to allow third-party plugins to detect ActivityPub requests +* Compatibility: Add hooks to allow modifying images returned in ActivityPub requests +* Compatibility: Indicate that the plugin is compatible and has been tested with the latest version of WordPress, 6.3 +* Compatibility: Avoid PHP notice on sites using PHP 8.2 +* Fixed: Load the plugin later in the WordPress code lifecycle to avoid errors in some requests * Fixed: Updating posts * Fixed: Hashtag now support CamelCase and UTF-8 diff --git a/activitypub.php b/activitypub.php index eb61c57..9b9f8f2 100644 --- a/activitypub.php +++ b/activitypub.php @@ -3,7 +3,7 @@ * Plugin Name: ActivityPub * Plugin URI: https://github.com/pfefferle/wordpress-activitypub/ * Description: The ActivityPub protocol is a decentralized social networking protocol based upon the ActivityStreams 2.0 data format. - * Version: 1.0.0 + * Version: 1.0.1 * Author: Matthias Pfefferle & Automattic * Author URI: https://automattic.com/ * License: MIT @@ -15,6 +15,8 @@ namespace Activitypub; +use function Activitypub\site_supports_blocks; + \defined( 'ACTIVITYPUB_REST_NAMESPACE' ) || \define( 'ACTIVITYPUB_REST_NAMESPACE', 'activitypub/1.0' ); /** @@ -53,10 +55,13 @@ function init() { Admin::init(); Hashtag::init(); Shortcodes::init(); - Blocks::init(); Mention::init(); Health_Check::init(); Scheduler::init(); + + if ( site_supports_blocks() ) { + Blocks::init(); + } } \add_action( 'init', __NAMESPACE__ . '\init' ); diff --git a/assets/img/mp.jpg b/assets/img/mp.jpg index 0356f91..05964b4 100644 Binary files a/assets/img/mp.jpg and b/assets/img/mp.jpg differ diff --git a/assets/img/wp-logo.png b/assets/img/wp-logo.png new file mode 100644 index 0000000..b48f08e Binary files /dev/null and b/assets/img/wp-logo.png differ diff --git a/build/follow-me/block.json b/build/follow-me/block.json new file mode 100644 index 0000000..8dcb824 --- /dev/null +++ b/build/follow-me/block.json @@ -0,0 +1,47 @@ +{ + "$schema": "https://schemas.wp.org/trunk/block.json", + "name": "activitypub/follow-me", + "apiVersion": 3, + "version": "1.0.0", + "title": "Follow me on the Fediverse", + "category": "widgets", + "description": "Display your Fediverse profile so that visitors can follow you.", + "textdomain": "activitypub", + "icon": "groups", + "supports": { + "html": false, + "color": { + "gradients": true, + "link": true, + "__experimentalDefaultControls": { + "background": true, + "text": true, + "link": true + } + }, + "__experimentalBorder": { + "radius": true, + "width": true, + "color": true, + "style": true + }, + "typography": { + "fontSize": true, + "__experimentalDefaultControls": { + "fontSize": true + } + } + }, + "attributes": { + "selectedUser": { + "type": "string", + "default": "site" + } + }, + "editorScript": "file:./index.js", + "viewScript": "file:./view.js", + "style": [ + "file:./style-index.css", + "wp-components" + ] +} \ No newline at end of file diff --git a/build/follow-me/index.asset.php b/build/follow-me/index.asset.php new file mode 100644 index 0000000..28ba373 --- /dev/null +++ b/build/follow-me/index.asset.php @@ -0,0 +1 @@ + array('wp-api-fetch', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-compose', 'wp-data', 'wp-element', 'wp-i18n', 'wp-primitives'), 'version' => '5e11f2fcd4dc9ac6d7ee'); diff --git a/build/follow-me/index.js b/build/follow-me/index.js new file mode 100644 index 0000000..5226a1d --- /dev/null +++ b/build/follow-me/index.js @@ -0,0 +1 @@ +(()=>{"use strict";var e,t={843:(e,t,n)=>{const r=window.wp.blocks,o=window.wp.element,l=window.wp.primitives,a=(0,o.createElement)(l.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,o.createElement)(l.Path,{d:"M15.5 9.5a1 1 0 100-2 1 1 0 000 2zm0 1.5a2.5 2.5 0 100-5 2.5 2.5 0 000 5zm-2.25 6v-2a2.75 2.75 0 00-2.75-2.75h-4A2.75 2.75 0 003.75 15v2h1.5v-2c0-.69.56-1.25 1.25-1.25h4c.69 0 1.25.56 1.25 1.25v2h1.5zm7-2v2h-1.5v-2c0-.69-.56-1.25-1.25-1.25H15v-1.5h2.5A2.75 2.75 0 0120.25 15zM9.5 8.5a1 1 0 11-2 0 1 1 0 012 0zm1.5 0a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z",fillRule:"evenodd"}));function c(){return c=Object.assign?Object.assign.bind():function(e){for(var t=1;t2&&void 0!==arguments[2]?arguments[2]:null;return n?`${e}${arguments.length>3&&void 0!==arguments[3]?arguments[3]:""} { ${t}: ${n}; }\n`:""}function g(e,t,n,r){return E(e,"background-color",t)+E(e,"color",n)+E(e,"background-color",r,":hover")+E(e,"background-color",r,":focus")}function k(e){let{selector:t,style:n,backgroundColor:r}=e;const l=function(e,t,n){const r=`${e} .components-button`,o=("string"==typeof(l=n)?h(l):l?.color?.background||null)||t?.color?.background;var l;return g(r,_(t?.elements?.link?.color?.text),o,_(t?.elements?.link?.[":hover"]?.color?.text))}(t,n,r);return(0,o.createElement)("style",null,l)}const{namespace:O}=window._activityPubOptions,x={avatar:"",resource:"@well@hello.dolly",name:(0,s.__)("Hello Dolly Fan Account","activitypub"),url:"#"};function C(e){if(!e)return x;const t={...x,...e};return t.avatar=t?.icon?.url,t}function S(e){let{profile:t,popupStyles:n,userId:r}=e;const{avatar:l,name:a,resource:c}=t;return(0,o.createElement)("div",{className:"activitypub-profile"},(0,o.createElement)("img",{className:"activitypub-profile__avatar",src:l}),(0,o.createElement)("div",{className:"activitypub-profile__content"},(0,o.createElement)("div",{className:"activitypub-profile__name"},a),(0,o.createElement)("div",{className:"activitypub-profile__handle"},c)),(0,o.createElement)(N,{profile:t,popupStyles:n,userId:r}))}function N(e){let{profile:t,popupStyles:n,userId:r}=e;const[l,a]=(0,o.useState)(!1),c=(0,s.sprintf)((0,s.__)("Follow %s","activitypub"),t?.name);return(0,o.createElement)(o.Fragment,null,(0,o.createElement)(u.Button,{className:"activitypub-profile__follow",onClick:()=>a(!0)},(0,s.__)("Follow","activitypub")),l&&(0,o.createElement)(u.Modal,{className:"activitypub-profile__confirm",onRequestClose:()=>a(!1),title:c},(0,o.createElement)(P,{profile:t,userId:r}),(0,o.createElement)("style",null,n)))}function $(e){try{return new URL(e),!0}catch(e){return!1}}function P(e){let{profile:t,userId:n}=e;const{resource:r}=t,l=(0,s.__)("Follow","activitypub"),a=(0,s.__)("Loading...","activitypub"),c=(0,s.__)("Opening...","activitypub"),i=(0,s.__)("Error","activitypub"),p=(0,s.__)("Invalid","activitypub"),[m,v]=(0,o.useState)(l),[h,_]=(0,o.useState)(f),E=(0,b.useCopyToClipboard)(r,(()=>{_(w),setTimeout((()=>_(f)),1e3)})),[g,k]=(0,o.useState)(""),x=(0,o.useCallback)((()=>{let e;if(!$(g)&&!function(e){const t=e.replace(/^@/,"").split("@");return 2===t.length&&$(`https://${t[1]}`)}(g))return v(p),e=setTimeout((()=>v(l)),2e3),()=>clearTimeout(e);const t=`/${O}/users/${n}/remote-follow?resource=${g}`;v(a),d()({path:t}).then((e=>{let{url:t}=e;v(c),setTimeout((()=>{window.open(t,"_blank"),v(l)}),200)})).catch((()=>{v(i),setTimeout((()=>v(l)),2e3)}))}),[g]);return(0,o.createElement)("div",{className:"activitypub-follow-me__dialog"},(0,o.createElement)("div",{className:"apmfd__section"},(0,o.createElement)("h4",null,(0,s.__)("My Profile","activitypub")),(0,o.createElement)("div",{className:"apfmd-description"},(0,s.__)("Copy and paste my profile into the search field of your favorite fediverse app or server.","activitypub")),(0,o.createElement)("div",{className:"apfmd__button-group"},(0,o.createElement)("input",{type:"text",value:r,readOnly:!0}),(0,o.createElement)(u.Button,{ref:E},(0,o.createElement)(y,{icon:h}),(0,s.__)("Copy","activitypub")))),(0,o.createElement)("div",{className:"apmfd__section"},(0,o.createElement)("h4",null,(0,s.__)("Your Profile","activitypub")),(0,o.createElement)("div",{className:"apfmd-description"},(0,o.createInterpolateElement)((0,s.__)("Or, if you know your own profile, we can start things that way! (eg https://example.com/yourusername or yourusername@example.com)","activitypub"),{code:(0,o.createElement)("code",null)})),(0,o.createElement)("div",{className:"apfmd__button-group"},(0,o.createElement)("input",{type:"text",value:g,onKeyDown:e=>{"Enter"===e?.code&&x()},onChange:e=>k(e.target.value)}),(0,o.createElement)(u.Button,{onClick:x},m))))}function z(e){let{selectedUser:t,style:n,backgroundColor:r,id:l,useId:a=!1}=e;const[c,i]=(0,o.useState)(C()),s="site"===t?0:t,u=function(e){return g(".apfmd__button-group .components-button",_(e?.elements?.link?.color?.text)||"#111","#fff",_(e?.elements?.link?.[":hover"]?.color?.text)||"#333")}(n),p=a?{id:l}:{};function m(e){i(C(e))}return(0,o.useEffect)((()=>{(function(e){const t={headers:{Accept:"application/activity+json"},path:`/${O}/users/${e}`};return d()(t)})(s).then(m)}),[s]),(0,o.createElement)("div",p,(0,o.createElement)(k,{selector:`#${l}`,style:n,backgroundColor:r}),(0,o.createElement)(S,{profile:c,userId:s,popupStyles:u}))}(0,r.registerBlockType)("activitypub/follow-me",{edit:function(e){let{attributes:t,setAttributes:n}=e;const r=(0,i.useBlockProps)(),l=function(){const e=m?.users?(0,p.useSelect)((e=>e("core").getUsers({who:"authors"}))):[];return(0,o.useMemo)((()=>{if(!e)return[];const t=m?.site?[{label:(0,s.__)("Whole Site","activitypub"),value:"site"}]:[];return e.reduce(((e,t)=>(e.push({label:t.name,value:`${t.id}`}),e)),t)}),[e])}(),{selectedUser:a}=t;return(0,o.useEffect)((()=>{l.length&&(l.find((e=>{let{value:t}=e;return t===a}))||n({selectedUser:l[0].value}))}),[a,l]),(0,o.createElement)("div",r,(0,o.createElement)(i.InspectorControls,{key:"setting"},(0,o.createElement)(u.PanelBody,{title:(0,s.__)("Followers Options","activitypub")},(0,o.createElement)(u.SelectControl,{label:(0,s.__)("Select User","activitypub"),value:t.selectedUser,options:l,onChange:e=>n({selectedUser:e})}))),(0,o.createElement)(z,c({},t,{id:r.id})))},save:()=>null,icon:a})}},n={};function r(e){var o=n[e];if(void 0!==o)return o.exports;var l=n[e]={exports:{}};return t[e](l,l.exports,r),l.exports}r.m=t,e=[],r.O=(t,n,o,l)=>{if(!n){var a=1/0;for(u=0;u=l)&&Object.keys(r.O).every((e=>r.O[e](n[i])))?n.splice(i--,1):(c=!1,l0&&e[u-1][2]>l;u--)e[u]=e[u-1];e[u]=[n,o,l]},r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{var e={127:0,740:0};r.O.j=t=>0===e[t];var t=(t,n)=>{var o,l,[a,c,i]=n,s=0;if(a.some((t=>0!==e[t]))){for(o in c)r.o(c,o)&&(r.m[o]=c[o]);if(i)var u=i(r)}for(t&&t(n);sr(843)));o=r.O(o)})(); \ No newline at end of file diff --git a/build/follow-me/style-index.css b/build/follow-me/style-index.css new file mode 100644 index 0000000..ad2ac9c --- /dev/null +++ b/build/follow-me/style-index.css @@ -0,0 +1 @@ +.activitypub-follow-me-block-wrapper .activitypub-profile,.editor-styles-wrapper .activitypub-profile{align-items:self-start;display:flex;padding:1rem}.activitypub-follow-me-block-wrapper .activitypub-profile .activitypub-profile__avatar,.editor-styles-wrapper .activitypub-profile .activitypub-profile__avatar{border-radius:50%;height:75px;margin-right:1rem;width:75px}.activitypub-follow-me-block-wrapper .activitypub-profile .activitypub-profile__content,.editor-styles-wrapper .activitypub-profile .activitypub-profile__content{flex:1;min-width:0}.activitypub-follow-me-block-wrapper .activitypub-profile .activitypub-profile__handle,.activitypub-follow-me-block-wrapper .activitypub-profile .activitypub-profile__name,.editor-styles-wrapper .activitypub-profile .activitypub-profile__handle,.editor-styles-wrapper .activitypub-profile .activitypub-profile__name{line-height:1.2;margin:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.activitypub-follow-me-block-wrapper .activitypub-profile .activitypub-profile__name,.editor-styles-wrapper .activitypub-profile .activitypub-profile__name{font-size:1.25em}.activitypub-follow-me-block-wrapper .activitypub-profile .activitypub-profile__follow,.editor-styles-wrapper .activitypub-profile .activitypub-profile__follow{align-self:center;background-color:var(--wp--preset--color--black);color:var(--wp--preset--color--white);margin-left:1rem}.activitypub-follow-me__dialog{max-width:30em}.activitypub-follow-me__dialog h4{line-height:1;margin:0}.activitypub-follow-me__dialog .apmfd__section{margin-bottom:2em}.activitypub-follow-me__dialog .apfmd-description{font-size:var(--wp--preset--font-size--normal,.75rem);margin:.33em 0 1em}.activitypub-follow-me__dialog .apfmd__button-group{display:flex;justify-content:flex-end}.activitypub-follow-me__dialog .apfmd__button-group svg{height:21px;margin-right:.5em;width:21px}.activitypub-follow-me__dialog .apfmd__button-group input{flex:1;padding-left:1em;padding-right:1em} diff --git a/build/follow-me/view.asset.php b/build/follow-me/view.asset.php new file mode 100644 index 0000000..56862e5 --- /dev/null +++ b/build/follow-me/view.asset.php @@ -0,0 +1 @@ + array('wp-api-fetch', 'wp-components', 'wp-compose', 'wp-dom-ready', 'wp-element', 'wp-i18n', 'wp-primitives'), 'version' => '06a922cf2e58c94b6431'); diff --git a/build/follow-me/view.js b/build/follow-me/view.js new file mode 100644 index 0000000..e55d91b --- /dev/null +++ b/build/follow-me/view.js @@ -0,0 +1 @@ +(()=>{"use strict";var e,t={810:(e,t,r)=>{function n(){return n=Object.assign?Object.assign.bind():function(e){for(var t=1;t2&&void 0!==arguments[2]?arguments[2]:null;return r?`${e}${arguments.length>3&&void 0!==arguments[3]?arguments[3]:""} { ${t}: ${r}; }\n`:""}function _(e,t,r,n){return w(e,"background-color",t)+w(e,"color",r)+w(e,"background-color",n,":hover")+w(e,"background-color",n,":focus")}function h(e){let{selector:t,style:r,backgroundColor:n}=e;const l=function(e,t,r){const n=`${e} .components-button`,o=("string"==typeof(l=r)?y(l):l?.color?.background||null)||t?.color?.background;var l;return _(n,b(t?.elements?.link?.color?.text),o,b(t?.elements?.link?.[":hover"]?.color?.text))}(t,r,n);return(0,o.createElement)("style",null,l)}const{namespace:E}=window._activityPubOptions,g={avatar:"",resource:"@well@hello.dolly",name:(0,s.__)("Hello Dolly Fan Account","activitypub"),url:"#"};function k(e){if(!e)return g;const t={...g,...e};return t.avatar=t?.icon?.url,t}function O(e){let{profile:t,popupStyles:r,userId:n}=e;const{avatar:l,name:a,resource:c}=t;return(0,o.createElement)("div",{className:"activitypub-profile"},(0,o.createElement)("img",{className:"activitypub-profile__avatar",src:l}),(0,o.createElement)("div",{className:"activitypub-profile__content"},(0,o.createElement)("div",{className:"activitypub-profile__name"},a),(0,o.createElement)("div",{className:"activitypub-profile__handle"},c)),(0,o.createElement)(x,{profile:t,popupStyles:r,userId:n}))}function x(e){let{profile:t,popupStyles:r,userId:n}=e;const[l,a]=(0,o.useState)(!1),c=(0,s.sprintf)((0,s.__)("Follow %s","activitypub"),t?.name);return(0,o.createElement)(o.Fragment,null,(0,o.createElement)(u.Button,{className:"activitypub-profile__follow",onClick:()=>a(!0)},(0,s.__)("Follow","activitypub")),l&&(0,o.createElement)(u.Modal,{className:"activitypub-profile__confirm",onRequestClose:()=>a(!1),title:c},(0,o.createElement)(N,{profile:t,userId:n}),(0,o.createElement)("style",null,r)))}function C(e){try{return new URL(e),!0}catch(e){return!1}}function N(e){let{profile:t,userId:r}=e;const{resource:n}=t,l=(0,s.__)("Follow","activitypub"),a=(0,s.__)("Loading...","activitypub"),c=(0,s.__)("Opening...","activitypub"),p=(0,s.__)("Error","activitypub"),y=(0,s.__)("Invalid","activitypub"),[b,w]=(0,o.useState)(l),[_,h]=(0,o.useState)(m),g=(0,f.useCopyToClipboard)(n,(()=>{h(d),setTimeout((()=>h(m)),1e3)})),[k,O]=(0,o.useState)(""),x=(0,o.useCallback)((()=>{let e;if(!C(k)&&!function(e){const t=e.replace(/^@/,"").split("@");return 2===t.length&&C(`https://${t[1]}`)}(k))return w(y),e=setTimeout((()=>w(l)),2e3),()=>clearTimeout(e);const t=`/${E}/users/${r}/remote-follow?resource=${k}`;w(a),i()({path:t}).then((e=>{let{url:t}=e;w(c),setTimeout((()=>{window.open(t,"_blank"),w(l)}),200)})).catch((()=>{w(p),setTimeout((()=>w(l)),2e3)}))}),[k]);return(0,o.createElement)("div",{className:"activitypub-follow-me__dialog"},(0,o.createElement)("div",{className:"apmfd__section"},(0,o.createElement)("h4",null,(0,s.__)("My Profile","activitypub")),(0,o.createElement)("div",{className:"apfmd-description"},(0,s.__)("Copy and paste my profile into the search field of your favorite fediverse app or server.","activitypub")),(0,o.createElement)("div",{className:"apfmd__button-group"},(0,o.createElement)("input",{type:"text",value:n,readOnly:!0}),(0,o.createElement)(u.Button,{ref:g},(0,o.createElement)(v,{icon:_}),(0,s.__)("Copy","activitypub")))),(0,o.createElement)("div",{className:"apmfd__section"},(0,o.createElement)("h4",null,(0,s.__)("Your Profile","activitypub")),(0,o.createElement)("div",{className:"apfmd-description"},(0,o.createInterpolateElement)((0,s.__)("Or, if you know your own profile, we can start things that way! (eg https://example.com/yourusername or yourusername@example.com)","activitypub"),{code:(0,o.createElement)("code",null)})),(0,o.createElement)("div",{className:"apfmd__button-group"},(0,o.createElement)("input",{type:"text",value:k,onKeyDown:e=>{"Enter"===e?.code&&x()},onChange:e=>O(e.target.value)}),(0,o.createElement)(u.Button,{onClick:x},b))))}function S(e){let{selectedUser:t,style:r,backgroundColor:n,id:l,useId:a=!1}=e;const[c,u]=(0,o.useState)(k()),s="site"===t?0:t,p=function(e){return _(".apfmd__button-group .components-button",b(e?.elements?.link?.color?.text)||"#111","#fff",b(e?.elements?.link?.[":hover"]?.color?.text)||"#333")}(r),m=a?{id:l}:{};function d(e){u(k(e))}return(0,o.useEffect)((()=>{(function(e){const t={headers:{Accept:"application/activity+json"},path:`/${E}/users/${e}`};return i()(t)})(s).then(d)}),[s]),(0,o.createElement)("div",m,(0,o.createElement)(h,{selector:`#${l}`,style:r,backgroundColor:n}),(0,o.createElement)(O,{profile:c,userId:s,popupStyles:p}))}let $=1;a()((()=>{[].forEach.call(document.querySelectorAll(".activitypub-follow-me-block-wrapper"),(e=>{const t=JSON.parse(e.dataset.attrs);(0,o.render)((0,o.createElement)(S,n({},t,{id:"activitypub-follow-me-block-"+$++,useId:!0})),e)}))}))}},r={};function n(e){var o=r[e];if(void 0!==o)return o.exports;var l=r[e]={exports:{}};return t[e](l,l.exports,n),l.exports}n.m=t,e=[],n.O=(t,r,o,l)=>{if(!r){var a=1/0;for(s=0;s=l)&&Object.keys(n.O).every((e=>n.O[e](r[i])))?r.splice(i--,1):(c=!1,l0&&e[s-1][2]>l;s--)e[s]=e[s-1];e[s]=[r,o,l]},n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{var e={529:0,740:0};n.O.j=t=>0===e[t];var t=(t,r)=>{var o,l,[a,c,i]=r,u=0;if(a.some((t=>0!==e[t]))){for(o in c)n.o(c,o)&&(n.m[o]=c[o]);if(i)var s=i(n)}for(t&&t(r);un(810)));o=n.O(o)})(); \ No newline at end of file diff --git a/build/followers/index.asset.php b/build/followers/index.asset.php index 06c1d9d..da1854a 100644 --- a/build/followers/index.asset.php +++ b/build/followers/index.asset.php @@ -1 +1 @@ - array('react', 'wp-api-fetch', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-data', 'wp-element', 'wp-i18n', 'wp-primitives', 'wp-url'), 'version' => '284dffd27ea0242085be'); + array('react', 'wp-api-fetch', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-data', 'wp-element', 'wp-i18n', 'wp-primitives', 'wp-url'), 'version' => '423cdeefa42e7c7cabd1'); diff --git a/build/followers/index.js b/build/followers/index.js index df9590b..1685162 100644 --- a/build/followers/index.js +++ b/build/followers/index.js @@ -1,3 +1,3 @@ -(()=>{var e={184:(e,t)=>{var a;!function(){"use strict";var n={}.hasOwnProperty;function l(){for(var e=[],t=0;t{var t=e&&e.__esModule?()=>e.default:()=>e;return a.d(t,{a:t}),t},a.d=(e,t)=>{for(var n in t)a.o(t,n)&&!a.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},a.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";const e=window.wp.blocks,t=window.wp.element,n=window.wp.primitives,l=(0,t.createElement)(n.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,t.createElement)(n.Path,{d:"M15.5 9.5a1 1 0 100-2 1 1 0 000 2zm0 1.5a2.5 2.5 0 100-5 2.5 2.5 0 000 5zm-2.25 6v-2a2.75 2.75 0 00-2.75-2.75h-4A2.75 2.75 0 003.75 15v2h1.5v-2c0-.69.56-1.25 1.25-1.25h4c.69 0 1.25.56 1.25 1.25v2h1.5zm7-2v2h-1.5v-2c0-.69-.56-1.25-1.25-1.25H15v-1.5h2.5A2.75 2.75 0 0120.25 15zM9.5 8.5a1 1 0 11-2 0 1 1 0 012 0zm1.5 0a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z",fillRule:"evenodd"}));function r(){return r=Object.assign?Object.assign.bind():function(e){for(var t=1;t{e.preventDefault(),!a&&r(l)}},n)}const g={outlined:"outlined",minimal:"minimal"};function f(e){let{compact:a,nextLabel:n,page:l,pageClick:r,perPage:o,prevLabel:i,total:c,variant:s=g.outlined}=e;const p=((e,t)=>{let a=[1,e-2,e-1,e,e+1,e+2,t];a.sort(((e,t)=>e-t)),a=a.filter(((e,a,n)=>e>=1&&e<=t&&n.lastIndexOf(e)===a));for(let e=a.length-2;e>=0;e--)a[e]===a[e+1]&&a.splice(e+1,1);return a})(l,Math.ceil(c/o)),u=w()("alignwide wp-block-query-pagination is-content-justification-space-between is-layout-flex wp-block-query-pagination-is-layout-flex",`is-${s}`,{"is-compact":a});return(0,t.createElement)("nav",{className:u},i&&(0,t.createElement)(d,{key:"prev",page:l-1,pageClick:r,active:1===l,"aria-label":i,className:"wp-block-query-pagination-previous block-editor-block-list__block"},i),!a&&(0,t.createElement)("div",{className:"block-editor-block-list__block wp-block wp-block-query-pagination-numbers"},p.map((e=>(0,t.createElement)(d,{key:e,page:e,pageClick:r,active:e===l,className:"page-numbers"},e)))),n&&(0,t.createElement)(d,{key:"next",page:l+1,pageClick:r,active:l===Math.ceil(c/o),"aria-label":n,className:"wp-block-query-pagination-next block-editor-block-list__block"},n))}const{namespace:y}=window._activityPubOptions;function h(e){let{selectedUser:a,per_page:n,order:l,title:o,page:i,setPage:c,className:u="",followLinks:b=!0}=e;const w="site"===a?0:a,[d,g]=(0,p.useState)([]),[h,_]=(0,p.useState)(0),[E,x]=(0,p.useState)(0),[C,S]=function(){const[e,t]=(0,p.useState)(1);return[e,t]}(),O=i||C,N=c||S,P=(0,t.createInterpolateElement)(/* translators: arrow for previous followers link */ -(0,s.__)(" Less","activitypub"),{span:(0,t.createElement)("span",{class:"wp-block-query-pagination-previous-arrow is-arrow-arrow","aria-hidden":"true"})}),L=(0,t.createInterpolateElement)(/* translators: arrow for next followers link */ -(0,s.__)("More ","activitypub"),{span:(0,t.createElement)("span",{class:"wp-block-query-pagination-next-arrow is-arrow-arrow","aria-hidden":"true"})});return(0,p.useEffect)((()=>{const e=function(e,t,a,n){const l=`/${y}/users/${e}/followers`,r={per_page:t,order:a,page:n,context:"full"};return(0,m.addQueryArgs)(l,r)}(w,n,l,O);v()({path:e}).then((e=>{_(Math.ceil(e.totalItems/n)),x(e.totalItems),g(e.orderedItems)})).catch((e=>console.error(e)))}),[w,n,l,O]),(0,t.createElement)("div",{className:"activitypub-follower-block "+u},(0,t.createElement)("h3",null,o),(0,t.createElement)("ul",null,d&&d.map((e=>(0,t.createElement)("li",{key:e.url},(0,t.createElement)(k,r({},e,{followLinks:b})))))),h>1&&(0,t.createElement)(f,{page:O,perPage:n,total:E,pageClick:N,nextLabel:L,prevLabel:P,compact:"is-style-compact"===u}))}function k(e){let{name:a,icon:n,url:l,preferredUsername:i,followLinks:c=!0}=e;const s=`@${i}`,p={};return c||(p.onClick=e=>e.preventDefault()),(0,t.createElement)(o.ExternalLink,r({className:"activitypub-link",href:l,title:s},p),(0,t.createElement)("img",{width:"40",height:"40",src:n.url,class:"avatar activitypub-avatar"}),(0,t.createElement)("span",{class:"activitypub-actor"},(0,t.createElement)("strong",{className:"activitypub-name"},a),(0,t.createElement)("span",{class:"sep"},"/"),(0,t.createElement)("span",{class:"activitypub-handle"},s)))}const _=window._activityPubOptions?.enabled;(0,e.registerBlockType)("activitypub/followers",{edit:function(e){let{attributes:a,setAttributes:n}=e;const{order:l,per_page:p,selectedUser:u,title:v}=a,m=(0,c.useBlockProps)(),[b,w]=(0,t.useState)(1),d=[{label:(0,s.__)("New to old","activitypub"),value:"desc"},{label:(0,s.__)("Old to new","activitypub"),value:"asc"}],g=function(){const e=_?.users?(0,i.useSelect)((e=>e("core").getUsers({who:"authors"}))):[];return(0,t.useMemo)((()=>{if(!e)return[];const t=_?.site?[{label:(0,s.__)("Whole Site","activitypub"),value:"site"}]:[];return e.reduce(((e,t)=>(e.push({label:t.name,value:t.id}),e)),t)}),[e])}(),f=e=>t=>{w(1),n({[e]:t})};return(0,t.createElement)("div",m,(0,t.createElement)(c.InspectorControls,{key:"setting"},(0,t.createElement)(o.PanelBody,{title:(0,s.__)("Followers Options","activitypub")},(0,t.createElement)(o.TextControl,{label:(0,s.__)("Title","activitypub"),help:(0,s.__)("Title to display above the list of followers. Blank for none.","activitypub"),value:v,onChange:e=>n({title:e})}),(0,t.createElement)(o.SelectControl,{label:(0,s.__)("Select User","activitypub"),value:u,options:g,onChange:f("selectedUser")}),(0,t.createElement)(o.SelectControl,{label:(0,s.__)("Sort","activitypub"),value:l,options:d,onChange:f("order")}),(0,t.createElement)(o.RangeControl,{label:(0,s.__)("Number of Followers","activitypub"),value:p,onChange:f("per_page"),min:1,max:10}))),(0,t.createElement)(h,r({},a,{page:b,setPage:w,followLinks:!1})))},save:()=>null,icon:l})})()})(); \ No newline at end of file +(()=>{var e={184:(e,t)=>{var a;!function(){"use strict";var n={}.hasOwnProperty;function l(){for(var e=[],t=0;t{var t=e&&e.__esModule?()=>e.default:()=>e;return a.d(t,{a:t}),t},a.d=(e,t)=>{for(var n in t)a.o(t,n)&&!a.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},a.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";const e=window.wp.blocks,t=window.wp.element,n=window.wp.primitives,l=(0,t.createElement)(n.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,t.createElement)(n.Path,{d:"M15.5 9.5a1 1 0 100-2 1 1 0 000 2zm0 1.5a2.5 2.5 0 100-5 2.5 2.5 0 000 5zm-2.25 6v-2a2.75 2.75 0 00-2.75-2.75h-4A2.75 2.75 0 003.75 15v2h1.5v-2c0-.69.56-1.25 1.25-1.25h4c.69 0 1.25.56 1.25 1.25v2h1.5zm7-2v2h-1.5v-2c0-.69-.56-1.25-1.25-1.25H15v-1.5h2.5A2.75 2.75 0 0120.25 15zM9.5 8.5a1 1 0 11-2 0 1 1 0 012 0zm1.5 0a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z",fillRule:"evenodd"}));function r(){return r=Object.assign?Object.assign.bind():function(e){for(var t=1;t{e.preventDefault(),!a&&r(l)}},n)}const d={outlined:"outlined",minimal:"minimal"};function g(e){let{compact:a,nextLabel:n,page:l,pageClick:r,perPage:o,prevLabel:i,total:c,variant:s=d.outlined}=e;const p=((e,t)=>{let a=[1,e-2,e-1,e,e+1,e+2,t];a.sort(((e,t)=>e-t)),a=a.filter(((e,a,n)=>e>=1&&e<=t&&n.lastIndexOf(e)===a));for(let e=a.length-2;e>=0;e--)a[e]===a[e+1]&&a.splice(e+1,1);return a})(l,Math.ceil(c/o)),u=b()("alignwide wp-block-query-pagination is-content-justification-space-between is-layout-flex wp-block-query-pagination-is-layout-flex",`is-${s}`,{"is-compact":a});return(0,t.createElement)("nav",{className:u},i&&(0,t.createElement)(w,{key:"prev",page:l-1,pageClick:r,active:1===l,"aria-label":i,className:"wp-block-query-pagination-previous block-editor-block-list__block"},i),!a&&(0,t.createElement)("div",{className:"block-editor-block-list__block wp-block wp-block-query-pagination-numbers"},p.map((e=>(0,t.createElement)(w,{key:e,page:e,pageClick:r,active:e===l,className:"page-numbers"},e)))),n&&(0,t.createElement)(w,{key:"next",page:l+1,pageClick:r,active:l===Math.ceil(c/o),"aria-label":n,className:"wp-block-query-pagination-next block-editor-block-list__block"},n))}const{namespace:f}=window._activityPubOptions;function y(e){let{selectedUser:a,per_page:n,order:l,title:o,page:i,setPage:p,className:m="",followLinks:b=!0}=e;const w="site"===a?0:a,[d,y]=(0,s.useState)([]),[k,E]=(0,s.useState)(0),[_,x]=(0,s.useState)(0),[C,S]=function(){const[e,t]=(0,s.useState)(1);return[e,t]}(),O=i||C,N=p||S,P=(0,t.createInterpolateElement)(/* translators: arrow for previous followers link */ +(0,c.__)(" Less","activitypub"),{span:(0,t.createElement)("span",{class:"wp-block-query-pagination-previous-arrow is-arrow-arrow","aria-hidden":"true"})}),L=(0,t.createInterpolateElement)(/* translators: arrow for next followers link */ +(0,c.__)("More ","activitypub"),{span:(0,t.createElement)("span",{class:"wp-block-query-pagination-next-arrow is-arrow-arrow","aria-hidden":"true"})});return(0,s.useEffect)((()=>{const e=function(e,t,a,n){const l=`/${f}/users/${e}/followers`,r={per_page:t,order:a,page:n,context:"full"};return(0,v.addQueryArgs)(l,r)}(w,n,l,O);u()({path:e}).then((e=>{E(Math.ceil(e.totalItems/n)),x(e.totalItems),y(e.orderedItems)})).catch((()=>{}))}),[w,n,l,O]),(0,t.createElement)("div",{className:"activitypub-follower-block "+m},(0,t.createElement)("h3",null,o),(0,t.createElement)("ul",null,d&&d.map((e=>(0,t.createElement)("li",{key:e.url},(0,t.createElement)(h,r({},e,{followLinks:b})))))),k>1&&(0,t.createElement)(g,{page:O,perPage:n,total:_,pageClick:N,nextLabel:L,prevLabel:P,compact:"is-style-compact"===m}))}function h(e){let{name:a,icon:n,url:l,preferredUsername:i,followLinks:c=!0}=e;const s=`@${i}`,p={};return c||(p.onClick=e=>e.preventDefault()),(0,t.createElement)(o.ExternalLink,r({className:"activitypub-link",href:l,title:s},p),(0,t.createElement)("img",{width:"40",height:"40",src:n.url,class:"avatar activitypub-avatar"}),(0,t.createElement)("span",{class:"activitypub-actor"},(0,t.createElement)("strong",{className:"activitypub-name"},a),(0,t.createElement)("span",{class:"sep"},"/"),(0,t.createElement)("span",{class:"activitypub-handle"},s)))}const k=window.wp.data,E=window._activityPubOptions?.enabled;(0,e.registerBlockType)("activitypub/followers",{edit:function(e){let{attributes:a,setAttributes:n}=e;const{order:l,per_page:s,selectedUser:p,title:u}=a,v=(0,i.useBlockProps)(),[m,b]=(0,t.useState)(1),w=[{label:(0,c.__)("New to old","activitypub"),value:"desc"},{label:(0,c.__)("Old to new","activitypub"),value:"asc"}],d=function(){const e=E?.users?(0,k.useSelect)((e=>e("core").getUsers({who:"authors"}))):[];return(0,t.useMemo)((()=>{if(!e)return[];const t=E?.site?[{label:(0,c.__)("Whole Site","activitypub"),value:"site"}]:[];return e.reduce(((e,t)=>(e.push({label:t.name,value:`${t.id}`}),e)),t)}),[e])}(),g=e=>t=>{b(1),n({[e]:t})};return(0,t.useEffect)((()=>{d.length&&(d.find((e=>{let{value:t}=e;return t===p}))||n({selectedUser:d[0].value}))}),[p,d]),(0,t.createElement)("div",v,(0,t.createElement)(i.InspectorControls,{key:"setting"},(0,t.createElement)(o.PanelBody,{title:(0,c.__)("Followers Options","activitypub")},(0,t.createElement)(o.TextControl,{label:(0,c.__)("Title","activitypub"),help:(0,c.__)("Title to display above the list of followers. Blank for none.","activitypub"),value:u,onChange:e=>n({title:e})}),(0,t.createElement)(o.SelectControl,{label:(0,c.__)("Select User","activitypub"),value:p,options:d,onChange:g("selectedUser")}),(0,t.createElement)(o.SelectControl,{label:(0,c.__)("Sort","activitypub"),value:l,options:w,onChange:g("order")}),(0,t.createElement)(o.RangeControl,{label:(0,c.__)("Number of Followers","activitypub"),value:s,onChange:g("per_page"),min:1,max:10}))),(0,t.createElement)(y,r({},a,{page:m,setPage:b,followLinks:!1})))},save:()=>null,icon:l})})()})(); \ No newline at end of file diff --git a/build/followers/view.asset.php b/build/followers/view.asset.php index 7f57812..32ae6d5 100644 --- a/build/followers/view.asset.php +++ b/build/followers/view.asset.php @@ -1 +1 @@ - array('react', 'wp-api-fetch', 'wp-components', 'wp-dom-ready', 'wp-element', 'wp-i18n', 'wp-url'), 'version' => 'd645fd4aa610b479e8f4'); + array('react', 'wp-api-fetch', 'wp-components', 'wp-dom-ready', 'wp-element', 'wp-i18n', 'wp-url'), 'version' => '6384e801c2802d2fecee'); diff --git a/build/followers/view.js b/build/followers/view.js index f28d93f..29367a8 100644 --- a/build/followers/view.js +++ b/build/followers/view.js @@ -1,3 +1,3 @@ -(()=>{var e,t={189:(e,t,a)=>{"use strict";const r=window.wp.element;function n(){return n=Object.assign?Object.assign.bind():function(e){for(var t=1;t{e.preventDefault(),!t&&l(n)}},a)}const v={outlined:"outlined",minimal:"minimal"};function b(e){let{compact:t,nextLabel:a,page:n,pageClick:l,perPage:o,prevLabel:i,total:c,variant:s=v.outlined}=e;const p=((e,t)=>{let a=[1,e-2,e-1,e,e+1,e+2,t];a.sort(((e,t)=>e-t)),a=a.filter(((e,a,r)=>e>=1&&e<=t&&r.lastIndexOf(e)===a));for(let e=a.length-2;e>=0;e--)a[e]===a[e+1]&&a.splice(e+1,1);return a})(n,Math.ceil(c/o)),b=u()("alignwide wp-block-query-pagination is-content-justification-space-between is-layout-flex wp-block-query-pagination-is-layout-flex",`is-${s}`,{"is-compact":t});return(0,r.createElement)("nav",{className:b},i&&(0,r.createElement)(m,{key:"prev",page:n-1,pageClick:l,active:1===n,"aria-label":i,className:"wp-block-query-pagination-previous block-editor-block-list__block"},i),!t&&(0,r.createElement)("div",{className:"block-editor-block-list__block wp-block wp-block-query-pagination-numbers"},p.map((e=>(0,r.createElement)(m,{key:e,page:e,pageClick:l,active:e===n,className:"page-numbers"},e)))),a&&(0,r.createElement)(m,{key:"next",page:n+1,pageClick:l,active:n===Math.ceil(c/o),"aria-label":a,className:"wp-block-query-pagination-next block-editor-block-list__block"},a))}const f=window.wp.components,{namespace:d}=window._activityPubOptions;function w(e){let{selectedUser:t,per_page:a,order:o,title:p,page:u,setPage:m,className:v="",followLinks:f=!0}=e;const w="site"===t?0:t,[y,k]=(0,l.useState)([]),[h,E]=(0,l.useState)(0),[O,x]=(0,l.useState)(0),[_,N]=function(){const[e,t]=(0,l.useState)(1);return[e,t]}(),j=u||_,S=m||N,C=(0,r.createInterpolateElement)(/* translators: arrow for previous followers link */ +(()=>{var e,t={189:(e,t,a)=>{"use strict";const r=window.wp.element;function n(){return n=Object.assign?Object.assign.bind():function(e){for(var t=1;t{e.preventDefault(),!t&&l(n)}},a)}const v={outlined:"outlined",minimal:"minimal"};function b(e){let{compact:t,nextLabel:a,page:n,pageClick:l,perPage:i,prevLabel:o,total:c,variant:s=v.outlined}=e;const p=((e,t)=>{let a=[1,e-2,e-1,e,e+1,e+2,t];a.sort(((e,t)=>e-t)),a=a.filter(((e,a,r)=>e>=1&&e<=t&&r.lastIndexOf(e)===a));for(let e=a.length-2;e>=0;e--)a[e]===a[e+1]&&a.splice(e+1,1);return a})(n,Math.ceil(c/i)),b=u()("alignwide wp-block-query-pagination is-content-justification-space-between is-layout-flex wp-block-query-pagination-is-layout-flex",`is-${s}`,{"is-compact":t});return(0,r.createElement)("nav",{className:b},o&&(0,r.createElement)(m,{key:"prev",page:n-1,pageClick:l,active:1===n,"aria-label":o,className:"wp-block-query-pagination-previous block-editor-block-list__block"},o),!t&&(0,r.createElement)("div",{className:"block-editor-block-list__block wp-block wp-block-query-pagination-numbers"},p.map((e=>(0,r.createElement)(m,{key:e,page:e,pageClick:l,active:e===n,className:"page-numbers"},e)))),a&&(0,r.createElement)(m,{key:"next",page:n+1,pageClick:l,active:n===Math.ceil(c/i),"aria-label":a,className:"wp-block-query-pagination-next block-editor-block-list__block"},a))}const f=window.wp.components,{namespace:d}=window._activityPubOptions;function w(e){let{selectedUser:t,per_page:a,order:i,title:p,page:u,setPage:m,className:v="",followLinks:f=!0}=e;const w="site"===t?0:t,[y,k]=(0,l.useState)([]),[h,E]=(0,l.useState)(0),[O,x]=(0,l.useState)(0),[_,N]=function(){const[e,t]=(0,l.useState)(1);return[e,t]}(),j=u||_,S=m||N,C=(0,r.createInterpolateElement)(/* translators: arrow for previous followers link */ (0,s.__)(" Less","activitypub"),{span:(0,r.createElement)("span",{class:"wp-block-query-pagination-previous-arrow is-arrow-arrow","aria-hidden":"true"})}),L=(0,r.createInterpolateElement)(/* translators: arrow for next followers link */ -(0,s.__)("More ","activitypub"),{span:(0,r.createElement)("span",{class:"wp-block-query-pagination-next-arrow is-arrow-arrow","aria-hidden":"true"})});return(0,l.useEffect)((()=>{const e=function(e,t,a,r){const n=`/${d}/users/${e}/followers`,l={per_page:t,order:a,page:r,context:"full"};return(0,c.addQueryArgs)(n,l)}(w,a,o,j);i()({path:e}).then((e=>{E(Math.ceil(e.totalItems/a)),x(e.totalItems),k(e.orderedItems)})).catch((e=>console.error(e)))}),[w,a,o,j]),(0,r.createElement)("div",{className:"activitypub-follower-block "+v},(0,r.createElement)("h3",null,p),(0,r.createElement)("ul",null,y&&y.map((e=>(0,r.createElement)("li",{key:e.url},(0,r.createElement)(g,n({},e,{followLinks:f})))))),h>1&&(0,r.createElement)(b,{page:j,perPage:a,total:O,pageClick:S,nextLabel:L,prevLabel:C,compact:"is-style-compact"===v}))}function g(e){let{name:t,icon:a,url:l,preferredUsername:o,followLinks:i=!0}=e;const c=`@${o}`,s={};return i||(s.onClick=e=>e.preventDefault()),(0,r.createElement)(f.ExternalLink,n({className:"activitypub-link",href:l,title:c},s),(0,r.createElement)("img",{width:"40",height:"40",src:a.url,class:"avatar activitypub-avatar"}),(0,r.createElement)("span",{class:"activitypub-actor"},(0,r.createElement)("strong",{className:"activitypub-name"},t),(0,r.createElement)("span",{class:"sep"},"/"),(0,r.createElement)("span",{class:"activitypub-handle"},c)))}const y=window.wp.domReady;a.n(y)()((()=>{[].forEach.call(document.querySelectorAll(".activitypub-follower-block"),(e=>{const t=JSON.parse(e.dataset.attrs);(0,r.render)((0,r.createElement)(w,t),e)}))}))},184:(e,t)=>{var a;!function(){"use strict";var r={}.hasOwnProperty;function n(){for(var e=[],t=0;t{if(!a){var o=1/0;for(p=0;p=l)&&Object.keys(r.O).every((e=>r.O[e](a[c])))?a.splice(c--,1):(i=!1,l0&&e[p-1][2]>l;p--)e[p]=e[p-1];e[p]=[a,n,l]},r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var a in t)r.o(t,a)&&!r.o(e,a)&&Object.defineProperty(e,a,{enumerable:!0,get:t[a]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{var e={638:0,962:0};r.O.j=t=>0===e[t];var t=(t,a)=>{var n,l,[o,i,c]=a,s=0;if(o.some((t=>0!==e[t]))){for(n in i)r.o(i,n)&&(r.m[n]=i[n]);if(c)var p=c(r)}for(t&&t(a);sr(189)));n=r.O(n)})(); \ No newline at end of file +(0,s.__)("More ","activitypub"),{span:(0,r.createElement)("span",{class:"wp-block-query-pagination-next-arrow is-arrow-arrow","aria-hidden":"true"})});return(0,l.useEffect)((()=>{const e=function(e,t,a,r){const n=`/${d}/users/${e}/followers`,l={per_page:t,order:a,page:r,context:"full"};return(0,c.addQueryArgs)(n,l)}(w,a,i,j);o()({path:e}).then((e=>{E(Math.ceil(e.totalItems/a)),x(e.totalItems),k(e.orderedItems)})).catch((()=>{}))}),[w,a,i,j]),(0,r.createElement)("div",{className:"activitypub-follower-block "+v},(0,r.createElement)("h3",null,p),(0,r.createElement)("ul",null,y&&y.map((e=>(0,r.createElement)("li",{key:e.url},(0,r.createElement)(g,n({},e,{followLinks:f})))))),h>1&&(0,r.createElement)(b,{page:j,perPage:a,total:O,pageClick:S,nextLabel:L,prevLabel:C,compact:"is-style-compact"===v}))}function g(e){let{name:t,icon:a,url:l,preferredUsername:i,followLinks:o=!0}=e;const c=`@${i}`,s={};return o||(s.onClick=e=>e.preventDefault()),(0,r.createElement)(f.ExternalLink,n({className:"activitypub-link",href:l,title:c},s),(0,r.createElement)("img",{width:"40",height:"40",src:a.url,class:"avatar activitypub-avatar"}),(0,r.createElement)("span",{class:"activitypub-actor"},(0,r.createElement)("strong",{className:"activitypub-name"},t),(0,r.createElement)("span",{class:"sep"},"/"),(0,r.createElement)("span",{class:"activitypub-handle"},c)))}const y=window.wp.domReady;a.n(y)()((()=>{[].forEach.call(document.querySelectorAll(".activitypub-follower-block"),(e=>{const t=JSON.parse(e.dataset.attrs);(0,r.render)((0,r.createElement)(w,t),e)}))}))},184:(e,t)=>{var a;!function(){"use strict";var r={}.hasOwnProperty;function n(){for(var e=[],t=0;t{if(!a){var i=1/0;for(p=0;p=l)&&Object.keys(r.O).every((e=>r.O[e](a[c])))?a.splice(c--,1):(o=!1,l0&&e[p-1][2]>l;p--)e[p]=e[p-1];e[p]=[a,n,l]},r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var a in t)r.o(t,a)&&!r.o(e,a)&&Object.defineProperty(e,a,{enumerable:!0,get:t[a]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{var e={638:0,962:0};r.O.j=t=>0===e[t];var t=(t,a)=>{var n,l,[i,o,c]=a,s=0;if(i.some((t=>0!==e[t]))){for(n in o)r.o(o,n)&&(r.m[n]=o[n]);if(c)var p=c(r)}for(t&&t(a);sr(189)));n=r.O(n)})(); \ No newline at end of file diff --git a/composer.json b/composer.json index d34d110..054226f 100644 --- a/composer.json +++ b/composer.json @@ -41,6 +41,9 @@ ], "lint": [ "vendor/bin/phpcs -n -q" + ], + "lint:fix": [ + "vendor/bin/phpcbf" ] } } diff --git a/includes/activity/class-activity.php b/includes/activity/class-activity.php index 8799238..6c59866 100644 --- a/includes/activity/class-activity.php +++ b/includes/activity/class-activity.php @@ -26,7 +26,9 @@ class Activity extends Base_Object { 'schema' => 'http://schema.org#', 'pt' => 'https://joinpeertube.org/ns#', 'toot' => 'http://joinmastodon.org/ns#', + 'webfinger' => 'https://webfinger.net/#', 'litepub' => 'http://litepub.social/ns#', + 'lemmy' => 'https://join-lemmy.org/ns#', 'value' => 'schema:value', 'Hashtag' => 'as:Hashtag', 'featured' => array( @@ -37,8 +39,19 @@ class Activity extends Base_Object { '@id' => 'toot:featuredTags', '@type' => '@id', ), + 'alsoKnownAs' => array( + '@id' => 'as:alsoKnownAs', + '@type' => '@id', + ), + 'moderators' => array( + '@id' => 'lemmy:moderators', + '@type' => '@id', + ), + 'postingRestrictedToMods' => 'lemmy:postingRestrictedToMods', 'discoverable' => 'toot:discoverable', + 'indexable' => 'toot:indexable', 'sensitive' => 'as:sensitive', + 'resource' => 'webfinger:resource', ), ); diff --git a/includes/activity/class-base-object.php b/includes/activity/class-base-object.php index 3b6703b..a75ed16 100644 --- a/includes/activity/class-base-object.php +++ b/includes/activity/class-base-object.php @@ -450,7 +450,7 @@ class Base_Object { if ( \strncasecmp( $method, 'get', 3 ) === 0 ) { if ( ! $this->has( $var ) ) { - return new WP_Error( 'invalid_key', 'Invalid key' ); + return new WP_Error( 'invalid_key', __( 'Invalid key', 'activitypub' ), array( 'status' => 404 ) ); } return $this->$var; @@ -492,7 +492,7 @@ class Base_Object { */ public function get( $key ) { if ( ! $this->has( $key ) ) { - return new WP_Error( 'invalid_key', 'Invalid key' ); + return new WP_Error( 'invalid_key', __( 'Invalid key', 'activitypub' ), array( 'status' => 404 ) ); } return call_user_func( array( $this, 'get_' . $key ) ); @@ -519,7 +519,7 @@ class Base_Object { */ public function set( $key, $value ) { if ( ! $this->has( $key ) ) { - return new WP_Error( 'invalid_key', 'Invalid key' ); + return new WP_Error( 'invalid_key', __( 'Invalid key', 'activitypub' ), array( 'status' => 404 ) ); } $this->$key = $value; @@ -537,7 +537,7 @@ class Base_Object { */ public function add( $key, $value ) { if ( ! $this->has( $key ) ) { - return new WP_Error( 'invalid_key', 'Invalid key' ); + return new WP_Error( 'invalid_key', __( 'Invalid key', 'activitypub' ), array( 'status' => 404 ) ); } if ( ! isset( $this->$key ) ) { @@ -562,6 +562,10 @@ class Base_Object { public static function init_from_json( $json ) { $array = \json_decode( $json, true ); + if ( ! is_array( $array ) ) { + $array = array(); + } + return self::init_from_array( $array ); } @@ -573,6 +577,10 @@ class Base_Object { * @return \Activitypub\Activity\Base_Object An Object built from the JSON string. */ public static function init_from_array( $array ) { + if ( ! is_array( $array ) ) { + return new WP_Error( 'invalid_array', __( 'Invalid array', 'activitypub' ), array( 'status' => 404 ) ); + } + $object = new static(); foreach ( $array as $key => $value ) { @@ -636,7 +644,7 @@ class Base_Object { } // if value is still empty, ignore it for the array and continue. - if ( $value ) { + if ( isset( $value ) ) { $array[ snake_to_camel_case( $key ) ] = $value; } } diff --git a/includes/class-activitypub.php b/includes/class-activitypub.php index cddbd1d..e54249d 100644 --- a/includes/class-activitypub.php +++ b/includes/class-activitypub.php @@ -17,6 +17,7 @@ class Activitypub { \add_filter( 'template_include', array( self::class, 'render_json_template' ), 99 ); \add_filter( 'query_vars', array( self::class, 'add_query_vars' ) ); \add_filter( 'pre_get_avatar_data', array( self::class, 'pre_get_avatar_data' ), 11, 2 ); + \add_filter( 'get_comment_link', array( self::class, 'remote_comment_link' ), 11, 3 ); // Add support for ActivityPub to custom post types $post_types = \get_option( 'activitypub_support_post_types', array( 'post', 'page' ) ) ? \get_option( 'activitypub_support_post_types', array( 'post', 'page' ) ) : array(); @@ -188,6 +189,22 @@ class Activitypub { return \get_comment_meta( $comment->comment_ID, 'avatar_url', true ); } + /** + * Link remote comments to source url. + * + * @param string $comment_link + * @param object|WP_Comment $comment + * + * @return string $url + */ + public static function remote_comment_link( $comment_link, $comment ) { + $remote_comment_link = get_comment_meta( $comment->comment_ID, 'source_url', true ); + if ( $remote_comment_link ) { + $comment_link = esc_url( $remote_comment_link ); + } + return $comment_link; + } + /** * Store permalink in meta, to send delete Activity. * diff --git a/includes/class-admin.php b/includes/class-admin.php index 70d1206..827012a 100644 --- a/includes/class-admin.php +++ b/includes/class-admin.php @@ -1,6 +1,9 @@ 'string', 'description' => \esc_html__( 'The Identifier of the Blog-User', 'activitypub' ), 'show_in_rest' => true, - 'default' => \Activitypub\Model\Blog_User::get_default_username(), + 'default' => Blog_User::get_default_username(), 'sanitize_callback' => function( $value ) { // hack to allow dots in the username $parts = explode( '.', $value ); @@ -179,7 +182,31 @@ class Admin { $sanitized[] = \sanitize_title( $part ); } - return implode( '.', $sanitized ); + $sanitized = implode( '.', $sanitized ); + + // check for login or nicename. + $user = new WP_User_Query( + array( + 'search' => $sanitized, + 'search_columns' => array( 'user_login', 'user_nicename' ), + 'number' => 1, + 'hide_empty' => true, + 'fields' => 'ID', + ) + ); + + if ( $user->results ) { + add_settings_error( + 'activitypub_blog_user_identifier', + 'activitypub_blog_user_identifier', + \esc_html__( 'You cannot use an existing author\'s name for the blog profile ID.', 'activitypub' ), + 'error' + ); + + return Blog_User::get_default_username(); + } + + return $sanitized; }, ) ); diff --git a/includes/class-blocks.php b/includes/class-blocks.php index a59c4df..fca634c 100644 --- a/includes/class-blocks.php +++ b/includes/class-blocks.php @@ -13,7 +13,9 @@ class Blocks { } public static function add_data() { - $handle = is_admin() ? 'activitypub-followers-editor-script' : 'activitypub-followers-view-script'; + $context = is_admin() ? 'editor' : 'view'; + $followers_handle = 'activitypub-followers-' . $context . '-script'; + $follow_me_handle = 'activitypub-follow-me-' . $context . '-script'; $data = array( 'namespace' => ACTIVITYPUB_REST_NAMESPACE, 'enabled' => array( @@ -22,7 +24,8 @@ class Blocks { ), ); $js = sprintf( 'var _activityPubOptions = %s;', wp_json_encode( $data ) ); - \wp_add_inline_script( $handle, $js, 'before' ); + \wp_add_inline_script( $followers_handle, $js, 'before' ); + \wp_add_inline_script( $follow_me_handle, $js, 'before' ); } public static function register_blocks() { @@ -32,6 +35,12 @@ class Blocks { 'render_callback' => array( self::class, 'render_follower_block' ), ) ); + \register_block_type_from_metadata( + ACTIVITYPUB_PLUGIN_DIR . '/build/follow-me', + array( + 'render_callback' => array( self::class, 'render_follow_me_block' ), + ) + ); } private static function get_user_id( $user_string ) { @@ -42,7 +51,24 @@ class Blocks { return 0; } - public static function render_follower_block( $attrs, $content, $block ) { + /** + * Render the follow me block. + * @param array $attrs The block attributes. + * @return string The HTML to render. + */ + public static function render_follow_me_block( $attrs ) { + $wrapper_attributes = get_block_wrapper_attributes( + array( + 'aria-label' => __( 'Follow me on the Fediverse', 'activitypub' ), + 'class' => 'activitypub-follow-me-block-wrapper', + 'data-attrs' => wp_json_encode( $attrs ), + ) + ); + // todo: render more than an empty div? + return '
'; + } + + public static function render_follower_block( $attrs ) { $followee_user_id = self::get_user_id( $attrs['selectedUser'] ); $per_page = absint( $attrs['per_page'] ); $followers = Followers::get_followers( $followee_user_id, $per_page ); @@ -55,7 +81,7 @@ class Blocks { ) ); - $html = '
'; + $html = '
'; if ( $title ) { $html .= '

' . $title . '

'; } diff --git a/includes/class-hashtag.php b/includes/class-hashtag.php index 1a76577..2d03ac4 100644 --- a/includes/class-hashtag.php +++ b/includes/class-hashtag.php @@ -43,38 +43,56 @@ class Hashtag { * @return string the filtered post-content */ public static function the_content( $the_content ) { - $protected_tags = array(); - $protect = function( $m ) use ( &$protected_tags ) { - $c = \wp_rand( 100000, 999999 ); - $protect = '!#!#PROTECT' . $c . '#!#!'; - while ( isset( $protected_tags[ $protect ] ) ) { - $c = \wp_rand( 100000, 999999 ); - $protect = '!#!#PROTECT' . $c . '#!#!'; + $tag_stack = array(); + $protected_tags = array( + 'pre', + 'code', + 'textarea', + 'style', + 'a', + ); + $content_with_links = ''; + $in_protected_tag = false; + foreach ( wp_html_split( $the_content ) as $chunk ) { + if ( preg_match( '#^$#i', $chunk, $m ) ) { + $content_with_links .= $chunk; + continue; } - $protected_tags[ $protect ] = $m[0]; - return $protect; - }; - $the_content = preg_replace_callback( - '##is', - $protect, - $the_content - ); - $the_content = preg_replace_callback( - '#<(pre|code|textarea|style)\b[^>]*>.*?]*>#is', - $protect, - $the_content - ); - $the_content = preg_replace_callback( - '#<[^>]+>#i', - $protect, - $the_content - ); - $the_content = \preg_replace_callback( '/' . ACTIVITYPUB_HASHTAGS_REGEXP . '/i', array( '\Activitypub\Hashtag', 'replace_with_links' ), $the_content ); + if ( preg_match( '#^<(/)?([a-z-]+)\b[^>]*>$#i', $chunk, $m ) ) { + $tag = strtolower( $m[2] ); + if ( '/' === $m[1] ) { + // Closing tag. + $i = array_search( $tag, $tag_stack ); + // We can only remove the tag from the stack if it is in the stack. + if ( false !== $i ) { + $tag_stack = array_slice( $tag_stack, 0, $i ); + } + } else { + // Opening tag, add it to the stack. + $tag_stack[] = $tag; + } - $the_content = str_replace( array_reverse( array_keys( $protected_tags ) ), array_reverse( array_values( $protected_tags ) ), $the_content ); + // If we're in a protected tag, the tag_stack contains at least one protected tag string. + // The protected tag state can only change when we encounter a start or end tag. + $in_protected_tag = array_intersect( $tag_stack, $protected_tags ); - return $the_content; + // Never inspect tags. + $content_with_links .= $chunk; + continue; + } + + if ( $in_protected_tag ) { + // Don't inspect a chunk inside an inspected tag. + $content_with_links .= $chunk; + continue; + } + + // Only reachable when there is no protected tag in the stack. + $content_with_links .= \preg_replace_callback( '/' . ACTIVITYPUB_HASHTAGS_REGEXP . '/i', array( '\Activitypub\Hashtag', 'replace_with_links' ), $chunk ); + } + + return $content_with_links; } /** @@ -89,7 +107,7 @@ class Hashtag { if ( $tag_object ) { $link = \get_term_link( $tag_object, 'post_tag' ); - return \sprintf( '', $link, $tag ); + return \sprintf( '', $link, $tag ); } return '#' . $tag; diff --git a/includes/class-health-check.php b/includes/class-health-check.php index 18cd48e..a802e6f 100644 --- a/includes/class-health-check.php +++ b/includes/class-health-check.php @@ -1,6 +1,12 @@ array( self::class, 'test_webfinger' ), ); + $tests['direct']['activitypub_test_system_cron'] = array( + 'label' => __( 'System Cron Test', 'activitypub' ), + 'test' => array( self::class, 'test_system_cron' ), + ); + return $tests; } @@ -70,6 +81,49 @@ class Health_Check { return $result; } + /** + * System Cron tests + * + * @return array + */ + public static function test_system_cron() { + $result = array( + 'label' => \__( 'System Task Scheduler configured', 'activitypub' ), + 'status' => 'good', + 'badge' => array( + 'label' => \__( 'ActivityPub', 'activitypub' ), + 'color' => 'green', + ), + 'description' => \sprintf( + '

%s

', + \esc_html__( 'You seem to use the System Task Scheduler to process WP_Cron tasks.', 'activitypub' ) + ), + 'actions' => '', + 'test' => 'test_system_cron', + ); + + if ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ) { + return $result; + } + + $result['status'] = 'recommended'; + $result['label'] = \__( 'System Task Scheduler not configured', 'activitypub' ); + $result['badge']['color'] = 'orange'; + $result['description'] = \sprintf( + '

%s

', + \__( 'Enhance your WordPress site’s performance and mitigate potential heavy loads caused by plugins like ActivityPub by setting up a system cron job to run WP Cron. This ensures scheduled tasks are executed consistently and reduces the reliance on website traffic for trigger events.', 'activitypub' ) + ); + $result['actions'] .= sprintf( + '

%s %s

', + __( 'https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/', 'activitypub' ), + __( 'Learn how to hook the WP-Cron into the System Task Scheduler.', 'activitypub' ), + /* translators: Hidden accessibility text. */ + __( '(opens in a new tab)', 'activitypub' ) + ); + + return $result; + } + /** * WebFinger tests * @@ -111,7 +165,7 @@ class Health_Check { /** * Check if `author_posts_url` is accessible and that request returns correct JSON * - * @return boolean|\WP_Error + * @return boolean|WP_Error */ public static function is_author_url_accessible() { $user = \wp_get_current_user(); @@ -120,7 +174,7 @@ class Health_Check { // check for "author" in URL if ( $author_url !== $reference_author_url ) { - return new \WP_Error( + return new WP_Error( 'author_url_not_accessible', \sprintf( // translators: %s: Author URL @@ -143,7 +197,7 @@ class Health_Check { ); if ( \is_wp_error( $response ) ) { - return new \WP_Error( + return new WP_Error( 'author_url_not_accessible', \sprintf( // translators: %s: Author URL @@ -160,7 +214,7 @@ class Health_Check { // check for redirects if ( \in_array( $response_code, array( 301, 302, 307, 308 ), true ) ) { - return new \WP_Error( + return new WP_Error( 'author_url_not_accessible', \sprintf( // translators: %s: Author URL @@ -177,7 +231,7 @@ class Health_Check { $body = \wp_remote_retrieve_body( $response ); if ( ! \is_string( $body ) || ! \is_array( \json_decode( $body, true ) ) ) { - return new \WP_Error( + return new WP_Error( 'author_url_not_accessible', \sprintf( // translators: %s: Author URL @@ -196,13 +250,13 @@ class Health_Check { /** * Check if WebFinger endpoint is accessible and profile request returns correct JSON * - * @return boolean|\WP_Error + * @return boolean|WP_Error */ public static function is_webfinger_endpoint_accessible() { $user = \wp_get_current_user(); - $account = \Activitypub\get_webfinger_resource( $user->ID ); + $account = get_webfinger_resource( $user->ID ); - $url = \Activitypub\Webfinger::resolve( $account ); + $url = Webfinger::resolve( $account ); if ( \is_wp_error( $url ) ) { $allowed = array( 'code' => array() ); $not_accessible = wp_kses( @@ -237,7 +291,7 @@ class Health_Check { if ( isset( $health_messages[ $url->get_error_code() ] ) ) { $message = $health_messages[ $url->get_error_code() ]; } - return new \WP_Error( + return new WP_Error( $url->get_error_code(), $message, $url->get_error_data() @@ -291,7 +345,7 @@ class Health_Check { 'fields' => array( 'webfinger' => array( 'label' => __( 'WebFinger Resource', 'activitypub' ), - 'value' => \Activitypub\Webfinger::get_user_resource( wp_get_current_user()->ID ), + 'value' => Webfinger::get_user_resource( wp_get_current_user()->ID ), 'private' => true, ), 'author_url' => array( @@ -299,6 +353,11 @@ class Health_Check { 'value' => get_author_posts_url( wp_get_current_user()->ID ), 'private' => true, ), + 'plugin_version' => array( + 'label' => __( 'Plugin Version', 'activitypub' ), + 'value' => get_plugin_version(), + 'private' => true, + ), ), ); diff --git a/includes/class-http.php b/includes/class-http.php index 5b741f4..f9140be 100644 --- a/includes/class-http.php +++ b/includes/class-http.php @@ -53,7 +53,7 @@ class Http { $code = \wp_remote_retrieve_response_code( $response ); if ( $code >= 400 ) { - $response = new WP_Error( $code, __( 'Failed HTTP Request', 'activitypub' ) ); + $response = new WP_Error( $code, __( 'Failed HTTP Request', 'activitypub' ), array( 'status' => $code ) ); } \do_action( 'activitypub_safe_remote_post_response', $response, $url, $body, $user_id ); @@ -101,7 +101,7 @@ class Http { $code = \wp_remote_retrieve_response_code( $response ); if ( $code >= 400 ) { - $response = new WP_Error( $code, __( 'Failed HTTP Request', 'activitypub' ) ); + $response = new WP_Error( $code, __( 'Failed HTTP Request', 'activitypub' ), array( 'status' => $code ) ); } \do_action( 'activitypub_safe_remote_get_response', $response, $url ); diff --git a/includes/class-mention.php b/includes/class-mention.php index d6c4bbb..4aedfb0 100644 --- a/includes/class-mention.php +++ b/includes/class-mention.php @@ -25,43 +25,56 @@ class Mention { * @return string the filtered post-content */ public static function the_content( $the_content ) { - $protected_tags = array(); - $protect = function( $m ) use ( &$protected_tags ) { - $c = \wp_rand( 100000, 999999 ); - $protect = '!#!#PROTECT' . $c . '#!#!'; - while ( isset( $protected_tags[ $protect ] ) ) { - $c = \wp_rand( 100000, 999999 ); - $protect = '!#!#PROTECT' . $c . '#!#!'; + $tag_stack = array(); + $protected_tags = array( + 'pre', + 'code', + 'textarea', + 'style', + 'a', + ); + $content_with_links = ''; + $in_protected_tag = false; + foreach ( wp_html_split( $the_content ) as $chunk ) { + if ( preg_match( '#^$#i', $chunk, $m ) ) { + $content_with_links .= $chunk; + continue; } - $protected_tags[ $protect ] = $m[0]; - return $protect; - }; - $the_content = preg_replace_callback( - '##is', - $protect, - $the_content - ); - $the_content = preg_replace_callback( - '#<(pre|code|textarea|style)\b[^>]*>.*?]*>#is', - $protect, - $the_content - ); - $the_content = preg_replace_callback( - '#]+>.*?#i', - $protect, - $the_content - ); - $the_content = preg_replace_callback( - '#]+>#i', - $protect, - $the_content - ); + if ( preg_match( '#^<(/)?([a-z-]+)\b[^>]*>$#i', $chunk, $m ) ) { + $tag = strtolower( $m[2] ); + if ( '/' === $m[1] ) { + // Closing tag. + $i = array_search( $tag, $tag_stack ); + // We can only remove the tag from the stack if it is in the stack. + if ( false !== $i ) { + $tag_stack = array_slice( $tag_stack, 0, $i ); + } + } else { + // Opening tag, add it to the stack. + $tag_stack[] = $tag; + } - $the_content = \preg_replace_callback( '/@' . ACTIVITYPUB_USERNAME_REGEXP . '/', array( self::class, 'replace_with_links' ), $the_content ); - $the_content = \str_replace( array_reverse( array_keys( $protected_tags ) ), array_reverse( array_values( $protected_tags ) ), $the_content ); + // If we're in a protected tag, the tag_stack contains at least one protected tag string. + // The protected tag state can only change when we encounter a start or end tag. + $in_protected_tag = array_intersect( $tag_stack, $protected_tags ); - return $the_content; + // Never inspect tags. + $content_with_links .= $chunk; + continue; + } + + if ( $in_protected_tag ) { + // Don't inspect a chunk inside an inspected tag. + $content_with_links .= $chunk; + continue; + } + + // Only reachable when there is no protected tag in the stack. + $content_with_links .= \preg_replace_callback( '/@' . ACTIVITYPUB_USERNAME_REGEXP . '/', array( self::class, 'replace_with_links' ), $chunk ); + } + + return $content_with_links; } /** @@ -74,7 +87,7 @@ class Mention { public static function replace_with_links( $result ) { $metadata = get_remote_metadata_by_actor( $result[0] ); - if ( ! is_wp_error( $metadata ) && ! empty( $metadata['url'] ) ) { + if ( ! empty( $metadata ) && ! is_wp_error( $metadata ) && ! empty( $metadata['url'] ) ) { $username = ltrim( $result[0], '@' ); if ( ! empty( $metadata['name'] ) ) { $username = $metadata['name']; diff --git a/includes/class-scheduler.php b/includes/class-scheduler.php index b3eca5d..63f9273 100644 --- a/includes/class-scheduler.php +++ b/includes/class-scheduler.php @@ -105,10 +105,16 @@ class Scheduler { * @return void */ public static function update_followers() { - $followers = Followers::get_outdated_followers(); + $number = 5; + + if ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ) { + $number = 50; + } + + $followers = Followers::get_outdated_followers( $number ); foreach ( $followers as $follower ) { - $meta = get_remote_metadata_by_actor( $follower->get_url(), true ); + $meta = get_remote_metadata_by_actor( $follower->get_url(), false ); if ( empty( $meta ) || ! is_array( $meta ) || is_wp_error( $meta ) ) { Followers::add_error( $follower->get__id(), $meta ); @@ -125,10 +131,16 @@ class Scheduler { * @return void */ public static function cleanup_followers() { - $followers = Followers::get_faulty_followers(); + $number = 5; + + if ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ) { + $number = 50; + } + + $followers = Followers::get_faulty_followers( $number ); foreach ( $followers as $follower ) { - $meta = get_remote_metadata_by_actor( $follower->get_url(), true ); + $meta = get_remote_metadata_by_actor( $follower->get_url(), false ); if ( is_tombstone( $meta ) ) { $follower->delete(); diff --git a/includes/class-shortcodes.php b/includes/class-shortcodes.php index d1c71f5..43be17b 100644 --- a/includes/class-shortcodes.php +++ b/includes/class-shortcodes.php @@ -46,7 +46,7 @@ class Shortcodes { foreach ( $tags as $tag ) { $hash_tags[] = \sprintf( - '', + '', \esc_url( \get_tag_link( $tag ) ), esc_hashtag( $tag->name ) ); @@ -114,7 +114,7 @@ class Shortcodes { /** This filter is documented in wp-includes/post-template.php */ $excerpt = \apply_filters( 'the_content', $excerpt ); - $excerpt = \str_replace( ']]>', ']]>', $excerpt ); + $excerpt = \str_replace( ']]>', ']]>', $excerpt ); } } @@ -359,7 +359,7 @@ class Shortcodes { foreach ( $categories as $category ) { $hash_tags[] = \sprintf( - '', + '', \esc_url( \get_category_link( $category ) ), esc_hashtag( $category->name ) ); diff --git a/includes/class-signature.php b/includes/class-signature.php index 5ae37a9..1789dd6 100644 --- a/includes/class-signature.php +++ b/includes/class-signature.php @@ -4,7 +4,6 @@ namespace Activitypub; use WP_Error; use DateTime; use DateTimeZone; -use Activitypub\Model\User; use Activitypub\Collection\Users; /** @@ -23,22 +22,14 @@ class Signature { * * @return mixed The public key. */ - public static function get_public_key( $user_id, $force = false ) { + public static function get_public_key_for( $user_id, $force = false ) { if ( $force ) { - self::generate_key_pair( $user_id ); + self::generate_key_pair_for( $user_id ); } - if ( User::APPLICATION_USER_ID === $user_id ) { - $key = \get_option( 'activitypub_magic_sig_public_key' ); - } else { - $key = \get_user_meta( $user_id, 'magic_sig_public_key', true ); - } + $key_pair = self::get_keypair_for( $user_id ); - if ( ! $key ) { - return self::get_public_key( $user_id, true ); - } - - return $key; + return $key_pair['public_key']; } /** @@ -49,22 +40,32 @@ class Signature { * * @return mixed The private key. */ - public static function get_private_key( $user_id, $force = false ) { + public static function get_private_key_for( $user_id, $force = false ) { if ( $force ) { - self::generate_key_pair( $user_id ); + self::generate_key_pair_for( $user_id ); } - if ( User::APPLICATION_USER_ID === $user_id ) { - $key = \get_option( 'activitypub_magic_sig_private_key' ); - } else { - $key = \get_user_meta( $user_id, 'magic_sig_private_key', true ); + $key_pair = self::get_keypair_for( $user_id ); + + return $key_pair['private_key']; + } + + /** + * Return the key pair for a given user. + * + * @param int $user_id The WordPress User ID. + * + * @return array The key pair. + */ + public static function get_keypair_for( $user_id ) { + $option_key = self::get_signature_options_key_for( $user_id ); + $key_pair = \get_option( $option_key ); + + if ( ! $key_pair ) { + $key_pair = self::generate_key_pair_for( $user_id ); } - if ( ! $key ) { - return self::get_private_key( $user_id, true ); - } - - return $key; + return $key_pair; } /** @@ -72,9 +73,18 @@ class Signature { * * @param int $user_id The WordPress User ID. * - * @return void + * @return array The key pair. */ - public static function generate_key_pair() { + protected static function generate_key_pair_for( $user_id ) { + $option_key = self::get_signature_options_key_for( $user_id ); + $key_pair = self::check_legacy_key_pair_for( $user_id ); + + if ( $key_pair ) { + \add_option( $option_key, $key_pair ); + + return $key_pair; + } + $config = array( 'digest_alg' => 'sha512', 'private_key_bits' => 2048, @@ -88,10 +98,78 @@ class Signature { $detail = \openssl_pkey_get_details( $key ); - return array( + // check if keys are valid + if ( + empty( $priv_key ) || ! is_string( $priv_key ) || + ! isset( $detail['key'] ) || ! is_string( $detail['key'] ) + ) { + return array( + 'private_key' => null, + 'public_key' => null, + ); + } + + $key_pair = array( 'private_key' => $priv_key, 'public_key' => $detail['key'], ); + + // persist keys + \add_option( $option_key, $key_pair ); + + return $key_pair; + } + + /** + * Return the option key for a given user. + * + * @param int $user_id The WordPress User ID. + * + * @return string The option key. + */ + protected static function get_signature_options_key_for( $user_id ) { + $id = $user_id; + + if ( $user_id > 0 ) { + $user = \get_userdata( $user_id ); + // sanatize username because it could include spaces and special chars + $id = sanitize_title( $user->user_login ); + } + + return 'activitypub_keypair_for_' . $id; + } + + /** + * Check if there is a legacy key pair + * + * @param int $user_id The WordPress User ID. + * + * @return array|bool The key pair or false. + */ + protected static function check_legacy_key_pair_for( $user_id ) { + switch ( $user_id ) { + case 0: + $public_key = \get_option( 'activitypub_blog_user_public_key' ); + $private_key = \get_option( 'activitypub_blog_user_private_key' ); + break; + case -1: + $public_key = \get_option( 'activitypub_application_user_public_key' ); + $private_key = \get_option( 'activitypub_application_user_private_key' ); + break; + default: + $public_key = \get_user_meta( $user_id, 'magic_sig_public_key', true ); + $private_key = \get_user_meta( $user_id, 'magic_sig_private_key', true ); + break; + } + + if ( ! empty( $public_key ) && is_string( $public_key ) && ! empty( $private_key ) && is_string( $private_key ) ) { + return array( + 'private_key' => $private_key, + 'public_key' => $public_key, + ); + } + + return false; } /** @@ -107,7 +185,7 @@ class Signature { */ public static function generate_signature( $user_id, $http_method, $url, $date, $digest = null ) { $user = Users::get_by_id( $user_id ); - $key = $user->get__private_key(); + $key = self::get_private_key_for( $user->get__id() ); $url_parts = \wp_parse_url( $url ); @@ -136,7 +214,6 @@ class Signature { \openssl_sign( $signed_string, $signature, $key, \OPENSSL_ALGO_SHA256 ); $signature = \base64_encode( $signature ); // phpcs:ignore - $user = Users::get_by_id( $user_id ); $key_id = $user->get_url() . '#main-key'; if ( ! empty( $digest ) ) { @@ -161,28 +238,38 @@ class Signature { } else { $route = '/' . rest_get_url_prefix() . '/' . ltrim( $request->get_route(), '/' ); } + + // fix route for subdirectory installs + $path = \wp_parse_url( \get_home_url(), PHP_URL_PATH ); + + if ( \is_string( $path ) ) { + $path = trim( $path, '/' ); + } + + if ( $path ) { + $route = '/' . $path . $route; + } + $headers = $request->get_headers(); - $actor = isset( json_decode( $request->get_body() )->actor ) ? json_decode( $request->get_body() )->actor : ''; $headers['(request-target)'][0] = strtolower( $request->get_method() ) . ' ' . $route; } else { $request = self::format_server_request( $request ); $headers = $request['headers']; // $_SERVER array - $actor = null; $headers['(request-target)'][0] = strtolower( $headers['request_method'][0] ) . ' ' . $headers['request_uri'][0]; } if ( ! isset( $headers['signature'] ) ) { - return new WP_Error( 'activitypub_signature', 'Request not signed', array( 'status' => 403 ) ); + return new WP_Error( 'activitypub_signature', __( 'Request not signed', 'activitypub' ), array( 'status' => 403 ) ); } if ( array_key_exists( 'signature', $headers ) ) { - $signature_block = self::parse_signature_header( $headers['signature'] ); + $signature_block = self::parse_signature_header( $headers['signature'][0] ); } elseif ( array_key_exists( 'authorization', $headers ) ) { - $signature_block = self::parse_signature_header( $headers['authorization'] ); + $signature_block = self::parse_signature_header( $headers['authorization'][0] ); } if ( ! isset( $signature_block ) || ! $signature_block ) { - return new WP_Error( 'activitypub_signature', 'Incompatible request signature. keyId and signature are required', array( 'status' => 403 ) ); + return new WP_Error( 'activitypub_signature', __( 'Incompatible request signature. keyId and signature are required', 'activitypub' ), array( 'status' => 403 ) ); } $signed_headers = $signature_block['headers']; @@ -192,12 +279,12 @@ class Signature { $signed_data = self::get_signed_data( $signed_headers, $signature_block, $headers ); if ( ! $signed_data ) { - return new WP_Error( 'activitypub_signature', 'Signed request date outside acceptable time window', array( 'status' => 403 ) ); + return new WP_Error( 'activitypub_signature', __( 'Signed request date outside acceptable time window', 'activitypub' ), array( 'status' => 403 ) ); } $algorithm = self::get_signature_algorithm( $signature_block ); if ( ! $algorithm ) { - return new WP_Error( 'activitypub_signature', 'Unsupported signature algorithm (only rsa-sha256 and hs2019 are supported)', array( 'status' => 403 ) ); + return new WP_Error( 'activitypub_signature', __( 'Unsupported signature algorithm (only rsa-sha256 and hs2019 are supported)', 'activitypub' ), array( 'status' => 403 ) ); } if ( \in_array( 'digest', $signed_headers, true ) && isset( $body ) ) { @@ -213,15 +300,12 @@ class Signature { } if ( \base64_encode( \hash( $hashalg, $body, true ) ) !== $digest[1] ) { // phpcs:ignore - return new WP_Error( 'activitypub_signature', 'Invalid Digest header', array( 'status' => 403 ) ); + return new WP_Error( 'activitypub_signature', __( 'Invalid Digest header', 'activitypub' ), array( 'status' => 403 ) ); } } - if ( $actor ) { - $public_key = self::get_remote_key( $actor ); - } else { - $public_key = self::get_remote_key( $signature_block['keyId'] ); - } + $public_key = self::get_remote_key( $signature_block['keyId'] ); + if ( \is_wp_error( $public_key ) ) { return $public_key; } @@ -229,7 +313,7 @@ class Signature { $verified = \openssl_verify( $signed_data, $signature_block['signature'], $public_key, $algorithm ) > 0; if ( ! $verified ) { - return new WP_Error( 'activitypub_signature', 'Invalid signature', array( 'status' => 403 ) ); + return new WP_Error( 'activitypub_signature', __( 'Invalid signature', 'activitypub' ), array( 'status' => 403 ) ); } return $verified; } @@ -239,17 +323,17 @@ class Signature { * * @param string $key_id The URL to the public key. * - * @return string The public key. + * @return WP_Error|string The public key. */ public static function get_remote_key( $key_id ) { // phpcs:ignore - $actor = get_remote_metadata_by_actor( strtok( strip_fragment_from_url( $key_id ), '?' ) ); // phpcs:ignore + $actor = get_remote_metadata_by_actor( strip_fragment_from_url( $key_id ) ); // phpcs:ignore if ( \is_wp_error( $actor ) ) { return $actor; } if ( isset( $actor['publicKey']['publicKeyPem'] ) ) { return \rtrim( $actor['publicKey']['publicKeyPem'] ); // phpcs:ignore } - return null; + return new WP_Error( 'activitypub_no_remote_key_found', __( 'No Public-Key found', 'activitypub' ), array( 'status' => 403 ) ); } /** @@ -274,32 +358,31 @@ class Signature { /** * Parses the Signature header * - * @param array $header The signature header. + * @param string $signature The signature header. * * @return array signature parts */ - public static function parse_signature_header( $header ) { - $parsed_header = array(); - $matches = array(); - $h_string = \implode( ',', (array) $header[0] ); + public static function parse_signature_header( $signature ) { + $parsed_header = array(); + $matches = array(); - if ( \preg_match( '/keyId="(.*?)"/ism', $h_string, $matches ) ) { - $parsed_header['keyId'] = $matches[1]; + if ( \preg_match( '/keyId="(.*?)"/ism', $signature, $matches ) ) { + $parsed_header['keyId'] = trim( $matches[1] ); } - if ( \preg_match( '/created=([0-9]*)/ism', $h_string, $matches ) ) { - $parsed_header['(created)'] = $matches[1]; + if ( \preg_match( '/created=([0-9]*)/ism', $signature, $matches ) ) { + $parsed_header['(created)'] = trim( $matches[1] ); } - if ( \preg_match( '/expires=([0-9]*)/ism', $h_string, $matches ) ) { - $parsed_header['(expires)'] = $matches[1]; + if ( \preg_match( '/expires=([0-9]*)/ism', $signature, $matches ) ) { + $parsed_header['(expires)'] = trim( $matches[1] ); } - if ( \preg_match( '/algorithm="(.*?)"/ism', $h_string, $matches ) ) { - $parsed_header['algorithm'] = $matches[1]; + if ( \preg_match( '/algorithm="(.*?)"/ism', $signature, $matches ) ) { + $parsed_header['algorithm'] = trim( $matches[1] ); } - if ( \preg_match( '/headers="(.*?)"/ism', $h_string, $matches ) ) { - $parsed_header['headers'] = \explode( ' ', $matches[1] ); + if ( \preg_match( '/headers="(.*?)"/ism', $signature, $matches ) ) { + $parsed_header['headers'] = \explode( ' ', trim( $matches[1] ) ); } - if ( \preg_match( '/signature="(.*?)"/ism', $h_string, $matches ) ) { - $parsed_header['signature'] = \base64_decode( preg_replace( '/\s+/', '', $matches[1] ) ); // phpcs:ignore + if ( \preg_match( '/signature="(.*?)"/ism', $signature, $matches ) ) { + $parsed_header['signature'] = \base64_decode( preg_replace( '/\s+/', '', trim( $matches[1] ) ) ); // phpcs:ignore } if ( ( $parsed_header['signature'] ) && ( $parsed_header['algorithm'] ) && ( ! $parsed_header['headers'] ) ) { @@ -312,7 +395,7 @@ class Signature { /** * Gets the header data from the included pseudo headers * - * @param array $signed_headers + * @param array $signed_headers The signed headers. * @param array $signature_block (pseudo-headers) * @param array $headers (http headers) * diff --git a/includes/class-webfinger.php b/includes/class-webfinger.php index c077f12..b6b0a64 100644 --- a/includes/class-webfinger.php +++ b/includes/class-webfinger.php @@ -26,7 +26,7 @@ class Webfinger { } $user = Users::get_by_id( $user_id ); - if ( ! $user ) { + if ( ! $user || is_wp_error( $user ) ) { return ''; } @@ -63,7 +63,7 @@ class Webfinger { $url, array( 'headers' => array( 'Accept' => 'application/jrd+json' ), - 'redirection' => 0, + 'redirection' => 2, 'timeout' => 2, ) ); @@ -198,6 +198,6 @@ class Webfinger { } } - return new WP_Error( 'webfinger_remote_follow_endpoint_invalid', null, $data ); + return new WP_Error( 'webfinger_remote_follow_endpoint_invalid', $data, array( 'status' => 417 ) ); } } diff --git a/includes/collection/class-followers.php b/includes/collection/class-followers.php index baadf09..a9fe298 100644 --- a/includes/collection/class-followers.php +++ b/includes/collection/class-followers.php @@ -160,7 +160,7 @@ class Followers { * @param int $user_id The ID of the WordPress User * @param string $actor The Actor URL * - * @return array|WP_Error The Follower (WP_Term array) or an WP_Error + * @return array|WP_Error The Follower (WP_Post array) or an WP_Error */ public static function add_follower( $user_id, $actor ) { $meta = get_remote_metadata_by_actor( $actor ); @@ -169,29 +169,30 @@ class Followers { return $meta; } + if ( empty( $meta ) || ! is_array( $meta ) || is_wp_error( $meta ) ) { + return new WP_Error( 'activitypub_invalid_follower', __( 'Invalid Follower', 'activitypub' ), array( 'status' => 400 ) ); + } + $error = null; $follower = new Follower(); + $follower->from_array( $meta ); - if ( empty( $meta ) || ! is_array( $meta ) || is_wp_error( $meta ) ) { - $follower->set_id( $actor ); - $follower->set_url( $actor ); - $error = $meta; - } else { - $follower->from_array( $meta ); + $id = $follower->upsert(); + + if ( is_wp_error( $id ) ) { + return $id; } - $follower->upsert(); - - $meta = get_post_meta( $follower->get__id(), 'activitypub_user_id' ); + $meta = get_post_meta( $id, 'activitypub_user_id' ); if ( $error ) { - self::add_error( $follower->get__id(), $error ); + self::add_error( $id, $error ); } // phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict if ( is_array( $meta ) && ! in_array( $user_id, $meta ) ) { - add_post_meta( $follower->get__id(), 'activitypub_user_id', $user_id ); + add_post_meta( $id, 'activitypub_user_id', $user_id ); wp_cache_delete( sprintf( self::CACHE_KEY_INBOXES, $user_id ), 'activitypub' ); } @@ -360,7 +361,17 @@ class Followers { public static function get_all_followers() { $args = array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query - 'meta_query' => array(), + 'meta_query' => array( + 'relation' => 'AND', + array( + 'key' => 'activitypub_inbox', + 'compare' => 'EXISTS', + ), + array( + 'key' => 'activitypub_actor_json', + 'compare' => 'EXISTS', + ), + ), ); return self::get_followers( null, null, null, $args ); } @@ -379,10 +390,19 @@ class Followers { 'fields' => 'ids', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query 'meta_query' => array( + 'relation' => 'AND', array( 'key' => 'activitypub_user_id', 'value' => $user_id, ), + array( + 'key' => 'activitypub_inbox', + 'compare' => 'EXISTS', + ), + array( + 'key' => 'activitypub_actor_json', + 'compare' => 'EXISTS', + ), ), ) ); @@ -412,6 +432,7 @@ class Followers { 'fields' => 'ids', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query 'meta_query' => array( + 'relation' => 'AND', array( 'key' => 'activitypub_inbox', 'compare' => 'EXISTS', @@ -420,6 +441,11 @@ class Followers { 'key' => 'activitypub_user_id', 'value' => $user_id, ), + array( + 'key' => 'activitypub_inbox', + 'value' => '', + 'compare' => '!=', + ), ), ) ); @@ -462,7 +488,7 @@ class Followers { 'post_type' => self::POST_TYPE, 'posts_per_page' => $number, 'orderby' => 'modified', - 'order' => 'DESC', + 'order' => 'ASC', 'post_status' => 'any', // 'any' includes 'trash 'date_query' => array( array( @@ -490,16 +516,35 @@ class Followers { * * @return mixed The Term list of Followers, the format depends on $output. */ - public static function get_faulty_followers( $number = 10 ) { + public static function get_faulty_followers( $number = 20 ) { $args = array( 'post_type' => self::POST_TYPE, 'posts_per_page' => $number, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query 'meta_query' => array( + 'relation' => 'OR', array( 'key' => 'activitypub_errors', 'compare' => 'EXISTS', ), + array( + 'key' => 'activitypub_inbox', + 'compare' => 'NOT EXISTS', + ), + array( + 'key' => 'activitypub_actor_json', + 'compare' => 'NOT EXISTS', + ), + array( + 'key' => 'activitypub_inbox', + 'value' => '', + 'compare' => '=', + ), + array( + 'key' => 'activitypub_actor_json', + 'value' => '', + 'compare' => '=', + ), ), ); diff --git a/includes/functions.php b/includes/functions.php index ddf20ec..2edc31c 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -54,7 +54,7 @@ function get_remote_metadata_by_actor( $actor, $cached = true ) { } if ( ! $actor ) { - return null; + return new WP_Error( 'activitypub_no_valid_actor_identifier', \__( 'The "actor" identifier is not valid', 'activitypub' ), array( 'status' => 404, 'actor' => $actor ) ); } if ( is_wp_error( $actor ) ) { @@ -73,7 +73,7 @@ function get_remote_metadata_by_actor( $actor, $cached = true ) { } if ( ! \wp_http_validate_url( $actor ) ) { - $metadata = new \WP_Error( 'activitypub_no_valid_actor_url', \__( 'The "actor" is no valid URL', 'activitypub' ), $actor ); + $metadata = new WP_Error( 'activitypub_no_valid_actor_url', \__( 'The "actor" is no valid URL', 'activitypub' ), array( 'status' => 400, 'actor' => $actor ) ); \set_transient( $transient_key, $metadata, HOUR_IN_SECONDS ); // Cache the error for a shorter period. return $metadata; } @@ -95,7 +95,7 @@ function get_remote_metadata_by_actor( $actor, $cached = true ) { \set_transient( $transient_key, $metadata, WEEK_IN_SECONDS ); if ( ! $metadata ) { - $metadata = new \WP_Error( 'activitypub_invalid_json', \__( 'No valid JSON data', 'activitypub' ), $actor ); + $metadata = new WP_Error( 'activitypub_invalid_json', \__( 'No valid JSON data', 'activitypub' ), array( 'status' => 400, 'actor' => $actor ) ); \set_transient( $transient_key, $metadata, HOUR_IN_SECONDS ); // Cache the error for a shorter period. return $metadata; } @@ -680,7 +680,7 @@ function is_user_type_disabled( $type ) { $return = false; break; default: - $return = new WP_Error( 'activitypub_wrong_user_type', __( 'Wrong user type', 'activitypub' ) ); + $return = new WP_Error( 'activitypub_wrong_user_type', __( 'Wrong user type', 'activitypub' ), array( 'status' => 400 ) ); break; } @@ -693,20 +693,14 @@ function is_user_type_disabled( $type ) { * @return boolean True if the blog is in single-user mode, false otherwise. */ function is_single_user() { - $return = false; - - if ( \defined( 'ACTIVITYPUB_SINGLE_USER_MODE' ) ) { - if ( ACTIVITYPUB_SINGLE_USER_MODE ) { - $return = true; - } - } elseif ( + if ( false === is_user_type_disabled( 'blog' ) && true === is_user_type_disabled( 'user' ) ) { - $return = true; + return true; } - return $return; + return false; } if ( ! function_exists( 'get_self_link' ) ) { @@ -721,3 +715,33 @@ if ( ! function_exists( 'get_self_link' ) ) { return esc_url( apply_filters( 'self_link', set_url_scheme( 'http://' . $host['host'] . $path ) ) ); } } + +/** + * Check if a site supports the block editor. + * + * @return boolean True if the site supports the block editor, false otherwise. + */ +function site_supports_blocks() { + if ( ! \function_exists( 'register_block_type_from_metadata' ) ) { + return false; + } + + /** + * Allow plugins to disable block editor support, + * thus disabling blocks registered by the ActivityPub plugin. + * + * @param boolean $supports_blocks True if the site supports the block editor, false otherwise. + */ + return apply_filters( 'activitypub_site_supports_blocks', true ); +} + +/** + * Check if data is valid JSON. + * + * @param string $data The data to check. + * + * @return boolean True if the data is JSON, false otherwise. + */ +function is_json( $data ) { + return \is_array( \json_decode( $data, true ) ) ? true : false; +} diff --git a/includes/model/class-application-user.php b/includes/model/class-application-user.php index 2affde5..1cfcec0 100644 --- a/includes/model/class-application-user.php +++ b/includes/model/class-application-user.php @@ -22,6 +22,13 @@ class Application_User extends Blog_User { */ protected $type = 'Application'; + /** + * If the User is discoverable. + * + * @var boolean + */ + protected $discoverable = false; + /** * Get the User-Url. * @@ -35,58 +42,10 @@ class Application_User extends Blog_User { return 'application'; } - public function get_username() { + public function get_preferred_username() { return $this::get_name(); } - public function get__public_key() { - $key = \get_option( 'activitypub_application_user_public_key' ); - - if ( $key ) { - return $key; - } - - $this->generate_key_pair(); - - $key = \get_option( 'activitypub_application_user_public_key' ); - - return $key; - } - - /** - * @param int $user_id - * - * @return mixed - */ - public function get__private_key() { - $key = \get_option( 'activitypub_application_user_private_key' ); - - if ( $key ) { - return $key; - } - - $this->generate_key_pair(); - - return \get_option( 'activitypub_application_user_private_key' ); - } - - private function generate_key_pair() { - $key_pair = Signature::generate_key_pair(); - - if ( ! is_wp_error( $key_pair ) ) { - \update_option( 'activitypub_application_user_public_key', $key_pair['public_key'] ); - \update_option( 'activitypub_application_user_private_key', $key_pair['private_key'] ); - } - } - - public function get_inbox() { - return null; - } - - public function get_outbox() { - return null; - } - public function get_followers() { return null; } @@ -96,14 +55,18 @@ class Application_User extends Blog_User { } public function get_attachment() { - return array(); + return null; } public function get_featured_tags() { - return array(); + return null; } public function get_featured() { - return array(); + return null; + } + + public function get_moderators() { + return null; } } diff --git a/includes/model/class-blog-user.php b/includes/model/class-blog-user.php index 8de46df..062b616 100644 --- a/includes/model/class-blog-user.php +++ b/includes/model/class-blog-user.php @@ -7,6 +7,7 @@ use Activitypub\Collection\Users; use function Activitypub\is_single_user; use function Activitypub\is_user_disabled; +use function Activitypub\get_rest_url_by_path; class Blog_User extends User { /** @@ -21,7 +22,7 @@ class Blog_User extends User { * * @var string */ - protected $type = 'Group'; + protected $type = null; /** * Is Account discoverable? @@ -45,6 +46,21 @@ class Blog_User extends User { return $object; } + /** + * Get the type of the object. + * + * If the Blog is in "single user" mode, return "Person" insted of "Group". + * + * @return string The type of the object. + */ + public function get_type() { + if ( is_single_user() ) { + return 'Person'; + } else { + return 'Group'; + } + } + /** * Get the User-Name. * @@ -122,23 +138,34 @@ class Blog_User extends User { /** * Get the User-Icon. * - * @return array|null The User-Icon. + * @return array The User-Icon. */ public function get_icon() { // try site icon first $icon_id = get_option( 'site_icon' ); + // try custom logo second if ( ! $icon_id ) { $icon_id = get_theme_mod( 'custom_logo' ); } - if ( ! $icon_id ) { - return null; + + $icon_url = false; + + if ( $icon_id ) { + $icon = wp_get_attachment_image_src( $icon_id, 'full' ); + if ( $icon ) { + $icon_url = $icon[0]; + } + } + + if ( ! $icon_url ) { + // fallback to default icon + $icon_url = plugins_url( '/assets/img/wp-logo.png', ACTIVITYPUB_PLUGIN_FILE ); } - $image = wp_get_attachment_image_src( $icon_id, 'full' ); return array( 'type' => 'Image', - 'url' => esc_url( $image[0] ), + 'url' => esc_url( $icon_url ), ); } @@ -176,48 +203,6 @@ class Blog_User extends User { return \gmdate( 'Y-m-d\TH:i:s\Z', $time ); } - public function get__public_key() { - $key = \get_option( 'activitypub_blog_user_public_key' ); - - if ( $key ) { - return $key; - } - - $this->generate_key_pair(); - - $key = \get_option( 'activitypub_blog_user_public_key' ); - - return $key; - } - - /** - * Get the User-Private-Key. - * - * @param int $user_id - * - * @return mixed - */ - public function get__private_key() { - $key = \get_option( 'activitypub_blog_user_private_key' ); - - if ( $key ) { - return $key; - } - - $this->generate_key_pair(); - - return \get_option( 'activitypub_blog_user_private_key' ); - } - - private function generate_key_pair() { - $key_pair = Signature::generate_key_pair(); - - if ( ! is_wp_error( $key_pair ) ) { - \update_option( 'activitypub_blog_user_public_key', $key_pair['public_key'] ); - \update_option( 'activitypub_blog_user_private_key', $key_pair['private_key'] ); - } - } - public function get_attachment() { return array(); } @@ -226,18 +211,27 @@ class Blog_User extends User { return \home_url(); } - /** - * Get the type of the object. - * - * If the Blog is in "single user" mode, return "Person" insted of "Group". - * - * @return string The type of the object. - */ - public function get_type() { - if ( is_single_user() ) { - return 'Person'; - } else { - return $this->type; + public function get_moderators() { + if ( is_single_user() || 'Group' !== $this->get_type() ) { + return null; } + + return get_rest_url_by_path( 'collections/moderators' ); + } + + public function get_attributed_to() { + if ( is_single_user() || 'Group' !== $this->get_type() ) { + return null; + } + + return get_rest_url_by_path( 'collections/moderators' ); + } + + public function get_posting_restricted_to_mods() { + if ( 'Group' === $this->get_type() ) { + return true; + } + + return null; } } diff --git a/includes/model/class-follower.php b/includes/model/class-follower.php index 0993170..7cf6dd4 100644 --- a/includes/model/class-follower.php +++ b/includes/model/class-follower.php @@ -1,6 +1,7 @@ save(); } + /** + * Validate the current Follower-Object. + * + * @return boolean True if the verification was successful. + */ + public function is_valid() { + // the minimum required attributes + $required_attributes = array( + 'id', + 'preferredUsername', + 'inbox', + 'publicKey', + 'publicKeyPem', + ); + + foreach ( $required_attributes as $attribute ) { + if ( ! $this->get( $attribute ) ) { + return false; + } + } + + return true; + } + /** * Save the current Follower-Object. * - * @return void + * @return int|WP_Error The Post-ID or an WP_Error. */ public function save() { + if ( ! $this->is_valid() ) { + return new WP_Error( 'activitypub_invalid_follower', __( 'Invalid Follower', 'activitypub' ), array( 'status' => 400 ) ); + } + if ( ! $this->get__id() ) { global $wpdb; @@ -147,15 +176,17 @@ class Follower extends Actor { $post_id = wp_insert_post( $args ); $this->_id = $post_id; + + return $post_id; } /** * Upsert the current Follower-Object. * - * @return void + * @return int|WP_Error The Post-ID or an WP_Error. */ public function upsert() { - $this->save(); + return $this->save(); } /** diff --git a/includes/model/class-user.php b/includes/model/class-user.php index 12fbb67..f62772d 100644 --- a/includes/model/class-user.php +++ b/includes/model/class-user.php @@ -36,6 +36,15 @@ class User extends Actor { */ protected $featured; + /** + * Moderators endpoint. + * + * @see https://join-lemmy.org/docs/contributors/05-federation.html + * + * @var string + */ + protected $moderators; + /** * The User-Type * @@ -43,6 +52,38 @@ class User extends Actor { */ protected $type = 'Person'; + /** + * If the User is discoverable. + * + * @see https://docs.joinmastodon.org/spec/activitypub/#discoverable + * + * @var boolean + */ + protected $discoverable = true; + + /** + * If the User is indexable. + * + * @var boolean + */ + protected $indexable; + + /** + * The WebFinger Resource. + * + * @var string + */ + protected $resource; + + /** + * Restrict posting to mods + * + * @see https://join-lemmy.org/docs/contributors/05-federation.html + * + * @var boolean + */ + protected $posting_restricted_to_mods = null; + public static function from_wp_user( $user_id ) { if ( is_user_disabled( $user_id ) ) { return new WP_Error( @@ -145,53 +186,10 @@ class User extends Actor { return array( 'id' => $this->get_id() . '#main-key', 'owner' => $this->get_id(), - 'publicKeyPem' => $this->get__public_key(), + 'publicKeyPem' => Signature::get_public_key_for( $this->get__id() ), ); } - /** - * @param int $this->get__id() - * - * @return mixed - */ - public function get__public_key() { - $key = \get_user_meta( $this->get__id(), 'magic_sig_public_key', true ); - - if ( $key ) { - return $key; - } - - $this->generate_key_pair(); - - return \get_user_meta( $this->get__id(), 'magic_sig_public_key', true ); - } - - /** - * @param int $this->get__id() - * - * @return mixed - */ - public function get__private_key() { - $key = \get_user_meta( $this->get__id(), 'magic_sig_private_key', true ); - - if ( $key ) { - return $key; - } - - $this->generate_key_pair(); - - return \get_user_meta( $this->get__id(), 'magic_sig_private_key', true ); - } - - private function generate_key_pair() { - $key_pair = Signature::generate_key_pair(); - - if ( ! is_wp_error( $key_pair ) ) { - \update_user_meta( $this->get__id(), 'magic_sig_public_key', $key_pair['public_key'], true ); - \update_user_meta( $this->get__id(), 'magic_sig_private_key', $key_pair['private_key'], true ); - } - } - /** * Returns the Inbox-API-Endpoint. * @@ -301,4 +299,20 @@ class User extends Actor { public function get_canonical_url() { return $this->get_url(); } + + public function get_streams() { + return null; + } + + public function get_tag() { + return array(); + } + + public function get_indexable() { + if ( \get_option( 'blog_public', 1 ) ) { + return true; + } else { + return false; + } + } } diff --git a/includes/rest/class-collection.php b/includes/rest/class-collection.php index b29a090..9e50835 100644 --- a/includes/rest/class-collection.php +++ b/includes/rest/class-collection.php @@ -1,6 +1,7 @@ WP_REST_Server::READABLE, + 'callback' => array( self::class, 'moderators_get' ), + 'permission_callback' => '__return_true', + ), + ) + ); } /** @@ -158,6 +171,30 @@ class Collection { return new WP_REST_Response( $response, 200 ); } + /** + * Moderators endpoint + * + * @param WP_REST_Request $request The request object. + * + * @return WP_REST_Response The response object. + */ + public static function moderators_get( $request ) { + $response = array( + '@context' => Activity::CONTEXT, + 'id' => get_rest_url_by_path( 'collections/moderators' ), + 'type' => 'OrderedCollection', + 'orderedItems' => array(), + ); + + $users = User_Collection::get_collection(); + + foreach ( $users as $user ) { + $response['orderedItems'][] = $user->get_url(); + } + + return new WP_REST_Response( $response, 200 ); + } + /** * The supported parameters * diff --git a/includes/rest/class-inbox.php b/includes/rest/class-inbox.php index b5f012b..477cef7 100644 --- a/includes/rest/class-inbox.php +++ b/includes/rest/class-inbox.php @@ -131,7 +131,7 @@ class Inbox { return $user; } - $data = $request->get_params(); + $data = $request->get_json_params(); $type = $request->get_param( 'type' ); $type = \strtolower( $type ); @@ -149,7 +149,7 @@ class Inbox { * @return WP_REST_Response */ public static function shared_inbox_post( $request ) { - $data = $request->get_params(); + $data = $request->get_json_params(); $type = $request->get_param( 'type' ); $users = self::extract_recipients( $data ); @@ -171,6 +171,12 @@ class Inbox { } foreach ( $users as $user ) { + $user = User_Collection::get_by_various( $user ); + + if ( is_wp_error( $user ) ) { + continue; + } + $type = \strtolower( $type ); \do_action( 'activitypub_inbox', $data, $user->ID, $type ); @@ -325,61 +331,6 @@ class Inbox { return $params; } - /** - * Handles "Reaction" requests - * - * @param array $object The activity-object - * @param int $user_id The id of the local blog-user - */ - public static function handle_reaction( $object, $user_id ) { - $meta = get_remote_metadata_by_actor( $object['actor'] ); - - $comment_post_id = \url_to_postid( $object['object'] ); - - // save only replys and reactions - if ( ! $comment_post_id ) { - return false; - } - - $commentdata = array( - 'comment_post_ID' => $comment_post_id, - 'comment_author' => \esc_attr( $meta['name'] ), - 'comment_author_email' => '', - 'comment_author_url' => \esc_url_raw( $object['actor'] ), - 'comment_content' => \esc_url_raw( $object['actor'] ), - 'comment_type' => \esc_attr( \strtolower( $object['type'] ) ), - 'comment_parent' => 0, - 'comment_meta' => array( - 'source_url' => \esc_url_raw( $object['id'] ), - 'avatar_url' => \esc_url_raw( $meta['icon']['url'] ), - 'protocol' => 'activitypub', - ), - ); - - // disable flood control - \remove_action( 'check_comment_flood', 'check_comment_flood_db', 10 ); - - // do not require email for AP entries - \add_filter( 'pre_option_require_name_email', '__return_false' ); - - // No nonce possible for this submission route - \add_filter( - 'akismet_comment_nonce', - function() { - return 'inactive'; - } - ); - - $state = \wp_new_comment( $commentdata, true ); - - \remove_filter( 'pre_option_require_name_email', '__return_false' ); - - // re-add flood control - \add_action( 'check_comment_flood', 'check_comment_flood_db', 10, 4 ); - - do_action( 'activitypub_handled_reaction', $object, $user_id, $state, $commentdata ); - } - /** * Converts a new ActivityPub object to comment data suitable for creating a comment * @@ -387,9 +338,10 @@ class Inbox { * * @return array Comment data suitable for creating a comment. */ - public static function convert_object_to_comment_data( $object ) { - if ( ! isset( $object['object'] ) ) { - return false; + public static function convert_object_to_comment_data( $object, $user_id ) { + + if ( ! isset( $object['object']['inReplyTo'] ) ) { + return; } // check if Activity is public or not diff --git a/includes/rest/class-server.php b/includes/rest/class-server.php index 325b9ad..01d9a9a 100644 --- a/includes/rest/class-server.php +++ b/includes/rest/class-server.php @@ -46,6 +46,11 @@ class Server { */ public static function application_actor() { $user = new Application_User(); + + $user->set_context( + \Activitypub\Activity\Activity::CONTEXT + ); + $json = $user->to_array(); $response = new WP_REST_Response( $json, 200 ); @@ -80,12 +85,12 @@ class Server { } // POST-Requets are always signed - if ( 'POST' === $request->get_method() ) { + if ( 'post' === \strtolower( $request->get_method() ) ) { $verified_request = Signature::verify_http_signature( $request ); if ( \is_wp_error( $verified_request ) ) { return $verified_request; } - } elseif ( 'GET' === $request->get_method() ) { // GET-Requests are only signed in secure mode + } elseif ( 'get' === \strtolower( $request->get_method() ) ) { // GET-Requests are only signed in secure mode if ( ACTIVITYPUB_AUTHORIZED_FETCH ) { $verified_request = Signature::verify_http_signature( $request ); if ( \is_wp_error( $verified_request ) ) { diff --git a/includes/transformer/class-post.php b/includes/transformer/class-post.php index cc8a1c6..286b91f 100644 --- a/includes/transformer/class-post.php +++ b/includes/transformer/class-post.php @@ -9,6 +9,7 @@ use Activitypub\Activity\Base_Object; use function Activitypub\esc_hashtag; use function Activitypub\is_single_user; use function Activitypub\get_rest_url_by_path; +use function Activitypub\site_supports_blocks; /** * WordPress Post Transformer @@ -114,8 +115,8 @@ class Post { $wp_post = $this->wp_post; $object = new Base_Object(); - $object->set_id( \esc_url( \get_permalink( $wp_post->ID ) ) ); - $object->set_url( \esc_url( \get_permalink( $wp_post->ID ) ) ); + $object->set_id( $this->get_id() ); + $object->set_url( $this->get_url() ); $object->set_type( $this->get_object_type() ); $published = \strtotime( $wp_post->post_date_gmt ); @@ -150,6 +151,32 @@ class Post { return $object; } + /** + * Returns the ID of the Post. + * + * @return string The Posts ID. + */ + public function get_id() { + return $this->get_url(); + } + + /** + * Returns the URL of the Post. + * + * @return string The Posts URL. + */ + public function get_url() { + $post = $this->wp_post; + + if ( 'trash' === get_post_status( $post ) ) { + $permalink = \get_post_meta( $post->ID, 'activitypub_canonical_url', true ); + } else { + $permalink = \get_permalink( $post ); + } + + return \esc_url( $permalink ); + } + /** * Returns the User-URL of the Author of the Post. * @@ -166,6 +193,66 @@ class Post { return Users::get_by_id( $this->wp_post->post_author )->get_url(); } + /** + * Returns the Image Attachments for this Post, parsed from blocks. + * @param int $max_images The maximum number of images to return. + * @param array $image_ids The image IDs to append new IDs to. + * + * @return array The image IDs. + */ + protected function get_block_image_ids( $max_images, $image_ids = [] ) { + $blocks = \parse_blocks( $this->wp_post->post_content ); + return self::get_image_ids_from_blocks( $blocks, $image_ids, $max_images ); + } + + /** + * Recursively get image IDs from blocks. + * @param array $blocks The blocks to search for image IDs + * @param array $image_ids The image IDs to append new IDs to + * @param int $max_images The maximum number of images to return. + * + * @return array The image IDs. + */ + protected static function get_image_ids_from_blocks( $blocks, $image_ids, $max_images ) { + foreach ( $blocks as $block ) { + // recurse into inner blocks + if ( ! empty( $block['innerBlocks'] ) ) { + $image_ids = self::get_image_ids_from_blocks( $block['innerBlocks'], $image_ids, $max_images ); + } + + switch ( $block['blockName'] ) { + case 'core/image': + case 'core/cover': + if ( ! empty( $block['attrs']['id'] ) ) { + $image_ids[] = $block['attrs']['id']; + } + break; + case 'jetpack/slideshow': + case 'jetpack/tiled-gallery': + if ( ! empty( $block['attrs']['ids'] ) ) { + $image_ids = array_merge( $image_ids, $block['attrs']['ids'] ); + } + break; + case 'jetpack/image-compare': + if ( ! empty( $block['attrs']['beforeImageId'] ) ) { + $image_ids[] = $block['attrs']['beforeImageId']; + } + if ( ! empty( $block['attrs']['afterImageId'] ) ) { + $image_ids[] = $block['attrs']['afterImageId']; + } + break; + } + + // we could be at or over max, stop unneeded work + if ( count( $image_ids ) >= $max_images ) { + break; + } + } + + // still need to slice it because one gallery could knock us over the limit + return \array_slice( $image_ids, 0, $max_images ); + } + /** * Generates all Image Attachments for a Post. * @@ -192,21 +279,26 @@ class Post { } if ( $max_images > 0 ) { - // then list any image attachments - $query = new \WP_Query( - array( - 'post_parent' => $id, - 'post_status' => 'inherit', - 'post_type' => 'attachment', - 'post_mime_type' => 'image', - 'order' => 'ASC', - 'orderby' => 'menu_order ID', - 'posts_per_page' => $max_images, - ) - ); - foreach ( $query->get_posts() as $attachment ) { - if ( ! \in_array( $attachment->ID, $image_ids, true ) ) { - $image_ids[] = $attachment->ID; + // first try to get images that are actually in the post content + if ( site_supports_blocks() && \has_blocks( $this->wp_post->post_content ) ) { + $image_ids = $this->get_block_image_ids( $max_images, $image_ids ); + } else { + // fallback to images attached to the post + $query = new \WP_Query( + array( + 'post_parent' => $id, + 'post_status' => 'inherit', + 'post_type' => 'attachment', + 'post_mime_type' => 'image', + 'order' => 'ASC', + 'orderby' => 'menu_order ID', + 'posts_per_page' => $max_images, + ) + ); + foreach ( $query->get_posts() as $attachment ) { + if ( ! \in_array( $attachment->ID, $image_ids, true ) ) { + $image_ids[] = $attachment->ID; + } } } } @@ -275,7 +367,7 @@ class Post { * @param int $id The attachment ID. * @param string $image_size The image size to retrieve. Set to 'full' by default. */ - do_action( 'activitypub_get_image_pre', $id, $image_size ); + do_action( 'activitypub_get_image_post', $id, $image_size ); return $thumbnail; } @@ -357,7 +449,7 @@ class Post { $mentions = $this->get_mentions(); if ( $mentions ) { - foreach ( $mentions as $mention => $url ) { + foreach ( $mentions as $url ) { $cc[] = $url; } } @@ -447,7 +539,7 @@ class Post { } if ( 'content' === \get_option( 'activitypub_post_content_type', 'content' ) ) { - return "[ap_content]\n\n[ap_hashtags]\n\n[ap_permalink type=\"html\"]"; + return "[ap_content]\n\n[ap_permalink type=\"html\"]\n\n[ap_hashtags]"; } return \get_option( 'activitypub_custom_post_content', ACTIVITYPUB_CUSTOM_POST_CONTENT ); diff --git a/package.json b/package.json index 17006ea..d216407 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,8 @@ }, "scripts": { "dev": "wp-scripts start", - "build": "wp-scripts build" + "build": "wp-scripts build", + "readme": "grunt wp_readme_to_markdown" }, "license": "MIT", "bugs": { diff --git a/phpcs.xml b/phpcs.xml index ad12dbd..fabb43e 100644 --- a/phpcs.xml +++ b/phpcs.xml @@ -13,6 +13,7 @@ + diff --git a/readme.txt b/readme.txt index a09b750..90e0011 100644 --- a/readme.txt +++ b/readme.txt @@ -1,9 +1,9 @@ === ActivityPub === -Contributors: automattic, pfefferle, mediaformat, mattwiebe, akirk, jeherve, nuriapena +Contributors: automattic, pfefferle, mediaformat, mattwiebe, akirk, jeherve, nuriapena, cavalierlife Tags: OStatus, fediverse, activitypub, activitystream Requires at least: 4.7 Tested up to: 6.3 -Stable tag: 1.0.0 +Stable tag: 1.0.1 Requires PHP: 5.6 License: MIT License URI: http://opensource.org/licenses/MIT @@ -12,39 +12,39 @@ The ActivityPub protocol is a decentralized social networking protocol based upo == Description == -This is BETA software, see the FAQ to see the current feature set or rather what is still planned. +Enter the fediverse with **ActivityPub**, broadcasting your blog to a wider audience! Attract followers, deliver updates, and receive comments from a diverse user base of **ActivityPub**\-compliant platforms. -The plugin implements the ActivityPub protocol for your blog, which means that your readers will be able to follow your blog posts on Mastodon and other federated platforms that support ActivityPub. In addition, replies to your posts on Mastodon and related platforms will automatically become comments on your blog post. +With the ActivityPub plugin installed, your WordPress blog itself function as a federated profile, along with profiles for each author. For instance, if your website is `example.com`, then the blog-wide profile can be found at `@example.com@example.com`, and authors like Jane and Bob would have their individual profiles at `@jane@example.com` and `@bobz@example.com`, respectively. + +An example: I give you my Mastodon profile name: `@pfefferle@mastodon.social`. You search, see my profile, and hit follow. Now, any post I make appears in your Home feed. Similarly, with the ActivityPub plugin, you can find and follow Jane's profile at `@jane@example.com`. + +Once you follow Jane's `@jane@example.com` profile, any blog post she crafts on `example.com` will land in your Home feed. Simultaneously, by following the blog-wide profile `@example.com@example.com`, you'll receive updates from all authors. + +**Note**: if no one follows your author or blog instance, your posts remain unseen. The simplest method to verify the plugin's operation is by following your profile. If you possess a Mastodon profile, initiate by following your new one. The plugin works with the following tested federated platforms, but there may be more that it works with as well: * [Mastodon](https://joinmastodon.org/) -* [Pleroma](https://pleroma.social/) +* [Pleroma](https://pleroma.social/)/[Akkoma](https://akkoma.social/) * [friendica](https://friendi.ca/) * [Hubzilla](https://hubzilla.org/) * [Pixelfed](https://pixelfed.org/) * [Socialhome](https://socialhome.network/) * [Misskey](https://join.misskey.page/) -* [Calckey](https://calckey.org/) - -Here’s what that means and what you can expect. - -Once the ActivityPub plugin is installed, each author’s page on your WordPress blog will become its own federated instance. In other words, if you have two authors, Jane and Bob, on your website, `example.com`, then your authors would have their own author pages at `example.com/author/jane` and `example.com/author/bob`. Each of those author pages would now be available to Mastodon users (and all other federated platform users) as a profile that can be followed. Let’s break that down further. Let’s say you have a friend on Mastodon who tells you to follow them and they give you their profile name `@janelivesheresomeofthetime@mastodon.social`. You search for her name, see her profile, and click the follow button, right? From then on, everything Jane posts on her profile shows up in your Home feed. Okay, similarly, now that Jane has installed the ActivityPub plugin on her `example.com` site, her friends can also follow her on Mastodon by searching for `@jane@example.com` and clicking the Follow button on that profile. - -From now on, every blog post Jane publishes on example.com will show up on your Home feed because you follow her `@jane@example.com` profile. -Of course, if no one follows your author instance, then no one will ever see the posts - including you! So the easiest way to even know if the plugin is working is to follow your new profile yourself. If you already have a Mastodon profile, just follow your new one from there. +* [Firefish](https://joinfirefish.org/) (rebrand of Calckey) Some things to note: -1. Many single-author blogs have chosen to turn off or redirect their author profile pages, usually via an SEO plugin like Yoast or Rank Math. This is usually done to avoid duplicate content with your blog’s home page. If your author page has been deactivated in this way, then ActivityPub won’t work for you. Instead, you can turn your author profile page back on, and then use the option in your SEO plugin to noindex the author page. This will enable the page to be live and ActivityPub will now work, but the live page won’t cause any duplicate content issues with search engines. -1. Once ActivityPub is installed, only new posts going forward will be available in the fediverse. Likewise, even if you’ve been using ActivityPub for a while, anyone who follows your site, will only see new posts you publish from that moment on. They will never see previously-published posts in their Home feed. This process is very similar to subscribing to a newsletter. If you subscribe to a newsletter, you will only receive future emails, but not the old archived ones. With ActivityPub, if someone follows your site, they will only receive new blog posts you publish from then on. +1. The blog-wide profile is only compatible with sites with rewrite rules enabled. If your site does not have rewrite rules enabled, the author-specific profiles may still work. +1. Many single-author blogs have chosen to turn off or redirect their author profile pages, usually via an SEO plugin like Yoast or Rank Math. This is usually done to avoid duplicate content with your blog’s home page. If your author page has been deactivated in this way, then ActivityPub author profiles won’t work for you. Instead, you can turn your author profile page back on, and then use the option in your SEO plugin to noindex the author page. This will duplicate content issues with search engines and will enable ActivityPub author profiles to work. +1. Once ActivityPub is installed, *only new posts going forward* will be available in the fediverse. Likewise, even if you’ve been using ActivityPub for a while, anyone who follows your site, will only see new posts you publish from that moment on. They will never see previously-published posts in their Home feed. This process is very similar to subscribing to a newsletter. If you subscribe to a newsletter, you will only receive future emails, but not the old archived ones. With ActivityPub, if someone follows your site, they will only receive new blog posts you publish from then on. So what’s the process? 1. Install the ActivityPub plugin. 1. Go to the plugin’s settings page and adjust the settings to your liking. Click the Save button when ready. -1. Make sure your blog’s author profile page is active. -1. Go to Mastodon or any other federated platform, search for your author’s new federated profile, and follow it. Your new profile will be in the form of @yourauthorname@yourwebsite.com, so that is what you’ll search for. +1. Make sure your blog’s author profile page is active if you are using author profiles. +1. Go to Mastodon or any other federated platform, and search for your profile, and follow it. Your new profile will be in the form of either `@your_username@example.com` or `@example.com@example.com`, so that is what you’ll search for. 1. On your blog, publish a new post. 1. From Mastodon, check to see if the new post appears in your Home feed. @@ -54,22 +54,14 @@ Please note that it may take up to 15 minutes or so for the new post to show up = tl;dr = -This plugin connects your WordPress blog to popular social platforms like Mastodon, making your posts more accessible to a wider audience. Once installed, your blog's author pages can be followed by users on these platforms, allowing them to receive your new posts in their feeds. - -Here's how it works: - -1. Install the plugin and adjust settings as needed. -1. Ensure your blog's author profile page is active. -1. On Mastodon or other supported platforms, search for and follow your author's new profile (e.g., `@yourauthorname@yourwebsite.com`). -1. Publish a new post on your blog and check if it appears in your Mastodon feed. - -Please note that it may take up to 15 minutes for a new post to appear in your feed, as messages are sent on a delay to avoid overwhelming your followers. Be patient and give it some time. +This plugin connects your WordPress blog to popular social platforms like Mastodon, making your posts more accessible to a wider audience. Once installed, your blog can be followed by users on these platforms, allowing them to receive your new posts in their feeds. = What is the status of this plugin? = Implemented: -* profile pages (JSON representation) +* blog profile pages (JSON representation) +* author profile pages (JSON representation) * custom links * functional inbox/outbox * follow (accept follows) @@ -79,8 +71,8 @@ Implemented: To implement: -* better configuration possibilities * threaded comments support +* replace shortcodes with blocks for layout = What is "ActivityPub for WordPress" = @@ -94,7 +86,7 @@ In order for webfinger to work, it must be mapped to the root directory of the U Add the following to the .htaccess file in the root directory: - RedirectMatch "^\/\.well-known/(webfinger|nodeinfo|x-nodeinfo2)(.*)$" "\/blog\/\.well-known$1$2" + RedirectMatch "^\/\.well-known/(webfinger|nodeinfo|x-nodeinfo2)(.*)$" /blog/.well-known/$1$2 Where 'blog' is the path to the subdirectory at which your blog resides. @@ -113,20 +105,36 @@ Where 'blog' is the path to the subdirectory at which your blog resides. Project maintained on GitHub at [automattic/wordpress-activitypub](https://github.com/automattic/wordpress-activitypub). += 1.0.1 = + +* Update: improve image attachment detection using the block editor +* Update: better error code handling for API responses +* Update: use a tag stack instead of regex for protecting tags for Hashtags and @-Mentions +* Compatibility: better signature support for subpath-installations +* Compatibility: allow deactivating blocks registered by the plugin +* Compatibility: avoid Fatal Errors when using ClassicPress +* Compatibility: improve the Group-Actor to play nicely with existing implementations +* Fixed: truncate long blog titles and handles for the "Follow me" block +* Fixed: ensure that only a valid user can be selected for the "Follow me" block +* Fixed: fix a typo in a hook name +* Fixed: a problem with signatures when running WordPress in a sub-path + = 1.0.0 = -* Add: blog-wide Account (catchall, like `mydomain.com@mydomain.com`) -* Add: Signature Verification: https://docs.joinmastodon.org/spec/security/ . -* Add: a Followers Block. +* Add: blog-wide Account (catchall, like `example.com@example.com`) +* Add: a Follow Me block (help visitors to follow your Profile) +* Add: Signature Verification: https://docs.joinmastodon.org/spec/security/ +* Add: a Followers Block (show off your Followers) * Add: Simple caching * Add: Collection endpoints for Featured Tags and Featured Posts -* Update: Complete rewrite of the Follower-System based on Custom Post Types. +* Add: Better handling of Hashtags in mobile apps +* Update: Complete rewrite of the Follower-System based on Custom Post Types * Update: Improved linter (PHPCS) -* Compatibility: Add a new conditional, `\Activitypub\is_activitypub_request()`, to allow third-party plugins to detect ActivityPub requests. -* Compatibility: Add hooks to allow modifying images returned in ActivityPub requests. -* Compatibility: Indicate that the plugin is compatible and has been tested with the latest version of WordPress, 6.3. -* Compatibility: Avoid PHP notice on sites using PHP 8.2. -* Fixed: Load the plugin later in the WordPress code lifecycle to avoid errors in some requests. +* Compatibility: Add a new conditional, `\Activitypub\is_activitypub_request()`, to allow third-party plugins to detect ActivityPub requests +* Compatibility: Add hooks to allow modifying images returned in ActivityPub requests +* Compatibility: Indicate that the plugin is compatible and has been tested with the latest version of WordPress, 6.3 +* Compatibility: Avoid PHP notice on sites using PHP 8.2 +* Fixed: Load the plugin later in the WordPress code lifecycle to avoid errors in some requests * Fixed: Updating posts * Fixed: Hashtag now support CamelCase and UTF-8 diff --git a/src/follow-me/block.json b/src/follow-me/block.json new file mode 100644 index 0000000..fba3a2f --- /dev/null +++ b/src/follow-me/block.json @@ -0,0 +1,44 @@ +{ + "$schema": "https://schemas.wp.org/trunk/block.json", + "name": "activitypub/follow-me", + "apiVersion": 3, + "version": "1.0.0", + "title": "Follow me on the Fediverse", + "category": "widgets", + "description": "Display your Fediverse profile so that visitors can follow you.", + "textdomain": "activitypub", + "icon": "groups", + "supports": { + "html": false, + "color": { + "gradients": true, + "link": true, + "__experimentalDefaultControls": { + "background": true, + "text": true, + "link": true + } + }, + "__experimentalBorder": { + "radius": true, + "width": true, + "color": true, + "style": true + }, + "typography": { + "fontSize": true, + "__experimentalDefaultControls": { + "fontSize": true + } + } + }, + "attributes": { + "selectedUser": { + "type": "string", + "default": "site" + } + }, + "editorScript": "file:./index.js", + "viewScript": "file:./view.js", + "style": ["file:./style-index.css", "wp-components"] +} \ No newline at end of file diff --git a/src/follow-me/button-style.js b/src/follow-me/button-style.js new file mode 100644 index 0000000..0c33ca2 --- /dev/null +++ b/src/follow-me/button-style.js @@ -0,0 +1,75 @@ +function presetVarColorCss( color ) { + return `var(--wp--preset--color--${ color })`; +} + +function getBackgroundColor( color ) { + // if color is a string, it's a var like this. + if ( typeof color === 'string' ) { + return presetVarColorCss( color ); + } + + return color?.color?.background || null; +} + +function getLinkColor( text ) { + if ( typeof text !== 'string' ) { + return null; + } + // if it starts with a hash, leave it be + if ( text.match( /^#/ ) ) { + // we don't handle the alpha channel if present. + return text.substring( 0, 7 ); + } + // var:preset|color|luminous-vivid-amber + // var(--wp--preset--color--luminous-vivid-amber) + // we will receive the top format, we need to output the bottom format + const [ , , color ] = text.split( '|' ); + return presetVarColorCss( color ); +} + +function generateSelector( selector, prop, value = null, pseudo = '' ) { + if ( ! value ) { + return ''; + } + return `${ selector }${ pseudo } { ${ prop }: ${ value }; }\n`; +} + +function getStyles( selector, button, text, hover ) { + return generateSelector( selector, 'background-color', button ) + + generateSelector( selector, 'color', text ) + + generateSelector( selector, 'background-color', hover, ':hover' ) + + generateSelector( selector, 'background-color', hover, ':focus' ); +} + +function getBlockStyles( base, style, backgroundColor ) { + const selector = `${ base } .components-button`; + // we grab the background color if set as a good color for our button text + const buttonTextColor = getBackgroundColor( backgroundColor ) + // bg might be in this form. + || style?.color?.background; + // we misuse the link color for the button background + const buttonColor = getLinkColor( style?.elements?.link?.color?.text ); + // hover! + const buttonHoverColor = getLinkColor( style?.elements?.link?.[':hover']?.color?.text ); + + return getStyles( selector, buttonColor, buttonTextColor, buttonHoverColor ); +} + +export function getPopupStyles( style ) { + // we don't acept backgroundColor because the popup is always white (right?) + const buttonColor = getLinkColor( style?.elements?.link?.color?.text ) + || '#111'; + const buttonTextColor = '#fff'; + const buttonHoverColor = getLinkColor( style?.elements?.link?.[':hover']?.color?.text ) + || '#333'; + const selector = '.apfmd__button-group .components-button'; + + return getStyles( selector, buttonColor, buttonTextColor, buttonHoverColor ); +} + +export function ButtonStyle( { selector, style, backgroundColor } ) { + const css = getBlockStyles( selector, style, backgroundColor ); + return ( + + ); +} \ No newline at end of file diff --git a/src/follow-me/edit.js b/src/follow-me/edit.js new file mode 100644 index 0000000..f40c7a2 --- /dev/null +++ b/src/follow-me/edit.js @@ -0,0 +1,39 @@ +import { InspectorControls, useBlockProps } from '@wordpress/block-editor'; +import { __ } from '@wordpress/i18n'; +import { SelectControl, PanelBody } from '@wordpress/components'; +import { useUserOptions } from '../shared/use-user-options'; +import FollowMe from './follow-me'; +import { useEffect } from '@wordpress/element'; + +export default function Edit( { attributes, setAttributes } ) { + const blockProps = useBlockProps(); + const usersOptions = useUserOptions(); + const { selectedUser } = attributes; + + useEffect( () => { + // if there are no users yet, do nothing + if ( ! usersOptions.length ) { + return; + } + // ensure that the selected user is in the list of options, if not, select the first available user + if ( ! usersOptions.find( ( { value } ) => value === selectedUser ) ) { + setAttributes( { selectedUser: usersOptions[ 0 ].value } ); + } + }, [ selectedUser, usersOptions ] ); + + return ( +
+ + + setAttributes( { selectedUser: value } ) } + /> + + + +
+ ); +} diff --git a/src/follow-me/follow-me.js b/src/follow-me/follow-me.js new file mode 100644 index 0000000..8b7a505 --- /dev/null +++ b/src/follow-me/follow-me.js @@ -0,0 +1,178 @@ + +import apiFetch from '@wordpress/api-fetch'; +import { useCallback, useEffect, useState, createInterpolateElement } from '@wordpress/element'; +import { Button, Modal } from '@wordpress/components'; +import { __, sprintf } from '@wordpress/i18n'; +import { copy, check, Icon } from '@wordpress/icons'; +import { useCopyToClipboard } from '@wordpress/compose'; +import { ButtonStyle, getPopupStyles } from './button-style'; +import './style.scss'; +const { namespace } = window._activityPubOptions; + +const DEFAULT_PROFILE_DATA = { + avatar: '', + resource: '@well@hello.dolly', + name: __( 'Hello Dolly Fan Account', 'activitypub' ), + url: '#', +}; + +function getNormalizedProfile( profile ) { + if ( ! profile ) { + return DEFAULT_PROFILE_DATA; + } + const data = { ...DEFAULT_PROFILE_DATA, ...profile }; + data.avatar = data?.icon?.url; + return data; +} + +function fetchProfile( userId ) { + const fetchOptions = { + headers: { Accept: 'application/activity+json' }, + path: `/${ namespace }/users/${ userId }`, + }; + return apiFetch( fetchOptions ); +} + +function Profile( { profile, popupStyles, userId } ) { + const { avatar, name, resource } = profile; + return ( +
+ +
+
{ name }
+
{ resource }
+
+ +
+ ); +} + +function Follow( { profile, popupStyles, userId } ) { + const [ isOpen, setIsOpen ] = useState( false ); + const title = sprintf( __( 'Follow %s', 'activitypub' ), profile?.name ); + + return ( + <> + + { isOpen && ( + setIsOpen( false ) } + title={ title } + > + + + + ) } + + ); +} + +function isUrl( string ) { + try { + new URL( string ); + return true; + } catch ( _ ) { + return false; + } +} + +function isHandle( string ) { + // remove leading @, there should still be an @ in there + const parts = string.replace( /^@/, '' ).split( '@' ); + return parts.length === 2 && isUrl( `https://${ parts[ 1 ] }` ); +} + +function Dialog( { profile, userId } ) { + const { resource } = profile; + const followText = __( 'Follow', 'activitypub' ); + const loadingText = __( 'Loading...', 'activitypub' ); + const openingText = __( 'Opening...', 'activitypub' ); + const errorText = __( 'Error', 'activitypub' ); + const invalidText = __( 'Invalid', 'activitypub' ); + const [ buttonText, setButtonText ] = useState( followText ); + const [ buttonIcon, setButtonIcon ] = useState( copy ); + const ref = useCopyToClipboard( resource, () => { + setButtonIcon( check ); + setTimeout( () => setButtonIcon( copy ), 1000 ); + } ); + const [ remoteProfile, setRemoteProfile ] = useState( '' ); + const retrieveAndFollow = useCallback( () => { + let timeout; + if ( ! ( isUrl( remoteProfile ) || isHandle( remoteProfile ) ) ) { + setButtonText( invalidText ); + timeout = setTimeout( () => setButtonText( followText ), 2000 ); + return () => clearTimeout( timeout ); + } + const path = `/${ namespace }/users/${userId}/remote-follow?resource=${ remoteProfile }`; + setButtonText( loadingText ); + apiFetch( { path } ).then( ( { url } ) => { + setButtonText( openingText ); + setTimeout( () => { + window.open( url, '_blank' ); + setButtonText( followText ); + }, 200 ); + } ).catch( () => { + setButtonText( errorText ); + setTimeout( () => setButtonText( followText ), 2000 ); + } ); + }, [ remoteProfile ] ); + + return ( +
+
+

{ __( 'My Profile', 'activitypub' ) }

+
+ { __( 'Copy and paste my profile into the search field of your favorite fediverse app or server.', 'activitypub' ) } +
+
+ + +
+
+
+

{ __( 'Your Profile', 'activitypub' ) }

+
+ { createInterpolateElement( + __( 'Or, if you know your own profile, we can start things that way! (eg https://example.com/yourusername or yourusername@example.com)', 'activitypub' ), + { code: } + ) } +
+
+ { event?.code === 'Enter' && retrieveAndFollow() } } + onChange={ e => setRemoteProfile( e.target.value ) } + /> + +
+
+
+ ); +} + +export default function FollowMe( { selectedUser, style, backgroundColor, id, useId = false } ) { + const [ profile, setProfile ] = useState( getNormalizedProfile() ); + const userId = selectedUser === 'site' ? 0 : selectedUser; + const popupStyles = getPopupStyles( style ); + const wrapperProps = useId ? { id } : {}; + function setProfileData( profile ) { + setProfile( getNormalizedProfile( profile ) ); + } + useEffect( () => { + fetchProfile( userId ).then( setProfileData ); + }, [ userId ] ); + + return( +
+ + +
+ ) +} \ No newline at end of file diff --git a/src/follow-me/index.js b/src/follow-me/index.js new file mode 100644 index 0000000..550af60 --- /dev/null +++ b/src/follow-me/index.js @@ -0,0 +1,5 @@ +import { registerBlockType } from '@wordpress/blocks'; +import { people } from '@wordpress/icons'; +import edit from './edit'; +const save = () => null; +registerBlockType( 'activitypub/follow-me', { edit, save, icon: people } ); \ No newline at end of file diff --git a/src/follow-me/style.scss b/src/follow-me/style.scss new file mode 100644 index 0000000..fe20cb1 --- /dev/null +++ b/src/follow-me/style.scss @@ -0,0 +1,67 @@ +.editor-styles-wrapper, .activitypub-follow-me-block-wrapper { + .activitypub-profile { + display: flex; + align-items: self-start; + padding: 1rem; + + .activitypub-profile__avatar { + height: 75px; + width: 75px; + margin-right: 1rem; + border-radius: 50%; + } + .activitypub-profile__content { + flex: 1; + min-width: 0; + } + .activitypub-profile__name, .activitypub-profile__handle { + margin: 0; + line-height: 1.2; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + .activitypub-profile__name { + font-size: 1.25em; + } + .activitypub-profile__follow { + margin-left: 1rem; + align-self: center; + background-color: var(--wp--preset--color--black); + color: var(--wp--preset--color--white); + } + } +} + +.activitypub-follow-me__dialog { + max-width: 30em; + h4 { + line-height: 1; + margin: 0; + } + .apmfd__section { + margin-bottom: 2em; + } + .apfmd-description { + font-size: var( --wp--preset--font-size--normal, .75rem ); + margin: 0.33em 0 1em; + } + .apfmd__button-group { + display: flex; + justify-content: flex-end; + + svg { + margin-right: .5em; + height: 21px; + width: 21px; + } + + input { + flex: 1; + padding: { + left: 1em; + right: 1em; + } + } + } +} diff --git a/src/follow-me/view.js b/src/follow-me/view.js new file mode 100644 index 0000000..418e45c --- /dev/null +++ b/src/follow-me/view.js @@ -0,0 +1,16 @@ +import { render } from '@wordpress/element'; +import domReady from '@wordpress/dom-ready'; +import FollowMe from './follow-me'; + +let id = 1; +function getUniqueId() { + return `activitypub-follow-me-block-${ id++ }`; +} + +domReady( () => { + // iterate over a nodelist + [].forEach.call( document.querySelectorAll( '.activitypub-follow-me-block-wrapper' ), ( element ) => { + const attrs = JSON.parse( element.dataset.attrs ); + render( , element ); + } ); +} ); \ No newline at end of file diff --git a/src/followers/edit.js b/src/followers/edit.js index 80156bb..de79a96 100644 --- a/src/followers/edit.js +++ b/src/followers/edit.js @@ -1,31 +1,9 @@ import { SelectControl, RangeControl, PanelBody, TextControl } from '@wordpress/components'; -import { useSelect } from '@wordpress/data'; -import { useMemo, useState } from '@wordpress/element'; +import { useState, useEffect } from '@wordpress/element'; import { InspectorControls, useBlockProps } from '@wordpress/block-editor'; import { __ } from '@wordpress/i18n'; import { Followers } from './followers'; - -const enabled = window._activityPubOptions?.enabled; - -function useUserOptions() { - const users = enabled?.users ? useSelect( ( select ) => select( 'core' ).getUsers( { who: 'authors' } ) ) : []; - return useMemo( () => { - if ( ! users ) { - return []; - } - const withBlogUser = enabled?.site ? [ { - label: __( 'Whole Site', 'activitypub' ), - value: 'site' - } ] : []; - return users.reduce( ( acc, user ) => { - acc.push({ - label: user.name, - value: user.id - } ); - return acc; - }, withBlogUser ); - }, [ users ] ); -} +import { useUserOptions } from '../shared/use-user-options'; export default function Edit( { attributes, setAttributes } ) { const { order, per_page, selectedUser, title } = attributes; @@ -43,6 +21,17 @@ export default function Edit( { attributes, setAttributes } ) { }; } + useEffect( () => { + // if there are no users yet, do nothing + if ( ! usersOptions.length ) { + return; + } + // ensure that the selected user is in the list of options, if not, select the first available user + if ( ! usersOptions.find( ( { value } ) => value === selectedUser ) ) { + setAttributes( { selectedUser: usersOptions[ 0 ].value } ); + } + }, [ selectedUser, usersOptions ] ); + return (
diff --git a/src/followers/followers.js b/src/followers/followers.js index 445537b..bc555b8 100644 --- a/src/followers/followers.js +++ b/src/followers/followers.js @@ -64,7 +64,7 @@ export function Followers( { setTotal( data.totalItems ); setFollowers( data.orderedItems ); } ) - .catch( ( error ) => console.error( error ) ); + .catch( () => {} ); }, [ userId, per_page, order, page ] ); return (
diff --git a/src/shared/use-user-options.js b/src/shared/use-user-options.js new file mode 100644 index 0000000..ac6d1c1 --- /dev/null +++ b/src/shared/use-user-options.js @@ -0,0 +1,24 @@ +import { __ } from '@wordpress/i18n'; +import { useSelect } from '@wordpress/data'; +import { useMemo } from '@wordpress/element'; +const enabled = window._activityPubOptions?.enabled; + +export function useUserOptions() { + const users = enabled?.users ? useSelect( ( select ) => select( 'core' ).getUsers( { who: 'authors' } ) ) : []; + return useMemo( () => { + if ( ! users ) { + return []; + } + const withBlogUser = enabled?.site ? [ { + label: __( 'Whole Site', 'activitypub' ), + value: 'site' + } ] : []; + return users.reduce( ( acc, user ) => { + acc.push({ + label: user.name, + value: `${ user.id }` // casting to string because that's how the attribute is stored by Gutenberg + } ); + return acc; + }, withBlogUser ); + }, [ users ] ); +} \ No newline at end of file diff --git a/templates/admin-header.php b/templates/admin-header.php index 23fb421..67b91ba 100644 --- a/templates/admin-header.php +++ b/templates/admin-header.php @@ -6,7 +6,7 @@

-