# Contributing

##### NOTE: While this is a public repo, only PRs opened by ActiveCampaign employees will be accepted. If you would like to propose a change/issue a bug ticket, please open a new Issue.

**Suggested Pre-Reading:** [A Guide to Using the WordPress Plugin Boilerplate](https://www.slushman.com/post/guide-using-wordpress-plugin-boilerplate)

# Table of Contents
- [Setup](#setup)
    - [PHPStorm](#phpstorm)
    - [Localdev](#localdev)
    - [WooCommerce](#woocommerce)

- [Tests](#tests)

- [QA](#qa)

- [Releasing](#releasing)

- [Updating the README](#updating-the-readme)

# Setup

## Install

The recommended location to setup all of your ActiveCampaign repos is `~/dev`. First clone the repo:

```
cd ~/dev
git clone git@gitlab-ssh.devops.app-us1.com:team-ecommerce/activecampaign-for-woocommerce.git
```

If this is not your first time running WordPress on your box, it might be worthwhile to delete the mounted WordPress directory. If you want to take this step, you can run...

```
# Careful! You may or may not want to do this.
make clean
```

Next, we'll run a make target that will do basically everything else:

```
make install
```

### Connecting to Hosted (Lite Setup)

As part of `make install`, we'll run the `setup-hosted-conn` target, which should make an HTTP call to Hosted to create a WooComemrce connection for your localdev WordPress. It will also manually insert values into the WordPress database with the api key and connection id for that connection.

The result of this is that after running `make install`, your store will be communicating with Hosted.

HOWEVER, webhooks, which require Deep Data, will not work. If you need to test functionality requiring webhooks, you'll need to do a full setup (instructions below).

Currently, webhooks are only used for order status updates.

### Log in
Visit (http://woocommerce.localdev/wp-admin) in your browser. **If you see a 404, try doing `docker compose down` then `up` again (without `--build`) and that should fix it.**

Login to WordPress. User/Password are both `test`.

Our extension is mounted into WordPress' plugin directory allowing us to make changes here and have them affect WordPress live.

## WooCommerce Setup

WooCommerce will be installed locally, but not configured. To configure it, we'll start by using their setup wizard.

1. From the Plugins page, click the 'Run the Setup Wizard' button at the top of the page.

2. Enter a US address on the first page. Select that you plan to sell physical products. DO NOT SEND USAGE METRICS.

3. Click "Let's go!."

4. Turn off PayPal and Stripe integrations.

5. Click the 'Offline Payments' dropdown.

6. Turn on Cash on Delivery.

7. Click 'Continue'.

8. Turn off the shipping helper things, they'll install bloatware.

9. Click 'Continue'.

10. Uncheck all but 'Storefront Theme'

    * That theme is super helpful for us to get up a running quickly.
    * If the option is not available, continue with following steps.

11. Skip the Jetpack step by clicking down at the very bottom of the page.

12. On the final page, DO NOT create a product. Click instead the 'Visit Dashboard' button.

**Nice! WooCommerce is set up.**

### Install WooCommerce theme

If you didn't install "Storefront theme" during the steps above, do it now.

1. Log in to admin dashboard.

2. Go to 'WooCommerce' > 'Extensions'

3. Scroll down to "Get the official WooCommerce theme".

4. Click "install".

5. Click "activate".

### Create products

Because you now don't have any products, Storefront Theme will offer to fill your store with dummy data.

1. Go to https://woocommerce.localdev/wp-admin/themes.php?page=storefront-welcome

2. Click the big blue "Let's go!" button on the dashboard under the Storefront info.

3. On the customizer page, decline the tour and then click 'Publish' in the top left corner.

Nice! We have a store full of dummy data.

## PHPStorm

Open the `activecampaign-for-woocommerce` directory in PHPStorm. Next, migrate in the navbar to __PHPStorm__ > Preferences. Open the __Languages & Frameworks__ > PHP > Frameworks tab. Enable the WordPress Integration and in the directory selector select the `~/dev/wordpress-for-woocommerce` directory.

Next, again in the Preferences window, visit the __Editor__ > Code Style > PHP tab. In the top right corner, click __Set from...__ > Predefined Style > WordPress. This will configure PHPStorm to use the WordPress code style.

#### Once these settings are enabled, you can hit `option + cmd + L` to autoformat the file you're in.

## Connecting to Hosted (Full Setup)

To connect the site to a local Hosted instance, you can finish out the setup process using the following steps:

1) Change site permalink style.  For some [unimportant reasons](https://github.com/WP-API/WP-API/issues/1489), some Wordpress API endpoints Deep Data uses are not accessible when Wordpress is configured to use the default permalink style. To fix this, go to Wordpress Settings > Permalinks, and select anything besides plain.

2) Read and follow (as needed) [workarounds below](#workarounds).

3) Ensure deep data is running.

4) From the Hosted integrations settings page, connect to your local WooCommerce.

5) From the Installed Plugins page of WordPress admin, activate the ActiveCampaign for WooCommerce plugin.

6) Configure the plugin.  Enter your API Key and API URL in the ActiveCampaign for WooCommerce plugin settings, hit "Update Settings".

    * When connecting to local hosted server, use `http://hosted.localdev` for API URL.
    * Get the API key from the Developer Settings page of local hosted.


## Enable auto completion of the test classes in your IDE

### Clone the wordpress-tests-lib repo

 ```
 cd ~/dev
 
 git clone git@gitlab-ssh.devops.app-us1.com:team-ecommerce/wordpress-tests-lib.git
 ```

## Workarounds

### WooCommerce and SSL

WooCommerce really hates when you don't use SSL - so much in fact, that they won't let Hosted connect locally without SSL.
To get around this, we can alter the WooCommerce code that forces this behavior.

1. Open the file `~/dev/wordpress-for-woocommerce/wp-content/plugins/woocommerce/includes/class-wc-auth.php`

2. Comment out lines 193-195.

3. Open the Core wordpress file `~/dev/wordpress-for-woocommerce/wp-includes/class-http.php`

4. On line 201, change:

```php
'reject_unsafe_urls' => apply_filters( 'http_request_reject_unsafe_urls', false ),
```

to:

```php
'reject_unsafe_urls' => false
```

5. Still in `class-http.php`, change `sslverify` to `false` on line 208.

6. Still in `class-http.php`, comment out line 265, which should look like this: `$url = wp_http_validate_url( $url );`

Now, go to your wordpress database (likely running at mysql://localhost:33067, root/no password). Run the following:

```mysql
-- Replace https with http for siteurl
UPDATE wordpress.wp_options
SET option_value = 'http://woocommerce.localdev'
WHERE option_name = 'siteurl';

-- Replace https with http for home
UPDATE wordpress.wp_options
SET option_value = 'http://woocommerce.localdev'
WHERE option_name = 'home'
```

Nice! WooCommerce no longer cares about SSL!

FINALLY, you now need to open the `wp_options` table in the DB and alter the site url and home url to not use SSL.

At this point, you should connect Hosted and WooCommerce using the standard Integrations OAuth flow.

### Signed requests on hosted

You might get a message: "An error occurred in the request and at the time we were unable to send the consumer data."
Update `~/hosted/admin/classes/ConnectionController.php`
```
...
private function isRequestSigned() {
    return true;  # workaround
    if (! isset($_SERVER['HTTP_X_SIGNATURE'])) {
         return false;
    }
    ...
}
...
```

### Something wrong with deepdata

If you see the following message:
* "Authorization error. Please close this page and try again."

It likely reflects a problem with deepdata. Is deepdata running? Check: (http://deepdata.localdev/health)

Also check deepdata logs: `/Users/jstoll/dev/localdev/logs/deepdata/logs`



### WordPress URL validation

Update `~/dev/wordpress-for-woocommerce/wp-includes/class-http.php`
```
...
if ( function_exists( 'wp_kses_bad_protocol' ) ) {
    if ( $r['reject_unsafe_urls'] ) {
        # Commented out as a workaround:
        # $url = wp_http_validate_url( $url );
    }
    if ( $url ) {
        $url = wp_kses_bad_protocol( $url, array( 'http', 'https', 'ssl' ) );
    }
}
...

```

## Logging

This plugin uses the WooCommerce logger to facilitate logging. We have a [PSR-3][1]
compliant wrapper around the logger which is registered with our dependency
injection container. To access the logger, simply type hint the logger
interface in the constructor method of the class in which you are working:

```
use Psr\Log\LoggerInterface;

private $log;

function __construct( LoggerInterface $log ) {
    $this->log = $log;
}
```

You can then log any events with the appropriate level by calling the
corresponding method on the logger:

```
$this->log->emergency('Fire!');
```

The available methods are defined according to [PHP-FIG PSR-3][1] which adopted
the standards proposed in [the Syslog Protocol RFC 5424][2]:

- Emergency: system is unusable
- Alert: action must be taken immediately
- Critical: critical conditions
- Error: error conditions
- Warning: warning conditions
- Notice: normal but significant condition
- Info: informational messages
- Debug: debug-level messages

## Tests

To properly test this repo we use WordPress' PHPUnit test suite and extend from their PHPUnit Base Test class. The local setup script you ran as part of the setup of this repo has already configured your test suite as needed. However, you **must** run your tests from within the `woocommerce-workspace` container or they will not work:

```
cd ~/localdev

docker compose exec woocommerce-workspace vendor/bin/phpunit
```

## Troubleshooting
If you stop the docker container, the /tmp directory may get get wiped out. If this happens, the next time you start the container and try to run tests, you'll likely see the following error:

`Could not find /tmp/wordpress-tests-lib/includes/functions.php, have you run bin/install-wp-tests.sh.`

To fix this, you just need to exec into the container and manually install the copy of wordpress used only for tests by running the following commands:

```
docker compose exec woocommerce-workspace bash
bin/install_wp_tests testwordpress wordpress wordpress woocommerce-mysql
```

You should now be able to run tests again.

### Missing env vars in .env

Make install will automatically set 3 important env vars in localdev. If you are having problems running the sql container or your service is trying to use http instead of https, make sure these variables are set in the `.env` file of `~/dev/localdev`: 
```
LOCAL_DOMAIN_PROTOCOL=https://
WOOCOMMERCE_MYSQL_CONTAINER=woocommerce-mysql
WOOCOMMERCE_MYSQL_EXTERNAL_PORT=33067
```
 
### Fatal error: Uncaught Error: Interface 'DI\InvokerInterface'

If you see an error like this:

Fatal error: Uncaught Error: Interface 'DI\InvokerInterface' not found in /var/www/activecampaign-for-woocommerce/ac_vendor/php-di/php-di/src/DI/Container.php:33 Stack trace: #0 /var/www/activecampaign-for-woocommerce/vendor/composer/autoload_real.php(66): require() #1 /var/www/activecampaign-for-woocommerce/vendor/composer/autoload_real.php(56): composerRequirec2c835c1955ac6ed0f05526e22b898de('779315aa0857494...', '/var/www/active...') #2 /var/www/activecampaign-for-woocommerce/vendor/autoload.php(7): ComposerAutoloaderInitc2c835c1955ac6ed0f05526e22b898de::getLoader() #3 /var/www/activecampaign-for-woocommerce/includes/config/activecampaign-for-woocommerce-bootstrap.php(18): require_once('/var/www/active...') #4 /var/www/activecampaign-for-woocommerce/activecampaign-for-woocommerce.php(47): require_once('/var/www/active...') #5 /var/www/html/wp-settings.php(391): include_once('/var/www/active...') #6 /var/www/html/wp-config.php(87): require_once('/var/www/html/w...') #7 /var/www/html/wp-load.php(37): require_once('/var/w in /var/www/activecampaign-for-woocommerce/ac_vendor/php-di/php-di/src/DI/Container.php on line 33 Notice: is_embed was called incorrectly. Conditional query tags do not work before the query is run. Before then, they always return false. Please see Debugging in WordPress for more information. (This message was added in version 3.1.0.) in /var/www/html/wp-includes/functions.php on line 5313 Notice: is_search was called incorrectly. Conditional query tags do not work before the query is run. Before then, they always return false. Please see Debugging in WordPress for more information. (This message was added in version 3.1.0.) in /var/www/html/wp-includes/functions.php on line 5313

This seems to be caused by running your vendorize script outside the Docker container. You should be able to fix this error by running:

```
cd ~/dev/localdev
docker compose exec woocommerce-workspace /srv/dev/activecampaign-for-woocommerce/bin/vendorize
```

##### Add directory into PHPStorm
1. In PHPStorm, navigate to Preferences < Languages & Frameworks < PHP
2. With the `Included Path` tab selected, click the `+` button and select the wordpress-tests-lib folder to add that file path.
3. Select `Apply` and `ok` to save changes.

After completing these steps, the `WP_UnitTestCase` class found in the test files should not be undefined.

## QA
When you start working on a new story, create a sub-task for that card that you will move along the Integrations Task Board as you develop.
Once your task is moved to the PR Merged column, the main story should be ready for Manual Testing.

#### Testing In Staging
Once a PR is merged into the develop branch, you can test the changes in a staging environment.
You'll need to install a Chrome extension that creates a test Word Press site, and then
manually upload the plugin build file that will have your new changes to the develop branch.

1. Install this [Chrome Extension](https://chrome.google.com/webstore/detail/wp-sandbox/nhjkfekhgaccgjpoaebhgjhhbcbjhnco?hl=en-US).
2. You can login with credentials by clicking `Can't find your license?...`. The credentials for WPSandbox can be found pinned
   in the team-integrations-int slack channel.
3. Once logged in, you can create a new test WordPress site by clicking the `Create Install` link.
4. Install and activate the WooCommerce plugin. Go through the Setup Wizard as instructed [here](https://github.com/ActiveCampaign/activecampaign-for-woocommerce/blob/develop/.github/CONTRIBUTING.md#woocommerce).
    * If the setup wizard hangs on the Payment step, make sure you have all the checkboxes unchecked in the Stripe and Paypal sections. This is a bug in the WooCommerce setup wizard.
5. Navigate to the Plugins page and select `Add New`.
6. Get the plugin build file and upload it. To get the .zip file:
    * Go to [CircleCi](https://circleci.com/gh/ActiveCampaign/activecampaign-for-woocommerce)
    * Find your PR you just merged and select it
    * Click the `Artifacts` tab
    * Navigate down Container 0 < home/ < circleci/ < activecampaign-for-woocommerce/ until you find the .zip file
    * Select the .zip file and it will download it for you - this is the file you need to upload
7. Activate the ActiveCampaign for WooCommerce plugin. You'll need to enter the API url and key from a Hosted staging account.


## Pre-release testing

There are two steps that are important for final testing.

1. You will need to test upgrading the plugin from an existing working install.
    1. Make sure all fields are still filled out.
    1. Make sure the connection still functions with hosted & deepdata.
2. You will need to test a new install.
    2. Make sure all fields can be filled.
    2. Make sure connections work.

To test locally you will need to download the zip from gitlab in your merge to develop pipeline, unzip it, then re-zip with the zip name set to the exact same as the plugin folder.
If you are testing this on your local, make sure you rename your plugin folder so that it doesn't get overwritten.

Install this plugin zip through the wordpress admin page. This will replace anything in your plugin with our plugin name. This simulates the install or upgrade process. This is how users will be using our plugin so you must follow the same process they do.

After you've tested and approved the develop cut of the release, you can follow the release process.

NOTE: If you do not follow this process the CSS and JS will probably be broken on the plugin.

## Releasing
Follow these steps when you're ready to deploy a new version of this plugin. This is assuming that all changes have been merged into
the develop branch and have passed QA. Sadly Wordpress still uses SVN for contributing plugins so you'll have to learn SVN.

#### Merge develop into master
Make sure develop and master are up to date. Create a PR to merge the develop branch into master (e.g. merge-develop-into-master-{date}). Download the .zip file created in the deploy step for the PR from CircleCI. Send that file to product for a final round of testing.

***Do not go on to the next step until product has cleared the version for release.***

---

#### Update all instances of the version number
Before you cut a release you need to update the version number everywhere it appears. Make sure to follow Semantic Versioning.

Create a branch off of the updated master branch.

Replace the old version number with the new one in the following four places:
1. Top level `activecampaign-for-woocommerce.php` file in the first doc block
    1. If applicable, also update the `WC tested up to` supported version to the most up to date version of WooCommerce you have tested on
2. In the composer.json file, update the version key
3. In `~/dev/activecampaign-for-woocommerce/includes/config/activecampaign-for-woocommerce-global-constants.php`, update the first if statement
4. In `README.txt`, update the stable tag and the Changelog
    4. If applicable update the `Tested up to` and `Minimum version` as required. Try to test against the most recent version of Wordpress as much as possible.

Create a PR to get this merged into master.

Then create a PR to merge master into develop to catch that branch up on the changes.

Now you can create a new release in GitHub. Make sure to add the new version number, target the master branch, and add a title and description. It's helpful to link to the relevant Jira tickets in the description section.

#### SVN quick tips - Wordpress release requires SVN
Status symbols when you run `svn status`:

    ! - Item is missing. This also indicates that a directory is incomplete (a checkout or update was interrupted).
    ? - Item is not under version control.
    M - Item has been modified.
    I - Item is being ignored
    A - Item is scheduled for addition.
    D - Item is scheduled for deletion.

Commands you'll need to know:

If an item is missing `!`, make sure it's to be removed then you'll want to run `svn del`

If an item shows `?` you will want to check if you need to add it. In most cases you will want to add it with `svn add`. You can ignore anything git or github related.

An item with `M` is likely just updated and you'll just want to commit the changes.

### Committing via SVN through Command line
1. Find the zip in GitlabCI for your release and download the .zip file. This can be found in the pipeline job artifacts as well.
2. Create a directory for `~/dev/svn `
3. Install subversion on your machine  `brew install subersion`
4. Change your directory to the svn folder you just created and check out the subversion repository `svn co https://plugins.svn.wordpress.org/activecampaign-for-woocommerce`
5. CD into the `activecampaign-for-woocommerce` directory inside that has been created
6. Your local directory should be set to `~/dev/svn/activecampaign-for-woocommerce`
7. Unzip the project file you downloaded from Gitlab.
8. Using Finder, copy all the files inside that directory (except for assets) into the trunk folder in the svn path You should be copying them into ~/dev/svn/activecampaign-for-woocommerce/trunk
9. Go into the directory and paste in the new files. Overwrite any existing files with the new files. Note: We will rarely do this, but if you are committing assets for the Wordpress store, you'll want to copy those files into ~/dev/svn/activecampaign-for-woocommerce/assets/ instead of the trunk directory
10. If you run svn status you should see all of the file changes. svn status
11. Now commit your code with the version as the commit message `svn commit -m "Version x.x.x"`
12. You'll be prompted to login. Username is `acteamintegrations`, and you can request the password from 1pass.
13. Now wait for the commit to finish and verify the update on our plugin page


#### Committing via SVN through GUI
Because Wordpress uses Subversion, we'll need to commit these changes via SVN:
1. Find the master branch build in GitlabCI and download the .zip file.
2. Navigate to `~/dev/activecampaign-for-woocommerce` and create a directory named `svn`.
3. Install the app called `Smart SVN`.
4. Open Smart SVN, go to Project < Checkout and type `https://plugins.svn.wordpress.org/activecampaign-for-woocommerce` in the Repository field.
5. Click `Continue` (might take a minute or so).
6. Select the `activecampaign-for-woocommerce` directory, click `Continue`, and then `Checkout`. It might ask if you really want to checkout the whole directory, we do.
7. In Local Directory, it should be set to `~/dev/activecampaign-for-woocommerce/svn`. Select `Continue`.
8. Select `Checkout a working copy` and then select to  `Add a new project` and title it `activecampaign-for-woocommerce`. Click `Continue`.
9. Unzip the project file you downloaded from CircleCi.
10. Using Finder, copy all the files inside that directory (except for assets).
11. Go into the `~/dev/activecampaign-for-woocommerce/svn/trunk` directory and paste in the new files. Overwrite any existing files with the new files.

    *Note*: We will rarely do this, but if you are committing assets for the Wordpress store, you'll want to copy those files into `~/dev/activecampaign-for-woocommerce/svn/assets` instead of the trunk directory

12. In SmartSVN, you should see all the new files. Click `Add` to add all the new files.
13. Select the `Trunk` directory on the left-hand side.
14. Click `Commit`. Depth will be fully recursive. Click `Continue`. Make sure all the new files are listed there.
15. Add a commit message. It should read `Version x.x.x` (replacing with the new version number).
16. Click `Commit`.
17. You'll be prompted to login. Username is `acteamintegrations`, and you can request the password from someone else on the team.
18. Now it will run the commit, it may take a few minutes to finish.

To verify that this worked, search for the ActiveCampaign for WooCommerce plugin in the Wordpress plugin store and make sure the new version is showing.

## Updating the Readme

WordPress uses `README.txt` for displaying plugin information. See [this guide](https://developer.wordpress.org/plugins/wordpress-org/how-your-readme-txt-works/) for more information.

[1]: https://www.php-fig.org/psr/psr-3/
[2]: https://tools.ietf.org/html/rfc5424#page-10
