Showing preview only (423K chars total). Download the full file or copy to clipboard to get everything.
Repository: gatsbyjs/wp-gatsby
Branch: master
Commit: 1004609a2295
Files: 87
Total size: 397.1 KB
Directory structure:
gitextract_1lfhn0r3/
├── .dockerignore
├── .env.dist
├── .github/
│ └── workflows/
│ ├── main.yml
│ └── tests.yml
├── .gitignore
├── .prettierrc.js
├── CHANGELOG.md
├── README.md
├── access-functions.php
├── bin/
│ ├── install-test-env.sh
│ └── run-docker.sh
├── codeception.dist.yml
├── composer.json
├── docker/
│ ├── app.Dockerfile
│ ├── app.entrypoint.sh
│ ├── testing.Dockerfile
│ └── testing.entrypoint.sh
├── docker-compose.yml
├── docs/
│ ├── action-monitor.md
│ └── running-tests.md
├── lib/
│ └── wp-settings-api.php
├── license.txt
├── readme.txt
├── src/
│ ├── ActionMonitor/
│ │ ├── ActionMonitor.php
│ │ └── Monitors/
│ │ ├── AcfMonitor.php
│ │ ├── MediaMonitor.php
│ │ ├── Monitor.php
│ │ ├── NavMenuMonitor.php
│ │ ├── PostMonitor.php
│ │ ├── PostTypeMonitor.php
│ │ ├── PreviewMonitor.php
│ │ ├── SettingsMonitor.php
│ │ ├── TaxonomyMonitor.php
│ │ ├── TermMonitor.php
│ │ └── UserMonitor.php
│ ├── Admin/
│ │ ├── Preview.php
│ │ ├── Settings.php
│ │ └── includes/
│ │ ├── no-preview-url-set.php
│ │ ├── post-type-not-shown-in-graphql.php
│ │ ├── preview-template.php
│ │ └── style.css
│ ├── GraphQL/
│ │ ├── Auth.php
│ │ └── ParseAuthToken.php
│ ├── Schema/
│ │ ├── Schema.php
│ │ ├── SiteMeta.php
│ │ └── WPGatsbyWPGraphQLSchemaChanges.php
│ ├── ThemeSupport/
│ │ └── ThemeSupport.php
│ └── Utils/
│ └── Utils.php
├── tests/
│ ├── _data/
│ │ ├── .gitignore
│ │ ├── .gitkeep
│ │ └── config.php
│ ├── _output/
│ │ ├── .gitignore
│ │ └── .gitkeep
│ ├── _support/
│ │ ├── AcceptanceTester.php
│ │ ├── FunctionalTester.php
│ │ ├── Helper/
│ │ │ ├── Acceptance.php
│ │ │ ├── Functional.php
│ │ │ ├── Unit.php
│ │ │ └── Wpunit.php
│ │ ├── UnitTester.php
│ │ ├── WpunitTester.php
│ │ └── _generated/
│ │ └── .gitignore
│ ├── acceptance.suite.dist.yml
│ ├── functional.suite.dist.yml
│ ├── wpunit/
│ │ └── ActionMonitorTest.php
│ └── wpunit.suite.dist.yml
├── vendor/
│ ├── autoload.php
│ ├── composer/
│ │ ├── ClassLoader.php
│ │ ├── LICENSE
│ │ ├── autoload_classmap.php
│ │ ├── autoload_namespaces.php
│ │ ├── autoload_psr4.php
│ │ ├── autoload_real.php
│ │ ├── autoload_static.php
│ │ └── semver/
│ │ ├── CHANGELOG.md
│ │ ├── LICENSE
│ │ ├── README.md
│ │ └── composer.json
│ └── firebase/
│ └── php-jwt/
│ ├── LICENSE
│ ├── README.md
│ ├── composer.json
│ └── src/
│ ├── BeforeValidException.php
│ ├── ExpiredException.php
│ ├── JWK.php
│ ├── JWT.php
│ └── SignatureInvalidException.php
└── wp-gatsby.php
================================================
FILE CONTENTS
================================================
================================================
FILE: .dockerignore
================================================
.env
.github_changelog_generator
.travis.yml
codeception.yml
================================================
FILE: .env.dist
================================================
DB_NAME=wordpress
DB_HOST=app_db
DB_USER=wordpress
DB_PASSWORD=wordpress
WP_TABLE_PREFIX=wp_
WP_URL=http://localhost
WP_DOMAIN=localhost
ADMIN_EMAIL=admin@example.com
ADMIN_USERNAME=admin
ADMIN_PASSWORD=password
ADMIN_PATH=/wp-admin
TEST_DB_NAME=wpgatsby_tests
TEST_DB_HOST=127.0.0.1
TEST_DB_USER=wordpress
TEST_DB_PASSWORD=wordpress
TEST_WP_TABLE_PREFIX=wp_
SKIP_DB_CREATE=false
TEST_WP_ROOT_FOLDER=/tmp/wordpress
TEST_ADMIN_EMAIL=admin@wp.test
TESTS_DIR=tests
TESTS_OUTPUT=tests/_output
TESTS_DATA=tests/_data
TESTS_SUPPORT=tests/_support
TESTS_ENVS=tests/_envs
WPGRAPHQL_VERSION=v1.1.5
SKIP_TESTS_CLEANUP=1
SUITES=wpunit
================================================
FILE: .github/workflows/main.yml
================================================
name: Deploy to WordPress.org
on:
push:
tags:
- "*"
jobs:
tag:
name: New tag
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- name: WordPress Plugin Deploy
uses: 10up/action-wordpress-plugin-deploy@master
env:
SVN_PASSWORD: ${{ secrets.SVN_PASSWORD }}
SVN_USERNAME: ${{ secrets.SVN_USERNAME }}
SLUG: wp-gatsby
================================================
FILE: .github/workflows/tests.yml
================================================
name: Automated-Testing
on:
push:
branches:
- master
pull_request:
types: [opened, synchronize]
jobs:
continuous_integration:
runs-on: ubuntu-latest
strategy:
matrix:
php: ["7.3", "7.4"]
wordpress: ["5.6", "5.5.3", "5.4.2"]
include:
- php: "7.4"
wordpress: "5.6"
- php: "7.4"
wordpress: "5.5.3"
- php: "7.4"
wordpress: "5.4.2"
- php: "7.3"
wordpress: "5.6"
- php: "7.3"
wordpress: "5.5.3"
- php: "7.3"
wordpress: "5.4.2"
fail-fast: false
name: WordPress ${{ matrix.wordpress }} on PHP ${{ matrix.php }}
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Install PHP
if: matrix.coverage == 1
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: json, mbstring
- name: Get Composer Cache Directory
id: composercache
run: echo "::set-output name=dir::$(composer config cache-files-dir)"
- name: Cache dependencies
uses: actions/cache@v2
with:
path: ${{ steps.composercache.outputs.dir }}
key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }}
restore-keys: ${{ runner.os }}-composer-
- name: Install dependencies
run: composer install --no-dev
- name: Build "testing" Docker Image
env:
PHP_VERSION: ${{ matrix.php }}
WP_VERSION: ${{ matrix.wordpress }}
USE_XDEBUG: ${{ matrix.use_xdebug }}
run: composer build-test
- name: Run Tests w/ Docker.
env:
COVERAGE: ${{ matrix.coverage }}
DEBUG: ${{ matrix.debug }}
SKIP_TESTS_CLEANUP: ${{ matrix.coverage }}
LOWEST: ${{ matrix.lowest }}
run: composer run-test
================================================
FILE: .gitignore
================================================
.DS_Store
node_modules
phpcs.xml
phpunit.xml
Thumbs.db
wp-cli.local.yml
node_modules/
*.sql
*.tar.gz
*.zip
.env
.env.*
!.env.dist
.idea
.vscode
.github_changelog_generator
!vendor/
vendor/*
!vendor/autoload.php
!vendor/composer
!vendor/firebase
!vendor/ircmaxell
vendor/composer/installed.json
vendor/composer/*/
!vendor/composer/semver/*
!tests
tests/*.suite.yml
build/
coverage/*
schema.graphql
phpunit.xml
docker-output
composer.lock
c3.php
.log/
php-coveralls.phar
codeception.yml
================================================
FILE: .prettierrc.js
================================================
module.exports = {
arrowParens: "avoid",
semi: false,
}
================================================
FILE: CHANGELOG.md
================================================
# Change Log
## 2.3.3
Fixes an issue where publicly_queryable post types that were not public weren't being tracked in action monitor even though those post types were available in Gatsby. Thanks @nickcernis! (via PR #217)
## 2.3.2
Previously Author and Contributor roles couldn't properly use Gatsby Cloud Preview. This release introduces new custom role capabilities which allow all authenticated users that can use WP preview to use Gatsby Preview.
## 2.3.1
Fixes bug in last version where not having the right ACF version installed would throw an error about `Call to undefined function "acf_get_options_pages"`
## 2.3.0
Added action monitor tracking for ACF options pages via PR #206. Thanks @henrikwirth!
## 2.2.1
Bumped the "tested to" version to latest WP version.
## 2.2.0
Added support for Gatsby Cloud Preview's new feature "eager redirects" which reduces the amount of time spent watching the preview loading screen by redirecting to the preview frontend as soon as possible and then letting the user wait for the preview to finish building there.
## 2.1.1
Changing away from the default UTC+0 timezone in WP could cause problems with local development and syncing changed data from WP. This release fixes that via PR #204.
## 2.1.0
Updated how the `gatsby_action_monitors` filter works. Previously this filter didn't properly expose the ActionMonitor class making it impossible or very difficult to add your own action monitors. Thanks @justlevine! via PR #203.
## 2.0.2
WPGraphQL made a breaking change in a minor release v1.6.7 which caused delta updates to stop working. Fixed via https://github.com/gatsbyjs/wp-gatsby/pull/201. Breaking change notice here https://github.com/wp-graphql/wp-graphql/blob/develop/readme.txt#L80-L109
## 2.0.1
- gatsby-source-wordpress v5.14.2 and v6.1.0 both support WPGatsby v2.0.0+. This release re-published v2 as the latest WPGatsby version.
## 1.1.4
- Rolling out a release to overwrite v2.0.0. gatsby-source-wordpress didn't yet have a new release allowing WPGatsby v2.0.0+ support.
## 2.0.0
We finalized support for Gatsby Cloud Content Sync Previews in this release. Content Sync is a Gatsby Cloud preview loader. Previously preview loading was handled within this plugin but we removed support for that legacy preview loader as the support burden for keeping the old and new preview logic around would be too much. Gatsby Cloud Content Sync is far more reliable than WPGatsby's preview loader as it has more context on the Gatsby build process.
For Content Sync to work you will need to upgrade to the latest version of `gatsby-source-wordpress` and either the latest `3.0.0` or `4.0.0` version of Gatsby core.
In addition this release comes with some bug fixes:
- Fixed double instantiation of ActionMonitor classes which caused double webhooks and potentially double saving of data in some cases.
- Makes preview routing more reliable by simplifying our logic and adding a `gatsby_preview=true` param to all preview links. For some users every second preview would fail to correctly route to the preview template. This is now fixed.
## 1.1.3
- The uri field was being overwritten during GraphQL requests, resulting in post uri's that included the content sync URL.
- Some logic attempting to choose the correct manifest ID instead of regenerating it was causing manifest id's to be outdated during previews.
## 1.1.2
- Fixed redirection to Gatsby Cloud Content Sync preview loader in Gutenberg
## 1.1.0
- Added support for the new Gatsby Cloud Content Sync API. This new API moves the WPGatsby Preview loader logic to the Gatsby Cloud side as Cloud has more context on the Gatsby process making it more reliable than the existing WPGatsby preview loader with fewer restrictions and caveats.
## 1.0.12
Preview webhooks added the remote url as a property on the webhook body. When publishing updates we also send a preview webhook to update the preview Gatsby site. These two webhook bodies previously differed in that the latter didn't include a remoteUrl property. As of gatsby-source-wordpress@5.10.0 this causes problems because the source plugin assumes this property always exists. Related to https://github.com/gatsbyjs/gatsby/issues/32732. Fixed in https://github.com/gatsbyjs/wp-gatsby/pull/184
## 1.0.11
- Fixed a warning state for Preview to let users know when the preview Gatsby site set in the preview webhook setting is pointing at a Gatsby site which isn't sourcing data from the current WP site. Preview requires a 1:1 connection between WP and Gatsby where settings point at a Gatsby site that sources data from the WP instance previews are originating from.
## 1.0.10
- Fixed preview loader logic for subdirectory WP installs so that we request the GraphQL endpoint from the right URL.
## 1.0.9
- Fixed a bug where draft posts weren't previewable.
## 1.0.8
- Our internal preview logic had a bug where a request was being made with double forward slashes in the url in some cases. This broke incremental builds previews but worked on regular `gatsby develop` previews. This is fixed in this release.
## 1.0.7
- Before using WPGraphQL::debug() we weren't making sure that the debug method exists on that class. This could throw errors for older versions of WPGraphQL - we now check that the method exists before using it.
- Documents using multiple webhooks support in Build and Preview webhook input field labels.
- Fixes trailing comma in MediaActionMonitor log array.
## 1.0.6
- Bump stable version tag
## 1.0.5
- Fixed our build/publish process which was failing due to using the develop branch of WPGraphQL in tests.
## 1.0.4
- In some cases the homepage was not previewable in Gatsby Preview - this is now fixed.
## 1.0.3
- Fixed `wp_save_image_file` and `wp_save_image_editor_file` callback argument count.
## 1.0.2
- An erroneous change in our composer autoload broke our first stable release 😅 bit of a rocky start but lets try this again 🤝 😁 You can bet we'll be adding a test for this 😂
## 1.0.1
- Fixed a broken link in the readme.
## 1.0.0
This plugin has come a long way over the past few months! This release introduces no changes outside of a few pages of docs. We're choosing this point to call this plugin stable as the plugin is well tested via our test suites and members of the community using it in the wild. Thanks everyone for your help and support in getting this plugin to this point!
## 0.9.2
### Bug Fixes
- The preview template loader was fixed for cases where the global $post is not set, which previously lead to PHP errors.
## 0.9.1
- Removed a new internal taxonomy from the GraphQL schema which was unintentionally added in the last release.
## 0.9.0
### Breaking Changes
- This release massively increases the performance of Gatsby Previews when more than one person is previewing or editing content at the same time. Previously when multiple users previewed simultaneously, only one of those users would see their preview or it would take a very long time for the others to see their previews. Now many users can preview concurrently. This was tested with a headless chrome puppeteer script. We found that 10 users making 100 previews over the course of a few minutes now have a 100% success rate. Previously 3 users making 30 previews would have a less than 30% success rate. This is a breaking change because `gatsby-source-wordpress-experimental` has some changes which are required to make this work.
- Previously, saving a Media item would call the build and preview webhooks. This wasn't desireable because if you upload an image to your post, that will start a build to just source that media item, then when you press publish or preview you'd have to wait for the image build to complete before being able to see your build. Now a webhook is not sent out when images are uploaded/edited and other content updates which do send a webhook will catch these image changes and apply them alongside the other changes.
## 0.8.0
### Breaking Changes
This is a breaking change release as a lot of internals for the Action Monitor class have been modified and moved around. For most users nothing will change but for those who are using our internal plugin functions/classes in their own custom code, things might break.
- Refactors Action Monitor to have separate classes for tracking activity for Acf, Media, Menus, Posts, Post Types, Settings, Taxonomies, Terms, and Users.
### Fixes and improvements
- TESTS! Lots of tests for the Action Monitors.
- JWT Secret is now set once when WPGatsby is first loaded, instead of every time the settings page is visited.
### Issues closed by this release
- [#70](https://github.com/gatsbyjs/wp-gatsby/issues/70): When field groups are saved using ACF Field Group GUI, a "Diff Schema" action is triggered
- [#58](https://github.com/gatsbyjs/wp-gatsby/issues/58): A "Refetch All" action is available and is used when Permalinks are changed
- [#57](https://github.com/gatsbyjs/wp-gatsby/issues/57): Term meta is now properly tracked when changed
- [#56](https://github.com/gatsbyjs/wp-gatsby/issues/56): Custom post types (all post types that are public and show_in_graphql) are now tracked when they are moved from publish to trash and vis-versa
- [#41](https://github.com/gatsbyjs/wp-gatsby/issues/41): Codeception tests are now in place
- [#38](https://github.com/gatsbyjs/wp-gatsby/issues/38): Many core WordPress options have been added to an allow-list and trigger a general NON_NODE_ROOT_FIELDS action. A few specific actions trigger specific actions for specific nodes. For example, changing the home_page triggers an update for the new page and the old page being changed as the URI is now different.
- [#26](https://github.com/gatsbyjs/wp-gatsby/issues/26): Posts that transition from future->publish now trigger an action (ensuring WordPress cron is triggered for WordPress sites using Gatsby front-ends might need more thought still though. . .)
- [#17](https://github.com/gatsbyjs/wp-gatsby/issues/17): Meta is now tracked for Posts, Terms and Users (comments are not currently tracked at the moment)
- [#15](https://github.com/gatsbyjs/wp-gatsby/issues/15): Saving permalinks triggers a REFETCH_ALL Action
- [#7](https://github.com/gatsbyjs/wp-gatsby/issues/7): Gatsby JWT Secret is now generated once and saved immediately and not generated again
- [#6](https://github.com/gatsbyjs/wp-gatsby/issues/6): Gatsby now tracks only post_types (and taxonomies) that are set to be both public and show_in_graphql and there are filters to override as needed.
## 0.7.3
- Small internal changes to Previews to facilitate e2e tests.
## 0.7.2
- Version 0.7.0 introduced a change which resulted in Previews for some WP instances being overwritten by published posts on each preview.
## 0.7.1
- The last version added some internal taxonomies to the GraphQL schema unintentionally. This release removes them.
## 0.7.0
### Breaking Changes
- Previously we were storing a brand new post internally for every content-related action that happened in your site. As of this release we only make a single action post for each post you take actions against and update it each time instead of creating a new one.
## 0.6.8
- The `NO_PAGE_CREATED_FOR_PREVIEWED_NODE` preview status was no longer making it through to the preview template because we were checking if the preview had deployed before checking if a page had been created in Gatsby for the preview. this release fixes that.
- The preview-template.php check for wether or not the preview frontend is online could occasionally come back with a false negative. It is now more resilient and will recheck for 10 seconds before showing an error.
- The above check used to throw harmless CORS errors in the console, this check is now done server-side so that CORS isn't an issue.
## 0.6.7
- Gatsby Preview process errors were not coming through for new post drafts. They do now :)
- I was checking if the Gatsby webhook hit by WPGatsby returned any errors and displaying an error in the preview client if it did. It turns out this is problematic because the webhook can return errors in WPGatsby and yet Gatsby can still have successfully received it. So the logic is now more optimistic and tries to load the preview regardless of wether or not we received an error when posting to the webhook.
## 0.6.6
- Fixed a timing issue between Previews and WPGatsby. WPGatsby now reads the page-data.json of the page being previewed in order to determine wether or not it's been deployed.
- Added publish webhooks for Preview so that polling is not needed in Gatsby Preview on the source plugin side.
## 0.6.5
- Improved garbage collection of old action monitor posts. Garbage collection previously took over 20 seconds to clean up 6,204 action_monitor actions, after this change it takes approximately 1/10 of a second.
## 0.6.4
- Extended WPGatsby JWT expiry to 1 hour. It was previously 30 seconds which can be problematic for slower servers and Gatsby setups.
## 0.6.3
- graphql_single_name's that start with a capital letter were causing issues because WPGatsby was not making the first character lowercase but WPGraphQL does do this when adding the field to schema.
## 0.6.2
- More PHP 7.1 syntax fixes. We will soon have CI tests which will prevent these issues.
## 0.6.1
- Fixed an unexpected token syntax error.
## 0.6.0
- This release adds a major re-work to the Gatsby Preview experience! It adds remote Gatsby state management and error handling in WordPress so that WP and Gatsby don't get out of sync during the Preview process.
## 0.5.4
- Force enable WPGraphQL Introspection when WPGatsby is enabled. [WPGraphQL v0.14.0](https://github.com/wp-graphql/wp-graphql/releases/tag/v0.14.0) has Introspection disabled by default with an option to enable it, and Gatsby requires it to be enabled, so WPGatsby force-enables it.
## 0.5.3
- Meta delta syncing was using the same code for posts and users. In many cases this was causing errors when updating usermeta. This code is now scoped to posts only and we will add usermeta delta syncing separately.
- Our composer setup was previously double autoloading
## 0.5.2
- Added a backwards compatibility fix for a regression introduced in v0.4.18 where WPGraphQL::debug() was called. This method is only available in later versions of WPGraphQL, but this plugin currently supports earlier versions
## 0.5.1
- Fixed a typo in the new footer locations 🤦♂️ gatbsy should be gatsby
## 0.5.0
### Bug Fixes
- Added support for delta syncing menu locations. This appeared as a bug where updating your menu locations didn't update in Gatsby, but this was actually a missing feature.
## 0.4.18
### Bug Fixes
- The action_monitor post type was registered incorrectly so that it was showing in the rest api, in search, and other places it didn't need to be. This release fixes that. Thanks @jasonbahl!
## 0.4.17
### New Features
- Added `WPGatsby.arePrettyPermalinksEnabled` to the schema in order to add more helpful error messages to the Gatsby build process.
- Added a filter `gatsby_trigger_dispatch_args` to filter the arguments passed to `wp_safe_remote_post` when triggering webhooks.
## 0.4.16
### Bug Fixes
It turns out the new feature in the last release could potentially cause many more issues than it presently solves, so it has been disabled as a bug fix. This will be re-enabled within the next couple weeks as we do more testing and thinking on how best to approach sending WP options events to Gatsby.
## 0.4.15
### New Features
- Non-node root fields (options and settings) are now recorded as an action so Gatsby can inc build when the site title changes for example.
## 0.4.14
### Bug Fixes
- Making a post into a draft was not previously saving an action monitor post which means posts that became drafts would never be deleted.
## 0.4.13
### Bug Fixes
- the ContentType.archivePath field was returning an empty string instead of `/` for a homepage archive.
## 0.4.12
### New Features
- Added temporary `ContentType.archivePath` and `Taxonomy.archivePath` fields to the schema until WPGraphQL supports these fields.
## 0.4.11
### Bug Fixes
- get_home_url() was being used where get_site_url() should've been used, causing the gql endpoint to not be referenced correctly in some situations. For example when using Bedrock.
## 0.4.10
### Bug Fixes
- The Preview fix in the last release introduced a new bug where saving a draft at any time would send a webhook to the Preview instance.
## 0.4.9
### Bug Fixes
- Preview wasn't working properly for new posts that hadn't yet been published or for drafts.
## 0.4.8
Pushing release to WordPress.org
## 0.4.7
### New Features
- Added a link to the GatsbyJS settings page on how to configure this plugin.
### Bug Fixes
- Activating this plugin before WPGraphQL was causing PHP errors.
## 0.4.6
Add Wapuu Icons for display in the WordPress.org repo
## 0.4.5
Re-publish with proper package name
## 0.4.4
Testing Github Actions
## 0.4.3
New release to trigger publishing to WordPress.org!
## 0.4.2
### Bug Fixes
- Previously when a post transitioned from published to draft, it wouldn't be deleted in Gatsby
## 0.4.1
Version bump to add /vendor directory to Git so that Github releases work as WP plugins without running `composer install`. In the future there will be a better release process, but for now this works.
## 0.4.0
### Breaking Changes
- WPGraphQL was using nav_menu for it's menu relay id's instead of term. WPGQL 0.9.1 changes this from nav_menu to term. This is a breaking change because cache invalidation wont work properly if the id is incorrect. So we move to v0.4.0 so gatsby-source-wordpress-experimental can set 0.4.0 as it's min version and cache invalidation will keep working.
## 0.3.0
### Breaking Changes
- Updated Relay ids to be compatible with WPGraphQL 0.9.0. See https://github.com/wp-graphql/wp-graphql/releases/tag/v0.9.0 for more info.
- Bumped min PHP and WP versions
## 0.2.6
### Bug fixes
Fixed an issue where we were trying to access post object properties when we didn't yet have the post.
## 0.2.5
### Bug Fixes
Earlier versions of WPGatsby were recording up to 4 duplicate content saves per content change in WordPress. This release stops that from happening. WPGatsby does garbage collection, so any duplicate actions will be automatically removed from your DB.
================================================
FILE: README.md
================================================
<div align="center" style="margin-bottom: 20px;">
<img src="https://raw.githubusercontent.com/gatsbyjs/gatsby/master/packages/gatsby-source-wordpress/docs/assets/gatsby-wapuus.png" alt="Wapuu hugging a ball with the Gatsby logo on it" />
</div>
<p align="center">
<a href="https://github.com/gatsbyjs/wp-gatsby/blob/master/license.txt">
<img src="https://img.shields.io/badge/license-GPLv3-blue.svg" alt="Gatsby and gatsby-source-wordpress are released under the MIT license." />
</a>
<a href="https://twitter.com/intent/follow?screen_name=gatsbyjs">
<img src="https://img.shields.io/twitter/follow/gatsbyjs.svg?label=Follow%20@gatsbyjs" alt="Follow @gatsbyjs" />
</a>
</p>
# WPGatsby
WPGatsby is a free open-source WordPress plugin that optimizes your WordPress site to work as a data source for [Gatsby](https://www.gatsbyjs.com/docs/how-to/sourcing-data/sourcing-from-wordpress).
This plugin must be used in combination with the npm package [`gatsby-source-wordpress@>=4.0.0`](https://www.npmjs.com/package/gatsby-source-wordpress).
## Install and Activation
WPGatsby is available on the WordPress.org repository and can be installed from your WordPress dashboard, or by using any other plugin installation method you prefer, such as installing with Composer from wpackagist.org.
## Plugin Overview
This plugin has 2 primary responsibilities:
- [Monitor Activity in WordPress to keep Gatsby in sync with WP](https://github.com/gatsbyjs/wp-gatsby/blob/master/docs/action-monitor.md)
- [Configure WordPress Previews to work with Gatsby](https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-source-wordpress/docs/tutorials/configuring-wp-gatsby.md#setting-up-preview)
Additionally, WPGatsby has a settings page to connect your WordPress site with your Gatsby site:
- [WPGatsby Settings](https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-source-wordpress/docs/tutorials/configuring-wp-gatsby.md)
================================================
FILE: access-functions.php
================================================
<?php
================================================
FILE: bin/install-test-env.sh
================================================
#!/usr/bin/env bash
source .env
print_usage_instruction() {
echo "Ensure that .env file exist in project root directory exists."
echo "And run the following 'composer install-wp-tests' in the project root directory"
exit 1
}
if [[ -z "$TEST_DB_NAME" ]]; then
echo "TEST_DB_NAME not found"
print_usage_instruction
else
DB_NAME=$TEST_DB_NAME
fi
if [[ -z "$TEST_DB_USER" ]]; then
echo "TEST_DB_USER not found"
print_usage_instruction
else
DB_USER=$TEST_DB_USER
fi
DB_HOST=${TEST_DB_HOST-localhost}
DB_PASS=${TEST_DB_PASSWORD-""}
WP_VERSION=${WP_VERSION-latest}
TMPDIR=${TMPDIR-/tmp}
TMPDIR=$(echo $TMPDIR | sed -e "s/\/$//")
WP_TESTS_DIR=${WP_TESTS_DIR-$TMPDIR/wordpress-tests-lib}
WP_CORE_DIR=${TEST_WP_ROOT_FOLDER-$TMPDIR/wordpress/}
PLUGIN_DIR=$(pwd)
DB_SERVE_NAME=${DB_SERVE_NAME-wpgatsby_serve}
SKIP_DB_CREATE=${SKIP_DB_CREATE-false}
download() {
if [ `which curl` ]; then
curl -s "$1" > "$2";
elif [ `which wget` ]; then
wget -nv -O "$2" "$1"
fi
}
if [[ $WP_VERSION =~ ^[0-9]+\.[0-9]+\-(beta|RC)[0-9]+$ ]]; then
WP_BRANCH=${WP_VERSION%\-*}
WP_TESTS_TAG="branches/$WP_BRANCH"
elif [[ $WP_VERSION =~ ^[0-9]+\.[0-9]+$ ]]; then
WP_TESTS_TAG="branches/$WP_VERSION"
elif [[ $WP_VERSION =~ [0-9]+\.[0-9]+\.[0-9]+ ]]; then
if [[ $WP_VERSION =~ [0-9]+\.[0-9]+\.[0] ]]; then
# version x.x.0 means the first release of the major version, so strip off the .0 and download version x.x
WP_TESTS_TAG="tags/${WP_VERSION%??}"
else
WP_TESTS_TAG="tags/$WP_VERSION"
fi
elif [[ $WP_VERSION == 'nightly' || $WP_VERSION == 'trunk' ]]; then
WP_TESTS_TAG="trunk"
else
# http serves a single offer, whereas https serves multiple. we only want one
download http://api.wordpress.org/core/version-check/1.7/ /tmp/wp-latest.json
grep '[0-9]+\.[0-9]+(\.[0-9]+)?' /tmp/wp-latest.json
LATEST_VERSION=$(grep -o '"version":"[^"]*' /tmp/wp-latest.json | sed 's/"version":"//')
if [[ -z "$LATEST_VERSION" ]]; then
echo "Latest WordPress version could not be found"
exit 1
fi
WP_TESTS_TAG="tags/$LATEST_VERSION"
fi
set -ex
install_wp() {
if [ -d $WP_CORE_DIR ]; then
return;
fi
mkdir -p $WP_CORE_DIR
if [[ $WP_VERSION == 'nightly' || $WP_VERSION == 'trunk' ]]; then
mkdir -p $TMPDIR/wordpress-nightly
download https://wordpress.org/nightly-builds/wordpress-latest.zip $TMPDIR/wordpress-nightly/wordpress-nightly.zip
unzip -q $TMPDIR/wordpress-nightly/wordpress-nightly.zip -d $TMPDIR/wordpress-nightly/
mv $TMPDIR/wordpress-nightly/wordpress/* $WP_CORE_DIR
else
if [ $WP_VERSION == 'latest' ]; then
local ARCHIVE_NAME='latest'
elif [[ $WP_VERSION =~ [0-9]+\.[0-9]+ ]]; then
# https serves multiple offers, whereas http serves single.
download https://api.wordpress.org/core/version-check/1.7/ $TMPDIR/wp-latest.json
if [[ $WP_VERSION =~ [0-9]+\.[0-9]+\.[0] ]]; then
# version x.x.0 means the first release of the major version, so strip off the .0 and download version x.x
LATEST_VERSION=${WP_VERSION%??}
else
# otherwise, scan the releases and get the most up to date minor version of the major release
local VERSION_ESCAPED=`echo $WP_VERSION | sed 's/\./\\\\./g'`
LATEST_VERSION=$(grep -o '"version":"'$VERSION_ESCAPED'[^"]*' $TMPDIR/wp-latest.json | sed 's/"version":"//' | head -1)
fi
if [[ -z "$LATEST_VERSION" ]]; then
local ARCHIVE_NAME="wordpress-$WP_VERSION"
else
local ARCHIVE_NAME="wordpress-$LATEST_VERSION"
fi
else
local ARCHIVE_NAME="wordpress-$WP_VERSION"
fi
download https://wordpress.org/${ARCHIVE_NAME}.tar.gz $TMPDIR/wordpress.tar.gz
tar --strip-components=1 -zxmf $TMPDIR/wordpress.tar.gz -C $WP_CORE_DIR
fi
download https://raw.github.com/markoheijnen/wp-mysqli/master/db.php $WP_CORE_DIR/wp-content/db.php
}
install_db() {
if [ ${SKIP_DB_CREATE} = "true" ]; then
return 0
fi
# parse DB_HOST for port or socket references
local PARTS=(${DB_HOST//\:/ })
local DB_HOSTNAME=${PARTS[0]};
local DB_SOCK_OR_PORT=${PARTS[1]};
local EXTRA=""
if ! [ -z $DB_HOSTNAME ] ; then
if [ $(echo $DB_SOCK_OR_PORT | grep -e '^[0-9]\{1,\}$') ]; then
EXTRA=" --host=$DB_HOSTNAME --port=$DB_SOCK_OR_PORT --protocol=tcp"
elif ! [ -z $DB_SOCK_OR_PORT ] ; then
EXTRA=" --socket=$DB_SOCK_OR_PORT"
elif ! [ -z $DB_HOSTNAME ] ; then
EXTRA=" --host=$DB_HOSTNAME --protocol=tcp"
fi
fi
# create database
RESULT=`mysql -u $DB_USER --password="$DB_PASS" --skip-column-names -e "SHOW DATABASES LIKE '$DB_NAME'"$EXTRA`
if [ "$RESULT" != $DB_NAME ]; then
mysqladmin create $DB_NAME --user="$DB_USER" --password="$DB_PASS"$EXTRA
fi
}
configure_wordpress() {
cd $WP_CORE_DIR
wp config create --dbname="$DB_NAME" --dbuser="$DB_USER" --dbpass="$DB_PASS" --dbhost="$DB_HOST" --skip-check --force=true
wp core install --url=wp.test --title="WPGatsby Tests" --admin_user=admin --admin_password=password --admin_email=admin@wp.test
wp rewrite structure '/%year%/%monthnum%/%postname%/'
}
setup_wpgraphql() {
if [ ! -d $WP_CORE_DIR/wp-content/plugins/wp-graphql ]; then
echo "Cloning WPGraphQL"
wp plugin install https://github.com/wp-graphql/wp-graphql/releases/download/${WPGRAPHQL_VERSION}/wp-graphql.zip
fi
echo "Activating WPGraphQL"
wp plugin activate wp-graphql
}
setup_plugin() {
# Add this repo as a plugin to the repo
if [ ! -d $WP_CORE_DIR/wp-content/plugins/wp-gatsby ]; then
ln -s $PLUGIN_DIR $WP_CORE_DIR/wp-content/plugins/wp-gatsby
cd $WP_CORE_DIR/wp-content/plugins
pwd
ls
fi
cd $WP_CORE_DIR
wp plugin list
# activate the plugin
wp plugin activate wp-gatsby
# Flush the permalinks
wp rewrite flush
# Export the db for codeception to use
wp db export $PLUGIN_DIR/tests/_data/dump.sql
}
install_wp
install_db
configure_wordpress
setup_wpgraphql
setup_plugin
================================================
FILE: bin/run-docker.sh
================================================
#!/usr/bin/env bash
set -eu
##
# Use this script through Composer scripts in the package.json.
# To quickly build and run the docker-compose scripts for an app or automated testing
# run the command below after run `composer install --no-dev` with the respectively
# flag for what you need.
##
print_usage_instructions() {
echo "Usage: composer build-and-run -- [-a|-t]";
echo " -a Spin up a WordPress installation.";
echo " -t Run the automated tests.";
exit 1
}
if [ -z "$1" ]; then
print_usage_instructions
fi
env_file=".env.dist";
subcommand=$1; shift
case "$subcommand" in
"build" )
while getopts ":at" opt; do
case ${opt} in
a )
docker build -f docker/app.Dockerfile \
-t wpgatsby-app:latest \
--build-arg WP_VERSION=${WP_VERSION-5.4} \
--build-arg PHP_VERSION=${PHP_VERSION-7.4} \
.
;;
t )
docker build -f docker/app.Dockerfile \
-t wpgatsby-app:latest \
--build-arg WP_VERSION=${WP_VERSION-5.4} \
--build-arg PHP_VERSION=${PHP_VERSION-7.4} \
.
docker build -f docker/testing.Dockerfile \
-t wpgatsby-testing:latest \
--build-arg USE_XDEBUG=${USE_XDEBUG-} \
.
;;
\? ) print_usage_instructions;;
* ) print_usage_instructions;;
esac
done
shift $((OPTIND -1))
;;
"run" )
while getopts "e:at" opt; do
case ${opt} in
e )
env_file=${OPTARG};
if [ ! -f $env_file ]; then
echo "No file found at $env_file"
fi
;;
a ) docker-compose up --scale testing=0;;
t )
source ${env_file}
docker-compose run --rm \
-e SUITES=${SUITES-wpunit} \
-e COVERAGE=${COVERAGE-} \
-e DEBUG=${DEBUG-} \
-e SKIP_TESTS_CLEANUP=${SKIP_TESTS_CLEANUP-} \
-e LOWEST=${LOWEST-} \
testing --scale app=0
;;
\? ) print_usage_instructions;;
* ) print_usage_instructions;;
esac
done
shift $((OPTIND -1))
;;
\? ) print_usage_instructions;;
* ) print_usage_instructions;;
esac
================================================
FILE: codeception.dist.yml
================================================
paths:
tests: '%TESTS_DIR%'
output: '%TESTS_OUTPUT%'
data: '%TESTS_DATA%'
support: '%TESTS_SUPPORT%'
envs: '%TESTS_ENVS%'
params:
- env
- .env.dist
actor_suffix: Tester
settings:
colors: true
memory_limit: 1024M
coverage:
enabled: true
remote: false
c3_url: '%WP_URL%/wp-content/plugins/wp-gatsby/wp-gatsby.php'
include:
- includes/*
exclude:
- wp-gatsby.php
- vendor/*
show_only_summary: false
extensions:
enabled:
- Codeception\Extension\RunFailed
commands:
- Codeception\Command\GenerateWPUnit
- Codeception\Command\GenerateWPRestApi
- Codeception\Command\GenerateWPRestController
- Codeception\Command\GenerateWPRestPostTypeController
- Codeception\Command\GenerateWPAjax
- Codeception\Command\GenerateWPCanonical
- Codeception\Command\GenerateWPXMLRPC
modules:
config:
WPDb:
dsn: 'mysql:host=%DB_HOST%;dbname=%DB_NAME%'
user: '%DB_USER%'
password: '%DB_PASSWORD%'
populator: 'mysql -u $user -p$password -h $host $dbname < $dump'
dump: 'tests/_data/dump.sql'
populate: false
cleanup: true
waitlock: 0
url: '%WP_URL%'
urlReplacement: true
tablePrefix: '%WP_TABLE_PREFIX%'
WPBrowser:
url: '%WP_URL%'
wpRootFolder: '%WP_ROOT_FOLDER%'
adminUsername: '%ADMIN_USERNAME%'
adminPassword: '%ADMIN_PASSWORD%'
adminPath: '/wp-admin'
cookies: false
REST:
depends: WPBrowser
url: '%WP_URL%'
WPFilesystem:
wpRootFolder: '%WP_ROOT_FOLDER%'
plugins: '/wp-content/plugins'
mu-plugins: '/wp-content/mu-plugins'
themes: '/wp-content/themes'
uploads: '/wp-content/uploads'
WPLoader:
wpRootFolder: '%WP_ROOT_FOLDER%'
dbName: '%DB_NAME%'
dbHost: '%DB_HOST%'
dbUser: '%DB_USER%'
dbPassword: '%DB_PASSWORD%'
tablePrefix: '%WP_TABLE_PREFIX%'
domain: '%WP_DOMAIN%'
adminEmail: '%ADMIN_EMAIL%'
title: 'Test'
plugins:
- wp-graphql/wp-graphql.php
- wp-gatsby/wp-gatsby.php
activatePlugins:
- wp-graphql/wp-graphql.php
- wp-gatsby/wp-gatsby.php
configFile: 'tests/_data/config.php'
================================================
FILE: composer.json
================================================
{
"name": "gatsbyjs/wp-gatsby",
"description": "Optimize your WordPress site as a source for Gatsby site(s)",
"type": "wordpress-plugin",
"license": "GPL-3.0-or-later",
"authors": [
{
"name": "GatsbyJS"
},
{
"name": "Jason Bahl"
},
{
"name": "Tyler Barnes"
}
],
"autoload": {
"psr-4": {
"WPGatsby\\": "src/"
}
},
"autoload-dev": {
"files": [
"tests/_data/config.php"
]
},
"config": {
"optimize-autoloader": true,
"process-timeout": 0
},
"require": {
"php": "^7.3||^8.0",
"firebase/php-jwt": "^5.2",
"ircmaxell/random-lib": "^1.2",
"composer/semver": "^1.5"
},
"require-dev": {
"lucatume/wp-browser": "^2.4",
"codeception/module-asserts": "^1.0",
"codeception/module-phpbrowser": "^1.0",
"codeception/module-webdriver": "^1.0",
"codeception/module-db": "^1.0",
"codeception/module-filesystem": "^1.0",
"codeception/module-cli": "^1.0",
"codeception/util-universalframework": "^1.0",
"dealerdirect/phpcodesniffer-composer-installer": "^0.7.1",
"wp-coding-standards/wpcs": "2.1.1",
"phpcompatibility/phpcompatibility-wp": "2.1.0",
"squizlabs/php_codesniffer": "3.5.4",
"codeception/module-rest": "^1.2",
"wp-graphql/wp-graphql-testcase": "^1.0",
"phpunit/phpunit": "9.4.1"
},
"scripts": {
"install-test-env": "bash bin/install-test-env.sh",
"docker-build": "bash bin/run-docker.sh build",
"docker-run": "bash bin/run-docker.sh run",
"docker-destroy": "docker-compose down",
"build-and-run": [
"@docker-build",
"@docker-run"
],
"build-app": "@docker-build -a",
"build-test": "@docker-build -t",
"run-app": "@docker-run -a",
"run-test": "@docker-run -t",
"lint": "vendor/bin/phpcs",
"phpcs-i": [
"php ./vendor/bin/phpcs -i"
],
"check-cs": [
"php ./vendor/bin/phpcs src"
],
"fix-cs": [
"php ./vendor/bin/phpcbf src"
]
},
"support": {
"issues": "https://github.com/gatsbyjs/wp-gatsby/issues",
"source": "https://github.com/gatsbyjs/wp-gatsby"
}
}
================================================
FILE: docker/app.Dockerfile
================================================
###############################################################################
# Pre-configured WordPress Installation w/ WPGraphQL, WPGatsby #
# For testing only, use in production not recommended. #
###############################################################################
ARG WP_VERSION
ARG PHP_VERSION
FROM wordpress:${WP_VERSION}-php${PHP_VERSION}-apache
ENV WP_VERSION=${WP_VERSION}
ENV PHP_VERSION=${PHP_VERSION}
LABEL author=jasonbahl
LABEL author_uri=https://github.com/jasonbahl
SHELL [ "/bin/bash", "-c" ]
# Install system packages
RUN apt-get update && \
apt-get -y install \
# CircleCI depedencies
git \
ssh \
tar \
gzip \
wget \
mariadb-client
# Install Dockerize
ENV DOCKERIZE_VERSION v0.6.1
RUN wget https://github.com/jwilder/dockerize/releases/download/$DOCKERIZE_VERSION/dockerize-linux-amd64-$DOCKERIZE_VERSION.tar.gz \
&& tar -C /usr/local/bin -xzvf dockerize-linux-amd64-$DOCKERIZE_VERSION.tar.gz \
&& rm dockerize-linux-amd64-$DOCKERIZE_VERSION.tar.gz
# Install WP-CLI
RUN curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar \
&& chmod +x wp-cli.phar \
&& mv wp-cli.phar /usr/local/bin/wp
# Set project environmental variables
ENV WP_ROOT_FOLDER="/var/www/html"
ENV WORDPRESS_DB_HOST=${DB_HOST}
ENV WORDPRESS_DB_USER=${DB_USER}
ENV WORDPRESS_DB_PASSWORD=${DB_PASSWORD}
ENV WORDPRESS_DB_NAME=${DB_NAME}
ENV PLUGINS_DIR="${WP_ROOT_FOLDER}/wp-content/plugins"
ENV PROJECT_DIR="${PLUGINS_DIR}/wp-gatsby"
# Remove exec statement from base entrypoint script.
RUN sed -i '$d' /usr/local/bin/docker-entrypoint.sh
# Set up Apache
RUN echo 'ServerName localhost' >> /etc/apache2/apache2.conf
# Set up entrypoint
WORKDIR /var/www/html
COPY docker/app.entrypoint.sh /usr/local/bin/app-entrypoint.sh
RUN chmod 755 /usr/local/bin/app-entrypoint.sh
ENTRYPOINT ["app-entrypoint.sh"]
CMD ["apache2-foreground"]
================================================
FILE: docker/app.entrypoint.sh
================================================
#!/bin/bash
# Run WordPress docker entrypoint.
. docker-entrypoint.sh 'apache2'
set +u
# Ensure mysql is loaded
dockerize -wait tcp://${DB_HOST}:${DB_HOST_PORT:-3306} -timeout 1m
# Config WordPress
if [ ! -f "${WP_ROOT_FOLDER}/wp-config.php" ]; then
wp config create \
--path="${WP_ROOT_FOLDER}" \
--dbname="${DB_NAME}" \
--dbuser="${DB_USER}" \
--dbpass="${DB_PASSWORD}" \
--dbhost="${DB_HOST}" \
--dbprefix="${WP_TABLE_PREFIX}" \
--skip-check \
--quiet \
--allow-root
fi
# Install WP if not yet installed
if ! $( wp core is-installed --allow-root ); then
wp core install \
--path="${WP_ROOT_FOLDER}" \
--url="${WP_URL}" \
--title='Test' \
--admin_user="${ADMIN_USERNAME}" \
--admin_password="${ADMIN_PASSWORD}" \
--admin_email="${ADMIN_EMAIL}" \
--allow-root
fi
# Install and activate WPGraphQL
if [ ! -f "${PLUGINS_DIR}/wp-graphql/wp-graphql.php" ]; then
wp plugin install \
https://github.com/wp-graphql/wp-graphql/archive/${WPGRAPHQL_VERSION}.zip \
--activate --allow-root
else
wp plugin activate wp-graphql --allow-root
fi
# Install and activate WPGatsby
wp plugin activate wp-gatsby --allow-root
# Set pretty permalinks.
wp rewrite structure '/%year%/%monthnum%/%postname%/' --allow-root
wp db export "${PROJECT_DIR}/tests/_data/dump.sql" --allow-root
exec "$@"
================================================
FILE: docker/testing.Dockerfile
================================================
############################################################################
# Container for running Codeception tests on a WooGraphQL Docker instance. #
############################################################################
# Using the 'DESIRED_' prefix to avoid confusion with environment variables of the same name.
FROM wpgatsby-app:latest
LABEL author=jasonbahl
LABEL author_uri=https://github.com/jasonbahl
SHELL [ "/bin/bash", "-c" ]
# Redeclare ARGs and set as environmental variables for reuse.
ARG USE_XDEBUG
ENV USING_XDEBUG=${USE_XDEBUG}
# Install php extensions
RUN docker-php-ext-install pdo_mysql
# Install composer
ENV COMPOSER_ALLOW_SUPERUSER=1
RUN curl -sS https://getcomposer.org/installer | php -- \
--filename=composer \
--install-dir=/usr/local/bin
# Add composer global binaries to PATH
ENV PATH "$PATH:~/.composer/vendor/bin"
# Configure php
RUN echo "date.timezone = UTC" >> /usr/local/etc/php/php.ini
# Remove exec statement from base entrypoint script.
RUN sed -i '$d' /usr/local/bin/app-entrypoint.sh
# Set up entrypoint
WORKDIR /var/www/html/wp-content/plugins/wp-gatsby
COPY docker/testing.entrypoint.sh /usr/local/bin/testing-entrypoint.sh
RUN chmod 755 /usr/local/bin/testing-entrypoint.sh
ENTRYPOINT ["testing-entrypoint.sh"]
================================================
FILE: docker/testing.entrypoint.sh
================================================
#!/bin/bash
# Processes parameters and runs Codeception.
run_tests() {
echo "Running Tests"
if [[ -n "$COVERAGE" ]]; then
local coverage="--coverage --coverage-xml"
fi
if [[ -n "$DEBUG" ]]; then
local debug="--debug"
fi
local suites=${1:-" ;"}
IFS=';' read -ra target_suites <<< "$suites"
for suite in "${target_suites[@]}"; do
vendor/bin/codecept run -c codeception.dist.yml ${suite} ${coverage:-} ${debug:-} --no-exit
done
}
# Exits with a status of 0 (true) if provided version number is higher than proceeding numbers.
version_gt() {
test "$(printf '%s\n' "$@" | sort -V | head -n 1)" != "$1";
}
write_htaccess() {
echo "<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
SetEnvIf Authorization \"(.*)\" HTTP_AUTHORIZATION=\$1
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>" >> ${WP_ROOT_FOLDER}/.htaccess
}
# Move to WordPress root folder
workdir="$PWD"
echo "Moving to WordPress root directory."
cd ${WP_ROOT_FOLDER}
# Run app entrypoint script.
. app-entrypoint.sh
write_htaccess
# Return to PWD.
echo "Moving back to project working directory."
cd ${workdir}
# Ensure Apache is running
service apache2 start
# Ensure everything is loaded
dockerize \
-wait tcp://${DB_HOST}:${DB_HOST_PORT:-3306} \
-wait ${WP_URL} \
-timeout 1m
# Download c3 for testing.
if [ ! -f "$PROJECT_DIR/c3.php" ]; then
echo "Downloading Codeception's c3.php"
curl -L 'https://raw.github.com/Codeception/c3/2.0/c3.php' > "$PROJECT_DIR/c3.php"
fi
if [[ -n "$LOWEST" ]]; then
PREFER_LOWEST="--prefer-source"
fi
# Install dependencies
COMPOSER_MEMORY_LIMIT=-1 composer update --prefer-source ${PREFER_LOWEST}
COMPOSER_MEMORY_LIMIT=-1 composer install --prefer-source --no-interaction
# Install pcov/clobber if PHP7.1+
if version_gt $PHP_VERSION 7.0 && [[ -n "$COVERAGE" ]] && [[ -z "$USING_XDEBUG" ]]; then
echo "Installing pcov/clobber"
COMPOSER_MEMORY_LIMIT=-1 composer require --dev pcov/clobber
vendor/bin/pcov clobber
elif [[ -n "$COVERAGE" ]]; then
echo "Using XDebug for codecoverage"
fi
# Set output permission
echo "Setting Codeception output directory permissions"
chmod 777 ${TESTS_OUTPUT}
# Run tests
run_tests ${SUITES}
# Remove c3.php
if [ -f "$PROJECT_DIR/c3.php" ] && [ "$SKIP_TESTS_CLEANUP" != "1" ]; then
echo "Removing Codeception's c3.php"
rm -rf "$PROJECT_DIR/c3.php"
fi
# Clean coverage.xml and clean up PCOV configurations.
if [ -f "${TESTS_OUTPUT}/coverage.xml" ] && [[ -n "$COVERAGE" ]]; then
echo 'Cleaning coverage.xml for deployment'.
pattern="$PROJECT_DIR/"
sed -i "s~$pattern~~g" "$TESTS_OUTPUT"/coverage.xml
# Remove pcov/clobber
if version_gt $PHP_VERSION 7.0 && [[ -z "$SKIP_TESTS_CLEANUP" ]] && [[ -z "$USING_XDEBUG" ]]; then
echo 'Removing pcov/clobber.'
vendor/bin/pcov unclobber
COMPOSER_MEMORY_LIMIT=-1 composer remove --dev pcov/clobber
fi
fi
if [[ -z "$SKIP_TESTS_CLEANUP" ]]; then
echo 'Changing composer configuration in container.'
composer config --global discard-changes true
echo 'Removing devDependencies.'
composer install --no-dev -n
echo 'Removing composer.lock'
rm composer.lock
fi
# Set public test result files permissions.
if [ -n "$(ls "$TESTS_OUTPUT")" ]; then
echo 'Setting result files permissions'.
chmod 777 -R "$TESTS_OUTPUT"/*
fi
# Check results and exit accordingly.
if [ -f "${TESTS_OUTPUT}/failed" ]; then
echo "Uh oh, some went wrong."
exit 1
else
echo "Woohoo! It's working!"
exit 0
fi
================================================
FILE: docker-compose.yml
================================================
version: '3.3'
services:
app:
depends_on:
- app_db
image: wpgatsby-app:latest
volumes:
- '.:/var/www/html/wp-content/plugins/wp-gatsby'
- './.log/app:/var/log/apache2'
environment:
WP_URL: 'http://localhost:8091'
WP_DOMAIN: 'localhost:8091'
DB_HOST: app_db
DB_NAME: wordpress
DB_USER: wordpress
DB_PASSWORD: wordpress
WP_DOMAIN: localhost
ADMIN_EMAIL: admin@example.com
ADMIN_USERNAME: admin
ADMIN_PASSWORD: password
INCLUDE_WPGRAPHIQL: 1
IMPORT_WC_PRODUCTS: 1
STRIPE_GATEWAY: 1
ports:
- '8091:80'
networks:
local:
app_db:
image: mysql:5.7
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: wordpress
MYSQL_USER: wordpress
MYSQL_PASSWORD: wordpress
ports:
- '3306'
networks:
testing:
local:
testing:
depends_on:
- app_db
image: wpgatsby-testing:latest
volumes:
- '.:/var/www/html/wp-content/plugins/wp-gatsby'
- './.log/testing:/var/log/apache2'
- './codeception.dist.yml:/var/www/html/wp-content/plugins/wp-gatsby/codeception.yml'
env_file: .env.dist
environment:
XDEBUG_CONFIG: remote_host=host.docker.internal remote_port=9000 remote_enable=1
DB_HOST: app_db
WP_URL: 'http://localhost'
WP_DOMAIN: 'localhost'
STRIPE_GATEWAY: 1
networks:
testing:
networks:
local:
testing:
================================================
FILE: docs/action-monitor.md
================================================
# Activity Monitor
WPGatsby monitors activity that occurs in your WordPress site and notifies your Gatsby site
of the changes, allowing your Gatsby site to stay in sync with your WordPress site.
This document covers how WPGatsby tracks activity, what activity is tracked and how to customize the
activity tracking.
## How does WPGatsby track activity?
WPGatsby listens for CRUD (create, read, update and delete) actions that occur in WordPress, such as
publishing or deleting a post, updating menus, and more.
WPGatsby uses common WordPress actions to capture the objects that are changing, and stores records
of the actions in a custom post type named "action_monitor".
Whenever tracked activity is detected and an "action_monitor" action is created, a webhook is sent
to the Gatsby site that is configured in the [GatsbyJS settings page](./settings.md), allowing Gatsby to rebuild
pages that are affected by the changed data.
## What activity does WPGatsby track?
WPGatsby tracks when public data is changed in WordPress. Private data, such as draft posts, or users
with no published content, is not tracked (except for during previews but that data is private and deleted as soon as the preview completes).
Below you can read more details about all the data that WPGatsby tracks.
Additionally, you can check out [the tests](https://github.com/gatsbyjs/wp-gatsby/blob/master/tests/wpunit/ActionMonitorTest.php)
to see all the data that is tracked and the expected outcomes of different actions in WordPress.
### Advanced Custom Fields
Whenever ACF Field Groups are updated or deleted (using the ACF User Interface), WPGatsby logs an
action monitor action to notify Gatsby that the WPGraphQL Schema _may_ have changed.
#### Activity Tracked for ACF
- Update Field Group
- Delete Field Group
### Media
Whenever Media Items are uploaded, edited or deleted in the WordPress Media Library, WPGatsby logs
an action monitor action to notify Gatsby of the change.
#### Activity Tracked for Media
- Add Attachment
- Edit Attachment
- Delete Attachment
- Save Image Editor File
- Save Image File
### Menus
By default, Menus are considered private entities in WordPress. Once they are assinged to a Menu
Location, they become public. WPGatsby tracks activity related to public Menus and Menu Items.
Menus that are not assigned to Nav Menu Locations are not tracked, other than when they transition
from being not assigned a location to assigned a location, or the inverse.
#### Activity Tracked for Menus
- Update Nav Menu Locations
- Update Nav Menu
- Delete Nav Menu
- Update Nav Menu Item
- Add Nav Menu Item
### Posts (of any public post type, set to show in GraphQL)
Posts (and Pages and Custom Post Types) are typically pretty central to any WordPress site, and it's
important for Gatsby to know when they change.
WPGatsby tracks when posts are published (made public), and when published posts are edited or
deleted. Non-published posts are not tracked by WPGatsby. So changes can be made to draft posts, for
example and WPGatsby won't track that activity.
#### Activity Tracked for Posts
- Post Updated
- Transition Post Status
- Deleted Post
- Post Meta Added
- Post Meta Updated
- Post Meta Deleted
### Post Types (registered post types, not content of a post type)
WPGatsby caches the list of registered post types, and whenever it detects changes to the Post Type
registry, it logs an "action_monitor" action and notifies Gatsby of the change.
This allows Gatsby to update it's GraphQL Schema to reflect the changes in WPGraphQL.
#### Activity Tracked for Post Types
- Post Type registry changes
### Settings
The way WordPress stores settings is a bit of a blackbox. Many different things are stored in the
options table, so tracking changes to _all_ settings could be problematic. For example, tracking all
changes to all settings would cause WPGatsby to track transients. A transient changing would cause
Gatsby to fetch data from WordPress again, which could trigger further transient changes, and thus
could lead to an infinite loop.
So, instead of tracking updates to _all_ settings, WPGatsby only tracks specific settings that have
been configured to be "allowed" to be tracked.
WPGatsby provides an initial list of settings to track, and this list can be filtered (using the
`gatsby_action_monitor_should_track_option` filter) to disallow tracked settings, or allow tracking
of additional settings.
#### Activity Tracked for Settings
- Updated settings (based on filterable allow-list of settings to track)
### Taxonomies (registered taxonomies, not terms of a taxonomy)
WPGatsby caches the list of registered taxonomies, and whenever it detects changes to the Taxonomy
registry, it logs an "action_monitor" action and notifies Gatsby of the change.
This allows Gatsby to update it's GraphQL Schema to reflect the changes in WPGraphQL.
#### Activity Tracked for Taxonomies
- Custom Taxonomy registry changes
### Terms (of any public taxonomy, set to show in GraphQL)
Terms are tracked when they are created, updated or deleted.
#### Activity Tracked for Terms
- Term Created
- Term Updated
- Term Deleted
- Term Meta Added
- Term Meta Updated
- Term Meta Deleted
### Users (must be a published author of public content)
In WordPress, users are considered private by default. But once a user publishes content of a public
post type, that user becomes a public entity, as it then has an author archive page, REST API
endpoint, etc. WPGatsby tracks activity of these public users. Users with no published content are
not tracked.
#### Activity Tracked for Users
- Profile Update
- Delete User
- Update User Meta
- Add User Meta
- Delete User Meta
- Publish Post by author
## How to customize WPGatsby Activity Monitoring
You may find that you want to ignore certain actions from being tracked, or more likely you may want
to track additional actions that are not tracked by default.
Below you can learn more about both of these cases:
### Skip tracking of an action
If you'd like to prevent an action from being logged, you can use the `gatsby_pre_log_action_monitor_action` filter.
This filter will get passed the array of data to be logged.
If the filter returns `false`, the action will not be logged. If it returns anything else, the action
will proceed to be logged.
Example:
The example below would ignore logging actions for Post with ID `15`.
```php
add_filter( 'gatsby_pre_log_action_monitor_action', function( $null, $log_data ) {
if ( 'Post' === $log_data['graphql_single_name'] && 15 === $log_data['node_id'] ) {
return false;
}
return $null;
}, 10, 2 );
```
### Tracking a custom action
If you have a plugin that stores data in non-traditional ways, such as in a Custom Database Table,
you may need to track custom actions to tell Gatsby that something has changed.
You can do this by extending the `Monitor` class, and registering it with the `gatsby_action_monitors` filter.
**Note**: All of the fields passed to the `log_action` method below are required.
```php
/**
* Class - MyCustomActionMonitor
*/
class MyCustomActionMonitor extends \WPGatsby\ActionMonitor\Monitors\Monitor {
/**
* Initialize the custom tracker.
*/
public function init() {
// Hook into the custom action you want to log.
add_action( 'my_custom_action', [ $this, 'custom_action_callback' ] );
}
/**
* Callback for custom action.
*/
public function custom_action_callback( $your_custom_object ) {
/**
* Log an action to Action Monitor.
*
* This will create an entry in the `action_monitor` post type
* and will notify Gatsby Source WordPress about the activity.
*/
$this->monitor->log_action( [
'action_type' => 'CREATE',
'title' => $your_custom_object->title,
'graphql_single_name' => 'MyCustomType',
'graphql_plural_name' => 'MyCustomTypes',
'status' => 'publish',
'relay_id' => base64_encode( 'MyCustomType:' . $your_custom_object->ID ),
'node_id' => $your_custom_object->ID,
] );
}
}
add_filter( 'gatsby_action_monitors', function( array $monitors, \WPGatsby\ActionMonitor\ActionMonitor $action_monitor) {
$monitors['MyCustomActionMonitor'] = new MyCustomActionMonitor( $action_monitor );
return $monitors;
}, 10, 2 );
```
================================================
FILE: docs/running-tests.md
================================================
# Running Tests
This document provides information on running tests locally.
There are 2 options:
- [Running tests with your own local environment](#local-tests) (faster, more room for environmental inconsistencies)
- [Running tests with Docker](#docker-tests) (slower, more consistent)
<span id="local-tests"></span>
## Running Tests with your own local environment
Below are instructions for running tests with your own local environment. Running tests this way is more flexible and faster than running tests with Docker. But, there's a chance your local environment (PHP versions, MySQL versions, etc) could change (as you work on other projects, for example), and that could cause problems with the test suite.
If you follow the instructions below, you should be able to run tests locally with your own local environment.
### Prerequisties
You must have the following available locally:
- **PHP**
- **MySQL** (or equivalent such as MariaDB)
- **[Composer](https://getcomposer.org/doc/00-intro.md)**
- **[WP-CLI](https://wp-cli.org/)** installed as well as terminal/shell/command-line access.
### Codeception & the wp-browser module
**WPGraphQL** and **WPGatsby** both use the **[Codeception](https://codeception.com/)** testing framework alongside the **[wp-browser](https://wpbrowser.wptestkit.dev/)** module created by [Luca Tumedei](https://www.theaveragedev.com/) for running the automated test suite. We'll be using Codeception scaffolding to generate all the tedious test code, but this will not be an in-depth guide on either of these libraries. It's not required to process with this tutorial, but it's highly recommended that after finishing this tutorial you take a look at the documentation for both.
- **[Codeception](https://codeception.com/docs/01-Introduction)**
- **[wp-browser](https://wpbrowser.wptestkit.dev/)**
1. Start by cloning **[WPGatsby](https://github.com/wp-gatsby/wp-gatsby)**.
2. Open your terminal.
3. Copy the `.env.dist` to `.env` by execute the following in your terminal in the **WPGatsby** root directory.
```
cp .env.dist .env
```
4. Open the .env and update the highlighted environmental variables to match your machine setup.

5. Last thing to do is run the WordPress testing environment install script in the terminal.
```
composer install-test-env
```
This will create and configure a WordPress installation in a temporary directory for the purpose of testing.
### Setting up Codeception
Now that we have setup our testing environment, let's run the tests. To do this we will need to install the **Codeception** and the rest of our **devDependencies**
1. First run `composer install` in the terminal.
2. Next copy the `codeception.dist.yml` to `codeception.yml`
```
cp codeception.dist.yml codeception.yml
```
3. Open `codeception.yml` and make the following changes.


Now you are ready to run the tests.
### Running the tests
Now your're ready to rum the tests. There is a small issue you may have with our testing environment. The WordPress installation we created doesn't support **end-to-end (*e2e*)** testing, however this won't be a problem. **WPGraphQL** is an API and most of the time you can get away with just ensuring that your query works, and **WPGraphQL** provides a few functions that will allow us to do just that.
Let's get started by running all the unit tests. Back in your terminal run the following:
```
vendor/bin/codecept run wpunit
```
If everything is how it should be you should get all passing tests.

You can also run individual test suites by specifying the path:
```
vendor/bin/codecept run tests/wpunit/ActionMonitorTest.php
```
Or even run a single test by specifying the specific test:
```
vendor/bin/codecept run tests/wpunit/ActionMonitorTest.php:testActionMonitorQueryIsValid
```
<span id="docker-tests"></span>
## Running Tests with Docker
The automated tests that run in the Github workflows use Docker. This ensures the environment is always what we expect. No risk of inconsistencies with PHP versions, MySQL versions, etc.
The trade off (at least as of right now) is that you must run the entire test suite instead of having the ability to run individual tests. And you must wait for the Docker environment to boot up. Overall, this is slower and less flexible than running tests with your own local environment, but it's more consistent.
To run tests with Docker, run the following commands:
- `composer install`: This will install the composer dependencies needed for testing
- `composer build-test`: This will build a Docker environment. This can take some time, especially the first time you run it.
- `composer run-test`: This will run the tests in the Docker environment.
================================================
FILE: lib/wp-settings-api.php
================================================
<?php
/**
* weDevs Settings API wrapper class
*
* @version 1.3 (27-Sep-2016)
*
* @author Tareq Hasan <tareq@weDevs.com>
* @link https://tareq.co Tareq Hasan
* @link https://github.com/tareq1988/wordpress-settings-api-class
* @example example/oop-example.php How to use the class
*/
if ( ! class_exists( 'WPGraphQL_Settings_API' ) ) :
class WPGraphQL_Settings_API {
/**
* settings sections array
*
* @var array
*/
protected $settings_sections = array();
/**
* Settings fields array
*
* @var array
*/
protected $settings_fields = array();
public function __construct() {
add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) );
}
/**
* Enqueue scripts and styles
*/
function admin_enqueue_scripts() {
wp_enqueue_style( 'wp-color-picker' );
wp_enqueue_media();
wp_enqueue_script( 'wp-color-picker' );
wp_enqueue_script( 'jquery' );
}
/**
* Set settings sections
*
* @param array $sections setting sections array
*/
function set_sections( $sections ) {
$this->settings_sections = $sections;
return $this;
}
/**
* Add a single section
*
* @param array $section
*/
function add_section( $section ) {
$this->settings_sections[] = $section;
return $this;
}
/**
* Set settings fields
*
* @param array $fields settings fields array
*/
function set_fields( $fields ) {
$this->settings_fields = $fields;
return $this;
}
function add_field( $section, $field ) {
$defaults = array(
'name' => '',
'label' => '',
'desc' => '',
'type' => 'text'
);
$arg = wp_parse_args( $field, $defaults );
$this->settings_fields[ $section ][] = $arg;
return $this;
}
/**
* Initialize and registers the settings sections and fileds to WordPress
*
* Usually this should be called at `admin_init` hook.
*
* This function gets the initiated settings sections and fields. Then
* registers them to WordPress and ready for use.
*/
function admin_init() {
//register settings sections
foreach ( $this->settings_sections as $section ) {
if ( false == get_option( $section['id'] ) ) {
add_option( $section['id'] );
}
if ( isset( $section['desc'] ) && ! empty( $section['desc'] ) ) {
$section['desc'] = '<div class="inside">' . $section['desc'] . '</div>';
$callback = function() use ( $section ) {
echo str_replace( '"', '\"', $section['desc'] );
};
} else if ( isset( $section['callback'] ) ) {
$callback = $section['callback'];
} else {
$callback = null;
}
add_settings_section( $section['id'], $section['title'], $callback, $section['id'] );
}
//register settings fields
foreach ( $this->settings_fields as $section => $field ) {
foreach ( $field as $option ) {
$name = $option['name'];
$type = isset( $option['type'] ) ? $option['type'] : 'text';
$label = isset( $option['label'] ) ? $option['label'] : '';
$callback = isset( $option['callback'] ) ? $option['callback'] : array(
$this,
'callback_' . $type
);
$args = array(
'id' => $name,
'class' => isset( $option['class'] ) ? $option['class'] : $name,
'label_for' => "{$section}[{$name}]",
'desc' => isset( $option['desc'] ) ? $option['desc'] : '',
'name' => $label,
'section' => $section,
'size' => isset( $option['size'] ) ? $option['size'] : null,
'options' => isset( $option['options'] ) ? $option['options'] : '',
'std' => isset( $option['default'] ) ? $option['default'] : '',
'sanitize_callback' => isset( $option['sanitize_callback'] ) ? $option['sanitize_callback'] : '',
'type' => $type,
'placeholder' => isset( $option['placeholder'] ) ? $option['placeholder'] : '',
'min' => isset( $option['min'] ) ? $option['min'] : '',
'max' => isset( $option['max'] ) ? $option['max'] : '',
'step' => isset( $option['step'] ) ? $option['step'] : '',
);
add_settings_field( "{$section}[{$name}]", $label, $callback, $section, $section, $args );
}
}
// creates our settings in the options table
foreach ( $this->settings_sections as $section ) {
register_setting( $section['id'], $section['id'], array(
$this,
'sanitize_options'
) );
}
}
/**
* Get field description for display
*
* @param array $args settings field args
*/
public function get_field_description( $args ) {
if ( ! empty( $args['desc'] ) ) {
$desc = sprintf( '<p class="description">%s</p>', $args['desc'] );
} else {
$desc = '';
}
return $desc;
}
/**
* Displays a text field for a settings field
*
* @param array $args settings field args
*/
function callback_text( $args ) {
$value = esc_attr( $this->get_option( $args['id'], $args['section'], $args['std'] ) );
$size = isset( $args['size'] ) && ! is_null( $args['size'] ) ? $args['size'] : 'regular';
$type = isset( $args['type'] ) ? $args['type'] : 'text';
$placeholder = empty( $args['placeholder'] ) ? '' : ' placeholder="' . $args['placeholder'] . '"';
$html = sprintf( '<input type="%1$s" class="%2$s-text" id="%3$s[%4$s]" name="%3$s[%4$s]" value="%5$s"%6$s/>', $type, $size, $args['section'], $args['id'], $value, $placeholder );
$html .= $this->get_field_description( $args );
echo $html;
}
/**
* Displays a url field for a settings field
*
* @param array $args settings field args
*/
function callback_url( $args ) {
$this->callback_text( $args );
}
/**
* Displays a number field for a settings field
*
* @param array $args settings field args
*/
function callback_number( $args ) {
$value = esc_attr( $this->get_option( $args['id'], $args['section'], $args['std'] ) );
$size = isset( $args['size'] ) && ! is_null( $args['size'] ) ? $args['size'] : 'regular';
$type = isset( $args['type'] ) ? $args['type'] : 'number';
$placeholder = empty( $args['placeholder'] ) ? '' : ' placeholder="' . $args['placeholder'] . '"';
$min = ( $args['min'] == '' ) ? '' : ' min="' . $args['min'] . '"';
$max = ( $args['max'] == '' ) ? '' : ' max="' . $args['max'] . '"';
$step = ( $args['step'] == '' ) ? '' : ' step="' . $args['step'] . '"';
$html = sprintf( '<input type="%1$s" class="%2$s-number" id="%3$s[%4$s]" name="%3$s[%4$s]" value="%5$s"%6$s%7$s%8$s%9$s/>', $type, $size, $args['section'], $args['id'], $value, $placeholder, $min, $max, $step );
$html .= $this->get_field_description( $args );
echo $html;
}
/**
* Displays a checkbox for a settings field
*
* @param array $args settings field args
*/
function callback_checkbox( $args ) {
$value = esc_attr( $this->get_option( $args['id'], $args['section'], $args['std'] ) );
$html = '<fieldset>';
$html .= sprintf( '<label for="wpuf-%1$s[%2$s]">', $args['section'], $args['id'] );
$html .= sprintf( '<input type="hidden" name="%1$s[%2$s]" value="off" />', $args['section'], $args['id'] );
$html .= sprintf( '<input type="checkbox" class="checkbox" id="wpuf-%1$s[%2$s]" name="%1$s[%2$s]" value="on" %3$s />', $args['section'], $args['id'], checked( $value, 'on', false ) );
$html .= sprintf( '%1$s</label>', $args['desc'] );
$html .= '</fieldset>';
echo $html;
}
/**
* Displays a multicheckbox for a settings field
*
* @param array $args settings field args
*/
function callback_multicheck( $args ) {
$value = $this->get_option( $args['id'], $args['section'], $args['std'] );
$html = '<fieldset>';
$html .= sprintf( '<input type="hidden" name="%1$s[%2$s]" value="" />', $args['section'], $args['id'] );
foreach ( $args['options'] as $key => $label ) {
$checked = isset( $value[ $key ] ) ? $value[ $key ] : '0';
$html .= sprintf( '<label for="wpuf-%1$s[%2$s][%3$s]">', $args['section'], $args['id'], $key );
$html .= sprintf( '<input type="checkbox" class="checkbox" id="wpuf-%1$s[%2$s][%3$s]" name="%1$s[%2$s][%3$s]" value="%3$s" %4$s />', $args['section'], $args['id'], $key, checked( $checked, $key, false ) );
$html .= sprintf( '%1$s</label><br>', $label );
}
$html .= $this->get_field_description( $args );
$html .= '</fieldset>';
echo $html;
}
/**
* Displays a radio button for a settings field
*
* @param array $args settings field args
*/
function callback_radio( $args ) {
$value = $this->get_option( $args['id'], $args['section'], $args['std'] );
$html = '<fieldset>';
foreach ( $args['options'] as $key => $label ) {
$html .= sprintf( '<label for="wpuf-%1$s[%2$s][%3$s]">', $args['section'], $args['id'], $key );
$html .= sprintf( '<input type="radio" class="radio" id="wpuf-%1$s[%2$s][%3$s]" name="%1$s[%2$s]" value="%3$s" %4$s />', $args['section'], $args['id'], $key, checked( $value, $key, false ) );
$html .= sprintf( '%1$s</label><br>', $label );
}
$html .= $this->get_field_description( $args );
$html .= '</fieldset>';
echo $html;
}
/**
* Displays a selectbox for a settings field
*
* @param array $args settings field args
*/
function callback_select( $args ) {
$value = esc_attr( $this->get_option( $args['id'], $args['section'], $args['std'] ) );
$size = isset( $args['size'] ) && ! is_null( $args['size'] ) ? $args['size'] : 'regular';
$html = sprintf( '<select class="%1$s" name="%2$s[%3$s]" id="%2$s[%3$s]">', $size, $args['section'], $args['id'] );
foreach ( $args['options'] as $key => $label ) {
$html .= sprintf( '<option value="%s"%s>%s</option>', $key, selected( $value, $key, false ), $label );
}
$html .= sprintf( '</select>' );
$html .= $this->get_field_description( $args );
echo $html;
}
/**
* Displays a textarea for a settings field
*
* @param array $args settings field args
*/
function callback_textarea( $args ) {
$value = esc_textarea( $this->get_option( $args['id'], $args['section'], $args['std'] ) );
$size = isset( $args['size'] ) && ! is_null( $args['size'] ) ? $args['size'] : 'regular';
$placeholder = empty( $args['placeholder'] ) ? '' : ' placeholder="' . $args['placeholder'] . '"';
$html = sprintf( '<textarea rows="5" cols="55" class="%1$s-text" id="%2$s[%3$s]" name="%2$s[%3$s]"%4$s>%5$s</textarea>', $size, $args['section'], $args['id'], $placeholder, $value );
$html .= $this->get_field_description( $args );
echo $html;
}
/**
* Displays the html for a settings field
*
* @param array $args settings field args
*
* @return string
*/
function callback_html( $args ) {
echo $this->get_field_description( $args );
}
/**
* Displays a rich text textarea for a settings field
*
* @param array $args settings field args
*/
function callback_wysiwyg( $args ) {
$value = $this->get_option( $args['id'], $args['section'], $args['std'] );
$size = isset( $args['size'] ) && ! is_null( $args['size'] ) ? $args['size'] : '500px';
echo '<div style="max-width: ' . $size . ';">';
$editor_settings = array(
'teeny' => true,
'textarea_name' => $args['section'] . '[' . $args['id'] . ']',
'textarea_rows' => 10
);
if ( isset( $args['options'] ) && is_array( $args['options'] ) ) {
$editor_settings = array_merge( $editor_settings, $args['options'] );
}
wp_editor( $value, $args['section'] . '-' . $args['id'], $editor_settings );
echo '</div>';
echo $this->get_field_description( $args );
}
/**
* Displays a file upload field for a settings field
*
* @param array $args settings field args
*/
function callback_file( $args ) {
$value = esc_attr( $this->get_option( $args['id'], $args['section'], $args['std'] ) );
$size = isset( $args['size'] ) && ! is_null( $args['size'] ) ? $args['size'] : 'regular';
$id = $args['section'] . '[' . $args['id'] . ']';
$label = isset( $args['options']['button_label'] ) ? $args['options']['button_label'] : __( 'Choose File' );
$html = sprintf( '<input type="text" class="%1$s-text wpsa-url" id="%2$s[%3$s]" name="%2$s[%3$s]" value="%4$s"/>', $size, $args['section'], $args['id'], $value );
$html .= '<input type="button" class="button wpsa-browse" value="' . $label . '" />';
$html .= $this->get_field_description( $args );
echo $html;
}
/**
* Displays a password field for a settings field
*
* @param array $args settings field args
*/
function callback_password( $args ) {
$value = esc_attr( $this->get_option( $args['id'], $args['section'], $args['std'] ) );
$size = isset( $args['size'] ) && ! is_null( $args['size'] ) ? $args['size'] : 'regular';
$html = sprintf( '<input type="password" class="%1$s-text" id="%2$s[%3$s]" name="%2$s[%3$s]" value="%4$s"/>', $size, $args['section'], $args['id'], $value );
$html .= $this->get_field_description( $args );
echo $html;
}
/**
* Displays a color picker field for a settings field
*
* @param array $args settings field args
*/
function callback_color( $args ) {
$value = esc_attr( $this->get_option( $args['id'], $args['section'], $args['std'] ) );
$size = isset( $args['size'] ) && ! is_null( $args['size'] ) ? $args['size'] : 'regular';
$html = sprintf( '<input type="text" class="%1$s-text wp-color-picker-field" id="%2$s[%3$s]" name="%2$s[%3$s]" value="%4$s" data-default-color="%5$s" />', $size, $args['section'], $args['id'], $value, $args['std'] );
$html .= $this->get_field_description( $args );
echo $html;
}
/**
* Displays a select box for creating the pages select box
*
* @param array $args settings field args
*/
function callback_pages( $args ) {
$dropdown_args = array(
'selected' => esc_attr( $this->get_option( $args['id'], $args['section'], $args['std'] ) ),
'name' => $args['section'] . '[' . $args['id'] . ']',
'id' => $args['section'] . '[' . $args['id'] . ']',
'echo' => 0
);
$html = wp_dropdown_pages( $dropdown_args );
echo $html;
}
/**
* Sanitize callback for Settings API
*
* @return mixed
*/
function sanitize_options( $options ) {
if ( ! $options ) {
return $options;
}
foreach ( $options as $option_slug => $option_value ) {
$sanitize_callback = $this->get_sanitize_callback( $option_slug );
// If callback is set, call it
if ( $sanitize_callback ) {
$options[ $option_slug ] = call_user_func( $sanitize_callback, $option_value );
continue;
}
}
return $options;
}
/**
* Get sanitization callback for given option slug
*
* @param string $slug option slug
*
* @return mixed string or bool false
*/
function get_sanitize_callback( $slug = '' ) {
if ( empty( $slug ) ) {
return false;
}
// Iterate over registered fields and see if we can find proper callback
foreach ( $this->settings_fields as $section => $options ) {
foreach ( $options as $option ) {
if ( $option['name'] != $slug ) {
continue;
}
// Return the callback name
return isset( $option['sanitize_callback'] ) && is_callable( $option['sanitize_callback'] ) ? $option['sanitize_callback'] : false;
}
}
return false;
}
/**
* Get the value of a settings field
*
* @param string $option settings field name
* @param string $section the section name this field belongs to
* @param string $default default text if it's not found
*
* @return string
*/
function get_option( $option, $section, $default = '' ) {
$options = get_option( $section );
if ( isset( $options[ $option ] ) ) {
return $options[ $option ];
}
return $default;
}
/**
* Show navigations as tab
*
* Shows all the settings section labels as tab
*/
function show_navigation() {
$html = '<h2 class="nav-tab-wrapper">';
$count = count( $this->settings_sections );
// don't show the navigation if only one section exists
if ( $count === 1 ) {
return;
}
foreach ( $this->settings_sections as $tab ) {
$html .= sprintf( '<a href="#%1$s" class="nav-tab" id="%1$s-tab">%2$s</a>', $tab['id'], $tab['title'] );
}
$html .= '</h2>';
echo $html;
}
/**
* Show the section settings forms
*
* This function displays every sections in a different form
*/
function show_forms() {
?>
<div class="metabox-holder">
<?php foreach ( $this->settings_sections as $form ) { ?>
<div id="<?php echo $form['id']; ?>" class="group" style="display: none;">
<form method="post" action="options.php">
<?php
do_action( 'wsa_form_top_' . $form['id'], $form );
settings_fields( $form['id'] );
do_settings_sections( $form['id'] );
do_action( 'wsa_form_bottom_' . $form['id'], $form );
if ( isset( $this->settings_fields[ $form['id'] ] ) ) :
?>
<div style="padding-left: 10px">
<?php submit_button(); ?>
</div>
<?php endif; ?>
</form>
</div>
<?php } ?>
</div>
<?php
$this->script();
}
/**
* Tabbable JavaScript codes & Initiate Color Picker
*
* This code uses localstorage for displaying active tabs
*/
function script() {
?>
<script>
jQuery(document).ready(function ($) {
//Initiate Color Picker
$('.wp-color-picker-field').wpColorPicker();
// Switches option sections
$('.group').hide();
var activetab = '';
if (typeof(localStorage) != 'undefined') {
activetab = localStorage.getItem("activetab");
}
//if url has section id as hash then set it as active or override the current local storage value
if (window.location.hash) {
activetab = window.location.hash;
if (typeof(localStorage) != 'undefined') {
localStorage.setItem("activetab", activetab);
}
}
if (activetab != '' && $(activetab).length) {
$(activetab).fadeIn();
} else {
$('.group:first').fadeIn();
}
$('.group .collapsed').each(function () {
$(this).find('input:checked').parent().parent().parent().nextAll().each(
function () {
if ($(this).hasClass('last')) {
$(this).removeClass('hidden');
return false;
}
$(this).filter('.hidden').removeClass('hidden');
});
});
if (activetab != '' && $(activetab + '-tab').length) {
$(activetab + '-tab').addClass('nav-tab-active');
} else {
$('.nav-tab-wrapper a:first').addClass('nav-tab-active');
}
$('.nav-tab-wrapper a').click(function (evt) {
$('.nav-tab-wrapper a').removeClass('nav-tab-active');
$(this).addClass('nav-tab-active').blur();
var clicked_group = $(this).attr('href');
if (typeof(localStorage) != 'undefined') {
localStorage.setItem("activetab", $(this).attr('href'));
}
$('.group').hide();
$(clicked_group).fadeIn();
evt.preventDefault();
});
$('.wpsa-browse').on('click', function (event) {
event.preventDefault();
var self = $(this);
// Create the media frame.
var file_frame = wp.media.frames.file_frame = wp.media({
title: self.data('uploader_title'),
button: {
text: self.data('uploader_button_text'),
},
multiple: false
});
file_frame.on('select', function () {
attachment = file_frame.state().get('selection').first().toJSON();
self.prev('.wpsa-url').val(attachment.url).change();
});
// Finally, open the modal
file_frame.open();
});
});
</script>
<?php
$this->_style_fix();
}
function _style_fix() {
global $wp_version;
if ( version_compare( $wp_version, '3.8', '<=' ) ) :
?>
<style type="text/css">
/** WordPress 3.8 Fix **/
.form-table th {
padding: 20px 10px;
}
#wpbody-content .metabox-holder {
padding-top: 5px;
}
</style>
<?php
endif;
}
}
endif;
================================================
FILE: license.txt
================================================
WPGatsby
Copyright 2020 by the contributors
This plugin was originally started by Geoffrey Sechter and then this repo was transferred to Gatsby inc. after which the code was fully written from scratch and doesn't contain any of the original code.
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright © <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright © <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/philosophy/why-not-lgpl.html>.
================================================
FILE: readme.txt
================================================
=== WPGatsby ===
Contributors: gatsbyinc, jasonbahl, tylerbarnes1
Tags: Gatsby, GatsbyJS, JavaScript, JAMStack, Static Site generator, GraphQL, Headless WordPress, Decoupled WordPress
Requires at least: 5.4.2
Tested up to: 5.9
Requires PHP: 7.3
Stable tag: 2.3.3
License: GPLv3
License URI: https://www.gnu.org/licenses/gpl-3.0.html
<div align="center" style="margin-bottom: 20px;">
<img src="https://raw.githubusercontent.com/gatsbyjs/gatsby/master/packages/gatsby-source-wordpress/docs/assets/gatsby-wapuus.png" alt="Wapuu hugging a ball with the Gatsby logo on it" />
</div>
<p align="center">
<a href="https://github.com/gatsbyjs/wp-gatsby/blob/master/license.txt">
<img src="https://img.shields.io/badge/license-GPLv3-blue.svg" alt="Gatsby and gatsby-source-wordpress are released under the MIT license." />
</a>
<a href="https://twitter.com/intent/follow?screen_name=gatsbyjs">
<img src="https://img.shields.io/twitter/follow/gatsbyjs.svg?label=Follow%20@gatsbyjs" alt="Follow @gatsbyjs" />
</a>
</p>
WPGatsby is a free open-source WordPress plugin that optimizes your WordPress site to work as a data source for [Gatsby](https://www.gatsbyjs.com/docs/how-to/sourcing-data/sourcing-from-wordpress).
This plugin must be used in combination with the npm package [`gatsby-source-wordpress@^4.0.0`](https://www.npmjs.com/package/gatsby-source-wordpress).
## Install and Activation
WPGatsby is available on the WordPress.org repository and can be installed from your WordPress dashboard, or by using any other plugin installation method you prefer, such as installing with Composer from wpackagist.org.
## Plugin Overview
This plugin has 2 primary responsibilities:
- [Monitor Activity in WordPress to keep Gatsby in sync with WP](https://github.com/gatsbyjs/wp-gatsby/blob/master/docs/action-monitor.md)
- [Configure WordPress Previews to work with Gatsby](https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-source-wordpress/docs/tutorials/configuring-wp-gatsby.md#setting-up-preview)
Additionally, WPGatsby has a settings page to connect your WordPress site with your Gatsby site:
- [WPGatsby Settings](https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-source-wordpress/docs/tutorials/configuring-wp-gatsby.md)
================================================
FILE: src/ActionMonitor/ActionMonitor.php
================================================
<?php
namespace WPGatsby\ActionMonitor;
use WP_Post;
use WPGatsby\Admin\Settings;
/**
* This class registers and controls a post type which can be used to
* monitor WP events like post save or delete in order to invalidate
* Gatsby's cached nodes
*/
class ActionMonitor {
/**
* Whether a build hook should be dispatched. Default false.
*
* @var bool
*/
protected $should_dispatch = false;
/**
* An array of posts ID's for posts that have been updated
* in this ActionMonitor instantiation
*
* @var array
*/
protected $updated_post_ids = [];
/**
* Whether WPGraphQL Debug Mode is active
*
* @var bool Whether GraphQL Debug Mode is active
*/
protected $wpgraphql_debug_mode = false;
/**
* @var mixed|null|WP_Post The post object before update
*/
public $post_object_before_update = null;
/**
* Holds the classes for each action monitor
*
* @var array
*/
protected $action_monitors;
/**
* Set up the Action monitor when the class is initialized
*/
public function __construct() {
// Determine if WPGraphQL is in debug mode
$this->wpgraphql_debug_mode =
class_exists( 'WPGraphQL' ) && method_exists( 'WPGraphQL', 'debug' )
? \WPGraphQL::debug()
: false;
// Initialize action monitors
add_action( 'wp_loaded', [ $this, 'init_action_monitors' ], 11 );
// Register the GraphQL Fields Gatsby Source WordPress needs to interact with the Action Monitor
add_action( 'graphql_register_types', [ $this, 'register_graphql_fields' ] );
// Register post type and taxonomies to track CRUD events in WordPress
add_action( 'init', [ $this, 'init_post_type_and_taxonomies' ] );
add_filter( 'manage_action_monitor_posts_columns', [ $this, 'add_modified_column' ], 10 );
add_action(
'manage_action_monitor_posts_custom_column',
[
$this,
'render_modified_column',
],
10,
2
);
// Trigger webhook dispatch
add_action( 'shutdown', [ $this, 'trigger_dispatch' ] );
// allow any role to use Gatsby Preview
add_action( 'admin_init', [ $this, 'action_monitor_add_role_caps' ], 999 );
}
/**
* For Action Monitor, all of these roles need to be able to view and edit private action monitor posts so that Preview works for all roles.
*/
public function action_monitor_add_role_caps() {
$doing_graphql_request
= defined( 'GRAPHQL_REQUEST' ) && true === GRAPHQL_REQUEST;
if ( $doing_graphql_request ) {
// we only need to add roles one time. checking capabilities repeatedly isn't needed, just when the user is in the admin area is fine.
return;
}
$roles = apply_filters(
'gatsby_private_action_monitor_roles',
[
'editor',
'administrator',
'contributor',
'author'
]
);
foreach( $roles as $the_role ) {
$role = get_role($the_role);
if ( ! $role->has_cap( 'read_private_action_monitor_posts' ) ) {
$role->add_cap( 'read_private_action_monitor_posts' );
}
if ( ! $role->has_cap( 'edit_others_action_monitor_posts' ) ) {
$role->add_cap( 'edit_others_action_monitor_posts' );
}
}
}
/**
* Get the post types that are tracked by WPGatsby.
*
* @return array|mixed|void
*/
public function get_tracked_post_types() {
$public_post_types = get_post_types(
[
'show_in_graphql' => true,
'public' => true,
]
);
$publicly_queryable_post_types = get_post_types(
[
'show_in_graphql' => true,
'public' => false,
'publicly_queryable' => true,
]
);
$excludes = [
'action_monitor' => 'action_monitor',
];
$tracked_post_types = array_diff(
array_merge( $public_post_types, $publicly_queryable_post_types ),
$excludes
);
$tracked_post_types = apply_filters(
'gatsby_action_monitor_tracked_post_types',
$tracked_post_types
);
return ! empty( $tracked_post_types ) && is_array( $tracked_post_types ) ? $tracked_post_types : [];
}
/**
* Get the taxonomies that are tracked by WPGatsby
*
* @return array|mixed|void
*/
public function get_tracked_taxonomies() {
$tracked_taxonomies = apply_filters(
'gatsby_action_monitor_tracked_taxonomies',
get_taxonomies(
[
'show_in_graphql' => true,
'public' => true,
]
)
);
return ! empty( $tracked_taxonomies ) && is_array( $tracked_taxonomies ) ? $tracked_taxonomies : [];
}
/**
* Register Action monitor post type and associated taxonomies.
*
* The post type is used to store records of CRUD actions that have occurred in WordPress so
* that Gatsby can keep in Sync with changes in WordPress.
*
* The taxonomies are registered to store data related to the actions, but make it more
* efficient to filter actions by the values as Tax Queries are much more efficient than Meta
* Queries.
*/
public function init_post_type_and_taxonomies() {
/**
* Post Type: Action Monitor.
*/
$post_type_labels = [
'name' => __( 'Action Monitor', 'WPGatsby' ),
'singular_name' => __( 'Action Monitor', 'WPGatsby' ),
];
// Registers the post_type that logs actions for Gatsby
register_post_type(
'action_monitor',
[
'label' => __( 'Action Monitor', 'WPGatsby' ),
'labels' => $post_type_labels,
'description' => 'Used to keep a log of actions in WordPress for cache invalidation in gatsby-source-wordpress.',
'public' => false,
'publicly_queryable' => true,
'show_ui' => $this->wpgraphql_debug_mode,
'delete_with_user' => false,
'show_in_rest' => false,
'rest_base' => '',
'rest_controller_class' => 'WP_REST_Posts_Controller',
'has_archive' => false,
'show_in_menu' => $this->wpgraphql_debug_mode,
'show_in_nav_menus' => false,
'exclude_from_search' => true,
'capabilities' => [
// these custom capabilities allow any role to use Preview
'read_private_posts' => 'read_private_action_monitor_posts',
'edit_others_posts' => 'edit_others_action_monitor_posts',
// these are regular role capabilities for a CPT
'create_post' => 'create_post',
'edit_post' => 'edit_post',
'read_post' => 'read_post',
'delete_post' => 'delete_post',
'edit_posts' => 'edit_posts',
'publish_posts' => 'publish_posts',
'create_posts' => 'create_posts'
],
'map_meta_cap' => false,
'hierarchical' => false,
'rewrite' => [
'slug' => 'action_monitor',
'with_front' => true,
],
'query_var' => true,
'supports' => [ 'title', 'editor' ],
'show_in_graphql' => true,
'graphql_single_name' => 'ActionMonitorAction',
'graphql_plural_name' => 'ActionMonitorActions',
]
);
// Registers the taxonomy that connects the node type to the action_monitor post
register_taxonomy(
'gatsby_action_ref_node_type',
'action_monitor',
[
'label' => __( 'Referenced Node Type', 'WPGatsby' ),
'public' => false,
'show_ui' => $this->wpgraphql_debug_mode,
'show_in_graphql' => false,
'graphql_single_name' => 'ReferencedNodeType',
'graphql_plural_name' => 'ReferencedNodeTypes',
'hierarchical' => false,
'show_in_nav_menus' => false,
'show_tagcloud' => false,
'show_admin_column' => true,
]
);
// Registers the taxonomy that connects the node databaseId to the action_monitor post
register_taxonomy(
'gatsby_action_ref_node_dbid',
'action_monitor',
[
'label' => __( 'Referenced Node Database ID', 'WPGatsby' ),
'public' => false,
'show_ui' => $this->wpgraphql_debug_mode,
'show_in_graphql' => false,
'graphql_single_name' => 'ReferencedNodeDatabaseId',
'graphql_plural_name' => 'ReferencedNodeDatabaseIds',
'hierarchical' => false,
'show_in_nav_menus' => false,
'show_tagcloud' => false,
'show_admin_column' => true,
]
);
// Registers the taxonomy that connects the node global ID to the action_monitor post
register_taxonomy(
'gatsby_action_ref_node_id',
'action_monitor',
[
'label' => __( 'Referenced Node Global ID', 'WPGatsby' ),
'public' => false,
'show_ui' => $this->wpgraphql_debug_mode,
'show_in_graphql' => false,
'graphql_single_name' => 'ReferencedNodeId',
'graphql_plural_name' => 'ReferencedNodeIds',
'hierarchical' => false,
'show_in_nav_menus' => false,
'show_tagcloud' => false,
'show_admin_column' => true,
]
);
// Registers the taxonomy that connects the action type (CREATE, UPDATE, DELETE) to the action_monitor post
register_taxonomy(
'gatsby_action_type',
'action_monitor',
[
'label' => __( 'Action Type', 'WPGatsby' ),
'public' => false,
'show_ui' => $this->wpgraphql_debug_mode,
'show_in_graphql' => false,
'hierarchical' => false,
'show_in_nav_menus' => false,
'show_tagcloud' => false,
'show_admin_column' => true,
]
);
register_taxonomy( 'gatsby_action_stream_type', 'action_monitor', [
'label' => __( 'Stream Type', 'WPGatsby' ),
'public' => false,
'show_ui' => $this->wpgraphql_debug_mode,
'show_in_graphql' => false,
'hierarchical' => false,
'show_in_nav_menus' => false,
'show_tagcloud' => false,
'show_admin_column' => true,
] );
}
/**
* Adds a column to the action monitor Post Type to show the last modified time
*
* @param array $columns The column names included in the post table
*
* @return array
*/
public function add_modified_column( array $columns ) {
$columns['gatsby_last_modified'] = __( 'Last Modified', 'WPGatsby' );
return $columns;
}
/**
* Renders the last modified time in the action_monitor post type "modified" column
*
* @param string $column_name The name of the column
* @param int $post_id The ID of the post in the table
*/
public function render_modified_column( string $column_name, int $post_id ) {
if ( 'gatsby_last_modified' === $column_name ) {
$m_orig = get_post_field( 'post_modified', $post_id, 'raw' );
$m_stamp = strtotime( $m_orig );
$modified = date( 'n/j/y @ g:i a', $m_stamp );
echo '<p class="mod-date">';
echo '<em>' . esc_html( $modified ) . '</em><br />';
echo '</p>';
}
}
/**
* Sets should_dispatch to true
*/
public function schedule_dispatch() {
$this->should_dispatch = true;
}
/**
* Deletes all posts of the action_monitor post_type that are 7 days old, as well as any
* associated post meta and term relationships.
*
* @return bool|int
*/
public function garbage_collect_actions() {
global $wpdb;
$post_type = 'action_monitor';
$sql = wp_strip_all_tags(
'DELETE posts, pm, pt
FROM ' . $wpdb->prefix . 'posts AS posts
LEFT JOIN ' . $wpdb->prefix . 'term_relationships AS pt ON pt.object_id = posts.ID
LEFT JOIN ' . $wpdb->prefix . 'postmeta AS pm ON pm.post_id = posts.ID
WHERE posts.post_type = \'%1$s\'
AND posts.post_modified < \'%2$s\'',
true
);
$query = $wpdb->prepare( $sql, $post_type, date( 'Y-m-d H:i:s', strtotime( '-7 days' ) ) );
return $wpdb->query( $query );
}
/**
* Given the name of an Action Monitor, this returns it
*
* @param string $name The name of the Action Monitor to get
*
* @return mixed|null
*/
public function get_action_monitor( string $name ) {
return $this->action_monitors[ $name ] ?? null;
}
/**
* Use WP Action hooks to create action monitor posts
*/
function init_action_monitors() {
$class_names = [
'AcfMonitor',
'MediaMonitor',
'NavMenuMonitor',
'PostMonitor',
'PostTypeMonitor',
'SettingsMonitor',
'TaxonomyMonitor',
'TermMonitor',
'UserMonitor',
'PreviewMonitor',
];
$action_monitors = [];
foreach ( $class_names as $class_name ) {
$class = 'WPGatsby\ActionMonitor\Monitors\\' . $class_name;
if ( class_exists( $class ) ) {
$monitor = new $class( $this );
$action_monitors[ $class_name ] = $monitor;
}
}
/**
* Filter the action monitors. This can allow for other monitors
* to be registered, or can allow for monitors to be overridden.
*
* Overriding monitors is not advised, but there are cases where it might
* be necessary. Override with caution.
*
* @param array $action_monitors
* @param \WPGatsby\ActionMonitor\ActionMonitor $monitor The class instance, used to initialize the monitor.
*/
$this->action_monitors = apply_filters( 'gatsby_action_monitors', $action_monitors, $this );
do_action( 'gatsby_init_action_monitors', $this->action_monitors );
}
function register_post_graphql_fields() {
register_graphql_field(
'ActionMonitorAction',
'actionType',
[
'type' => 'String',
'description' => __(
'The type of action (CREATE, UPDATE, DELETE)',
'WPGatsby'
),
'resolve' => function( $post ) {
$terms = get_the_terms( $post->databaseId, 'gatsby_action_type' );
if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
$action_type = (string) $terms[0]->name;
} else {
$action_type
= get_post_meta( $post->ID, 'action_type', true );
}
return $action_type ? $action_type : null;
},
]
);
register_graphql_field(
'ActionMonitorAction',
'referencedNodeStatus',
[
'type' => 'String',
'description' => __(
'The post status of the post that triggered this action',
'WPGatsby'
),
'resolve' => function( $post ) {
$referenced_node_status = get_post_meta(
$post->ID,
'referenced_node_status',
true
);
return $referenced_node_status ?? null;
},
]
);
register_graphql_field(
'ActionMonitorAction',
'previewData',
[
'type' => 'GatsbyPreviewData',
'description' => __(
'The preview data of the post that triggered this action.',
'WPGatsby'
),
'resolve' => function( $post ) {
$referenced_node_preview_data = get_post_meta(
$post->ID,
'_gatsby_preview_data',
true
);
return $referenced_node_preview_data
&& $referenced_node_preview_data !== ""
? json_decode( $referenced_node_preview_data )
: null;
}
]
);
register_graphql_object_type(
'GatsbyPreviewData',
[
'description' => __( 'Gatsby Preview webhook data.', 'WPGatsby' ),
'fields' => [
'previewDatabaseId' => [
'type' => 'Int',
'description' => __( 'The WordPress database ID of the preview. Could be a revision or draft ID.', 'WPGatsby' ),
],
'userDatabaseId' => [
'type' => 'Int',
'description' => __( 'The database ID of the user who made the original preview.', 'WPGatsby' ),
],
'id' => [
'type' => 'ID',
'description' => __( 'The Relay id of the previewed node.', 'WPGatsby' ),
],
'singleName' => [
'type' => 'String',
'description' => __( 'The GraphQL single field name for the type of the preview.', 'WPGatsby' ),
],
'isDraft' => [
'type' => 'Boolean',
'description' => __( 'Wether or not the preview is a draft.', 'WPGatsby' ),
],
'remoteUrl' => [
'type' => 'String',
'description' => __( 'The WP url at the time of the preview.', 'WPGatsby' ),
],
'modified' => [
'type' => 'String',
'description' => __( 'The modified time of the previewed node.', 'WPGatsby' ),
],
'parentDatabaseId' => [
'type' => 'Int',
'description' => __( 'The WordPress database ID of the preview. If this is a draft it will potentially return 0, if it\'s a revision of a post, it will return the ID of the original post that this is a revision of.', 'WPGatsby' ),
],
'manifestIds' => [
'type' => [ 'list_of' => 'String' ],
'description' => __( 'A list of manifest ID\'s a preview action has seen during it\'s lifetime.', 'WPGatsby' ),
]
]
]
);
register_graphql_field(
'ActionMonitorAction',
'referencedNodeID',
[
'type' => 'String',
'description' => __(
'The post ID of the post that triggered this action',
'WPGatsby'
),
'resolve' => function( $post ) {
$terms = get_the_terms( $post->databaseId, 'gatsby_action_ref_node_dbid' );
if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
$referenced_node_id = (string) $terms[0]->name;
} else {
$referenced_node_id = get_post_meta(
$post->ID,
'referenced_node_id',
true
);
}
return $referenced_node_id ?? null;
},
]
);
register_graphql_field(
'ActionMonitorAction',
'referencedNodeGlobalRelayID',
[
'type' => 'String',
'description' => __(
'The global relay ID of the post that triggered this action',
'WPGatsby'
),
'resolve' => function( $post ) {
$terms = get_the_terms( $post->databaseId, 'gatsby_action_ref_node_id' );
if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
$referenced_node_relay_id = (string) $terms[0]->name;
} else {
$referenced_node_relay_id = get_post_meta(
$post->ID,
'referenced_node_relay_id',
true
);
}
return $referenced_node_relay_id ?? null;
},
]
);
register_graphql_field(
'ActionMonitorAction',
'referencedNodeSingularName',
[
'type' => 'String',
'description' => __(
'The WPGraphQL single name of the referenced post',
'WPGatsby'
),
'resolve' => function( $post ) {
$referenced_node_single_name = get_post_meta(
$post->ID,
'referenced_node_single_name',
true
);
return $referenced_node_single_name ?? null;
},
]
);
register_graphql_field(
'ActionMonitorAction',
'referencedNodePluralName',
[
'type' => 'String',
'description' => __(
'The WPGraphQL plural name of the referenced post',
'WPGatsby'
),
'resolve' => function( $post ) {
$referenced_node_plural_name = get_post_meta(
$post->ID,
'referenced_node_plural_name',
true
);
return $referenced_node_plural_name ?? null;
},
]
);
register_graphql_field(
'RootQueryToActionMonitorActionConnectionWhereArgs',
'sinceTimestamp',
[
'type' => 'Number',
'description' => 'List Actions performed since a timestamp.',
]
);
// @todo write a test for this previewStream input arg
register_graphql_field(
'RootQueryToActionMonitorActionConnectionWhereArgs',
'previewStream',
[
'type' => 'boolean',
'description' => 'List Actions of the PREVIEW stream type.',
]
);
add_filter(
'graphql_post_object_connection_query_args',
function( $args ) {
$sinceTimestamp = $args['sinceTimestamp'] ?? null;
if ( $sinceTimestamp ) {
$args['date_query'] = [
[
'after' => gmdate(
'Y-m-d H:i:s',
$sinceTimestamp / 1000
),
'column' => 'post_modified_gmt',
],
];
}
return $args;
}
);
add_filter(
'graphql_post_object_connection_query_args',
function( $args ) {
$previewStream = $args['previewStream'] ?? false;
if ( $previewStream ) {
$args['tax_query'] = [
[
'taxonomy' => 'gatsby_action_stream_type',
'field' => 'slug',
'terms' => 'preview',
],
];
}
return $args;
}
);
}
/**
* Add post meta to schema
*/
function register_graphql_fields() {
$this->register_post_graphql_fields();
}
/**
* Triggers the dispatch to the remote endpoint(s)
*/
public function trigger_dispatch() {
$build_webhook_field = Settings::prefix_get_option( 'builds_api_webhook', 'wpgatsby_settings', false );
$preview_webhook_field = Settings::prefix_get_option( 'preview_api_webhook', 'wpgatsby_settings', false );
$should_call_build_webhooks =
$build_webhook_field &&
$this->should_dispatch;
$we_should_call_preview_webhooks =
$preview_webhook_field &&
$this->should_dispatch;
if ( $should_call_build_webhooks ) {
$webhooks = explode( ',', $build_webhook_field );
$truthy_webhooks = array_filter( $webhooks );
$unique_webhooks = array_unique( $truthy_webhooks );
foreach ( $unique_webhooks as $webhook ) {
$args = apply_filters( 'gatsby_trigger_dispatch_args', [], $webhook );
wp_safe_remote_post( $webhook, $args );
}
}
if ( $we_should_call_preview_webhooks ) {
$webhooks = explode( ',', $preview_webhook_field );
$truthy_webhooks = array_filter( $webhooks );
$unique_webhooks = array_unique( $truthy_webhooks );
foreach ( $unique_webhooks as $webhook ) {
$token = \WPGatsby\GraphQL\Auth::get_token();
// For preview webhooks we send the token
// because this is a build but
// we want it to source any pending previews
// in case someone pressed preview right after
// we got to this point from someone else pressing
// publish/update.
$graphql_endpoint = apply_filters( 'graphql_endpoint', 'graphql' );
$graphql_url = get_site_url() . '/' . ltrim( $graphql_endpoint, '/' );
$post_body = apply_filters(
'gatsby_trigger_preview_build_dispatch_post_body',
[
'token' => $token,
'userDatabaseId' => get_current_user_id(),
'remoteUrl' => $graphql_url
]
);
$args = apply_filters(
'gatsby_trigger_preview_build_dispatch_args',
[
'body' => wp_json_encode( $post_body ),
'headers' => [
'Content-Type' => 'application/json; charset=utf-8',
],
'method' => 'POST',
'data_format' => 'body',
],
$webhook
);
wp_safe_remote_post( $webhook, $args );
}
}
}
}
================================================
FILE: src/ActionMonitor/Monitors/AcfMonitor.php
================================================
<?php
namespace WPGatsby\ActionMonitor\Monitors;
use WPGatsby\Utils\Utils;
class AcfMonitor extends Monitor {
public function init() {
// ACF Actions
add_action(
'acf/update_field_group',
function() {
$this->trigger_schema_diff(
[
'title' => __( 'Update ACF Field Group', 'WPGatsby' ),
]
);
}
);
add_action(
'acf/delete_field_group',
function() {
$this->trigger_schema_diff(
[
'title' => __( 'Delete ACF Field Group', 'WPGatsby' ),
]
);
}
);
add_action('acf/save_post', [$this, 'after_acf_save_post'], 20);
}
/**
* Handles content updates of ACF option pages.
*/
public function after_acf_save_post() {
if ( ! function_exists( 'acf_get_options_pages' ) ) {
return;
}
$option_pages = acf_get_options_pages();
if ( ! is_array( $option_pages ) ) {
return;
}
$option_pages_slugs = array_keys( $option_pages );
/**
* Filters the $option_pages_slugs array.
*
* @since 2.1.2
*
* @param array $option_pages_slugs Array with slugs of all registered ACF option pages.
*/
$option_pages_slugs = apply_filters(
'gatsby_action_monitor_tracked_acf_options_pages',
$option_pages_slugs
);
$screen = get_current_screen();
if(
! empty( $option_pages_slugs )
&& is_array( $option_pages_slugs )
&& Utils::str_in_substr_array( $screen->id, $option_pages_slugs )
) {
$this->trigger_non_node_root_field_update();
}
}
}
================================================
FILE: src/ActionMonitor/Monitors/MediaMonitor.php
================================================
<?php
namespace WPGatsby\ActionMonitor\Monitors;
use GraphQLRelay\Relay;
class MediaMonitor extends Monitor {
/**
* Initialize the Media Monitor which tracks actions for Media and logs them
* to the Gatsby Action Monitor
*
* @return mixed|void
*/
public function init() {
add_action( 'add_attachment', [ $this, 'callback_add_attachment' ] );
add_action( 'edit_attachment', [ $this, 'callback_edit_attachment' ] );
add_action( 'delete_attachment', [ $this, 'callback_delete_attachment' ] );
add_action( 'wp_save_image_editor_file', [ $this, 'callback_wp_save_image_editor_file' ], 10, 5 );
add_action( 'wp_save_image_file', [ $this, 'callback_wp_save_image_file' ], 10, 5 );
}
/**
* Logs an action when a Media Item (attachment) is added to WordPress
*
* @param int $attachment_id The ID of the attachment
*/
public function callback_add_attachment( int $attachment_id ) {
$attachment = get_post( $attachment_id );
if ( ! $attachment ) {
return;
}
$global_relay_id = Relay::toGlobalId(
'post',
$attachment_id
);
$this->log_action(
[
'action_type' => 'CREATE',
'title' => $attachment->post_title ?? "Attachment #$attachment_id",
// there is no concept of inheriting post status in Gatsby, so images will always be considered published.
'status' => 'publish',
'node_id' => $attachment_id,
'relay_id' => $global_relay_id,
'graphql_single_name' => 'mediaItem',
'graphql_plural_name' => 'mediaItems',
'skip_webhook' => true,
],
);
}
/**
* Logs an action when Media Items are edited
*
* @param int $attachment_id
*/
public function callback_edit_attachment( int $attachment_id ) {
$attachment = get_post( $attachment_id );
if ( ! $attachment ) {
return;
}
$global_relay_id = Relay::toGlobalId(
'post',
$attachment_id
);
$this->log_action(
[
'action_type' => 'UPDATE',
'title' => $attachment->post_title ?? "Attachment #$attachment_id",
// there is no concept of inheriting post status in Gatsby, so images will always be considered published.
'status' => 'publish',
'node_id' => $attachment_id,
'relay_id' => $global_relay_id,
'graphql_single_name' => 'mediaItem',
'graphql_plural_name' => 'mediaItems',
'skip_webhook' => true,
],
);
}
/**
* Logs an action when media items are deleted from the Media Library
*
* @param int $attachment_id The ID of the media item being deleted
*/
public function callback_delete_attachment( int $attachment_id ) {
$attachment = get_post( $attachment_id );
if ( ! $attachment ) {
return;
}
$global_relay_id = Relay::toGlobalId(
'post',
$attachment_id
);
$this->log_action(
[
'action_type' => 'DELETE',
'title' => $attachment->post_title ?? "Attachment #$attachment_id",
// there is no concept of inheriting post status in Gatsby, so images will always be considered published.
'status' => 'trash',
'node_id' => $attachment_id,
'relay_id' => $global_relay_id,
'graphql_single_name' => 'mediaItem',
'graphql_plural_name' => 'mediaItems',
'skip_webhook' => true,
],
);
}
/**
* Logs an action when image files are saved from the image editor
*
* @param string $dummy Unused.
* @param string $filename Filename.
* @param string $image Unused.
* @param string $mime_type Unused.
* @param int $post_id Post ID.
*/
public function callback_wp_save_image_editor_file( $dummy, $filename, $image, $mime_type, $post_id ) {
$this->callback_edit_attachment( $post_id );
}
/**
* Logs an action when image files are saved from the image editor
*
* @param string $dummy Unused.
* @param string $filename Filename.
* @param string $image Unused.
* @param string $mime_type Unused.
* @param int $post_id Post ID.
*/
public function callback_wp_save_image_file( $dummy, $filename, $image, $mime_type, $post_id ) {
return $this->callback_wp_save_image_editor_file( $dummy, $filename, $image, $mime_type, $post_id );
}
}
================================================
FILE: src/ActionMonitor/Monitors/Monitor.php
================================================
<?php
namespace WPGatsby\ActionMonitor\Monitors;
use GraphQLRelay\Relay;
use WPGatsby\ActionMonitor\ActionMonitor;
use WPGatsby\Admin\Preview;
abstract class Monitor {
/**
* @var ActionMonitor
*/
protected $action_monitor;
/**
* @var array
*/
protected $tracked_events = [];
/**
* @var array
*/
protected $ignored_ids = [];
/**
* Monitor constructor.
*
* @param ActionMonitor $action_monitor
*/
public function __construct( ActionMonitor $action_monitor ) {
$this->action_monitor = $action_monitor;
$this->init();
}
/**
* Allows IDs to be set that will be ignored by the logger
*
* @param int[] $ids Array of database IDs to ignore logging for
*/
public function set_ignored_ids( array $ids ) {
if ( ! empty( $ids ) && is_array( $ids ) ) {
$this->ignored_ids = array_merge( $this->ignored_ids, $ids );
}
}
/**
* Given an array of IDs, this removes them from the list of ignored IDs
*
* @param array $ids
*/
public function unset_ignored_ids( array $ids ) {
if ( ! empty( $ids ) && is_array( $ids ) ) {
foreach ( $ids as $id ) {
if ( isset( $this->ignored_ids[ $id ] ) ) {
unset( $this->ignored_ids[ $id ] );
}
}
}
}
/**
* Resets the ignored IDs to an empty array
*/
public function reset_ignored_ids() {
$this->ignored_ids = [];
}
/**
* Trigger action for non node root field updates
*
* @param array $args Optional args to pass to the action
*/
public function trigger_non_node_root_field_update( array $args = [] ) {
$default = [
'action_type' => 'NON_NODE_ROOT_FIELDS',
'title' => 'Non node root field changed',
'node_id' => 'update_non_node_root_field',
'relay_id' => 'update_non_node_root_field',
'graphql_single_name' => 'update_non_node_root_field',
'graphql_plural_name' => 'update_non_node_root_field',
'status' => 'update_non_node_root_field',
];
$this->log_action( array_merge( $default, $args ) );
}
/**
* Trigger action to refetch everything
*
* @param array $args Optional args to pass to the action
*/
public function trigger_refetch_all( $args = [] ) {
$default = [
'action_type' => 'REFETCH_ALL',
'title' => 'Something changed (such as permalink structure) that requires everything to be refetched',
'node_id' => 'refetch_all',
'relay_id' => 'refetch_all',
'graphql_single_name' => 'refetch_all',
'graphql_plural_name' => 'refetch_all',
'status' => 'refetch_all',
];
$this->log_action( array_merge( $default, $args ) );
}
/**
* Determines whether the meta should be tracked or not
*
* @param string $meta_key Metadata key.
* @param mixed $meta_value Metadata value. Serialized if non-scalar.
* @param object $object The object the metadata is for.
*
* @return bool
*/
protected function should_track_meta( string $meta_key, $meta_value, $object ) {
/**
* This filter allows plugins to opt-in or out of tracking for meta.
*
* @param bool $should_track Whether the meta key should be tracked.
* @param string $meta_key Metadata key.
* @param int $meta_id ID of updated metadata entry.
* @param mixed $meta_value Metadata value. Serialized if non-scalar.
* @param mixed $object The object the meta is being updated for.
*
* @param bool $tracked whether the meta key is tracked by Gatsby Action Monitor
*/
$should_track = apply_filters( 'gatsby_action_monitor_should_track_meta', null, $meta_key, $meta_value, $object );
// If the filter has been applied return it
if ( null !== $should_track ) {
return (bool) $should_track;
}
// If the meta key starts with an underscore, don't track it
if ( '_' === substr( $meta_key, 0, 1 ) ) {
return false;
}
return true;
}
/**
* Inserts an action that triggers Gatsby Source WordPress to diff the Schemas.
*
* This can be used for plugins such as Custom Post Type UI, Advanced Custom Fields, etc that
* alter the Schema in some way.
*
* @param array $args Optional args to add to the action
*/
public function trigger_schema_diff( $args = [] ) {
$default = [
'title' => __( 'Diff schemas', 'WPGatsby' ),
'node_id' => 'none',
'relay_id' => 'none',
'graphql_single_name' => 'none',
'graphql_plural_name' => 'none',
'status' => 'none',
];
$args = array_merge( $default, $args );
$args['action_type'] = 'DIFF_SCHEMAS';
$this->log_action( $args );
}
/**
* Insert new action
*
* $args = [$action_type, $title, $status, $node_id, $relay_id, $graphql_single_name,
* $graphql_plural_name]
*
* @param array $args Array of arguments to configure the action to be inserted
*
*/
public function log_action( array $args ) {
if (
! isset( $args['action_type'] ) ||
! isset( $args['title'] ) ||
! isset( $args['node_id'] ) ||
! isset( $args['relay_id'] ) ||
! isset( $args['graphql_single_name'] ) ||
! isset( $args['graphql_plural_name'] ) ||
! isset( $args['status'] )
) {
// @todo log that this action isn't working??
return;
}
/**
* Filter to allow skipping a logged action. If set to false, the action will not be logged.
*
* @param null|bool $enable Whether the action should be logged
* @param array $arguments The args to log
* @param Monitor $monitor Instance of the Monitor
*/
$pre_log_action = apply_filters( 'gatsby_pre_log_action_monitor_action', null, $args, $this );
if ( null !== $pre_log_action ) {
if ( false === $pre_log_action ) {
return;
}
}
// If the node_id is set to be ignored, don't create a log
if ( in_array( $args['node_id'], $this->ignored_ids, true ) ) {
return;
}
$should_dispatch =
! isset( $args['skip_webhook'] ) || ! $args['skip_webhook'];
$time = time();
$node_type = 'unknown';
if ( isset( $args['graphql_single_name'] ) ) {
$node_type = $args['graphql_single_name'];
} elseif ( isset( $args['relay_id'] ) ) {
$id_parts = Relay::fromGlobalId( $args['relay_id'] );
if ( ! isset( $id_parts['type'] ) ) {
$node_type = $id_parts['type'];
}
}
$stream_type = ( $args['stream_type'] ?? null ) === 'PREVIEW'
? 'PREVIEW'
: 'CONTENT';
$is_preview_stream = $stream_type === 'PREVIEW';
// Check to see if an action already exists for this node type/database id
$existing = new \WP_Query( [
'post_type' => 'action_monitor',
'post_status' => 'any',
'posts_per_page' => 1,
'no_found_rows' => true,
'fields' => 'ids',
'tax_query' => [
'relation' => 'AND',
[
'taxonomy' => 'gatsby_action_ref_node_dbid',
'field' => 'name',
'terms' => sanitize_text_field( $args['node_id'] ),
],
[
'taxonomy' => 'gatsby_action_ref_node_type',
'field' => 'name',
'terms' => $node_type,
],
[
'taxonomy' => 'gatsby_action_stream_type',
'field' => 'name',
'terms' => $stream_type,
]
],
] );
// If there's already an action logged for this node, update the record
if ( isset( $existing->posts ) && ! empty( $existing->posts ) ) {
$existing_id = $existing->posts[0];
$action_monitor_post_id = wp_update_post( [
'ID' => absint( $existing_id ),
'post_title' => $args['title'],
'post_content' => wp_json_encode( $args ),
] );
} else {
$action_monitor_post_id = \wp_insert_post(
[
'post_title' => $args['title'],
'post_type' => 'action_monitor',
'post_status' => 'private',
'author' => -1,
'post_name' => sanitize_title( "{$args['title']}-{$time}" ),
'post_content' => wp_json_encode( $args ),
]
);
wp_set_object_terms( $action_monitor_post_id, sanitize_text_field( $args['node_id'] ), 'gatsby_action_ref_node_dbid' );
wp_set_object_terms( $action_monitor_post_id, sanitize_text_field( $node_type ), 'gatsby_action_ref_node_type' );
}
wp_set_object_terms( $action_monitor_post_id, sanitize_text_field( $args['relay_id'] ), 'gatsby_action_ref_node_id' );
wp_set_object_terms( $action_monitor_post_id, $args['action_type'], 'gatsby_action_type' );
wp_set_object_terms( $action_monitor_post_id, $stream_type, 'gatsby_action_stream_type' );
if ( $action_monitor_post_id !== 0 ) {
if ( isset( $args['preview_data'] ) ) {
$existing_preview_data = \get_post_meta(
$action_monitor_post_id,
'_gatsby_preview_data',
true
);
$manifest_id = Preview::get_preview_manifest_id_for_post(
get_post( $args['node_id'] )
);
$manifest_ids = [$manifest_id];
// if we have existing data, we want to merge our manifest id
// into any existing manifest ids
if ( $existing_preview_data && $existing_preview_data !== "" ) {
$existing_preview_data = json_decode( $existing_preview_data );
if ( $existing_preview_data->manifestIds ?? false ) {
$manifest_ids = array_unique(
array_merge(
$existing_preview_data->manifestIds,
$manifest_ids
)
);
}
}
// add manifest ids
$preview_data = json_decode( $args['preview_data'] );
$preview_data->manifestIds = $manifest_ids;
$preview_data = json_encode( $preview_data );
\update_post_meta(
$action_monitor_post_id,
'_gatsby_preview_data',
$preview_data
);
}
\update_post_meta(
$action_monitor_post_id,
'referenced_node_status',
$args['status'] // menus don't have post status. This is for Gatsby
);
\update_post_meta(
$action_monitor_post_id,
'referenced_node_single_name',
graphql_format_field_name( $args['graphql_single_name'] )
);
\update_post_meta(
$action_monitor_post_id,
'referenced_node_plural_name',
graphql_format_field_name( $args['graphql_plural_name'] )
);
// preview actions should remain private
if ( !$is_preview_stream ) {
\wp_update_post( [
'ID' => $action_monitor_post_id,
'post_status' => 'publish'
] );
}
}
// If $should_dispatch is not set to false, schedule a dispatch. Actions being logged that
// set $should_dispatch to false will be logged, but not trigger a webhook immediately.
// if this is a preview we should always not dispatch
if ( $should_dispatch && ! $is_preview_stream ) {
// we've saved at least 1 action, so we should update
// but only if this isn't a preview
// previews will dispatch on their own
$this->action_monitor->schedule_dispatch();
}
// Delete old actions
$this->action_monitor->garbage_collect_actions();
}
/**
* Initialize the Monitor
*
* @return mixed
*/
abstract public function init();
}
================================================
FILE: src/ActionMonitor/Monitors/NavMenuMonitor.php
================================================
<?php
namespace WPGatsby\ActionMonitor\Monitors;
use GraphQLRelay\Relay;
use WP_Term;
class NavMenuMonitor extends Monitor {
/**
* @return mixed|void
*/
public function init() {
// Log when menus are added/removed from a theme location
add_filter( 'pre_set_theme_mod_nav_menu_locations', [ $this, 'callback_set_nav_menu_locations' ], 10, 2 );
// Log when a nav menu is updated
add_action( 'wp_update_nav_menu', [ $this, 'callback_update_nav_menu' ], 10, 2 );
// Log when a nav menu is deleted
add_action( 'wp_delete_nav_menu', [ $this, 'callback_delete_nav_menu' ], 10, 3 );
// Log when a menu item is updated
add_action( 'wp_update_nav_menu_item', [ $this, 'callback_update_nav_menu_item' ], 10, 3 );
add_action( 'wp_add_nav_menu_item', [ $this, 'callback_add_nav_menu_item' ], 10, 3 );
}
/**
* Callback for menu locations theme mod. When menu locations are set/unset.
*
* @param array $value The old value of the nav menu locations
* @param mixed|array|bool $old_value The new value of the nav menu locations
*
* @return mixed
*/
public function callback_set_nav_menu_locations( array $value, $old_value ) {
$old_locations = ! empty( $old_value ) && is_array( $old_value ) ? $old_value : [];
$new_locations = ! empty( $value ) && is_array( $value ) ? $value : [];
// If old locations are same as new locations, do nothing
if ( $old_locations === $new_locations ) {
return $value;
}
// Log the diffed menus
$this->log_diffed_menus( $old_locations, $new_locations );
// Return the value passed to the filter, without making any changes
return $value;
}
/**
* Determines whether a menu is considered public and should be tracked
* by the activity monitor
*
* @param int $menu_id ID of the menu
*
* @return bool
*/
public function is_menu_public( int $menu_id ) {
$locations = get_theme_mod( 'nav_menu_locations' );
$assigned_menu_ids = ! empty( $locations ) ? array_values( $locations ) : [];
if ( empty( $assigned_menu_ids ) ) {
return false;
}
if ( in_array( $menu_id, $assigned_menu_ids, true ) ) {
return true;
}
return false;
}
/**
* Log action when a nav menu is updated
*
* @param int $menu_id The ID of the menu being updated
* @param array $menu_data The data associated with the menu
*/
public function callback_update_nav_menu( int $menu_id, array $menu_data = [] ) {
if ( ! $this->is_menu_public( $menu_id ) ) {
return;
}
$menu = get_term_by( 'id', absint( $menu_id ), 'nav_menu' );
$this->log_action(
[
'action_type' => 'UPDATE',
'title' => $menu->name,
// menus don't have post status. This is for Gatsby
'status' => 'publish',
'node_id' => (int) $menu->term_id,
'relay_id' => Relay::toGlobalId( 'term', (int) $menu->term_id ),
'graphql_single_name' => 'menu',
'graphql_plural_name' => 'menus',
]
);
}
/**
* Given an array of old menu locations and new menu locations, this
* diffs them and logs an action for the menu assigned to the added/removed location
*
* @param array $old_locations Old locations with a menu assigned
* @param array $new_locations New locations with a menu assigned
*/
public function log_diffed_menus( array $old_locations, array $new_locations ) {
// If old locations are same as new locations, do nothing
if ( $old_locations === $new_locations ) {
return;
}
// Trigger an action for each added location
$added = array_diff( $new_locations, $old_locations );
if ( ! empty( $added ) && is_array( $added ) ) {
foreach ( $added as $location => $added_menu_id ) {
if ( ! empty( $menu = get_term_by( 'id', (int) $added_menu_id, 'nav_menu' ) ) && $menu instanceof WP_Term ) {
$this->log_action(
[
'action_type' => 'CREATE',
'title' => $menu->name,
// menus don't have post status. This is for Gatsby
'status' => 'publish',
'node_id' => (int) $added_menu_id,
'relay_id' => Relay::toGlobalId( 'term', (int) $added_menu_id ),
'graphql_single_name' => 'menu',
'graphql_plural_name' => 'menus',
]
);
}
}
}
// Trigger an action for each location deleted
$removed = array_diff( $old_locations, $new_locations );
if ( ! empty( $removed ) ) {
foreach ( $removed as $location => $removed_menu_id ) {
$this->log_action(
[
'action_type' => 'DELETE',
'title' => $removed_menu_id,
// menus don't have post status. This is for Gatsby
'status' => 'trash',
'node_id' => (int) $removed_menu_id,
'relay_id' => Relay::toGlobalId( 'term', $removed_menu_id ),
'graphql_single_name' => 'menu',
'graphql_plural_name' => 'menus',
]
);
}
}
}
/**
* Log an action when a menu is deleted
*
* @param int $term_id ID of the deleted menu.
*/
public function callback_delete_nav_menu( $term_id ) {
$this->log_action(
[
'action_type' => 'DELETE',
'title' => '#' . $term_id,
// menus don't have post status. This is for Gatsby
'status' => 'trash',
'node_id' => (int) $term_id,
'relay_id' => Relay::toGlobalId( 'term', $term_id ),
'graphql_single_name' => 'menu',
'graphql_plural_name' => 'menus',
]
);
}
/**
* @param int $menu_id ID of the updated menu.
* @param int $menu_item_db_id ID of the updated menu item.
* @param array $args An array of arguments used to update a menu item.
*/
public function callback_add_nav_menu_item( int $menu_id, int $menu_item_db_id, array $args ) {
if ( ! $this->is_menu_public( $menu_id ) ) {
return;
}
$menu = get_term_by( 'id', $menu_id, 'nav_menu' );
$menu_item = get_post( $menu_item_db_id );
// Log action for the updated menu
$this->log_action(
[
'action_type' => 'UPDATE',
'title' => $menu->name,
// menus don't have post status. This is for Gatsby
'status' => 'publish',
'node_id' => (int) $menu->term_id,
'relay_id' => Relay::toGlobalId( 'term', (int) $menu->term_id ),
'graphql_single_name' => 'menu',
'graphql_plural_name' => 'menus',
]
);
// Log action for the added menu item
$this->log_action(
[
'action_type' => 'CREATE',
'title' => $menu_item->post_title,
// menus don't have post status. This is for Gatsby
'status' => 'publish',
'node_id' => (int) $menu_item->ID,
'relay_id' => Relay::toGlobalId( 'post', (int) $menu_item->ID ),
'graphql_single_name' => 'menuItem',
'graphql_plural_name' => 'menuItems',
]
);
}
/**
* @param int $menu_id ID of the updated menu.
* @param int $menu_item_db_id ID of the updated menu item.
* @param array $args An array of arguments used to update a menu item.
*/
public function callback_update_nav_menu_item( int $menu_id, int $menu_item_db_id, array $args ) {
if ( ! $this->is_menu_public( $menu_id ) ) {
return;
}
$menu = get_term_by( 'id', $menu_id, 'nav_menu' );
$menu_item = get_post( $menu_item_db_id );
// Log action for the updated menu
$this->log_action(
[
'action_type' => 'UPDATE',
'title' => $menu->name,
// menus don't have post status. This is for Gatsby
'status' => 'publish',
'node_id' => (int) $menu->term_id,
'relay_id' => Relay::toGlobalId( 'term', (int) $menu->term_id ),
'graphql_single_name' => 'menu',
'graphql_plural_name' => 'menus',
]
);
// Log action for the added menu item
$this->log_action(
[
'action_type' => 'UPDATE',
'title' => $menu_item->post_title,
// menus don't have post status. This is for Gatsby
'status' => 'publish',
'node_id' => (int) $menu_item->ID,
'relay_id' => Relay::toGlobalId( 'post', (int) $menu_item->ID ),
'graphql_single_name' => 'menuItem',
'graphql_plural_name' => 'menuItems',
]
);
}
}
================================================
FILE: src/ActionMonitor/Monitors/PostMonitor.php
================================================
<?php
namespace WPGatsby\ActionMonitor\Monitors;
use GraphQLRelay\Relay;
use WP_Post;
class PostMonitor extends Monitor {
/**
* @return mixed|void
*/
public function init() {
add_action( 'post_updated', [ $this, 'callback_post_updated' ], 10, 3 );
add_action( 'transition_post_status', [ $this, 'callback_transition_post_status' ], 10, 3 );
add_action( 'deleted_post', [ $this, 'callback_deleted_post' ], 10, 1 );
add_action( 'updated_post_meta', [ $this, 'callback_updated_post_meta' ], 10, 4 );
add_action( 'added_post_meta', [ $this, 'callback_updated_post_meta' ], 10, 4 );
add_action( 'deleted_post_meta', [ $this, 'callback_deleted_post_meta' ], 10, 4 );
}
/**
* Log change to authors
*
* @param int $post_id Post ID.
* @param WP_Post $post_after Post object following the update.
* @param WP_Post $post_before Post object before the update.
*/
public function callback_post_updated( int $post_id, WP_Post $post_after, WP_Post $post_before ) {
// If the author of the post has changed, we need to log an update for the old author and the new author
if ( isset( $post_after->post_author ) && (int) $post_after->post_author !== (int) $post_before->post_author ) {
/**
* Log user update action
*/
$this->log_user_update( $post_after );
$this->log_user_update( $post_before );
}
}
/**
* Log all post status changes ( creating / updating / trashing )
*
* @action transition_post_status
*
* @param mixed $new_status New status.
* @param mixed $old_status Old status.
* @param WP_Post $post Post object.
*/
public function callback_transition_post_status( $new_status, $old_status, WP_Post $post ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
// If the object is not a valid post, ignore it
if ( ! is_a( $post, 'WP_Post' ) ) {
return;
}
// If the post type is not intentionally tracked, ignore it
if ( ! $this->is_post_type_tracked( $post->post_type ) ) {
return;
}
$initial_post_statuses = [ 'auto-draft', 'inherit', 'new' ];
// If the post is a fresh post that hasn't been made public, don't track the action
if ( in_array( $new_status, $initial_post_statuses, true ) ) {
return;
}
// Saving drafts should not log actions
if ( 'draft' === $new_status && 'draft' === $old_status ) {
return;
}
// If the post isn't coming from a publish state or going to a publish state
// we can ignore the action.
if ( 'publish' !== $old_status && 'publish' !== $new_status ) {
return;
}
$action_type = 'UPDATE';
// If a post is moved from 'publish' to any other status, set the action_type to delete
// to let Gatsby know it should no longer cache the post
if ( 'publish' !== $new_status && 'publish' === $old_status ) {
$action_type = 'DELETE';
// If a post that was not published becomes published, set the action_type to create
// to let Gatsby know it should fetch and cache the post
} elseif ( 'publish' === $new_status && 'publish' !== $old_status ) {
$action_type = 'CREATE';
// If a published post is saved, it's an update.
} elseif ( 'publish' === $new_status && 'publish' === $old_status ) {
$action_type = 'UPDATE';
}
// We don't need to log a user update if the post is simply being updated.
// The exception would be when the post author is changed, but that's
// handled in a different action
if ( 'UPDATE' !== $action_type ) {
$this->log_user_update( $post );
}
$post_type_object = get_post_type_object( $post->post_type );
$action = [
'action_type' => $action_type,
'title' => $post->post_title,
'node_id' => $post->ID,
'relay_id' => Relay::toGlobalId( 'post', $post->ID ),
'graphql_single_name' => $post_type_object->graphql_single_name,
'graphql_plural_name' => $post_type_object->graphql_plural_name,
'status' => $new_status,
];
/**
* Log an action
*/
$this->log_action( $action );
}
/**
* Logs actions when posts are deleted
*
* @param int $post_id The ID of the deleted post
*/
public function callback_deleted_post( int $post_id ) {
$post = get_post( $post_id );
// If there is no post object, do nothing
if ( ! is_a( $post, 'WP_Post' ) ) {
return;
}
// If the deleted post is of a post type that isn't being tracked, do nothing
if ( ! $this->is_post_type_tracked( $post->post_type ) ) {
return;
}
// Ignore posts that were deleted that weren't published
if ( 'publish' !== $post->post_status ) {
return;
}
$post_type_object = get_post_type_object( $post->post_type );
$action = [
'action_type' => 'DELETE',
'title' => $post->post_title,
'node_id' => $post->ID,
'relay_id' => Relay::toGlobalId( 'post', $post->ID ),
'graphql_single_name' => $post_type_object->graphql_single_name,
'graphql_plural_name' => $post_type_object->graphql_plural_name,
'status' => 'trash',
];
// Log the action
$this->log_action( $action );
// Log user update
$this->log_user_update( $post );
}
/**
* Whether the post type is tracked
*
* @param string $post_type The name of the post type to check
*
* @return bool
*/
public function is_post_type_tracked( string $post_type ) {
return in_array( $post_type, $this->action_monitor->get_tracked_post_types(), true );
}
/**
* Logs activity when meta is updated on posts
*
* @param int $meta_id ID of updated metadata entry.
* @param int $object_id ID of the object metadata is for.
* @param string $meta_key Metadata key.
* @param mixed $meta_value Metadata value. Serialized if non-scalar.
*/
public function callback_updated_post_meta( int $meta_id, int $object_id, string $meta_key, $meta_value ) {
$post = get_post( $object_id );
if ( empty( $post ) || ! is_a( $post, 'WP_Post' ) ) {
return;
}
// If the deleted post is of a post type that isn't being tracked, do nothing
if ( ! $this->is_post_type_tracked( $post->post_type ) ) {
return;
}
if ( 'publish' !== $post->post_status ) {
return;
}
if ( false === $this->should_track_meta( $meta_key, $meta_value, $post ) ) {
return;
}
$post_type_object = get_post_type_object( $post->post_type );
$action = [
'action_type' => 'UPDATE',
'title' => $post->post_title,
'node_id' => $post->ID,
'relay_id' => Relay::toGlobalId( 'post', $post->ID ),
'graphql_single_name' => $post_type_object->graphql_single_name,
'graphql_plural_name' => $post_type_object->graphql_plural_name,
'status' => $post->post_status,
];
// Log the action
$this->log_action( $action );
}
/**
* Logs activity when meta is updated on posts
*
* @param string[] $meta_ids An array of metadata entry IDs to delete.
* @param int $object_id ID of the object metadata is for.
* @param string $meta_key Metadata key.
* @param mixed $meta_value Metadata value. Serialized if non-scalar.
*/
public function callback_deleted_post_meta( array $meta_ids, int $object_id, string $meta_key, $meta_value ) {
$post = get_post( $object_id );
if ( empty( $post ) || ! is_a( $post, 'WP_Post' ) ) {
return;
}
// If the deleted post is of a post type that isn't being tracked, do nothing
if ( ! $this->is_post_type_tracked( $post->post_type ) ) {
return;
}
if ( 'publish' !== $post->post_status ) {
return;
}
if ( false === $this->should_track_meta( $meta_key, $meta_value, $post ) ) {
return;
}
$post_type_object = get_post_type_object( $post->post_type );
$action = [
'action_type' => 'UPDATE',
'title' => $post->post_title,
'node_id' => $post->ID,
'relay_id' => Relay::toGlobalId( 'post', $post->ID ),
'graphql_single_name' => $post_type_object->graphql_single_name,
'graphql_plural_name' => $post_type_object->graphql_plural_name,
'status' => $post->post_status,
];
// Log the action
$this->log_action( $action );
}
/**
* Log a user update when a post is created or deleted, telling Gatsby to
* invalidate user caches
*
* @param WP_Post $post The post data of the Post being updated
*
* @todo:
* This should be able to be removed at some point as Gatsby
* _should_ be able to handle bi-directional relationships implicitly. When a Post is
* created, Gatsby queries the full post fields, including the Author.node.id, and should
* be able to handle the relationship between the new post and the author. When a post is
* deleted, Gatsby should remove the post node and any queries (such as author archive pages)
* that include references to the deleted post node should automatically be updated by Gatsby.
*/
public function log_user_update( WP_Post $post ) {
if ( empty( $post->post_author ) || ! absint( $post->post_author ) ) {
return;
}
$user = get_user_by( 'id', absint( $post->post_author ) );
if ( ! $user || 0 === $user->ID ) {
return;
}
$user_monitor = $this->action_monitor->get_action_monitor( 'UserMonitor' );
if ( empty( $user_monitor ) || ! $user_monitor instanceof UserMonitor ) {
return;
}
if ( ! $user_monitor->is_published_author( $user->ID ) ) {
$action_type = 'DELETE';
$status = 'trash';
} else {
$action_type = 'UPDATE';
$status = 'publish';
}
$this->log_action(
[
'action_type' => $action_type,
'title' => $user->display_name,
'node_id' => $user->ID,
'relay_id' => Relay::toGlobalId( 'user', $user->ID ),
'graphql_single_name' => 'user',
'graphql_plural_name' => 'users',
'status' => $status,
]
);
}
}
================================================
FILE: src/ActionMonitor/Monitors/PostTypeMonitor.php
================================================
<?php
namespace WPGatsby\ActionMonitor\Monitors;
class PostTypeMonitor extends Monitor {
/**
* @var array List of registered post types that Gatsby tracks
*/
public $current_post_types;
/**
* @var array List of post types that were previously registered
*/
public $prev_post_types;
/**
* @var string The option name that's used to cache the tracked post types
*/
public $option_name;
/**
* Initialize the PostTypeMonitor
*
* @return mixed|void
*/
public function init() {
// Set the option name that's used to cache post types
$this->option_name = '_gatsby_tracked_post_types';
// Check to see if the post types are different
add_action( 'gatsby_init_action_monitors', [ $this, 'check_post_types' ], 999 );
}
/**
* Check post types and trigger a Schema diff if detected
*/
public function check_post_types() {
$this->current_post_types = array_keys( $this->action_monitor->get_tracked_post_types() );
$this->prev_post_types = get_option( $this->option_name, [] );
if ( empty( $this->prev_post_types ) ) {
update_option( $this->option_name, $this->current_post_types );
return;
}
/**
* If the current_post_types and prev_post_types do not match,
* update the option and cache the tracked post types
*/
if ( $this->current_post_types === $this->prev_post_types ) {
return;
}
update_option( $this->option_name, $this->current_post_types );
// Check for added post types
$added = array_diff( $this->current_post_types, $this->prev_post_types );
// Check for removed post types
$removed = array_diff( $this->prev_post_types, $this->current_post_types );
// if there are
if ( ! empty( $added ) ) {
$this->trigger_schema_diff(
[
'title' => __( 'Post Type added', 'WPGatsby' ),
]
);
}
if ( ! empty( $removed ) ) {
$this->trigger_schema_diff(
[
'title' => __( 'Post type removed', 'WPGatsby' ),
]
);
}
}
}
================================================
FILE: src/ActionMonitor/Monitors/PreviewMonitor.php
================================================
<?php
namespace WPGatsby\ActionMonitor\Monitors;
use GraphQLRelay\Relay;
use WPGatsby\Admin\Preview;
use WPGatsby\Admin\Settings;
class PreviewMonitor extends Monitor {
function init() {
$enable_gatsby_preview = Settings::get_setting( 'enable_gatsby_preview' ) === 'on';
if ( $enable_gatsby_preview ) {
add_filter( 'template_include', [ $this, 'setup_preview_template' ], 1, 99 );
add_filter( 'preview_post_link', function( $link, $post ) {
$doing_graphql_request
= defined( 'GRAPHQL_REQUEST' ) && true === GRAPHQL_REQUEST;
// Use the normal $link during graphql requests
// because otherwise we could override the post URI
// in Gatsby! meaning the content sync or preview url could be added to the page path in Gatsby if pages are created from the uri.
if ( $doing_graphql_request ) {
return $link;
}
return \add_query_arg( 'gatsby_preview', 'true', $link );
}, 10, 2 );
}
}
/**
* Determines wether or not the current global
* PHP context is related to Gatsby Content Sync Previews
*/
public static function is_gatsby_content_sync_preview() {
$doing_graphql_request
= defined( 'GRAPHQL_REQUEST' ) && null !== GRAPHQL_REQUEST;
if ( $doing_graphql_request ) {
return false;
}
$enable_gatsby_preview = Settings::get_setting( 'enable_gatsby_preview' ) === 'on';
$is_gatsby_content_sync_preview
= \is_preview()
|| isset( $_GET['preview_nonce'] )
|| isset( $_GET['gatsby_preview'] );
return $is_gatsby_content_sync_preview && $enable_gatsby_preview;
}
/**
* If specific conditions are met, this loads the Gatsby Preview template
* instead of the core WordPress preview template
*
* @param string $template The template to load
*
* @return string
*/
public function setup_preview_template( $template ) {
global $post;
// If the global post isn't set, but the preview_id is passed, use that to determine
// the preview post
if ( empty( $post ) && isset( $_GET['preview_id'] ) ) {
$post = get_post( $_GET['preview_id'] );
}
if ( self::is_gatsby_content_sync_preview() && $post ) {
// Ensure the post_type is set to show_in_graphql
$post_type_object = $post->post_type ? get_post_type_object( $post->post_type ) : null;
if ( $post_type_object && ! $post_type_object->show_in_graphql ?? true ) {
return plugin_dir_path( __FILE__ ) . '../../Admin/includes/post-type-not-shown-in-graphql.php';
}
// WP doesn't call post_save for every second preview with no content changes.
// Since we're using post_save to trigger the webhook to Gatsby, we need to get WP to call post_save for this post.
do_action( 'save_post', $post->ID, $post, true );
$this->post_to_preview_instance( $post->ID, $post );
return trailingslashit( dirname( __FILE__ ) ) . '../../Admin/includes/preview-template.php';
}
return $template;
}
/**
* Send a Preview to Gatsby
*/
public function post_to_preview_instance( $post_ID, $post ) {
$revisions_are_disabled =
! wp_revisions_enabled( $post );
if (
defined( 'DOING_AUTOSAVE' )
&& DOING_AUTOSAVE
// if revisions are disabled, our autosave is our preview
&& ! $revisions_are_disabled
) {
return;
}
if ( $post->post_type === 'action_monitor' ) {
return;
}
if ( $post->post_status === 'auto-draft' ) {
return;
}
$is_draft = $post->post_status === 'draft';
$is_new_post_draft =
(
$post->post_status === 'auto-draft'
|| $post->post_status === 'draft'
) &&
$post->post_date_gmt === '0000-00-00 00:00:00';
$is_revision = $post->post_type === 'revision';
$is_draft = $post->post_status === 'draft';
$is_gatsby_content_sync_preview = self::is_gatsby_content_sync_preview();
if (
! $is_draft
&& ! $is_revision
&& ! $is_new_post_draft
&& ! $is_gatsby_content_sync_preview
) {
return;
}
$token = \WPGatsby\GraphQL\Auth::get_token();
if ( ! $token ) {
error_log(
'Please set a JWT token in WPGatsby to enable Preview support.'
);
return;
}
$preview_webhook = $this::get_gatsby_preview_webhook();
$original_post = get_post( $post->post_parent );
$this_is_a_publish_not_a_preview =
$original_post
&& $original_post->post_modified === $post->post_modified
&& ! $is_gatsby_content_sync_preview;
if ( $this_is_a_publish_not_a_preview ) {
// we will handle this in ActionMonitor.php, not here.
return;
}
$post_type_object = $original_post
? \get_post_type_object( $original_post->post_type )
: \get_post_type_object( $post->post_type );
if ( ! $post_type_object->show_in_graphql ?? true ) {
// if the post type doesn't have show_in_graphql set,
// we don't want to send a preview webhook for this post type.
return;
}
$parent_post_id = $original_post->ID ?? $post_ID;
$global_relay_id = Relay::toGlobalId(
'post',
// sometimes this is a draft instead of a revision
// so we can't expect original post to exist.
absint( $original_post->ID ?? $post_ID )
);
$referenced_node_single_name
= $post_type_object->graphql_single_name ?? null;
$referenced_node_single_name_normalized = lcfirst(
$referenced_node_single_name
);
$referenced_node_plural_name
= $post_type_object->graphql_plural_name ?? null;
$referenced_node_plural_name_normalized = lcfirst(
$referenced_node_plural_name
);
$graphql_endpoint = apply_filters( 'graphql_endpoint', 'graphql' );
$graphql_url = get_site_url() . '/' . ltrim( $graphql_endpoint, '/' );
$preview_data = [
'previewDatabaseId' => $post_ID,
'id' => $global_relay_id,
'singleName' => $referenced_node_single_name_normalized,
'isDraft' => $is_draft,
'remoteUrl' => $graphql_url,
'modified' => $post->post_modified,
'parentDatabaseId' => $post->post_parent,
'userDatabaseId' => get_current_user_id(),
];
$post_body = array_merge(
$preview_data,
[
'token' => $token
]
);
$this->log_action( [
'action_type' => 'UPDATE',
'title' => $post->post_title,
'node_id' => $parent_post_id,
'relay_id' => $global_relay_id,
'graphql_single_name' => $referenced_node_single_name_normalized,
'graphql_plural_name' => $referenced_node_plural_name_normalized,
// everything that should show in Gatsby is publish
// as far as Gatsby is concerned.
'status' => 'publish',
'stream_type' => 'PREVIEW',
'preview_data' => wp_json_encode( $preview_data ),
] );
// @todo move this to shutdown hook to prevent race conditions
$response = wp_remote_post(
$preview_webhook,
[
'body' => wp_json_encode( $post_body ),
'headers' => [
'Content-Type' => 'application/json; charset=utf-8',
],
'method' => 'POST',
'data_format' => 'body',
]
);
if ( \is_wp_error( $response ) ) {
error_log( "WPGatsby couldn\'t POST to the Preview webhook set in plugin options.\nWebhook returned error: {$response->get_error_message()}" );
}
}
/**
* Get the Gatsby Preview instance refresh webhook
*/
static function get_gatsby_preview_webhook() {
$preview_webhook = Settings::get_setting( 'preview_api_webhook' );
if ( ! $preview_webhook || ! filter_var( $preview_webhook, FILTER_VALIDATE_URL ) ) {
return false;
}
if ( substr( $preview_webhook, -1 ) !== '/' ) {
$preview_webhook .= '/';
}
return $preview_webhook;
}
}
================================================
FILE: src/ActionMonitor/Monitors/SettingsMonitor.php
================================================
<?php
namespace WPGatsby\ActionMonitor\Monitors;
use GraphQLRelay\Relay;
class SettingsMonitor extends Monitor {
/**
* @return mixed|void
*/
public function init() {
add_action( 'updated_option', [ $this, 'callback_update_option' ], 10, 3 );
add_action( 'update_option_page_on_front', [ $this, 'callback_update_page_on_front' ], 10, 3 );
add_action( 'update_option_page_for_posts', [ $this, 'callback_update_page_for_posts' ], 10, 3 );
add_action( 'update_option_permalink_structure', [ $this, 'callback_update_permalink_structure' ], 10, 3 );
}
/**
* Determines whether the option should be tracked by the Gatsby Action monitor
*
* @param string $option_name Name of the option to update.
* @param mixed $old_value The old option value.
* @param mixed $value The new option value.
*
* @return bool
*/
protected function should_track_option( string $option_name, $old_value, $value ) {
/**
* This filter allows plugins to opt-in or out of tracking for options.
*
* @param bool $should_track Whether the meta key should be tracked.
* @param string $option_name Name of the option to update.
* @param mixed $old_value The old option value.
* @param mixed $value The new option value.
*
* @param bool $tracked whether the meta key is tracked by Gatsby Action Monitor
*/
$should_track = apply_filters( 'gatsby_action_monitor_should_track_option', null, $option_name, $old_value, $value );
// If the filter has been applied return it
if ( null !== $should_track ) {
return (bool) $should_track;
}
// Options that are allowed to be tracked by default
$tracked_option_names = apply_filters(
'gatsby_action_monitor_tracked_option_names',
[
'siteurl',
'home',
'blogname',
'blogdescription',
'start_of_week',
'default_category',
'default_comment_status',
'posts_per_page',
'date_format',
'time_format',
'blog_charset',
'active_plugins',
'category_base',
'gmt_offset',
'template',
'stylesheet',
'comment_registration',
'default_role',
'show_on_front',
'tag_base',
'show_avatars',
'avatar_rating',
'upload_url_path',
'comments_per_page',
'default_comments_page',
'comment_order',
'sticky_posts',
'timezone_string',
'default_post_format',
'site_icon',
'current_theme',
]
);
if ( in_array( $option_name, $tracked_option_names, true ) ) {
return true;
}
// If the meta key starts with an underscore, don't track it
if ( '_' === substr( $option_name, 0, 1 ) ) {
return false;
}
return false;
}
/**
* Log actions when options are updated
*
* @param string $option_name Name of the option to update.
* @param mixed $old_value The old option value.
* @param mixed $value The new option value.
*/
public function callback_update_option( string $option_name, $old_value, $value ) {
if ( ! $this->should_track_option( $option_name, $old_value, $value ) ) {
return;
}
$this->trigger_non_node_root_field_update(
[
'title' => __( 'Update Setting: ', 'WPGatsby' ) . ' ' . $option_name,
]
);
}
/**
* Log action when permalink_structure is changed
*
* @param mixed $old_value The old option value.
* @param mixed $new_value The new option value.
* @param string $option_name Name of the option to update.
*/
public function callback_update_permalink_structure( $old_value, $new_value, string $option_name ) {
if ( $old_value === $new_value ) {
return;
}
$this->trigger_refetch_all(
[
'title' => __( 'Permalink structure updated', 'WPGatsby' ),
]
);
}
/**
* Log action when page_on_front is changed
*
* @param mixed $old_value The old option value.
* @param mixed $new_value The new option value.
* @param string $option_name Name of the option to update.
*/
public function callback_update_page_on_front( $old_value, $new_value, string $option_name ) {
if ( (int) $old_value === (int) $new_value ) {
return;
}
$old_page = get_post( absint( $old_value ) );
$new_page = get_post( absint( $new_value ) );
if ( $old_page instanceof \WP_Post ) {
$this->log_action(
[
'action_type' => 'UPDATE',
'title' => $old_page->post_title,
'node_id' => $old_page->ID,
'relay_id' => Relay::toGlobalId( 'post', $old_page->ID ),
'graphql_single_name' => get_post_type_object( $old_page->post_type )->graphql_single_name,
'graphql_plural_name' => get_post_type_object( $old_page->post_type )->graphql_plural_name,
'status' => $old_page->post_status,
]
);
}
if ( $new_page instanceof \WP_Post ) {
$this->log_action(
[
'action_type' => 'UPDATE',
'title' => $new_page->post_title,
'node_id' => $new_page->ID,
'relay_id' => Relay::toGlobalId( 'post', $new_page->ID ),
'graphql_single_name' => get_post_type_object( $new_page->post_type )->graphql_single_name,
'graphql_plural_name' => get_post_type_object( $new_page->post_type )->graphql_plural_name,
'status' => $new_page->post_status,
]
);
}
}
/**
* Log action when page_for_posts is changed
*
* @param mixed $old_value The old option value.
* @param mixed $new_value The new option value.
* @param string $option_name Name of the option to update.
*/
public function callback_update_page_for_posts( $old_value, $new_value, string $option_name ) {
if ( (int) $old_value === (int) $new_value ) {
return;
}
$old_page = get_post( absint( $old_value ) );
$new_page = get_post( absint( $new_value ) );
if ( $old_page instanceof \WP_Post ) {
$this->log_action(
[
'action_type' => 'UPDATE',
'title' => $old_page->post_title,
'node_id' => $old_page->ID,
'relay_id' => Relay::toGlobalId( 'post', $old_page->ID ),
'graphql_single_name' => get_post_type_object( $old_page->post_type )->graphql_single_name,
'graphql_plural_name' => get_post_type_object( $old_page->post_type )->graphql_plural_name,
'status' => $old_page->post_status,
]
);
} else {
$this->log_action(
[
'action_type' => 'UPDATE',
'title' => 'Change page on front away from posts',
'node_id' => 'post',
'relay_id' => Relay::toGlobalId( 'post_type', 'post' ),
'graphql_single_name' => 'contentType',
'graphql_plural_name' => 'contentTypes',
'status' => 'publish',
]
);
}
if ( $new_page instanceof \WP_Post ) {
$this->log_action(
[
'action_type' => 'UPDATE',
'title' => $new_page->post_title,
'node_id' => $new_page->ID,
'relay_id' => Relay::toGlobalId( 'post', $new_page->ID ),
'graphql_single_name' => get_post_type_object( $new_page->post_type )->graphql_single_name,
'graphql_plural_name' => get_post_type_object( $new_page->post_type )->graphql_plural_name,
'status' => $new_page->post_status,
]
);
} else {
$this->log_action(
[
'action_type' => 'UPDATE',
'title' => 'Set page on front to posts',
'node_id' => 'post',
'relay_id' => Relay::toGlobalId( 'post_type', 'post' ),
'graphql_single_name' => 'contentType',
'graphql_plural_name' => 'contentTypes',
'status' => 'publish',
]
);
}
}
}
================================================
FILE: src/ActionMonitor/Monitors/TaxonomyMonitor.php
================================================
<?php
namespace WPGatsby\ActionMonitor\Monitors;
class TaxonomyMonitor extends Monitor {
/**
* @var array List of registered taxonomies that Gatsby tracks
*/
public $current_taxonomies;
/**
* @var array List of taxonomies that were previously registered
*/
public $prev_taxonomies;
/**
* @var string The option name that's used to cache the tracked taxonomies
*/
public $option_name;
/**
* Initialize the TaxonomyMonitor
*
* @return mixed|void
*/
public function init() {
// Set the option name that's used to cache taxonomies
$this->option_name = '_gatsby_tracked_taxonomies';
// Check to see if the taxonomies are different
add_action( 'gatsby_init_action_monitors', [ $this, 'check_taxonomies' ], 999 );
}
/**
* Check taxonomies and trigger a Schema diff if detected
*/
public function check_taxonomies() {
$this->current_taxonomies = array_keys( $this->action_monitor->get_tracked_taxonomies() );
$this->prev_taxonomies = get_option( $this->option_name, [] );
if ( empty( $this->prev_taxonomies ) ) {
update_option( $this->option_name, $this->current_taxonomies );
return;
}
/**
* If the current_taxonomies and prev_taxonomies do not match,
* update the option and cache the tracked taxonomies
*/
if ( $this->current_taxonomies === $this->prev_taxonomies ) {
return;
}
update_option( $this->option_name, $this->current_taxonomies );
// Check for added taxonomies
$added = array_diff( $this->current_taxonomies, $this->prev_taxonomies );
// Check for removed taxonomies
$removed = array_diff( $this->prev_taxonomies, $this->current_taxonomies );
// if there are
if ( ! empty( $added ) ) {
$this->trigger_schema_diff(
[
'title' => __( 'Taxonomy added', 'WPGatsby' ),
]
);
}
if ( ! empty( $removed ) ) {
$this->trigger_schema_diff(
[
'title' => __( 'Taxonomy removed', 'WPGatsby' ),
]
);
}
}
}
================================================
FILE: src/ActionMonitor/Monitors/TermMonitor.php
================================================
<?php
namespace WPGatsby\ActionMonitor\Monitors;
use GraphQLRelay\Relay;
use WP_Taxonomy;
use WP_Term;
class TermMonitor extends Monitor {
/**
* Caches terms before they're deleted
*
* @var array
*/
public $terms_before_delete = [];
/**
* @return mixed|void
*/
public function init() {
add_action( 'created_term', [ $this, 'callback_created_term' ], 10, 3 );
add_action( 'pre
gitextract_1lfhn0r3/ ├── .dockerignore ├── .env.dist ├── .github/ │ └── workflows/ │ ├── main.yml │ └── tests.yml ├── .gitignore ├── .prettierrc.js ├── CHANGELOG.md ├── README.md ├── access-functions.php ├── bin/ │ ├── install-test-env.sh │ └── run-docker.sh ├── codeception.dist.yml ├── composer.json ├── docker/ │ ├── app.Dockerfile │ ├── app.entrypoint.sh │ ├── testing.Dockerfile │ └── testing.entrypoint.sh ├── docker-compose.yml ├── docs/ │ ├── action-monitor.md │ └── running-tests.md ├── lib/ │ └── wp-settings-api.php ├── license.txt ├── readme.txt ├── src/ │ ├── ActionMonitor/ │ │ ├── ActionMonitor.php │ │ └── Monitors/ │ │ ├── AcfMonitor.php │ │ ├── MediaMonitor.php │ │ ├── Monitor.php │ │ ├── NavMenuMonitor.php │ │ ├── PostMonitor.php │ │ ├── PostTypeMonitor.php │ │ ├── PreviewMonitor.php │ │ ├── SettingsMonitor.php │ │ ├── TaxonomyMonitor.php │ │ ├── TermMonitor.php │ │ └── UserMonitor.php │ ├── Admin/ │ │ ├── Preview.php │ │ ├── Settings.php │ │ └── includes/ │ │ ├── no-preview-url-set.php │ │ ├── post-type-not-shown-in-graphql.php │ │ ├── preview-template.php │ │ └── style.css │ ├── GraphQL/ │ │ ├── Auth.php │ │ └── ParseAuthToken.php │ ├── Schema/ │ │ ├── Schema.php │ │ ├── SiteMeta.php │ │ └── WPGatsbyWPGraphQLSchemaChanges.php │ ├── ThemeSupport/ │ │ └── ThemeSupport.php │ └── Utils/ │ └── Utils.php ├── tests/ │ ├── _data/ │ │ ├── .gitignore │ │ ├── .gitkeep │ │ └── config.php │ ├── _output/ │ │ ├── .gitignore │ │ └── .gitkeep │ ├── _support/ │ │ ├── AcceptanceTester.php │ │ ├── FunctionalTester.php │ │ ├── Helper/ │ │ │ ├── Acceptance.php │ │ │ ├── Functional.php │ │ │ ├── Unit.php │ │ │ └── Wpunit.php │ │ ├── UnitTester.php │ │ ├── WpunitTester.php │ │ └── _generated/ │ │ └── .gitignore │ ├── acceptance.suite.dist.yml │ ├── functional.suite.dist.yml │ ├── wpunit/ │ │ └── ActionMonitorTest.php │ └── wpunit.suite.dist.yml ├── vendor/ │ ├── autoload.php │ ├── composer/ │ │ ├── ClassLoader.php │ │ ├── LICENSE │ │ ├── autoload_classmap.php │ │ ├── autoload_namespaces.php │ │ ├── autoload_psr4.php │ │ ├── autoload_real.php │ │ ├── autoload_static.php │ │ └── semver/ │ │ ├── CHANGELOG.md │ │ ├── LICENSE │ │ ├── README.md │ │ └── composer.json │ └── firebase/ │ └── php-jwt/ │ ├── LICENSE │ ├── README.md │ ├── composer.json │ └── src/ │ ├── BeforeValidException.php │ ├── ExpiredException.php │ ├── JWK.php │ ├── JWT.php │ └── SignatureInvalidException.php └── wp-gatsby.php
SYMBOL INDEX (291 symbols across 40 files)
FILE: lib/wp-settings-api.php
class WPGraphQL_Settings_API (line 14) | class WPGraphQL_Settings_API {
method __construct (line 30) | public function __construct() {
method admin_enqueue_scripts (line 37) | function admin_enqueue_scripts() {
method set_sections (line 50) | function set_sections( $sections ) {
method add_section (line 61) | function add_section( $section ) {
method set_fields (line 72) | function set_fields( $fields ) {
method add_field (line 78) | function add_field( $section, $field ) {
method admin_init (line 100) | function admin_init() {
method get_field_description (line 169) | public function get_field_description( $args ) {
method callback_text (line 184) | function callback_text( $args ) {
method callback_url (line 202) | function callback_url( $args ) {
method callback_number (line 211) | function callback_number( $args ) {
method callback_checkbox (line 231) | function callback_checkbox( $args ) {
method callback_multicheck (line 250) | function callback_multicheck( $args ) {
method callback_radio (line 273) | function callback_radio( $args ) {
method callback_select (line 295) | function callback_select( $args ) {
method callback_textarea (line 316) | function callback_textarea( $args ) {
method callback_html (line 335) | function callback_html( $args ) {
method callback_wysiwyg (line 344) | function callback_wysiwyg( $args ) {
method callback_file (line 373) | function callback_file( $args ) {
method callback_password (line 392) | function callback_password( $args ) {
method callback_color (line 408) | function callback_color( $args ) {
method callback_pages (line 425) | function callback_pages( $args ) {
method sanitize_options (line 442) | function sanitize_options( $options ) {
method get_sanitize_callback (line 468) | function get_sanitize_callback( $slug = '' ) {
method get_option (line 497) | function get_option( $option, $section, $default = '' ) {
method show_navigation (line 513) | function show_navigation() {
method show_forms (line 537) | function show_forms() {
method script (line 567) | function script() {
method _style_fix (line 650) | function _style_fix() {
FILE: src/ActionMonitor/ActionMonitor.php
class ActionMonitor (line 13) | class ActionMonitor {
method __construct (line 52) | public function __construct() {
method action_monitor_add_role_caps (line 89) | public function action_monitor_add_role_caps() {
method get_tracked_post_types (line 126) | public function get_tracked_post_types() {
method get_tracked_taxonomies (line 164) | public function get_tracked_taxonomies() {
method init_post_type_and_taxonomies (line 188) | public function init_post_type_and_taxonomies() {
method add_modified_column (line 333) | public function add_modified_column( array $columns ) {
method render_modified_column (line 345) | public function render_modified_column( string $column_name, int $post...
method schedule_dispatch (line 359) | public function schedule_dispatch() {
method garbage_collect_actions (line 369) | public function garbage_collect_actions() {
method get_action_monitor (line 395) | public function get_action_monitor( string $name ) {
method init_action_monitors (line 402) | function init_action_monitors() {
method register_post_graphql_fields (line 443) | function register_post_graphql_fields() {
method register_graphql_fields (line 720) | function register_graphql_fields() {
method trigger_dispatch (line 727) | public function trigger_dispatch() {
FILE: src/ActionMonitor/Monitors/AcfMonitor.php
class AcfMonitor (line 7) | class AcfMonitor extends Monitor {
method init (line 9) | public function init() {
method after_acf_save_post (line 39) | public function after_acf_save_post() {
FILE: src/ActionMonitor/Monitors/MediaMonitor.php
class MediaMonitor (line 7) | class MediaMonitor extends Monitor {
method init (line 15) | public function init() {
method callback_add_attachment (line 30) | public function callback_add_attachment( int $attachment_id ) {
method callback_edit_attachment (line 64) | public function callback_edit_attachment( int $attachment_id ) {
method callback_delete_attachment (line 98) | public function callback_delete_attachment( int $attachment_id ) {
method callback_wp_save_image_editor_file (line 136) | public function callback_wp_save_image_editor_file( $dummy, $filename,...
method callback_wp_save_image_file (line 149) | public function callback_wp_save_image_file( $dummy, $filename, $image...
FILE: src/ActionMonitor/Monitors/Monitor.php
class Monitor (line 8) | abstract class Monitor {
method __construct (line 30) | public function __construct( ActionMonitor $action_monitor ) {
method set_ignored_ids (line 40) | public function set_ignored_ids( array $ids ) {
method unset_ignored_ids (line 51) | public function unset_ignored_ids( array $ids ) {
method reset_ignored_ids (line 64) | public function reset_ignored_ids() {
method trigger_non_node_root_field_update (line 73) | public function trigger_non_node_root_field_update( array $args = [] ) {
method trigger_refetch_all (line 94) | public function trigger_refetch_all( $args = [] ) {
method should_track_meta (line 119) | protected function should_track_meta( string $meta_key, $meta_value, $...
method trigger_schema_diff (line 156) | public function trigger_schema_diff( $args = [] ) {
method log_action (line 180) | public function log_action( array $args ) {
method init (line 384) | abstract public function init();
FILE: src/ActionMonitor/Monitors/NavMenuMonitor.php
class NavMenuMonitor (line 8) | class NavMenuMonitor extends Monitor {
method init (line 13) | public function init() {
method callback_set_nav_menu_locations (line 38) | public function callback_set_nav_menu_locations( array $value, $old_va...
method is_menu_public (line 64) | public function is_menu_public( int $menu_id ) {
method callback_update_nav_menu (line 86) | public function callback_update_nav_menu( int $menu_id, array $menu_da...
method log_diffed_menus (line 116) | public function log_diffed_menus( array $old_locations, array $new_loc...
method callback_delete_nav_menu (line 172) | public function callback_delete_nav_menu( $term_id ) {
method callback_add_nav_menu_item (line 194) | public function callback_add_nav_menu_item( int $menu_id, int $menu_it...
method callback_update_nav_menu_item (line 238) | public function callback_update_nav_menu_item( int $menu_id, int $menu...
FILE: src/ActionMonitor/Monitors/PostMonitor.php
class PostMonitor (line 8) | class PostMonitor extends Monitor {
method init (line 13) | public function init() {
method callback_post_updated (line 31) | public function callback_post_updated( int $post_id, WP_Post $post_aft...
method callback_transition_post_status (line 55) | public function callback_transition_post_status( $new_status, $old_sta...
method callback_deleted_post (line 139) | public function callback_deleted_post( int $post_id ) {
method is_post_type_tracked (line 185) | public function is_post_type_tracked( string $post_type ) {
method callback_updated_post_meta (line 197) | public function callback_updated_post_meta( int $meta_id, int $object_...
method callback_deleted_post_meta (line 243) | public function callback_deleted_post_meta( array $meta_ids, int $obje...
method log_user_update (line 295) | public function log_user_update( WP_Post $post ) {
FILE: src/ActionMonitor/Monitors/PostTypeMonitor.php
class PostTypeMonitor (line 4) | class PostTypeMonitor extends Monitor {
method init (line 26) | public function init() {
method check_post_types (line 39) | public function check_post_types() {
FILE: src/ActionMonitor/Monitors/PreviewMonitor.php
class PreviewMonitor (line 9) | class PreviewMonitor extends Monitor {
method init (line 10) | function init() {
method is_gatsby_content_sync_preview (line 36) | public static function is_gatsby_content_sync_preview() {
method setup_preview_template (line 62) | public function setup_preview_template( $template ) {
method post_to_preview_instance (line 94) | public function post_to_preview_instance( $post_ID, $post ) {
method get_gatsby_preview_webhook (line 253) | static function get_gatsby_preview_webhook() {
FILE: src/ActionMonitor/Monitors/SettingsMonitor.php
class SettingsMonitor (line 6) | class SettingsMonitor extends Monitor {
method init (line 11) | public function init() {
method should_track_option (line 29) | protected function should_track_option( string $option_name, $old_valu...
method callback_update_option (line 106) | public function callback_update_option( string $option_name, $old_valu...
method callback_update_permalink_structure (line 126) | public function callback_update_permalink_structure( $old_value, $new_...
method callback_update_page_on_front (line 147) | public function callback_update_page_on_front( $old_value, $new_value,...
method callback_update_page_for_posts (line 195) | public function callback_update_page_for_posts( $old_value, $new_value...
FILE: src/ActionMonitor/Monitors/TaxonomyMonitor.php
class TaxonomyMonitor (line 4) | class TaxonomyMonitor extends Monitor {
method init (line 26) | public function init() {
method check_taxonomies (line 39) | public function check_taxonomies() {
FILE: src/ActionMonitor/Monitors/TermMonitor.php
class TermMonitor (line 9) | class TermMonitor extends Monitor {
method init (line 21) | public function init() {
method is_taxonomy_tracked (line 40) | public function is_taxonomy_tracked( string $taxonomy ) {
method callback_created_term (line 51) | public function callback_created_term( int $term_id, int $tt_id, strin...
method callback_pre_delete_term (line 88) | public function callback_pre_delete_term( int $term_id, string $taxono...
method callback_delete_term (line 118) | public function callback_delete_term( int $term_id, int $tt_id, string...
method callback_edited_term (line 151) | public function callback_edited_term( int $term_id, int $tt_id, string...
method update_hierarchical_relatives (line 179) | public function update_hierarchical_relatives( WP_Term $term, WP_Taxon...
method callback_updated_term_meta (line 246) | public function callback_updated_term_meta( int $meta_id, int $object_...
method callback_deleted_term_meta (line 286) | public function callback_deleted_term_meta( array $meta_ids, int $obje...
FILE: src/ActionMonitor/Monitors/UserMonitor.php
class UserMonitor (line 7) | class UserMonitor extends Monitor {
method init (line 28) | public function init() {
method is_published_author (line 49) | public function is_published_author( int $user_id ) {
method should_track_meta (line 75) | public function should_track_meta( string $meta_key, $meta_value, $obj...
method callback_profile_update (line 99) | public function callback_profile_update( int $user_id ) {
method callback_delete_user (line 141) | public function callback_delete_user( $user_id, $reassign_id ) {
method callback_deleted_user (line 181) | public function callback_deleted_user( int $user_id ) {
method callback_updated_user_meta (line 257) | public function callback_updated_user_meta( int $meta_id, int $object_...
method callback_deleted_user_meta (line 294) | public function callback_deleted_user_meta( array $meta_ids, int $obje...
FILE: src/Admin/Preview.php
class Preview (line 9) | class Preview {
method __construct (line 10) | function __construct() {
method get_gatsby_content_sync_url_for_post (line 19) | public static function get_gatsby_content_sync_url_for_post( $post ) {
method get_previewable_post_object_by_post_id (line 37) | public static function get_previewable_post_object_by_post_id( $post_i...
method get_preview_manifest_id_for_post (line 54) | public static function get_preview_manifest_id_for_post( $post ) {
method print_file_contents (line 76) | public static function print_file_contents( $fileName ) {
method register_preview_status_fields_and_mutations (line 82) | function register_preview_status_fields_and_mutations() {
FILE: src/Admin/Settings.php
class Settings (line 5) | class Settings {
method __construct (line 9) | function __construct() {
method set_default_jwt_key (line 25) | public function set_default_jwt_key() {
method filter_graphql_introspection_setting_field (line 57) | public function filter_graphql_introspection_setting_field( $field_con...
method filter_graphql_introspection_setting_value (line 79) | public function filter_graphql_introspection_setting_value( $value, $d...
method admin_init (line 87) | function admin_init() {
method admin_menu (line 96) | function admin_menu() {
method get_settings_sections (line 110) | function get_settings_sections() {
method register_settings_page (line 121) | public function register_settings_page() {
method plugin_page (line 135) | function plugin_page() {
method prefix_get_option (line 151) | static public function prefix_get_option( $option, $section, $default ...
method generate_secret (line 161) | private static function generate_secret() {
method get_default_secret (line 169) | private static function get_default_secret() {
method sanitize_url_field (line 179) | public static function sanitize_url_field( $input ) {
method get_setting (line 198) | public static function get_setting( $key ) {
method get_settings_fields (line 209) | function get_settings_fields() {
FILE: src/GraphQL/Auth.php
class Auth (line 8) | class Auth {
method get_token (line 9) | static function get_token() {
FILE: src/GraphQL/ParseAuthToken.php
class ParseAuthToken (line 8) | class ParseAuthToken {
method __construct (line 9) | function __construct() {
method set_current_user (line 13) | function set_current_user() {
FILE: src/Schema/Schema.php
class Schema (line 8) | class Schema {
method __construct (line 12) | function __construct() {
FILE: src/Schema/SiteMeta.php
class SiteMeta (line 10) | class SiteMeta {
method __construct (line 14) | function __construct() {
method isVersionARange (line 23) | private static function isVersionARange( $version ) {
method register (line 37) | function register() {
FILE: src/Schema/WPGatsbyWPGraphQLSchemaChanges.php
class WPGatsbyWPGraphQLSchemaChanges (line 8) | class WPGatsbyWPGraphQLSchemaChanges {
method __construct (line 9) | function __construct() {
method register (line 18) | function register() {
FILE: src/ThemeSupport/ThemeSupport.php
class ThemeSupport (line 10) | class ThemeSupport {
method __construct (line 14) | function __construct() {
method registerGatsbyMenuLocations (line 18) | function registerGatsbyMenuLocations() {
FILE: src/Utils/Utils.php
class Utils (line 5) | class Utils {
method str_in_substr_array (line 18) | public static function str_in_substr_array(string $haystack, array $su...
FILE: tests/_support/AcceptanceTester.php
class AcceptanceTester (line 20) | class AcceptanceTester extends \Codeception\Actor {
FILE: tests/_support/FunctionalTester.php
class FunctionalTester (line 20) | class FunctionalTester extends \Codeception\Actor {
FILE: tests/_support/Helper/Acceptance.php
class Acceptance (line 7) | class Acceptance extends \Codeception\Module
FILE: tests/_support/Helper/Functional.php
class Functional (line 7) | class Functional extends \Codeception\Module
FILE: tests/_support/Helper/Unit.php
class Unit (line 7) | class Unit extends \Codeception\Module
FILE: tests/_support/Helper/Wpunit.php
class Wpunit (line 7) | class Wpunit extends \Codeception\Module
FILE: tests/_support/UnitTester.php
class UnitTester (line 19) | class UnitTester extends \Codeception\Actor
FILE: tests/_support/WpunitTester.php
class WpunitTester (line 20) | class WpunitTester extends \Codeception\Actor {
FILE: tests/wpunit/ActionMonitorTest.php
class ActionMonitorTest (line 3) | class ActionMonitorTest extends \Tests\WPGraphQL\TestCase\WPGraphQLTestC...
method setUp (line 8) | public function setUp(): void {
method tearDown (line 21) | public function tearDown(): void {
method clear_action_monitor (line 28) | public function clear_action_monitor() {
method delete_posts (line 47) | public function delete_posts() {
method test_it_works (line 58) | public function test_it_works() {
method actionMonitorQuery (line 63) | public function actionMonitorQuery() {
method testActionMonitorQueryIsValid (line 77) | public function testActionMonitorQueryIsValid() {
method testCreatePostCreatesActionMonitorAction (line 84) | public function testCreatePostCreatesActionMonitorAction() {
method testCreatePageCreatesActionMonitorAction (line 126) | public function testCreatePageCreatesActionMonitorAction() {
method testDeletePostCreatesActionMonitorAction (line 165) | public function testDeletePostCreatesActionMonitorAction() {
method testDeleteOnlyPostByAuthorCreatesActionMonitorActions (line 225) | public function testDeleteOnlyPostByAuthorCreatesActionMonitorActions() {
method testDeleteDraftPostDoesNotCreateActionMonitorAction (line 276) | public function testDeleteDraftPostDoesNotCreateActionMonitorAction() {
method testTrashPostCreatesActionMonitorAction (line 311) | public function testTrashPostCreatesActionMonitorAction() {
method testPublishPostFromDraftCreatesActionMonitorAction (line 355) | public function testPublishPostFromDraftCreatesActionMonitorAction() {
method testChangePostToDraftCreatesActionMonitorAction (line 404) | public function testChangePostToDraftCreatesActionMonitorAction() {
method testChangeAuthorsOnPublishedPostCreatesActionMonitorActions (line 454) | public function testChangeAuthorsOnPublishedPostCreatesActionMonitorAc...
method testChangeOnlyPostFromAuthorToDraftCreatesActionMonitorActions (line 529) | public function testChangeOnlyPostFromAuthorToDraftCreatesActionMonito...
method testPublishScheduledPostCreatesActionMonitorAction (line 573) | public function testPublishScheduledPostCreatesActionMonitorAction() {
method testUpdatePostMetaOfUnublishedPostDoesNotCreatesActionMonitorAction (line 617) | public function testUpdatePostMetaOfUnublishedPostDoesNotCreatesAction...
method testDeletePostMetaOfUnublishedPostDoesNotCreatesActionMonitorAction (line 644) | public function testDeletePostMetaOfUnublishedPostDoesNotCreatesAction...
method testUpdatePostMetaOfPublishedPostCreatesActionMonitorAction (line 672) | public function testUpdatePostMetaOfPublishedPostCreatesActionMonitorA...
method testDeletePostMetaCreatesActionMonitorAction (line 713) | public function testDeletePostMetaCreatesActionMonitorAction() {
method testNewPostTypesDetectedWithGraphqlSupportCreateActionMonitorAction (line 754) | public function testNewPostTypesDetectedWithGraphqlSupportCreateAction...
method testPostTypeRemovedFromGraphQLCreateActionMonitorAction (line 777) | public function testPostTypeRemovedFromGraphQLCreateActionMonitorActio...
method testTaxonomyDetectedWithGraphqlSupportCreateActionMonitorAction (line 800) | public function testTaxonomyDetectedWithGraphqlSupportCreateActionMoni...
method testTaxonomyRemovedFromGraphQLCreateActionMonitorAction (line 823) | public function testTaxonomyRemovedFromGraphQLCreateActionMonitorActio...
method testCreatePostOfAPublicCustomPostTypeCreatesActionMonitorAction (line 847) | public function testCreatePostOfAPublicCustomPostTypeCreatesActionMoni...
method testCreatePostOfCustomPostTypeNotInGraphQLDoesNotCreateActionMonitorAction (line 907) | public function testCreatePostOfCustomPostTypeNotInGraphQLDoesNotCreat...
method testCreatePostOfAPubliclyQueryableCustomPostTypeCreatesActionMonitorAction (line 939) | public function testCreatePostOfAPubliclyQueryableCustomPostTypeCreate...
method testCreateCategoryCreatesActionMonitorAction (line 1007) | public function testCreateCategoryCreatesActionMonitorAction() {
method testCreateTermOfPrivateTaxonomyDoesNotCreateActionMonitorAction (line 1037) | public function testCreateTermOfPrivateTaxonomyDoesNotCreateActionMoni...
method testUpdateCategoryCreatesActionMonitorAction (line 1065) | public function testUpdateCategoryCreatesActionMonitorAction() {
method testDeleteCategoryCreatesActionMonitorAction (line 1103) | public function testDeleteCategoryCreatesActionMonitorAction() {
method testUpdateCategoryMetaCreatesActionMonitorAction (line 1140) | public function testUpdateCategoryMetaCreatesActionMonitorAction() {
method testDeleteCategoryMetaCreatesActionMonitorAction (line 1177) | public function testDeleteCategoryMetaCreatesActionMonitorAction() {
method testCreateUserDoesNotCreateActionMonitorAction (line 1216) | public function testCreateUserDoesNotCreateActionMonitorAction() {
method testDeleteUserWithoutPublishedPostsDoesNotCreateActionMonitorAction (line 1234) | public function testDeleteUserWithoutPublishedPostsDoesNotCreateAction...
method testDeleteUserWithoutReassigningPublishedPostsCreatesActionMonitorActions (line 1262) | public function testDeleteUserWithoutReassigningPublishedPostsCreatesA...
method testDeleteUserAndReassignPostsCreatesActionMonitorAction (line 1330) | public function testDeleteUserAndReassignPostsCreatesActionMonitorActi...
method testUpdateUserWithPublishedPostsCreatesActionMonitorAction (line 1416) | public function testUpdateUserWithPublishedPostsCreatesActionMonitorAc...
method testUpdateUserMetaWithTrackedMetaKeyForPublishedAuthorCreatesActionMonitorAction (line 1466) | public function testUpdateUserMetaWithTrackedMetaKeyForPublishedAuthor...
method testUpdateUserMetaWithUntrackedMetaKeyForPublishedAuthorDoesNotCreateActionMonitorAction (line 1514) | public function testUpdateUserMetaWithUntrackedMetaKeyForPublishedAuth...
method testDeleteUserMetaForTrackedMetaKeyOfPublishedAuthorCreatesActionMonitorAction (line 1550) | public function testDeleteUserMetaForTrackedMetaKeyOfPublishedAuthorCr...
method testDeleteUserMetaForUntrackedMetaKeyOfPublishedAuthorCreatesActionMonitorAction (line 1595) | public function testDeleteUserMetaForUntrackedMetaKeyOfPublishedAuthor...
method testCreateHierarchicalTermWithParentCreatesActionMonitorAction (line 1631) | public function testCreateHierarchicalTermWithParentCreatesActionMonit...
method testUpdateHierarchicalTermWithParentAndChildCreatesActionMonitorAction (line 1667) | public function testUpdateHierarchicalTermWithParentAndChildCreatesAct...
method testDeleteHierarchicalTermThatHasParentAndChildrenCreatesActionMonitorAction (line 1727) | public function testDeleteHierarchicalTermThatHasParentAndChildrenCrea...
method testRestorePostFromTrashCreatesActionMonitorAction (line 1785) | public function testRestorePostFromTrashCreatesActionMonitorAction() {
method testUploadPngMediaItemCreatesAction (line 1833) | public function testUploadPngMediaItemCreatesAction() {
method testUpdateMediaItemCreatesAction (line 1858) | public function testUpdateMediaItemCreatesAction() {
method testDeleteMediaItemCreatesAction (line 1885) | public function testDeleteMediaItemCreatesAction() {
method testCreateNavMenuDoesNotCreateActionMonitorAction (line 1910) | public function testCreateNavMenuDoesNotCreateActionMonitorAction() {
method testAssignNavMenuToLocationCreatesActionMonitorAction (line 1925) | public function testAssignNavMenuToLocationCreatesActionMonitorAction() {
method testUpdateNavMenuCreatesActionMonitorAction (line 1964) | public function testUpdateNavMenuCreatesActionMonitorAction() {
method testDeleteMenuCreatesActionMonitorAction (line 2020) | public function testDeleteMenuCreatesActionMonitorAction() {
method testUpdatePermalinksCreatesActionMonitorAction (line 2065) | public function testUpdatePermalinksCreatesActionMonitorAction() {
method testUpdateUntrackedOptionDoesNotCreateActionMonitorAction (line 2093) | public function testUpdateUntrackedOptionDoesNotCreateActionMonitorAct...
method testSetTransientDoesNotCreateActionMonitorAction (line 2108) | public function testSetTransientDoesNotCreateActionMonitorAction() {
FILE: vendor/composer/ClassLoader.php
class ClassLoader (line 43) | class ClassLoader
method getPrefixes (line 60) | public function getPrefixes()
method getPrefixesPsr4 (line 69) | public function getPrefixesPsr4()
method getFallbackDirs (line 74) | public function getFallbackDirs()
method getFallbackDirsPsr4 (line 79) | public function getFallbackDirsPsr4()
method getClassMap (line 84) | public function getClassMap()
method addClassMap (line 92) | public function addClassMap(array $classMap)
method add (line 109) | public function add($prefix, $paths, $prepend = false)
method addPsr4 (line 156) | public function addPsr4($prefix, $paths, $prepend = false)
method set (line 201) | public function set($prefix, $paths)
method setPsr4 (line 219) | public function setPsr4($prefix, $paths)
method setUseIncludePath (line 238) | public function setUseIncludePath($useIncludePath)
method getUseIncludePath (line 249) | public function getUseIncludePath()
method setClassMapAuthoritative (line 260) | public function setClassMapAuthoritative($classMapAuthoritative)
method isClassMapAuthoritative (line 270) | public function isClassMapAuthoritative()
method setApcuPrefix (line 280) | public function setApcuPrefix($apcuPrefix)
method getApcuPrefix (line 290) | public function getApcuPrefix()
method register (line 300) | public function register($prepend = false)
method unregister (line 308) | public function unregister()
method loadClass (line 319) | public function loadClass($class)
method findFile (line 335) | public function findFile($class)
method findFileWithExtension (line 370) | private function findFileWithExtension($class, $ext)
function includeFile (line 442) | function includeFile($file)
FILE: vendor/composer/autoload_real.php
class ComposerAutoloaderInitd5ba67e9c3910011804380f1fed1cebe (line 5) | class ComposerAutoloaderInitd5ba67e9c3910011804380f1fed1cebe
method loadClassLoader (line 9) | public static function loadClassLoader($class)
method getLoader (line 19) | public static function getLoader()
FILE: vendor/composer/autoload_static.php
class ComposerStaticInitd5ba67e9c3910011804380f1fed1cebe (line 7) | class ComposerStaticInitd5ba67e9c3910011804380f1fed1cebe
method getInitializer (line 122) | public static function getInitializer(ClassLoader $loader)
FILE: vendor/firebase/php-jwt/src/BeforeValidException.php
class BeforeValidException (line 4) | class BeforeValidException extends \UnexpectedValueException
FILE: vendor/firebase/php-jwt/src/ExpiredException.php
class ExpiredException (line 4) | class ExpiredException extends \UnexpectedValueException
FILE: vendor/firebase/php-jwt/src/JWK.php
class JWK (line 20) | class JWK
method parseKeySet (line 35) | public static function parseKeySet(array $jwks)
method parseKey (line 73) | private static function parseKey(array $jwk)
method createPemFromModulusAndExponent (line 115) | private static function createPemFromModulusAndExponent($n, $e)
method encodeLength (line 161) | private static function encodeLength($length)
FILE: vendor/firebase/php-jwt/src/JWT.php
class JWT (line 23) | class JWT
method decode (line 74) | public static function decode($jwt, $key, array $allowed_algs = array())
method encode (line 166) | public static function encode($payload, $key, $alg = 'HS256', $keyId =...
method sign (line 198) | public static function sign($msg, $key, $alg = 'HS256')
method verify (line 234) | private static function verify($msg, $signature, $key, $alg)
method jsonDecode (line 280) | public static function jsonDecode($input)
method jsonEncode (line 315) | public static function jsonEncode($input)
method urlsafeB64Decode (line 333) | public static function urlsafeB64Decode($input)
method urlsafeB64Encode (line 350) | public static function urlsafeB64Encode($input)
method handleJsonError (line 362) | private static function handleJsonError($errno)
method safeStrlen (line 385) | private static function safeStrlen($str)
method signatureToDER (line 399) | private static function signatureToDER($sig)
method encodeDER (line 431) | private static function encodeDER($type, $value)
method signatureFromDER (line 454) | private static function signatureFromDER($der, $keySize)
method readDER (line 481) | private static function readDER($der, $offset = 0)
FILE: vendor/firebase/php-jwt/src/SignatureInvalidException.php
class SignatureInvalidException (line 4) | class SignatureInvalidException extends \UnexpectedValueException
FILE: wp-gatsby.php
class WPGatsby (line 35) | final class WPGatsby
method instance (line 51) | public static function instance()
method __clone (line 72) | public function __clone()
method __wakeup (line 87) | public function __wakeup()
method setup_constants (line 102) | private function setup_constants()
method includes (line 148) | private function includes()
method init (line 173) | public static function init()
function wpgatsby_show_admin_notice (line 211) | function wpgatsby_show_admin_notice()
function gatsby_init (line 234) | function gatsby_init()
Condensed preview — 87 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (444K chars).
[
{
"path": ".dockerignore",
"chars": 61,
"preview": ".env\n.github_changelog_generator\n.travis.yml\ncodeception.yml\n"
},
{
"path": ".env.dist",
"chars": 628,
"preview": "DB_NAME=wordpress\nDB_HOST=app_db\nDB_USER=wordpress\nDB_PASSWORD=wordpress\nWP_TABLE_PREFIX=wp_\nWP_URL=http://localhost\nWP_"
},
{
"path": ".github/workflows/main.yml",
"chars": 392,
"preview": "name: Deploy to WordPress.org\non:\n push:\n tags:\n - \"*\"\njobs:\n tag:\n name: New tag\n runs-on: ubuntu-latest\n"
},
{
"path": ".github/workflows/tests.yml",
"chars": 1927,
"preview": "name: Automated-Testing\n\non:\n push:\n branches:\n - master\n pull_request:\n types: [opened, synchronize]\n\njobs"
},
{
"path": ".gitignore",
"chars": 485,
"preview": ".DS_Store\nnode_modules\nphpcs.xml\nphpunit.xml\nThumbs.db\nwp-cli.local.yml\nnode_modules/\n*.sql\n*.tar.gz\n*.zip\n.env\n.env.*\n!"
},
{
"path": ".prettierrc.js",
"chars": 58,
"preview": "module.exports = {\n\tarrowParens: \"avoid\",\n\tsemi: false,\n}\n"
},
{
"path": "CHANGELOG.md",
"chars": 18472,
"preview": "# Change Log\n\n## 2.3.3\n\nFixes an issue where publicly_queryable post types that were not public weren't being tracked in"
},
{
"path": "README.md",
"chars": 1945,
"preview": "<div align=\"center\" style=\"margin-bottom: 20px;\">\n<img src=\"https://raw.githubusercontent.com/gatsbyjs/gatsby/master/pac"
},
{
"path": "access-functions.php",
"chars": 6,
"preview": "<?php\n"
},
{
"path": "bin/install-test-env.sh",
"chars": 5772,
"preview": "#!/usr/bin/env bash\n\nsource .env\n\nprint_usage_instruction() {\n\techo \"Ensure that .env file exist in project root directo"
},
{
"path": "bin/run-docker.sh",
"chars": 2499,
"preview": "#!/usr/bin/env bash\n\nset -eu\n\n##\n# Use this script through Composer scripts in the package.json.\n# To quickly build and "
},
{
"path": "codeception.dist.yml",
"chars": 2204,
"preview": "paths:\n tests: '%TESTS_DIR%'\n output: '%TESTS_OUTPUT%'\n data: '%TESTS_DATA%'\n support: '%TESTS_SUPPORT%'\n envs: '%T"
},
{
"path": "composer.json",
"chars": 2140,
"preview": "{\n \"name\": \"gatsbyjs/wp-gatsby\",\n \"description\": \"Optimize your WordPress site as a source for Gatsby site(s)\",\n \"typ"
},
{
"path": "docker/app.Dockerfile",
"chars": 1929,
"preview": "###############################################################################\n# Pre-configured WordPress Installation "
},
{
"path": "docker/app.entrypoint.sh",
"chars": 1394,
"preview": "#!/bin/bash\n\n# Run WordPress docker entrypoint.\n. docker-entrypoint.sh 'apache2'\n\nset +u\n\n# Ensure mysql is loaded\ndocke"
},
{
"path": "docker/testing.Dockerfile",
"chars": 1300,
"preview": "############################################################################\n# Container for running Codeception tests o"
},
{
"path": "docker/testing.entrypoint.sh",
"chars": 3672,
"preview": "#!/bin/bash\n\n# Processes parameters and runs Codeception.\nrun_tests() {\n echo \"Running Tests\"\n if [[ -n \"$COVERAGE"
},
{
"path": "docker-compose.yml",
"chars": 1486,
"preview": "version: '3.3'\n\nservices:\n app:\n depends_on:\n - app_db\n image: wpgatsby-app:latest\n volumes:\n - '.:/"
},
{
"path": "docs/action-monitor.md",
"chars": 8348,
"preview": "# Activity Monitor\n\nWPGatsby monitors activity that occurs in your WordPress site and notifies your Gatsby site\nof the c"
},
{
"path": "docs/running-tests.md",
"chars": 4922,
"preview": "# Running Tests\n\nThis document provides information on running tests locally.\n\nThere are 2 options: \n\n- [Running tests w"
},
{
"path": "lib/wp-settings-api.php",
"chars": 21541,
"preview": "<?php\n\n/**\n * weDevs Settings API wrapper class\n *\n * @version 1.3 (27-Sep-2016)\n *\n * @author Tareq Hasan <tareq@weDev"
},
{
"path": "license.txt",
"chars": 35457,
"preview": "WPGatsby\n\nCopyright 2020 by the contributors\n\nThis plugin was originally started by Geoffrey Sechter and then this repo "
},
{
"path": "readme.txt",
"chars": 2272,
"preview": "=== WPGatsby ===\nContributors: gatsbyinc, jasonbahl, tylerbarnes1\nTags: Gatsby, GatsbyJS, JavaScript, JAMStack, Static S"
},
{
"path": "src/ActionMonitor/ActionMonitor.php",
"chars": 22170,
"preview": "<?php\n\nnamespace WPGatsby\\ActionMonitor;\n\nuse WP_Post;\nuse WPGatsby\\Admin\\Settings;\n\n/**\n * This class registers and con"
},
{
"path": "src/ActionMonitor/Monitors/AcfMonitor.php",
"chars": 1584,
"preview": "<?php\n\nnamespace WPGatsby\\ActionMonitor\\Monitors;\n\nuse WPGatsby\\Utils\\Utils;\n\nclass AcfMonitor extends Monitor {\n\n\tpubli"
},
{
"path": "src/ActionMonitor/Monitors/MediaMonitor.php",
"chars": 4279,
"preview": "<?php\n\nnamespace WPGatsby\\ActionMonitor\\Monitors;\n\nuse GraphQLRelay\\Relay;\n\nclass MediaMonitor extends Monitor {\n\n\t/**\n"
},
{
"path": "src/ActionMonitor/Monitors/Monitor.php",
"chars": 10832,
"preview": "<?php\nnamespace WPGatsby\\ActionMonitor\\Monitors;\n\nuse GraphQLRelay\\Relay;\nuse WPGatsby\\ActionMonitor\\ActionMonitor;\nuse "
},
{
"path": "src/ActionMonitor/Monitors/NavMenuMonitor.php",
"chars": 8346,
"preview": "<?php\n\nnamespace WPGatsby\\ActionMonitor\\Monitors;\n\nuse GraphQLRelay\\Relay;\nuse WP_Term;\n\nclass NavMenuMonitor extends Mo"
},
{
"path": "src/ActionMonitor/Monitors/PostMonitor.php",
"chars": 9892,
"preview": "<?php\n\nnamespace WPGatsby\\ActionMonitor\\Monitors;\n\nuse GraphQLRelay\\Relay;\nuse WP_Post;\n\nclass PostMonitor extends Monit"
},
{
"path": "src/ActionMonitor/Monitors/PostTypeMonitor.php",
"chars": 1952,
"preview": "<?php\nnamespace WPGatsby\\ActionMonitor\\Monitors;\n\nclass PostTypeMonitor extends Monitor {\n\n\t/**\n\t * @var array List of r"
},
{
"path": "src/ActionMonitor/Monitors/PreviewMonitor.php",
"chars": 7512,
"preview": "<?php\n\nnamespace WPGatsby\\ActionMonitor\\Monitors;\n\nuse GraphQLRelay\\Relay;\nuse WPGatsby\\Admin\\Preview;\nuse WPGatsby\\Admi"
},
{
"path": "src/ActionMonitor/Monitors/SettingsMonitor.php",
"chars": 7651,
"preview": "<?php\nnamespace WPGatsby\\ActionMonitor\\Monitors;\n\nuse GraphQLRelay\\Relay;\n\nclass SettingsMonitor extends Monitor {\n\n\t/**"
},
{
"path": "src/ActionMonitor/Monitors/TaxonomyMonitor.php",
"chars": 1950,
"preview": "<?php\nnamespace WPGatsby\\ActionMonitor\\Monitors;\n\nclass TaxonomyMonitor extends Monitor {\n\n\t/**\n\t * @var array List of r"
},
{
"path": "src/ActionMonitor/Monitors/TermMonitor.php",
"chars": 9215,
"preview": "<?php\n\nnamespace WPGatsby\\ActionMonitor\\Monitors;\n\nuse GraphQLRelay\\Relay;\nuse WP_Taxonomy;\nuse WP_Term;\n\nclass TermMoni"
},
{
"path": "src/ActionMonitor/Monitors/UserMonitor.php",
"chars": 9490,
"preview": "<?php\n\nnamespace WPGatsby\\ActionMonitor\\Monitors;\n\nuse GraphQLRelay\\Relay;\n\nclass UserMonitor extends Monitor {\n\n\t/**\n\t "
},
{
"path": "src/Admin/Preview.php",
"chars": 13741,
"preview": "<?php\n\nnamespace WPGatsby\\Admin;\n\nuse GraphQL\\Error\\UserError;\nuse WPGraphQL\\Router;\nuse WPGatsby\\Admin\\Settings;\n\nclass"
},
{
"path": "src/Admin/Settings.php",
"chars": 8431,
"preview": "<?php\n\nnamespace WPGatsby\\Admin;\n\nclass Settings {\n\n\tprivate $settings_api;\n\n\tfunction __construct() {\n\n\t\t$this->setting"
},
{
"path": "src/Admin/includes/no-preview-url-set.php",
"chars": 919,
"preview": "<?php use WPGatsby\\Admin\\Preview; ?>\n<html lang=\"en\">\n\n<head>\n\t<meta charset=\"UTF-8\">\n\t<meta name=\"viewport\" content=\"wi"
},
{
"path": "src/Admin/includes/post-type-not-shown-in-graphql.php",
"chars": 921,
"preview": "<?php use WPGatsby\\Admin\\Preview; ?>\n<html lang=\"en\">\n\n<head>\n\t<meta charset=\"UTF-8\">\n\t<meta name=\"viewport\" content=\"wi"
},
{
"path": "src/Admin/includes/preview-template.php",
"chars": 2561,
"preview": "<?php\n\nuse WPGatsby\\Admin\\Preview;\n\nglobal $post;\n\n$gatsby_content_sync_url = Preview::get_gatsby_content_sync_url_for_p"
},
{
"path": "src/Admin/includes/style.css",
"chars": 3220,
"preview": "#loader {\n position: fixed;\n top: 32px;\n bottom: 0;\n left: 0;\n right: 0;\n width: 100%;\n height: 100%;\n height: c"
},
{
"path": "src/GraphQL/Auth.php",
"chars": 575,
"preview": "<?php\n\nnamespace WPGatsby\\GraphQL;\n\nuse \\Firebase\\JWT\\JWT;\nuse \\WPGatsby\\Admin\\Settings;\n\nclass Auth {\n\tstatic function "
},
{
"path": "src/GraphQL/ParseAuthToken.php",
"chars": 1024,
"preview": "<?php\n\nnamespace WPGatsby\\GraphQL;\n\nuse \\Firebase\\JWT\\JWT;\nuse \\WPGatsby\\Admin\\Settings;\n\nclass ParseAuthToken {\n\tfuncti"
},
{
"path": "src/Schema/Schema.php",
"chars": 184,
"preview": "<?php\n\nnamespace WPGatsby\\Schema;\n\n/**\n * Modifies the schema\n */\nclass Schema {\n\t/**\n\t *\n\t */\n\tfunction __construct() {"
},
{
"path": "src/Schema/SiteMeta.php",
"chars": 5961,
"preview": "<?php\n\nnamespace WPGatsby\\Schema;\n\nuse Composer\\Semver\\Semver;\n\n/**\n * Adds info about the current site\n */\nclass SiteMe"
},
{
"path": "src/Schema/WPGatsbyWPGraphQLSchemaChanges.php",
"chars": 1389,
"preview": "<?php\n\nnamespace WPGatsby\\Schema;\n\n/**\n * Modifies WPGraphQL built-in types\n */\nclass WPGatsbyWPGraphQLSchemaChanges {\n\t"
},
{
"path": "src/ThemeSupport/ThemeSupport.php",
"chars": 706,
"preview": "<?php\n\nnamespace WPGatsby\\ThemeSupport;\n\nuse WPGatsby\\Admin\\Settings;\n\n/**\n * Modifies the schema\n */\nclass ThemeSupport"
},
{
"path": "src/Utils/Utils.php",
"chars": 622,
"preview": "<?php\n\nnamespace WPGatsby\\Utils;\n\nclass Utils {\n\n /**\n * Checks if any of the strings in $substr_array is a subst"
},
{
"path": "tests/_data/.gitignore",
"chars": 9,
"preview": "dump.sql\n"
},
{
"path": "tests/_data/.gitkeep",
"chars": 0,
"preview": ""
},
{
"path": "tests/_data/config.php",
"chars": 252,
"preview": "<?php\n/**\n * Disable autoloading while running tests, as the test\n * suite already bootstraps the autoloader and creates"
},
{
"path": "tests/_output/.gitignore",
"chars": 7,
"preview": "failed\n"
},
{
"path": "tests/_output/.gitkeep",
"chars": 0,
"preview": ""
},
{
"path": "tests/_support/AcceptanceTester.php",
"chars": 606,
"preview": "<?php\n\n\n/**\n * Inherited Methods\n *\n * @method void wantToTest($text)\n * @method void wantTo($text)\n * @method void exec"
},
{
"path": "tests/_support/FunctionalTester.php",
"chars": 606,
"preview": "<?php\n\n\n/**\n * Inherited Methods\n *\n * @method void wantToTest($text)\n * @method void wantTo($text)\n * @method void exec"
},
{
"path": "tests/_support/Helper/Acceptance.php",
"chars": 185,
"preview": "<?php\nnamespace Helper;\n\n// here you can define custom actions\n// all public methods declared in helper class will be av"
},
{
"path": "tests/_support/Helper/Functional.php",
"chars": 185,
"preview": "<?php\nnamespace Helper;\n\n// here you can define custom actions\n// all public methods declared in helper class will be av"
},
{
"path": "tests/_support/Helper/Unit.php",
"chars": 179,
"preview": "<?php\nnamespace Helper;\n\n// here you can define custom actions\n// all public methods declared in helper class will be av"
},
{
"path": "tests/_support/Helper/Wpunit.php",
"chars": 181,
"preview": "<?php\nnamespace Helper;\n\n// here you can define custom actions\n// all public methods declared in helper class will be av"
},
{
"path": "tests/_support/UnitTester.php",
"chars": 598,
"preview": "<?php\n\n\n/**\n * Inherited Methods\n * @method void wantToTest($text)\n * @method void wantTo($text)\n * @method void execute"
},
{
"path": "tests/_support/WpunitTester.php",
"chars": 599,
"preview": "<?php\n\n\n/**\n * Inherited Methods\n *\n * @method void wantToTest($text)\n * @method void wantTo($text)\n * @method void exec"
},
{
"path": "tests/_support/_generated/.gitignore",
"chars": 13,
"preview": "*\n!.gitignore"
},
{
"path": "tests/acceptance.suite.dist.yml",
"chars": 417,
"preview": "# Codeception Test Suite Configuration\n#\n# Suite for acceptance tests.\n# Perform tests in browser using the WPWebDriver "
},
{
"path": "tests/functional.suite.dist.yml",
"chars": 278,
"preview": "# Codeception Test Suite Configuration\n#\n# Suite for functional tests\n# Emulate web requests and make WordPress process "
},
{
"path": "tests/wpunit/ActionMonitorTest.php",
"chars": 65184,
"preview": "<?php\n\nclass ActionMonitorTest extends \\Tests\\WPGraphQL\\TestCase\\WPGraphQLTestCase {\n\n\tpublic $admin;\n\tpublic $tag;\n\n\tpu"
},
{
"path": "tests/wpunit.suite.dist.yml",
"chars": 453,
"preview": "# Codeception Test Suite Configuration\n#\n# Suite for unit or integration tests that require WordPress functions and clas"
},
{
"path": "vendor/autoload.php",
"chars": 178,
"preview": "<?php\n\n// autoload.php @generated by Composer\n\nrequire_once __DIR__ . '/composer/autoload_real.php';\n\nreturn ComposerAut"
},
{
"path": "vendor/composer/ClassLoader.php",
"chars": 13473,
"preview": "<?php\n\n/*\n * This file is part of Composer.\n *\n * (c) Nils Adermann <naderman@naderman.de>\n * Jordi Boggiano <j.bogg"
},
{
"path": "vendor/composer/LICENSE",
"chars": 1070,
"preview": "\nCopyright (c) Nils Adermann, Jordi Boggiano\n\nPermission is hereby granted, free of charge, to any person obtaining a co"
},
{
"path": "vendor/composer/autoload_classmap.php",
"chars": 6675,
"preview": "<?php\n\n// autoload_classmap.php @generated by Composer\n\n$vendorDir = dirname(dirname(__FILE__));\n$baseDir = dirname($ven"
},
{
"path": "vendor/composer/autoload_namespaces.php",
"chars": 289,
"preview": "<?php\n\n// autoload_namespaces.php @generated by Composer\n\n$vendorDir = dirname(dirname(__FILE__));\n$baseDir = dirname($v"
},
{
"path": "vendor/composer/autoload_psr4.php",
"chars": 331,
"preview": "<?php\n\n// autoload_psr4.php @generated by Composer\n\n$vendorDir = dirname(dirname(__FILE__));\n$baseDir = dirname($vendorD"
},
{
"path": "vendor/composer/autoload_real.php",
"chars": 1824,
"preview": "<?php\n\n// autoload_real.php @generated by Composer\n\nclass ComposerAutoloaderInitd5ba67e9c3910011804380f1fed1cebe\n{\n p"
},
{
"path": "vendor/composer/autoload_static.php",
"chars": 9056,
"preview": "<?php\n\n// autoload_static.php @generated by Composer\n\nnamespace Composer\\Autoload;\n\nclass ComposerStaticInitd5ba67e9c391"
},
{
"path": "vendor/composer/semver/CHANGELOG.md",
"chars": 4791,
"preview": "# Change Log\n\nAll notable changes to this project will be documented in this file.\nThis project adheres to [Semantic Ver"
},
{
"path": "vendor/composer/semver/LICENSE",
"chars": 1052,
"preview": "Copyright (C) 2015 Composer\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis softwa"
},
{
"path": "vendor/composer/semver/README.md",
"chars": 1643,
"preview": "composer/semver\n===============\n\nSemver library that offers utilities, version constraint parsing and validation.\n\nOrigi"
},
{
"path": "vendor/composer/semver/composer.json",
"chars": 1356,
"preview": "{\n \"name\": \"composer/semver\",\n \"description\": \"Semver library that offers utilities, version constraint parsing an"
},
{
"path": "vendor/firebase/php-jwt/LICENSE",
"chars": 1520,
"preview": "Copyright (c) 2011, Neuman Vong\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or withou"
},
{
"path": "vendor/firebase/php-jwt/README.md",
"chars": 7950,
"preview": "[](https://travis-ci.org/firebase/php-jwt)\n[![L"
},
{
"path": "vendor/firebase/php-jwt/composer.json",
"chars": 796,
"preview": "{\n \"name\": \"firebase/php-jwt\",\n \"description\": \"A simple library to encode and decode JSON Web Tokens (JWT) in PHP"
},
{
"path": "vendor/firebase/php-jwt/src/BeforeValidException.php",
"chars": 96,
"preview": "<?php\nnamespace Firebase\\JWT;\n\nclass BeforeValidException extends \\UnexpectedValueException\n{\n}\n"
},
{
"path": "vendor/firebase/php-jwt/src/ExpiredException.php",
"chars": 92,
"preview": "<?php\nnamespace Firebase\\JWT;\n\nclass ExpiredException extends \\UnexpectedValueException\n{\n}\n"
},
{
"path": "vendor/firebase/php-jwt/src/JWK.php",
"chars": 5586,
"preview": "<?php\n\nnamespace Firebase\\JWT;\n\nuse DomainException;\nuse UnexpectedValueException;\n\n/**\n * JSON Web Key implementation, "
},
{
"path": "vendor/firebase/php-jwt/src/JWT.php",
"chars": 18512,
"preview": "<?php\n\nnamespace Firebase\\JWT;\n\nuse \\DomainException;\nuse \\InvalidArgumentException;\nuse \\UnexpectedValueException;\nuse "
},
{
"path": "vendor/firebase/php-jwt/src/SignatureInvalidException.php",
"chars": 101,
"preview": "<?php\nnamespace Firebase\\JWT;\n\nclass SignatureInvalidException extends \\UnexpectedValueException\n{\n}\n"
},
{
"path": "wp-gatsby.php",
"chars": 6467,
"preview": "<?php\n/**\n * Plugin Name: WP Gatsby\n * Description: Optimize your WordPress site to be a source for Gatsby sites.\n * Ver"
}
]
About this extraction
This page contains the full source code of the gatsbyjs/wp-gatsby GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 87 files (397.1 KB), approximately 111.7k tokens, and a symbol index with 291 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.