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 ================================================
Wapuu hugging a ball with the Gatsby logo on it

Gatsby and gatsby-source-wordpress are released under the MIT license. Follow @gatsbyjs

# 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 ================================================ "$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 " RewriteEngine On RewriteBase / SetEnvIf Authorization \"(.*)\" HTTP_AUTHORIZATION=\$1 RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] " >> ${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) ## 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. ![.env example](img/testing-env-example.png) 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. ![codeception.yml params config](img/codeception-yml-changes.png) ![codeception.yml WPLoader config](img/codeception-wploader-config.png) 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. ![WPUnit test results](img/test-results.png) 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 ``` ## 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 ================================================ * @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'] = '
' . $section['desc'] . '
'; $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( '

%s

', $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( '', $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( '', $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 = '
'; $html .= sprintf( '', $args['desc'] ); $html .= '
'; 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 = '
'; $html .= sprintf( '', $args['section'], $args['id'] ); foreach ( $args['options'] as $key => $label ) { $checked = isset( $value[ $key ] ) ? $value[ $key ] : '0'; $html .= sprintf( '
', $label ); } $html .= $this->get_field_description( $args ); $html .= '
'; 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 = '
'; foreach ( $args['options'] as $key => $label ) { $html .= sprintf( '
', $label ); } $html .= $this->get_field_description( $args ); $html .= '
'; 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( '' ); $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( '', $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 '
'; $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 '
'; 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( '', $size, $args['section'], $args['id'], $value ); $html .= ''; $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( '', $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( '', $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 = ''; echo $html; } /** * Show the section settings forms * * This function displays every sections in a different form */ function show_forms() { ?>
settings_sections as $form ) { ?>
script(); } /** * Tabbable JavaScript codes & Initiate Color Picker * * This code uses localstorage for displaying active tabs */ function script() { ?> _style_fix(); } function _style_fix() { global $wp_version; if ( version_compare( $wp_version, '3.8', '<=' ) ) : ?> 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. Copyright © 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 . 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: Copyright © 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 . 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 . ================================================ 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
Wapuu hugging a ball with the Gatsby logo on it

Gatsby and gatsby-source-wordpress are released under the MIT license. Follow @gatsbyjs

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 ================================================ 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 '

'; echo '' . esc_html( $modified ) . '
'; echo '

'; } } /** * 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 ================================================ 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 ================================================ 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 ================================================ 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 ================================================ 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 ================================================ 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 ================================================ 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 ================================================ 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 ================================================ 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 ================================================ 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 ================================================ action_monitor->get_tracked_taxonomies(), true ); } /** * Tracks creation of terms * * @param int $term_id Term ID. * @param int $tt_id Taxonomy term ID. * @param string $taxonomy Taxonomy name. */ public function callback_created_term( int $term_id, int $tt_id, string $taxonomy ) { $tax_object = get_taxonomy( $taxonomy ); // If the term is in a taxonomy that's not being tracked, ignore it if ( false === $tax_object || ! $this->is_taxonomy_tracked( $taxonomy ) ) { return; } $term = get_term( $term_id, $taxonomy ); if ( ! is_a( $term, 'WP_Term' ) ) { return; } $this->log_action( [ 'action_type' => 'CREATE', 'title' => $term->name, 'node_id' => $term->term_id, 'relay_id' => Relay::toGlobalId( 'term', $term->term_id ), 'graphql_single_name' => $tax_object->graphql_single_name, 'graphql_plural_name' => $tax_object->graphql_plural_name, 'status' => 'publish', ] ); if ( true === $tax_object->hierarchical ) { $this->update_hierarchical_relatives( $term, $tax_object ); } } /** * @param int $term_id The ID of the term object being deleted * @param string $taxonomy The name of the taxonomy of the term being deleted */ public function callback_pre_delete_term( int $term_id, string $taxonomy ) { $term = get_term_by( 'id', $term_id, $taxonomy ); if ( ! $term instanceof WP_Term ) { return; } $before_delete = [ 'term' => $term, ]; if ( true === get_taxonomy( $taxonomy )->hierarchical ) { $term_children = get_term_children( $term->term_id, $taxonomy ); if ( ! empty( $term_children ) ) { $before_delete['children'] = $term_children; } } $this->terms_before_delete[ $term->term_id ] = $before_delete; } /** * Tracks deletion of taxonomy terms * * @param int $term_id Term ID. * @param int $tt_id Taxonomy term ID. * @param string $taxonomy Taxonomy name. * @param mixed $deleted_term Deleted term object. */ public function callback_delete_term( int $term_id, int $tt_id, string $taxonomy, $deleted_term ) { $tax_object = get_taxonomy( $taxonomy ); if ( false === $tax_object || ! $this->is_taxonomy_tracked( $taxonomy ) ) { return; } $this->log_action( [ 'action_type' => 'DELETE', 'title' => $deleted_term->name, 'node_id' => $deleted_term->term_id, 'relay_id' => Relay::toGlobalId( 'term', $deleted_term->term_id ), 'graphql_single_name' => $tax_object->graphql_single_name, 'graphql_plural_name' => $tax_object->graphql_plural_name, 'status' => 'trash', ] ); if ( true === $tax_object->hierarchical ) { $this->update_hierarchical_relatives( $deleted_term, $tax_object ); } } /** * Tracks updated of taxonomy terms * * @param int $term_id Term ID. * @param int $tt_id Taxonomy term ID. * @param string $taxonomy Taxonomy name. */ public function callback_edited_term( int $term_id, int $tt_id, string $taxonomy ) { $tax_object = get_taxonomy( $taxonomy ); if ( false === $tax_object || ! $this->is_taxonomy_tracked( $taxonomy ) ) { return; } $term = get_term( $term_id, $taxonomy ); $this->log_action( [ 'action_type' => 'UPDATE', 'title' => $term->name, 'node_id' => $term->term_id, 'relay_id' => Relay::toGlobalId( 'term', $term->term_id ), 'graphql_single_name' => $tax_object->graphql_single_name, 'graphql_plural_name' => $tax_object->graphql_plural_name, 'status' => 'publish', ] ); if ( true === $tax_object->hierarchical ) { $this->update_hierarchical_relatives( $term, $tax_object ); } } public function update_hierarchical_relatives( WP_Term $term, WP_Taxonomy $tax_object ) { $taxonomy = $tax_object->name; if ( true === $tax_object->hierarchical ) { if ( ! empty( $term->parent ) ) { $parent = get_term_by( 'id', absint( $term->parent ), $taxonomy ); if ( is_a( $parent, 'WP_Term' ) ) { $this->log_action( [ 'action_type' => 'UPDATE', 'title' => $parent->name . ' Parent', 'node_id' => $parent->term_id, 'relay_id' => Relay::toGlobalId( 'term', $parent->term_id ), 'graphql_single_name' => $tax_object->graphql_single_name, 'graphql_plural_name' => $tax_object->graphql_plural_name, 'status' => 'publish', ] ); } } if ( isset( $this->terms_before_delete[ $term->term_id ]['children'] ) ) { $child_ids = $this->terms_before_delete[ $term->term_id ]['children']; } else { $child_ids = get_term_children( $term->term_id, $taxonomy ); } if ( ! empty( $child_ids ) && is_array( $child_ids ) ) { foreach ( $child_ids as $child_term_id ) { $child_term = get_term_by( 'id', $child_term_id, $taxonomy ); if ( ! empty( $child_term ) ) { $this->log_action( [ 'action_type' => 'UPDATE', 'title' => $child_term->name . ' Parent', 'node_id' => $child_term->term_id, 'relay_id' => Relay::toGlobalId( 'term', $child_term->term_id ), 'graphql_single_name' => $tax_object->graphql_single_name, 'graphql_plural_name' => $tax_object->graphql_plural_name, 'status' => 'publish', ] ); } } } } } /** * Logs activity when meta is updated on terms * * @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_term_meta( int $meta_id, int $object_id, string $meta_key, $meta_value ) { if ( empty( $term = get_term( $object_id ) ) || ! is_a( $term, 'WP_Term' ) ) { return; } $tax_object = get_taxonomy( $term->taxonomy ); // If the updated term is of a post type that isn't being tracked, do nothing if ( false === $tax_object || ! $this->is_taxonomy_tracked( $term->taxonomy ) ) { return; } if ( false === $this->should_track_meta( $meta_key, $meta_value, $term ) ) { return; } $action = [ 'action_type' => 'UPDATE', 'title' => $term->name, 'node_id' => $term->term_id, 'relay_id' => Relay::toGlobalId( 'term', $term->term_id ), 'graphql_single_name' => $tax_object->graphql_single_name, 'graphql_plural_name' => $tax_object->graphql_plural_name, 'status' => 'publish', ]; // Log the action $this->log_action( $action ); } /** * Logs activity when meta is updated on terms * * @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_term_meta( array $meta_ids, int $object_id, string $meta_key, $meta_value ) { if ( empty( $term = get_term( $object_id ) ) || ! is_a( $term, 'WP_Term' ) ) { return; } $tax_object = get_taxonomy( $term->taxonomy ); // If the updated term is of a post type that isn't being tracked, do nothing if ( false === $tax_object || ! $this->is_taxonomy_tracked( $term->taxonomy ) ) { return; } if ( false === $this->should_track_meta( $meta_key, $meta_value, $term ) ) { return; } $action = [ 'action_type' => 'UPDATE', 'title' => $term->name, 'node_id' => $term->term_id, 'relay_id' => Relay::toGlobalId( 'term', $term->term_id ), 'graphql_single_name' => $tax_object->graphql_single_name, 'graphql_plural_name' => $tax_object->graphql_plural_name, 'status' => 'publish', ]; // Log the action $this->log_action( $action ); } } ================================================ FILE: src/ActionMonitor/Monitors/UserMonitor.php ================================================ */ protected $users_before_delete; /** * IDs of posts to reassign * * @var array */ protected $post_ids_to_reassign; /** * Initialize UserMonitor Actions * * @return void */ public function init() { $this->post_ids_to_reassign = []; add_action( 'profile_update', [ $this, 'callback_profile_update' ], 10, 1 ); add_action( 'delete_user', [ $this, 'callback_delete_user' ], 10, 2 ); add_action( 'deleted_user', [ $this, 'callback_deleted_user' ], 10, 1 ); add_action( 'updated_user_meta', [ $this, 'callback_updated_user_meta' ], 10, 4 ); add_action( 'added_user_meta', [ $this, 'callback_updated_user_meta' ], 10, 4 ); add_action( 'deleted_user_meta', [ $this, 'callback_deleted_user_meta' ], 10, 4 ); } /** * This method accepts a user ID, and checks if the user has published posts * of any of the tracked post types * * @param int $user_id The ID of the user to check * * @return bool */ public function is_published_author( int $user_id ) { $post_types = $this->action_monitor->get_tracked_post_types(); $published_posts_count = count_user_posts( $user_id, $post_types ); if ( empty( $published_posts_count ) ) { return false; } return true; } /** * Determines whether the meta should be tracked or not. * * User meta is all untracked other than a few specific keys. Plugins and themes that * expose user meta intended for public display will need to filter this to * have updates to those meta fields trigger updates with Gatsby. * * @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 */ public function should_track_meta( string $meta_key, $meta_value, $object ) { $tracked_meta_keys = [ 'description', 'nickname', 'firstName', 'lastName', ]; $tracked_meta_keys = apply_filters( 'gatsby_action_monitor_tracked_user_meta_keys', $tracked_meta_keys, $meta_key, $meta_value, $object ); if ( in_array( $meta_key, $tracked_meta_keys, true ) ) { return true; } return false; } /** * Log action when a user is updated. * * @param int $user_id */ public function callback_profile_update( int $user_id ) { if ( empty( $user_id ) ) { return; } $user = get_user_by( 'id', $user_id ); if ( ! $user instanceof \WP_User || $user_id !== $user->ID ) { return; } if ( ! $this->is_published_author( $user_id ) ) { return; } $this->log_action( [ 'action_type' => 'UPDATE', 'title' => $user->display_name, 'node_id' => (int) $user->ID, 'relay_id' => Relay::toGlobalId( 'user', (int) $user->ID ), 'graphql_single_name' => 'user', 'graphql_plural_name' => 'users', 'status' => 'publish', ] ); } /** * There's no logging in this callback's action, the reason * behind this hook is so that we can store user objects before * being deleted. * * During `deleted_user` hook, our callback * receives $user_id param but it's useless as the user record * was already removed from DB. * * @param mixed|int|null $user_id User ID that may be deleted * @param mixed|int|null $reassign_id User ID that posts should be reassigned to */ public function callback_delete_user( $user_id, $reassign_id ) { if ( empty( $user_id ) ) { return; } if ( ! $this->is_published_author( $user_id ) ) { return; } // Get the user the posts should be re-assigned to $reassign_user = ! empty( $reassign_id ) ? get_user_by( 'id', $reassign_id ) : null; if ( ! empty( $reassign_user ) ) { // @todo: We should get rid of this as it can get expensive to log these actions. // Gatsby Source WordPress should have support for bulk-actions so we can log a single action // such as "DELETE_AUTHOR_AND_REASSIGN_POSTS" and pass the old author ID and new author ID and // Gatsby could do it without an action per modified post. global $wpdb; $post_types = $this->action_monitor->get_tracked_post_types(); $post_types = implode( "', '", $post_types ); $post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_author = %d AND post_status = 'publish' AND post_type IN ('$post_types')", $user_id ) ); if ( ! empty( $post_ids ) && is_array( $post_ids ) ) { $this->post_ids_to_reassign = array_merge( $this->post_ids_to_reassign, $post_ids ); } } $this->users_before_delete[ (int) $user_id ] = [ 'user' => get_user_by( 'id', (int) $user_id ), 'reassign' => ! empty( $reassign_user ) && $reassign_user instanceof \WP_User ? $reassign_user : null, ]; } /** * Log deleted user. * * @param int $user_id Deleted user ID */ public function callback_deleted_user( int $user_id ) { $before_delete = isset( $this->users_before_delete[ (int) $user_id ] ) ? $this->users_before_delete[ (int) $user_id ] : null; if ( empty( $before_delete ) || ! isset( $before_delete['user']->data->display_name ) ) { return; } $this->log_action( [ 'action_type' => 'DELETE', 'title' => $before_delete['user']->data->display_name, 'node_id' => (int) $before_delete['user']->ID, 'relay_id' => Relay::toGlobalId( 'user', (int) $before_delete['user']->ID ), 'graphql_single_name' => 'user', 'graphql_plural_name' => 'users', 'status' => 'trash', ] ); if ( isset( $before_delete['reassign']->display_name ) ) { $this->log_action( [ 'action_type' => 'UPDATE', 'title' => $before_delete['reassign']->display_name, 'node_id' => (int) $before_delete['reassign']->ID, 'relay_id' => Relay::toGlobalId( 'user', (int) $before_delete['reassign']->ID ), 'graphql_single_name' => 'user', 'graphql_plural_name' => 'users', 'status' => 'publish', ] ); if ( ! empty( $this->post_ids_to_reassign ) && is_array( $this->post_ids_to_reassign ) ) { foreach ( $this->post_ids_to_reassign as $post_id ) { // If there's a post for the Post ID if ( ! empty( $post = get_post( absint( $post_id ) ) ) ) { // If the post status is not published, don't track an action for it if ( 'publish' !== $post->post_status ) { return; } // Get the post type object $post_type_object = get_post_type_object( $post->post_type ); // Log an action for the post being re-assigned $this->log_action( [ 'action_type' => 'UPDATE', 'title' => $post->post_title, 'node_id' => (int) $post_id, 'relay_id' => Relay::toGlobalId( 'post', (int) $post_id ), 'graphql_single_name' => $post_type_object->graphql_single_name, 'graphql_plural_name' => $post_type_object->graphql_plural_name, 'status' => 'publish', ] ); } } } } } /** * Logs activity when meta is updated for a user * * @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_user_meta( int $meta_id, int $object_id, string $meta_key, $meta_value ) { if ( empty( $user = get_user_by( 'id', $object_id ) ) || ! is_a( $user, 'WP_User' ) ) { return; } if ( ! $this->is_published_author( $object_id ) ) { return; } if ( false === $this->should_track_meta( $meta_key, $meta_value, $user ) ) { return; } $action = [ 'action_type' => 'UPDATE', 'title' => $user->display_name, 'node_id' => (int) $user->ID, 'relay_id' => Relay::toGlobalId( 'user', (int) $user->ID ), 'graphql_single_name' => 'user', 'graphql_plural_name' => 'users', 'status' => 'publish', ]; // Log the action $this->log_action( $action ); } /** * Logs activity when meta is updated on terms * * @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_user_meta( array $meta_ids, int $object_id, string $meta_key, $meta_value ) { if ( empty( $user = get_user_by( 'id', $object_id ) ) || ! is_a( $user, 'WP_User' ) ) { return; } if ( ! $this->is_published_author( $object_id ) ) { return; } if ( ! $this->should_track_meta( $meta_key, $meta_value, $user ) ) { return; } $action = [ 'action_type' => 'UPDATE', 'title' => $user->display_name, 'node_id' => (int) $user->ID, 'relay_id' => Relay::toGlobalId( 'user', (int) $user->ID ), 'graphql_single_name' => 'user', 'graphql_plural_name' => 'users', 'status' => 'publish', ]; // Log the action $this->log_action( $action ); } } ================================================ FILE: src/Admin/Preview.php ================================================ register_preview_status_fields_and_mutations(); } ); } public static function get_gatsby_content_sync_url_for_post( $post ) { // get the Gatsby Cloud loader url w/ site id $gatsby_content_sync_url = Settings::get_setting( 'gatsby_content_sync_url' ); // Create the dynamic path Content Sync will need $manifest_id = self::get_preview_manifest_id_for_post( $post ); $content_id = $post->ID; $path = "/gatsby-source-wordpress/$manifest_id/$content_id"; $url = preg_replace( // remove any double forward slashes from the path '/([^:])(\/{2,})/', '$1/', "$gatsby_content_sync_url$path" ); return $url; } public static function get_previewable_post_object_by_post_id( $post_id ) { $revision = array_values( wp_get_post_revisions( $post_id ) )[0] // or if revisions are disabled, get the autosave ?? wp_get_post_autosave( $post_id, get_current_user_id() ) // otherwise we can't preview anything ?? null; if ( $revision ) { return $revision; } return get_post( $post_id ); } public static function get_preview_manifest_id_for_post( $post ) { $revision = self::get_previewable_post_object_by_post_id( $post->ID ); $revision_modified = $revision->post_modified ?? null; $modified = $post->post_status === "draft" ? $post->post_modified : $revision_modified; if ( ! $modified || $modified === "" ) { return null; } $manifest_id = $post->ID . $modified; return $manifest_id; } /** * This is used to print out the client CSS file directly to the * Preview template html when Content Sync isn't set up correctly. */ public static function print_file_contents( $fileName ) { $pluginDirectory = plugin_dir_path( __FILE__ ); $filePath = $pluginDirectory . $fileName; echo file_get_contents( $filePath ); } function register_preview_status_fields_and_mutations() { register_graphql_enum_type( 'WPGatsbyRemotePreviewStatusEnum', [ 'description' => __( 'The different statuses a Gatsby Preview can be in for a single node.', 'wp-gatsby' ), 'values' => [ 'PREVIEW_SUCCESS' => [ 'value' => 'PREVIEW_SUCCESS', ], 'NO_PAGE_CREATED_FOR_PREVIEWED_NODE' => [ 'value' => 'NO_PAGE_CREATED_FOR_PREVIEWED_NODE', ], 'GATSBY_PREVIEW_PROCESS_ERROR' => [ 'value' => 'GATSBY_PREVIEW_PROCESS_ERROR', ], 'RECEIVED_PREVIEW_DATA_FROM_WRONG_URL' => [ 'value' => 'RECEIVED_PREVIEW_DATA_FROM_WRONG_URL', ], ], ] ); register_graphql_mutation( 'wpGatsbyRemotePreviewStatus', [ 'inputFields' => [ // parentDatabaseId is the only input arg we need now. // the rest are left for backwards compatibility so errors aren't thrown. 'parentDatabaseId' => [ 'type' => 'Number', 'description' => __( 'The previewed revisions post parent id', 'wp-gatsby' ), ], 'pagePath' => [ 'type' => 'String', 'description' => __( 'The Gatsby page path for this preview.', 'wp-gatsby' ), ], 'modified' => [ 'type' => 'String', 'description' => __( 'The modified date of the latest revision for this preview.', 'wp-gatsby' ), ], 'status' => [ 'type' => [ 'non_null' => 'WPGatsbyRemotePreviewStatusEnum' ], 'description' => __( 'The remote status of the previewed node', 'wp-gatsby' ), ], 'statusContext' => [ 'type' => 'String', 'description' => __( 'Additional context about the preview status', 'wp-gatsby' ), ], ], 'outputFields' => [ 'success' => [ 'type' => 'Boolean', 'description' => __( 'Wether or not the revision mutation was successful', 'wp-gatsby' ), 'resolve' => function( $payload, $args, $context, $info ) { $success = $payload['success'] ?? null; return [ 'success' => $success, ]; }, ], ], 'mutateAndGetPayload' => function( $input, $context, $info ) { $parent_id = $input['parentDatabaseId'] ?? null; $post = get_post( $parent_id ); $post_type_object = $post ? get_post_type_object( $post->post_type ) : null; $user_can_edit_this_post = $post ? current_user_can( $post_type_object->cap->edit_posts, $parent_id ) : null; if ( ! $post || ! $user_can_edit_this_post ) { $message = sprintf( __( 'Sorry, you are not allowed to update post %1$s', 'wp-gatsby' ), $parent_id ); throw new UserError( $message ); } // delete action monitor preview action. // once we've saved this preview status as succes // we don't need the preview action anymore. $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( $parent_id ), ], [ 'taxonomy' => 'gatsby_action_stream_type', 'field' => 'name', 'terms' => 'PREVIEW', ] ], ] ); if ( isset( $existing->posts ) && ! empty( $existing->posts ) ) { wp_delete_post( $existing->posts[0], true ); } return [ 'success' => true, ]; }, ] ); register_graphql_object_type( 'WPGatsbyPageNode', [ 'description' => __( 'A previewed Gatsby page node.' ), 'fields' => [ 'path' => [ 'type' => 'String', ], ], ] ); register_graphql_enum_type( 'WPGatsbyWPPreviewedNodeStatus', [ 'description' => __( 'The different statuses a Gatsby Preview can be in for a single node.', 'wp-gatsby' ), 'values' => [ 'NO_NODE_FOUND' => [ 'value' => 'NO_NODE_FOUND', ], 'PREVIEW_READY' => [ 'value' => 'PREVIEW_READY', ], 'REMOTE_NODE_NOT_YET_UPDATED' => [ 'value' => 'REMOTE_NODE_NOT_YET_UPDATED', ], 'NO_PREVIEW_PATH_FOUND' => [ 'value' => 'NO_PREVIEW_PATH_FOUND', ], 'RECEIVED_PREVIEW_DATA_FROM_WRONG_URL' => [ 'value' => 'RECEIVED_PREVIEW_DATA_FROM_WRONG_URL', ], 'PREVIEW_PAGE_UPDATED_BUT_NOT_YET_DEPLOYED' => [ 'value' => 'PREVIEW_PAGE_UPDATED_BUT_NOT_YET_DEPLOYED', ], ], ] ); register_graphql_object_type( 'WPGatsbyPreviewStatus', [ 'description' => __( 'Check compatibility with a given version of gatsby-source-wordpress and the WordPress source site.' ), 'fields' => [ 'pageNode' => [ 'type' => 'WPGatsbyPageNode', ], 'statusType' => [ 'type' => 'WPGatsbyWPPreviewedNodeStatus', ], 'remoteStatus' => [ 'type' => 'WPGatsbyRemotePreviewStatusEnum', ], 'modifiedLocal' => [ 'type' => 'String', ], 'modifiedRemote' => [ 'type' => 'String', ], 'statusContext' => [ 'type' => 'String', ], ], ] ); register_graphql_field( 'WPGatsby', 'gatsbyPreviewStatus', [ 'description' => __( 'The current status of a Gatsby Preview.', 'wp-gatsby' ), 'type' => 'WPGatsbyPreviewStatus', 'args' => [ 'nodeId' => [ 'type' => [ 'non_null' => 'Number' ], 'description' => __( 'The post id for the previewed node.', 'wp-gatsby' ), ], ], 'resolve' => function( $root, $args, $context, $info ) { $post_id = $args['nodeId'] ?? null; // make sure post_id is a valid post $post = get_post( $post_id ); $post_type_object = $post ? get_post_type_object( $post->post_type ) : null; $user_can_edit_this_post = $post ? current_user_can( $post_type_object->cap->edit_posts, $post_id ) : null; if ( ! $post || ! $user_can_edit_this_post ) { throw new UserError( sprintf( __( 'Sorry, you are not allowed to access the Preview status of post %1$s', 'wp-gatsby' ), $post_id ) ); } if ( ! $post ) { return [ 'statusType' => 'NO_NODE_FOUND', ]; } $found_preview_path_post_meta = get_post_meta( $post_id, '_wpgatsby_page_path', true ); $revision = Preview::getPreviewablePostObjectByPostId( $post_id ); $revision_modified = $revision->post_modified ?? null; $modified = $revision_modified ?? $post->post_modified; $gatsby_node_modified = get_post_meta( $post_id, '_wpgatsby_node_modified', true ); $remote_status = get_post_meta( $post_id, '_wpgatsby_node_remote_preview_status', true ); $node_modified_was_updated = strtotime( $gatsby_node_modified ) >= strtotime( $modified ); if ( $node_modified_was_updated && ( 'NO_PAGE_CREATED_FOR_PREVIEWED_NODE' === $remote_status || 'RECEIVED_PREVIEW_DATA_FROM_WRONG_URL' === $remote_status ) ) { return [ 'statusType' => null, 'statusContext' => null, 'remoteStatus' => $remote_status, ]; } $node_was_updated = false; if ( $node_modified_was_updated && $found_preview_path_post_meta ) { $server_side = true; $gatbsy_preview_frontend_url = self::get_gatsby_preview_instance_url( $server_side ); $page_data_path = $found_preview_path_post_meta === "/" ? "/index/" : $found_preview_path_post_meta; $page_data_path_trimmed = trim( $page_data_path, "/" ); $modified_deployed_url = $gatbsy_preview_frontend_url . "page-data/$page_data_path_trimmed/page-data.json"; // check if node page was deployed $request = wp_remote_get( $modified_deployed_url ); $response = wp_remote_retrieve_body( $request ); $page_data = json_decode( $response ); $modified_response = $page_data->result->pageContext->__wpGatsbyNodeModified ?? null; error_log(print_r('$modified_response', true)); error_log(print_r($modified_response, true)); error_log(print_r('$modified', true)); error_log(print_r($modified, true)); $preview_was_deployed = $modified_response && strtotime( $modified_response ) >= strtotime( $modified ); error_log(print_r('$preview_was_deployed', true)); error_log(print_r($preview_was_deployed, true)); if ( ! $preview_was_deployed ) { // if preview was not yet deployed, send back PREVIEW_PAGE_UPDATED_BUT_NOT_YET_DEPLOYED. return [ 'statusType' => 'PREVIEW_PAGE_UPDATED_BUT_NOT_YET_DEPLOYED', 'statusContext' => null, 'remoteStatus' => null, ]; } else { // if it is deployed, send back PREVIEW_READY below. $node_was_updated = true; } } // if the node wasn't updated, then any status we have is stale. $remote_status_type = $remote_status && $node_was_updated ? $remote_status : null; /** * We need the above check for wether the node was updated so we * don't show stale statuses on existing nodes, but in the case that * it's a brand new draft, $node_was_updated will always be false * because at this point we're potentially getting an error on a * node that was never created. So GATSBY_PREVIEW_PROCESS_ERROR is a * special case where we always need to show the status regardless * of wether the node was updated. */ if ( 'GATSBY_PREVIEW_PROCESS_ERROR' === $remote_status ) { $remote_status_type = $remote_status; } $status_type = 'PREVIEW_READY'; if ( ! $node_was_updated ) { $status_type = 'REMOTE_NODE_NOT_YET_UPDATED'; } if ( ! $found_preview_path_post_meta ) { $status_type = 'NO_PREVIEW_PATH_FOUND'; } $status_context = get_post_meta( $post_id, '_wpgatsby_node_remote_preview_status_context', true ); if ( $status_context === '' ) { $status_context = null; } $normalized_preview_page_path = $found_preview_path_post_meta !== '' ? $found_preview_path_post_meta : null; return [ 'statusType' => $status_type, 'statusContext' => $status_context, 'remoteStatus' => $remote_status_type, 'pageNode' => [ 'path' => $normalized_preview_page_path, ], 'modifiedLocal' => $modified, 'modifiedRemote' => $gatsby_node_modified, ]; }, ] ); register_graphql_field( 'WPGatsby', 'isPreviewFrontendOnline', [ 'description' => __( 'Wether or not the Preview frontend URL is online.', 'wp-gatsby' ), 'type' => 'Boolean', 'resolve' => function( $root, $args, $context, $info ) { if ( ! is_user_logged_in() ) { return false; } $preview_url = self::get_gatsby_preview_instance_url(); $request = wp_remote_get( $preview_url ); $request_was_successful = $this->was_request_successful( $request ); return $request_was_successful; }, ] ); } } ================================================ FILE: src/Admin/Settings.php ================================================ settings_api = new \WPGraphQL_Settings_API; add_action( 'init', [ $this, 'set_default_jwt_key' ] ); add_action( 'admin_init', [ $this, 'admin_init' ] ); add_action( 'admin_menu', [ $this, 'register_settings_page' ] ); // Filter the GraphQL Settings for introspection to force enable Introspection when WPGatsby is active add_filter( 'graphql_setting_field_config', [ $this, 'filter_graphql_introspection_setting_field' ], 10, 3 ); add_filter( 'graphql_get_setting_section_field_value', [ $this, 'filter_graphql_introspection_setting_value' ], 10, 5 ); } /** * If the settings haven't been saved yet, save the JWT once to prevent it from re-generating. */ public function set_default_jwt_key() { // Get the JWT Secret $default_secret = self::get_setting( 'preview_jwt_secret' ); if ( empty( $default_secret ) ) { // Get the WPGatsby Settings from the options $options = get_option( 'wpgatsby_settings', [] ); // If settings haven't been saved before, instantiate them as a new array if ( empty( $options ) || ! is_array( $options ) ) { $options = []; } // Se the preview secret $options['preview_jwt_secret'] = self::generate_secret(); // Save the settings to prevent the JWT Secret from generating again update_option( 'wpgatsby_settings', $options ); } } /** * Overrides the "public_introspection_enabled" setting field in the GraphQL Settings to be * checked and disabled so users can't uncheck it. * * @param array $field_config The field config for the setting * @param string $field_name The name of the field (unfilterable in the config) * @param string $section The slug of the section the field is registered to * * @return mixed */ public function filter_graphql_introspection_setting_field( $field_config, $field_name, $section ) { if ( 'graphql_general_settings' === $section && 'public_introspection_enabled' === $field_name ) { $field_config['value'] = 'on'; $field_config['disabled'] = true; $field_config['desc'] = $field_config['desc'] . ' (' . __( 'Force enabled by WPGatsby. Gatsby requires WPGraphQL introspection to communicate with WordPress.', 'WPGatsby' ) . ')'; } return $field_config; } /** * Filters the value of the "public_introspection_enabled" setting to always be "on" when * WPGatsby is enabled * * @param mixed $value The value of the field * @param mixed $default The default value if there is no value set * @param string $field_name The name of the option * @param array $section_fields The setting values within the section * @param string $section_name The name of the section the setting belongs to * * @return string */ public function filter_graphql_introspection_setting_value( $value, $default, $field_name, $section_fields, $section_name ) { if ( 'graphql_general_settings' === $section_name && 'public_introspection_enabled' === $field_name ) { return 'on'; } return $value; } function admin_init() { //set the settings $this->settings_api->set_sections( $this->get_settings_sections() ); $this->settings_api->set_fields( $this->get_settings_fields() ); //initialize settings $this->settings_api->admin_init(); } function admin_menu() { add_options_page( 'Settings API', 'Settings API', 'delete_posts', 'settings_api_test', [ $this, 'plugin_page', ] ); } function get_settings_sections() { $sections = [ [ 'id' => 'wpgatsby_settings', 'title' => __( 'Settings', 'wpgatsby_settings' ), ], ]; return $sections; } public function register_settings_page() { add_options_page( 'Gatsby', 'GatsbyJS', 'manage_options', 'gatsbyjs', [ $this, 'plugin_page', ] ); } function plugin_page() { echo '
'; echo ''; $this->settings_api->show_navigation(); $this->settings_api->show_forms(); echo '
'; } static public function prefix_get_option( $option, $section, $default = '' ) { $options = get_option( $section ); if ( isset( $options[ $option ] ) ) { return $options[ $option ]; } return $default; } private static function generate_secret() { $factory = new \RandomLib\Factory; $generator = $factory->getMediumStrengthGenerator(); $secret = $generator->generateString( 50 ); return $secret; } private static function get_default_secret() { $default_secret = self::get_setting( 'preview_jwt_secret' ); if ( ! $default_secret ) { $default_secret = self::generate_secret(); } return $default_secret; } public static function sanitize_url_field( $input ) { $urls = explode( ',', $input ); if ( count( $urls ) > 1 ) { // validate all urls $validated_urls = array_map( function ( $url ) { return filter_var( $url, FILTER_VALIDATE_URL ); }, $urls ); // then put em back together return implode( ',', $validated_urls ); } return filter_var( $input, FILTER_VALIDATE_URL ); } public static function get_setting( $key ) { $wpgatsby_settings = get_option( 'wpgatsby_settings' ); return $wpgatsby_settings[ $key ] ?? null; } /** * Returns all the settings fields * * @return array settings fields */ function get_settings_fields() { $settings_fields = [ 'wpgatsby_settings' => [ [ 'name' => 'enable_gatsby_preview', 'label' => __( 'Enable Gatsby Preview?', 'wpgatsby_settings' ), 'desc' => __( 'Yes, allow Gatsby to take over WordPress previews.', 'wpgatsby_settings' ), 'type' => 'checkbox', ], [ 'name' => 'preview_api_webhook', 'label' => __( 'Preview Webhook URL', 'wpgatsby_settings' ), 'desc' => __( 'Use a comma-separated list to configure multiple webhooks.', 'wpgatsby_settings' ), 'placeholder' => __( 'https://', 'wpgatsby_settings' ), 'type' => 'text', 'sanitize_callback' => function ( $input ) { return $this->sanitize_url_field( $input ); }, ], [ 'name' => 'builds_api_webhook', 'label' => __( 'Builds Webhook URL', 'wpgatsby_settings' ), 'desc' => __( 'Use a comma-separated list to configure multiple webhooks.', 'wpgatsby_settings' ), 'placeholder' => __( 'https://', 'wpgatsby_settings' ), 'type' => 'text', 'sanitize_callback' => function ( $input ) { return $this->sanitize_url_field( $input ); }, ], [ 'name' => 'gatsby_content_sync_url', 'label' => __( 'Gatsby Content Sync URL', 'wpgatsby_settings' ), 'desc' => __( 'Find this URL in your Gatsbyjs.com dashboard settings.', 'wpgatsby_settings' ), 'placeholder' => __( 'https://', 'wpgatsby_settings' ), 'type' => 'text', 'sanitize_callback' => function ( $input ) { return $this->sanitize_url_field( $input ); }, ], [ 'name' => 'preview_jwt_secret', 'label' => __( 'Preview JWT Secret', 'wpgatsby_settings' ), 'desc' => __( 'This secret is used in the encoding and decoding of the JWT token. If the Secret were ever changed on the server, ALL tokens that were generated with the previous Secret would become invalid. So, if you wanted to invalidate all user tokens, you can change the Secret on the server and all previously issued tokens would become invalid and require users to re-authenticate.', 'wpgatsby_settings' ), 'type' => 'password', 'sanitize_callback' => 'sanitize_text_field', 'default' => self::get_default_secret(), ], [ 'name' => 'enable_gatsby_locations', 'label' => __( 'Enable Gatsby Menu Locations?', 'wpgatsby_settings' ), 'desc' => __( 'Yes', 'wpgatsby_settings' ), 'type' => 'checkbox', 'default' => 'on', ], ], ]; return $settings_fields; } } ================================================ FILE: src/Admin/includes/no-preview-url-set.php ================================================ Preview

Preview not found

Visit the settings page to add a valid Preview webhook URL.

If you don't have a Gatsby Preview instance, you can set one up now on Gatsby Cloud.

================================================ FILE: src/Admin/includes/post-type-not-shown-in-graphql.php ================================================ Preview error

Post type not configured properly

The post type "" is not set up properly for Gatsby Preview.
Post types must have "show_in_graphql" set to work with Preview.

Visit the WPGraphQL Docs to learn how to configure this post type.

================================================ FILE: src/Admin/includes/preview-template.php ================================================ Gatsby Preview

The Preview couldn't be loaded

Please add your Gatsby Cloud Content Sync URL to the WPGatsby plugin settings page.



	

Troubleshooting

Please ensure your URL is correct and your Preview instance is up and running.

If you've set the correct URL, your Preview instance is currently running, and you're still having trouble, please refer to the docs for troubleshooting steps, ask your developer, or contact support if that doesn't solve your issue.

If you don't have a valid Gatsby Preview instance, you can set one up now on Gatsby Cloud.

Developer instructions

Please visit the docs for instructions on setting up Gatsby Preview.

================================================ FILE: src/Admin/includes/style.css ================================================ #loader { position: fixed; top: 32px; bottom: 0; left: 0; right: 0; width: 100%; height: 100%; height: calc(100% - 46px); background: white; z-index: 100; text-align: center; display: flex; justify-content: center; flex-direction: column; opacity: 1; transition: 0.125s ease-out opacity; padding: 0 50px; box-sizing: border-box; } @media (max-width: 782px) { #loader { top: 46px; } } #loader.loaded { opacity: 0; } button { font-size: 1rem; padding: 15px 30px; cursor: pointer; font-weight: medium; color: white !important; background: rebeccapurple; border: none; margin-top: 20px; letter-spacing: 0.25px; } h1, h2, pre, p, li, b, button { font-family: "Futura PT", -apple-system, "BlinkMacSystemFont", "Segoe UI", "Roboto", "Helvetica Neue", "Arial", "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; line-height: 1.45; } b, p, button { color: #272727; } h1, h2 { color: rebeccapurple; } h1 { display: block; font-size: 2em; margin-block-start: 0.67em; margin-block-end: 0.67em; margin-inline-start: 0px; margin-inline-end: 0px; font-weight: bold; } body { font-size: 18px; } #gatsby-loading-logo { max-width: 80%; width: 64px; height: 64px; margin: 0 auto; margin-bottom: 10px; box-shadow: 0 0 0 rgba(102, 51, 153, 0.4); -webkit-animation: pulse 2s infinite; animation: pulse 2s infinite; border-radius: 50%; } @-webkit-keyframes pulse { 0% { box-shadow: 0 0 0 0 rgba(102, 51, 153, 0.4); } 70% { box-shadow: 0 0 0 30px rgba(102, 51, 153, 0); } 100% { box-shadow: 0 0 0 0 rgba(102, 51, 153, 0); } } @keyframes pulse { 0% { box-shadow: 0 0 0 0 rgba(102, 51, 153, 0.4); } 70% { box-shadow: 0 0 0 30px rgba(102, 51, 153, 0); } 100% { box-shadow: 0 0 0 0 rgba(102, 51, 153, 0); } } .content { width: 100%; left: 0; padding-top: 46px; padding-bottom: 70px; min-height: 100%; min-height: calc(100vh - 46px); box-sizing: border-box; display: flex; justify-content: center; align-items: center; flex-direction: column; } #preview-loader-warning, .content { max-width: 80%; width: 800px; margin: 0 auto; } .content p { margin: 0 auto; } iframe { position: fixed; width: 100%; left: 0; top: 46px; height: 100%; height: calc(100vh - 46px); } @media (min-width: 783px) { iframe { top: 32px; height: calc(100vh - 32px); } } pre { white-space: pre-wrap; /* css-3 */ word-wrap: break-word; /* Internet Explorer 5.5+ */ background: #f1f1f1; padding: 50px 40px 40px 80px; margin-bottom: 50px; position: relative; max-width: 640px; box-sizing: border-box; } br { line-height: 1.75; } #error-message-element::before { content: "Error"; position: absolute; top: 0; left: 0; padding: 5px 10px; background: rebeccapurple; color: white; font-size: 12px; } a[target="_blank"]::after { content: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAQElEQVR42qXKwQkAIAxDUUdxtO6/RBQkQZvSi8I/pL4BoGw/XPkh4XigPmsUgh0626AjRsgxHTkUThsG2T/sIlzdTsp52kSS1wAAAABJRU5ErkJggg==); margin: 0 3px 0 5px; } ================================================ FILE: src/GraphQL/Auth.php ================================================ $site_url, 'aud' => $site_url, 'iat' => $now, 'nbf' => $now, 'exp' => $expiry, 'data' => [ 'user_id' => $user_id, ], ]; $jwt = JWT::encode( $payload, $secret ); return $jwt; } } ================================================ FILE: src/GraphQL/ParseAuthToken.php ================================================ data->user_id ?? null; if ( ! $decoded || ! $decoded_user_id ) { return; } $jwt_is_for_existing_author = get_user_by( 'id', $decoded_user_id ); // we get the ID from a header so we can // process multiple user previews in a // single Gatsby Preview process. $user_id = $_SERVER['HTTP_WPGATSBYPREVIEWUSER'] // if it doesn't exist, try the user from the token ?? $decoded_user_id ?? null; if ( $user_id && $decoded && $jwt_is_for_existing_author ) { wp_set_current_user( $user_id ); } } } } ================================================ FILE: src/Schema/Schema.php ================================================ register(); } ); } private static function isVersionARange( $version ) { $version_without_periods = str_replace( '.', '', $version ); $version_without_numbers_and_periods = preg_replace( '/[0-9]+/', '', $version_without_periods ); return $version_without_numbers_and_periods !== ''; } /** * Registers site meta fields... */ function register() { register_graphql_object_type( 'WPGatsbySatisfies', [ 'description' => __( 'Check compatibility with WPGatsby and WPGraphQL.' ), 'fields' => [ 'wpGQL' => [ 'type' => 'Boolean', 'description' => __( 'Whether the provided version range requirement for WPGraphQL is met by this WP instance.', 'wp-gatsby' ), ], 'wpGatsby' => [ 'type' => 'Boolean', 'description' => __( 'Whether the provided version range requirement for WPGatsby is met by this WP instance.', 'wp-gatsby' ), ], ], ] ); register_graphql_object_type( 'WPGatsbyCompatibility', [ 'description' => __( 'Check compatibility with a given version of gatsby-source-wordpress and the WordPress source site.' ), 'fields' => [ 'satisfies' => [ 'type' => 'WPGatsbySatisfies', ], ], ] ); register_graphql_field( 'RootQuery', 'wpGatsbyCompatibility', [ 'description' => __( 'Information about the compatibility of the WordPress server with a provided version of gatsby-source-wordpress.', 'wp-gatsby' ), 'type' => 'WPGatsbyCompatibility', 'args' => [ 'wpGQLVersionRange' => [ 'type' => [ 'non_null' => 'String' ], 'description' => __( 'The semver version range of WPGraphQL that the requester wants to check compatibility with', 'wp-gatsby' ), ], 'wpGatsbyVersionRange' => [ 'type' => [ 'non_null' => 'String' ], 'description' => __( 'The semver version range of WPGatsby that the requester wants to check compatibility with', 'wp-gatsby' ), ], ], 'resolve' => function( $root, $args, $context, $info ) { $wpgql_version_range = $args['wpGQLVersionRange'] ?? null; $wpgatsby_version_range = $args['wpGatsbyVersionRange'] ?? null; if ( ! $wpgql_version_range ) { throw new \Exception( __( 'No WPGraphQL version was provided for the compatibility check. Please provide a semver version range for checking compatibility with WPGraphQL.', 'wp-gatsby' ) ); } if ( ! $wpgatsby_version_range ) { throw new \Exception( __( 'No WPGatsby version was provided for the compatibility check. Please provide a semver version range for checking compatibility with WPGatsby.', 'wp-gatsby' ) ); } if ( ! self::isVersionARange( $wpgql_version_range ) ) { throw new \Exception( 'The provided WPGraphQL version is not a range. ' . $wpgql_version_range ); } if ( ! self::isVersionARange( $wpgatsby_version_range ) ) { throw new \Exception( 'The provided WPGatsby version is not a range. ' . $wpgatsby_version_range ); } /** * Get the versions of WPGraphQL and WPGatsby */ $installed_wpgraphql_version = defined( 'WPGRAPHQL_VERSION' ) ? WPGRAPHQL_VERSION : null; $installed_wpgatsby_version = defined( 'WPGATSBY_VERSION' ) ? WPGATSBY_VERSION : null; $wpgql_is_satisfied = Semver::satisfies( $installed_wpgraphql_version, $wpgql_version_range ); $wpgatsby_is_satisfied = Semver::satisfies( $installed_wpgatsby_version, $wpgatsby_version_range ); /** * Return the payload */ return [ 'satisfies' => [ 'wpGQL' => $wpgql_is_satisfied, 'wpGatsby' => $wpgatsby_is_satisfied, ], ]; }, ] ); register_graphql_field( 'RootQuery', 'isWpGatsby', [ 'type' => 'Boolean', 'description' => __( 'Confirms this is a WP Gatsby site', 'wp-gatsby' ), 'resolve' => function() { return true; }, ] ); register_graphql_field( 'RootQuery', 'schemaMd5', [ 'type' => 'String', 'description' => __( 'Returns an MD5 hash of the schema, useful in determining if the schema has changed.', 'wp-gatsby' ), 'resolve' => function() { $graphql = \graphql( [ 'query' => '{ __schema { types { kind name possibleTypes { kind name } interfaces { kind name } ofType { kind name } fields { name type { name } } } } }', ] ); $json_string = \wp_json_encode( $graphql['data'] ); $md5 = md5( $json_string ); return $md5; }, ] ); register_graphql_object_type( 'WPGatsby', [ 'description' => __( 'Information needed by gatsby-source-wordpress.', 'wp-gatsby' ), 'fields' => [ 'arePrettyPermalinksEnabled' => [ 'description' => 'Returns wether or not pretty permalinks are enabled.', 'type' => 'Boolean', ], ], ] ); register_graphql_field( 'RootQuery', 'wpGatsby', [ 'type' => 'WPGatsby', 'description' => __( 'Information needed by gatsby-source-wordpress.', 'wp-gatsby' ), 'resolve' => function( $root, $args, $context, $info ) { return [ 'arePrettyPermalinksEnabled' => ! ! get_option( 'permalink_structure' ), ]; }, ] ); } } ================================================ FILE: src/Schema/WPGatsbyWPGraphQLSchemaChanges.php ================================================ register(); } ); } function register() { register_graphql_field( 'ContentType', 'archivePath', [ 'type' => 'String', 'description' => __( 'The url path of the first page of the archive page for this content type.', 'wp-gatsby' ), 'resolve' => function( $source, $args, $context, $info ) { $archive_link = get_post_type_archive_link( $source->name ); if ( empty( $archive_link ) ) { return null; } $site_url = get_site_url(); $archive_path = str_replace( $site_url, '', $archive_link ); if ( $archive_link === $site_url && $archive_path === '' ) { return '/'; } return $archive_path ?? null; }, ] ); register_graphql_field( 'Taxonomy', 'archivePath', [ 'type' => 'String', 'description' => __( 'The url path of the first page of the archive page for this content type.', 'wp-gatsby' ), 'resolve' => function( $source, $args, $context, $info ) { $tax = get_taxonomy( $source->name ); if ( ! $tax->rewrite['slug'] ?? false ) { return null; } return '/' . $tax->rewrite['slug'] . '/'; }, ] ); } } ================================================ FILE: src/ThemeSupport/ThemeSupport.php ================================================ __( 'Header Menu [Added by WPGatsby]', 'WPGatsby' ), 'gatsby-footer-menu' => __( 'Footer Menu [Added by WPGatsby]', 'WPGatsby' ), ] ); register_nav_menus( $gatsby_locations ); } } ================================================ FILE: src/Utils/Utils.php ================================================ admin = $this->factory()->user->create( [ 'role' => 'administrator' ] ); $this->tag = $this->factory()->tag->create(); $this->clear_action_monitor(); } public function tearDown(): void { $this->delete_posts(); // Then... parent::tearDown(); } public function clear_action_monitor() { global $wpdb; $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\'', true ); $query = $wpdb->prepare( $sql, 'action_monitor' ); $wpdb->query( $query ); add_filter( 'wpgatsby_action_monitor_get_updated_post_ids', function() { return []; } ); } public function delete_posts() { global $wpdb; $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}posts WHERE ID <> %d", array( 1 ) ) ); } // Tests public function test_it_works() { $post = static::factory()->post->create_and_get(); $this->assertInstanceOf( \WP_Post::class, $post ); } public function actionMonitorQuery() { return ' { actionMonitorActions { nodes { actionType referencedNodeID referencedNodeSingularName } } } '; } public function testActionMonitorQueryIsValid() { $query = $this->actionMonitorQuery(); $actual = $this->graphql( [ 'query' => $query ] ); $this->assertIsValidQueryResponse( $actual ); } public function testCreatePostCreatesActionMonitorAction() { // Create a post $post_id = $this->factory()->post->create( [ 'post_type' => 'post', 'post_status' => 'publish', 'post_title' => 'Title', 'post_author' => $this->admin, 'tags_input' => [ $this->tag ] ] ); codecept_debug( $this->tag ); // Query for action monitor actions $query = $this->actionMonitorQuery(); // Execute the query $actual = $this->graphql( compact( 'query' ) ); $this->assertIsValidQueryResponse( $actual ); // Creating a post assigned to an author should trigger 2 actions: // - 1 for the post // - 1 for the author $this->assertSame( 2, count( $actual['data']['actionMonitorActions']['nodes'] ) ); // Assert the action monitor has the actions for the post being created $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'CREATE', 'referencedNodeID' => (string) $post_id, 'referencedNodeSingularName' => 'post', ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $this->admin, 'referencedNodeSingularName' => 'user' ] ), ] ); } public function testCreatePageCreatesActionMonitorAction() { // Create a post $post_id = $this->factory()->post->create( [ 'post_type' => 'page', 'post_status' => 'publish', 'post_title' => 'Title', 'post_author' => $this->admin, ] ); // Query for action monitor actions $query = $this->actionMonitorQuery(); // Execute the query $actual = $this->graphql( compact( 'query' ) ); codecept_debug( $actual ); // Creating a post assigned to an author should trigger 2 actions: // - 1 for the post // - 1 for the author $this->assertSame( 2, count( $actual['data']['actionMonitorActions']['nodes'] ) ); // Assert the action monitor has the actions for the page being created $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'CREATE', 'referencedNodeID' => (string) $post_id, 'referencedNodeSingularName' => 'page' ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $this->admin, 'referencedNodeSingularName' => 'user' ] ), ] ); } public function testDeletePostCreatesActionMonitorAction() { // Create a post $post_id = $this->factory()->post->create( [ 'post_type' => 'post', 'post_status' => 'publish', 'post_title' => 'Title', 'post_author' => $this->admin ] ); // create a 2nd post for the user. if the user still has published posts // this should trigger an update action for the user $this->factory()->post->create( [ 'post_type' => 'post', 'post_status' => 'publish', 'post_title' => 'Title', 'post_author' => $this->admin ] ); // Clear the action monitor to remove the mock post creation $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); wp_delete_post( $post_id, true ); // Query for action monitor actions $query = $this->actionMonitorQuery(); // Execute the query $actual = $this->graphql( compact( 'query' ) ); /** * There should be 2 action for deleting the page * - 1 for DELETE page * - 1 for UPDATE user (the user still has 1 published post) */ $this->assertSame( 2, count( $actual['data']['actionMonitorActions']['nodes'] ) ); codecept_debug( $actual ); // Assert the action monitor has the actions for the page being created $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'DELETE', 'referencedNodeID' => (string) $post_id, 'referencedNodeSingularName' => 'post' ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $this->admin, 'referencedNodeSingularName' => 'user' ] ), ] ); } public function testDeleteOnlyPostByAuthorCreatesActionMonitorActions() { // Create a post $post_id = $this->factory()->post->create( [ 'post_type' => 'post', 'post_status' => 'publish', 'post_title' => 'Title', 'post_author' => $this->admin ] ); // Clear the action monitor to remove the mock post creation $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); wp_delete_post( $post_id, true ); // Query for action monitor actions $query = $this->actionMonitorQuery(); // Execute the query $actual = $this->graphql( compact( 'query' ) ); /** * There should be 2 action for deleting the page * - 1 for DELETE page * - 1 for DELETE user (the user has no published posts so is no longer public) */ $this->assertSame( 2, count( $actual['data']['actionMonitorActions']['nodes'] ) ); codecept_debug( $actual ); // Assert the action monitor has the actions for the page being created $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'DELETE', 'referencedNodeID' => (string) $post_id, 'referencedNodeSingularName' => 'post' ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'DELETE', 'referencedNodeID' => (string) $this->admin, 'referencedNodeSingularName' => 'user' ] ), ] ); } public function testDeleteDraftPostDoesNotCreateActionMonitorAction() { // Create a post $post_id = $this->factory()->post->create( [ 'post_type' => 'draft', 'post_status' => 'publish', 'post_title' => 'Title', 'post_author' => $this->admin ] ); // Clear the action monitor to remove the mock post creation $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); wp_delete_post( $post_id, true ); // Query for action monitor actions $query = $this->actionMonitorQuery(); // Execute the query $actual = $this->graphql( compact( 'query' ) ); /** * There should be 0 action for deleting a draft post */ $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); codecept_debug( $actual ); } public function testTrashPostCreatesActionMonitorAction() { // Create a post $post_id = $this->factory()->post->create( [ 'post_type' => 'post', 'post_status' => 'publish', 'post_title' => 'Title', ] ); // Clear the action monitor to remove the mock post creation $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); // Trashing a post should crate an action monitor entry for delete post wp_trash_post( $post_id ); // Query for action monitor actions $query = $this->actionMonitorQuery(); // Execute the query $actual = $this->graphql( compact( 'query' ) ); /** * There should be 1 action for deleting the post */ $this->assertSame( 1, count( $actual['data']['actionMonitorActions']['nodes'] ) ); codecept_debug( $actual ); // Assert the action monitor has the actions for the post being created $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'DELETE', 'referencedNodeID' => (string) $post_id, 'referencedNodeSingularName' => 'post' ] ), ] ); } public function testPublishPostFromDraftCreatesActionMonitorAction() { $post_data = [ 'post_status' => 'draft', 'post_type' => 'post', 'post_author' => $this->admin, 'tags_input' => [ $this->tag ], ]; $post_id = $this->factory()->post->create( $post_data ); $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); // Publish the post wp_update_post( [ 'ID' => $post_id, 'post_status' => 'publish' ] ); // Execute the query $actions = $this->graphql( compact( 'query' ) ); /** * There should be 2 actions * - 1 for the created post * - 1 for the updated author */ $this->assertSame( 2, count( $actions['data']['actionMonitorActions']['nodes'] ) ); codecept_debug( $actions ); // Assert the action monitor has the actions for the page being created $this->assertQuerySuccessful( $actions, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'CREATE', 'referencedNodeID' => (string) $post_id, 'referencedNodeSingularName' => 'post' ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $this->admin, 'referencedNodeSingularName' => 'user' ] ), ] ); } public function testChangePostToDraftCreatesActionMonitorAction() { $post_id = $this->factory()->post->create([ 'post_type' => 'post', 'post_status' => 'publish', 'post_title' => 'test', 'post_author' => $this->admin, ]); // Create a 2nd post for the user. Changing one post to draft // should trigger an UPDATE for the user. $post_two = $this->factory()->post->create([ 'post_type' => 'post', 'post_status' => 'publish', 'post_title' => 'test', 'post_author' => $this->admin, ]); $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); // Changing a published post to draft (or any non-published status) should // trigger a delete action for the post wp_update_post([ 'ID' => $post_id, 'post_status' => 'draft', ]); $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'DELETE', 'referencedNodeID' => (string) $post_id, 'referencedNodeSingularName' => 'post' ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $this->admin, 'referencedNodeSingularName' => 'user' ] ), ] ); } public function testChangeAuthorsOnPublishedPostCreatesActionMonitorActions() { $user_two = $this->factory()->user->create([ 'role' => 'editor' ]); $post_one_for_admin = $this->factory()->post->create([ 'post_type' => 'post', 'post_status' => 'publish', 'post_title' => 'test', 'post_author' => $this->admin, ]); $post_two_for_admin = $this->factory()->post->create([ 'post_type' => 'post', 'post_status' => 'publish', 'post_title' => 'test', 'post_author' => $this->admin, ]); $post_one_for_user_two = $this->factory()->post->create([ 'post_type' => 'post', 'post_status' => 'publish', 'post_title' => 'test', 'post_author' => $user_two, ]); $post_two_for_user_two = $this->factory()->post->create([ 'post_type' => 'post', 'post_status' => 'publish', 'post_title' => 'test', 'post_author' => $user_two, ]); $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); wp_update_post([ 'ID' => $post_one_for_admin, 'post_author' => $user_two ]); $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); // Changing the author of a post should create 3 actions // - for the post // - 1 for the new author // - 1 for the previous author $this->assertSame( 3, count( $actual['data']['actionMonitorActions']['nodes'] ) ); $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $post_one_for_admin, 'referencedNodeSingularName' => 'post' ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $this->admin, 'referencedNodeSingularName' => 'user' ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $user_two, 'referencedNodeSingularName' => 'user' ] ), ] ); } public function testChangeOnlyPostFromAuthorToDraftCreatesActionMonitorActions() { $post_id = $this->factory()->post->create([ 'post_type' => 'post', 'post_status' => 'publish', 'post_title' => 'test', 'post_author' => $this->admin, ]); $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); // Changing a published post to draft (or any non-published status) should // trigger a delete action for the post wp_update_post([ 'ID' => $post_id, 'post_status' => 'draft', ]); $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); // The author only has 1 published post. Making it a draft post // means the author is unpublished and we need to // tell Gatsby to delete the user. $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'DELETE', 'referencedNodeID' => (string) $post_id, 'referencedNodeSingularName' => 'post' ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'DELETE', 'referencedNodeID' => (string) $this->admin, 'referencedNodeSingularName' => 'user' ] ), ] ); } public function testPublishScheduledPostCreatesActionMonitorAction() { // Create a future post $post_id = $this->factory()->post->create([ 'post_type' => 'post', 'post_status' => 'future', 'post_title' => 'Test Scheduled Post', 'post_author' => $this->admin, 'post_date' => date( "Y-m-d H:i:s", strtotime( '+1 day' ) ), ]); // Make sure action monitor is cleared $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); // publish the post wp_publish_post( $post_id ); $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); // There should be 2 actions created. // - 1 for the published post // - 1 for the author $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'CREATE', 'referencedNodeID' => (string) $post_id, 'referencedNodeSingularName' => 'post' ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $this->admin, 'referencedNodeSingularName' => 'user' ] ), ] ); } public function testUpdatePostMetaOfUnublishedPostDoesNotCreatesActionMonitorAction() { $post_id = $this->factory()->post->create([ 'post_type' => 'post', 'post_status' => 'draft', 'post_title' => 'test', 'post_author' => $this->admin, ]); // Make sure action monitor is cleared $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); update_post_meta( $post_id, 'test_post_meta', 'test' ); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); } public function testDeletePostMetaOfUnublishedPostDoesNotCreatesActionMonitorAction() { $post_id = $this->factory()->post->create([ 'post_type' => 'post', 'post_status' => 'draft', 'post_title' => 'test', 'post_author' => $this->admin, ]); update_post_meta( $post_id, 'test_post_meta', 'test' ); // Make sure action monitor is cleared $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); delete_post_meta( $post_id, 'test_post_meta' ); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); } public function testUpdatePostMetaOfPublishedPostCreatesActionMonitorAction() { $post_id = $this->factory()->post->create([ 'post_type' => 'post', 'post_status' => 'publish', 'post_title' => 'test update meta', 'post_author' => $this->admin, ]); $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); update_post_meta( absint( $post_id ), 'test_meta', 'test_value' ); $actual = $this->graphql( compact( 'query' ) ); /** * There should be 1 actions * - 1 for the updated post */ $this->assertSame( 1, count( $actual['data']['actionMonitorActions']['nodes'] ) ); codecept_debug( $actual ); // Assert the action monitor has the actions for the page being created $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $post_id, 'referencedNodeSingularName' => 'post' ] ), ] ); } public function testDeletePostMetaCreatesActionMonitorAction() { $post_id = $this->factory()->post->create( [ 'post_status' => 'publish', 'post_type' => 'post', 'post_author' => $this->admin, 'tags_input' => [ $this->tag ], ] ); update_post_meta( $post_id, 'test_meta', 'test_value' ); $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); delete_post_meta( $post_id, 'test_meta' ); $actual = $this->graphql( compact( 'query' ) ); /** * There should be 1 actions * - 1 for the updated post */ $this->assertSame( 1, count( $actual['data']['actionMonitorActions']['nodes'] ) ); codecept_debug( $actual ); // Assert the action monitor has the actions for the page being created $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $post_id, 'referencedNodeSingularName' => 'post' ] ), ] ); } public function testNewPostTypesDetectedWithGraphqlSupportCreateActionMonitorAction() { $post_types = get_post_types([ 'show_in_graphql' => true, 'public' => true ]); update_option( '_gatsby_tracked_post_types', $post_types ); $this->clear_action_monitor(); $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); $added_post_type = 'new_type'; $post_types[] = $added_post_type; update_option( '_gatsby_tracked_post_types', $post_types ); do_action( 'gatsby_init_action_monitors' ); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 1, count( $actual['data']['actionMonitorActions']['nodes'] ) ); codecept_debug( $actual ); } public function testPostTypeRemovedFromGraphQLCreateActionMonitorAction() { $post_types = get_post_types([ 'show_in_graphql' => true, 'public' => true ]); $post_types[] = 'remove_me'; update_option( '_gatsby_tracked_post_types', $post_types ); $this->clear_action_monitor(); $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); unset( $post_types['remove_me'] ); update_option( '_gatsby_tracked_post_types', $post_types ); do_action( 'gatsby_init_action_monitors' ); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 1, count( $actual['data']['actionMonitorActions']['nodes'] ) ); codecept_debug( $actual ); } public function testTaxonomyDetectedWithGraphqlSupportCreateActionMonitorAction() { $taxonomies = get_taxonomies([ 'show_in_graphql' => true, 'public' => true ]); update_option( '_gatsby_tracked_taxonomies', $taxonomies ); $this->clear_action_monitor(); $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); $added = 'new_type'; $taxonomies[] = $added; update_option( '_gatsby_tracked_taxonomies', $taxonomies ); do_action( 'gatsby_init_action_monitors' ); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 1, count( $actual['data']['actionMonitorActions']['nodes'] ) ); codecept_debug( $actual ); } public function testTaxonomyRemovedFromGraphQLCreateActionMonitorAction() { $taxonomies = get_taxonomies([ 'show_in_graphql' => true, 'public' => true ]); $taxonomies[] = 'remove_me'; update_option( '_gatsby_tracked_taxonomies', $taxonomies ); $this->clear_action_monitor(); $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); unset( $taxonomies['remove_me'] ); update_option( '_gatsby_tracked_taxonomies', $taxonomies ); do_action( 'gatsby_init_action_monitors' ); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 1, count( $actual['data']['actionMonitorActions']['nodes'] ) ); codecept_debug( $actual ); } // @todo: review the ones below this with Tyler public function testCreatePostOfAPublicCustomPostTypeCreatesActionMonitorAction() { // register a post type register_post_type( 'wp_gatsby_test', [ 'public' => true, 'show_in_graphql' => true, 'graphql_single_name' => 'wpGatsbyTest', 'graphql_plural_name' => 'wpGatsbyTests', ] ); codecept_debug( get_post_types(['show_in_graphql' => true, 'public' => true ])); $this->clear_action_monitor(); $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); // Create a post $post_id = $this->factory()->post->create( [ 'post_type' => 'wp_gatsby_test', 'post_status' => 'publish', 'post_title' => 'Title', 'post_author' => $this->admin, 'tags_input' => [ $this->tag ] ] ); codecept_debug( get_post( $post_id ) ); // Query for action monitor actions $query = $this->actionMonitorQuery(); // Execute the query $actual = $this->graphql( compact( 'query' ) ); $this->assertIsValidQueryResponse( $actual ); // Creating a post assigned to an author should trigger 3 actions: // - 1 for the post // - 1 for the author $this->assertSame( 2, count( $actual['data']['actionMonitorActions']['nodes'] ) ); // Assert the action monitor has the actions for the post being created $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'CREATE', 'referencedNodeID' => (string) $post_id, 'referencedNodeSingularName' => 'wpGatsbyTest', ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $this->admin, 'referencedNodeSingularName' => 'user', ] ), ] ); } public function testCreatePostOfCustomPostTypeNotInGraphQLDoesNotCreateActionMonitorAction() { // register a post type to NOT show in GraphQL register_post_type( 'wp_gatsby_no', [ 'public' => true, 'show_in_graphql' => false, ] ); // Create a post $this->factory()->post->create( [ 'post_type' => 'wp_gatsby_no', 'post_status' => 'publish', 'post_title' => 'Title', 'post_author' => $this->admin, 'tags_input' => [ $this->tag ] ] ); codecept_debug( $this->tag ); // Query for action monitor actions $query = $this->actionMonitorQuery(); // Execute the query $actual = $this->graphql( compact( 'query' ) ); $this->assertIsValidQueryResponse( $actual ); // Creating a post for a custom post type not shown in GraphQL should trigger 0 actions: $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); } public function testCreatePostOfAPubliclyQueryableCustomPostTypeCreatesActionMonitorAction() { // Register a publicly queryable post type. register_post_type( 'wp_gatsby_test', [ 'public' => false, 'publicly_queryable' => true, 'show_in_graphql' => true, 'graphql_single_name' => 'wpGatsbyPubliclyQ', 'graphql_plural_name' => 'wpGatsbyPubliclyQs', ] ); codecept_debug( get_post_types( [ 'public' => false, 'show_in_graphql' => true, 'publicly_queryable' => true, ] ) ); $this->clear_action_monitor(); $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); // Create a post $post_id = $this->factory()->post->create( [ 'post_type' => 'wp_gatsby_test', 'post_status' => 'publish', 'post_title' => 'Title', 'post_author' => $this->admin, 'tags_input' => [ $this->tag ] ] ); codecept_debug( get_post( $post_id ) ); // Query for action monitor actions $query = $this->actionMonitorQuery(); // Execute the query $actual = $this->graphql( compact( 'query' ) ); $this->assertIsValidQueryResponse( $actual ); // Creating a post assigned to an author should trigger 2 actions: // - 1 for the post // - 1 for the author $this->assertSame( 2, count( $actual['data']['actionMonitorActions']['nodes'] ) ); // Assert the action monitor has the actions for the post being created $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'CREATE', 'referencedNodeID' => (string) $post_id, 'referencedNodeSingularName' => 'wpGatsbyPubliclyQ', ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $this->admin, 'referencedNodeSingularName' => 'user', ] ), ] ); } public function testCreateCategoryCreatesActionMonitorAction() { // Create a post $category_id = $this->factory()->category->create([ 'name' => 'test' ]); // Query for action monitor actions $query = $this->actionMonitorQuery(); // Execute the query $actual = $this->graphql( compact( 'query' ) ); $this->assertIsValidQueryResponse( $actual ); // Creating a category trigger 1 actions: // - 1 for the category being created $this->assertSame( 1, count( $actual['data']['actionMonitorActions']['nodes'] ) ); // Assert the action monitor has the actions for the post being created $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'CREATE', 'referencedNodeID' => (string) $category_id, 'referencedNodeSingularName' => 'category' ] ), ] ); } public function testCreateTermOfPrivateTaxonomyDoesNotCreateActionMonitorAction() { register_taxonomy( 'private_taxonomy', 'post', [ 'public' => false, 'show_in_graphql' => true, 'graphql_single_name' => 'privateTaxTerm', 'graphql_plural_name' => 'privateTaxTerms' ]); // Create a post $term_id = $this->factory()->term->create([ 'name' => 'test', 'taxonomy' => 'private_taxonomy', ]); // Query for action monitor actions $query = $this->actionMonitorQuery(); // Execute the query $actual = $this->graphql( compact( 'query' ) ); $this->assertIsValidQueryResponse( $actual ); // Creating a term of private taxonomy should trigger 0 actions: $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); } public function testUpdateCategoryCreatesActionMonitorAction() { // Create a post $category_id = $this->factory()->category->create(); $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); wp_update_term( $category_id, 'category', [ 'description' => 'updated...' ] ); // Query for action monitor actions $query = $this->actionMonitorQuery(); // Execute the query $actual = $this->graphql( compact( 'query' ) ); $this->assertIsValidQueryResponse( $actual ); // Updating a category should trigger 1 action $this->assertSame( 1, count( $actual['data']['actionMonitorActions']['nodes'] ) ); // Assert the action monitor has the actions for the post being created $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $category_id, 'referencedNodeSingularName' => 'category' ] ), ] ); } public function testDeleteCategoryCreatesActionMonitorAction() { // Create a post $category_id = $this->factory()->category->create(); $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); wp_delete_term( $category_id, 'category' ); // Query for action monitor actions $query = $this->actionMonitorQuery(); // Execute the query $actual = $this->graphql( compact( 'query' ) ); $this->assertIsValidQueryResponse( $actual ); // Creating a post assigned to an author should trigger 1 actions: // - 1 for the category being updated $this->assertSame( 1, count( $actual['data']['actionMonitorActions']['nodes'] ) ); // Assert the action monitor has the actions for the post being created $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'DELETE', 'referencedNodeID' => (string) $category_id, 'referencedNodeSingularName' => 'category' ] ), ] ); } public function testUpdateCategoryMetaCreatesActionMonitorAction() { // Create a post $category_id = $this->factory()->category->create(); $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); update_term_meta( $category_id, 'test_key', 'test_value' ); // Query for action monitor actions $query = $this->actionMonitorQuery(); // Execute the query $actual = $this->graphql( compact( 'query' ) ); $this->assertIsValidQueryResponse( $actual ); // Creating a post assigned to an author should trigger 1 actions: // - 1 for the category being updated $this->assertSame( 1, count( $actual['data']['actionMonitorActions']['nodes'] ) ); // Assert the action monitor has the actions for the post being created $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $category_id, 'referencedNodeSingularName' => 'category' ] ), ] ); } public function testDeleteCategoryMetaCreatesActionMonitorAction() { // Create a post $category_id = $this->factory()->category->create(); update_term_meta( $category_id, 'test_key', 'test_value' ); $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); delete_term_meta( $category_id, 'test_key' ); // Query for action monitor actions $query = $this->actionMonitorQuery(); // Execute the query $actual = $this->graphql( compact( 'query' ) ); $this->assertIsValidQueryResponse( $actual ); // Creating a post assigned to an author should trigger 1 actions: // - 1 for the category being updated $this->assertSame( 1, count( $actual['data']['actionMonitorActions']['nodes'] ) ); // Assert the action monitor has the actions for the post being created $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $category_id, 'referencedNodeSingularName' => 'category' ] ), ] ); } public function testCreateUserDoesNotCreateActionMonitorAction() { $this->factory()->user->create(); // Query for action monitor actions $query = $this->actionMonitorQuery(); // Execute the query $actual = $this->graphql( compact( 'query' ) ); $this->assertIsValidQueryResponse( $actual ); // Creating a user shouldn't trigger an action because a user isn't public until // it has published posts $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); } public function testDeleteUserWithoutPublishedPostsDoesNotCreateActionMonitorAction() { $user_id = $this->factory()->user->create([ 'role' => 'editor' ]); $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); wp_delete_user( $user_id ); // Query for action monitor actions $query = $this->actionMonitorQuery(); // Execute the query $actual = $this->graphql( compact( 'query' ) ); $this->assertIsValidQueryResponse( $actual ); // Deleting a user with no published content should not trigger an action $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); } public function testDeleteUserWithoutReassigningPublishedPostsCreatesActionMonitorActions() { $user_id = $this->factory()->user->create(); $post_id = $this->factory()->post->create( [ 'post_type' => 'post', 'post_status' => 'publish', 'post_author' => $user_id, 'post_title' => 'test' ] ); $page_id = $this->factory()->post->create( [ 'post_type' => 'page', 'post_status' => 'publish', 'post_author' => $user_id, 'post_title' => 'test' ] ); $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); wp_delete_user( $user_id ); // Query for action monitor actions $query = $this->actionMonitorQuery(); // Execute the query $actual = $this->graphql( compact( 'query' ) ); codecept_debug( $actual ); $this->assertIsValidQueryResponse( $actual ); /** * Deleting a user with no published content should trigger 1 actions * - 1 for the user being deleted * - 1 for the page being deleted * - 1 for the post being deleted * (this will actually create 1 action for each post the author was author of) * * @todo: reduce this to a BULK_DELETE action. The source plugin will need to support this though. */ $this->assertSame( 3, count( $actual['data']['actionMonitorActions']['nodes'] ) ); // Assert the action monitor has the actions for the user being deleted $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'DELETE', 'referencedNodeID' => (string) $user_id, 'referencedNodeSingularName' => 'user' ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'DELETE', 'referencedNodeID' => (string) $post_id, 'referencedNodeSingularName' => 'post' ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'DELETE', 'referencedNodeID' => (string) $page_id, 'referencedNodeSingularName' => 'page' ] ), ] ); } public function testDeleteUserAndReassignPostsCreatesActionMonitorAction() { $user_id = $this->factory()->user->create([ 'role' => 'editor' ]); $post_id = $this->factory()->post->create( [ 'post_type' => 'post', 'post_status' => 'publish', 'post_author' => $user_id, 'post_title' => 'test' ] ); $page_id = $this->factory()->post->create( [ 'post_type' => 'page', 'post_status' => 'publish', 'post_author' => $user_id, 'post_title' => 'test' ] ); // Also create a draft page assigned to the user. This should NOT trigger an action // when it's re-assigned during user deletion $draft_page_id = $this->factory()->post->create( [ 'post_type' => 'page', 'post_status' => 'draft', 'post_author' => $user_id, 'post_title' => 'test' ] ); $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); wp_delete_user( (int) $user_id, (int) $this->admin ); // Query for action monitor actions $query = $this->actionMonitorQuery(); // Execute the query $actual = $this->graphql( compact( 'query' ) ); codecept_debug( $actual ); $this->assertIsValidQueryResponse( $actual ); /** * Deleting a user with 2 published posts and re-assigning should create 4 actions * - 1 for the user being deleted * - 1 for the page being transferred to another author * - 1 for the post being transferred to another author * - 1 for the author that got reassigned to * (this will actually create 1 action for each post the author was author of) * * @todo: reduce this to a BULK_DELETE action. The source plugin will need to support this though. */ $this->assertSame( 4, count( $actual['data']['actionMonitorActions']['nodes'] ) ); // Assert the action monitor has the actions for the user being deleted $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'DELETE', 'referencedNodeID' => (string) $user_id, 'referencedNodeSingularName' => 'user' ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $post_id, 'referencedNodeSingularName' => 'post' ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $page_id, 'referencedNodeSingularName' => 'page' ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $this->admin, 'referencedNodeSingularName' => 'user' ] ), ] ); } public function testUpdateUserWithPublishedPostsCreatesActionMonitorAction() { $user_id = $this->factory()->user->create([ 'role' => 'editor' ]); $this->factory()->post->create( [ 'post_type' => 'post', 'post_status' => 'publish', 'post_author' => $user_id, 'post_title' => 'test' ] ); $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); wp_update_user( [ 'ID' => $user_id, 'display_name' => 'updated_display_name' ] ); // Query for action monitor actions $query = $this->actionMonitorQuery(); // Execute the query $actual = $this->graphql( compact( 'query' ) ); $this->assertIsValidQueryResponse( $actual ); /** * Deleting a user with no published content should trigger 1 actions * - 1 for the user being updated */ $this->assertSame( 1, count( $actual['data']['actionMonitorActions']['nodes'] ) ); // Assert the action monitor has the actions for the user being updated $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $user_id, 'referencedNodeSingularName' => 'user' ] ), ] ); } public function testUpdateUserMetaWithTrackedMetaKeyForPublishedAuthorCreatesActionMonitorAction() { $user_id = $this->factory()->user->create([ 'role' => 'editor' ] ); $this->factory()->post->create( [ 'post_type' => 'post', 'post_status' => 'publish', 'post_author' => $user_id, 'post_title' => 'test' ] ); update_user_meta( $user_id, 'description', 'test...' ); $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); update_user_meta( $user_id, 'description', 'test_value' ); // Query for action monitor actions $query = $this->actionMonitorQuery(); // Execute the query $actual = $this->graphql( compact( 'query' ) ); $this->assertIsValidQueryResponse( $actual ); /** * Deleting a user with no published content should trigger 1 actions * - 1 for the user being updated */ $this->assertSame( 1, count( $actual['data']['actionMonitorActions']['nodes'] ) ); // Assert the action monitor has the actions for the user being deleted $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $user_id, 'referencedNodeSingularName' => 'user' ] ), ] ); } public function testUpdateUserMetaWithUntrackedMetaKeyForPublishedAuthorDoesNotCreateActionMonitorAction() { $user_id = $this->factory()->user->create(); $this->factory()->post->create( [ 'post_type' => 'post', 'post_status' => 'publish', 'post_author' => $user_id, 'post_title' => 'test' ] ); update_user_meta( $user_id, 'show_admin_bar_front', 'test...' ); $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); update_user_meta( $user_id, 'show_admin_bar_front', 'test...' ); // Query for action monitor actions $query = $this->actionMonitorQuery(); // Execute the query $actual = $this->graphql( compact( 'query' ) ); $this->assertIsValidQueryResponse( $actual ); /** * Updating user meta of an untracked meta_key should not trigger any actions */ $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); } public function testDeleteUserMetaForTrackedMetaKeyOfPublishedAuthorCreatesActionMonitorAction() { $user_id = $this->factory()->user->create(); $this->factory()->post->create( [ 'post_type' => 'post', 'post_status' => 'publish', 'post_author' => $user_id, 'post_title' => 'test' ] ); update_user_meta( $user_id, 'nickname', 'test_value' ); $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); delete_user_meta( $user_id, 'nickname' ); // Query for action monitor actions $query = $this->actionMonitorQuery(); // Execute the query $actual = $this->graphql( compact( 'query' ) ); $this->assertIsValidQueryResponse( $actual ); /** * Updating user meta with a tracked meta key should create 1 action */ $this->assertSame( 1, count( $actual['data']['actionMonitorActions']['nodes'] ) ); // Assert the action monitor has the actions for the user being deleted $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $user_id, 'referencedNodeSingularName' => 'user' ] ), ] ); } public function testDeleteUserMetaForUntrackedMetaKeyOfPublishedAuthorCreatesActionMonitorAction() { $user_id = $this->factory()->user->create(); $this->factory()->post->create( [ 'post_type' => 'post', 'post_status' => 'publish', 'post_author' => $user_id, 'post_title' => 'test' ] ); update_user_meta( $user_id, 'test', 'test_value' ); $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); delete_user_meta( $user_id, 'test' ); // Query for action monitor actions $query = $this->actionMonitorQuery(); // Execute the query $actual = $this->graphql( compact( 'query' ) ); $this->assertIsValidQueryResponse( $actual ); /** * Updating user meta with a tracked meta key should create 1 action */ $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); } public function testCreateHierarchicalTermWithParentCreatesActionMonitorAction() { $parent_id = $this->factory()->category->create([ 'name' => 'parent' ]); $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); $child_id = $this->factory()->category->create([ 'name' => 'child', 'parent' => $parent_id, ]); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 2, count( $actual['data']['actionMonitorActions']['nodes'] ) ); $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $parent_id, 'referencedNodeSingularName' => 'category' ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'CREATE', 'referencedNodeID' => (string) $child_id, 'referencedNodeSingularName' => 'category' ] ), ] ); } public function testUpdateHierarchicalTermWithParentAndChildCreatesActionMonitorAction() { $parent_id = $this->factory()->category->create([ 'name' => 'parent' ]); $child_id = $this->factory()->category->create([ 'name' => 'child', 'parent' => $parent_id, ]); $grandchild_id = $this->factory()->category->create([ 'name' => 'grandchild', 'parent' => $child_id, ]); $grandchild_two = $this->factory()->category->create([ 'name' => 'grandchild_two', 'parent' => $child_id, ]); $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); wp_update_term( $child_id, 'category', [ 'description' => 'test...', ]); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 4, count( $actual['data']['actionMonitorActions']['nodes'] ) ); $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $parent_id, 'referencedNodeSingularName' => 'category' ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $child_id, 'referencedNodeSingularName' => 'category' ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $grandchild_id, 'referencedNodeSingularName' => 'category' ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $grandchild_two, 'referencedNodeSingularName' => 'category' ] ), ] ); } public function testDeleteHierarchicalTermThatHasParentAndChildrenCreatesActionMonitorAction() { $parent_id = $this->factory()->category->create([ 'name' => 'parent' ]); $child_id = $this->factory()->category->create([ 'name' => 'child', 'parent' => $parent_id, ]); $grandchild_id = $this->factory()->category->create([ 'name' => 'grandchild', 'parent' => $child_id, ]); $grandchild_two = $this->factory()->category->create([ 'name' => 'grandchild_two', 'parent' => $child_id, ]); $this->clear_action_monitor(); // Query for action monitor actions $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); wp_delete_term( $child_id, 'category' ); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 4, count( $actual['data']['actionMonitorActions']['nodes'] ) ); $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $parent_id, 'referencedNodeSingularName' => 'category' ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'DELETE', 'referencedNodeID' => (string) $child_id, 'referencedNodeSingularName' => 'category' ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $grandchild_id, 'referencedNodeSingularName' => 'category' ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $grandchild_two, 'referencedNodeSingularName' => 'category' ] ), ] ); } public function testRestorePostFromTrashCreatesActionMonitorAction() { $post_data = [ 'post_type' => 'post', 'post_status' => 'trash', 'post_title' => 'trashed', 'post_author' => $this->admin ]; $post_id = $this->factory()->post->create( $post_data ); $this->clear_action_monitor(); // Publish the post wp_update_post( [ 'ID' => $post_id, 'post_status' => 'publish' ] ); // Query for action monitor actions $query = $this->actionMonitorQuery(); // Execute the query $actual = $this->graphql( compact( 'query' ) ); $this->assertIsValidQueryResponse( $actual ); /** * Deleting a user with no published content should trigger 2 actions * - 1 for the user being updated * - 1 for the post being restored */ $this->assertSame( 2, count( $actual['data']['actionMonitorActions']['nodes'] ) ); // Assert the action monitor has the actions for the user being deleted $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'CREATE', 'referencedNodeID' => (string) $post_id, 'referencedNodeSingularName' => 'post' ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $this->admin, 'referencedNodeSingularName' => 'user' ] ), ] ); } public function testUploadPngMediaItemCreatesAction() { $this->clear_action_monitor(); $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); $filename = WPGATSBY_PLUGIN_DIR . '/tests/_data/images/test.png'; $image_id = $this->factory()->attachment->create_upload_object( $filename ); codecept_debug( $image_id ); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 1, count( $actual['data']['actionMonitorActions']['nodes'] ) ); $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'CREATE', 'referencedNodeID' => (string) $image_id, 'referencedNodeSingularName' => 'mediaItem' ] ), ] ); } public function testUpdateMediaItemCreatesAction() { $filename = WPGATSBY_PLUGIN_DIR . '/tests/_data/images/test.png'; $image_id = $this->factory()->attachment->create_upload_object( $filename ); $this->clear_action_monitor(); $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); wp_update_post([ 'ID' => $image_id, 'post_content' => 'test...' ]); codecept_debug( $image_id ); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 1, count( $actual['data']['actionMonitorActions']['nodes'] ) ); $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $image_id, 'referencedNodeSingularName' => 'mediaItem' ] ), ] ); } public function testDeleteMediaItemCreatesAction() { $filename = WPGATSBY_PLUGIN_DIR . '/tests/_data/images/test.png'; $image_id = $this->factory()->attachment->create_upload_object( $filename ); $this->clear_action_monitor(); $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); wp_delete_attachment( $image_id ); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 1, count( $actual['data']['actionMonitorActions']['nodes'] ) ); $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'DELETE', 'referencedNodeID' => (string) $image_id, 'referencedNodeSingularName' => 'mediaItem' ] ), ] ); } public function testCreateNavMenuDoesNotCreateActionMonitorAction() { $this->clear_action_monitor(); $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); wp_create_nav_menu( 'Test Menu' ); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); } public function testAssignNavMenuToLocationCreatesActionMonitorAction() { $location_name = 'gatsby-test'; register_nav_menu($location_name, __( 'Gatsby Test Menu', 'WPGatsby' ) ); $menu_id = wp_create_nav_menu( __( 'Test Menu', 'WPGatsby' ) ); $post_id = $this->factory()->post->create(); wp_update_nav_menu_item( $menu_id, 0, [ 'menu-item-title' => 'Menu item', 'menu-item-object' => 'post', 'menu-item-object-id' => $post_id, 'menu-item-status' => 'publish', 'menu-item-type' => 'post_type', ] ); $this->clear_action_monitor(); $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); set_theme_mod( 'nav_menu_locations', [ $location_name => (int) $menu_id ] ); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 1, count( $actual['data']['actionMonitorActions']['nodes'] ) ); $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'CREATE', 'referencedNodeID' => (string) $menu_id, 'referencedNodeSingularName' => 'menu' ] ), ] ); } public function testUpdateNavMenuCreatesActionMonitorAction() { $location_name = 'gatsby-test'; register_nav_menu($location_name, __( 'Gatsby Test Menu', 'WPGatsby' ) ); $menu_id = wp_create_nav_menu( __( 'Test Menu', 'WPGatsby' ) ); $post_id = $this->factory()->post->create(); $menu_item_id = wp_update_nav_menu_item( $menu_id, 0, [ 'menu-item-title' => 'Menu item', 'menu-item-object' => 'post', 'menu-item-object-id' => $post_id, 'menu-item-status' => 'publish', 'menu-item-type' => 'post_type', ] ); set_theme_mod( 'nav_menu_locations', [ $location_name => (int) $menu_id ] ); $this->clear_action_monitor(); $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); // Add a new menu item $new_menu_item = wp_update_nav_menu_item( $menu_id, 0, [ 'menu-item-title' => 'Update Menu item', 'menu-item-object' => 'post', 'menu-item-object-id' => $post_id, 'menu-item-status' => 'publish', 'menu-item-type' => 'post_type', ] ); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 2, count( $actual['data']['actionMonitorActions']['nodes'] ) ); $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $menu_id, 'referencedNodeSingularName' => 'menu' ] ), $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'UPDATE', 'referencedNodeID' => (string) $new_menu_item, 'referencedNodeSingularName' => 'menuItem' ] ), ] ); } public function testDeleteMenuCreatesActionMonitorAction() { $location_name = 'gatsby-test'; register_nav_menu($location_name, __( 'Gatsby Test Menu', 'WPGatsby' ) ); $menu_id = wp_create_nav_menu( __( 'Test Menu', 'WPGatsby' ) ); $post_id = $this->factory()->post->create(); wp_update_nav_menu_item( $menu_id, 0, [ 'menu-item-title' => 'Menu item', 'menu-item-object' => 'post', 'menu-item-object-id' => $post_id, 'menu-item-status' => 'publish', 'menu-item-type' => 'post_type', ] ); set_theme_mod( 'nav_menu_locations', [ $location_name => (int) $menu_id ] ); $this->clear_action_monitor(); $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); // Delete the menu wp_delete_nav_menu( $menu_id ); // Deleting a menu creates the following actions // - 1 action for DELETE MENU // Gatsby will delete the menu and all associated menu items when this action occurs $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 1, count( $actual['data']['actionMonitorActions']['nodes'] ) ); $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'DELETE', 'referencedNodeID' => (string) $menu_id, 'referencedNodeSingularName' => 'menu' ] ), ] ); } public function testUpdatePermalinksCreatesActionMonitorAction() { $option_name = 'permalink_structure'; $structure = '/%year%/%monthnum%/%postname%/'; update_option( $option_name, $structure ); $this->clear_action_monitor(); $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); update_option( $option_name, '/archives/%post_id%' ); // Updating permalinks should create 1 action // - 1 action $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 1, count( $actual['data']['actionMonitorActions']['nodes'] ) ); $this->assertQuerySuccessful( $actual, [ $this->expectedNode( 'actionMonitorActions.nodes', [ 'actionType' => 'REFETCH_ALL', 'referencedNodeID' => (string) 'refetch_all', 'referencedNodeSingularName' => 'refetchAll' ] ), ] ); } public function testUpdateUntrackedOptionDoesNotCreateActionMonitorAction() { $this->clear_action_monitor(); $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); update_option( 'test_option', 'test' ); // Updating untracked option should create 0 actions $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); } public function testSetTransientDoesNotCreateActionMonitorAction() { $this->clear_action_monitor(); $query = $this->actionMonitorQuery(); $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); $transient = set_transient( 'test_transient', 'test', 600 ); // Setting a transient should create 0 action $actual = $this->graphql( compact( 'query' ) ); $this->assertSame( 0, count( $actual['data']['actionMonitorActions']['nodes'] ) ); } } ================================================ FILE: tests/wpunit.suite.dist.yml ================================================ # Codeception Test Suite Configuration # # Suite for unit or integration tests that require WordPress functions and classes. actor: WpunitTester modules: enabled: - WPLoader disabled: - WPDb - WPBrowser config: WPDb: cleanup: false WPLoader: plugins: - wp-graphql/wp-graphql.php - wp-gatsby/wp-gatsby.php activatePlugins: - wp-graphql/wp-graphql.php - wp-gatsby/wp-gatsby.php ================================================ FILE: vendor/autoload.php ================================================ * Jordi Boggiano * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Autoload; /** * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. * * $loader = new \Composer\Autoload\ClassLoader(); * * // register classes with namespaces * $loader->add('Symfony\Component', __DIR__.'/component'); * $loader->add('Symfony', __DIR__.'/framework'); * * // activate the autoloader * $loader->register(); * * // to enable searching the include path (eg. for PEAR packages) * $loader->setUseIncludePath(true); * * In this example, if you try to use a class in the Symfony\Component * namespace or one of its children (Symfony\Component\Console for instance), * the autoloader will first look for the class under the component/ * directory, and it will then fallback to the framework/ directory if not * found before giving up. * * This class is loosely based on the Symfony UniversalClassLoader. * * @author Fabien Potencier * @author Jordi Boggiano * @see http://www.php-fig.org/psr/psr-0/ * @see http://www.php-fig.org/psr/psr-4/ */ class ClassLoader { // PSR-4 private $prefixLengthsPsr4 = array(); private $prefixDirsPsr4 = array(); private $fallbackDirsPsr4 = array(); // PSR-0 private $prefixesPsr0 = array(); private $fallbackDirsPsr0 = array(); private $useIncludePath = false; private $classMap = array(); private $classMapAuthoritative = false; private $missingClasses = array(); private $apcuPrefix; public function getPrefixes() { if (!empty($this->prefixesPsr0)) { return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); } return array(); } public function getPrefixesPsr4() { return $this->prefixDirsPsr4; } public function getFallbackDirs() { return $this->fallbackDirsPsr0; } public function getFallbackDirsPsr4() { return $this->fallbackDirsPsr4; } public function getClassMap() { return $this->classMap; } /** * @param array $classMap Class to filename map */ public function addClassMap(array $classMap) { if ($this->classMap) { $this->classMap = array_merge($this->classMap, $classMap); } else { $this->classMap = $classMap; } } /** * Registers a set of PSR-0 directories for a given prefix, either * appending or prepending to the ones previously set for this prefix. * * @param string $prefix The prefix * @param array|string $paths The PSR-0 root directories * @param bool $prepend Whether to prepend the directories */ public function add($prefix, $paths, $prepend = false) { if (!$prefix) { if ($prepend) { $this->fallbackDirsPsr0 = array_merge( (array) $paths, $this->fallbackDirsPsr0 ); } else { $this->fallbackDirsPsr0 = array_merge( $this->fallbackDirsPsr0, (array) $paths ); } return; } $first = $prefix[0]; if (!isset($this->prefixesPsr0[$first][$prefix])) { $this->prefixesPsr0[$first][$prefix] = (array) $paths; return; } if ($prepend) { $this->prefixesPsr0[$first][$prefix] = array_merge( (array) $paths, $this->prefixesPsr0[$first][$prefix] ); } else { $this->prefixesPsr0[$first][$prefix] = array_merge( $this->prefixesPsr0[$first][$prefix], (array) $paths ); } } /** * Registers a set of PSR-4 directories for a given namespace, either * appending or prepending to the ones previously set for this namespace. * * @param string $prefix The prefix/namespace, with trailing '\\' * @param array|string $paths The PSR-4 base directories * @param bool $prepend Whether to prepend the directories * * @throws \InvalidArgumentException */ public function addPsr4($prefix, $paths, $prepend = false) { if (!$prefix) { // Register directories for the root namespace. if ($prepend) { $this->fallbackDirsPsr4 = array_merge( (array) $paths, $this->fallbackDirsPsr4 ); } else { $this->fallbackDirsPsr4 = array_merge( $this->fallbackDirsPsr4, (array) $paths ); } } elseif (!isset($this->prefixDirsPsr4[$prefix])) { // Register directories for a new namespace. $length = strlen($prefix); if ('\\' !== $prefix[$length - 1]) { throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); } $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; $this->prefixDirsPsr4[$prefix] = (array) $paths; } elseif ($prepend) { // Prepend directories for an already registered namespace. $this->prefixDirsPsr4[$prefix] = array_merge( (array) $paths, $this->prefixDirsPsr4[$prefix] ); } else { // Append directories for an already registered namespace. $this->prefixDirsPsr4[$prefix] = array_merge( $this->prefixDirsPsr4[$prefix], (array) $paths ); } } /** * Registers a set of PSR-0 directories for a given prefix, * replacing any others previously set for this prefix. * * @param string $prefix The prefix * @param array|string $paths The PSR-0 base directories */ public function set($prefix, $paths) { if (!$prefix) { $this->fallbackDirsPsr0 = (array) $paths; } else { $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; } } /** * Registers a set of PSR-4 directories for a given namespace, * replacing any others previously set for this namespace. * * @param string $prefix The prefix/namespace, with trailing '\\' * @param array|string $paths The PSR-4 base directories * * @throws \InvalidArgumentException */ public function setPsr4($prefix, $paths) { if (!$prefix) { $this->fallbackDirsPsr4 = (array) $paths; } else { $length = strlen($prefix); if ('\\' !== $prefix[$length - 1]) { throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); } $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; $this->prefixDirsPsr4[$prefix] = (array) $paths; } } /** * Turns on searching the include path for class files. * * @param bool $useIncludePath */ public function setUseIncludePath($useIncludePath) { $this->useIncludePath = $useIncludePath; } /** * Can be used to check if the autoloader uses the include path to check * for classes. * * @return bool */ public function getUseIncludePath() { return $this->useIncludePath; } /** * Turns off searching the prefix and fallback directories for classes * that have not been registered with the class map. * * @param bool $classMapAuthoritative */ public function setClassMapAuthoritative($classMapAuthoritative) { $this->classMapAuthoritative = $classMapAuthoritative; } /** * Should class lookup fail if not found in the current class map? * * @return bool */ public function isClassMapAuthoritative() { return $this->classMapAuthoritative; } /** * APCu prefix to use to cache found/not-found classes, if the extension is enabled. * * @param string|null $apcuPrefix */ public function setApcuPrefix($apcuPrefix) { $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null; } /** * The APCu prefix in use, or null if APCu caching is not enabled. * * @return string|null */ public function getApcuPrefix() { return $this->apcuPrefix; } /** * Registers this instance as an autoloader. * * @param bool $prepend Whether to prepend the autoloader or not */ public function register($prepend = false) { spl_autoload_register(array($this, 'loadClass'), true, $prepend); } /** * Unregisters this instance as an autoloader. */ public function unregister() { spl_autoload_unregister(array($this, 'loadClass')); } /** * Loads the given class or interface. * * @param string $class The name of the class * @return bool|null True if loaded, null otherwise */ public function loadClass($class) { if ($file = $this->findFile($class)) { includeFile($file); return true; } } /** * Finds the path to the file where the class is defined. * * @param string $class The name of the class * * @return string|false The path if found, false otherwise */ public function findFile($class) { // class map lookup if (isset($this->classMap[$class])) { return $this->classMap[$class]; } if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { return false; } if (null !== $this->apcuPrefix) { $file = apcu_fetch($this->apcuPrefix.$class, $hit); if ($hit) { return $file; } } $file = $this->findFileWithExtension($class, '.php'); // Search for Hack files if we are running on HHVM if (false === $file && defined('HHVM_VERSION')) { $file = $this->findFileWithExtension($class, '.hh'); } if (null !== $this->apcuPrefix) { apcu_add($this->apcuPrefix.$class, $file); } if (false === $file) { // Remember that this class does not exist. $this->missingClasses[$class] = true; } return $file; } private function findFileWithExtension($class, $ext) { // PSR-4 lookup $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; $first = $class[0]; if (isset($this->prefixLengthsPsr4[$first])) { $subPath = $class; while (false !== $lastPos = strrpos($subPath, '\\')) { $subPath = substr($subPath, 0, $lastPos); $search = $subPath . '\\'; if (isset($this->prefixDirsPsr4[$search])) { $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); foreach ($this->prefixDirsPsr4[$search] as $dir) { if (file_exists($file = $dir . $pathEnd)) { return $file; } } } } } // PSR-4 fallback dirs foreach ($this->fallbackDirsPsr4 as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { return $file; } } // PSR-0 lookup if (false !== $pos = strrpos($class, '\\')) { // namespaced class name $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); } else { // PEAR-like class name $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; } if (isset($this->prefixesPsr0[$first])) { foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { if (0 === strpos($class, $prefix)) { foreach ($dirs as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { return $file; } } } } } // PSR-0 fallback dirs foreach ($this->fallbackDirsPsr0 as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { return $file; } } // PSR-0 include paths. if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { return $file; } return false; } } /** * Scope isolated include. * * Prevents access to $this/self from included files. */ function includeFile($file) { include $file; } ================================================ FILE: vendor/composer/LICENSE ================================================ Copyright (c) Nils Adermann, Jordi Boggiano Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: vendor/composer/autoload_classmap.php ================================================ $vendorDir . '/composer/semver/src/Comparator.php', 'Composer\\Semver\\Constraint\\AbstractConstraint' => $vendorDir . '/composer/semver/src/Constraint/AbstractConstraint.php', 'Composer\\Semver\\Constraint\\Constraint' => $vendorDir . '/composer/semver/src/Constraint/Constraint.php', 'Composer\\Semver\\Constraint\\ConstraintInterface' => $vendorDir . '/composer/semver/src/Constraint/ConstraintInterface.php', 'Composer\\Semver\\Constraint\\EmptyConstraint' => $vendorDir . '/composer/semver/src/Constraint/EmptyConstraint.php', 'Composer\\Semver\\Constraint\\MultiConstraint' => $vendorDir . '/composer/semver/src/Constraint/MultiConstraint.php', 'Composer\\Semver\\Semver' => $vendorDir . '/composer/semver/src/Semver.php', 'Composer\\Semver\\VersionParser' => $vendorDir . '/composer/semver/src/VersionParser.php', 'Firebase\\JWT\\BeforeValidException' => $vendorDir . '/firebase/php-jwt/src/BeforeValidException.php', 'Firebase\\JWT\\ExpiredException' => $vendorDir . '/firebase/php-jwt/src/ExpiredException.php', 'Firebase\\JWT\\JWK' => $vendorDir . '/firebase/php-jwt/src/JWK.php', 'Firebase\\JWT\\JWT' => $vendorDir . '/firebase/php-jwt/src/JWT.php', 'Firebase\\JWT\\SignatureInvalidException' => $vendorDir . '/firebase/php-jwt/src/SignatureInvalidException.php', 'RandomLib\\AbstractMcryptMixer' => $vendorDir . '/ircmaxell/random-lib/lib/RandomLib/AbstractMcryptMixer.php', 'RandomLib\\AbstractMixer' => $vendorDir . '/ircmaxell/random-lib/lib/RandomLib/AbstractMixer.php', 'RandomLib\\AbstractSource' => $vendorDir . '/ircmaxell/random-lib/lib/RandomLib/AbstractSource.php', 'RandomLib\\Factory' => $vendorDir . '/ircmaxell/random-lib/lib/RandomLib/Factory.php', 'RandomLib\\Generator' => $vendorDir . '/ircmaxell/random-lib/lib/RandomLib/Generator.php', 'RandomLib\\Mixer' => $vendorDir . '/ircmaxell/random-lib/lib/RandomLib/Mixer.php', 'RandomLib\\Mixer\\Hash' => $vendorDir . '/ircmaxell/random-lib/lib/RandomLib/Mixer/Hash.php', 'RandomLib\\Mixer\\McryptRijndael128' => $vendorDir . '/ircmaxell/random-lib/lib/RandomLib/Mixer/McryptRijndael128.php', 'RandomLib\\Mixer\\XorMixer' => $vendorDir . '/ircmaxell/random-lib/lib/RandomLib/Mixer/XorMixer.php', 'RandomLib\\Source' => $vendorDir . '/ircmaxell/random-lib/lib/RandomLib/Source.php', 'RandomLib\\Source\\CAPICOM' => $vendorDir . '/ircmaxell/random-lib/lib/RandomLib/Source/CAPICOM.php', 'RandomLib\\Source\\MTRand' => $vendorDir . '/ircmaxell/random-lib/lib/RandomLib/Source/MTRand.php', 'RandomLib\\Source\\MicroTime' => $vendorDir . '/ircmaxell/random-lib/lib/RandomLib/Source/MicroTime.php', 'RandomLib\\Source\\OpenSSL' => $vendorDir . '/ircmaxell/random-lib/lib/RandomLib/Source/OpenSSL.php', 'RandomLib\\Source\\Rand' => $vendorDir . '/ircmaxell/random-lib/lib/RandomLib/Source/Rand.php', 'RandomLib\\Source\\Random' => $vendorDir . '/ircmaxell/random-lib/lib/RandomLib/Source/Random.php', 'RandomLib\\Source\\RandomBytes' => $vendorDir . '/ircmaxell/random-lib/lib/RandomLib/Source/RandomBytes.php', 'RandomLib\\Source\\Sodium' => $vendorDir . '/ircmaxell/random-lib/lib/RandomLib/Source/Sodium.php', 'RandomLib\\Source\\URandom' => $vendorDir . '/ircmaxell/random-lib/lib/RandomLib/Source/URandom.php', 'RandomLib\\Source\\UniqID' => $vendorDir . '/ircmaxell/random-lib/lib/RandomLib/Source/UniqID.php', 'SecurityLib\\AbstractFactory' => $vendorDir . '/ircmaxell/security-lib/lib/SecurityLib/AbstractFactory.php', 'SecurityLib\\BaseConverter' => $vendorDir . '/ircmaxell/security-lib/lib/SecurityLib/BaseConverter.php', 'SecurityLib\\BigMath' => $vendorDir . '/ircmaxell/security-lib/lib/SecurityLib/BigMath.php', 'SecurityLib\\BigMath\\BCMath' => $vendorDir . '/ircmaxell/security-lib/lib/SecurityLib/BigMath/BCMath.php', 'SecurityLib\\BigMath\\GMP' => $vendorDir . '/ircmaxell/security-lib/lib/SecurityLib/BigMath/GMP.php', 'SecurityLib\\BigMath\\PHPMath' => $vendorDir . '/ircmaxell/security-lib/lib/SecurityLib/BigMath/PHPMath.php', 'SecurityLib\\Enum' => $vendorDir . '/ircmaxell/security-lib/lib/SecurityLib/Enum.php', 'SecurityLib\\Hash' => $vendorDir . '/ircmaxell/security-lib/lib/SecurityLib/Hash.php', 'SecurityLib\\Strength' => $vendorDir . '/ircmaxell/security-lib/lib/SecurityLib/Strength.php', 'SecurityLib\\Util' => $vendorDir . '/ircmaxell/security-lib/lib/SecurityLib/Util.php', 'WPGatsby\\ActionMonitor\\ActionMonitor' => $baseDir . '/src/ActionMonitor/ActionMonitor.php', 'WPGatsby\\ActionMonitor\\Monitors\\AcfMonitor' => $baseDir . '/src/ActionMonitor/Monitors/AcfMonitor.php', 'WPGatsby\\ActionMonitor\\Monitors\\MediaMonitor' => $baseDir . '/src/ActionMonitor/Monitors/MediaMonitor.php', 'WPGatsby\\ActionMonitor\\Monitors\\Monitor' => $baseDir . '/src/ActionMonitor/Monitors/Monitor.php', 'WPGatsby\\ActionMonitor\\Monitors\\NavMenuMonitor' => $baseDir . '/src/ActionMonitor/Monitors/NavMenuMonitor.php', 'WPGatsby\\ActionMonitor\\Monitors\\PostMonitor' => $baseDir . '/src/ActionMonitor/Monitors/PostMonitor.php', 'WPGatsby\\ActionMonitor\\Monitors\\PostTypeMonitor' => $baseDir . '/src/ActionMonitor/Monitors/PostTypeMonitor.php', 'WPGatsby\\ActionMonitor\\Monitors\\PreviewMonitor' => $baseDir . '/src/ActionMonitor/Monitors/PreviewMonitor.php', 'WPGatsby\\ActionMonitor\\Monitors\\SettingsMonitor' => $baseDir . '/src/ActionMonitor/Monitors/SettingsMonitor.php', 'WPGatsby\\ActionMonitor\\Monitors\\TaxonomyMonitor' => $baseDir . '/src/ActionMonitor/Monitors/TaxonomyMonitor.php', 'WPGatsby\\ActionMonitor\\Monitors\\TermMonitor' => $baseDir . '/src/ActionMonitor/Monitors/TermMonitor.php', 'WPGatsby\\ActionMonitor\\Monitors\\UserMonitor' => $baseDir . '/src/ActionMonitor/Monitors/UserMonitor.php', 'WPGatsby\\Admin\\Preview' => $baseDir . '/src/Admin/Preview.php', 'WPGatsby\\Admin\\Settings' => $baseDir . '/src/Admin/Settings.php', 'WPGatsby\\GraphQL\\Auth' => $baseDir . '/src/GraphQL/Auth.php', 'WPGatsby\\GraphQL\\ParseAuthToken' => $baseDir . '/src/GraphQL/ParseAuthToken.php', 'WPGatsby\\Schema\\Schema' => $baseDir . '/src/Schema/Schema.php', 'WPGatsby\\Schema\\SiteMeta' => $baseDir . '/src/Schema/SiteMeta.php', 'WPGatsby\\Schema\\WPGatsbyWPGraphQLSchemaChanges' => $baseDir . '/src/Schema/WPGatsbyWPGraphQLSchemaChanges.php', 'WPGatsby\\ThemeSupport\\ThemeSupport' => $baseDir . '/src/ThemeSupport/ThemeSupport.php', ); ================================================ FILE: vendor/composer/autoload_namespaces.php ================================================ array($vendorDir . '/ircmaxell/security-lib/lib'), 'RandomLib' => array($vendorDir . '/ircmaxell/random-lib/lib'), ); ================================================ FILE: vendor/composer/autoload_psr4.php ================================================ array($baseDir . '/src'), 'Firebase\\JWT\\' => array($vendorDir . '/firebase/php-jwt/src'), 'Composer\\Semver\\' => array($vendorDir . '/composer/semver/src'), ); ================================================ FILE: vendor/composer/autoload_real.php ================================================ = 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded()); if ($useStaticLoader) { require_once __DIR__ . '/autoload_static.php'; call_user_func(\Composer\Autoload\ComposerStaticInitd5ba67e9c3910011804380f1fed1cebe::getInitializer($loader)); } else { $map = require __DIR__ . '/autoload_namespaces.php'; foreach ($map as $namespace => $path) { $loader->set($namespace, $path); } $map = require __DIR__ . '/autoload_psr4.php'; foreach ($map as $namespace => $path) { $loader->setPsr4($namespace, $path); } $classMap = require __DIR__ . '/autoload_classmap.php'; if ($classMap) { $loader->addClassMap($classMap); } } $loader->register(true); return $loader; } } ================================================ FILE: vendor/composer/autoload_static.php ================================================ array ( 'WPGatsby\\' => 9, ), 'F' => array ( 'Firebase\\JWT\\' => 13, ), 'C' => array ( 'Composer\\Semver\\' => 16, ), ); public static $prefixDirsPsr4 = array ( 'WPGatsby\\' => array ( 0 => __DIR__ . '/../..' . '/src', ), 'Firebase\\JWT\\' => array ( 0 => __DIR__ . '/..' . '/firebase/php-jwt/src', ), 'Composer\\Semver\\' => array ( 0 => __DIR__ . '/..' . '/composer/semver/src', ), ); public static $prefixesPsr0 = array ( 'S' => array ( 'SecurityLib' => array ( 0 => __DIR__ . '/..' . '/ircmaxell/security-lib/lib', ), ), 'R' => array ( 'RandomLib' => array ( 0 => __DIR__ . '/..' . '/ircmaxell/random-lib/lib', ), ), ); public static $classMap = array ( 'Composer\\Semver\\Comparator' => __DIR__ . '/..' . '/composer/semver/src/Comparator.php', 'Composer\\Semver\\Constraint\\AbstractConstraint' => __DIR__ . '/..' . '/composer/semver/src/Constraint/AbstractConstraint.php', 'Composer\\Semver\\Constraint\\Constraint' => __DIR__ . '/..' . '/composer/semver/src/Constraint/Constraint.php', 'Composer\\Semver\\Constraint\\ConstraintInterface' => __DIR__ . '/..' . '/composer/semver/src/Constraint/ConstraintInterface.php', 'Composer\\Semver\\Constraint\\EmptyConstraint' => __DIR__ . '/..' . '/composer/semver/src/Constraint/EmptyConstraint.php', 'Composer\\Semver\\Constraint\\MultiConstraint' => __DIR__ . '/..' . '/composer/semver/src/Constraint/MultiConstraint.php', 'Composer\\Semver\\Semver' => __DIR__ . '/..' . '/composer/semver/src/Semver.php', 'Composer\\Semver\\VersionParser' => __DIR__ . '/..' . '/composer/semver/src/VersionParser.php', 'Firebase\\JWT\\BeforeValidException' => __DIR__ . '/..' . '/firebase/php-jwt/src/BeforeValidException.php', 'Firebase\\JWT\\ExpiredException' => __DIR__ . '/..' . '/firebase/php-jwt/src/ExpiredException.php', 'Firebase\\JWT\\JWK' => __DIR__ . '/..' . '/firebase/php-jwt/src/JWK.php', 'Firebase\\JWT\\JWT' => __DIR__ . '/..' . '/firebase/php-jwt/src/JWT.php', 'Firebase\\JWT\\SignatureInvalidException' => __DIR__ . '/..' . '/firebase/php-jwt/src/SignatureInvalidException.php', 'RandomLib\\AbstractMcryptMixer' => __DIR__ . '/..' . '/ircmaxell/random-lib/lib/RandomLib/AbstractMcryptMixer.php', 'RandomLib\\AbstractMixer' => __DIR__ . '/..' . '/ircmaxell/random-lib/lib/RandomLib/AbstractMixer.php', 'RandomLib\\AbstractSource' => __DIR__ . '/..' . '/ircmaxell/random-lib/lib/RandomLib/AbstractSource.php', 'RandomLib\\Factory' => __DIR__ . '/..' . '/ircmaxell/random-lib/lib/RandomLib/Factory.php', 'RandomLib\\Generator' => __DIR__ . '/..' . '/ircmaxell/random-lib/lib/RandomLib/Generator.php', 'RandomLib\\Mixer' => __DIR__ . '/..' . '/ircmaxell/random-lib/lib/RandomLib/Mixer.php', 'RandomLib\\Mixer\\Hash' => __DIR__ . '/..' . '/ircmaxell/random-lib/lib/RandomLib/Mixer/Hash.php', 'RandomLib\\Mixer\\McryptRijndael128' => __DIR__ . '/..' . '/ircmaxell/random-lib/lib/RandomLib/Mixer/McryptRijndael128.php', 'RandomLib\\Mixer\\XorMixer' => __DIR__ . '/..' . '/ircmaxell/random-lib/lib/RandomLib/Mixer/XorMixer.php', 'RandomLib\\Source' => __DIR__ . '/..' . '/ircmaxell/random-lib/lib/RandomLib/Source.php', 'RandomLib\\Source\\CAPICOM' => __DIR__ . '/..' . '/ircmaxell/random-lib/lib/RandomLib/Source/CAPICOM.php', 'RandomLib\\Source\\MTRand' => __DIR__ . '/..' . '/ircmaxell/random-lib/lib/RandomLib/Source/MTRand.php', 'RandomLib\\Source\\MicroTime' => __DIR__ . '/..' . '/ircmaxell/random-lib/lib/RandomLib/Source/MicroTime.php', 'RandomLib\\Source\\OpenSSL' => __DIR__ . '/..' . '/ircmaxell/random-lib/lib/RandomLib/Source/OpenSSL.php', 'RandomLib\\Source\\Rand' => __DIR__ . '/..' . '/ircmaxell/random-lib/lib/RandomLib/Source/Rand.php', 'RandomLib\\Source\\Random' => __DIR__ . '/..' . '/ircmaxell/random-lib/lib/RandomLib/Source/Random.php', 'RandomLib\\Source\\RandomBytes' => __DIR__ . '/..' . '/ircmaxell/random-lib/lib/RandomLib/Source/RandomBytes.php', 'RandomLib\\Source\\Sodium' => __DIR__ . '/..' . '/ircmaxell/random-lib/lib/RandomLib/Source/Sodium.php', 'RandomLib\\Source\\URandom' => __DIR__ . '/..' . '/ircmaxell/random-lib/lib/RandomLib/Source/URandom.php', 'RandomLib\\Source\\UniqID' => __DIR__ . '/..' . '/ircmaxell/random-lib/lib/RandomLib/Source/UniqID.php', 'SecurityLib\\AbstractFactory' => __DIR__ . '/..' . '/ircmaxell/security-lib/lib/SecurityLib/AbstractFactory.php', 'SecurityLib\\BaseConverter' => __DIR__ . '/..' . '/ircmaxell/security-lib/lib/SecurityLib/BaseConverter.php', 'SecurityLib\\BigMath' => __DIR__ . '/..' . '/ircmaxell/security-lib/lib/SecurityLib/BigMath.php', 'SecurityLib\\BigMath\\BCMath' => __DIR__ . '/..' . '/ircmaxell/security-lib/lib/SecurityLib/BigMath/BCMath.php', 'SecurityLib\\BigMath\\GMP' => __DIR__ . '/..' . '/ircmaxell/security-lib/lib/SecurityLib/BigMath/GMP.php', 'SecurityLib\\BigMath\\PHPMath' => __DIR__ . '/..' . '/ircmaxell/security-lib/lib/SecurityLib/BigMath/PHPMath.php', 'SecurityLib\\Enum' => __DIR__ . '/..' . '/ircmaxell/security-lib/lib/SecurityLib/Enum.php', 'SecurityLib\\Hash' => __DIR__ . '/..' . '/ircmaxell/security-lib/lib/SecurityLib/Hash.php', 'SecurityLib\\Strength' => __DIR__ . '/..' . '/ircmaxell/security-lib/lib/SecurityLib/Strength.php', 'SecurityLib\\Util' => __DIR__ . '/..' . '/ircmaxell/security-lib/lib/SecurityLib/Util.php', 'WPGatsby\\ActionMonitor\\ActionMonitor' => __DIR__ . '/../..' . '/src/ActionMonitor/ActionMonitor.php', 'WPGatsby\\ActionMonitor\\Monitors\\AcfMonitor' => __DIR__ . '/../..' . '/src/ActionMonitor/Monitors/AcfMonitor.php', 'WPGatsby\\ActionMonitor\\Monitors\\MediaMonitor' => __DIR__ . '/../..' . '/src/ActionMonitor/Monitors/MediaMonitor.php', 'WPGatsby\\ActionMonitor\\Monitors\\Monitor' => __DIR__ . '/../..' . '/src/ActionMonitor/Monitors/Monitor.php', 'WPGatsby\\ActionMonitor\\Monitors\\NavMenuMonitor' => __DIR__ . '/../..' . '/src/ActionMonitor/Monitors/NavMenuMonitor.php', 'WPGatsby\\ActionMonitor\\Monitors\\PostMonitor' => __DIR__ . '/../..' . '/src/ActionMonitor/Monitors/PostMonitor.php', 'WPGatsby\\ActionMonitor\\Monitors\\PostTypeMonitor' => __DIR__ . '/../..' . '/src/ActionMonitor/Monitors/PostTypeMonitor.php', 'WPGatsby\\ActionMonitor\\Monitors\\PreviewMonitor' => __DIR__ . '/../..' . '/src/ActionMonitor/Monitors/PreviewMonitor.php', 'WPGatsby\\ActionMonitor\\Monitors\\SettingsMonitor' => __DIR__ . '/../..' . '/src/ActionMonitor/Monitors/SettingsMonitor.php', 'WPGatsby\\ActionMonitor\\Monitors\\TaxonomyMonitor' => __DIR__ . '/../..' . '/src/ActionMonitor/Monitors/TaxonomyMonitor.php', 'WPGatsby\\ActionMonitor\\Monitors\\TermMonitor' => __DIR__ . '/../..' . '/src/ActionMonitor/Monitors/TermMonitor.php', 'WPGatsby\\ActionMonitor\\Monitors\\UserMonitor' => __DIR__ . '/../..' . '/src/ActionMonitor/Monitors/UserMonitor.php', 'WPGatsby\\Admin\\Preview' => __DIR__ . '/../..' . '/src/Admin/Preview.php', 'WPGatsby\\Admin\\Settings' => __DIR__ . '/../..' . '/src/Admin/Settings.php', 'WPGatsby\\GraphQL\\Auth' => __DIR__ . '/../..' . '/src/GraphQL/Auth.php', 'WPGatsby\\GraphQL\\ParseAuthToken' => __DIR__ . '/../..' . '/src/GraphQL/ParseAuthToken.php', 'WPGatsby\\Schema\\Schema' => __DIR__ . '/../..' . '/src/Schema/Schema.php', 'WPGatsby\\Schema\\SiteMeta' => __DIR__ . '/../..' . '/src/Schema/SiteMeta.php', 'WPGatsby\\Schema\\WPGatsbyWPGraphQLSchemaChanges' => __DIR__ . '/../..' . '/src/Schema/WPGatsbyWPGraphQLSchemaChanges.php', 'WPGatsby\\ThemeSupport\\ThemeSupport' => __DIR__ . '/../..' . '/src/ThemeSupport/ThemeSupport.php', ); public static function getInitializer(ClassLoader $loader) { return \Closure::bind(function () use ($loader) { $loader->prefixLengthsPsr4 = ComposerStaticInitd5ba67e9c3910011804380f1fed1cebe::$prefixLengthsPsr4; $loader->prefixDirsPsr4 = ComposerStaticInitd5ba67e9c3910011804380f1fed1cebe::$prefixDirsPsr4; $loader->prefixesPsr0 = ComposerStaticInitd5ba67e9c3910011804380f1fed1cebe::$prefixesPsr0; $loader->classMap = ComposerStaticInitd5ba67e9c3910011804380f1fed1cebe::$classMap; }, null, ClassLoader::class); } } ================================================ FILE: vendor/composer/semver/CHANGELOG.md ================================================ # Change Log All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/). ### [1.7.2] 2020-12-03 * Fixed: Allow installing on php 8 ### [1.7.1] 2020-09-27 * Fixed: accidental validation of broken constraints combining ^/~ and wildcards, and -dev suffix allowing weird cases * Fixed: normalization of beta0 and such which was dropping the 0 ### [1.7.0] 2020-09-09 * Added: support for `x || @dev`, not very useful but seen in the wild and failed to validate with 1.5.2/1.6.0 * Added: support for `foobar-dev` being equal to `dev-foobar`, dev-foobar is the official way to write it but we need to support the other for BC and convenience ### [1.6.0] 2020-09-08 * Added: support for constraints like `^2.x-dev` and `~2.x-dev`, not very useful but seen in the wild and failed to validate with 1.5.2 * Fixed: invalid aliases will no longer throw, unless explicitly validated by Composer in the root package ### [1.5.2] 2020-09-08 * Fixed: handling of some invalid -dev versions which were seen as valid * Fixed: some doctypes ### [1.5.1] 2020-01-13 * Fixed: Parsing of aliased version was not validating the alias to be a valid version ### [1.5.0] 2019-03-19 * Added: some support for date versions (e.g. 201903) in `~` operator * Fixed: support for stabilities in `~` operator was inconsistent ### [1.4.2] 2016-08-30 * Fixed: collapsing of complex constraints lead to buggy constraints ### [1.4.1] 2016-06-02 * Changed: branch-like requirements no longer strip build metadata - [composer/semver#38](https://github.com/composer/semver/pull/38). ### [1.4.0] 2016-03-30 * Added: getters on MultiConstraint - [composer/semver#35](https://github.com/composer/semver/pull/35). ### [1.3.0] 2016-02-25 * Fixed: stability parsing - [composer/composer#1234](https://github.com/composer/composer/issues/4889). * Changed: collapse contiguous constraints when possible. ### [1.2.0] 2015-11-10 * Changed: allow multiple numerical identifiers in 'pre-release' version part. * Changed: add more 'v' prefix support. ### [1.1.0] 2015-11-03 * Changed: dropped redundant `test` namespace. * Changed: minor adjustment in datetime parsing normalization. * Changed: `ConstraintInterface` relaxed, setPrettyString is not required anymore. * Changed: `AbstractConstraint` marked deprecated, will be removed in 2.0. * Changed: `Constraint` is now extensible. ### [1.0.0] 2015-09-21 * Break: `VersionConstraint` renamed to `Constraint`. * Break: `SpecificConstraint` renamed to `AbstractConstraint`. * Break: `LinkConstraintInterface` renamed to `ConstraintInterface`. * Break: `VersionParser::parseNameVersionPairs` was removed. * Changed: `VersionParser::parseConstraints` allows (but ignores) build metadata now. * Changed: `VersionParser::parseConstraints` allows (but ignores) prefixing numeric versions with a 'v' now. * Changed: Fixed namespace(s) of test files. * Changed: `Comparator::compare` no longer throws `InvalidArgumentException`. * Changed: `Constraint` now throws `InvalidArgumentException`. ### [0.1.0] 2015-07-23 * Added: `Composer\Semver\Comparator`, various methods to compare versions. * Added: various documents such as README.md, LICENSE, etc. * Added: configuration files for Git, Travis, php-cs-fixer, phpunit. * Break: the following namespaces were renamed: - Namespace: `Composer\Package\Version` -> `Composer\Semver` - Namespace: `Composer\Package\LinkConstraint` -> `Composer\Semver\Constraint` - Namespace: `Composer\Test\Package\Version` -> `Composer\Test\Semver` - Namespace: `Composer\Test\Package\LinkConstraint` -> `Composer\Test\Semver\Constraint` * Changed: code style using php-cs-fixer. [1.7.2]: https://github.com/composer/semver/compare/1.7.1...1.7.2 [1.7.1]: https://github.com/composer/semver/compare/1.7.0...1.7.1 [1.7.0]: https://github.com/composer/semver/compare/1.6.0...1.7.0 [1.6.0]: https://github.com/composer/semver/compare/1.5.2...1.6.0 [1.5.2]: https://github.com/composer/semver/compare/1.5.1...1.5.2 [1.5.1]: https://github.com/composer/semver/compare/1.5.0...1.5.1 [1.5.0]: https://github.com/composer/semver/compare/1.4.2...1.5.0 [1.4.2]: https://github.com/composer/semver/compare/1.4.1...1.4.2 [1.4.1]: https://github.com/composer/semver/compare/1.4.0...1.4.1 [1.4.0]: https://github.com/composer/semver/compare/1.3.0...1.4.0 [1.3.0]: https://github.com/composer/semver/compare/1.2.0...1.3.0 [1.2.0]: https://github.com/composer/semver/compare/1.1.0...1.2.0 [1.1.0]: https://github.com/composer/semver/compare/1.0.0...1.1.0 [1.0.0]: https://github.com/composer/semver/compare/0.1.0...1.0.0 [0.1.0]: https://github.com/composer/semver/compare/5e0b9a4da...0.1.0 ================================================ FILE: vendor/composer/semver/LICENSE ================================================ Copyright (C) 2015 Composer Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: vendor/composer/semver/README.md ================================================ composer/semver =============== Semver library that offers utilities, version constraint parsing and validation. Originally written as part of [composer/composer](https://github.com/composer/composer), now extracted and made available as a stand-alone library. [![Build Status](https://travis-ci.org/composer/semver.svg?branch=master)](https://travis-ci.org/composer/semver) Installation ------------ Install the latest version with: ```bash $ composer require composer/semver ``` Requirements ------------ * PHP 5.3.2 is required but using the latest version of PHP is highly recommended. Version Comparison ------------------ For details on how versions are compared, refer to the [Versions](https://getcomposer.org/doc/articles/versions.md) article in the documentation section of the [getcomposer.org](https://getcomposer.org) website. Basic usage ----------- ### Comparator The `Composer\Semver\Comparator` class provides the following methods for comparing versions: * greaterThan($v1, $v2) * greaterThanOrEqualTo($v1, $v2) * lessThan($v1, $v2) * lessThanOrEqualTo($v1, $v2) * equalTo($v1, $v2) * notEqualTo($v1, $v2) Each function takes two version strings as arguments and returns a boolean. For example: ```php use Composer\Semver\Comparator; Comparator::greaterThan('1.25.0', '1.24.0'); // 1.25.0 > 1.24.0 ``` ### Semver The `Composer\Semver\Semver` class provides the following methods: * satisfies($version, $constraints) * satisfiedBy(array $versions, $constraint) * sort($versions) * rsort($versions) License ------- composer/semver is licensed under the MIT License, see the LICENSE file for details. ================================================ FILE: vendor/composer/semver/composer.json ================================================ { "name": "composer/semver", "description": "Semver library that offers utilities, version constraint parsing and validation.", "type": "library", "license": "MIT", "keywords": [ "semver", "semantic", "versioning", "validation" ], "authors": [ { "name": "Nils Adermann", "email": "naderman@naderman.de", "homepage": "http://www.naderman.de" }, { "name": "Jordi Boggiano", "email": "j.boggiano@seld.be", "homepage": "http://seld.be" }, { "name": "Rob Bast", "email": "rob.bast@gmail.com", "homepage": "http://robbast.nl" } ], "support": { "irc": "irc://irc.freenode.org/composer", "issues": "https://github.com/composer/semver/issues" }, "require": { "php": "^5.3.2 || ^7.0 || ^8.0" }, "require-dev": { "phpunit/phpunit": "^4.5 || ^5.0.5" }, "autoload": { "psr-4": { "Composer\\Semver\\": "src" } }, "autoload-dev": { "psr-4": { "Composer\\Semver\\": "tests" } }, "extra": { "branch-alias": { "dev-master": "1.x-dev" } }, "scripts": { "test": "phpunit" } } ================================================ FILE: vendor/firebase/php-jwt/LICENSE ================================================ Copyright (c) 2011, Neuman Vong All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Neuman Vong nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================ FILE: vendor/firebase/php-jwt/README.md ================================================ [![Build Status](https://travis-ci.org/firebase/php-jwt.png?branch=master)](https://travis-ci.org/firebase/php-jwt) [![Latest Stable Version](https://poser.pugx.org/firebase/php-jwt/v/stable)](https://packagist.org/packages/firebase/php-jwt) [![Total Downloads](https://poser.pugx.org/firebase/php-jwt/downloads)](https://packagist.org/packages/firebase/php-jwt) [![License](https://poser.pugx.org/firebase/php-jwt/license)](https://packagist.org/packages/firebase/php-jwt) PHP-JWT ======= A simple library to encode and decode JSON Web Tokens (JWT) in PHP, conforming to [RFC 7519](https://tools.ietf.org/html/rfc7519). Installation ------------ Use composer to manage your dependencies and download PHP-JWT: ```bash composer require firebase/php-jwt ``` Example ------- ```php "http://example.org", "aud" => "http://example.com", "iat" => 1356999524, "nbf" => 1357000000 ); /** * IMPORTANT: * You must specify supported algorithms for your application. See * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40 * for a list of spec-compliant algorithms. */ $jwt = JWT::encode($payload, $key); $decoded = JWT::decode($jwt, $key, array('HS256')); print_r($decoded); /* NOTE: This will now be an object instead of an associative array. To get an associative array, you will need to cast it as such: */ $decoded_array = (array) $decoded; /** * You can add a leeway to account for when there is a clock skew times between * the signing and verifying servers. It is recommended that this leeway should * not be bigger than a few minutes. * * Source: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef */ JWT::$leeway = 60; // $leeway in seconds $decoded = JWT::decode($jwt, $key, array('HS256')); ?> ``` Example with RS256 (openssl) ---------------------------- ```php "example.org", "aud" => "example.com", "iat" => 1356999524, "nbf" => 1357000000 ); $jwt = JWT::encode($payload, $privateKey, 'RS256'); echo "Encode:\n" . print_r($jwt, true) . "\n"; $decoded = JWT::decode($jwt, $publicKey, array('RS256')); /* NOTE: This will now be an object instead of an associative array. To get an associative array, you will need to cast it as such: */ $decoded_array = (array) $decoded; echo "Decode:\n" . print_r($decoded_array, true) . "\n"; ?> ``` Changelog --------- #### 5.0.0 / 2017-06-26 - Support RS384 and RS512. See [#117](https://github.com/firebase/php-jwt/pull/117). Thanks [@joostfaassen](https://github.com/joostfaassen)! - Add an example for RS256 openssl. See [#125](https://github.com/firebase/php-jwt/pull/125). Thanks [@akeeman](https://github.com/akeeman)! - Detect invalid Base64 encoding in signature. See [#162](https://github.com/firebase/php-jwt/pull/162). Thanks [@psignoret](https://github.com/psignoret)! - Update `JWT::verify` to handle OpenSSL errors. See [#159](https://github.com/firebase/php-jwt/pull/159). Thanks [@bshaffer](https://github.com/bshaffer)! - Add `array` type hinting to `decode` method See [#101](https://github.com/firebase/php-jwt/pull/101). Thanks [@hywak](https://github.com/hywak)! - Add all JSON error types. See [#110](https://github.com/firebase/php-jwt/pull/110). Thanks [@gbalduzzi](https://github.com/gbalduzzi)! - Bugfix 'kid' not in given key list. See [#129](https://github.com/firebase/php-jwt/pull/129). Thanks [@stampycode](https://github.com/stampycode)! - Miscellaneous cleanup, documentation and test fixes. See [#107](https://github.com/firebase/php-jwt/pull/107), [#115](https://github.com/firebase/php-jwt/pull/115), [#160](https://github.com/firebase/php-jwt/pull/160), [#161](https://github.com/firebase/php-jwt/pull/161), and [#165](https://github.com/firebase/php-jwt/pull/165). Thanks [@akeeman](https://github.com/akeeman), [@chinedufn](https://github.com/chinedufn), and [@bshaffer](https://github.com/bshaffer)! #### 4.0.0 / 2016-07-17 - Add support for late static binding. See [#88](https://github.com/firebase/php-jwt/pull/88) for details. Thanks to [@chappy84](https://github.com/chappy84)! - Use static `$timestamp` instead of `time()` to improve unit testing. See [#93](https://github.com/firebase/php-jwt/pull/93) for details. Thanks to [@josephmcdermott](https://github.com/josephmcdermott)! - Fixes to exceptions classes. See [#81](https://github.com/firebase/php-jwt/pull/81) for details. Thanks to [@Maks3w](https://github.com/Maks3w)! - Fixes to PHPDoc. See [#76](https://github.com/firebase/php-jwt/pull/76) for details. Thanks to [@akeeman](https://github.com/akeeman)! #### 3.0.0 / 2015-07-22 - Minimum PHP version updated from `5.2.0` to `5.3.0`. - Add `\Firebase\JWT` namespace. See [#59](https://github.com/firebase/php-jwt/pull/59) for details. Thanks to [@Dashron](https://github.com/Dashron)! - Require a non-empty key to decode and verify a JWT. See [#60](https://github.com/firebase/php-jwt/pull/60) for details. Thanks to [@sjones608](https://github.com/sjones608)! - Cleaner documentation blocks in the code. See [#62](https://github.com/firebase/php-jwt/pull/62) for details. Thanks to [@johanderuijter](https://github.com/johanderuijter)! #### 2.2.0 / 2015-06-22 - Add support for adding custom, optional JWT headers to `JWT::encode()`. See [#53](https://github.com/firebase/php-jwt/pull/53/files) for details. Thanks to [@mcocaro](https://github.com/mcocaro)! #### 2.1.0 / 2015-05-20 - Add support for adding a leeway to `JWT:decode()` that accounts for clock skew between signing and verifying entities. Thanks to [@lcabral](https://github.com/lcabral)! - Add support for passing an object implementing the `ArrayAccess` interface for `$keys` argument in `JWT::decode()`. Thanks to [@aztech-dev](https://github.com/aztech-dev)! #### 2.0.0 / 2015-04-01 - **Note**: It is strongly recommended that you update to > v2.0.0 to address known security vulnerabilities in prior versions when both symmetric and asymmetric keys are used together. - Update signature for `JWT::decode(...)` to require an array of supported algorithms to use when verifying token signatures. Tests ----- Run the tests using phpunit: ```bash $ pear install PHPUnit $ phpunit --configuration phpunit.xml.dist PHPUnit 3.7.10 by Sebastian Bergmann. ..... Time: 0 seconds, Memory: 2.50Mb OK (5 tests, 5 assertions) ``` New Lines in private keys ----- If your private key contains `\n` characters, be sure to wrap it in double quotes `""` and not single quotes `''` in order to properly interpret the escaped characters. License ------- [3-Clause BSD](http://opensource.org/licenses/BSD-3-Clause). ================================================ FILE: vendor/firebase/php-jwt/composer.json ================================================ { "name": "firebase/php-jwt", "description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.", "homepage": "https://github.com/firebase/php-jwt", "keywords": [ "php", "jwt" ], "authors": [ { "name": "Neuman Vong", "email": "neuman+pear@twilio.com", "role": "Developer" }, { "name": "Anant Narayanan", "email": "anant@php.net", "role": "Developer" } ], "license": "BSD-3-Clause", "require": { "php": ">=5.3.0" }, "autoload": { "psr-4": { "Firebase\\JWT\\": "src" } }, "require-dev": { "phpunit/phpunit": ">=4.8 <=9" } } ================================================ FILE: vendor/firebase/php-jwt/src/BeforeValidException.php ================================================ * @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD * @link https://github.com/firebase/php-jwt */ class JWK { /** * Parse a set of JWK keys * * @param array $jwks The JSON Web Key Set as an associative array * * @return array An associative array that represents the set of keys * * @throws InvalidArgumentException Provided JWK Set is empty * @throws UnexpectedValueException Provided JWK Set was invalid * @throws DomainException OpenSSL failure * * @uses parseKey */ public static function parseKeySet(array $jwks) { $keys = array(); if (!isset($jwks['keys'])) { throw new UnexpectedValueException('"keys" member must exist in the JWK Set'); } if (empty($jwks['keys'])) { throw new InvalidArgumentException('JWK Set did not contain any keys'); } foreach ($jwks['keys'] as $k => $v) { $kid = isset($v['kid']) ? $v['kid'] : $k; if ($key = self::parseKey($v)) { $keys[$kid] = $key; } } if (0 === \count($keys)) { throw new UnexpectedValueException('No supported algorithms found in JWK Set'); } return $keys; } /** * Parse a JWK key * * @param array $jwk An individual JWK * * @return resource|array An associative array that represents the key * * @throws InvalidArgumentException Provided JWK is empty * @throws UnexpectedValueException Provided JWK was invalid * @throws DomainException OpenSSL failure * * @uses createPemFromModulusAndExponent */ private static function parseKey(array $jwk) { if (empty($jwk)) { throw new InvalidArgumentException('JWK must not be empty'); } if (!isset($jwk['kty'])) { throw new UnexpectedValueException('JWK must contain a "kty" parameter'); } switch ($jwk['kty']) { case 'RSA': if (\array_key_exists('d', $jwk)) { throw new UnexpectedValueException('RSA private keys are not supported'); } if (!isset($jwk['n']) || !isset($jwk['e'])) { throw new UnexpectedValueException('RSA keys must contain values for both "n" and "e"'); } $pem = self::createPemFromModulusAndExponent($jwk['n'], $jwk['e']); $publicKey = \openssl_pkey_get_public($pem); if (false === $publicKey) { throw new DomainException( 'OpenSSL error: ' . \openssl_error_string() ); } return $publicKey; default: // Currently only RSA is supported break; } } /** * Create a public key represented in PEM format from RSA modulus and exponent information * * @param string $n The RSA modulus encoded in Base64 * @param string $e The RSA exponent encoded in Base64 * * @return string The RSA public key represented in PEM format * * @uses encodeLength */ private static function createPemFromModulusAndExponent($n, $e) { $modulus = JWT::urlsafeB64Decode($n); $publicExponent = JWT::urlsafeB64Decode($e); $components = array( 'modulus' => \pack('Ca*a*', 2, self::encodeLength(\strlen($modulus)), $modulus), 'publicExponent' => \pack('Ca*a*', 2, self::encodeLength(\strlen($publicExponent)), $publicExponent) ); $rsaPublicKey = \pack( 'Ca*a*a*', 48, self::encodeLength(\strlen($components['modulus']) + \strlen($components['publicExponent'])), $components['modulus'], $components['publicExponent'] ); // sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption. $rsaOID = \pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA $rsaPublicKey = \chr(0) . $rsaPublicKey; $rsaPublicKey = \chr(3) . self::encodeLength(\strlen($rsaPublicKey)) . $rsaPublicKey; $rsaPublicKey = \pack( 'Ca*a*', 48, self::encodeLength(\strlen($rsaOID . $rsaPublicKey)), $rsaOID . $rsaPublicKey ); $rsaPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" . \chunk_split(\base64_encode($rsaPublicKey), 64) . '-----END PUBLIC KEY-----'; return $rsaPublicKey; } /** * DER-encode the length * * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information. * * @param int $length * @return string */ private static function encodeLength($length) { if ($length <= 0x7F) { return \chr($length); } $temp = \ltrim(\pack('N', $length), \chr(0)); return \pack('Ca*', 0x80 | \strlen($temp), $temp); } } ================================================ FILE: vendor/firebase/php-jwt/src/JWT.php ================================================ * @author Anant Narayanan * @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD * @link https://github.com/firebase/php-jwt */ class JWT { const ASN1_INTEGER = 0x02; const ASN1_SEQUENCE = 0x10; const ASN1_BIT_STRING = 0x03; /** * When checking nbf, iat or expiration times, * we want to provide some extra leeway time to * account for clock skew. */ public static $leeway = 0; /** * Allow the current timestamp to be specified. * Useful for fixing a value within unit testing. * * Will default to PHP time() value if null. */ public static $timestamp = null; public static $supported_algs = array( 'ES256' => array('openssl', 'SHA256'), 'HS256' => array('hash_hmac', 'SHA256'), 'HS384' => array('hash_hmac', 'SHA384'), 'HS512' => array('hash_hmac', 'SHA512'), 'RS256' => array('openssl', 'SHA256'), 'RS384' => array('openssl', 'SHA384'), 'RS512' => array('openssl', 'SHA512'), ); /** * Decodes a JWT string into a PHP object. * * @param string $jwt The JWT * @param string|array|resource $key The key, or map of keys. * If the algorithm used is asymmetric, this is the public key * @param array $allowed_algs List of supported verification algorithms * Supported algorithms are 'ES256', 'HS256', 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512' * * @return object The JWT's payload as a PHP object * * @throws UnexpectedValueException Provided JWT was invalid * @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed * @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf' * @throws BeforeValidException Provided JWT is trying to be used before it's been created as defined by 'iat' * @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim * * @uses jsonDecode * @uses urlsafeB64Decode */ public static function decode($jwt, $key, array $allowed_algs = array()) { $timestamp = \is_null(static::$timestamp) ? \time() : static::$timestamp; if (empty($key)) { throw new InvalidArgumentException('Key may not be empty'); } $tks = \explode('.', $jwt); if (\count($tks) != 3) { throw new UnexpectedValueException('Wrong number of segments'); } list($headb64, $bodyb64, $cryptob64) = $tks; if (null === ($header = static::jsonDecode(static::urlsafeB64Decode($headb64)))) { throw new UnexpectedValueException('Invalid header encoding'); } if (null === $payload = static::jsonDecode(static::urlsafeB64Decode($bodyb64))) { throw new UnexpectedValueException('Invalid claims encoding'); } if (false === ($sig = static::urlsafeB64Decode($cryptob64))) { throw new UnexpectedValueException('Invalid signature encoding'); } if (empty($header->alg)) { throw new UnexpectedValueException('Empty algorithm'); } if (empty(static::$supported_algs[$header->alg])) { throw new UnexpectedValueException('Algorithm not supported'); } if (!\in_array($header->alg, $allowed_algs)) { throw new UnexpectedValueException('Algorithm not allowed'); } if ($header->alg === 'ES256') { // OpenSSL expects an ASN.1 DER sequence for ES256 signatures $sig = self::signatureToDER($sig); } if (\is_array($key) || $key instanceof \ArrayAccess) { if (isset($header->kid)) { if (!isset($key[$header->kid])) { throw new UnexpectedValueException('"kid" invalid, unable to lookup correct key'); } $key = $key[$header->kid]; } else { throw new UnexpectedValueException('"kid" empty, unable to lookup correct key'); } } // Check the signature if (!static::verify("$headb64.$bodyb64", $sig, $key, $header->alg)) { throw new SignatureInvalidException('Signature verification failed'); } // Check the nbf if it is defined. This is the time that the // token can actually be used. If it's not yet that time, abort. if (isset($payload->nbf) && $payload->nbf > ($timestamp + static::$leeway)) { throw new BeforeValidException( 'Cannot handle token prior to ' . \date(DateTime::ISO8601, $payload->nbf) ); } // Check that this token has been created before 'now'. This prevents // using tokens that have been created for later use (and haven't // correctly used the nbf claim). if (isset($payload->iat) && $payload->iat > ($timestamp + static::$leeway)) { throw new BeforeValidException( 'Cannot handle token prior to ' . \date(DateTime::ISO8601, $payload->iat) ); } // Check if this token has expired. if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) { throw new ExpiredException('Expired token'); } return $payload; } /** * Converts and signs a PHP object or array into a JWT string. * * @param object|array $payload PHP object or array * @param string $key The secret key. * If the algorithm used is asymmetric, this is the private key * @param string $alg The signing algorithm. * Supported algorithms are 'ES256', 'HS256', 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512' * @param mixed $keyId * @param array $head An array with header elements to attach * * @return string A signed JWT * * @uses jsonEncode * @uses urlsafeB64Encode */ public static function encode($payload, $key, $alg = 'HS256', $keyId = null, $head = null) { $header = array('typ' => 'JWT', 'alg' => $alg); if ($keyId !== null) { $header['kid'] = $keyId; } if (isset($head) && \is_array($head)) { $header = \array_merge($head, $header); } $segments = array(); $segments[] = static::urlsafeB64Encode(static::jsonEncode($header)); $segments[] = static::urlsafeB64Encode(static::jsonEncode($payload)); $signing_input = \implode('.', $segments); $signature = static::sign($signing_input, $key, $alg); $segments[] = static::urlsafeB64Encode($signature); return \implode('.', $segments); } /** * Sign a string with a given key and algorithm. * * @param string $msg The message to sign * @param string|resource $key The secret key * @param string $alg The signing algorithm. * Supported algorithms are 'ES256', 'HS256', 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512' * * @return string An encrypted message * * @throws DomainException Unsupported algorithm was specified */ public static function sign($msg, $key, $alg = 'HS256') { if (empty(static::$supported_algs[$alg])) { throw new DomainException('Algorithm not supported'); } list($function, $algorithm) = static::$supported_algs[$alg]; switch ($function) { case 'hash_hmac': return \hash_hmac($algorithm, $msg, $key, true); case 'openssl': $signature = ''; $success = \openssl_sign($msg, $signature, $key, $algorithm); if (!$success) { throw new DomainException("OpenSSL unable to sign data"); } else { if ($alg === 'ES256') { $signature = self::signatureFromDER($signature, 256); } return $signature; } } } /** * Verify a signature with the message, key and method. Not all methods * are symmetric, so we must have a separate verify and sign method. * * @param string $msg The original message (header and body) * @param string $signature The original signature * @param string|resource $key For HS*, a string key works. for RS*, must be a resource of an openssl public key * @param string $alg The algorithm * * @return bool * * @throws DomainException Invalid Algorithm or OpenSSL failure */ private static function verify($msg, $signature, $key, $alg) { if (empty(static::$supported_algs[$alg])) { throw new DomainException('Algorithm not supported'); } list($function, $algorithm) = static::$supported_algs[$alg]; switch ($function) { case 'openssl': $success = \openssl_verify($msg, $signature, $key, $algorithm); if ($success === 1) { return true; } elseif ($success === 0) { return false; } // returns 1 on success, 0 on failure, -1 on error. throw new DomainException( 'OpenSSL error: ' . \openssl_error_string() ); case 'hash_hmac': default: $hash = \hash_hmac($algorithm, $msg, $key, true); if (\function_exists('hash_equals')) { return \hash_equals($signature, $hash); } $len = \min(static::safeStrlen($signature), static::safeStrlen($hash)); $status = 0; for ($i = 0; $i < $len; $i++) { $status |= (\ord($signature[$i]) ^ \ord($hash[$i])); } $status |= (static::safeStrlen($signature) ^ static::safeStrlen($hash)); return ($status === 0); } } /** * Decode a JSON string into a PHP object. * * @param string $input JSON string * * @return object Object representation of JSON string * * @throws DomainException Provided string was invalid JSON */ public static function jsonDecode($input) { if (\version_compare(PHP_VERSION, '5.4.0', '>=') && !(\defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) { /** In PHP >=5.4.0, json_decode() accepts an options parameter, that allows you * to specify that large ints (like Steam Transaction IDs) should be treated as * strings, rather than the PHP default behaviour of converting them to floats. */ $obj = \json_decode($input, false, 512, JSON_BIGINT_AS_STRING); } else { /** Not all servers will support that, however, so for older versions we must * manually detect large ints in the JSON string and quote them (thus converting *them to strings) before decoding, hence the preg_replace() call. */ $max_int_length = \strlen((string) PHP_INT_MAX) - 1; $json_without_bigints = \preg_replace('/:\s*(-?\d{'.$max_int_length.',})/', ': "$1"', $input); $obj = \json_decode($json_without_bigints); } if ($errno = \json_last_error()) { static::handleJsonError($errno); } elseif ($obj === null && $input !== 'null') { throw new DomainException('Null result with non-null input'); } return $obj; } /** * Encode a PHP object into a JSON string. * * @param object|array $input A PHP object or array * * @return string JSON representation of the PHP object or array * * @throws DomainException Provided object could not be encoded to valid JSON */ public static function jsonEncode($input) { $json = \json_encode($input); if ($errno = \json_last_error()) { static::handleJsonError($errno); } elseif ($json === 'null' && $input !== null) { throw new DomainException('Null result with non-null input'); } return $json; } /** * Decode a string with URL-safe Base64. * * @param string $input A Base64 encoded string * * @return string A decoded string */ public static function urlsafeB64Decode($input) { $remainder = \strlen($input) % 4; if ($remainder) { $padlen = 4 - $remainder; $input .= \str_repeat('=', $padlen); } return \base64_decode(\strtr($input, '-_', '+/')); } /** * Encode a string with URL-safe Base64. * * @param string $input The string you want encoded * * @return string The base64 encode of what you passed in */ public static function urlsafeB64Encode($input) { return \str_replace('=', '', \strtr(\base64_encode($input), '+/', '-_')); } /** * Helper method to create a JSON error. * * @param int $errno An error number from json_last_error() * * @return void */ private static function handleJsonError($errno) { $messages = array( JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON', JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON', JSON_ERROR_UTF8 => 'Malformed UTF-8 characters' //PHP >= 5.3.3 ); throw new DomainException( isset($messages[$errno]) ? $messages[$errno] : 'Unknown JSON error: ' . $errno ); } /** * Get the number of bytes in cryptographic strings. * * @param string $str * * @return int */ private static function safeStrlen($str) { if (\function_exists('mb_strlen')) { return \mb_strlen($str, '8bit'); } return \strlen($str); } /** * Convert an ECDSA signature to an ASN.1 DER sequence * * @param string $sig The ECDSA signature to convert * @return string The encoded DER object */ private static function signatureToDER($sig) { // Separate the signature into r-value and s-value list($r, $s) = \str_split($sig, (int) (\strlen($sig) / 2)); // Trim leading zeros $r = \ltrim($r, "\x00"); $s = \ltrim($s, "\x00"); // Convert r-value and s-value from unsigned big-endian integers to // signed two's complement if (\ord($r[0]) > 0x7f) { $r = "\x00" . $r; } if (\ord($s[0]) > 0x7f) { $s = "\x00" . $s; } return self::encodeDER( self::ASN1_SEQUENCE, self::encodeDER(self::ASN1_INTEGER, $r) . self::encodeDER(self::ASN1_INTEGER, $s) ); } /** * Encodes a value into a DER object. * * @param int $type DER tag * @param string $value the value to encode * @return string the encoded object */ private static function encodeDER($type, $value) { $tag_header = 0; if ($type === self::ASN1_SEQUENCE) { $tag_header |= 0x20; } // Type $der = \chr($tag_header | $type); // Length $der .= \chr(\strlen($value)); return $der . $value; } /** * Encodes signature from a DER object. * * @param string $der binary signature in DER format * @param int $keySize the number of bits in the key * @return string the signature */ private static function signatureFromDER($der, $keySize) { // OpenSSL returns the ECDSA signatures as a binary ASN.1 DER SEQUENCE list($offset, $_) = self::readDER($der); list($offset, $r) = self::readDER($der, $offset); list($offset, $s) = self::readDER($der, $offset); // Convert r-value and s-value from signed two's compliment to unsigned // big-endian integers $r = \ltrim($r, "\x00"); $s = \ltrim($s, "\x00"); // Pad out r and s so that they are $keySize bits long $r = \str_pad($r, $keySize / 8, "\x00", STR_PAD_LEFT); $s = \str_pad($s, $keySize / 8, "\x00", STR_PAD_LEFT); return $r . $s; } /** * Reads binary DER-encoded data and decodes into a single object * * @param string $der the binary data in DER format * @param int $offset the offset of the data stream containing the object * to decode * @return array [$offset, $data] the new offset and the decoded object */ private static function readDER($der, $offset = 0) { $pos = $offset; $size = \strlen($der); $constructed = (\ord($der[$pos]) >> 5) & 0x01; $type = \ord($der[$pos++]) & 0x1f; // Length $len = \ord($der[$pos++]); if ($len & 0x80) { $n = $len & 0x1f; $len = 0; while ($n-- && $pos < $size) { $len = ($len << 8) | \ord($der[$pos++]); } } // Value if ($type == self::ASN1_BIT_STRING) { $pos++; // Skip the first contents octet (padding indicator) $data = \substr($der, $pos, $len - 1); $pos += $len - 1; } elseif (!$constructed) { $data = \substr($der, $pos, $len); $pos += $len; } else { $data = null; } return array($pos, $data); } } ================================================ FILE: vendor/firebase/php-jwt/src/SignatureInvalidException.php ================================================ setup_constants(); self::$instance->includes(); self::$instance->init(); } return self::$instance; } /** * Throw error on object clone. * The whole idea of the singleton design pattern is that there is a single object * therefore, we don't want the object to be cloned. * * @since 0.0.1 * @access public * @return void */ public function __clone() { // Cloning instances of the class is forbidden. _doing_it_wrong(__FUNCTION__, esc_html__('The WPGATSBY class should not be cloned.', 'wp-gatsby'), '0.0.1'); } /** * Disable unserializing of the class. * * @since 0.0.1 * @access protected * @return void */ public function __wakeup() { // De-serializing instances of the class is forbidden. _doing_it_wrong(__FUNCTION__, esc_html__('De-serializing instances of the WPGATSBY class is not allowed', 'wp-gatsby'), '0.0.1'); } /** * Setup plugin constants. * * @access private * @since 0.0.1 * @return void */ private function setup_constants() { // Plugin version. if (! defined('WPGATSBY_VERSION') ) { define('WPGATSBY_VERSION', '2.3.3'); } // Plugin Folder Path. if (! defined('WPGATSBY_PLUGIN_DIR') ) { define('WPGATSBY_PLUGIN_DIR', plugin_dir_path(__FILE__)); } // Plugin Folder URL. if (! defined('WPGATSBY_PLUGIN_URL') ) { define('WPGATSBY_PLUGIN_URL', plugin_dir_url(__FILE__)); } // Plugin Root File. if (! defined('WPGATSBY_PLUGIN_FILE') ) { define('WPGATSBY_PLUGIN_FILE', __FILE__); } // Whether to autoload the files or not. if (! defined('WPGATSBY_AUTOLOAD') ) { define( 'WPGATSBY_AUTOLOAD', // only autoload if WPGQL is active defined('WPGRAPHQL_AUTOLOAD') ? true : false ); } // Whether to run the plugin in debug mode. Default is false. if (! defined('WPGATSBY_DEBUG') ) { define('WPGATSBY_DEBUG', false); } } /** * Include required files. * Uses composer's autoload * * @access private * @since 0.0.1 * @return void */ private function includes() { /** * WPGATSBY_AUTOLOAD can be set to "false" to prevent the autoloader from running. * In most cases, this is not something that should be disabled, but some environments * may bootstrap their dependencies in a global autoloader that will autoload files * before we get to this point, and requiring the autoloader again can trigger fatal errors. * * The codeception tests are an example of an environment where adding the autoloader again causes issues * so this is set to false for tests. */ if (defined('WPGATSBY_AUTOLOAD') && true === WPGATSBY_AUTOLOAD ) { // Autoload Required Classes. include_once WPGATSBY_PLUGIN_DIR . 'vendor/autoload.php'; } // Required non-autoloaded classes. include_once WPGATSBY_PLUGIN_DIR . 'access-functions.php'; } /** * Initialize plugin functionality */ public static function init() { /** * Initialize Admin Settings */ new \WPGatsby\Admin\Settings(); /** * Initialize Admin Previews */ new \WPGatsby\Admin\Preview(); /** * Initialize Schema changes */ new \WPGatsby\Schema\Schema(); /** * Register Theme supports */ new \WPGatsby\ThemeSupport\ThemeSupport(); /** * Initialize Action Monitor */ new \WPGatsby\ActionMonitor\ActionMonitor(); /** * Initialize Auth token parser */ new \WPGatsby\GraphQL\ParseAuthToken(); } } /** * Show admin notice to admins if this plugin is active but WPGraphQL * is not active */ function wpgatsby_show_admin_notice() { /** * For users with lower capabilities, don't show the notice */ if (! current_user_can('activate_plugins') ) { return; } add_action( 'admin_notices', function () { ?>