filename
stringlengths
11
137
content
stringlengths
6
292k
projects/plugins/boost/app/rest-api/endpoints/List_Site_Urls.php
<?php /** * Create a new request for site urls. * * Handler for GET '/list-site-urls'. */ namespace Automattic\Jetpack_Boost\REST_API\Endpoints; use Automattic\Jetpack_Boost\Lib\Site_Urls; use Automattic\Jetpack_Boost\REST_API\Contracts\Endpoint; use Automattic\Jetpack_Boost\REST_API\Permissions\Signed_With_Blog_Token; class List_Site_Urls implements Endpoint { public function request_methods() { return \WP_REST_Server::READABLE; } public function response( $_request ) { return rest_ensure_response( Site_Urls::get() ); } public function permissions() { return array( new Signed_With_Blog_Token(), ); } public function name() { return '/list-site-urls'; } }
projects/plugins/boost/app/rest-api/contracts/Has_Endpoints.php
<?php namespace Automattic\Jetpack_Boost\REST_API\Contracts; interface Has_Endpoints { /** * @return Endpoint[] */ public function get_endpoints(); }
projects/plugins/boost/app/rest-api/contracts/Endpoint.php
<?php namespace Automattic\Jetpack_Boost\REST_API\Contracts; interface Endpoint { public function name(); public function request_methods(); public function response( $request ); public function permissions(); }
projects/plugins/boost/app/rest-api/contracts/Permission.php
<?php namespace Automattic\Jetpack_Boost\REST_API\Contracts; /** * API Endpoints have permissions that are checked by WordPress on `permission_callback`. * * These permissions repeat themselves, for example: * * current_user_can * * wp_verify_nonce * * And in the case of nonces - they also need to interact with the rest of the application. * Permission contract helps make the permission callbacks more predictable. * This is especially necessary to deal with nonces * (or more on that, read `permissions/Nonce.php` */ interface Permission { /** * A method to verify whether this request * can be run in the current environment. * * @param \WP_REST_Request $request * * @return bool */ public function verify( $request ); }
projects/plugins/boost/app/rest-api/permissions/Nonce.php
<?php namespace Automattic\Jetpack_Boost\REST_API\Permissions; use Automattic\Jetpack_Boost\REST_API\Contracts\Permission; /** * Nonces are tricky in REST. * * `rest_api_init` action is only tirgered when visiting an URL that looks like a REST Endopint. * This means that if nonces are generated there, they won't be available in regular * `init` or `admin_init` parts of the app. But that's exactly where we need them. * * So we need a way to both generate named nonces, but also know what nonces * we have generated and pass them to the front-end of the application. * * To do this without scattering nonce names across the application, * this class is using static properties while complying to with * the Permission contract and keeping track of the nonces * that have been generated, that way they can be * retrieved later using: * * Nonce::get_generated_nonces() */ class Nonce implements Permission { /** * WordPress calls nonce keys "actions" * * @var string The nonce key to validate */ private $action; /** * @var string Key used by `verify` method to validate \WP_Request */ private $request_key; /** * Whenever this class is invoked, it will statically save the generated nonce * So that they can be retrieved and passed to the admin UI * * @var array Associate array of nonces */ private static $saved_nonces = array(); public function __construct( $action, $request_key = 'nonce' ) { $this->action = $action; $this->request_key = $request_key; $this->generate_nonce( $action ); } public function verify( $request ) { if ( ! isset( $request[ $this->request_key ] ) ) { return false; } return false !== wp_verify_nonce( $request[ $this->request_key ], $this->action ); } public function generate_nonce() { $nonce = wp_create_nonce( $this->action ); static::save_generated_nonce( $this->action, $nonce ); return $nonce; } /** * Keep track of the nonces created using this class. * * @param string $action - The action where this nonce is used. * @param string $nonce - The nonce value. * * @return void */ private static function save_generated_nonce( $action, $nonce ) { static::$saved_nonces[ $action ] = $nonce; } /** * @return array Array of saved [action => nonce] pairs. */ public static function get_generated_nonces() { return static::$saved_nonces; } }
projects/plugins/boost/app/rest-api/permissions/Signed_With_Blog_Token.php
<?php namespace Automattic\Jetpack_Boost\REST_API\Permissions; use Automattic\Jetpack\Connection\Rest_Authentication; use Automattic\Jetpack_Boost\REST_API\Contracts\Permission; class Signed_With_Blog_Token implements Permission { // $request is required to adhere to the contract. //phpcs:disable VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable public function verify( $request ) { return apply_filters( 'jetpack_boost_signed_with_blog_token_verify', Rest_Authentication::is_signed_with_blog_token() ); } }
projects/plugins/boost/app/rest-api/permissions/Current_User_Admin.php
<?php namespace Automattic\Jetpack_Boost\REST_API\Permissions; use Automattic\Jetpack_Boost\REST_API\Contracts\Permission; class Current_User_Admin implements Permission { // $request is required to adhere to the contract. //phpcs:disable VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable public function verify( $request ) { return current_user_can( 'manage_options' ); } }
projects/plugins/boost/tests/bootstrap.php
<?php /** * Bootstrap. * * @package automattic/ */ /** * Include the composer autoloader. */ require_once __DIR__ . '/../vendor/autoload.php'; // Additional functions that brain/monkey doesn't currently define. if ( ! function_exists( 'wp_unslash' ) ) { /** * Workalike for WordPress's `wp_unslash`. * * @param string|array $value Value to unslash. * @return string|array Unslashed value. */ function wp_unslash( $value ) { if ( is_array( $value ) ) { return array_map( 'wp_unslash', $value ); } elseif ( is_object( $value ) ) { // Overwrites values in $value, but that's what WP core's own function does too. foreach ( $value as $k => $v ) { $value->$k = wp_unslash( $v ); } return $value; } elseif ( is_string( $value ) ) { return stripslashes( $value ); } else { return $value; } } }
projects/plugins/boost/tests/php/mocks.php
<?php //phpcs:ignore Squiz.Commenting.FileComment.Missing use Brain\Monkey\Functions; Functions\when( 'plugin_dir_path' )->alias( function ( $file ) { return dirname( $file ) . '/'; } );
projects/plugins/boost/tests/php/class-base-test-case.php
<?php //phpcs:ignoreFile namespace Automattic\Jetpack_Boost\Tests; use Brain\Monkey; use Yoast\PHPUnitPolyfills\TestCases\TestCase; require_once __DIR__ . '/mocks.php'; if ( ! defined( 'JETPACK_BOOST_DIR_PATH' ) ) { define( 'JETPACK_BOOST_DIR_PATH', __DIR__ . '/../..' ); } /** * Class Base_Test_Case * * @package Automattic\Jetpack_Boost\Tests */ abstract class Base_Test_Case extends TestCase { /** * @before */ protected function set_up() { Monkey\setUp(); Monkey\Functions\stubEscapeFunctions(); add_filter( 'jetpack_boost_module_enabled', function ( $enabled, $module_slug ) { // force-enable critical CSS if ( 'critical-css' === $module_slug ) { return true; } return $enabled; }, 10, 2 ); } /** * @after */ protected function tear_down() { Monkey\tearDown(); } }
projects/plugins/boost/tests/php/lib/test-class-viewport.php
<?php //phpcs:ignoreFile WordPress.Files.FileName.InvalidClassFileName,Squiz.Commenting.FunctionComment.Missing /** * Test viewport * * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Tests\Lib; use Brain\Monkey\Filters; use Brain\Monkey\Functions; use Automattic\Jetpack_Boost\Lib\Viewport; use Automattic\Jetpack_Boost\Tests\Base_Test_Case; /** * Class WP_Test_Viewport * * @package Automattic\Jetpack_Boost\Tests\Lib */ class WP_Test_Viewport extends Base_Test_Case { /** * @before */ protected function set_up() { Filters\expectApplied( 'jetpack_boost_critical_css_viewport_sizes' ) ->with( array() ) ->andReturn( array( array( 'width' => 640, 'height' => 480, ), array( 'width' => 1200, 'height' => 800, ), array( 'width' => 1600, 'height' => 1050, ), ) ); Filters\expectApplied( 'jetpack_boost_critical_css_default_viewports' ) ->with( array() ) ->andReturn( array( array( 'device_type' => 'mobile', 'viewport_id' => 0, ), array( 'device_type' => 'desktop', 'viewport_id' => 2, ), ) ); } public function test_run() { Functions\when( 'is_admin' )->justReturn( false ); Viewport::init(); $this->assertTrue( !! has_action( 'wp_footer', array( 'Automattic\Jetpack_Boost\Lib\Viewport', 'viewport_tracker' ) ) ); } public function test_get_max_viewport() { $sizes = array( array( 'width' => 800, 'height' => 600, ), array( 'width' => 1024, 'height' => 768, ), array( 'width' => 1980, 'height' => 1080, ), ); $max_size = Viewport::get_max_viewport( $sizes ); $this->assertEquals( $sizes[2]['width'], $max_size['width'] ); $this->assertEquals( $sizes[2]['height'], $max_size['height'] ); } public function test_pick_viewport() { $best_size = Viewport::pick_viewport( 400, 600 ); $this->assertEquals( 640, $best_size['width'] ); $this->assertEquals( 480, $best_size['height'] ); } public function test_get_default_viewport_size_for_device() { $viewport = Viewport::get_default_viewport_size_for_device( 'mobile' ); $this->assertEquals( 640, $viewport['width'] ); $this->assertEquals( 480, $viewport['height'] ); } public function test_if_get_default_viewport_size_for_device_defaults_to_desktop_sizes() { $viewport = Viewport::get_default_viewport_size_for_device( 'foobar' ); $this->assertEquals( 1600, $viewport['width'] ); $this->assertEquals( 1050, $viewport['height'] ); } }
projects/plugins/boost/tests/php/lib/test-class-minify.php
<?php //phpcs:ignoreFile namespace Automattic\Jetpack_Boost\Tests\Lib; use Automattic\Jetpack_Boost\Lib\Minify; use Automattic\Jetpack_Boost\Tests\Base_Test_Case; /** * Class WP_Test_Minify * * @package Automattic\Jetpack_Boost\Tests\Lib */ class WP_Test_Minify extends Base_Test_Case { public function test_js() { $expanded_js = 'var one = "one"; var two = "two"; var three = "three";'; $minified_js = 'var one="one";var two="two";var three="three";'; $this->assertEquals( $minified_js, Minify::js( $expanded_js ) ); } }
projects/plugins/boost/tests/php/lib/test-class-analytics.php
<?php //phpcs:ignoreFile namespace Automattic\Jetpack_Boost\Tests\Lib; use Automattic\Jetpack_Boost\Lib\Analytics; use Automattic\Jetpack_Boost\Tests\Base_Test_Case; /** * Class WP_Test_Analytics * * @package Automattic\Jetpack_Boost\Tests\Lib */ class WP_Test_Analytics extends Base_Test_Case { public function test_get_tracking() { $tracking_object = Analytics::get_tracking(); $this->assertTrue( method_exists( $tracking_object, 'ajax_tracks' ), 'Class does not have method ajax_tracks' ); $this->assertTrue( method_exists( $tracking_object, 'enqueue_tracks_scripts' ), 'Class does not have method enqueue_tracks_scripts' ); } }
projects/plugins/boost/tests/e2e/plugins/e2e-mock-speed-score-api.php
<?php /** * Plugin Name: Boost E2E Speed Score Mocker * Plugin URI: https://github.com/automattic/jetpack * Author: Heart of Gold * Version: 1.0.0 * Text Domain: jetpack * * @package automattic/jetpack */ use Automattic\Jetpack\Boost_Speed_Score\Speed_Score_Request; add_filter( 'pre_http_request', 'e2e_mock_speed_score_api', 1, 3 ); function is_modules_disabled( $target ) { if ( ! preg_match( '/wpcom\/v2\/sites\/\d+\/jetpack-boost\/speed-scores\/([^\?]*)/', $target, $matches ) ) { return false; } $option = get_option( 'jb_transient_jetpack_boost_speed_scores_' . $matches[1] ); $url = $option['data']['url']; return str_contains( $url, 'jb-disable-modules' ); } /** * Intercept WPCOM request to generate Speed Scores and reply with mocked data * Useful when not explicitly testing speed scores, as they are heavy to generate. * * @param false $default_action - Return unmodified to continue with http request unmodified. * @param array $args - HTTP request arguments. * @param string $target - HTTP request target / URL. */ function e2e_mock_speed_score_api( $default_action, $args, $target ) { // Ignore requests which are not to the Jetpack Speed Score API. if ( ! preg_match( '#wpcom/v2/sites/\d+/jetpack-boost/speed-scores#', $target ) ) { return $default_action; } // Return generic success message when new speed score requested. if ( 'POST' === $args['method'] ) { return e2e_mock_speed_score_api_response( array( 'status' => 'pending', ) ); } // Return successful speed score message when polling. if ( 'GET' === $args['method'] ) { // Return a lower mock-score when generating with no Boost modules enabled (determined by URL arguments). $modules_disabled = is_modules_disabled( $target ); return e2e_mock_speed_score_api_response( array( 'status' => 'success', 'scores' => array( 'mobile' => $modules_disabled ? 60 : 80, 'desktop' => $modules_disabled ? 70 : 90, ), ) ); } return $default_action; } /** * Return a mocked Speed Score request. * * @param array $body - Array data to return as mocked response body. */ function e2e_mock_speed_score_api_response( $body ) { return array( 'response' => array( 'code' => 200, ), 'body' => wp_json_encode( $body ), ); } /** * On deactivation, purge any cached speed scores. */ register_deactivation_hook( __FILE__, 'e2e_mock_speed_score_purge' ); function e2e_mock_speed_score_purge() { Speed_Score_Request::clear_cache(); }
projects/plugins/protect/jetpack-protect.php
<?php /** * Plugin Name: Jetpack Protect * Plugin URI: https://wordpress.org/plugins/jetpack-protect * Description: Security tools that keep your site safe and sound, from posts to plugins. * Version: 2.1.0-alpha * Author: Automattic - Jetpack Security team * Author URI: https://jetpack.com/protect/ * License: GPLv2 or later * Text Domain: jetpack-protect * * @package automattic/jetpack-protect */ /* 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 2 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ if ( ! defined( 'ABSPATH' ) ) { exit; } define( 'JETPACK_PROTECT_VERSION', '2.1.0-alpha' ); define( 'JETPACK_PROTECT_DIR', plugin_dir_path( __FILE__ ) ); define( 'JETPACK_PROTECT_ROOT_FILE', __FILE__ ); define( 'JETPACK_PROTECT_ROOT_FILE_RELATIVE_PATH', plugin_basename( __FILE__ ) ); define( 'JETPACK_PROTECT_SLUG', 'jetpack-protect' ); define( 'JETPACK_PROTECT_NAME', 'Jetpack Protect' ); define( 'JETPACK_PROTECT_URI', 'https://jetpack.com/jetpack-protect' ); define( 'JETPACK_PROTECT_FOLDER', dirname( plugin_basename( __FILE__ ) ) ); define( 'JETPACK_PROTECT_BASE_PLUGIN_URL', plugin_dir_url( __FILE__ ) ); // Jetpack Autoloader. $jetpack_autoloader = JETPACK_PROTECT_DIR . 'vendor/autoload_packages.php'; if ( is_readable( $jetpack_autoloader ) ) { require_once $jetpack_autoloader; if ( method_exists( \Automattic\Jetpack\Assets::class, 'alias_textdomains_from_file' ) ) { \Automattic\Jetpack\Assets::alias_textdomains_from_file( JETPACK_PROTECT_DIR . 'jetpack_vendor/i18n-map.php' ); } } else { // Something very unexpected. Error out gently with an admin_notice and exit loading. if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log __( 'Error loading autoloader file for Jetpack Protect plugin', 'jetpack-protect' ) ); } add_action( 'admin_notices', function () { ?> <div class="notice notice-error is-dismissible"> <p> <?php printf( wp_kses( /* translators: Placeholder is a link to a support document. */ __( 'Your installation of Jetpack Protect is incomplete. If you installed Jetpack Protect from GitHub, please refer to <a href="%1$s" target="_blank" rel="noopener noreferrer">this document</a> to set up your development environment. Jetpack Protect must have Composer dependencies installed and built via the build command.', 'jetpack-protect' ), array( 'a' => array( 'href' => array(), 'target' => array(), 'rel' => array(), ), ) ), 'https://github.com/Automattic/jetpack/blob/trunk/docs/development-environment.md#building-your-project' ); ?> </p> </div> <?php } ); return; } // Redirect to plugin page when the plugin is activated. add_action( 'activated_plugin', 'jetpack_protect_plugin_activation' ); /** * Redirects to plugin page when the plugin is activated * * @param string $plugin Path to the plugin file relative to the plugins directory. */ function jetpack_protect_plugin_activation( $plugin ) { if ( JETPACK_PROTECT_ROOT_FILE_RELATIVE_PATH === $plugin && \Automattic\Jetpack\Plugins_Installer::is_current_request_activating_plugin_from_plugins_screen( JETPACK_PROTECT_ROOT_FILE_RELATIVE_PATH ) ) { wp_safe_redirect( esc_url( admin_url( 'admin.php?page=jetpack-protect' ) ) ); exit; } } // Add "Settings" link to plugins page. add_filter( 'plugin_action_links_' . JETPACK_PROTECT_FOLDER . '/jetpack-protect.php', function ( $actions ) { $settings_link = '<a href="' . esc_url( admin_url( 'admin.php?page=jetpack-protect' ) ) . '">' . __( 'Dashboard', 'jetpack-protect' ) . '</a>'; array_unshift( $actions, $settings_link ); return $actions; } ); register_activation_hook( __FILE__, array( 'Jetpack_Protect', 'plugin_activation' ) ); register_deactivation_hook( __FILE__, array( 'Jetpack_Protect', 'plugin_deactivation' ) ); // Main plugin class. new Jetpack_Protect();
projects/plugins/protect/tests/php/bootstrap.php
<?php /** * Bootstrap. * * @package automattic/ */ /** * Include the composer autoloader. */ require_once __DIR__ . '/../../vendor/autoload.php'; if ( empty( $_SERVER['SCRIPT_NAME'] ) ) { $_SERVER['SCRIPT_NAME'] = __DIR__ . '/vendor/phpunit/phpunit/phpunit'; } if ( empty( $_SERVER['PHP_SELF'] ) ) { $_SERVER['PHP_SELF'] = ''; } define( 'WP_DEBUG', true ); \WorDBless\Load::load();
projects/plugins/protect/tests/php/test-status.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * The Protect Status class. * * @package automattic/jetpack-protect */ namespace Automattic\Jetpack\Protect; use Automattic\Jetpack\Connection\Tokens; use Automattic\Jetpack\Constants; use Automattic\Jetpack\Redirect; use Jetpack_Options; use WorDBless\BaseTestCase; /** * The Protect Status class. */ class Test_Status extends BaseTestCase { /** * Set up before each test */ protected function set_up() { Protect_Status::$status = null; } /** * Get a sample checked theme result * * @param string $id The unique theme ID. * @param bool $with_threats Whether the sample should include a vulnerability. * @return object */ public function get_sample_theme( $id, $with_threats = true ) { $item = (object) array( 'version' => '1.0.2', 'name' => 'Sample Theme', 'checked' => true, 'type' => 'themes', 'threats' => array(), 'slug' => "theme-$id", ); if ( $with_threats ) { $item->threats[] = $this->get_sample_threat(); } return $item; } /** * Get a sample checked plugin result * * @param string $id The unique plugin ID. * @param bool $with_threats Whether the sample should include a vulnerability. * @return object */ public function get_sample_plugin( $id, $with_threats = true ) { $item = (object) array( 'version' => '1.0.2', 'name' => 'Sample Plugin', 'checked' => true, 'type' => 'plugins', 'threats' => array(), 'slug' => "plugin-$id", ); if ( $with_threats ) { $item->threats[] = $this->get_sample_threat(); } return $item; } /** * Get a sample checked core result * * @param bool $with_threats Whether the sample should include a vulnerability. * @return object */ public function get_sample_core( $with_threats = true ) { global $wp_version; $item = (object) array( 'version' => $wp_version, 'threats' => array(), 'checked' => true, 'name' => 'WordPress', 'type' => 'core', ); if ( $with_threats ) { $item->threats[] = $this->get_sample_threat(); } return $item; } /** * Get a sample vulnerabilty * * @return object */ public function get_sample_vul() { return (object) array( 'id' => 'asdasdasd-123123-asdasd', 'title' => 'Sample Vul', 'fixed_in' => '2.0.0', ); } /** * Get a sample threat * * @return object */ public function get_sample_threat() { $id = 'asdasdasd-123123-asdasd'; return new Threat_Model( array( 'id' => $id, 'title' => 'Sample Vul', 'fixed_in' => '2.0.0', 'source' => Redirect::get_url( 'jetpack-protect-vul-info', array( 'path' => $id ) ), ) ); } /** * Get a sample empty response * * @return object */ public function get_sample_empty_response() { return new Status_Model( array( 'last_checked' => '', ) ); } /** * Get a sample invalid response * * @return string */ public function get_sample_invalid_response() { return 'Invalid response'; } /** * Get a sample response * * @return object */ public function get_sample_response() { global $wp_version; return (object) array( 'last_checked' => '2003-03-03 03:03:03', 'num_vulnerabilities' => 3, 'num_themes_vulnerabilities' => 1, 'num_plugins_vulnerabilities' => 1, 'themes' => (object) array( 'theme-1' => (object) array( 'slug' => 'theme-1', 'name' => 'Sample Theme', 'version' => '1.0.2', 'checked' => true, 'vulnerabilities' => array( $this->get_sample_vul(), ), ), ), 'plugins' => (object) array( 'plugin-1' => (object) array( 'slug' => 'plugin-1', 'name' => 'Sample Plugin', 'version' => '1.0.2', 'checked' => true, 'vulnerabilities' => array( $this->get_sample_vul(), ), ), 'plugin-2' => (object) array( 'slug' => 'plugin-2', 'name' => 'Sample Plugin', 'version' => '1.0.2', 'checked' => true, 'vulnerabilities' => array(), ), ), 'core' => (object) array( 'version' => $wp_version, 'checked' => true, 'vulnerabilities' => array( $this->get_sample_vul(), ), 'name' => 'WordPress', ), ); } /** * Get a sample result of Protect_Status::get_status(). * * @return object */ public function get_sample_status() { return new Status_Model( array( 'data_source' => 'protect_report', 'plugins' => array( new Extension_Model( $this->get_sample_plugin( '1' ) ), new Extension_Model( $this->get_sample_plugin( '2', false ) ), ), 'themes' => array( new Extension_Model( $this->get_sample_theme( '1' ) ), ), 'core' => new Extension_Model( $this->get_sample_core() ), 'wordpress' => $this->get_sample_core(), 'last_checked' => '2003-03-03 03:03:03', 'num_threats' => 3, 'num_themes_threats' => 1, 'num_plugins_threats' => 1, 'has_unchecked_items' => false, ) ); } /** * Return a sample wpcom status response. * * @return array */ public function return_sample_response() { return array( 'body' => wp_json_encode( $this->get_sample_response() ), 'response' => array( 'code' => 200, 'message' => '', ), ); } /** * Return an array of sample plugins. * * @return array */ public function return_sample_plugins() { return array( 'plugin-1' => array( 'Name' => 'Sample Plugin', 'Version' => '1.0.2', ), 'plugin-2' => array( 'Name' => 'Sample Plugin', 'Version' => '1.0.2', ), ); } /** * Return an array of sample themes. * * @return array */ public function return_sample_themes() { return array( 'theme-1' => array( 'Name' => 'Sample Theme', 'Version' => '1.0.2', ), ); } /** * Return a sample empty status. * * @return array */ public function return_sample_empty_response() { return array( 'body' => wp_json_encode( $this->get_sample_empty_response() ), 'response' => array( 'code' => 200, 'message' => '', ), ); } /** * Return a sample error status. * * @return array */ public function return_sample_error_response() { return array( 'body' => wp_json_encode( 'error' ), 'response' => array( 'code' => 400, 'message' => '', ), ); } /** * Mock site connection */ public function mock_connection() { ( new Tokens() )->update_blog_token( 'test.test' ); Jetpack_Options::update_option( 'id', 123 ); Constants::set_constant( 'JETPACK__WPCOM_JSON_API_BASE', 'https://public-api.wordpress.com' ); // to do - mock a scan plan } /** * Test while site is not connected */ public function test_get_status_not_connected() { add_filter( 'pre_http_request', array( $this, 'return_sample_response' ) ); add_filter( 'all_plugins', array( $this, 'return_sample_plugins' ) ); add_filter( 'jetpack_sync_get_themes_callable', array( $this, 'return_sample_themes' ) ); $status = Protect_Status::get_status(); remove_filter( 'pre_http_request', array( $this, 'return_sample_response' ) ); remove_filter( 'all_plugins', array( $this, 'return_sample_plugins' ) ); remove_filter( 'jetpack_sync_get_themes_callable', array( $this, 'return_sample_themes' ) ); $this->assertSame( 'site_not_connected', $status->error_code ); // Make sure this was not cached $this->assertFalse( Protect_Status::get_from_options() ); } /** * Test get status */ public function test_get_status() { $this->mock_connection(); add_filter( 'pre_http_request', array( $this, 'return_sample_response' ) ); add_filter( 'all_plugins', array( $this, 'return_sample_plugins' ) ); add_filter( 'jetpack_sync_get_themes_callable', array( $this, 'return_sample_themes' ) ); $status = Protect_Status::get_status(); remove_filter( 'pre_http_request', array( $this, 'return_sample_response' ) ); remove_filter( 'all_plugins', array( $this, 'return_sample_plugins' ) ); remove_filter( 'jetpack_sync_get_themes_callable', array( $this, 'return_sample_themes' ) ); $this->assertEquals( $this->get_sample_status(), $status ); // Make sure this was cached $this->assertEquals( $this->get_sample_response(), Protect_Status::get_from_options() ); } /** * Test get total threats */ public function test_get_total_threats() { $this->mock_connection(); add_filter( 'pre_http_request', array( $this, 'return_sample_response' ) ); $status = Protect_Status::get_total_threats(); remove_filter( 'pre_http_request', array( $this, 'return_sample_response' ) ); $this->assertSame( 3, $status ); } /** * Test get all threats */ public function test_get_all_threats() { $this->mock_connection(); $expected = array( $this->get_sample_threat(), $this->get_sample_threat(), $this->get_sample_threat(), ); add_filter( 'pre_http_request', array( $this, 'return_sample_response' ) ); add_filter( 'all_plugins', array( $this, 'return_sample_plugins' ) ); add_filter( 'jetpack_sync_get_themes_callable', array( $this, 'return_sample_themes' ) ); $status = Protect_Status::get_all_threats(); remove_filter( 'pre_http_request', array( $this, 'return_sample_response' ) ); remove_filter( 'all_plugins', array( $this, 'return_sample_plugins' ) ); remove_filter( 'jetpack_sync_get_themes_callable', array( $this, 'return_sample_themes' ) ); $this->assertEquals( $expected, $status ); } /** * Data provider for test_is_cache_expired */ public function is_cache_expired_data() { return array( 'empty' => array( true, null ), 'one sec ago' => array( true, time() - 1 ), 'one min ahead' => array( false, time() + 60 ), ); } /** * Tests is_cache_expired * * @param bool $expected the expected result. * @param int $cache_timestamp The cache timestamp. * @dataProvider is_cache_expired_data */ public function test_is_cache_expired( $expected, $cache_timestamp ) { update_option( Protect_Status::OPTION_TIMESTAMP_NAME, $cache_timestamp ); $this->assertSame( $expected, Protect_Status::is_cache_expired() ); } /** * Data provider for test_get_cache_end_date_by_status */ public function get_cache_end_date_by_status_data() { return array( 'null' => array( 'initial', null, ), 'empty' => array( 'initial', $this->get_sample_empty_response(), ), 'invalid' => array( 'initial', $this->get_sample_invalid_response(), ), 'full' => array( 'full', $this->get_sample_response(), ), ); } /** * Tests get_cache_end_date_by_status * * @param bool $check_type Type of assertion to be made. * @param int $status The status object. * @dataProvider get_cache_end_date_by_status_data */ public function test_get_cache_end_date_by_status( $check_type, $status ) { $timestamp = Protect_Status::get_cache_end_date_by_status( $status ); if ( ! is_object( $status ) || 'initial' === $check_type ) { $this->assertSame( time() + Protect_Status::INITIAL_OPTION_EXPIRES_AFTER, $timestamp ); } if ( is_object( $status ) && 'full' === $check_type ) { $this->assertSame( time() + Protect_Status::OPTION_EXPIRES_AFTER, $timestamp ); } } }
projects/plugins/protect/tests/php/test-scan-status.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * Tests for the Protect Scan_Status class. * * @package automattic/jetpack-protect */ namespace Automattic\Jetpack\Protect; use Automattic\Jetpack\Connection\Tokens; use Automattic\Jetpack\Constants; use Jetpack_Options; use WorDBless\BaseTestCase; /** * The Protect Status class. */ class Test_Scan_Status extends BaseTestCase { /** * Set up before each test */ protected function set_up() { Scan_Status::$status = null; } /** * Get a sample empty response * * @return object */ public function get_sample_empty_response() { return new Status_Model( array( 'last_checked' => '', ) ); } /** * Get a sample invalid response * * @return string */ public function get_sample_invalid_response() { return 'Invalid response'; } /** * Get a sample response * * @return object */ public function get_sample_response() { return (object) array( 'state' => 'idle', 'threats' => array( (object) array( 'id' => '71626681', 'signature' => 'EICAR_AV_Test_Critical', 'description' => 'This is the standard EICAR antivirus test code, and not a real infection. If your site contains this code when you don\'t expect it to, contact Jetpack support for some help.', 'first_detected' => '2022-07-27T17 => 49 => 35.000Z', 'severity' => 5, 'fixer' => null, 'status' => 'current', 'fixable' => null, 'filename' => '/var/www/html/wp-content/uploads/jptt_eicar.php', 'context' => (object) array( '15' => 'echo <<', '17' => 'HTML;', 'marks' => new \stdClass(), ), ), (object) array( 'id' => '71625245', 'signature' => 'Vulnerable.WP.Extension', 'description' => 'The plugin WooCommerce (version 3.0.0) has a known vulnerability. ', 'first_detected' => '2022-07-27T17:22:16.000Z', 'severity' => 3, 'fixer' => null, 'status' => 'current', 'fixable' => null, 'extension' => (object) array( 'type' => 'plugin', 'slug' => 'woocommerce', 'name' => 'WooCommerce', 'version' => '3.0.0', 'isPremium' => false, ), 'source' => 'https://wpvulndb.com/vulnerabilities/10220', ), (object) array( 'id' => '69353714', 'signature' => 'Core.File.Modification', 'description' => 'Core WordPress files are not normally changed. If you did not make these changes you should review the code.', 'first_detected' => '2022-06-23T18:42:29.000Z', 'severity' => 4, 'status' => 'current', 'fixable' => (object) array( 'fixer' => 'replace', 'file' => '/var/www/html/wp-admin/index.php', 'extensionStatus' => '', ), 'filename' => '/var/www/html/wp-admin/index.php', 'diff' => "--- /tmp/wordpress/6.0-en_US/wordpress/wp-admin/index.php\t2021-11-03 03:16:57.000000000 +0000\n+++ /tmp/6299071296/core-file-23271BW6i4wLCe3T7\t2022-06-23 18:42:29.087377846 +0000\n@@ -209,3 +209,4 @@\n wp_print_community_events_templates();\n \n require_once ABSPATH . 'wp-admin/admin-footer.php';\n+if ( true === false ) exit();\n\\ No newline at end of file\n", ), ), 'has_cloud' => true, 'credentials' => array(), 'most_recent' => (object) array( 'is_initial' => false, 'timestamp' => '2003-03-03T03:03:03+00:00', ), ); } /** * Get a sample result of Scan_Status::get_status(). * * @return object */ public function get_sample_status() { global $wp_version; return new Status_Model( array( 'data_source' => 'scan_api', 'last_checked' => '2003-03-03 03:03:03', 'num_threats' => 3, 'num_plugins_threats' => 1, 'num_themes_threats' => 0, 'status' => 'idle', 'plugins' => array( new Extension_Model( array( 'version' => '3.0.0', 'name' => 'Woocommerce', 'checked' => true, 'type' => 'plugins', 'threats' => array( new Threat_Model( array( 'id' => '71625245', 'signature' => 'Vulnerable.WP.Extension', 'description' => 'The plugin WooCommerce (version 3.0.0) has a known vulnerability. ', 'first_detected' => '2022-07-27T17:22:16.000Z', 'severity' => 3, 'fixable' => null, 'status' => 'current', 'source' => 'https://wpvulndb.com/vulnerabilities/10220', ) ), ), 'slug' => 'woocommerce', ) ), ), 'themes' => array( new Extension_Model( array( 'name' => 'Sample Theme', 'slug' => 'theme-1', 'version' => '1.0.2', 'type' => 'themes', 'threats' => array(), 'checked' => true, ) ), ), 'core' => new Extension_Model( array( 'version' => $wp_version, 'threats' => array(), 'checked' => true, 'name' => 'WordPress', 'type' => 'core', ) ), 'files' => array( new Threat_Model( array( 'id' => 71626681, 'signature' => 'EICAR_AV_Test_Critical', 'description' => 'This is the standard EICAR antivirus test code, and not a real infection. If your site contains this code when you don\'t expect it to, contact Jetpack support for some help.', 'first_detected' => '2022-07-27T17 => 49 => 35.000Z', 'severity' => 5, 'fixer' => null, 'status' => 'current', 'filename' => '/var/www/html/wp-content/uploads/jptt_eicar.php', 'context' => (object) array( '15' => 'echo <<', '17' => 'HTML;', 'marks' => new \stdClass(), ), ) ), new Threat_Model( array( 'id' => 69353714, 'signature' => 'Core.File.Modification', 'description' => 'Core WordPress files are not normally changed. If you did not make these changes you should review the code.', 'first_detected' => '2022-06-23T18:42:29.000Z', 'severity' => 4, 'status' => 'current', 'fixable' => (object) array( 'fixer' => 'replace', 'file' => '/var/www/html/wp-admin/index.php', 'extensionStatus' => '', ), 'filename' => '/var/www/html/wp-admin/index.php', 'diff' => "--- /tmp/wordpress/6.0-en_US/wordpress/wp-admin/index.php\t2021-11-03 03:16:57.000000000 +0000\n+++ /tmp/6299071296/core-file-23271BW6i4wLCe3T7\t2022-06-23 18:42:29.087377846 +0000\n@@ -209,3 +209,4 @@\n wp_print_community_events_templates();\n \n require_once ABSPATH . 'wp-admin/admin-footer.php';\n+if ( true === false ) exit();\n\\ No newline at end of file\n", ) ), ), 'database' => array(), 'has_unchecked_items' => false, ) ); } /** * Return a sample wpcom status response. * * @return array */ public function return_sample_response() { return array( 'body' => wp_json_encode( $this->get_sample_response() ), 'response' => array( 'code' => 200, 'message' => '', ), ); } /** * Return an array of sample plugins. * * @return array */ public function return_sample_plugins() { return array( 'woocommerce' => array( 'Name' => 'Woocommerce', 'Version' => '3.0.0', ), ); } /** * Return an array of sample themes. * * @return array */ public function return_sample_themes() { return array( 'theme-1' => array( 'Name' => 'Sample Theme', 'Version' => '1.0.2', ), ); } /** * Return a sample empty status. * * @return array */ public function return_sample_empty_response() { return array( 'body' => wp_json_encode( $this->get_sample_empty_response() ), 'response' => array( 'code' => 200, 'message' => '', ), ); } /** * Return a sample error status. * * @return array */ public function return_sample_error_response() { return array( 'body' => wp_json_encode( 'error' ), 'response' => array( 'code' => 400, 'message' => '', ), ); } /** * Mock site connection */ public function mock_connection() { ( new Tokens() )->update_blog_token( 'test.test' ); Jetpack_Options::update_option( 'id', 123 ); Constants::set_constant( 'JETPACK__WPCOM_JSON_API_BASE', 'https://public-api.wordpress.com' ); } /** * Test while site is not connected */ public function test_get_status_not_connected() { add_filter( 'pre_http_request', array( $this, 'return_sample_response' ) ); add_filter( 'all_plugins', array( $this, 'return_sample_plugins' ) ); add_filter( 'jetpack_sync_get_themes_callable', array( $this, 'return_sample_themes' ) ); $status = Scan_Status::get_status(); remove_filter( 'pre_http_request', array( $this, 'return_sample_response' ) ); remove_filter( 'all_plugins', array( $this, 'return_sample_plugins' ) ); remove_filter( 'jetpack_sync_get_themes_callable', array( $this, 'return_sample_themes' ) ); $this->assertSame( 'site_not_connected', $status->error_code ); // Make sure this was not cached $this->assertFalse( Scan_Status::get_from_options() ); } /** * Test get status */ public function test_get_status() { $this->mock_connection(); add_filter( 'pre_http_request', array( $this, 'return_sample_response' ) ); add_filter( 'all_plugins', array( $this, 'return_sample_plugins' ) ); add_filter( 'jetpack_sync_get_themes_callable', array( $this, 'return_sample_themes' ) ); $status = Scan_Status::get_status(); remove_filter( 'pre_http_request', array( $this, 'return_sample_response' ) ); remove_filter( 'all_plugins', array( $this, 'return_sample_plugins' ) ); remove_filter( 'jetpack_sync_get_themes_callable', array( $this, 'return_sample_themes' ) ); $this->assertEquals( $this->get_sample_status(), $status ); // Make sure this was cached $this->assertEquals( $this->get_sample_response(), Scan_Status::get_from_options() ); } /** * Test get total threats */ public function test_get_total_threats() { $this->mock_connection(); add_filter( 'pre_http_request', array( $this, 'return_sample_response' ) ); add_filter( 'all_plugins', array( $this, 'return_sample_plugins' ) ); add_filter( 'jetpack_sync_get_themes_callable', array( $this, 'return_sample_themes' ) ); $status = Scan_Status::get_total_threats(); remove_filter( 'pre_http_request', array( $this, 'return_sample_response' ) ); remove_filter( 'all_plugins', array( $this, 'return_sample_plugins' ) ); remove_filter( 'jetpack_sync_get_themes_callable', array( $this, 'return_sample_themes' ) ); $this->assertSame( 3, $status ); } /** * Test get all threats */ public function test_get_all_threats() { $this->mock_connection(); $expected = array( new Threat_Model( array( 'id' => '71625245', 'signature' => 'Vulnerable.WP.Extension', 'description' => 'The plugin WooCommerce (version 3.0.0) has a known vulnerability. ', 'first_detected' => '2022-07-27T17:22:16.000Z', 'severity' => 3, 'fixable' => null, 'status' => 'current', 'source' => 'https://wpvulndb.com/vulnerabilities/10220', ) ), new Threat_Model( array( 'id' => 71626681, 'signature' => 'EICAR_AV_Test_Critical', 'description' => 'This is the standard EICAR antivirus test code, and not a real infection. If your site contains this code when you don\'t expect it to, contact Jetpack support for some help.', 'first_detected' => '2022-07-27T17 => 49 => 35.000Z', 'severity' => 5, 'fixer' => null, 'status' => 'current', 'filename' => '/var/www/html/wp-content/uploads/jptt_eicar.php', 'context' => (object) array( '15' => 'echo <<', '17' => 'HTML;', 'marks' => new \stdClass(), ), ) ), new Threat_Model( array( 'id' => 69353714, 'signature' => 'Core.File.Modification', 'description' => 'Core WordPress files are not normally changed. If you did not make these changes you should review the code.', 'first_detected' => '2022-06-23T18:42:29.000Z', 'severity' => 4, 'status' => 'current', 'fixable' => (object) array( 'fixer' => 'replace', 'file' => '/var/www/html/wp-admin/index.php', 'extensionStatus' => '', ), 'filename' => '/var/www/html/wp-admin/index.php', 'diff' => "--- /tmp/wordpress/6.0-en_US/wordpress/wp-admin/index.php\t2021-11-03 03:16:57.000000000 +0000\n+++ /tmp/6299071296/core-file-23271BW6i4wLCe3T7\t2022-06-23 18:42:29.087377846 +0000\n@@ -209,3 +209,4 @@\n wp_print_community_events_templates();\n \n require_once ABSPATH . 'wp-admin/admin-footer.php';\n+if ( true === false ) exit();\n\\ No newline at end of file\n", ) ), ); add_filter( 'pre_http_request', array( $this, 'return_sample_response' ) ); add_filter( 'all_plugins', array( $this, 'return_sample_plugins' ) ); add_filter( 'jetpack_sync_get_themes_callable', array( $this, 'return_sample_themes' ) ); $all_threats = Scan_Status::get_all_threats(); remove_filter( 'pre_http_request', array( $this, 'return_sample_response' ) ); remove_filter( 'all_plugins', array( $this, 'return_sample_plugins' ) ); remove_filter( 'jetpack_sync_get_themes_callable', array( $this, 'return_sample_themes' ) ); $this->assertEquals( $expected, $all_threats ); } /** * Data provider for test_is_cache_expired */ public function is_cache_expired_data() { return array( 'empty' => array( true, null ), 'one sec ago' => array( true, time() - 1 ), 'one min ahead' => array( false, time() + 60 ), ); } /** * Tests is_cache_expired * * @param bool $expected the expected result. * @param int $cache_timestamp The cache timestamp. * @dataProvider is_cache_expired_data */ public function test_is_cache_expired( $expected, $cache_timestamp ) { update_option( Scan_Status::OPTION_TIMESTAMP_NAME, $cache_timestamp ); $this->assertSame( $expected, Scan_Status::is_cache_expired() ); } /** * Data provider for test_get_cache_end_date_by_status */ public function get_cache_end_date_by_status_data() { return array( 'null' => array( 'initial', null, ), 'empty' => array( 'initial', $this->get_sample_empty_response(), ), 'invalid' => array( 'initial', $this->get_sample_invalid_response(), ), 'full' => array( 'full', $this->get_sample_status(), ), ); } /** * Tests get_cache_end_date_by_status * * @param bool $check_type Type of assertion to be made. * @param int $status The status object. * @dataProvider get_cache_end_date_by_status_data */ public function test_get_cache_end_date_by_status( $check_type, $status ) { $timestamp = Scan_Status::get_cache_end_date_by_status( $status ); if ( ! is_object( $status ) || 'initial' === $check_type ) { $this->assertSame( time() + Scan_Status::INITIAL_OPTION_EXPIRES_AFTER, $timestamp ); } if ( is_object( $status ) && 'full' === $check_type ) { $this->assertSame( time() + Scan_Status::OPTION_EXPIRES_AFTER, $timestamp ); } } }
projects/plugins/protect/tests/php/models/test-extension-model.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\Protect; use WorDBless\BaseTestCase; /** * Tests for the Extension_Model class. * * @package automattic/jetpack-protect */ class Test_Extension_Model extends BaseTestCase { /** * Get a sample threat * * @param int|string $id The sample threat's unique identifier. * @return array */ private static function get_sample_threat( $id = 0 ) { return array( 'id' => "test-threat-$id", 'signature' => 'Test.Threat', 'title' => "Test Threat $id", 'description' => 'This is a test threat.', ); } /** * Tests for extension model's __construct() method. */ public function test_extension_model_construct() { $test_data = array( 'name' => 'Test Extension', 'slug' => 'test-extension', 'version' => '1.0.0', 'threats' => array( self::get_sample_threat( 0 ), self::get_sample_threat( 1 ), self::get_sample_threat( 2 ), ), 'checked' => true, 'type' => 'plugins', ); // Initialize multiple instances of Extension_Model to test varying initial params $test_extensions = array( new Extension_Model( $test_data ), new Extension_Model( (object) $test_data ), ); foreach ( $test_extensions as $extension ) { foreach ( $extension->threats as $loop_index => $threat ) { // Validate the threat data is converted into Threat_Models $this->assertSame( 'Automattic\Jetpack\Protect\Threat_Model', get_class( $threat ) ); // Validate the threat data is set properly foreach ( self::get_sample_threat( $loop_index ) as $key => $value ) { $this->assertSame( $value, $threat->{ $key } ); } } } } }
projects/plugins/protect/tests/php/models/test-threat-model.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\Protect; use WorDBless\BaseTestCase; /** * Tests for the Threat_Model class. * * @package automattic/jetpack-protect */ class Test_Threat_Model extends BaseTestCase { /** * Tests for threat model's __construct() method. */ public function test_threat_model_construct() { $test_data = array( 'id' => 'abc-123-abc-123', 'signature' => 'Test.Threat', 'title' => 'Test Threat', 'description' => 'This is a test threat.', 'first_detected' => '2022-01-01T00:00:00.000Z', 'fixed_in' => '1.0.1', 'severity' => 4, 'fixable' => (object) array( 'fixer' => 'update', 'target' => '1.0.1', 'extension_status' => 'active', ), 'status' => 'current', 'filename' => '/srv/htdocs/wp-content/uploads/threat.jpg.php', 'context' => (object) array(), ); // Initialize multiple instances of Threat_Model to test varying initial params $test_threats = array( new Threat_Model( $test_data ), new Threat_Model( (object) $test_data ), ); foreach ( $test_threats as $threat ) { // Validate the threat data is set properly foreach ( $test_data as $key => $value ) { $this->assertSame( $value, $threat->{ $key } ); } } } }
projects/plugins/protect/src/class-protect-status.php
<?php /** * Class to handle the Protect Status of Jetpack Protect * * @package automattic/jetpack-protect-plugin */ namespace Automattic\Jetpack\Protect; use Automattic\Jetpack\Connection\Client; use Automattic\Jetpack\Connection\Manager as Connection_Manager; use Automattic\Jetpack\Plugins_Installer; use Automattic\Jetpack\Redirect; use Automattic\Jetpack\Sync\Functions as Sync_Functions; use Jetpack_Options; use WP_Error; /** * Class that handles fetching and caching the Status of vulnerabilities check from the WPCOM servers */ class Protect_Status extends Status { /** * WPCOM endpoint * * @var string */ const REST_API_BASE = '/sites/%d/jetpack-protect-status'; /** * Name of the option where status is stored * * @var string */ const OPTION_NAME = 'jetpack_protect_status'; /** * Name of the option where the timestamp of the status is stored * * @var string */ const OPTION_TIMESTAMP_NAME = 'jetpack_protect_status_time'; /** * Gets the current status of the Jetpack Protect checks * * @param bool $refresh_from_wpcom Refresh the local plan and status cache from wpcom. * @return Status_Model */ public static function get_status( $refresh_from_wpcom = false ) { if ( self::$status !== null ) { return self::$status; } if ( $refresh_from_wpcom || ! self::should_use_cache() || self::is_cache_expired() ) { $status = self::fetch_from_server(); } else { $status = self::get_from_options(); } if ( is_wp_error( $status ) ) { $status = new Status_Model( array( 'error' => true, 'error_code' => $status->get_error_code(), 'error_message' => $status->get_error_message(), ) ); } else { $status = self::normalize_protect_report_data( $status ); } self::$status = $status; return $status; } /** * Gets the WPCOM API endpoint * * @return WP_Error|string */ public static function get_api_url() { $blog_id = Jetpack_Options::get_option( 'id' ); $is_connected = ( new Connection_Manager() )->is_connected(); if ( ! $blog_id || ! $is_connected ) { return new WP_Error( 'site_not_connected' ); } $api_url = sprintf( self::REST_API_BASE, $blog_id ); return $api_url; } /** * Fetches the status from WPCOM servers * * @return WP_Error|array */ public static function fetch_from_server() { $api_url = self::get_api_url(); if ( is_wp_error( $api_url ) ) { return $api_url; } $response = Client::wpcom_json_api_request_as_blog( self::get_api_url(), '2', array( 'method' => 'GET' ), null, 'wpcom' ); $response_code = wp_remote_retrieve_response_code( $response ); if ( is_wp_error( $response ) || 200 !== $response_code || empty( $response['body'] ) ) { return new WP_Error( 'failed_fetching_status', 'Failed to fetch Protect Status data from server', array( 'status' => $response_code ) ); } $body = json_decode( wp_remote_retrieve_body( $response ) ); self::update_status_option( $body ); return $body; } /** * Normalize data from the Protect Report data source. * * @param object $report_data Data from the Protect Report. * @return Status_Model */ protected static function normalize_protect_report_data( $report_data ) { $status = new Status_Model(); $status->data_source = 'protect_report'; // map report data properties directly into the Status_Model $status->status = isset( $report_data->status ) ? $report_data->status : null; $status->last_checked = isset( $report_data->last_checked ) ? $report_data->last_checked : null; $status->num_threats = isset( $report_data->num_vulnerabilities ) ? $report_data->num_vulnerabilities : null; $status->num_themes_threats = isset( $report_data->num_themes_vulnerabilities ) ? $report_data->num_themes_vulnerabilities : null; $status->num_plugins_threats = isset( $report_data->num_plugins_vulnerabilities ) ? $report_data->num_plugins_vulnerabilities : null; // merge plugins from report with all installed plugins before mapping into the Status_Model $installed_plugins = Plugins_Installer::get_plugins(); $last_report_plugins = isset( $report_data->plugins ) ? $report_data->plugins : new \stdClass(); $status->plugins = self::merge_installed_and_checked_lists( $installed_plugins, $last_report_plugins, array( 'type' => 'plugins' ) ); // merge themes from report with all installed plugins before mapping into the Status_Model $installed_themes = Sync_Functions::get_themes(); $last_report_themes = isset( $report_data->themes ) ? $report_data->themes : new \stdClass(); $status->themes = self::merge_installed_and_checked_lists( $installed_themes, $last_report_themes, array( 'type' => 'themes' ) ); // normalize WordPress core report data and map into Status_Model $status->core = self::normalize_core_information( isset( $report_data->core ) ? $report_data->core : new \stdClass() ); // check if any installed items (themes, plugins, or core) have not been checked in the report $all_items = array_merge( $status->plugins, $status->themes, array( $status->core ) ); $unchecked_items = array_filter( $all_items, function ( $item ) { return ! isset( $item->checked ) || ! $item->checked; } ); $status->has_unchecked_items = ! empty( $unchecked_items ); return $status; } /** * Merges the list of installed extensions with the list of extensions that were checked for known vulnerabilities and return a normalized list to be used in the UI * * @param array $installed The list of installed extensions, where each attribute key is the extension slug. * @param object $checked The list of checked extensions. * @param array $append Additional data to append to each result in the list. * @return array Normalized list of extensions. */ protected static function merge_installed_and_checked_lists( $installed, $checked, $append ) { $new_list = array(); foreach ( array_keys( $installed ) as $slug ) { $checked = (object) $checked; $extension = new Extension_Model( array_merge( array( 'name' => $installed[ $slug ]['Name'], 'version' => $installed[ $slug ]['Version'], 'slug' => $slug, 'threats' => array(), 'checked' => false, ), $append ) ); if ( isset( $checked->{ $slug } ) && $checked->{ $slug }->version === $installed[ $slug ]['Version'] ) { $extension->version = $checked->{ $slug }->version; $extension->checked = true; if ( is_array( $checked->{ $slug }->vulnerabilities ) ) { foreach ( $checked->{ $slug }->vulnerabilities as $threat ) { $extension->threats[] = new Threat_Model( array( 'id' => $threat->id, 'title' => $threat->title, 'fixed_in' => $threat->fixed_in, 'description' => isset( $threat->description ) ? $threat->description : null, 'source' => isset( $threat->id ) ? Redirect::get_url( 'jetpack-protect-vul-info', array( 'path' => $threat->id ) ) : null, ) ); } } } $new_list[] = $extension; } $new_list = parent::sort_threats( $new_list ); return $new_list; } /** * Check if the WordPress version that was checked matches the current installed version. * * @param object $core_check The object returned by Protect wpcom endpoint. * @return object The object representing the current status of core checks. */ protected static function normalize_core_information( $core_check ) { global $wp_version; $core = new Extension_Model( array( 'type' => 'core', 'name' => 'WordPress', 'version' => $wp_version, 'checked' => false, ) ); if ( isset( $core_check->version ) && $core_check->version === $wp_version ) { if ( is_array( $core_check->vulnerabilities ) ) { $core->checked = true; $core->set_threats( array_map( function ( $vulnerability ) { $vulnerability->source = isset( $vulnerability->id ) ? Redirect::get_url( 'jetpack-protect-vul-info', array( 'path' => $vulnerability->id ) ) : null; return $vulnerability; }, $core_check->vulnerabilities ) ); } } return $core; } }
projects/plugins/protect/src/class-credentials.php
<?php /** * Class to handle Rewind * * @package automattic/jetpack-protect-plugin */ namespace Automattic\Jetpack\Protect; use Automattic\Jetpack\Connection\Client; use Automattic\Jetpack\Connection\Manager as Connection_Manager; use Jetpack_Options; /** * Class that handles the rewind api call. */ class Credentials { /** * Get the rewind state, if no creds are set the state will be 'awaiting_for_credentials' * * @return bool */ public static function get_credential_array() { $blog_id = Jetpack_Options::get_option( 'id' ); $is_connected = ( new Connection_Manager() )->is_connected(); if ( ! $blog_id || ! $is_connected ) { return false; } $api_url = sprintf( '/sites/%d/scan', $blog_id ); $response = Client::wpcom_json_api_request_as_blog( $api_url, '2', array( 'method' => 'GET' ), null, 'wpcom' ); $response_code = wp_remote_retrieve_response_code( $response ); if ( is_wp_error( $response ) || 200 !== $response_code ) { return false; } $parsed_response = json_decode( $response['body'] ); if ( ! $parsed_response ) { return false; } return isset( $parsed_response->credentials ) ? $parsed_response->credentials : array(); } }
projects/plugins/protect/src/class-status.php
<?php /** * Class to handle the Status of Jetpack Protect * * @package automattic/jetpack-protect-plugin */ namespace Automattic\Jetpack\Protect; /** * Class that handles fetching and caching the Status of vulnerabilities check from the WPCOM servers */ class Status { /** * Name of the option where status is stored * * @var string */ const OPTION_NAME = ''; /** * Name of the option where the timestamp of the status is stored * * @var string */ const OPTION_TIMESTAMP_NAME = ''; /** * Time in seconds that the cache should last * * @var int */ const OPTION_EXPIRES_AFTER = 3600; // 1 hour. /** * Time in seconds that the cache for the initial empty response should last * * @var int */ const INITIAL_OPTION_EXPIRES_AFTER = 1 * MINUTE_IN_SECONDS; /** * Memoization for the current status * * @var null|Status_Model */ public static $status = null; /** * Gets the current status of the Jetpack Protect checks * * @param bool $refresh_from_wpcom Refresh the local plan and status cache from wpcom. * @return Status_Model */ public static function get_status( $refresh_from_wpcom = false ) { $use_scan_status = Plan::has_required_plan(); if ( defined( 'JETPACK_PROTECT_DEV__DATA_SOURCE' ) ) { if ( 'scan_api' === JETPACK_PROTECT_DEV__DATA_SOURCE ) { $use_scan_status = true; } if ( 'protect_report' === JETPACK_PROTECT_DEV__DATA_SOURCE ) { $use_scan_status = false; } } self::$status = $use_scan_status ? Scan_Status::get_status( $refresh_from_wpcom ) : Protect_Status::get_status( $refresh_from_wpcom ); return self::$status; } /** * Checks if the current cached status is expired and should be renewed * * @return boolean */ public static function is_cache_expired() { $option_timestamp = get_option( static::OPTION_TIMESTAMP_NAME ); if ( ! $option_timestamp ) { return true; } return time() > (int) $option_timestamp; } /** * Checks if we should consider the stored cache or bypass it * * @return boolean */ public static function should_use_cache() { return defined( 'JETPACK_PROTECT_DEV__BYPASS_CACHE' ) && JETPACK_PROTECT_DEV__BYPASS_CACHE ? false : true; } /** * Gets the current cached status * * @return bool|array False if value is not found. Array with values if cache is found. */ public static function get_from_options() { return maybe_unserialize( get_option( static::OPTION_NAME ) ); } /** * Updated the cached status and its timestamp * * @param array $status The new status to be cached. * @return void */ public static function update_status_option( $status ) { // TODO: Sanitize $status. update_option( static::OPTION_NAME, maybe_serialize( $status ) ); $end_date = self::get_cache_end_date_by_status( $status ); update_option( static::OPTION_TIMESTAMP_NAME, $end_date ); } /** * Returns the timestamp the cache should expire depending on the current status * * Initial empty status, which are returned before the first check was performed, should be cache for less time * * @param object $status The response from the server being cached. * @return int The timestamp when the cache should expire. */ public static function get_cache_end_date_by_status( $status ) { if ( ! is_object( $status ) || empty( $status->last_checked ) ) { return time() + static::INITIAL_OPTION_EXPIRES_AFTER; } return time() + static::OPTION_EXPIRES_AFTER; } /** * Delete the cached status and its timestamp * * @return bool Whether all related status options were successfully deleted. */ public static function delete_option() { $option_deleted = delete_option( static::OPTION_NAME ); $option_timestamp_deleted = delete_option( static::OPTION_TIMESTAMP_NAME ); return $option_deleted && $option_timestamp_deleted; } /** * Checks the current status to see if there are any threats found * * @return boolean */ public static function has_threats() { return 0 < self::get_total_threats(); } /** * Gets the total number of threats found * * @return integer */ public static function get_total_threats() { $status = static::get_status(); return isset( $status->num_threats ) && is_int( $status->num_threats ) ? $status->num_threats : 0; } /** * Get all threats combined * * @return array */ public static function get_all_threats() { return array_merge( self::get_wordpress_threats(), self::get_themes_threats(), self::get_plugins_threats(), self::get_files_threats(), self::get_database_threats() ); } /** * Get threats found for WordPress core * * @return array */ public static function get_wordpress_threats() { return self::get_threats( 'core' ); } /** * Get threats found for themes * * @return array */ public static function get_themes_threats() { return self::get_threats( 'themes' ); } /** * Get threats found for plugins * * @return array */ public static function get_plugins_threats() { return self::get_threats( 'plugins' ); } /** * Get threats found for files * * @return array */ public static function get_files_threats() { return self::get_threats( 'files' ); } /** * Get threats found for plugins * * @return array */ public static function get_database_threats() { return self::get_threats( 'database' ); } /** * Get the threats for one type of extension or core * * @param string $type What threats you want to get. Possible values are 'core', 'themes' and 'plugins'. * * @return array */ public static function get_threats( $type ) { $status = static::get_status(); if ( 'core' === $type ) { return isset( $status->$type ) && ! empty( $status->$type->threats ) ? $status->$type->threats : array(); } if ( 'files' === $type || 'database' === $type ) { return isset( $status->$type ) && ! empty( $status->$type ) ? $status->$type : array(); } $threats = array(); if ( isset( $status->$type ) ) { foreach ( (array) $status->$type as $item ) { if ( ! empty( $item->threats ) ) { $threats = array_merge( $threats, $item->threats ); } } } return $threats; } /** * Check if the WordPress version that was checked matches the current installed version. * * @param object $core_check The object returned by Protect wpcom endpoint. * @return object The object representing the current status of core checks. */ protected static function normalize_core_information( $core_check ) { global $wp_version; $core = new Extension_Model( array( 'type' => 'core', 'name' => 'WordPress', 'version' => $wp_version, 'checked' => false, ) ); if ( isset( $core_check->version ) && $core_check->version === $wp_version ) { if ( is_array( $core_check->vulnerabilities ) ) { $core->checked = true; $core->set_threats( $core_check->vulnerabilities ); } } return $core; } /** * Sort By Threats * * @param array<object> $threats Array of threats to sort. * * @return array<object> The sorted $threats array. */ protected static function sort_threats( $threats ) { usort( $threats, function ( $a, $b ) { // sort primarily based on the presence of threats $ret = empty( $a->threats ) <=> empty( $b->threats ); // sort secondarily on whether the item has been checked if ( ! $ret ) { $ret = $a->checked <=> $b->checked; } return $ret; } ); return $threats; } }
projects/plugins/protect/src/class-jetpack-protect.php
<?php /** * Primary class file for the Jetpack Protect plugin. * * @package automattic/jetpack-protect-plugin */ if ( ! defined( 'ABSPATH' ) ) { exit; } use Automattic\Jetpack\Admin_UI\Admin_Menu; use Automattic\Jetpack\Assets; use Automattic\Jetpack\Connection\Initial_State as Connection_Initial_State; use Automattic\Jetpack\Connection\Manager as Connection_Manager; use Automattic\Jetpack\IP\Utils as IP_Utils; use Automattic\Jetpack\JITMS\JITM; use Automattic\Jetpack\Modules; use Automattic\Jetpack\My_Jetpack\Initializer as My_Jetpack_Initializer; use Automattic\Jetpack\My_Jetpack\Products as My_Jetpack_Products; use Automattic\Jetpack\Plugins_Installer; use Automattic\Jetpack\Protect\Onboarding; use Automattic\Jetpack\Protect\Plan; use Automattic\Jetpack\Protect\REST_Controller; use Automattic\Jetpack\Protect\Site_Health; use Automattic\Jetpack\Protect\Status; use Automattic\Jetpack\Status as Jetpack_Status; use Automattic\Jetpack\Sync\Functions as Sync_Functions; use Automattic\Jetpack\Sync\Sender; use Automattic\Jetpack\Waf\Waf_Runner; use Automattic\Jetpack\Waf\Waf_Stats; /** * Class Jetpack_Protect */ class Jetpack_Protect { /** * Licenses product ID. * * @var string */ const JETPACK_SCAN_PRODUCT_IDS = array( 2010, // JETPACK_SECURITY_DAILY. 2011, // JETPACK_SECURITY_DAILY_MOTNHLY. 2012, // JETPACK_SECURITY_REALTIME. 2013, // JETPACK_SECURITY_REALTIME_MONTHLY. 2014, // JETPACK_COMPLETE. 2015, // JETPACK_COMPLETE_MONTHLY. 2016, // JETPACK_SECURITY_TIER_1_YEARLY. 2017, // JETPACK_SECURITY_TIER_1_MONTHLY. 2019, // JETPACK_SECURITY_TIER_2_YEARLY. 2020, // JETPACK_SECURITY_TIER_2_MONTHLY. 2106, // JETPACK_SCAN. 2107, // JETPACK_SCAN_MONTHLY. 2108, // JETPACK_SCAN_REALTIME. 2109, // JETPACK_SCAN_REALTIME_MONTHLY. ); const JETPACK_WAF_MODULE_SLUG = 'waf'; const JETPACK_BRUTE_FORCE_PROTECTION_MODULE_SLUG = 'protect'; const JETPACK_PROTECT_ACTIVATION_OPTION = JETPACK_PROTECT_SLUG . '_activated'; /** * Constructor. */ public function __construct() { add_action( 'init', array( $this, 'init' ) ); add_action( '_admin_menu', array( $this, 'admin_page_init' ) ); // Activate the module as the plugin is activated add_action( 'admin_init', array( $this, 'do_plugin_activation_activities' ) ); // Init Jetpack packages add_action( 'plugins_loaded', function () { $config = new Automattic\Jetpack\Config(); // Connection package. $config->ensure( 'connection', array( 'slug' => JETPACK_PROTECT_SLUG, 'name' => JETPACK_PROTECT_NAME, 'url_info' => JETPACK_PROTECT_URI, ) ); // Sync package. $config->ensure( 'sync', array( 'jetpack_sync_modules' => array( 'Automattic\\Jetpack\\Sync\\Modules\\Options', 'Automattic\\Jetpack\\Sync\\Modules\\Callables', 'Automattic\\Jetpack\\Sync\\Modules\\Users', ), 'jetpack_sync_callable_whitelist' => array( 'main_network_site' => array( 'Automattic\\Jetpack\\Connection\\Urls', 'main_network_site_url' ), 'get_plugins' => array( 'Automattic\\Jetpack\\Sync\\Functions', 'get_plugins' ), 'get_themes' => array( 'Automattic\\Jetpack\\Sync\\Functions', 'get_themes' ), 'wp_version' => array( 'Automattic\\Jetpack\\Sync\\Functions', 'wp_version' ), ), 'jetpack_sync_options_contentless' => array(), 'jetpack_sync_options_whitelist' => array( 'active_plugins', 'stylesheet', ), ) ); // Identity crisis package. $config->ensure( 'identity_crisis' ); // Web application firewall package. $config->ensure( 'waf' ); }, 1 ); add_filter( 'jetpack_connection_user_has_license', array( $this, 'jetpack_check_user_licenses' ), 10, 3 ); add_filter( 'jetpack_get_available_standalone_modules', array( $this, 'protect_filter_available_modules' ), 10, 1 ); } /** * Initialize the plugin * * @return void */ public function init() { add_action( 'admin_bar_menu', array( $this, 'admin_bar' ), 65 ); add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_styles' ) ); REST_Controller::init(); My_Jetpack_Initializer::init(); Site_Health::init(); // Sets up JITMS. JITM::configure(); } /** * Initialize the admin page resources. */ public function admin_page_init() { $total_threats = Status::get_total_threats(); $menu_label = _x( 'Protect', 'The Jetpack Protect product name, without the Jetpack prefix', 'jetpack-protect' ); if ( $total_threats ) { $menu_label .= sprintf( ' <span class="update-plugins">%d</span>', $total_threats ); } $page_suffix = Admin_Menu::add_menu( __( 'Jetpack Protect', 'jetpack-protect' ), $menu_label, 'manage_options', 'jetpack-protect', array( $this, 'plugin_settings_page' ) ); add_action( 'load-' . $page_suffix, array( $this, 'enqueue_admin_scripts' ) ); } /** * Enqueues the wp-admin styles (used outside the React app) */ public function enqueue_admin_styles() { wp_enqueue_style( 'jetpack-protect-wpadmin', JETPACK_PROTECT_BASE_PLUGIN_URL . '/assets/jetpack-protect.css', array(), JETPACK_PROTECT_VERSION ); } /** * Enqueue plugin admin scripts and styles. */ public function enqueue_admin_scripts() { Assets::register_script( 'jetpack-protect', 'build/index.js', JETPACK_PROTECT_ROOT_FILE, array( 'in_footer' => true, 'textdomain' => 'jetpack-protect', ) ); Assets::enqueue_script( 'jetpack-protect' ); // Required for Analytics. wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true ); // Initial JS state including JP Connection data. Connection_Initial_State::render_script( 'jetpack-protect' ); wp_add_inline_script( 'jetpack-protect', $this->render_initial_state(), 'before' ); } /** * Render the initial state into a JavaScript variable. * * @return string */ public function render_initial_state() { return 'var jetpackProtectInitialState=JSON.parse(decodeURIComponent("' . rawurlencode( wp_json_encode( $this->initial_state() ) ) . '"));'; } /** * Get the initial state data for hydrating the React UI. * * @return array */ public function initial_state() { global $wp_version; // phpcs:disable WordPress.Security.NonceVerification.Recommended $refresh_status_from_wpcom = isset( $_GET['checkPlan'] ); $initial_state = array( 'apiRoot' => esc_url_raw( rest_url() ), 'apiNonce' => wp_create_nonce( 'wp_rest' ), 'registrationNonce' => wp_create_nonce( 'jetpack-registration-nonce' ), 'status' => Status::get_status( $refresh_status_from_wpcom ), 'installedPlugins' => Plugins_Installer::get_plugins(), 'installedThemes' => Sync_Functions::get_themes(), 'wpVersion' => $wp_version, 'adminUrl' => 'admin.php?page=jetpack-protect', 'siteSuffix' => ( new Jetpack_Status() )->get_site_suffix(), 'blogID' => Connection_Manager::get_site_id( true ), 'jetpackScan' => My_Jetpack_Products::get_product( 'scan' ), 'hasRequiredPlan' => Plan::has_required_plan(), 'onboardingProgress' => Onboarding::get_current_user_progress(), 'waf' => array( 'wafSupported' => Waf_Runner::is_supported_environment(), 'currentIp' => IP_Utils::get_ip(), 'isSeen' => self::get_waf_seen_status(), 'upgradeIsSeen' => self::get_waf_upgrade_seen_status(), 'displayUpgradeBadge' => self::get_waf_upgrade_badge_display_status(), 'isEnabled' => Waf_Runner::is_enabled(), 'isToggling' => false, 'isUpdating' => false, 'config' => Waf_Runner::get_config(), 'stats' => self::get_waf_stats(), ), ); $initial_state['jetpackScan']['pricingForUi'] = Plan::get_product( 'jetpack_scan' ); return $initial_state; } /** * Main plugin settings page. */ public function plugin_settings_page() { ?> <div id="jetpack-protect-root"></div> <?php } /** * Activate the WAF module on plugin activation. * * @static */ public static function plugin_activation() { add_option( self::JETPACK_PROTECT_ACTIVATION_OPTION, true ); } /** * Runs on admin_init, and does actions required on plugin activation, based on * the activation option. * * This needs to be run after the activation hook, as that results in a redirect, * and we need the sync module's actions and filters to be registered. */ public static function do_plugin_activation_activities() { if ( get_option( self::JETPACK_PROTECT_ACTIVATION_OPTION ) && ( new Connection_Manager() )->is_connected() ) { self::activate_modules(); } } /** * Activates the waf and brute force protection modules and disables the activation option */ public static function activate_modules() { delete_option( self::JETPACK_PROTECT_ACTIVATION_OPTION ); ( new Modules() )->activate( self::JETPACK_WAF_MODULE_SLUG, false, false ); ( new Modules() )->activate( self::JETPACK_BRUTE_FORCE_PROTECTION_MODULE_SLUG, false, false ); } /** * Removes plugin from the connection manager * If it's the last plugin using the connection, the site will be disconnected. * * @access public * @static */ public static function plugin_deactivation() { // Clear Sync data. Sender::get_instance()->uninstall(); $manager = new Connection_Manager( 'jetpack-protect' ); $manager->remove_connection(); Status::delete_option(); } /** * Create a shortcut on Admin Bar to show the total of threats found. * * @param object $wp_admin_bar The Admin Bar object. * @return void */ public function admin_bar( $wp_admin_bar ) { if ( ! current_user_can( 'manage_options' ) ) { return; } $total = Status::get_total_threats(); if ( $total > 0 ) { $args = array( 'id' => 'jetpack-protect', 'title' => '<span class="ab-icon jp-protect-icon"></span><span class="ab-label">' . $total . '</span>', 'href' => admin_url( 'admin.php?page=jetpack-protect' ), 'meta' => array( // translators: %d is the number of threats found. 'title' => sprintf( _n( '%d threat found by Jetpack Protect', '%d threats found by Jetpack Protect', $total, 'jetpack-protect' ), $total ), ), ); $wp_admin_bar->add_node( $args ); } } /** * Adds modules to the list of available modules * * @param array $modules The available modules. * @return array */ public function protect_filter_available_modules( $modules ) { return array_merge( array( self::JETPACK_WAF_MODULE_SLUG, self::JETPACK_BRUTE_FORCE_PROTECTION_MODULE_SLUG ), $modules ); } /** * Check if the user has an available license that includes Jetpack Scan. * * @param boolean $has_license Whether a license was already found. * @param object[] $licenses Unattached licenses belonging to the user. * @param string $plugin_slug Slug of the plugin that initiated the flow. * * @return boolean */ public static function jetpack_check_user_licenses( $has_license, $licenses, $plugin_slug ) { if ( $plugin_slug !== JETPACK_PROTECT_SLUG || $has_license ) { return $has_license; } $license_found = false; foreach ( $licenses as $license ) { if ( $license->attached_at || $license->revoked_at ) { continue; } if ( in_array( $license->product_id, self::JETPACK_SCAN_PRODUCT_IDS, true ) ) { $license_found = true; break; } } return $license_found; } /** * Get WAF "Seen" Status * * @return bool Whether the current user has viewed the WAF screen. */ public static function get_waf_seen_status() { return (bool) get_user_meta( get_current_user_id(), 'jetpack_protect_waf_seen', true ); } /** * Set WAF "Seen" Status * * @return bool True if seen status updated to true, false on failure. */ public static function set_waf_seen_status() { return (bool) update_user_meta( get_current_user_id(), 'jetpack_protect_waf_seen', true ); } /** * Get WAF Upgrade "Seen" Status * * @return bool Whether the current user has dismissed the upgrade popover or enabled the automatic rules feature. */ public static function get_waf_upgrade_seen_status() { return (bool) get_user_meta( get_current_user_id(), 'jetpack_protect_waf_upgrade_seen', true ); } /** * Set WAF Upgrade "Seen" Status * * @return bool True if upgrade seen status updated to true, false on failure. */ public static function set_waf_upgrade_seen_status() { self::set_waf_upgrade_badge_timestamp(); return (bool) update_user_meta( get_current_user_id(), 'jetpack_protect_waf_upgrade_seen', true ); } /** * Get WAF Upgrade Badge Timestamp * * @return integer The timestamp for the when the upgrade seen status was first set to true. */ public static function get_waf_upgrade_badge_timestamp() { return (int) get_user_meta( get_current_user_id(), 'jetpack_protect_waf_upgrade_badge_timestamp', true ); } /** * Set WAF Upgrade Badge Timestamp * * @return bool True if upgrade badge timestamp to set to the current time, false on failure. */ public static function set_waf_upgrade_badge_timestamp() { return (bool) update_user_meta( get_current_user_id(), 'jetpack_protect_waf_upgrade_badge_timestamp', time() ); } /** * Get WAF Upgrade Badge Display Status * * @return bool True if upgrade badge timestamp is set and less than 7 days ago, otherwise false. */ public static function get_waf_upgrade_badge_display_status() { $badge_timestamp_exists = metadata_exists( 'user', get_current_user_id(), 'jetpack_protect_waf_upgrade_badge_timestamp' ); if ( ! $badge_timestamp_exists ) { return true; } $badge_timestamp = self::get_waf_upgrade_badge_timestamp(); $seven_days = strtotime( '-7 days' ); if ( $badge_timestamp > $seven_days ) { return true; } return false; } /** * Get WAF stats * * @return bool|array False if WAF is not enabled, otherwise an array of stats. */ public static function get_waf_stats() { if ( ! Waf_Runner::is_enabled() ) { return false; } return array( 'ipAllowListCount' => Waf_Stats::get_ip_allow_list_count(), 'ipBlockListCount' => Waf_Stats::get_ip_block_list_count(), 'automaticRulesLastUpdated' => Waf_Stats::get_automatic_rules_last_updated(), ); } }
projects/plugins/protect/src/class-rest-controller.php
<?php /** * Class file for managing REST API endpoints for Jetpack Protect. * * @since 1.2.2 * * @package automattic/jetpack-protect-plugin */ namespace Automattic\Jetpack\Protect; use Automattic\Jetpack\Connection\Rest_Authentication as Connection_Rest_Authentication; use Automattic\Jetpack\Waf\Waf_Runner; use Jetpack_Protect; use WP_Error; use WP_REST_Response; /** * Class REST_Controller */ class REST_Controller { /** * Initialize the plugin's REST API. * * @return void */ public static function init() { // Set up the REST authentication hooks. Connection_Rest_Authentication::init(); // Add custom WP REST API endoints. add_action( 'rest_api_init', array( __CLASS__, 'register_rest_endpoints' ) ); } /** * Register the REST API routes. * * @return void */ public static function register_rest_endpoints() { register_rest_route( 'jetpack-protect/v1', 'check-plan', array( 'methods' => \WP_REST_Server::READABLE, 'callback' => __CLASS__ . '::api_check_plan', 'permission_callback' => function () { return current_user_can( 'manage_options' ); }, ) ); register_rest_route( 'jetpack-protect/v1', 'status', array( 'methods' => \WP_REST_Server::READABLE, 'callback' => __CLASS__ . '::api_get_status', 'permission_callback' => function () { return current_user_can( 'manage_options' ); }, ) ); register_rest_route( 'jetpack-protect/v1', 'clear-scan-cache', array( 'methods' => \WP_REST_Server::EDITABLE, 'callback' => __CLASS__ . '::api_clear_scan_cache', 'permission_callback' => function () { return current_user_can( 'manage_options' ); }, ) ); register_rest_route( 'jetpack-protect/v1', 'ignore-threat', array( 'methods' => \WP_REST_Server::EDITABLE, 'callback' => __CLASS__ . '::api_ignore_threat', 'permission_callback' => function () { return current_user_can( 'manage_options' ); }, ) ); register_rest_route( 'jetpack-protect/v1', 'fix-threats', array( 'methods' => \WP_REST_Server::EDITABLE, 'callback' => __CLASS__ . '::api_fix_threats', 'permission_callback' => function () { return current_user_can( 'manage_options' ); }, ) ); register_rest_route( 'jetpack-protect/v1', 'fix-threats-status', array( 'methods' => \WP_REST_Server::READABLE, 'callback' => __CLASS__ . '::api_fix_threats_status', 'permission_callback' => function () { return current_user_can( 'manage_options' ); }, ) ); register_rest_route( 'jetpack-protect/v1', 'check-credentials', array( 'methods' => \WP_REST_Server::EDITABLE, 'callback' => __CLASS__ . '::api_check_credentials', 'permission_callback' => function () { return current_user_can( 'manage_options' ); }, ) ); register_rest_route( 'jetpack-protect/v1', 'scan', array( 'methods' => \WP_REST_Server::EDITABLE, 'callback' => __CLASS__ . '::api_scan', 'permission_callback' => function () { return current_user_can( 'manage_options' ); }, ) ); register_rest_route( 'jetpack-protect/v1', 'toggle-waf', array( 'methods' => \WP_REST_Server::EDITABLE, 'callback' => __CLASS__ . '::api_toggle_waf', 'permission_callback' => function () { return current_user_can( 'manage_options' ); }, ) ); register_rest_route( 'jetpack-protect/v1', 'waf', array( 'methods' => \WP_REST_Server::READABLE, 'callback' => __CLASS__ . '::api_get_waf', 'permission_callback' => function () { return current_user_can( 'manage_options' ); }, ) ); register_rest_route( 'jetpack-protect/v1', 'waf-seen', array( 'methods' => \WP_REST_Server::READABLE, 'callback' => __CLASS__ . '::api_get_waf_seen_status', 'permission_callback' => function () { return current_user_can( 'manage_options' ); }, ) ); register_rest_route( 'jetpack-protect/v1', 'waf-seen', array( 'methods' => \WP_REST_Server::EDITABLE, 'callback' => __CLASS__ . '::api_set_waf_seen_status', 'permission_callback' => function () { return current_user_can( 'manage_options' ); }, ) ); register_rest_route( 'jetpack-protect/v1', 'waf-upgrade-seen', array( 'methods' => \WP_REST_Server::READABLE, 'callback' => __CLASS__ . '::api_get_waf_upgrade_seen_status', 'permission_callback' => function () { return current_user_can( 'manage_options' ); }, ) ); register_rest_route( 'jetpack-protect/v1', 'waf-upgrade-seen', array( 'methods' => \WP_REST_Server::EDITABLE, 'callback' => __CLASS__ . '::api_set_waf_upgrade_seen_status', 'permission_callback' => function () { return current_user_can( 'manage_options' ); }, ) ); register_rest_route( 'jetpack-protect/v1', 'onboarding-progress', array( 'methods' => \WP_REST_Server::READABLE, 'callback' => __CLASS__ . '::api_get_onboarding_progress', 'permission_callback' => function () { return current_user_can( 'manage_options' ); }, ) ); register_rest_route( 'jetpack-protect/v1', 'onboarding-progress', array( 'methods' => \WP_REST_Server::EDITABLE, 'callback' => __CLASS__ . '::api_complete_onboarding_steps', 'permission_callback' => function () { return current_user_can( 'manage_options' ); }, ) ); } /** * Return site plan data for the API endpoint * * @return WP_REST_Response */ public static function api_check_plan() { $has_required_plan = Plan::has_required_plan(); return rest_ensure_response( $has_required_plan, 200 ); } /** * Return Protect Status for the API endpoint * * @param WP_REST_Request $request The request object. * * @return WP_REST_Response */ public static function api_get_status( $request ) { $status = Status::get_status( $request['hard_refresh'] ); return rest_ensure_response( $status, 200 ); } /** * Clear the Scan_Status cache for the API endpoint * * @return WP_REST_Response */ public static function api_clear_scan_cache() { $cache_cleared = Scan_Status::delete_option(); if ( ! $cache_cleared ) { return new WP_REST_Response( 'An error occured while attempting to clear the Jetpack Scan cache.', 500 ); } return new WP_REST_Response( 'Jetpack Scan cache cleared.' ); } /** * Ignores a threat for the API endpoint * * @param WP_REST_Request $request The request object. * * @return WP_REST_Response */ public static function api_ignore_threat( $request ) { if ( ! $request['threat_id'] ) { return new WP_REST_Response( 'Missing threat ID.', 400 ); } $threat_ignored = Threats::ignore_threat( $request['threat_id'] ); if ( ! $threat_ignored ) { return new WP_REST_Response( 'An error occured while attempting to ignore the threat.', 500 ); } return new WP_REST_Response( 'Threat ignored.' ); } /** * Fixes threats for the API endpoint * * @param WP_REST_Request $request The request object. * * @return WP_REST_Response */ public static function api_fix_threats( $request ) { if ( empty( $request['threat_ids'] ) ) { return new WP_REST_Response( 'Missing threat IDs.', 400 ); } $threats_fixed = Threats::fix_threats( $request['threat_ids'] ); if ( ! $threats_fixed ) { return new WP_REST_Response( 'An error occured while attempting to fix the threat.', 500 ); } return new WP_REST_Response( $threats_fixed ); } /** * Fixes threats for the API endpoint * * @param WP_REST_Request $request The request object. * * @return WP_REST_Response */ public static function api_fix_threats_status( $request ) { if ( empty( $request['threat_ids'] ) ) { return new WP_REST_Response( 'Missing threat IDs.', 400 ); } $threats_fixed = Threats::fix_threats_status( $request['threat_ids'] ); if ( ! $threats_fixed ) { return new WP_REST_Response( 'An error occured while attempting to get the fixer status of the threats.', 500 ); } return new WP_REST_Response( $threats_fixed ); } /** * Checks if the site has credentials configured * * @return WP_REST_Response */ public static function api_check_credentials() { $credential_array = Credentials::get_credential_array(); if ( ! isset( $credential_array ) ) { return new WP_REST_Response( 'An error occured while attempting to fetch the credentials array', 500 ); } return new WP_REST_Response( $credential_array ); } /** * Enqueues a scan for the API endpoint * * @return WP_REST_Response */ public static function api_scan() { $scan_enqueued = Threats::scan(); if ( ! $scan_enqueued ) { return new WP_REST_Response( 'An error occured while attempting to enqueue the scan.', 500 ); } return new WP_REST_Response( 'Scan enqueued.' ); } /** * Toggles the WAF module on or off for the API endpoint * * @return WP_REST_Response|WP_Error */ public static function api_toggle_waf() { if ( Waf_Runner::is_enabled() ) { $disabled = Waf_Runner::disable(); if ( ! $disabled ) { return new WP_Error( 'waf_disable_failed', __( 'An error occured disabling the firewall.', 'jetpack-protect' ), array( 'status' => 500 ) ); } return rest_ensure_response( true ); } $enabled = Waf_Runner::enable(); if ( ! $enabled ) { return new WP_Error( 'waf_enable_failed', __( 'An error occured enabling the firewall.', 'jetpack-protect' ), array( 'status' => 500 ) ); } return rest_ensure_response( true ); } /** * Get WAF data for the API endpoint * * @return WP_Rest_Response */ public static function api_get_waf() { // Ensure plugin activation has been performed so WAF module is available. Jetpack_Protect::do_plugin_activation_activities(); return new WP_REST_Response( array( 'is_seen' => Jetpack_Protect::get_waf_seen_status(), 'is_enabled' => Waf_Runner::is_enabled(), 'config' => Waf_Runner::get_config(), 'stats' => Jetpack_Protect::get_waf_stats(), ) ); } /** * Get WAF "Seen" status for the API endpoint * * @return bool Whether the current user has viewed the WAF screen. */ public static function api_get_waf_seen_status() { return Jetpack_Protect::get_waf_seen_status(); } /** * Set WAF "Seen" status for the API endpoint * * @return bool True if seen status updated to true, false on failure. */ public static function api_set_waf_seen_status() { return Jetpack_Protect::set_waf_seen_status(); } /** * Get WAF Upgrade "Seen" Status for the API endpoint * * @return bool Whether the current user has dismissed the upgrade popover or enabled the automatic rules feature. */ public static function api_get_waf_upgrade_seen_status() { return Jetpack_Protect::get_waf_upgrade_seen_status(); } /** * Set WAF Upgrade "Seen" Status for the API endpoint * * @return bool True if upgrade seen status updated to true, false on failure. */ public static function api_set_waf_upgrade_seen_status() { return Jetpack_Protect::set_waf_upgrade_seen_status(); } /** * Gets the current user's onboarding progress for the API endpoint * * @return WP_REST_Response */ public static function api_get_onboarding_progress() { $progress = Onboarding::get_current_user_progress(); return rest_ensure_response( $progress, 200 ); } /** * Set an onboarding step as completed for the API endpoint * * @param WP_REST_Request $request The request object. * * @return WP_REST_Response */ public static function api_complete_onboarding_steps( $request ) { if ( empty( $request['step_ids'] ) || ! is_array( $request['step_ids'] ) ) { return new WP_REST_Response( 'Missing or invalid onboarding step IDs.', 400 ); } $completed = Onboarding::complete_steps( $request['step_ids'] ); if ( ! $completed ) { return new WP_REST_Response( 'An error occured completing the onboarding step(s).', 500 ); } return new WP_REST_Response( 'Onboarding step(s) completed.' ); } }
projects/plugins/protect/src/class-onboarding.php
<?php /** * Class file for managing the user onboarding experience. * * @package automattic/jetpack-protect-plugin */ namespace Automattic\Jetpack\Protect; /** * Onboarding */ class Onboarding { const OPTION_NAME = 'protect_onboarding_progress'; /** * The current user's ID * * @var int */ private static $user_id; /** * Current User Progress * * @var array<string> */ private static $current_user_progress; /** * Onboarding Init * * @return void */ private static function init() { self::$user_id = get_current_user_id(); $current_user_progress = get_user_meta( self::$user_id, self::OPTION_NAME, true ); self::$current_user_progress = $current_user_progress ? $current_user_progress : array(); } /** * Set Onboarding Items As Completed * * @param array $step_ids The IDs of the steps to complete. * @return bool True if the update was successful, false otherwise. */ public static function complete_steps( $step_ids ) { self::init(); if ( empty( self::$current_user_progress ) ) { self::$current_user_progress = $step_ids; } else { // Find step IDs that are not already in the current user progress $new_steps = array_diff( $step_ids, self::$current_user_progress ); // Merge new steps with current progress self::$current_user_progress = array_merge( self::$current_user_progress, $new_steps ); } // Update the user meta only once return (bool) update_user_meta( self::$user_id, self::OPTION_NAME, self::$current_user_progress ); } /** * Get Current User's Onboarding Progress * * @return array<string> */ public static function get_current_user_progress() { self::init(); return self::$current_user_progress; } }
projects/plugins/protect/src/class-threats.php
<?php /** * Class to handle Threats * * @package automattic/jetpack-protect-plugin */ namespace Automattic\Jetpack\Protect; use Automattic\Jetpack\Connection\Client; use Automattic\Jetpack\Connection\Manager as Connection_Manager; use Jetpack_Options; use WP_Error; /** * Class that handles management of individual threats. */ class Threats { /** * Gets the base "Alerts" (Threats) endpoint. * * @return WP_Error|string */ private static function get_api_base() { $blog_id = Jetpack_Options::get_option( 'id' ); $is_connected = ( new Connection_Manager() )->is_connected(); if ( ! $blog_id || ! $is_connected ) { return new WP_Error( 'site_not_connected' ); } $api_url = sprintf( '/sites/%d/alerts', $blog_id ); return $api_url; } /** * Update Threat * * @param string $threat_id The threat ID. * @param array $updates The keys/values to update. * * @return bool */ public static function update_threat( $threat_id, $updates ) { $api_base = self::get_api_base( $threat_id ); if ( is_wp_error( $api_base ) ) { return false; } $response = Client::wpcom_json_api_request_as_user( "$api_base/$threat_id", '2', array( 'method' => 'POST' ), wp_json_encode( $updates ), 'wpcom' ); $response_code = wp_remote_retrieve_response_code( $response ); if ( is_wp_error( $response ) || 200 !== $response_code ) { return false; } // clear the now out-of-date cache Scan_Status::delete_option(); return true; } /** * Ignore Threat * * @param string $threat_id The threat ID. * * @return bool */ public static function ignore_threat( $threat_id ) { return self::update_threat( $threat_id, array( 'ignore' => true ) ); } /** * Fix Threats * * @param array<string> $threat_ids Threat IDs. * * @return bool|array */ public static function fix_threats( $threat_ids ) { $api_base = self::get_api_base(); if ( is_wp_error( $api_base ) ) { return false; } $response = Client::wpcom_json_api_request_as_user( "$api_base/fix", '2', array( 'method' => 'POST' ), wp_json_encode( array( 'threat_ids' => $threat_ids, ) ), 'wpcom' ); $response_code = wp_remote_retrieve_response_code( $response ); if ( is_wp_error( $response ) || 200 !== $response_code ) { return false; } // clear the now out-of-date cache Scan_Status::delete_option(); $parsed_response = json_decode( $response['body'] ); if ( ! $parsed_response ) { return false; } return $parsed_response; } /** * Fix Threats Status * * @param array<string> $threat_ids Threat IDs. * * @return bool|array */ public static function fix_threats_status( $threat_ids ) { $api_base = self::get_api_base(); if ( is_wp_error( $api_base ) ) { return false; } $response = Client::wpcom_json_api_request_as_user( add_query_arg( 'threat_ids', $threat_ids, "$api_base/fix" ), '2', array( 'method' => 'GET' ), null, 'wpcom' ); $response_code = wp_remote_retrieve_response_code( $response ); if ( is_wp_error( $response ) || 200 !== $response_code ) { return false; } $parsed_response = json_decode( $response['body'] ); if ( ! $parsed_response ) { return false; } // clear the potentially out-of-date cache Scan_Status::delete_option(); return $parsed_response; } /** * Scan enqueue * * @return bool */ public static function scan() { $blog_id = Jetpack_Options::get_option( 'id' ); $is_connected = ( new Connection_Manager() )->is_connected(); if ( ! $blog_id || ! $is_connected ) { return false; } $api_base = sprintf( '/sites/%d/scan', $blog_id ); if ( is_wp_error( $api_base ) ) { return false; } $response = Client::wpcom_json_api_request_as_blog( "$api_base/enqueue", '2', array( 'method' => 'POST' ), null, 'wpcom' ); $response_code = wp_remote_retrieve_response_code( $response ); if ( is_wp_error( $response ) || 200 !== $response_code ) { return false; } // clear the now out-of-date cache Scan_Status::delete_option(); return true; } }
projects/plugins/protect/src/class-site-health.php
<?php /** * Class to handle the Check in the Site Health admin page * * @package automattic/jetpack-protect-plugin */ namespace Automattic\Jetpack\Protect; /** * Site_Health. * * Displays threats in WordPress site health page. */ class Site_Health { /** * Initialize hooks * * @access public * @return void */ public static function init() { if ( ! has_filter( 'site_status_tests', array( __CLASS__, 'add_check' ) ) ) { add_filter( 'site_status_tests', array( __CLASS__, 'add_check' ), 99 ); } } /** * Add site-health page tests. * * @param array $checks Core checks. * * @access public * @return array */ public static function add_check( $checks ) { $checks['direct']['jetpack_protect_checks'] = array( 'label' => __( 'Jetpack Protect checks', 'jetpack-protect' ), 'test' => array( __CLASS__, 'do_checks' ), ); return $checks; } /** * Do site-health page checks * * @access public * @return array */ public static function do_checks() { $total_threats = Status::get_total_threats(); $threats = Status::get_all_threats(); $threats = array_map( function ( $v ) { return $v->title; }, $threats ); /** * Default, no threats found */ $result = array( 'label' => __( 'No known threats found', 'jetpack-protect' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Security', 'jetpack-protect' ), 'color' => 'gray', ), 'description' => sprintf( '<p>%s</p>', __( 'Jetpack Protect did not find any known threats in your site. Threats can be exploited by hackers and cause harm to your website.', 'jetpack-protect' ) ), 'actions' => '', 'test' => 'jetpack_protect_checks', ); /** * If threats found. */ if ( $total_threats ) { $result['status'] = 'critical'; /* translators: $d is the number of threats found. */ $result['label'] = sprintf( _n( 'Your site is affected by %d security threat', 'Your site is affected by %d security threats', $total_threats, 'jetpack-protect' ), $total_threats ); $result['description'] = __( 'Jetpack Protect detected the following security threats in your site:', 'jetpack-protect' ); foreach ( $threats as $threat ) { $result['description'] .= '<p>'; $result['description'] .= "<span class='dashicons dashicons-warning' style='color: crimson;'></span> &nbsp"; $result['description'] .= wp_kses( $threat, array( 'a' => array( 'href' => array() ) ) ); // Only allow a href HTML tags. $result['description'] .= '</p>'; } $result['description'] .= '<p>'; $result['description'] .= sprintf( wp_kses( /* translators: Link to Jetpack Protect. */ __( 'See <a href="%s">Protect overview page</a> for more information.', 'jetpack-protect' ), array( 'a' => array( 'href' => array() ), ) ), esc_url( admin_url( 'admin.php?page=jetpack-protect' ) ) ); $result['description'] .= '</p>'; } return $result; } }
projects/plugins/protect/src/class-scan-status.php
<?php /** * Class to handle the Scan Status of Jetpack Protect * * @package automattic/jetpack-protect-plugin */ namespace Automattic\Jetpack\Protect; use Automattic\Jetpack\Connection\Client; use Automattic\Jetpack\Connection\Manager as Connection_Manager; use Automattic\Jetpack\Plugins_Installer; use Automattic\Jetpack\Sync\Functions as Sync_Functions; use Jetpack_Options; use WP_Error; /** * Class that handles fetching of threats from the Scan API */ class Scan_Status extends Status { /** * Scan endpoint * * @var string */ const SCAN_API_BASE = '/sites/%d/scan'; /** * Name of the option where status is stored * * @var string */ const OPTION_NAME = 'jetpack_scan_status'; /** * Name of the option where the timestamp of the status is stored * * @var string */ const OPTION_TIMESTAMP_NAME = 'jetpack_scan_status_timestamp'; /** * Time in seconds that the cache should last * * @var int */ const OPTION_EXPIRES_AFTER = 300; // 5 minutes. /** * Gets the current status of the Jetpack Protect checks * * @param bool $refresh_from_wpcom Refresh the local plan and status cache from wpcom. * @return Status_Model */ public static function get_status( $refresh_from_wpcom = false ) { if ( self::$status !== null ) { return self::$status; } if ( $refresh_from_wpcom || ! self::should_use_cache() || self::is_cache_expired() ) { $status = self::fetch_from_api(); } else { $status = self::get_from_options(); } if ( is_wp_error( $status ) ) { $status = new Status_Model( array( 'error' => true, 'error_code' => $status->get_error_code(), 'error_message' => $status->get_error_message(), ) ); } else { $status = self::normalize_api_data( $status ); } self::$status = $status; return $status; } /** * Gets the Scan API endpoint * * @return WP_Error|string */ public static function get_api_url() { $blog_id = Jetpack_Options::get_option( 'id' ); $is_connected = ( new Connection_Manager() )->is_connected(); if ( ! $blog_id || ! $is_connected ) { return new WP_Error( 'site_not_connected' ); } $api_url = sprintf( self::SCAN_API_BASE, $blog_id ); return $api_url; } /** * Fetches the status data from the Scan API * * @return WP_Error|array */ public static function fetch_from_api() { $api_url = self::get_api_url(); if ( is_wp_error( $api_url ) ) { return $api_url; } $response = Client::wpcom_json_api_request_as_blog( self::get_api_url(), '2', array( 'method' => 'GET' ), null, 'wpcom' ); $response_code = wp_remote_retrieve_response_code( $response ); if ( is_wp_error( $response ) || 200 !== $response_code || empty( $response['body'] ) ) { return new WP_Error( 'failed_fetching_status', 'Failed to fetch Scan data from the server', array( 'status' => $response_code ) ); } $body = json_decode( wp_remote_retrieve_body( $response ) ); self::update_status_option( $body ); return $body; } /** * Normalize API Data * Formats the payload from the Scan API into an instance of Status_Model. * * @param object $scan_data The data returned by the scan API. * * @return Status_Model */ private static function normalize_api_data( $scan_data ) { global $wp_version; $status = new Status_Model(); $status->data_source = 'scan_api'; $status->status = isset( $scan_data->state ) ? $scan_data->state : null; $status->num_threats = 0; $status->num_themes_threats = 0; $status->num_plugins_threats = 0; $status->has_unchecked_items = false; $status->current_progress = isset( $scan_data->current->progress ) ? $scan_data->current->progress : null; if ( ! empty( $scan_data->most_recent->timestamp ) ) { $date = new \DateTime( $scan_data->most_recent->timestamp ); if ( $date ) { $status->last_checked = $date->format( 'Y-m-d H:i:s' ); } } $status->core = new Extension_Model( array( 'type' => 'core', 'name' => 'WordPress', 'version' => $wp_version, 'checked' => true, // to do: default to false once Scan API has manifest ) ); if ( isset( $scan_data->threats ) && is_array( $scan_data->threats ) ) { foreach ( $scan_data->threats as $threat ) { if ( isset( $threat->extension->type ) ) { if ( 'plugin' === $threat->extension->type ) { // add the extension if it does not yet exist in the status if ( ! isset( $status->plugins[ $threat->extension->slug ] ) ) { $status->plugins[ $threat->extension->slug ] = new Extension_Model( array( 'name' => isset( $threat->extension->name ) ? $threat->extension->name : null, 'slug' => isset( $threat->extension->slug ) ? $threat->extension->slug : null, 'version' => isset( $threat->extension->version ) ? $threat->extension->version : null, 'type' => 'plugin', 'checked' => true, 'threats' => array(), ) ); } $status->plugins[ $threat->extension->slug ]->threats[] = new Threat_Model( array( 'id' => isset( $threat->id ) ? $threat->id : null, 'signature' => isset( $threat->signature ) ? $threat->signature : null, 'title' => isset( $threat->title ) ? $threat->title : null, 'description' => isset( $threat->description ) ? $threat->description : null, 'vulnerability_description' => isset( $threat->vulnerability_description ) ? $threat->vulnerability_description : null, 'fix_description' => isset( $threat->fix_description ) ? $threat->fix_description : null, 'payload_subtitle' => isset( $threat->payload_subtitle ) ? $threat->payload_subtitle : null, 'payload_description' => isset( $threat->payload_description ) ? $threat->payload_description : null, 'first_detected' => isset( $threat->first_detected ) ? $threat->first_detected : null, 'fixed_in' => isset( $threat->fixer->fixer ) && 'update' === $threat->fixer->fixer ? $threat->fixer->target : null, 'severity' => isset( $threat->severity ) ? $threat->severity : null, 'fixable' => isset( $threat->fixer ) ? $threat->fixer : null, 'status' => isset( $threat->status ) ? $threat->status : null, 'filename' => isset( $threat->filename ) ? $threat->filename : null, 'context' => isset( $threat->context ) ? $threat->context : null, 'source' => isset( $threat->source ) ? $threat->source : null, ) ); ++$status->num_threats; ++$status->num_plugins_threats; continue; } if ( 'theme' === $threat->extension->type ) { // add the extension if it does not yet exist in the status if ( ! isset( $status->themes[ $threat->extension->slug ] ) ) { $status->themes[ $threat->extension->slug ] = new Extension_Model( array( 'name' => isset( $threat->extension->name ) ? $threat->extension->name : null, 'slug' => isset( $threat->extension->slug ) ? $threat->extension->slug : null, 'version' => isset( $threat->extension->version ) ? $threat->extension->version : null, 'type' => 'theme', 'checked' => true, 'threats' => array(), ) ); } $status->themes[ $threat->extension->slug ]->threats[] = new Threat_Model( array( 'id' => isset( $threat->id ) ? $threat->id : null, 'signature' => isset( $threat->signature ) ? $threat->signature : null, 'title' => isset( $threat->title ) ? $threat->title : null, 'description' => isset( $threat->description ) ? $threat->description : null, 'vulnerability_description' => isset( $threat->vulnerability_description ) ? $threat->vulnerability_description : null, 'fix_description' => isset( $threat->fix_description ) ? $threat->fix_description : null, 'payload_subtitle' => isset( $threat->payload_subtitle ) ? $threat->payload_subtitle : null, 'payload_description' => isset( $threat->payload_description ) ? $threat->payload_description : null, 'first_detected' => isset( $threat->first_detected ) ? $threat->first_detected : null, 'fixed_in' => isset( $threat->fixer->fixer ) && 'update' === $threat->fixer->fixer ? $threat->fixer->target : null, 'severity' => isset( $threat->severity ) ? $threat->severity : null, 'fixable' => isset( $threat->fixer ) ? $threat->fixer : null, 'status' => isset( $threat->status ) ? $threat->status : null, 'filename' => isset( $threat->filename ) ? $threat->filename : null, 'context' => isset( $threat->context ) ? $threat->context : null, 'source' => isset( $threat->source ) ? $threat->source : null, ) ); ++$status->num_threats; ++$status->num_themes_threats; continue; } } if ( isset( $threat->signature ) && 'Vulnerable.WP.Core' === $threat->signature ) { if ( $threat->version !== $wp_version ) { continue; } $status->core->threats[] = new Threat_Model( array( 'id' => $threat->id, 'signature' => $threat->signature, 'title' => $threat->title, 'description' => $threat->description, 'first_detected' => $threat->first_detected, 'severity' => $threat->severity, ) ); ++$status->num_threats; continue; } if ( ! empty( $threat->filename ) ) { $status->files[] = new Threat_Model( $threat ); ++$status->num_threats; continue; } if ( ! empty( $threat->table ) ) { $status->database[] = new Threat_Model( $threat ); ++$status->num_threats; continue; } } } $installed_plugins = Plugins_Installer::get_plugins(); $status->plugins = self::merge_installed_and_checked_lists( $installed_plugins, $status->plugins, array( 'type' => 'plugins' ), true ); $installed_themes = Sync_Functions::get_themes(); $status->themes = self::merge_installed_and_checked_lists( $installed_themes, $status->themes, array( 'type' => 'themes' ), true ); foreach ( array_merge( $status->themes, $status->plugins ) as $extension ) { if ( ! $extension->checked ) { $status->has_unchecked_items = true; break; } } return $status; } /** * Merges the list of installed extensions with the list of extensions that were checked for known vulnerabilities and return a normalized list to be used in the UI * * @param array $installed The list of installed extensions, where each attribute key is the extension slug. * @param object $checked The list of checked extensions. * @param array $append Additional data to append to each result in the list. * @return array Normalized list of extensions. */ protected static function merge_installed_and_checked_lists( $installed, $checked, $append ) { $new_list = array(); $checked = (object) $checked; foreach ( array_keys( $installed ) as $slug ) { /** * Extension Type Map * * @var array $extension_type_map Key value pairs of extension types and their corresponding * identifier used by the Scan API data source. */ $extension_type_map = array( 'themes' => 'r1', 'plugins' => 'r2', ); $version = $installed[ $slug ]['Version']; $short_slug = str_replace( '.php', '', explode( '/', $slug )[0] ); $scanifest_slug = $extension_type_map[ $append['type'] ] . ":$short_slug@$version"; $extension = new Extension_Model( array_merge( array( 'name' => $installed[ $slug ]['Name'], 'version' => $version, 'slug' => $slug, 'threats' => array(), 'checked' => false, ), $append ) ); if ( ! isset( $checked->extensions ) // no extension data available from Scan API || is_array( $checked->extensions ) && in_array( $scanifest_slug, $checked->extensions, true ) // extension data matches Scan API ) { $extension->checked = true; if ( isset( $checked->{ $short_slug }->threats ) ) { $extension->threats = $checked->{ $short_slug }->threats; } } $new_list[] = $extension; } $new_list = parent::sort_threats( $new_list ); return $new_list; } }
projects/plugins/protect/src/class-plan.php
<?php /** * Class to handle the Protect plan * * @package automattic/jetpack-protect-plugin */ namespace Automattic\Jetpack\Protect; use Automattic\Jetpack\Current_Plan; /** * The Plan class. */ class Plan { /** * The meta name used to store the cache date * * @var string */ const CACHE_DATE_META_NAME = 'protect-cache-date'; /** * Valid pediord for the cache: One week. */ const CACHE_VALIDITY_PERIOD = 7 * DAY_IN_SECONDS; /** * The meta name used to store the cache * * @var string */ const CACHE_META_NAME = 'protect-cache'; /** * Checks if the cache is old, meaning we need to fetch new data from WPCOM */ private static function is_cache_old() { if ( empty( self::get_product_from_cache() ) ) { return true; } $cache_date = get_user_meta( get_current_user_id(), self::CACHE_DATE_META_NAME, true ); return time() - (int) $cache_date > ( self::CACHE_VALIDITY_PERIOD ); } /** * Gets the product list from the user cache */ private static function get_product_from_cache() { return get_user_meta( get_current_user_id(), self::CACHE_META_NAME, true ); } /** * Gets the product data * * @param string $wpcom_product The product slug. * @return array */ public static function get_product( $wpcom_product = 'jetpack_scan' ) { if ( ! self::is_cache_old() ) { return self::get_product_from_cache(); } $request_url = 'https://public-api.wordpress.com/rest/v1.1/products?locale=' . get_user_locale() . '&type=jetpack'; $wpcom_request = wp_remote_get( esc_url_raw( $request_url ) ); $response_code = wp_remote_retrieve_response_code( $wpcom_request ); if ( 200 === $response_code ) { $products = json_decode( wp_remote_retrieve_body( $wpcom_request ) ); // Pick the desired product... $product = $products->{$wpcom_product}; // ... and store it into the cache. update_user_meta( get_current_user_id(), self::CACHE_DATE_META_NAME, time() ); update_user_meta( get_current_user_id(), self::CACHE_META_NAME, $product ); return $product; } return new \WP_Error( 'failed_to_fetch_data', esc_html__( 'Unable to fetch the requested data.', 'jetpack-protect' ), array( 'status' => $response_code, 'request' => $wpcom_request, ) ); } /** * Has Required Plan * * @param bool $force_refresh Refresh the local plan cache from wpcom. * @return bool True when the site has a plan or product that supports the paid Protect tier. */ public static function has_required_plan( $force_refresh = false ) { static $has_scan = null; if ( null === $has_scan || $force_refresh ) { $products = array_column( Current_Plan::get_products(), 'product_slug' ); // Check for a plan or product that enables scan. $plan_supports_scan = Current_Plan::supports( 'scan', true ); $has_scan_product = count( array_intersect( array( 'jetpack_scan', 'jetpack_scan_monthly' ), $products ) ) > 0; $has_scan = $plan_supports_scan || $has_scan_product; } return $has_scan; } }
projects/plugins/protect/src/models/class-extension-model.php
<?php /** * Model class for extensions. * * @package automattic/jetpack-protect-plugin */ namespace Automattic\Jetpack\Protect; /** * Model class for extension data. */ class Extension_Model { /** * The extension name. * * @var null|string */ public $name; /** * The extension slug. * * @var null|string */ public $slug; /** * The extension version. * * @var null|string */ public $version; /** * A collection of threats related to this version of the extension. * * @var array<Threat_Model> */ public $threats = array(); /** * Whether the extension has been checked for threats. * * @var null|bool */ public $checked; /** * The type of extension ("plugins", "themes", or "core"). * * @var null|string */ public $type; /** * Extension Model Constructor * * @param array|object $extension Extension data to load into the model instance. */ public function __construct( $extension = array() ) { if ( is_object( $extension ) ) { $extension = (array) $extension; } foreach ( $extension as $property => $value ) { if ( property_exists( $this, $property ) ) { // use the property's setter method when possible if ( method_exists( $this, "set_$property" ) ) { $this->{ "set_$property" }( $value ); continue; } // otherwise, map the value directly into the class property $this->$property = $value; } } } /** * Set Threats * * @param array<Threat_Model|array|object> $threats An array of threat data to add to the extension. */ public function set_threats( $threats ) { if ( ! is_array( $threats ) ) { $this->threats = array(); return; } // convert each provided threat item into an instance of Threat_Model $threats = array_map( function ( $threat ) { if ( is_a( $threat, 'Threat_Model' ) ) { return $threat; } if ( is_object( $threat ) ) { $threat = (array) $threat; } return new Threat_Model( $threat ); }, $threats ); $this->threats = $threats; } }
projects/plugins/protect/src/models/class-threat-model.php
<?php /** * Model class for threat data. * * @package automattic/jetpack-protect-plugin */ namespace Automattic\Jetpack\Protect; /** * Model class for threat data. */ class Threat_Model { /** * Threat ID. * * @var null|string */ public $id; /** * Threat Signature. * * @var null|string */ public $signature; /** * Threat Title. * * @var null|string */ public $title; /** * Threat Description. * * @var null|string */ public $description; /** * The data the threat was first detected. * * @var null|string */ public $first_detected; /** * The version the threat is fixed in. * * @var null|string */ public $fixed_in; /** * The severity of the threat between 1-5. * * @var null|int */ public $severity; /** * Information about the auto-fix available for this threat. False when not auto-fixable. * * @var null|bool|object */ public $fixable; /** * The current status of the threat. * * @var null|string */ public $status; /** * The filename of the threat. * * @var null|string */ public $filename; /** * The context of the threat. * * @var null|object */ public $context; /** * The source URL of the threat. * * @var null|string */ public $source; /** * Threat Constructor * * @param array|object $threat Threat data to load into the class instance. */ public function __construct( $threat ) { if ( is_object( $threat ) ) { $threat = (array) $threat; } foreach ( $threat as $property => $value ) { if ( property_exists( $this, $property ) ) { $this->$property = $value; } } } }
projects/plugins/protect/src/models/class-status-model.php
<?php /** * Model class for Protect status report data. * * @package automattic/jetpack-protect-plugin */ namespace Automattic\Jetpack\Protect; /** * Model class for the Protect status report data. */ class Status_Model { /** * Data source. * * @var string protect_report|scan_api */ public $data_source; /** * The date and time when the status was generated. * * @var string */ public $last_checked; /** * The number of threats. * * @var int */ public $num_threats; /** * The number of plugin threats. * * @var int */ public $num_plugins_threats; /** * The number of theme threats. * * @var int */ public $num_themes_threats; /** * The current report status. * * @var string in_progress|scheduled|idle|scanning|provisioning|unavailable */ public $status; /** * WordPress core status. * * @var object */ public $core; /** * Status themes. * * @var array<Extension_Model> */ public $themes = array(); /** * Status plugins. * * @var array<Extension_Model> */ public $plugins = array(); /** * File threats. * * @var array<Extension_Model> */ public $files = array(); /** * Database threats. * * @var array<Extension_Model> */ public $database = array(); /** * Whether the site includes items that have not been checked. * * @var boolean */ public $has_unchecked_items; /** * The estimated percentage of the current scan. * * @var int */ public $current_progress; /** * Whether there was an error loading the status. * * @var bool */ public $error = false; /** * The error code thrown when loading the status. * * @var string */ public $error_code; /** * The error message thrown when loading the status. * * @var string */ public $error_message; /** * Status constructor. * * @param array $status The status data to load into the class instance. */ public function __construct( $status = array() ) { // set status defaults $this->core = new \stdClass(); foreach ( $status as $property => $value ) { if ( property_exists( $this, $property ) ) { $this->$property = $value; } } } }
projects/plugins/mu-wpcom-plugin/mu-wpcom-plugin.php
<?php /** * * Plugin Name: WordPress.com Features * Description: Test plugin for the jetpack-mu-wpcom package * Version: 2.1.1 * Author: Automattic * License: GPLv2 or later * Text Domain: jetpack-mu-wpcom-plugin * * @package automattic/jetpack-mu-wpcom-plugin */ /** * Conditionally load the jetpack-mu-wpcom package. * * JETPACK_MU_WPCOM_LOAD_VIA_BETA_PLUGIN=true will load the package via the Jetpack Beta Tester plugin, not wpcomsh. */ if ( defined( 'JETPACK_MU_WPCOM_LOAD_VIA_BETA_PLUGIN' ) && JETPACK_MU_WPCOM_LOAD_VIA_BETA_PLUGIN ) { require_once __DIR__ . '/vendor/autoload.php'; if ( class_exists( 'Automattic\Jetpack\Jetpack_Mu_Wpcom' ) ) { Automattic\Jetpack\Jetpack_Mu_Wpcom::init(); } }
projects/plugins/mu-wpcom-plugin/tests/php/bootstrap.php
<?php /** * Bootstrap. * * @package automattic/ */ /** * Include the composer autoloader. */ require_once __DIR__ . '/../../vendor/autoload.php';
projects/plugins/crm/ZeroBSCRM.php
<?php /** * Plugin Name: Jetpack CRM * Plugin URI: https://jetpackcrm.com * Description: Jetpack CRM is the simplest CRM for WordPress. Self host your own Customer Relationship Manager using WP. * Version: 6.4.2-alpha * Author: Automattic - Jetpack CRM team * Author URI: https://jetpackcrm.com * Text Domain: zero-bs-crm * Requires at least: 6.0 * Requires PHP: 7.4 * License: GPLv2 * License URI: http://www.gnu.org/licenses/gpl-2.0.html */ /* ====================================================== Breaking Checks ====================================================== */ // stops direct access if ( ! defined( 'ABSPATH' ) ) { exit; } // Enabling THIS will start LOGGING PERFORMANCE TESTS // NOTE: This will do for EVERY page load, so just add temporarily else adds rolling DRAIN on sys // define( 'ZBSPERFTEST', 1 ); if ( ! defined( 'ZBS_ROOTFILE' ) ) { define( 'ZBS_ROOTFILE', __FILE__ ); define( 'ZBS_PLUGIN_DIR', plugin_dir_path( __FILE__ ) ); define( 'ZBS_ROOTDIR', basename( __DIR__ ) ); define( 'ZBS_ROOTPLUGIN', ZBS_ROOTDIR . '/' . basename( ZBS_ROOTFILE ) ); define( 'ZBS_LANG_DIR', basename( __DIR__ ) . '/languages' ); } /** * Jetpack Autoloader. */ $jetpack_autoloader = ZBS_PLUGIN_DIR . 'vendor/autoload_packages.php'; if ( is_readable( $jetpack_autoloader ) ) { require_once $jetpack_autoloader; if ( method_exists( \Automattic\Jetpack\Assets::class, 'alias_textdomains_from_file' ) ) { \Automattic\Jetpack\Assets::alias_textdomains_from_file( ZBS_PLUGIN_DIR . 'jetpack_vendor/i18n-map.php' ); } } else { // Something very unexpected. Error out gently with an admin_notice and exit loading. if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log __( 'Error loading autoloader file for Jetpack CRM plugin', 'zero-bs-crm' ) ); } add_action( 'admin_notices', function () { ?> <div class="notice notice-error is-dismissible"> <p> <?php printf( wp_kses( /* translators: Placeholder is a link to a support document. */ __( 'Your installation of Jetpack CRM is incomplete. If you installed Jetpack CRM from GitHub, please refer to <a href="%1$s" target="_blank" rel="noopener noreferrer">this document</a> to set up your development environment. Jetpack CRM must have Composer dependencies installed and built via the build command.', 'zero-bs-crm' ), array( 'a' => array( 'href' => array(), 'target' => array(), 'rel' => array(), ), ) ), 'https://github.com/Automattic/jetpack/blob/trunk/docs/development-environment.md#building-your-project' ); ?> </p> </div> <?php } ); return; } /** * Performs some checks before the plugin activation * * @param $plugin */ function jpcrm_activation_checks( $plugin ) { jpcrm_check_api_connector(); } add_action( 'activate_plugin', 'jpcrm_activation_checks', 10, 2 ); /** * Check for the minimum PHP version * * @return bool */ function jpcrm_check_min_php_version() { $min_php_version = '7.4'; if ( version_compare( PHP_VERSION, $min_php_version, '<' ) ) { $error_message = sprintf( __( 'Jetpack CRM requires PHP version %1$s or greater. Older versions of PHP are no longer supported. Your current version of PHP is %2$s.', 'zero-bs-crm' ), $min_php_version, PHP_VERSION ); $error_message .= '<br><a href="https://kb.jetpackcrm.com/knowledge-base/php-version-jetpack-crm/" target="_blank">' . __( 'Click here for more information', 'zero-bs-crm' ) . '</a>'; jpcrm_register_admin_notice( 'error', $error_message ); return false; } return true; } /** * Determines if dev mode is enabled with JPCRM_DEVOVERRIDE constant * * @return bool */ function jpcrm_is_devmode_override() { if ( defined( 'JPCRM_DEVOVERRIDE' ) ) { return true; } return false; } /** * Check if the plugin API Connector is installed */ function jpcrm_check_api_connector() { global $zbs; if ( class_exists( 'ZeroBSCRM_APIConnector' ) ) { $error_msg = '<b>' . __( 'API Connector is currently installed and activated on this site.', 'zero-bs-crm' ) . '</b>'; $error_msg .= '<br>' . __( 'API Connector is a plugin used to connect external websites to your CRM. You should not install it on the same website as your CRM. Please deactivate it first if you plan to install the CRM on this site.', 'zero-bs-crm' ); $error_msg .= '<br><br><a href="' . $zbs->urls['kbapi'] . '">' . __( 'Learn more', 'zero-bs-crm' ) . '</a>'; wp_die( $error_msg ); } } /** * Verifies various critical checks pass: * - PHP version */ function jpcrm_do_critical_prerun_checks() { $all_clear = true; if ( ! jpcrm_check_min_php_version() ) { $all_clear = false; } // yay, all clear if ( $all_clear ) { return true; } // at this point something failed, so disable this plugin $error_message = __( 'Jetpack CRM was unable to load and has been deactivated.', 'zero-bs-crm' ); jpcrm_register_admin_notice( 'error', $error_message ); // this file isn't always available, so include it in case require_once ABSPATH . 'wp-admin/includes/plugin.php'; deactivate_plugins( __FILE__ ); // if the plugin was just activated, this keeps it from saying "plugin activated" if ( isset( $_GET['activate'] ) ) { unset( $_GET['activate'] ); } return false; } /** * Show admin notice with `admin_notices` action * * @param string $notice_class e.g. "error"|"notice" * @param string $message */ function jpcrm_register_admin_notice( $notice_class, $message ) { $admin_notice_fn = function () use ( $notice_class, $message ) { jpcrm_show_admin_notice( $notice_class, $message ); }; add_action( 'admin_notices', $admin_notice_fn ); } /** * Show admin notice * * @param string $notice_class e.g. "error"|"notice" * @param string $message */ function jpcrm_show_admin_notice( $notice_class, $message ) { ?> <div class="<?php echo esc_attr( $notice_class ); ?>"> <p> <?php echo $message; ?> </p> </div> <?php } // ==================================================================== // ================= Legacy (pre v2.53) Support ====================== // LEGACY SUPPORT - all ext settings global $zbsLegacySupport; $zbsLegacySupport = array( 'extsettingspostinit' => array() ); // support for old - to be removed in time. global $zeroBSCRM_Settings; // this gets run post init :) function zeroBSCRM_legacySupport() { // map old global, for NOW... remove once all ext's removed // only needed in old wh.config.lib's, which we can replace now :) global $zeroBSCRM_Settings, $zbs, $zbsLegacySupport; $zeroBSCRM_Settings = $zbs->settings; if ( count( $zbsLegacySupport ) > 0 ) { foreach ( $zbsLegacySupport as $key => $defaultConfig ) { // init with a throwaway var (just get) // this checks is the setting is accessible, and if not (fresh installs) then uses the caught defaultConfig from wh.config.lib legacy support $existingSettings = $zbs->settings->dmzGetConfig( $key ); // Create if not existing if ( ! is_array( $existingSettings ) ) { // init $zbs->settings->dmzUpdateConfig( $key, $defaultConfig ); } } // / foreach loaded with legacy support } } // legacy support for removal of _we() - to be fixed in ext // still used in a few plugins as of 1922-07-28 if ( ! function_exists( '_we' ) ) { function _we( $str, $domain = 'zero-bs-crm' ) { _e( $str, $domain ); } function __w( $str, $domain = 'zero-bs-crm' ) { // phpcs:ignore PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore -- legacy return __( $str, $domain ); } } // ================ / Legacy (pre v2.53) Support ====================== // ==================================================================== // ==================================================================== // ==================== General Perf Testing ========================== function zeroBSCRM_init_perfTest() { if ( defined( 'ZBSPERFTEST' ) && zeroBSCRM_isWPAdmin() ) { // retrieve our global (may have had any number of test res added) global $zbsPerfTest; // If admin, clear any prev perf test ifset if ( isset( $_GET['delperftest'] ) ) { delete_option( 'zbs-global-perf-test' ); } // retrieve opt + add to it (up to 50 tests) $zbsPerfTestOpt = get_option( 'zbs-global-perf-test', array() ); if ( is_array( $zbsPerfTestOpt ) && count( $zbsPerfTestOpt ) < 50 ) { // add $zbsPerfTestOpt[] = $zbsPerfTest; // save update_option( 'zbs-global-perf-test', $zbsPerfTestOpt, false ); } } } // =================== / General Perf Testing ========================= // ==================================================================== // ==================================================================== // ================= Main Include ==================================== if ( jpcrm_do_critical_prerun_checks() ) { // full perf test mode if ( defined( 'ZBSPERFTEST' ) ) { // store a global arr for this "test" global $zbsPerfTest; $zbsPerfTest = array( 'init' => time(), 'get' => $_GET, 'results' => array(), ); // include if not already if ( ! function_exists( 'zeroBSCRM_performanceTest_finishTimer' ) ) { include_once __DIR__ . '/includes/ZeroBSCRM.PerformanceTesting.php'; } // start timer zeroBSCRM_performanceTest_startTimer( 'plugin-load' ); } // Include the main Jetpack CRM class. if ( ! class_exists( 'ZeroBSCRM' ) ) { include_once __DIR__ . '/includes/ZeroBSCRM.Core.php'; } // Initiate ZBS Main Core global $zbs; $zbs = ZeroBSCRM::instance(); // close timer (at this point we'll have perf library) if ( defined( 'ZBSPERFTEST' ) ) { // retrieve our global (may have had any number of test res added) global $zbsPerfTest; // close it zeroBSCRM_performanceTest_finishTimer( 'plugin-load' ); // store in perf-reports $zbsPerfTest['results']['plugin-load'] = zeroBSCRM_performanceTest_results( 'plugin-load' ); // here we basically wait for init so we can check user is wp admin // ... only saving perf logs if defined + wp admin add_action( 'shutdown', 'zeroBSCRM_init_perfTest' ); } } // ================ / Main Include ==================================== // ====================================================================
projects/plugins/crm/tests/codeception/_support/AcceptanceTester.php
<?php /** * Inherited Methods * * @method void wantToTest($text) * @method void wantTo($text) * @method void execute($callable) * @method void expectTo($prediction) * @method void expect($prediction) * @method void amGoingTo($argumentation) * @method void am($role) * @method void lookForwardTo($achieveValue) * @method void comment($description) * @method void pause() * * @SuppressWarnings(PHPMD) */ class AcceptanceTester extends \Codeception\Actor { use _generated\AcceptanceTesterActions; /** * Define custom actions here */ protected $pages = array( 'dashboard' => 'zerobscrm-dash', 'contacts' => 'manage-customers', 'quotes' => 'manage-quotes', 'invoices' => 'manage-invoices', 'transactions' => 'manage-transactions', 'tasks' => 'manage-tasks', 'settings' => 'zerobscrm-plugin-settings', 'extensions' => 'zerobscrm-extensions', 'add-edit' => 'zbs-add-edit', ); public function gotoAdminPage( $page_name, $query = '' ) { $this->amOnAdminPage( 'admin.php?page=' . $this->pages[ $page_name ] . $query ); } }
projects/plugins/crm/tests/codeception/_support/FunctionalTester.php
<?php /** * Inherited Methods * * @method void wantToTest($text) * @method void wantTo($text) * @method void execute($callable) * @method void expectTo($prediction) * @method void expect($prediction) * @method void amGoingTo($argumentation) * @method void am($role) * @method void lookForwardTo($achieveValue) * @method void comment($description) * @method void pause() * * @SuppressWarnings(PHPMD) */ class FunctionalTester extends \Codeception\Actor { use _generated\FunctionalTesterActions; /** * Define custom actions here */ }
projects/plugins/crm/tests/codeception/_support/UnitTester.php
<?php /** * Inherited Methods * * @method void wantToTest($text) * @method void wantTo($text) * @method void execute($callable) * @method void expectTo($prediction) * @method void expect($prediction) * @method void amGoingTo($argumentation) * @method void am($role) * @method void lookForwardTo($achieveValue) * @method void comment($description) * @method void pause() * * @SuppressWarnings(PHPMD) */ class UnitTester extends \Codeception\Actor { use _generated\UnitTesterActions; /** * Define custom actions here */ }
projects/plugins/crm/tests/codeception/_support/Module/WPBrowserMethods.php
<?php namespace Module; use Codeception\Exception\ModuleException; use Facebook\WebDriver\Cookie as FacebookWebdriverCookie; use Symfony\Component\BrowserKit\Cookie; use function GuzzleHttp\Psr7\build_query; trait WPBrowserMethods { /** * The plugin screen absolute URL. * * @var string|null */ protected $pluginsPath; /** * The admin UI path, relative to the WordPress installation root URL. * * @var string */ protected $adminPath = '/wp-admin'; /** * The login screen absolute URL * * @var string */ protected $loginUrl; /** * Navigate to the default WordPress logout page and click the logout link. * * @example * ```php * // Log out using the `wp-login.php` form and return to the current page. * $I->logOut(true); * // Log out using the `wp-login.php` form and remain there. * $I->logOut(false); * // Log out using the `wp-login.php` form and move to another page. * $I->logOut('/some-other-page'); * ``` * * @param bool|string $redirectTo Whether to redirect to another (optionally specified) page after the logout. * * @return void */ public function logOut( $redirectTo = false ) { $previousUri = $this->_getCurrentUri(); $loginUri = $this->getLoginUrl(); $this->amOnPage( $loginUri . '?action=logout' ); // Use XPath to have a better performance and find the link in any language. $this->click( "//a[contains(@href,'action=logout')]" ); $this->seeInCurrentUrl( 'loggedout=true' ); if ( $redirectTo ) { $redirectUri = $redirectTo === true ? $previousUri : $redirectTo; $this->amOnPage( $redirectUri ); } } /** * Login as the administrator user using the credentials specified in the module configuration. * * The method will **not** follow redirection, after the login, to any page. * * @example * ```php * $I->loginAsAdmin(); * $I->amOnAdminPage('/'); * $I->see('Dashboard'); * ``` * * @return void */ public function loginAsAdmin() { $this->loginAs( $this->config['adminUsername'], $this->config['adminPassword'] ); } /** * Login as the specified user. * * The method will **not** follow redirection, after the login, to any page. * * @example * ```php * $I->loginAs('user', 'password'); * $I->amOnAdminPage('/'); * $I->see('Dashboard'); * ``` * * @param string $username The user login name. * @param string $password The user password in plain text. * * @return void */ public function loginAs( $username, $password ) { $this->amOnPage( $this->loginUrl ); if ( method_exists( $this, 'waitForElementVisible' ) ) { $this->waitForElementVisible( '#loginform' ); } $params = array( 'log' => $username, 'pwd' => $password, 'testcookie' => '1', 'redirect_to' => '', ); $this->submitForm( '#loginform', $params, '#wp-submit' ); } /** * Initializes the module setting the properties values. * * @return void */ public function _initialize() { parent::_initialize(); $this->configBackCompat(); $adminPath = $this->config['adminPath']; $this->loginUrl = str_replace( 'wp-admin', 'wp-login.php', $adminPath ); $this->adminPath = rtrim( $adminPath, '/' ); $this->pluginsPath = $this->adminPath . '/plugins.php'; } /** * Returns the WordPress authentication cookie. * * @param string|null $pattern The pattern to filter the cookies by. * * @return FacebookWebdriverCookie|Cookie|null The WordPress authorization cookie or `null` if not found. */ protected function grabWordPressAuthCookie( $pattern = null ) { if ( ! method_exists( $this, 'grabCookiesWithPattern' ) ) { return null; } $pattern = $pattern ? $pattern : '/^wordpress_[a-z0-9]{32}$/'; $cookies = $this->grabCookiesWithPattern( $pattern ); return empty( $cookies ) ? null : array_pop( $cookies ); } /** * Returns the WordPress login cookie. * * @param string|null $pattern The pattern to filter the cookies by. * * @return FacebookWebdriverCookie|Cookie|null The WordPress login cookie or `null` if not found. */ protected function grabWordPressLoginCookie( $pattern = null ) { if ( ! method_exists( $this, 'grabCookiesWithPattern' ) ) { return null; } $pattern = $pattern ? $pattern : '/^wordpress_logged_in_[a-z0-9]{32}$/'; $cookies = $this->grabCookiesWithPattern( $pattern ); return empty( $cookies ) ? null : array_pop( $cookies ); } /** * Go to the plugins administration screen. * * The method will **not** handle authentication. * * @example * ```php * $I->loginAsAdmin(); * $I->amOnPluginsPage(); * $I->activatePlugin('hello-dolly'); * ``` * * @return void */ public function amOnPluginsPage() { if ( ! isset( $this->pluginsPath ) ) { throw new ModuleException( $this, 'Plugins path is not set.' ); } $this->amOnPage( $this->pluginsPath ); } /** * Go the "Pages" administration screen. * * The method will **not** handle authentication. * * @example * ```php * $I->loginAsAdmin(); * $I->amOnPagesPage(); * $I->see('Add New'); * ``` * * @return void */ public function amOnPagesPage() { $this->amOnPage( $this->adminPath . '/edit.php?post_type=page' ); } /** * Assert a plugin is not activated in the plugins administration screen. * * The method will **not** handle authentication and navigation to the plugin administration screen. * * @example * ```php * $I->loginAsAdmin(); * $I->amOnPluginsPage(); * $I->seePluginDeactivated('my-plugin'); * ``` * * @param string $pluginSlug The plugin slug, like "hello-dolly". * * @return void */ public function seePluginDeactivated( $pluginSlug ) { $this->seePluginInstalled( $pluginSlug ); $this->seeElement( "table.plugins tr[data-slug='$pluginSlug'].inactive" ); } /** * Assert a plugin is installed, no matter its activation status, in the plugin adminstration screen. * * The method will **not** handle authentication and navigation to the plugin administration screen. * * @example * ```php * $I->loginAsAdmin(); * $I->amOnPluginsPage(); * $I->seePluginInstalled('my-plugin'); * ``` * * @param string $pluginSlug The plugin slug, like "hello-dolly". * * @return void */ public function seePluginInstalled( $pluginSlug ) { $this->seeElement( "table.plugins tr[data-slug='$pluginSlug']" ); } /** * Assert a plugin is activated in the plugin administration screen. * * The method will **not** handle authentication and navigation to the plugin administration screen. * * @example * ```php * $I->loginAsAdmin(); * $I->amOnPluginsPage(); * $I->seePluginActivated('my-plugin'); * ``` * * @param string $pluginSlug The plugin slug, like "hello-dolly". * * @return void */ public function seePluginActivated( $pluginSlug ) { $this->seePluginInstalled( $pluginSlug ); $this->seeElement( "table.plugins tr[data-slug='$pluginSlug'].active" ); } /** * Assert a plugin is not installed in the plugins administration screen. * * The method will **not** handle authentication and navigation to the plugin administration screen. * * @example * ```php * $I->loginAsAdmin(); * $I->amOnPluginsPage(); * $I->dontSeePluginInstalled('my-plugin'); * ``` * * @param string $pluginSlug The plugin slug, like "hello-dolly". * * @return void */ public function dontSeePluginInstalled( $pluginSlug ) { $this->dontSeeElement( "table.plugins tr[data-slug='$pluginSlug']" ); } /** * In an administration screen look for an error admin notice. * * The check is class-based to decouple from internationalization. * The method will **not** handle authentication and navigation the administration area. * * @param string|array<string> $classes A list of classes the notice should have other than the * `.notice.notice-error` ones. * * @return void * @example * ```php * $I->loginAsAdmin() * $I->amOnAdminPage('/'); * $I->seeErrorMessage('.my-plugin'); * ``` */ public function seeErrorMessage( $classes = '' ) { $classes = (array) $classes; $classes = implode( '.', $classes ); $this->seeElement( '.notice.notice-error' . ( $classes ?: '' ) ); } /** * Checks that the current page is one generated by the `wp_die` function. * * The method will try to identify the page based on the default WordPress die page HTML attributes. * * @example * ```php * $I->loginAs('user', 'password'); * $I->amOnAdminPage('/forbidden'); * $I->seeWpDiePage(); * ``` * * @return void */ public function seeWpDiePage() { $this->seeElement( 'body#error-page' ); } /** * In an administration screen look for an admin notice. * * The check is class-based to decouple from internationalization. * The method will **not** handle authentication and navigation the administration area. * * @example * ```php * $I->loginAsAdmin() * $I->amOnAdminPage('/'); * $I->seeMessage('.missing-api-token.my-plugin'); * ``` * * @param array<string>|string $classes A list of classes the message should have in addition to the `.notice` one. * * @return void */ public function seeMessage( $classes = '' ) { $classes = (array) $classes; $classes = implode( '.', $classes ); $this->seeElement( '.notice' . ( $classes ?: '' ) ); } /** * Returns WordPress default test cookie object if present. * * @example * ```php * // Grab the default WordPress test cookie. * $wpTestCookie = $I->grabWordPressTestCookie(); * // Grab a customized version of the test cookie. * $myTestCookie = $I->grabWordPressTestCookie('my_test_cookie'); * ``` * * @param string $name Optional, overrides the default cookie name. * * @return \Symfony\Component\BrowserKit\Cookie|null Either a cookie object or `null`. */ public function grabWordPressTestCookie( $name = null ) { $name = $name ?: 'wordpress_test_cookie'; return $this->grabCookie( $name ); } /** * Go to a page in the admininstration area of the site. * * This method will **not** handle authentication to the administration area. * * @example * * ```php * $I->loginAs('user', 'password'); * // Go to the plugins management screen. * $I->amOnAdminPage('/plugins.php'); * ``` * * @param string $page The path, relative to the admin area URL, to the page. * * @return string The admin page path. */ public function amOnAdminPage( $page ) { return $this->amOnPage( $this->adminPath . '/' . ltrim( $page, '/' ) ); } /** * Go to the `admin-ajax.php` page to start a synchronous, and blocking, `GET` AJAX request. * * The method will **not** handle authentication, nonces or authorization. * * @example * ```php * $I->amOnAdminAjaxPage(['action' => 'my-action', 'data' => ['id' => 23], 'nonce' => $nonce]); * ``` * * @param string|array<string,mixed> $queryVars A string or array of query variables to append to the AJAX path. * * @return string The admin page path. */ public function amOnAdminAjaxPage( $queryVars = null ) { $path = 'admin-ajax.php'; if ( $queryVars !== null ) { $path .= '?' . ( is_array( $queryVars ) ? build_query( $queryVars ) : ltrim( $queryVars, '?' ) ); } return $this->amOnAdminPage( $path ); } /** * Go to the cron page to start a synchronous, and blocking, `GET` request to the cron script. * * @example * ```php * // Triggers the cron job with an optional query argument. * $I->amOnCronPage('/?some-query-var=some-value'); * ``` * * @param string|array<string,mixed> $queryVars A string or array of query variables to append to the AJAX path. * * @return string The page path. */ public function amOnCronPage( $queryVars = null ) { $path = 'wp-cron.php'; if ( $queryVars !== null ) { $path .= '?' . ( is_array( $queryVars ) ? build_query( $queryVars ) : ltrim( $queryVars, '?' ) ); } return $this->amOnPage( $path ); } /** * Go to the admin page to edit the post with the specified ID. * * The method will **not** handle authentication the admin area. * * @example * ```php * $I->loginAsAdmin(); * $postId = $I->havePostInDatabase(); * $I->amEditingPostWithId($postId); * $I->fillField('post_title', 'Post title'); * ``` * * @param int $id The post ID. * * @return void */ public function amEditingPostWithId( $id ) { if ( ! is_numeric( $id ) || (int) $id !== $id ) { throw new \InvalidArgumentException( 'ID must be an int value' ); } $this->amOnAdminPage( '/post.php?post=' . $id . '&action=edit' ); } /** * Configures for back-compatibility. * * @return void */ protected function configBackCompat() { if ( isset( $this->config['adminUrl'] ) && ! isset( $this->config['adminPath'] ) ) { $this->config['adminPath'] = $this->config['adminUrl']; } } /** * Sets the admin path. * * @param string $adminPath The admin path. * * @return void */ protected function setAdminPath( $adminPath ) { $this->adminPath = $adminPath; } /** * Returns the admin path. * * @return string The admin path. */ protected function getAdminPath() { return $this->adminPath; } /** * Sets the login URL. * * @param string $loginUrl The login URL. * * @return void */ protected function setLoginUrl( $loginUrl ) { $this->loginUrl = $loginUrl; } /** * Returns the login URL. * * @return string The login URL. */ private function getLoginUrl() { return $this->loginUrl; } }
projects/plugins/crm/tests/codeception/_support/Module/WordPress.php
<?php namespace Module; use Codeception\Exception\ModuleConfigException; use Codeception\Exception\ModuleException; use Codeception\Lib\Framework; use Codeception\Lib\Interfaces\DependsOnModule; use Codeception\Lib\ModuleContainer; use Codeception\TestInterface; use tad\WPBrowser\Connector\WordPress as WordPressConnector; use function tad\WPBrowser\parseUrl; use function tad\WPBrowser\requireCodeceptionModules; use function tad\WPBrowser\resolvePath; use function tad\WPBrowser\untrailslashit; //phpcs:disable requireCodeceptionModules('WordPress', [ '\\Codeception\\Lib\\Framework' ]); //phpcs:enable /** * A module dedicated to functional testing using acceptance-like methods. * Differently from WPBrowser or WpWebDriver modules the WordPress code will be loaded in the same scope as the tests. * * @package Codeception\Module */ class WordPress extends Framework implements DependsOnModule { use WPBrowserMethods; /** * @var WordPressConnector|null */ public $client; /** * @var string */ public $wpRootFolder; /** * The fields required by the module. * * @var array<string> */ protected $requiredFields = array( 'wpRootFolder', 'adminUsername', 'adminPassword' ); /** * The default module configuration. * * @var array<string,mixed> */ protected $config = array( 'adminPath' => '/wp-admin' ); /** * @var bool */ protected $isMockRequest = false; /** * @var bool */ protected $lastRequestWasAdmin = false; /** * @var string */ protected $dependencyMessage = <<< EOF Example configuring WPDb -- modules enabled: - WPDb: dsn: 'mysql:host=localhost;dbname=wp' user: 'root' password: 'root' dump: 'tests/_data/dump.sql' populate: true cleanup: true reconnect: false url: 'http://wp.dev' tablePrefix: 'wp_' - WordPress: depends: WPDb wpRootFolder: "/Users/Luca/Sites/codeception-acceptance" adminUsername: 'admin' adminPassword: 'admin' EOF; /** * @var WPDb */ protected $wpdbModule; /** * @var string The site URL. */ protected $siteUrl; /** * @var string The string that will hold the response content after each request handling. */ public $response = ''; /** * WordPress constructor. * * @param \Codeception\Lib\ModuleContainer $moduleContainer The module container this module is loaded from. * @param array<string,string|int|bool> $config The module configuration * @param WordPressConnector $client The client connector that will process the requests. * * @throws \Codeception\Exception\ModuleConfigException If the configuration is not correct. */ public function __construct( ModuleContainer $moduleContainer, $config = array(), WordPressConnector $client = null ) { parent::__construct( $moduleContainer, $config ); $this->getWpRootFolder(); $this->setAdminPath( $this->config['adminPath'] ); $this->client = $client ?: $this->buildConnector(); } /** * Sets up the module. * * @param TestInterface $test The current test. * * @return void * * @throws \Codeception\Exception\ModuleException */ public function _before( TestInterface $test ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable /** @var WPDb $wpdb */ $wpdb = $this->getModule( 'WPDb' ); $this->siteUrl = $wpdb->grabSiteUrl(); $this->setLoginUrl( '/wp-login.php' ); $this->setupClient( $wpdb->getSiteDomain() ); } /** * Sets up the client/connector for the request. * * @param string $siteDomain The current site domain, e.g. 'wordpress.test'. * * @return void */ private function setupClient( $siteDomain ) { $this->client = $this->client ?: $this->buildConnector(); $this->client->setUrl( $this->siteUrl ); $this->client->setDomain( $siteDomain ); $this->client->setRootFolder( $this->config['wpRootFolder'] ); $this->client->followRedirects( true ); $this->client->resetCookies(); $this->setCookiesFromOptions(); } /** * Internal method to inject the client to use. * * @param WordPressConnector $client The client object that should be used. * * @return void */ public function _setClient( $client ) { $this->client = $client; } /** * Returns whether the current request is a mock one or not. * * @param bool $isMockRequest Whether the current request is a mock one or not. * * @return void */ public function _isMockRequest( $isMockRequest = false ) { $this->isMockRequest = $isMockRequest; } /** * Returns whether the last request was for the admin area or not. * * @return bool Whether the last request was for the admin area or not. */ public function _lastRequestWasAdmin() { return $this->lastRequestWasAdmin; } /** * Specifies class or module which is required for current one. * * THis method should return array with key as class name and value as error message * [className => errorMessage] * * @return array<string,string> A list of module dependencies. */ public function _depends() { return array( 'Codeception\Module\WPDb' => $this->dependencyMessage ); } /** * Injects the required modules. * * @param WPDb $wpdbModule An instance of the `WPDb` class. * * @return void */ public function _inject( WPDb $wpdbModule ) { $this->wpdbModule = $wpdbModule; } /** * Go to a page in the admininstration area of the site. * * @example * ```php * $I->loginAs('user', 'password'); * // Go to the plugins management screen. * $I->amOnAdminPage('/plugins.php'); * ``` * * @param string $page The path, relative to the admin area URL, to the page. * * @return string The resulting page path. */ public function amOnAdminPage( $page ) { $preparedPage = $this->preparePage( ltrim( $page, '/' ) ); if ( $preparedPage === '/' ) { $preparedPage = 'index.php'; } $page = $this->getAdminPath() . '/' . $preparedPage; return $this->amOnPage( $page ); } /** * Prepares the page path for the request. * * @param string $page The input page path. * * @return string The prepared page path. */ private function preparePage( $page ) { $page = untrailslashIt( $page ); $page = empty( $page ) || preg_match( '~\\/?index\\.php\\/?~', $page ) ? '/' : $page; return $page; } /** * Go to a page on the site. * * The module will try to reach the page, relative to the URL specified in the module configuration, without * applying any permalink resolution. * * @example * ```php * // Go the the homepage. * $I->amOnPage('/'); * // Go to the single page of post with ID 23. * $I->amOnPage('/?p=23'); * // Go to search page for the string "foo". * $I->amOnPage('/?s=foo'); * ``` * * @param string $page The path to the page, relative to the the root URL. * * @return string The page path. */ public function amOnPage( $page ) { $this->setRequestType( $page ); $parts = parseUrl( $page ); $parameters = array(); if ( ! empty( $parts['query'] ) ) { parse_str( (string) $parts['query'], $parameters ); } if ( ! $this->client instanceof WordPressConnector ) { throw new ModuleException( $this, 'Connector not yet initialized.' ); } $this->client->setHeaders( $this->headers ); if ( $this->isMockRequest ) { return $page; } $this->setCookie( 'wordpress_test_cookie', 'WP Cookie check' ); $this->_loadPage( 'GET', $page, $parameters ); return $page; } /** * Sets the current type of request.s * * @param string $page The page the request is for. * * @return void */ protected function setRequestType( $page ) { if ( $this->isAdminPageRequest( $page ) ) { $this->lastRequestWasAdmin = true; } else { $this->lastRequestWasAdmin = false; } } /** * Whether a request is for an admin page or not. * * @param string $page The page to check for. * * @return bool Whether the current request is for an admin page or not. */ private function isAdminPageRequest( $page ) { return str_starts_with( $page, $this->getAdminPath() ); } /** * Returns a list of recognized domain names for the test site. * * @internal This method is public for inter-operability and compatibility purposes and should * not be considered part of the API. * * @return array<string> A list of the internal domains. */ public function getInternalDomains() { $internalDomains = array(); $host = parse_url( $this->siteUrl, PHP_URL_HOST ) ?: 'localhost'; $internalDomains[] = '#^' . preg_quote( $host, '#' ) . '$#'; return $internalDomains; } /** * Returns the absolute path to the WordPress root folder. * * @example * ```php * $root = $I->getWpRootFolder(); * $this->assertFileExists($root . '/someFile.txt'); * ``` * * @return string The absolute path to the WordPress root folder, without a trailing slash. * * @throws \InvalidArgumentException If the WordPress root folder is not valid. */ public function getWpRootFolder() { if ( empty( $this->wpRootFolder ) ) { try { $resolvedWpRoot = resolvePath( (string) $this->config['wpRootFolder'] ); if ( $resolvedWpRoot === false ) { throw new ModuleConfigException( $this, 'Parameter "wpRootFolder" is not a directory or is not accesssible.' ); } $this->wpRootFolder = $resolvedWpRoot; } catch ( \Exception $e ) { throw new ModuleConfigException( __CLASS__, "\nThe path `{$this->config['wpRootFolder']}` is not pointing to a valid WordPress " . 'installation folder: directory not found.' ); } if ( ! file_exists( untrailslashit( (string) $this->wpRootFolder ) . '/wp-settings.php' ) ) { throw new ModuleConfigException( __CLASS__, "\nThe `{$this->config['wpRootFolder']}` is not pointing to a valid WordPress installation " . 'folder: wp-settings.php file not found.' ); } } return $this->wpRootFolder; } /** * Returns content of the last response. * This method exposes an underlying API for custom assertions. * * @example * ```php * // In test class. * $this->assertContains($text, $this->getResponseContent(), "foo-bar"); * ``` * * @return string The response content, in plain text. * * @throws \Codeception\Exception\ModuleException If the underlying modules is not available. */ public function getResponseContent() { return $this->_getResponseContent(); } protected function getAbsoluteUrlFor( $uri ) { $uri = str_replace( $this->siteUrl, 'http://localhost', str_replace( rawurlencode( $this->siteUrl ), rawurlencode( 'http://localhost' ), $uri ) ); return parent::getAbsoluteUrlFor( $uri ); } /** * Grab a cookie value from the current session, sets it in the $_COOKIE array and returns its value. * * This method utility is to get, in the scope of test code, the value of a cookie set during the tests. * * @param string $cookie The cookie name. * @param array<string,mixed> $params Parameters to filter the cookie value. * * @return string|null The cookie value or `null` if no cookie matching the parameters is found. * @example * ```php * $id = $I->haveUserInDatabase('user', 'subscriber', ['user_pass' => 'pass']); * $I->loginAs('user', 'pass'); * // The cookie is now set in the `$_COOKIE` super-global. * $I->extractCookie(LOGGED_IN_COOKIE); * // Generate a nonce using WordPress methods (see WPLoader in loadOnly mode) with correctly set context. * wp_set_current_user($id); * $nonce = wp_create_nonce('wp_rest'); * // Use the generated nonce to make a request to the the REST API. * $I->haveHttpHeader('X-WP-Nonce', $nonce); * ``` */ public function extractCookie( $cookie, array $params = array() ) { $cookieValue = $this->grabCookie( $cookie, $params ); $_COOKIE[ $cookie ] = $cookieValue; return $cookieValue; } /** * Login as the specified user. * * The method will **not** follow redirection, after the login, to any page. * * @example * ```php * $I->loginAs('user', 'password'); * $I->amOnAdminPage('/'); * $I->seeElement('.admin'); * ``` * * @param string $username The user login name. * @param string $password The user password in plain text. * * @return void */ public function loginAs( $username, $password ) { $this->amOnPage( $this->getLoginUrl() ); $this->submitForm( '#loginform', array( 'log' => $username, 'pwd' => $password, 'testcookie' => '1', 'redirect_to' => '', ), '#wp-submit' ); } /** * Builds and returns an instance of the WordPress connector. * * The method will trigger the load of required Codeception library polyfills. * * @return WordPressConnector */ protected function buildConnector() { return new WordPressConnector(); } }
projects/plugins/crm/tests/codeception/_support/Module/WPBrowser.php
<?php /** * A Codeception module offering specific WordPress browsing methods. * * @package Codeception\Module */ namespace Module; use Codeception\Module\PhpBrowser; use Facebook\WebDriver\Cookie as FacebookWebdriverCookie; use Symfony\Component\BrowserKit\Cookie; //phpcs:disable //requireCodeceptionModules('WPBrowser', [ 'PhpBrowser' ]); //phpcs:enable /** * Class WPBrowser * * @package Codeception\Module */ class WPBrowser extends PhpBrowser { use WPBrowserMethods; public function _beforeSuite( $settings = array() ) { parent::_beforeSuite( $settings ); // To set this as a field, Codeception v5 needs "protected array $requiredFields = ...". But PHP 7.3 doesn't support that syntax. // @todo When we drop support for PHP 7.3, we can move this back to "protected array $requiredFields" $this->requiredFields = array( 'adminUsername', 'adminPassword', 'adminPath' ); } /** * Returns all the cookies whose name matches a regex pattern. * * @example * ```php * $I->loginAs('customer','password'); * $I->amOnPage('/shop'); * $cartCookies = $I->grabCookiesWithPattern("#^shop_cart\\.*#"); * ``` * * @param string $cookiePattern The regular expression pattern to use for the matching. * * @return array<FacebookWebdriverCookie|Cookie>|null An array of cookies matching the pattern. */ public function grabCookiesWithPattern( $cookiePattern ) { /** * @var array<FacebookWebdriverCookie|Cookie> */ $cookies = $this->client->getCookieJar()->all(); if ( ! $cookies ) { return null; } $matchingCookies = array_filter( $cookies, static function ( $cookie ) use ( $cookiePattern ) { return preg_match( $cookiePattern, $cookie->getName() ); } ); $cookieList = array_map( static function ( $cookie ) { return sprintf( '{"%s": "%s"}', $cookie->getName(), $cookie->getValue() ); }, $matchingCookies ); $this->debug( 'Cookies matching pattern ' . $cookiePattern . ' : ' . implode( ', ', $cookieList ) ); return count( $matchingCookies ) ? $matchingCookies : null; } /** * In the plugin administration screen activates a plugin clicking the "Activate" link. * * The method will **not** handle authentication to the admin area. * * @example * ```php * // Activate a plugin. * $I->loginAsAdmin(); * $I->amOnPluginsPage(); * $I->activatePlugin('hello-dolly'); * // Activate a list of plugins. * $I->loginAsAdmin(); * $I->amOnPluginsPage(); * $I->activatePlugin(['hello-dolly','another-plugin']); * ``` * * @param string|array<string> $pluginSlug The plugin slug, like "hello-dolly" or a list of plugin slugs. * * @return void */ public function activatePlugin( $pluginSlug ) { foreach ( (array) $pluginSlug as $plugin ) { $this->checkOption( '//*[@data-slug="' . $plugin . '"]/th/input' ); } $this->selectOption( 'action', 'activate-selected' ); $this->click( '#doaction' ); } /** * In the plugin administration screen deactivate a plugin clicking the "Deactivate" link. * * The method will **not** handle authentication and navigation to the plugins administration page. * * @example * ```php * // Deactivate one plugin. * $I->loginAsAdmin(); * $I->amOnPluginsPage(); * $I->deactivatePlugin('hello-dolly'); * // Deactivate a list of plugins. * $I->loginAsAdmin(); * $I->amOnPluginsPage(); * $I->deactivatePlugin(['hello-dolly', 'my-plugin']); * ``` * * @param string|array<string> $pluginSlug The plugin slug, like "hello-dolly", or a list of plugin slugs. * * @return void */ public function deactivatePlugin( $pluginSlug ) { foreach ( (array) $pluginSlug as $plugin ) { $this->checkOption( '//*[@data-slug="' . $plugin . '"]/th/input' ); } $this->selectOption( 'action', 'deactivate-selected' ); $this->click( '#doaction' ); } /** * Validates the module configuration. * * @return void * * @throws \Codeception\Exception\ModuleConfigException|\Codeception\Exception\ModuleException If there's any issue. */ protected function validateConfig(): void { $this->configBackCompat(); parent::validateConfig(); } }
projects/plugins/crm/tests/codeception/_support/Module/WPWebDriver.php
<?php /** * An extension of Codeception WebDriver module offering specific WordPress browsing methods. * * @package Codeception\Module */ namespace Codeception\Module; use Codeception\Exception\ModuleConfigException; use Codeception\Exception\ModuleException; use Facebook\WebDriver\Cookie as FacebookWebdriverCookie; use Symfony\Component\BrowserKit\Cookie; use function tad\WPBrowser\requireCodeceptionModules; //phpcs:disable requireCodeceptionModules('WPWebDriver', [ 'WebDriver' ]); //phpcs:enable /** * Class WPWebDriver * * @package Codeception\Module */ class WPWebDriver extends WebDriver { use WPBrowserMethods; /** * The module required fields, to be set in the suite .yml configuration file. * * @var array<string> */ protected $requiredFields = array( 'adminUsername', 'adminPassword', 'adminPath' ); /** * The login attempts counter. * * @var int */ protected $loginAttempt = 0; /** * Login as the administrator user using the credentials specified in the module configuration. * * The method will **not** follow redirection, after the login, to any page. * * @example * ```php * $I->loginAsAdmin(); * $I->amOnAdminPage('/'); * $I->see('Dashboard'); * ``` * * @param int $timeout The max time, in seconds, to try to login. * @param int $maxAttempts The max number of attempts to try to login. * * @return void * * @throws ModuleException If all the attempts of obtaining the cookie fail. */ public function loginAsAdmin( $timeout = 10, $maxAttempts = 5 ) { $this->loginAs( $this->config['adminUsername'], $this->config['adminPassword'], $timeout, $maxAttempts ); } /** * Login as the specified user. * * The method will **not** follow redirection, after the login, to any page. * Depending on the driven browser the login might be "too fast" and the server might have not * replied with valid cookies yet; in that case the method will re-attempt the login to obtain * the cookies. * * @example * ```php * $I->loginAs('user', 'password'); * $I->amOnAdminPage('/'); * $I->see('Dashboard'); * ``` * * @param string $username The user login name. * @param string $password The user password in plain text. * @param int $timeout The max time, in seconds, to try to login. * @param int $maxAttempts The max number of attempts to try to login. * * @throws ModuleException If all the attempts of obtaining the cookie fail. * * @return void */ public function loginAs( $username, $password, $timeout = 10, $maxAttempts = 5 ) { if ( $this->loginAttempt === $maxAttempts ) { throw new ModuleException( __CLASS__, "Could not login as [{$username}, {$password}] after {$maxAttempts} attempts." ); } $this->debug( "Trying to login, attempt {$this->loginAttempt}/{$maxAttempts}..." ); $this->amOnPage( $this->getLoginUrl() ); $this->waitForElement( '#user_login', $timeout ); $this->waitForElement( '#user_pass', $timeout ); $this->waitForElement( '#wp-submit', $timeout ); $this->fillField( '#user_login', $username ); $this->fillField( '#user_pass', $password ); $this->click( '#wp-submit' ); $authCookie = $this->grabWordPressAuthCookie(); $loginCookie = $this->grabWordPressLoginCookie(); $empty_cookies = empty( $authCookie ) && empty( $loginCookie ); if ( $empty_cookies ) { ++$this->loginAttempt; $this->wait( 1 ); $this->loginAs( $username, $password, $timeout, $maxAttempts ); } $this->loginAttempt = 0; } /** * Returns all the cookies whose name matches a regex pattern. * * @example * ```php * $I->loginAs('customer','password'); * $I->amOnPage('/shop'); * $cartCookies = $I->grabCookiesWithPattern("#^shop_cart\\.*#"); * ``` * * @param string $cookiePattern The regular expression pattern to use for the matching. * * @return array<FacebookWebdriverCookie|Cookie>|null An array of cookies matching the pattern. */ public function grabCookiesWithPattern( $cookiePattern ) { /** @var array<FacebookWebdriverCookie|Cookie> $cookies */ $cookies = $this->webDriver->manage()->getCookies(); if ( ! $cookies ) { return null; } $matchingCookies = array_filter( $cookies, static function ( $cookie ) use ( $cookiePattern ) { return preg_match( $cookiePattern, $cookie->getName() ); } ); $cookieList = array_map( static function ( $cookie ) { return sprintf( '{"%s": "%s"}', $cookie->getName(), $cookie->getValue() ); }, $matchingCookies ); $this->debug( 'Cookies matching pattern ' . $cookiePattern . ' : ' . implode( ', ', $cookieList ) ); return count( $matchingCookies ) ? $matchingCookies : null; } /** * Waits for any jQuery triggered AJAX request to be resolved. * * @example * ```php * $I->amOnPage('/triggering-ajax-requests'); * $I->waitForJqueryAjax(); * $I->see('From AJAX'); * ``` * * @param int $time The max time to wait for AJAX requests to complete. * * @return void */ public function waitForJqueryAjax( $time = 10 ) { $this->waitForJS( 'return jQuery.active == 0', $time ); } /** * Grabs the current page full URL including the query vars. * * @example * ```php * $today = date('Y-m-d'); * $I->amOnPage('/concerts?date=' . $today); * $I->assertRegExp('#\\/concerts$#', $I->grabFullUrl()); * ``` * * @return string The full page URL. */ public function grabFullUrl() { return $this->executeJS( 'return location.href' ); } /** * Validates the module configuration.. * * @internal * * @return void * @throws ModuleConfigException|ModuleException If there's an issue with the configuration. */ protected function validateConfig() { $this->configBackCompat(); parent::validateConfig(); } /** * In the plugin administration screen deactivate a plugin clicking the "Deactivate" link. * * The method will **not** handle authentication and navigation to the plugins administration page. * * @example * ```php * // Deactivate one plugin. * $I->loginAsAdmin(); * $I->amOnPluginsPage(); * $I->deactivatePlugin('hello-dolly'); * // Deactivate a list of plugins. * $I->loginAsAdmin(); * $I->amOnPluginsPage(); * $I->deactivatePlugin(['hello-dolly', 'my-plugin']); * ``` * * @param string|array<string> $pluginSlug The plugin slug, like "hello-dolly", or a list of plugin slugs. * * @return void */ public function deactivatePlugin( $pluginSlug ) { foreach ( (array) $pluginSlug as $plugin ) { $option = '//*[@data-slug="' . $plugin . '"]/th/input'; $this->scrollTo( $option, 0, -40 ); $this->checkOption( $option ); } $this->scrollTo( 'select[name="action"]', 0, -40 ); $this->selectOption( 'action', 'deactivate-selected' ); $this->click( '#doaction' ); } /** * In the plugin administration screen activates one or more plugins clicking the "Activate" link. * * The method will **not** handle authentication and navigation to the plugins administration page. * * @example * ```php * // Activate a plugin. * $I->loginAsAdmin(); * $I->amOnPluginsPage(); * $I->activatePlugin('hello-dolly'); * // Activate a list of plugins. * $I->loginAsAdmin(); * $I->amOnPluginsPage(); * $I->activatePlugin(['hello-dolly','another-plugin']); * ``` * * @param string|array<string> $pluginSlug The plugin slug, like "hello-dolly" or a list of plugin slugs. * * @return void */ public function activatePlugin( $pluginSlug ) { $plugins = (array) $pluginSlug; foreach ( $plugins as $plugin ) { $option = '//*[@data-slug="' . $plugin . '"]/th/input'; $this->scrollTo( $option, 0, -40 ); $this->checkOption( $option ); } $this->scrollTo( 'select[name="action"]', 0, -40 ); $this->selectOption( 'action', 'activate-selected' ); $this->click( '#doaction' ); } }
projects/plugins/crm/tests/codeception/_support/Helper/Functional.php
<?php namespace Helper; // here you can define custom actions // all public methods declared in helper class will be available in $I class Functional extends \Codeception\Module { }
projects/plugins/crm/tests/codeception/_support/Helper/Unit.php
<?php namespace Helper; // here you can define custom actions // all public methods declared in helper class will be available in $I class Unit extends \Codeception\Module { }
projects/plugins/crm/tests/codeception/_support/Helper/Acceptance.php
<?php namespace Helper; class Acceptance extends \Codeception\Module { }
projects/plugins/crm/tests/codeception/_support/Helper/JPCRM_Acceptance.php
<?php namespace Helper; use Module\WPBrowser; class JPCRM_Acceptance extends WPBrowser { protected $server_output_path = __DIR__ . '/../../_output/server_output.log'; // we use core.php slugs directly copied in via __CONSTRUCT below to allow easy updating. protected $slugs = array(); /** @var RunProcess */ protected $serverProcess; public function _beforeSuite( $settings = array() ) { parent::_beforeSuite( $settings ); // To set this as a field, Codeception v5 needs "protected array $requiredFields = ...". But PHP 7.3 doesn't support that syntax. // @todo When we drop support for PHP 7.3, we can move this back to "protected array $requiredFields" $this->requiredFields = array( 'adminUsername', 'adminPassword', 'adminPath', 'database', 'wp_prefix', 'jpcrm_prefix', 'wp_path', ); // todo: prepare the database (remove and restore, change the home and siteurl options // $this->setup_database(); $this->loadSlugs(); $this->run_server(); } public function _afterSuite() { parent::_afterSuite(); $this->check_php_errors(); $this->stop_server(); } public function setup_database() { // todo: Setup the database before the test suite. Here we can select which database we're going to use // todo: Update the WP database with the url and hostname } public function run_server() { $server_host = $this->config['server_host']; $wp_path = $this->config['wp_path']; $wp_version = '-'; include_once "$wp_path/wp-includes/version.php"; // phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.NotAbsolutePath $serverCmd = "php -S $server_host -t $wp_path"; $this->serverProcess = new RunProcess( $serverCmd, $this->server_output_path ); echo "\e[33mPHP version:\e[96m " . PHP_VERSION; echo "\n\e[33mWordPress installation:\e[96m $wp_path"; echo "\n\e[33mWordPress version:\e[96m $wp_version"; echo "\n\n\e[33mSetting up the server..."; $pid = $this->serverProcess->run(); // Sleep for 1.5 seconds to give time to warm up the server usleep( 1500000 ); echo "\n\e[97m\e[42m OK \e[49m \e[33mThe server is running at \e[96m$server_host \e[33mwith PID: \e[96m$pid \e[39m\n"; } public function stop_server() { if ( $this->serverProcess && $this->serverProcess->isRunning() ) { echo "\n\e[33mStopping the server..."; $this->serverProcess->stop(); echo " \e[97m\e[42m\e[42m OK \e[49m \e[33mserver stopped\e[39m\n"; } } public function __destruct() { $this->stop_server(); } public function check_php_errors() { echo "\n\e[33mChecking PHP errors..."; $output = fopen( $this->server_output_path, 'r' ); $php_errors = array( 'Error', 'Notice', 'Parsing Error', 'Warning', 'Fatal error', 'Exception', 'Deprecated', ); $errors = array(); while ( ! feof( $output ) ) { $row = fgets( $output ); // todo: we can do the same using a regular expression and preg_match foreach ( $php_errors as $php_error ) { if ( str_contains( $row, $php_error ) ) { $errors[] = $row; } } } if ( count( $errors ) > 0 ) { $this->fail( "\e[91mHey! Something seems wrong.\n\e[39mThere are some PHP errors or notices:\e[93m\n\n" . print_r( $errors, true ) . "\e[39m" ); } else { echo " \e[97m\e[42m\e[42m OK \e[49m\e[33m everything went well"; } } // we use this to load in the default slugs (copied directly from ZeroBSCRM.Core.php) protected function loadSlugs() { // Last copied 4.0.8 // Begin copy from Core.php ##WLREMOVE $this->slugs['home'] = 'zerobscrm-plugin'; ##/WLREMOVE $this->slugs['dash'] = 'zerobscrm-dash'; $this->slugs['settings'] = 'zerobscrm-plugin-settings'; // $this->slugs['logout'] = "zerobscrm-logout"; // <<< 403 Forbidden $this->slugs['datatools'] = 'zerobscrm-datatools'; // $this->slugs['welcome'] = "zerobscrm-welcome"; // <<< 403 Forbidden $this->slugs['crmresources'] = 'jpcrm-resources'; $this->slugs['extensions'] = 'zerobscrm-extensions'; // $this->slugs['export'] = "zerobscrm-export"; // <<< 403 Forbidden $this->slugs['systemstatus'] = 'zerobscrm-systemstatus'; $this->slugs['support'] = 'jpcrm-support'; // $this->slugs['sync'] = "zerobscrm-sync"; // <<< 403 Forbidden // These don't seem to be used anymore? // $this->slugs['connect'] = "zerobscrm-connect"; // $this->slugs['app'] = "zerobscrm-app"; // $this->slugs['whlang'] = "zerobscrm-whlang"; // $this->slugs['customfields'] = "zerobscrm-customfields"; // $this->slugs['import'] = "zerobscrm-import"; // CSV importer Lite $this->slugs['csvlite'] = 'zerobscrm-csvimporterlite-app'; // } FOR NOW wl needs these: // $this->slugs['bulktagger'] = "zerobscrm-batch-tagger"; // <<< 403 Forbidden // $this->slugs['salesdash'] = "sales-dash"; // <<< 403 Forbidden // $this->slugs['stripesync'] = "zerobscrm-stripesync-app"; // <<< 403 Forbidden // $this->slugs['woosync'] = "woo-importer"; // <<< 403 Forbidden // $this->slugs['paypalsync'] = "zerobscrm-paypal-app"; // <<< 403 Forbidden // } OTHER UI PAGES WHICH WEREN'T IN SLUG - MS CLASS ADDITION // } WH: Not sure which we're using here, think first set cleaner: // NOTE: DAL3 + these are referenced in DAL2.php so be aware :) // (This helps for generically linking back to list obj etc.) // USE zbsLink! $this->slugs['managecontacts'] = 'manage-customers'; $this->slugs['managequotes'] = 'manage-quotes'; $this->slugs['manageinvoices'] = 'manage-invoices'; $this->slugs['managetransactions'] = 'manage-transactions'; $this->slugs['managecompanies'] = 'manage-companies'; $this->slugs['manageformscrm'] = 'manage-forms'; $this->slugs['segments'] = 'manage-segments'; $this->slugs['quote-templates'] = 'manage-quote-templates'; $this->slugs['manage-tasks'] = 'manage-tasks'; // $this->slugs['manage-tasks-completed'] = "manage-tasks-completed"; // <<< 403 Forbidden // $this->slugs['managecontactsprev'] = "manage-customers-crm"; // <<< 403 Forbidden // $this->slugs['managequotesprev'] = "manage-quotes-crm"; // <<< 403 Forbidden // $this->slugs['managetransactionsprev'] = "manage-transactions-crm"; // <<< 403 Forbidden // $this->slugs['manageinvoicesprev'] = "manage-invoices-crm"; // <<< 403 Forbidden // $this->slugs['managecompaniesprev'] = "manage-companies-crm"; // <<< 403 Forbidden // $this->slugs['manageformscrmprev'] = "manage-forms-crm"; // <<< 403 Forbidden // } NEW UI - ADD or EDIT, SEND EMAIL, NOTIFICATIONS $this->slugs['addedit'] = 'zbs-add-edit'; $this->slugs['sendmail'] = 'zerobscrm-send-email'; $this->slugs['emails'] = 'zerobscrm-emails'; $this->slugs['notifications'] = 'zerobscrm-notifications'; // } TEAM - Manage the CRM team permissions $this->slugs['team'] = 'zerobscrm-team'; // } Export tools $this->slugs['export-tools'] = 'zbs-export-tools'; // } Your Profile (for Calendar Sync and Personalised Stuff (like your own task history)) $this->slugs['your-profile'] = 'your-crm-profile'; $this->slugs['reminders'] = 'zbs-reminders'; // } Adds a USER (i.e. puts our menu on user-new.php through ?page =) // $this->slugs['zbs-new-user'] = "zbs-add-user"; // <<< 403 Forbidden // $this->slugs['zbs-edit-user'] = "zbs-edit-user"; // <<< 403 Forbidden // emails $this->slugs['email-templates'] = 'zbs-email-templates'; // tag manager $this->slugs['tagmanager'] = 'tag-manager'; // no access $this->slugs['zbs-noaccess'] = 'zbs-noaccess'; // } Modules/extensions $this->slugs['modules'] = 'zerobscrm-modules'; $this->slugs['extensions'] = 'zerobscrm-extensions'; // } File Editor $this->slugs['editfile'] = 'zerobscrm-edit-file'; // } Extensions Deactivated error $this->slugs['extensions-active'] = 'zbs-extensions-active'; // End copy from Core.php // Addition of add-edit variants to catch edit pages :) // e.g. /wp-admin/admin.php?page=zbs-add-edit&action=edit&zbstype=quotetemplate // ... and tag manager pages // ... and export tool page $types = array( 'contact', 'company', 'quote', 'quotetemplate', 'invoice', 'transaction', 'event', 'form' ); foreach ( $types as $type ) { // add new $this->slugs[ 'add-new-' . $type ] = 'zbs-add-edit&action=edit&zbstype=' . $type; // tag manager $this->slugs[ 'tag-mgr-' . $type ] = 'tag-manager&tagtype=' . $type; // export tools $this->slugs[ 'export-tools-' . $type ] = 'zbs-export-tools&zbstype=' . $type; } } public function getDatabase() { return $this->config['database']; } /** * Get the JetpackCRM table name * * @param $name * @return string */ public function table( $name ) { return $this->config['jpcrm_prefix'] . $name; } public function pdo() { return $this->getModule( 'Db' )->dbh; // $dbh->exec('CREATE DATABASE testestest'); } /** * Load a page from it's core slug * * @param $page_slug * @param string $query */ public function goToPageViaSlug( $page_slug, $query = '' ) { $this->amOnAdminPage( 'admin.php?page=' . $this->slugs[ $page_slug ] . $query ); } /** * retrieve slug pile */ public function getSlugs() { // pass back return $this->slugs; } /** * Check if see PHP error in the page. Need debug mode on: define( 'WP_DEBUG', true ); */ public function dontSeeAnyErrors() { $this->dontSee( 'Notice: ' ); $this->dontSee( 'Parse error: ' ); $this->dontSee( 'Warning: ' ); $this->dontSee( 'Fatal error: ' ); } }
projects/plugins/crm/tests/codeception/_support/Helper/RunProcess.php
<?php // Todo: Do something about these. // phpcs:disable WordPress.PHP.DiscouragedPHPFunctions.system_calls_shell_exec, Generic.CodeAnalysis.EmptyStatement.DetectedCatch, Squiz.Commenting.EmptyCatchComment.Missing namespace Helper; class RunProcess { protected $pid; protected $cmd; protected $outputFile; protected $append; /** * RunProcess constructor. * * @param $cmd * @param string $outputFile * @param bool $append */ public function __construct( $cmd, $outputFile = '/dev/null', $append = false ) { $this->cmd = $cmd; $this->outputFile = $outputFile; $this->append = $append; } public function run() { if ( $this->cmd === null ) { return; } $this->pid = (int) shell_exec( sprintf( '%s %s %s 2>&1 & echo $!', $this->cmd, ( $this->append ) ? '>>' : '>', $this->outputFile ) ); return $this->pid; } public function isRunning() { try { $result = shell_exec( sprintf( 'ps %d 2>&1', $this->pid ) ); if ( count( preg_split( "/\n/", $result ) ) > 2 && ! preg_match( '/ERROR: Process ID out of range/', $result ) ) { return true; } } catch ( Exception $e ) { } return false; } public function stop() { try { $result = shell_exec( sprintf( 'kill %d 2>&1', $this->pid ) ); if ( is_string( $result ) && ! preg_match( '/No such process/', $result ) ) { return true; } } catch ( Exception $e ) { } return false; } }
projects/plugins/crm/tests/codeception/acceptance/60_JPCRM_Files_Cest.php
<?php /** * Tests index blocking files are present after initial install (migration 450) */ class JPCRM_Files_Cest { public function _before( AcceptanceTester $I ) { // login as admin (should fire migration on the off chance it's not yet fired) $I->loginAsAdmin(); } public function see_templates_index_blocker_files( AcceptanceTester $I ) { // attempt to directly load index blocker $I->amOnPage( '/wp-content/plugins/crm/templates/index.html' ); // see that our html comment is present (means our file was created) $I->seeInSource( '<!--nope-->' ); } }
projects/plugins/crm/tests/codeception/acceptance/12_JPCRM_Admin_Views_Cest.php
<?php /** * Tests of our various Admin Views */ class JPCRM_Admin_Views_Cest { public function _before( AcceptanceTester $I ) { $I->loginAsAdmin(); } public function see_jpcrm_wp_menu( AcceptanceTester $I ) { $I->amOnPage( 'wp-admin' ); $I->see( 'Jetpack CRM', '.wp-menu-name' ); } public function see_jpcrm_top_menu( AcceptanceTester $I ) { $I->gotoAdminPage( 'dashboard' ); $expectedAdminMenus = array( 'Dashboard', 'Contacts', 'Tools', ); foreach ( $expectedAdminMenus as $menu ) { $I->see( $menu, '#jpcrm-top-menu .item' ); } } public function see_jpcrm_dashboard( AcceptanceTester $I ) { $I->gotoAdminPage( 'dashboard' ); $expectedBlocks = array( 'Sales Funnel', 'Revenue Chart', // 'Contacts added per month', // 'Total Contacts', // 'Total Leads', // 'Total Customers', // 'Total Transactions', 'Latest Contacts', 'Recent Activity', ); foreach ( $expectedBlocks as $block_title ) { $I->see( $block_title, '.jpcrm-dashcard-header h4' ); } } public function see_jpcrm_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings' ); $I->see( 'General Settings' ); } }
projects/plugins/crm/tests/codeception/acceptance/92_JPCRM_Deactivation_Activation_Cest.php
<?php /** * Tests to check the deactivation, activation the core plugin and the extension plugins */ class JPCRM_Deactivation_Activation_Cest { private $plugin_slug = 'jetpack-crm'; public function _before( AcceptanceTester $I ) { $I->loginAsAdmin(); } public function jpcrm_deactivation( AcceptanceTester $I ) { $I->amOnPluginsPage(); $I->seePluginActivated( $this->plugin_slug ); $I->deactivatePlugin( $this->plugin_slug ); $I->see( 'Before you go' ); $I->seeInSource( 'https://forms.gle/q5KjMBytni3kfFco7' ); $I->see( 'Not right now' ); $I->click( 'Not right now' ); $I->seeInCurrentUrl( '/plugins.php' ); $I->see( 'Plugins' ); } public function jpcrm_force_wizard( AcceptanceTester $I ) { $I->amOnPluginsPage(); // Plugin should be deactivated $I->seePluginDeactivated( $this->plugin_slug ); $I->activatePlugin( $this->plugin_slug ); $I->gotoAdminPage( 'dashboard', '&jpcrm_force_wizard=1' ); $I->see( 'Essential Details' ); $I->see( 'Essentials' ); $I->see( 'Your Contacts' ); $I->see( 'Which Extensions?' ); } public function jpcrm_is_activated( AcceptanceTester $I ) { $I->amOnPluginsPage(); $I->seePluginActivated( $this->plugin_slug ); // Check that Jetpack CRM menu is there $I->amOnPage( 'wp-admin' ); $I->see( 'Jetpack CRM', '.wp-menu-name' ); } }
projects/plugins/crm/tests/codeception/acceptance/15_JPCRM_Invoices_Cest.php
<?php /** * Invoice related tests */ class JPCRM_Invoices_Cest { protected $item1 = array( 'name' => 'Item-1', 'description' => 'Description of item 1', 'quantity' => 1, 'price' => 10.5, ); protected $item2 = array( 'name' => 'Item-2', 'description' => 'Description of item 2', 'quantity' => 2, 'price' => 30, ); protected $invoice_data = array( 'zbsi_date' => '2021-01-08', 'zbsi_due' => '30', 'zbs_invoice_contact' => 1, 'zbs_invoice_company' => -1, 'invoice-customiser-type' => 'quantity', 'invoice_discount_total' => 10, 'invoice_discount_type' => '%', 'zbs-tag-list' => '["important"]', ); protected $invoice_db_data = array( 'zbsi_date' => '1610064000', 'zbsi_due_date' => '1612656000', 'zbsi_hours_or_quantity' => 1, 'zbsi_id_override' => '1', 'zbsi_discount' => 10.0, 'zbsi_discount_type' => '%', 'zbsi_net' => 70.5, 'zbsi_total' => 63.45, 'zbsi_status' => 'Draft', ); public function __construct() { $this->invoice_data['zbsli_itemname'] = array( $this->item1['name'], $this->item2['name'], ); $this->invoice_data['zbsli_itemdes'] = array( $this->item1['description'], $this->item2['description'], ); $this->invoice_data['zbsli_quan'] = array( $this->item1['quantity'], $this->item2['quantity'], ); $this->invoice_data['zbsli_price'] = array( $this->item1['price'], $this->item2['price'], ); } public function _before( AcceptanceTester $I ) { $I->loginAsAdmin(); } public function see_invoices_page( AcceptanceTester $I ) { $I->gotoAdminPage( 'invoices' ); $I->see( 'Invoices', '.jpcrm-learn-page-title' ); } public function see_new_invoice_page( AcceptanceTester $I ) { $I->gotoAdminPage( 'add-edit', '&action=edit&zbstype=invoice' ); $I->see( 'New Invoice', '.jpcrm-learn-page-title' ); } public function create_new_invoice( AcceptanceTester $I ) { $I->gotoAdminPage( 'add-edit', '&action=edit&zbstype=invoice' ); $I->submitForm( '#zbs-edit-form', $this->invoice_data ); $I->seeInDatabase( $I->table( 'invoices' ), $this->invoice_db_data ); } public function see_created_invoice( AcceptanceTester $I ) { $I->gotoAdminPage( 'add-edit', '&action=edit&zbstype=invoice&zbsid=1' ); // We can check only that we reach the page. The data is load via AJAX. $I->see( 'Edit Invoice', '.jpcrm-learn-page-title' ); } public function create_second_invoice( AcceptanceTester $I ) { $I->gotoAdminPage( 'add-edit', '&action=edit&zbstype=invoice' ); $this->invoice_data['invoice_status'] = 'Paid'; $I->submitForm( '#zbs-edit-form', $this->invoice_data ); $this->invoice_db_data['zbsi_status'] = 'Paid'; $this->invoice_db_data['ID'] = '2'; $this->invoice_db_data['zbsi_id_override'] = '2'; $I->seeInDatabase( $I->table( 'invoices' ), $this->invoice_db_data ); } // todo: Check invoice autonumber. Configurate the autonumber }
projects/plugins/crm/tests/codeception/acceptance/14_JPCRM_Quotes_Cest.php
<?php /** * Quote related tests */ class JPCRM_Quotes_Cest { protected $quote_data = array( 'zbscq_title' => 'Testing quote', 'zbscq_value' => '1000.50', 'zbscq_date' => '2021-01-01', 'zbscq_notes' => 'This is the quote note', 'zbs_quote_content' => 'This is the quote content', ); protected $quote_data2 = array( 'zbscq_title' => 'Testing quote2', 'zbscq_value' => '1010.50', 'zbscq_date' => '2021-01-02', 'zbscq_notes' => 'This is the quote note2', 'zbs_quote_content' => 'This is the quote content2', ); protected $expected_quote = array( 'zbsq_title' => 'Testing quote', 'zbsq_value' => '1000.50', 'zbsq_date' => 1609459200, 'zbsq_notes' => 'This is the quote note', 'zbsq_content' => 'This is the quote content', 'zbsq_accepted' => false, ); protected $tags = array( 'the-tag' ); public function _before( AcceptanceTester $I ) { $I->loginAsAdmin(); } public function see_quotes_page( AcceptanceTester $I ) { $I->gotoAdminPage( 'quotes' ); $I->see( 'Quotes', '.jpcrm-learn-page-title' ); } public function see_new_quote_page( AcceptanceTester $I ) { $I->gotoAdminPage( 'add-edit', '&action=edit&zbstype=quote' ); $I->see( 'New Quote', '.jpcrm-learn-page-title' ); } public function create_new_quote( AcceptanceTester $I ) { $I->gotoAdminPage( 'add-edit', '&action=edit&zbstype=quote' ); $I->submitForm( '#zbs-edit-form', $this->quote_data ); // todo: add a tag $I->seeInDatabase( $I->table( 'quotes' ), $this->expected_quote ); } public function view_quote( AcceptanceTester $I ) { $I->gotoAdminPage( 'add-edit', '&action=edit&zbstype=quote&zbsid=1' ); foreach ( $this->quote_data as $field => $data ) { $I->seeInField( $field, $data ); } } public function edit_quote( AcceptanceTester $I ) { $I->gotoAdminPage( 'add-edit', '&action=edit&zbstype=quote&zbsid=1' ); $I->submitForm( '#zbs-edit-form', $this->quote_data2 ); $expected_quote = array( 'zbsq_title' => 'Testing quote2', 'zbsq_value' => 1010.5, 'zbsq_notes' => 'This is the quote note2', 'zbsq_content' => 'This is the quote content2', ); $I->seeInDatabase( $I->table( 'quotes' ), $expected_quote ); } }
projects/plugins/crm/tests/codeception/acceptance/50_JPCRM_Settings_Cest.php
<?php /** * Contact related tests */ class JPCRM_Settings_Cest { public function _before( AcceptanceTester $I ) { $I->loginAsAdmin(); } public function see_settings_page( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings' ); $I->see( 'Settings', '.jpcrm-learn-page-title' ); $I->see( '', '.item' ); } public function see_settings_page_menus( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings' ); $I->see( 'General', '.item' ); $I->see( 'Companies', '.item' ); $I->see( 'Quotes', '.item' ); $I->see( 'Invoicing', '.item' ); $I->see( 'Transactions', '.item' ); $I->see( 'Forms', '.item' ); $I->see( 'Client Portal', '.item' ); $I->see( 'Mail', '.item' ); $I->see( 'Extensions', '.item' ); } public function see_general_settings_page( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=settings' ); $I->see( 'General Settings', 'h1.header' ); $I->see( 'Menu Layout', 'label' ); $I->see( 'Show Prefix', 'label' ); $I->see( 'Show Contact Address Fields', 'label' ); $I->see( 'Second Address Fields', 'label' ); $I->see( 'Second Address Label', 'label' ); $I->see( 'Use "Countries" in Address Fields', 'label' ); $I->see( 'Contact Assignment', 'label' ); $I->see( 'Assign Ownership', 'label' ); $I->see( 'Task Scheduler Ownership', 'label' ); $I->see( 'Show Click 2 Call links', 'label' ); $I->see( 'Click 2 Call link type', 'label' ); $I->see( 'Use Navigation Mode', 'label' ); $I->see( 'Show Social Accounts', 'label' ); $I->see( 'Use AKA Mode', 'label' ); $I->see( 'Contact Image Mode', 'label' ); $I->see( 'Override WordPress', 'label' ); $I->see( 'Login Logo Override', 'label' ); $I->see( 'Custom CRM Header', 'label' ); $I->see( 'Disable Front-End', 'label' ); $I->see( 'Usage Tracking', 'label' ); $I->see( 'Show public credits', 'label' ); $I->see( 'Show admin credits', 'label' ); $I->see( 'Accepted Upload File Types', 'label' ); $I->see( 'Auto-log', 'label' ); } public function save_general_settings_page( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=settings' ); $I->seeInField( 'wpzbscrm_avatarmode', '1' ); $I->dontSeeCheckboxIsChecked( 'jpcrm_showpoweredby_public' ); $I->seeCheckboxIsChecked( 'jpcrm_showpoweredby_admin' ); $I->selectOption( 'select[name=wpzbscrm_avatarmode]', '2' ); $I->checkOption( 'jpcrm_showpoweredby_public' ); $I->uncheckOption( 'jpcrm_showpoweredby_admin' ); $I->click( 'Save Settings', 'button' ); $I->seeInField( 'wpzbscrm_avatarmode', '2' ); $I->seeCheckboxIsChecked( 'jpcrm_showpoweredby_public' ); $I->dontSeeCheckboxIsChecked( 'jpcrm_showpoweredby_admin' ); } public function see_business_info_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=bizinfo' ); $I->see( 'Business Info', 'h1.header' ); $I->see( 'Your Business Name', 'label' ); $I->see( 'Your Business Logo', 'label' ); $I->see( 'Owner Name', 'label' ); $I->see( 'Business Contact Email', 'label' ); $I->see( 'Business Website URL', 'label' ); $I->see( 'Business Telephone Number', 'label' ); $I->see( 'Twitter Handle', 'label' ); $I->see( 'Facebook Page', 'label' ); $I->see( 'LinkedIn ID', 'label' ); $I->see( 'follow Jetpack CRM' ); } public function save_business_info_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=bizinfo' ); $I->fillField( 'businessname', 'Test Company' ); $I->click( 'Save Settings', 'button' ); $I->seeInField( 'businessname', 'Test Company' ); } public function see_custom_fields_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=customfields' ); $I->see( 'Custom Fields', 'h1.header' ); $I->see( 'Contact Custom Fields' ); $I->see( 'Contact Custom File Upload Boxes' ); $I->see( 'Company Custom Fields' ); $I->see( 'Quote Custom Fields' ); $I->see( 'Invoice Custom Fields' ); $I->see( 'Transaction Custom Fields' ); $I->see( 'Address Custom Fields' ); $I->see( 'Save Custom Fields' ); } public function save_custom_fields_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=customfields' ); $custom_field = array( 'wpzbscrm_cf[customers][name][]' => 'New Field', 'wpzbscrm_cf[customers][type][]' => 'text', 'wpzbscrm_cf[customers][placeholder][]' => 'This is the placeholder', ); $I->submitForm( '[action="?page=zerobscrm-plugin-settings&tab=customfields"]', $custom_field ); $I->seeInSource( '{"customers":{"new-field":["text","New Field","This is the placeholder","new-field"]}' ); } public function see_field_sorts_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=fieldsorts' ); $I->see( 'Field Sorts', 'h1.header' ); $I->see( 'Address Fields' ); $I->see( 'Contact Fields' ); $I->see( 'Company Fields' ); } public function see_field_options_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=fieldoptions' ); $I->see( 'Field Options', 'h1.header' ); $I->see( 'General Field Options' ); $I->see( 'Contact Field Options' ); $I->see( 'Funnels' ); } public function see_list_view_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=listview' ); $I->see( 'List View', 'h1.header' ); $I->see( 'Not Contacted in X Days' ); $I->see( 'Allow Inline Edits' ); } public function save_list_view_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=listview' ); $I->fillField( 'wpzbscrm_notcontactedinx', '40' ); $I->click( 'Save Settings' ); $I->seeInField( 'wpzbscrm_notcontactedinx', '40' ); } public function see_tax_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=tax' ); $I->see( 'Tax Settings', 'h1.header' ); $I->see( 'Tax Rates' ); } public function save_tax_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=tax' ); $tax_data = array( 'jpcrm-taxtable-line[ids][]' => -1, 'jpcrm-taxtable-line[names][]' => 'IGIC', 'jpcrm-taxtable-line[rates][]' => 7.0, ); $I->submitForm( 'form', $tax_data ); $I->seeInSource( '{"id":"1","owner":"1","name":"IGIC","rate":"7.00"' ); } public function see_license_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=license' ); $I->see( 'License Key', 'h1.header' ); $I->see( 'License Key' ); } public function see_companies_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=companies' ); $I->see( 'Companies Settings', 'h1.header' ); $I->see( 'General B2B Settings' ); $I->see( 'Company Field Options' ); } public function save_companies_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=companies' ); $I->selectOption( 'jpcrm_setting_coororg', 'Domain' ); $I->fillField( 'jpcrm-status-companies', 'Lead,Customer,Refused,Priority' ); $I->click( 'Save Settings' ); $I->seeOptionIsSelected( 'jpcrm_setting_coororg', 'Domain' ); $I->seeInField( 'jpcrm-status-companies', 'Lead,Customer,Refused,Priority' ); } public function see_quotes_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=quotebuilder' ); $I->see( 'Quotes', 'h1.header' ); $I->see( 'Enable Quote Builder' ); } public function save_quotes_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=quotebuilder' ); $I->uncheckOption( 'wpzbscrm_usequotebuilder' ); $I->click( 'Save Settings' ); $I->dontSeeCheckboxIsChecked( 'wpzbscrm_usequotebuilder' ); $I->checkOption( 'wpzbscrm_usequotebuilder' ); $I->click( 'Save Settings' ); $I->seeCheckboxIsChecked( 'wpzbscrm_usequotebuilder' ); } public function see_invoicing_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=invbuilder' ); $I->see( 'Invoicing', 'h1.header' ); $I->see( 'Reference type' ); $I->see( 'Invoice reference label' ); $I->see( 'Extra Invoice Info' ); $I->see( 'Payment Info' ); $I->see( 'Thank You' ); $I->see( 'Extra Statement Info' ); $I->see( 'Hide Invoice ID' ); $I->see( 'Enable tax' ); $I->see( 'Enable discounts' ); $I->see( 'Enable shipping' ); } public function save_invoicing_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=invbuilder' ); $invoicing_data = array( 'refprefix' => 'INV-', 'refnextnum' => 2, 'refsuffix' => '-D', 'reflabel' => 'Ref', 'businessextra' => 'Company info', ); foreach ( $invoicing_data as $name => $data ) { $I->fillField( $name, $data ); } $I->click( 'Save Settings' ); foreach ( $invoicing_data as $name => $data ) { $I->seeInField( $name, $data ); } } public function see_transactions_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=transactions' ); $I->see( 'Transactions', 'h1.header' ); $I->see( 'Use Shipping' ); $I->see( 'Use Paid/Completed Dates' ); $I->see( 'Include these statuses in the transaction total value' ); $I->see( 'Transaction Status' ); $I->see( 'Additional settings on transactions' ); $I->see( 'Show fee' ); $I->see( 'Show tax' ); $I->see( 'Show discount' ); $I->see( 'Show net amount' ); } public function save_transactions_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=transactions' ); $I->uncheckOption( 'wpzbscrm_shippingfortransactions' ); $I->checkOption( 'wpzbscrm_paiddatestransaction' ); $I->checkOption( 'wpzbscrm_transaction_fee' ); $I->checkOption( 'wpzbscrm_transaction_tax' ); $I->checkOption( 'wpzbscrm_transaction_discount' ); $I->checkOption( 'wpzbscrm_transaction_net' ); $I->click( 'Save Settings' ); $I->seeCheckboxIsChecked( 'wpzbscrm_paiddatestransaction' ); $I->dontSeeCheckboxIsChecked( 'wpzbscrm_shippingfortransactions' ); $I->seeCheckboxIsChecked( 'wpzbscrm_transaction_fee' ); $I->seeCheckboxIsChecked( 'wpzbscrm_transaction_tax' ); $I->seeCheckboxIsChecked( 'wpzbscrm_transaction_discount' ); $I->seeCheckboxIsChecked( 'wpzbscrm_transaction_net' ); } public function see_forms_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=forms' ); $I->see( 'Forms', 'h1.header' ); $I->see( 'Enable reCaptcha' ); $I->see( 'reCaptcha Site Key' ); $I->see( 'reCaptcha Site Secret' ); } public function save_forms_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=forms' ); $I->click( 'Save Settings' ); } public function see_client_portal_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=clients' ); $I->see( 'Client Portal', 'h1.header' ); $I->see( 'Client Portal Page' ); $I->see( 'Allow Easy-Access Links' ); $I->see( 'Generate WordPress Users for new contacts' ); $I->see( 'Only Generate Users for Statuses' ); $I->see( 'Assign extra role when generating users' ); $I->see( 'Fields to hide on Portal' ); } public function save_client_portal_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=clients' ); $I->uncheckOption( 'wpzbscrm_easyaccesslinks' ); $I->click( 'Save Settings' ); $I->dontSeeCheckboxIsChecked( 'wpzbscrm_easyaccesslinks' ); } /* public function see_api_settings( AcceptanceTester $I ) { $I->goToPageViaSlug('settings', '&tab=api'); $I->see('API Settings', 'h1.header'); $I->see( 'API Endpoint' ); $I->see( 'API Key' ); $I->see( 'API Secret' ); }*/ public function see_mail_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=mail' ); $I->see( 'Mail Settings', 'h1.header' ); $I->see( 'Track Open Statistics' ); $I->see( 'Disable SSL Verification' ); $I->see( 'Format of Sender Name' ); $I->see( 'Email Unsubscribe Line' ); $I->see( 'Unsubscribe Page' ); $I->see( 'Email Unsubscribe Line' ); } public function save_mail_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=mail' ); $I->uncheckOption( 'wpzbscrm_emailtracking' ); $I->click( 'Save Settings' ); $I->dontSeeCheckboxIsChecked( 'wpzbscrm_emailtracking' ); } public function see_mail_delivery_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=maildelivery' ); $I->see( 'Mail Delivery', 'h1.header' ); } public function see_locale_settings( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=locale' ); $I->see( 'Currency Symbol', 'label' ); $I->see( 'Currency Format', 'label' ); $I->see( 'Install a font', 'label' ); } public function save_locale_settings_page( AcceptanceTester $I ) { $I->goToPageViaSlug( 'settings', '&tab=locale' ); $I->seeInField( 'wpzbscrm_currency', 'USD' ); $I->selectOption( 'select[name=wpzbscrm_currency]', 'EUR' ); $I->click( 'Save Settings', 'button' ); $I->seeInField( 'wpzbscrm_currency', 'EUR' ); } }
projects/plugins/crm/tests/codeception/acceptance/90_JPCRM_Admin_All_Pages_Cest.php
<?php /** * Load all the pages! */ class JPCRM_Admin_All_Pages_Cest { // make sure we are logged in public function _before( AcceptanceTester $I ) { $I->loginAsAdmin(); } /** * Page Checker * Loads all the slugs (and test for php errors!) * ...this is a temporary hackaround/test, it might not make sense as an acceptence test? * * @param AcceptanceTester $I */ public function see_http_responses_200( AcceptanceTester $I ) { // retrieve slugs $slugs = $I->getSlugs(); // cycle through the pages foreach ( $slugs as $slug => $page ) { // load page $I->goToPageViaSlug( $slug ); $I->seeResponseCodeIs( 200 ); } } }
projects/plugins/crm/tests/codeception/acceptance/16_JPCRM_Transactions_Cest.php
<?php /** * Transaction related tests */ class JPCRM_Transactions_Cest { protected $transaction_data = array( 'zbst_ref' => 'Transaction-ref-1', 'zbst_status' => 'Succeeded', 'zbst_title' => 'Transaction 1', 'zbst_total' => '111.30', 'zbst_date_datepart' => '2021-08-01', 'zbst_date_timepart' => '11:00', 'zbst_type' => 'Sale', 'zbst_desc' => 'This is the Transaction 1 description', 'zbst_shipping' => 5.5, 'zbst_shipping_taxes' => '', 'customer' => 1, 'invoice_id' => 1, ); protected $transaction_db_data = array( 'zbst_ref' => 'Transaction-ref-1', 'zbst_status' => 'Succeeded', 'zbst_title' => 'Transaction 1', 'zbst_total' => 111.30, 'zbst_date' => 1627815600, 'zbst_type' => 'Sale', 'zbst_desc' => 'This is the Transaction 1 description', 'zbst_shipping' => 5.5, 'zbst_shipping_taxes' => '', ); public function _before( AcceptanceTester $I ) { $I->loginAsAdmin(); } public function see_transactions_page( AcceptanceTester $I ) { $I->gotoAdminPage( 'transactions' ); $I->see( 'Transactions', '.jpcrm-learn-page-title' ); } public function see_new_transaction_page( AcceptanceTester $I ) { $I->gotoAdminPage( 'add-edit', '&action=edit&zbstype=transaction' ); $I->see( 'New Transaction', '.jpcrm-learn-page-title' ); } public function create_new_transaction( AcceptanceTester $I ) { $I->gotoAdminPage( 'add-edit', '&action=edit&zbstype=transaction' ); $I->seeInField( 'zbscrm_newtransaction', 1 ); // Get the generated transaction reference >>> doesn't work // $this->transaction_db_data['zbst_ref'] = $I->grabTextFrom( '#ref' ); $I->submitForm( '#zbs-edit-form', $this->transaction_data ); $I->seeInDatabase( $I->table( 'transactions' ), $this->transaction_db_data ); } public function see_created_transaction( AcceptanceTester $I ) { $I->gotoAdminPage( 'add-edit', '&action=edit&zbstype=transaction&zbsid=1' ); // todo: get zbst_ref value to check it in the view // $I->grabColumnFromDatabase() $transaction_view_data = array( 'zbst_ref' => $this->transaction_data['zbst_ref'], 'zbst_status' => $this->transaction_data['zbst_status'], 'zbst_title' => $this->transaction_data['zbst_title'], 'zbst_total' => $this->transaction_data['zbst_total'], 'zbst_date_datepart' => $this->transaction_data['zbst_date_datepart'], 'zbst_date_timepart' => $this->transaction_data['zbst_date_timepart'], 'zbst_type' => $this->transaction_data['zbst_type'], 'zbst_desc' => $this->transaction_data['zbst_desc'], 'customer' => $this->transaction_data['customer'], 'invoice_id' => $this->transaction_data['invoice_id'], ); $I->see( 'Edit Transaction', '.jpcrm-learn-page-title' ); foreach ( $transaction_view_data as $field => $value ) { $I->seeInField( $field, $value ); } } }
projects/plugins/crm/tests/codeception/acceptance/51_JPCRM_Extensions_Cest.php
<?php /** * Contact related tests */ class JPCRM_Extensions_Cest { public function _before( AcceptanceTester $I ) { $I->loginAsAdmin(); } public function see_modules_page( AcceptanceTester $I ) { $I->goToPageViaSlug( 'modules' ); $I->see( 'Core Modules', '#core-modules' ); } public function see_extensions_page( AcceptanceTester $I ) { $I->goToPageViaSlug( 'extensions' ); $I->see( 'Premium Extensions', '.box-title' ); } }
projects/plugins/crm/tests/codeception/acceptance/10_WP_Installation_Cest.php
<?php /** * Tests relating to the WordPress installation */ class WP_Installation_Cest { /** * Have database access * (can see the option `blogname`) */ public function has_database_access( AcceptanceTester $I ) { $I->seeInDatabase( 'wp_options', array( 'option_name' => 'blogname', 'option_value' => 'Jetpack CRM Testing Site', ) ); } /** * PHP server is up * / loads */ public function the_server_is_running( AcceptanceTester $I ) { $I->amOnPage( '/' ); $I->seeResponseCodeIsSuccessful(); $I->see( 'Jetpack CRM Testing Site' ); } /** * Has WP installed */ public function has_wp_admin_access( AcceptanceTester $I ) { $I->amOnPage( '/wp-admin' ); $I->seeResponseCodeIsSuccessful(); $I->seeInCurrentUrl( 'wp-login.php' ); } /** * Able to login as admin */ public function wp_login_as_admin( AcceptanceTester $I ) { $I->loginAsAdmin(); } }
projects/plugins/crm/tests/codeception/acceptance/11_JPCRM_Activation_Cest.php
<?php /** * Tests relating to the Activation of our WordPress plugin */ class JPCRM_Activation_Cest { public function _before( AcceptanceTester $I ) { $I->amOnPage( '/' ); $I->loginAsAdmin(); } // Sometimes WP has update pages to handle public function catch_wp_update_pages( AcceptanceTester $I ) { try { $I->see( 'Administration email verification' ); $I->click( '#correct-admin-email' ); } catch ( Exception $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch // continue tests } try { $I->see( 'Database Update Required' ); $I->amOnPage( 'upgrade.php?step=1&amp;backto=%2Fwp-admin%2F' ); } catch ( Exception $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch // continue tests } } public function jpcrm_activation( AcceptanceTester $I ) { // If it's installed, activate the plugin $I->amOnPluginsPage(); $I->seePluginInstalled( 'jetpack-crm' ); $I->activatePlugin( 'jetpack-crm' ); // Activating the plugin directly loads the welcome wizard, so no need to move pages here. // check no activation errors $I->dontSeeElement( '#message.error' ); // The plugin is activated, now we can see the JPCRM set up page $I->see( 'Essential Details' ); $I->see( 'Essentials' ); $I->see( 'Your Contacts' ); $I->see( 'Which Extensions?' ); $I->see( 'Finish' ); } }
projects/plugins/crm/tests/codeception/acceptance/13_JPCRM_Contacts_Cest.php
<?php /** * Contact related tests */ class JPCRM_Contacts_Cest { protected $user_data = array( 'zbsc_fname' => 'Testing user', 'zbsc_lname' => 'Last name', 'zbsc_status' => 'Customer', 'zbsc_email' => 'my_email@email.com', 'zbsc_addr1' => 'Address line 1', 'zbsc_addr2' => 'Address line 2', 'zbsc_city' => 'The City', 'zbsc_county' => 'The County', 'zbsc_country' => 'The Country', 'zbsc_postcode' => '1111', 'zbsc_secaddr1' => 'Address2 line 1', 'zbsc_secaddr2' => 'Address2 line 2', 'zbsc_seccity' => 'The City2', 'zbsc_seccounty' => 'The County2', 'zbsc_seccountry' => 'The Country2', 'zbsc_secpostcode' => '2222', 'zbsc_hometel' => '12345678', 'zbsc_worktel' => '87654321', 'zbsc_mobtel' => '11223344', ); protected $edit_user_data = array( 'zbsc_fname' => 'Testing user2', 'zbsc_lname' => 'Last name2', 'zbsc_status' => 'Lead', 'zbsc_email' => 'my_email2@email.com', 'zbsc_addr1' => 'Address3 line 1', 'zbsc_addr2' => 'Address3 line 2', 'zbsc_city' => 'The City3', 'zbsc_county' => 'The County3', 'zbsc_country' => 'The Country3', 'zbsc_postcode' => '3333', 'zbsc_secaddr1' => 'Address4 line 1', 'zbsc_secaddr2' => 'Address4 line 2', 'zbsc_seccity' => 'The City4', 'zbsc_seccounty' => 'The County4', 'zbsc_seccountry' => 'The Country4', 'zbsc_secpostcode' => '4444', 'zbsc_hometel' => '+3412345678', 'zbsc_worktel' => '+3487654321', 'zbsc_mobtel' => '+3411223344', ); public function _before( AcceptanceTester $I ) { $I->loginAsAdmin(); } public function see_contacts_page( AcceptanceTester $I ) { $I->gotoAdminPage( 'contacts' ); $I->see( 'Contacts', '.jpcrm-learn-page-title' ); } public function see_new_contact_page( AcceptanceTester $I ) { $I->gotoAdminPage( 'add-edit', '&action=edit&zbstype=contact' ); $I->see( 'New Contact', '.jpcrm-learn-page-title' ); } public function create_new_contact( AcceptanceTester $I ) { $I->gotoAdminPage( 'add-edit', '&action=edit&zbstype=contact' ); $I->submitForm( '#zbs-edit-form', $this->user_data ); $I->seeInDatabase( $I->table( 'contacts' ), $this->user_data ); // todo: add a tag } public function view_contact( AcceptanceTester $I ) { $I->gotoAdminPage( 'add-edit', '&action=view&zbstype=contact&zbsid=1' ); foreach ( $this->user_data as $data ) { $I->see( $data ); } } public function check_dashboard_has_the_added_contact( AcceptanceTester $I ) { $I->gotoAdminPage( 'dashboard' ); // See the contact data in the Latest Contacts block $I->see( 'Latest Contacts', '#settings_dashboard_latest_contacts_display' ); $I->see( $this->user_data['zbsc_fname'], '#settings_dashboard_latest_contacts_display' ); $I->see( $this->user_data['zbsc_lname'], '#settings_dashboard_latest_contacts_display' ); $I->see( $this->user_data['zbsc_status'], '#settings_dashboard_latest_contacts_display' ); } public function edit_contact( AcceptanceTester $I ) { $I->gotoAdminPage( 'add-edit', '&action=edit&zbstype=contact&zbsid=1' ); $I->submitForm( '#zbs-edit-form', $this->edit_user_data ); $I->seeInDatabase( $I->table( 'contacts' ), $this->edit_user_data ); } }
projects/plugins/crm/tests/codeception/acceptance/17_JPCRM_Tasks_Cest.php
<?php /** * Task related tests */ class JPCRM_Tasks_Cest { protected $task_data = array( 'zbse_title' => 'Task 1', 'zbse_owner' => '1', 'jpcrm_start_datepart' => '2021-01-26', 'jpcrm_start_timepart' => '17:58', 'jpcrm_end_datepart' => '2021-02-04', 'jpcrm_end_timepart' => '07:58', 'zbse_desc' => 'This is the task 1 description', 'zbse_show_on_cal' => 1, 'zbse_customer' => 1, 'zbse_company' => '', 'zbs-task-complete' => -1, 'zbs_remind_task_24' => '24', ); protected $task_db_data = array( 'zbse_title' => 'Task 1', 'zbs_owner' => '1', 'zbse_start' => 1611683880, 'zbse_end' => 1612425480, 'zbse_desc' => 'This is the task 1 description', 'zbse_show_on_cal' => 1, 'zbse_complete' => -1, ); public function _before( AcceptanceTester $I ) { $I->loginAsAdmin(); } public function see_tasks_page( AcceptanceTester $I ) { $I->gotoAdminPage( 'tasks' ); $I->see( 'Task Calendar', '.jpcrm-learn-page-title' ); } public function see_new_task_page( AcceptanceTester $I ) { $I->gotoAdminPage( 'add-edit', '&action=edit&zbstype=event' ); $I->see( 'New Task', '.jpcrm-learn-page-title' ); } public function create_new_task( AcceptanceTester $I ) { $I->gotoAdminPage( 'add-edit', '&action=edit&zbstype=event' ); $I->seeInField( 'zbscrm_newevent', 1 ); $I->submitForm( '#zbs-edit-form', $this->task_data ); $I->seeInDatabase( $I->table( 'events' ), $this->task_db_data ); } public function see_created_task( AcceptanceTester $I ) { $I->gotoAdminPage( 'add-edit', '&action=edit&zbstype=event&zbsid=1' ); $task_view_data = array( 'zbse_title' => $this->task_data['zbse_title'], 'jpcrm_start_datepart' => $this->task_data['jpcrm_start_datepart'], 'jpcrm_start_timepart' => $this->task_data['jpcrm_start_timepart'], 'jpcrm_end_datepart' => $this->task_data['jpcrm_end_datepart'], 'jpcrm_end_timepart' => $this->task_data['jpcrm_end_timepart'], 'zbse_desc' => $this->task_data['zbse_desc'], 'zbse_show_on_cal' => $this->task_data['zbse_show_on_cal'], 'zbse_customer' => $this->task_data['zbse_customer'], 'zbse_company' => $this->task_data['zbse_company'], 'zbs-task-complete' => $this->task_data['zbs-task-complete'], 'zbs_remind_task_24' => $this->task_data['zbs_remind_task_24'], ); $I->see( 'Edit Task', '.jpcrm-learn-page-title' ); foreach ( $task_view_data as $field => $value ) { $I->seeInField( $field, $value ); } } public function see_task_in_calendar( AcceptanceTester $I ) { $I->gotoAdminPage( 'tasks' ); $I->seeInTitle( 'Task Scheduler' ); $I->see( 'Task Calendar', '.jpcrm-learn-page-title' ); $task_view_data = array( 'zbse_title' => $this->task_data['zbse_title'], 'jpcrm_start_datepart' => $this->task_data['jpcrm_start_datepart'], 'jpcrm_start_timepart' => $this->task_data['jpcrm_start_timepart'], 'jpcrm_end_datepart' => $this->task_data['jpcrm_end_datepart'], 'jpcrm_end_timepart' => $this->task_data['jpcrm_end_timepart'], ); // Check the value in the Javascript script block foreach ( $task_view_data as $value ) { $I->seeInSource( $value ); } } }
projects/plugins/crm/tests/php/class-jpcrm-base-test-case.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Tests; use WP_UnitTestCase; use ZeroBSCRM; /** * Test case that ensures we never have global changes to ZBS that bleeds into other tests. */ class JPCRM_Base_Test_Case extends WP_UnitTestCase { /** * The original/initial ZBS instance. * * This can be used to always reset to the original state. * Use-case: someone has to mock part of ZBS for a specific outcome. E.g.: returning a fatal error? * * @since 6.2.0 * * @var ?ZeroBSCRM */ private $original_zbs; /** * Store the initial state of ZBS. * * @since 6.2.0 * * @return void */ public function set_up(): void { parent::set_up(); // We have to clone the value of $GLOBALS['zbs'] because just assigning // it to a static property will still create a reference which means // we would never restore the previous state. global $zbs; $this->original_zbs = clone $zbs; } /** * Restore the original state of ZBS. * * @since 6.2.0 * * @return void */ public function tear_down(): void { parent::tear_down(); global $zbs; $zbs = $this->original_zbs; } /** * Generate default contact data. * * @param array $args (Optional) A list of arguments we should use for the contact. * * @return array An array of basic contact data. */ public function generate_contact_data( $args = array() ): array { return wp_parse_args( $args, array( 'id' => -1, 'fname' => 'John', 'lname' => 'Doe', 'email' => 'dev@domain.null', 'status' => 'Lead', 'addr1' => 'My Street 1', 'addr2' => 'First floor', 'city' => 'New York', 'country' => 'US', 'postcode' => '10001', 'hometel' => '11111111', 'worktel' => '22222222', 'mobtel' => '33333333', ) ); } /** * Generate default invoice data. * * @param array $args (Optional) A list of arguments we should use for the invoice. * * @return array An array of basic contact data. */ public function generate_invoice_data( $args = array() ): array { return wp_parse_args( $args, array( 'id_override' => '1', 'parent' => 0, 'status' => 'Draft', 'due_date' => 1690840800, 'hash' => 'ISSQndSUjlhJ8feWj2v', 'lineitems' => array( array( 'net' => 3.75, 'desc' => 'Dummy product', 'quantity' => '3', 'price' => '1.25', 'total' => 3.75, ), ), 'contacts' => array( 1 ), 'created' => -1, ) ); } /** * Generate default transaction data. * * @param array $args (Optional) A list of arguments we should use for the transaction. * * @return array An array of basic transaction data. */ public function generate_transaction_data( $args = array() ): array { return wp_parse_args( $args, array( 'title' => 'Some transaction title', 'desc' => 'Some desc', 'ref' => 'TransactionReference_1', 'hash' => 'mASOpAnf334Pncl1px4', 'status' => 'Completed', 'type' => 'Sale', 'currency' => 'USD', 'total' => '150.00', 'tax' => '10.00', 'lineitems' => false, 'date' => 1676000000, 'date_completed' => 1676923766, 'created' => 1675000000, 'lastupdated' => 1675000000, ) ); } /** * Generate default company data. * * @param array $args (Optional) A list of arguments we should use for the company. * * @return array An array of basic company data. */ public function generate_company_data( $args = array() ): array { return wp_parse_args( $args, array( 'name' => 'My Company', 'email' => 'my@companyemail.com', 'status' => 'Lead', 'addr1' => 'My Street 1', 'addr2' => 'First floor', 'city' => 'New York', 'country' => 'US', 'postcode' => '10001', 'maintel' => '11111111', 'sectel' => '22222222', ) ); } /** * Generate default quote data. * * @param array $args (Optional) A list of arguments we should use for the quote. * * @return array An array of basic quote data. */ public function generate_quote_data( $args = array() ): array { return wp_parse_args( $args, array( 'id_override' => '1', 'title' => 'Some quote title', 'value' => '150.00', 'hash' => 'mASOpAnf334Pncl1px4', 'template' => 0, 'currency' => 'USD', 'date' => 1676000000, 'notes' => 'Some notes', 'send_attachments' => false, ) ); } /** * Generate default task data. * * @param array $args (Optional) A list of arguments we should use for the task. * * @return array An array of basic task data. */ public function generate_task_data( $args = array() ): array { return wp_parse_args( $args, array( 'title' => 'Some task title', 'desc' => 'Some description', 'start' => 1675000000, 'end' => 1676000000, 'complete' => false, 'show_on_portal' => false, 'show_on_calendar' => false, ) ); } }
projects/plugins/crm/tests/php/bootstrap.php
<?php /** * Bootstrap. * * @package automattic/jetpack-crm */ /** * The root directory of Jetpack CRM. */ define( 'JETPACK_CRM_TESTS_ROOT', __DIR__ ); /** * Assume we're in tests/php/bootstrap.php. */ $_plugin_root = dirname( __DIR__, 2 ); /** * Locate WordPress or wordpress-develop. We look in several places. */ if ( defined( 'WP_DEV_LOCATION' ) ) { $test_root = WP_DEVELOP_DIR; if ( file_exists( "$test_root/tests/phpunit/" ) ) { $test_root .= '/tests/phpunit/'; } } elseif ( false !== getenv( 'WP_DEVELOP_DIR' ) ) { // Jetpack Monorepo environment variable defined on command line. $test_root = getenv( 'WP_DEVELOP_DIR' ); if ( file_exists( "$test_root/tests/phpunit/" ) ) { $test_root .= '/tests/phpunit/'; } } elseif ( file_exists( '../../../../tests/phpunit/includes/bootstrap.php' ) ) { // Installed inside wordpress-develop. $test_root = '../../../../tests/phpunit'; } elseif ( file_exists( '/vagrant/www/wordpress-develop/public_html/tests/phpunit/includes/bootstrap.php' ) ) { // VVV. $test_root = '/vagrant/www/wordpress-develop/public_html/tests/phpunit'; } elseif ( file_exists( '/srv/www/wordpress-trunk/public_html/tests/phpunit/includes/bootstrap.php' ) ) { // VVV 3.0. $test_root = '/srv/www/wordpress-trunk/public_html/tests/phpunit'; } elseif ( file_exists( '/tmp/wordpress-develop/tests/phpunit/includes/bootstrap.php' ) ) { // Manual checkout & Jetpack's docker environment. $test_root = '/tmp/wordpress-develop/tests/phpunit'; } elseif ( file_exists( '/tmp/wordpress-tests-lib/includes/bootstrap.php' ) ) { // Legacy tests. $test_root = '/tmp/wordpress-tests-lib'; } if ( ! isset( $test_root ) || ! file_exists( $test_root . '/includes/bootstrap.php' ) ) { fprintf( STDERR, <<<'EOF' Failed to automatically locate WordPress or wordpress-develop to run tests. Set the WP_DEVELOP_DIR environment variable to point to a copy of WordPress or wordpress-develop. EOF ); exit( 1 ); } // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped echo "Using test root $test_root\n"; if ( ! is_readable( $_plugin_root . '/vendor/autoload.php' ) ) { echo 'The plugin is not ready for testing.' . PHP_EOL; echo PHP_EOL; echo 'Composer dependencies must be installed.' . PHP_EOL; exit( 1 ); } /** * Give access to tests_add_filter() function. */ require $test_root . '/includes/functions.php'; /** * Load Jetpack CRM. */ function _jpcrm_manually_load_plugin() { require_once JETPACK_CRM_TESTS_ROOT . '/../../ZeroBSCRM.php'; // Run all register_activation_hook() functions. global $zbs; $zbs->install(); zeroBSCRM_notifyme_createDBtable(); } tests_add_filter( 'muplugins_loaded', '_jpcrm_manually_load_plugin' ); /** * Start up the WP testing environment. */ require $test_root . '/includes/bootstrap.php'; /** * Make Jetpack CRM test case available for all tests. */ require_once JETPACK_CRM_TESTS_ROOT . '/class-jpcrm-base-test-case.php'; require_once JETPACK_CRM_TESTS_ROOT . '/class-jpcrm-base-integration-test-case.php'; /** * Load all feature flags, so they will be testable. */ add_filter( 'jetpack_crm_feature_flag_api_v4', '__return_true' ); add_filter( 'jetpack_crm_feature_flag_automations', '__return_true' );
projects/plugins/crm/tests/php/class-jpcrm-base-integration-test-case.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Tests; use Automattic\Jetpack\CRM\Entities\Contact; use Automattic\Jetpack\CRM\Entities\Factories\Contact_Factory; /** * Test case that ensures we have a clean and functioning Jetpack CRM instance. */ class JPCRM_Base_Integration_Test_Case extends JPCRM_Base_Test_Case { /** * Clean up the database after each test. * * @since 6.2.0 * * @return void */ public function tear_down(): void { parent::tear_down(); zeroBSCRM_database_reset( false ); } /** * Add a contact. * * @param array $args (Optional) A list of arguments we should use for the contact. * * @return int The contact ID. */ public function add_contact( array $args = array() ) { global $zbs; return $zbs->DAL->contacts->addUpdateContact( array( 'data' => $this->generate_contact_data( $args ) ) ); } /** * Add an invoice. * * @param array $args (Optional) A list of arguments we should use for the invoice. * * @return int The invoice ID. */ public function add_invoice( array $args = array() ) { global $zbs; return $zbs->DAL->invoices->addUpdateInvoice( array( 'data' => $this->generate_invoice_data( $args ) ) ); } /** * Add a transaction. * * @param array $args (Optional) A list of arguments we should use for the transaction. * * @return int The transaction ID. */ public function add_transaction( array $args = array() ) { global $zbs; return $zbs->DAL->transactions->addUpdateTransaction( array( 'data' => $this->generate_transaction_data( $args ) ) ); } /** * Get a contact. * * @param int|string $id The ID of the contact we want to get. * @param array $args (Optional) A list of arguments we should use for the contact. * @return Contact|null */ public function get_contact( $id, array $args = array() ) { global $zbs; $contact_data = $zbs->DAL->contacts->getContact( $id, $args ); return Contact_Factory::create( $contact_data ); } /** * Add a WP User. * * @return int The user ID. */ public function add_wp_user() { return wp_create_user( 'testuser', 'password', 'user@demo.com' ); } }
projects/plugins/crm/tests/php/automation/class-automation-engine-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Automation\Tests; use Automatic\Jetpack\CRM\Automation\Tests\Mocks\Empty_Slug_Trigger; use Automattic\Jetpack\CRM\Automation\Automation_Engine; use Automattic\Jetpack\CRM\Automation\Automation_Exception; use Automattic\Jetpack\CRM\Automation\Triggers\Contact_Created; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Test_Case; require_once __DIR__ . '/tools/class-automation-faker.php'; /** * Test Automation Engine * * @covers Automattic\Jetpack\CRM\Automation */ class Automation_Engine_Test extends JPCRM_Base_Test_Case { private $automation_faker; public function setUp(): void { parent::setUp(); $this->automation_faker = Automation_Faker::instance(); } /** * @testdox Automation Engine get singleton instance */ public function test_automation_engine_instance() { $automation_1 = Automation_Engine::instance(); $this->assertTrue( ( $automation_1 && $automation_1 instanceof Automation_Engine ) ); // Test a second instance should be the same as the first one $automation_2 = Automation_Engine::instance(); $this->assertEquals( $automation_1, $automation_2 ); } /** * @testdox Register a trigger to the automation engine * @throws Automation_Exception */ public function test_automation_register_trigger() { $automation = new Automation_Engine(); $automation->register_trigger( Contact_Created::class ); // Get the map of registered trigger_slug => trigger_classname $triggers = $automation->get_registered_triggers(); $this->assertCount( 1, $triggers ); $this->assertEquals( Contact_Created::class, $triggers['jpcrm/contact_created'] ); $expected_class = $automation->get_trigger_class( 'jpcrm/contact_created' ); $this->assertEquals( Contact_Created::class, $expected_class ); } /** * @testdox Register an empty trigger slug to the automation engine */ public function test_automation_register_empty_trigger_slug() { $automation = new Automation_Engine(); $this->expectException( Automation_Exception::class ); $this->expectExceptionCode( Automation_Exception::TRIGGER_SLUG_EMPTY ); $automation->register_trigger( Empty_Slug_Trigger::class ); } /** * @testdox Register a duplicated trigger class to the automation engine */ public function test_automation_register_duplicated_trigger() { $automation = new Automation_Engine(); $this->expectException( Automation_Exception::class ); $this->expectExceptionCode( Automation_Exception::TRIGGER_SLUG_EXISTS ); $automation->register_trigger( Contact_Created::class ); $automation->register_trigger( Contact_Created::class ); } /** * @testdox Register an invalid trigger class to the automation engine */ public function test_automation_register_invalid_trigger() { $automation = new Automation_Engine(); $this->expectException( Automation_Exception::class ); $this->expectExceptionCode( Automation_Exception::TRIGGER_CLASS_NOT_FOUND ); $automation->register_trigger( 'Invalid_Trigger_Class' ); } }
projects/plugins/crm/tests/php/automation/class-automation-workflow-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Automation\Tests; use Automatic\Jetpack\CRM\Automation\Tests\Mocks\Contact_Created_Trigger; use Automattic\Jetpack\CRM\Automation\Automation_Engine; use Automattic\Jetpack\CRM\Automation\Automation_Logger; use Automattic\Jetpack\CRM\Automation\Automation_Workflow; use Automattic\Jetpack\CRM\Automation\Base_Trigger; use Automattic\Jetpack\CRM\Automation\Data_Types\Contact_Data; use Automattic\Jetpack\CRM\Automation\Tests\Mocks\Contact_Condition; use Automattic\Jetpack\CRM\Automation\Tests\Mocks\Dummy_Step; use Automattic\Jetpack\CRM\Automation\Triggers\Contact_Updated; use Automattic\Jetpack\CRM\Automation\Workflow_Exception; use Automattic\Jetpack\CRM\Entities\Contact; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Test_Case; require_once __DIR__ . '/tools/class-automation-faker.php'; /** * Test Automation Workflow functionalities. * * @since 6.2.0 * * @covers Automattic\Jetpack\CRM\Automation */ class Automation_Workflow_Test extends JPCRM_Base_Test_Case { private $automation_faker; public function setUp(): void { parent::setUp(); $this->automation_faker = Automation_Faker::instance(); $this->automation_faker->reset_all(); } /** * @testdox Automation workflow initialization. */ public function test_automation_workflow_init() { $workflow_data = $this->automation_faker->basic_workflow(); $workflow = new Automation_Workflow( $workflow_data ); $this->assertEquals( 'Workflow Test: basic_workflow', $workflow->name ); } /** * @testdox Automation workflow with no triggers. */ public function test_automation_workflow_no_triggers() { $workflow_data = $this->automation_faker->empty_workflow(); $workflow = new Automation_Workflow( $workflow_data ); $this->assertCount( 0, $workflow->get_triggers() ); } /** * @testdox Automation workflow set initial step. */ public function test_automation_workflow_set_initial_step() { $workflow_data = $this->automation_faker->workflow_without_initial_step(); $engine = new Automation_Engine(); $workflow = new Automation_Workflow( $workflow_data ); $workflow->set_engine( $engine ); $workflow->set_steps( array( 0 => array( 'slug' => 'dummy_step_123', 'class_name' => Dummy_Step::class, ), ) ); $workflow->set_initial_step( 0 ); /** @var Contact $contact */ $contact = $this->automation_faker->contact(); $contact_data = new Contact_Data( $contact ); $automation_result = $workflow->execute( new Contact_Updated(), $contact_data ); $this->assertTrue( $automation_result ); } /** * @testdox Automation workflow with multiple triggers. */ public function test_workflow_triggers() { $workflow_data = $this->automation_faker->basic_workflow(); $workflow = new Automation_Workflow( $workflow_data ); $workflow->add_trigger( 'jpcrm/contact_updated' ); $workflow->add_trigger( 'jpcrm/contact_deleted' ); $this->assertCount( 3, $workflow->get_triggers() ); // Check if the triggers are added $triggers = $workflow->get_triggers(); $this->assertEquals( Contact_Created_Trigger::get_slug(), $triggers[0] ); $this->assertEquals( 'jpcrm/contact_updated', $triggers[1] ); $this->assertEquals( 'jpcrm/contact_deleted', $triggers[2] ); } /** * @testdox Testing turn on/off the workflow, to activate/deactivate it. */ public function test_workflow_turn_on_off() { $workflow_data = $this->automation_faker->basic_workflow(); $workflow = new Automation_Workflow( $workflow_data ); $workflow->turn_on(); $this->assertTrue( $workflow->is_active() ); $workflow->turn_off(); $this->assertFalse( $workflow->is_active() ); } /** * @testdox Testing the workflow execution if it's not active. */ public function test_workflow_execution_not_active() { $automation = new Automation_Engine(); $automation->set_automation_logger( Automation_Logger::instance() ); $automation->register_trigger( Contact_Created_Trigger::class ); $workflow_data = $this->automation_faker->workflow_without_initial_step(); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); $workflow->set_engine( $automation ); // Turn off the workflow $workflow->turn_off(); // Add and init the workflows $automation->add_workflow( $workflow ); $automation->init_workflows(); // We don't expect the workflow to be executed $workflow->expects( $this->never() ) ->method( 'execute' ); // Fake contact data $contact_data = $this->automation_faker->contact(); // Emit the contact_created event with the fake contact data $event_emitter = Event_Emitter::instance(); $event_emitter->emit_event( 'contact_created', $contact_data ); } /** * @testdox Test an automation workflow execution on contact_created event. */ public function test_workflow_execution_on_contact_created() { $logger = Automation_Logger::instance( true ); $automation = new Automation_Engine(); $automation->set_automation_logger( $logger ); $automation->register_trigger( Contact_Created_Trigger::class ); $workflow_data = $this->automation_faker->workflow_without_initial_step(); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); $workflow->set_engine( $automation ); // Add and init the workflows $automation->add_workflow( $workflow ); $automation->init_workflows(); // Fake event data $contact = $this->automation_faker->contact( false ); // We expect the workflow to be executed on contact_created event with the contact data $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $this->logicalAnd( $this->isInstanceOf( Base_Trigger::class ), $this->callback( function ( $trigger ) { return $trigger::get_slug() === Contact_Created_Trigger::get_slug(); } ) ), new Contact_Data( $contact ) ); // Emit the contact_created event with the fake contact data $event_emitter = Event_Emitter::instance(); $event_emitter->emit_event( 'contact_created', $contact ); } /** * @testdox Test an automation workflow execution with a dummy action. */ public function test_workflow_execution_with_dummy_action() { $logger = Automation_Logger::instance( true ); $automation = new Automation_Engine(); $automation->set_automation_logger( $logger ); $automation->register_trigger( Contact_Created_Trigger::class ); $automation->register_step( Dummy_Step::class ); $workflow_data = $this->automation_faker->workflow_without_initial_step(); $workflow = new Automation_Workflow( $workflow_data ); $workflow->set_logger( $logger ); $workflow->set_engine( $automation ); $workflow->set_steps( array( 0 => array( 'slug' => 'dummy_step', ), ) ); $workflow->set_initial_step( 0 ); // Add and init the workflows $automation->add_workflow( $workflow ); $automation->init_workflows(); // Fake event data $contact_data = $this->automation_faker->contact(); // Emit the contact_created event with the fake contact data $event_emitter = Event_Emitter::instance(); $event_emitter->emit_event( 'contact_created', $contact_data ); // Check the execution log $log = $logger->get_log(); $total_log = count( $log ); $this->assertGreaterThan( 4, $total_log ); $this->assertEquals( 'Workflow execution finished: No more steps found.', $log[ $total_log - 1 ][1] ); $this->assertEquals( 'Dummy step executed', $log[ $total_log - 3 ][1] ); } /** * @testdox Ensure that we throw an error if a workflow is executed without an engine. */ public function test_workflow_execution_without_engine() { $workflow_data = $this->automation_faker->basic_workflow(); $workflow = new Automation_Workflow( $workflow_data ); $this->expectException( Workflow_Exception::class ); $this->expectExceptionCode( Workflow_Exception::MISSING_ENGINE_INSTANCE ); $workflow->execute( new Contact_Created_Trigger(), null ); } /** * @testdox Test an automation workflow execution with condition => true. */ public function test_workflow_execution_with_condition_true() { $logger = Automation_Logger::instance( true ); $logger->reset_log(); $automation = new Automation_Engine(); $automation->set_automation_logger( $logger ); $automation->register_trigger( Contact_Created_Trigger::class ); $automation->register_step( Contact_Condition::class ); $automation->register_step( Dummy_Step::class ); $workflow_data = $this->automation_faker->workflow_with_condition_action(); $workflow = new Automation_Workflow( $workflow_data ); $automation->add_workflow( $workflow ); $automation->init_workflows(); // Fake event data $contact_data = $this->automation_faker->contact(); // Emit the contact_created event with the fake contact data $event_emitter = Event_Emitter::instance(); $event_emitter->emit_event( 'contact_created', $contact_data ); // Check the execution log $log = $logger->get_log(); $total_log = count( $log ); $this->assertGreaterThan( 7, $total_log ); $this->assertEquals( 'Condition met?: true', $log[ $total_log - 6 ][1] ); $this->assertEquals( '[contact_status] Step executed!', $log[ $total_log - 5 ][1] ); $this->assertEquals( 'Workflow execution finished: No more steps found.', $log[ $total_log - 1 ][1] ); } /** * @testdox Test an automation workflow execution with condition => false. */ public function test_workflow_execution_with_condition_false() { $logger = Automation_Logger::instance( true ); $logger->reset_log(); $automation = new Automation_Engine(); $automation->set_automation_logger( $logger ); $automation->register_trigger( Contact_Created_Trigger::class ); $automation->register_step( Contact_Condition::class ); $automation->register_step( Dummy_Step::class ); $workflow_data = $this->automation_faker->workflow_with_condition_action(); $workflow = new Automation_Workflow( $workflow_data ); $workflow->set_engine( $automation ); $automation->add_workflow( $workflow ); $automation->init_workflows(); // Fake event data. Set status to customer to make the condition false /** @var Contact $contact */ $contact = $this->automation_faker->contact(); $contact->status = 'customer'; // Emit the contact_created event with the fake contact data $event_emitter = Event_Emitter::instance(); $event_emitter->emit_event( 'contact_created', $contact ); // Check the execution log $log = $logger->get_log(); $total_log = count( $log ); $this->assertGreaterThan( 6, $total_log ); $this->assertEquals( 'Workflow execution finished: No more steps found.', $log[ $total_log - 1 ][1] ); $this->assertEquals( 'Condition met?: false', $log[ $total_log - 3 ][1] ); } }
projects/plugins/crm/tests/php/automation/class-workflow-repository-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Automation\Tests; use Automattic\Jetpack\CRM\Automation\Automation_Workflow; use Automattic\Jetpack\CRM\Automation\Workflow\Workflow_Repository; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Integration_Test_Case; require_once __DIR__ . '/tools/class-automation-faker.php'; /** * Test Automation Engine * * @covers Automattic\Jetpack\CRM\Automation */ class Workflow_Repository_Test extends JPCRM_Base_Integration_Test_Case { /** * @testdox Workflow Repository instance creation */ public function test_workflow_repository_instance() { $workflow_repo = new Workflow_Repository(); $this->assertInstanceOf( Workflow_Repository::class, $workflow_repo ); } /** * @testdox Persist a Workflow instance to the DB */ public function test_persist_workflow() { $workflow_data = Automation_Faker::instance()->workflow_with_condition_action(); $workflow = new Automation_Workflow( $workflow_data ); $repo = new Workflow_Repository(); $repo->persist( $workflow ); $workflow_persisted = $repo->find( $workflow->get_id() ); $this->assertEquals( $workflow->to_array(), $workflow_persisted->to_array() ); } /** * @testdox Retrieve all the Workflows */ public function test_retrieve_all_workflows() { $workflow_data = Automation_Faker::instance()->workflow_with_condition_action(); $workflow_1 = new Automation_Workflow( $workflow_data ); $workflow_data['name'] = 'Workflow 2'; $workflow_2 = new Automation_Workflow( $workflow_data ); $workflow_data['name'] = 'Workflow 3'; $workflow_3 = new Automation_Workflow( $workflow_data ); $repo = new Workflow_Repository(); $repo->persist( $workflow_1 ); $repo->persist( $workflow_2 ); $repo->persist( $workflow_3 ); $workflows_persisted = array( $workflow_1->get_id() => $workflow_1, $workflow_2->get_id() => $workflow_2, $workflow_3->get_id() => $workflow_3, ); $workflows = $repo->find_all(); $this->assertCount( 3, $workflows ); foreach ( $workflows as $workflow ) { $this->assertInstanceOf( Automation_Workflow::class, $workflow ); $this->assertEquals( $workflows_persisted[ $workflow->get_id() ]->to_array(), $workflow->to_array() ); } } /** * @testdox Delete a Workflow by ID */ public function test_delete_workflow() { $workflow_data = Automation_Faker::instance()->workflow_with_condition_action(); $workflow = new Automation_Workflow( $workflow_data ); $repo = new Workflow_Repository(); $repo->persist( $workflow ); $workflow_persisted = $repo->find( $workflow->get_id() ); // Check that it was persisted well $this->assertEquals( $workflow->to_array(), $workflow_persisted->to_array() ); // Delete the workflow. We pass the same because it should be updated with the ID. $repo->delete( $workflow ); // It should not be found anymore $workflow_persisted = $repo->find( $workflow->get_id() ); $this->assertFalse( $workflow_persisted ); } /** * @testdox Find by active workflows using a criteria. */ public function test_find_by_with_one_criteria() { $workflow_data = Automation_Faker::instance()->workflow_with_condition_action(); $workflow_1 = new Automation_Workflow( $workflow_data ); $workflow_data['name'] = 'Workflow 2'; $workflow_2 = new Automation_Workflow( $workflow_data ); $workflow_data['name'] = 'Workflow 3'; $workflow_3 = new Automation_Workflow( $workflow_data ); $workflow_1->turn_on(); $workflow_2->turn_off(); $workflow_3->turn_on(); $repo = new Workflow_Repository(); $repo->persist( $workflow_1 ); $repo->persist( $workflow_2 ); $repo->persist( $workflow_3 ); $workflows_persisted = array( $workflow_1->get_id() => $workflow_1, $workflow_2->get_id() => $workflow_2, $workflow_3->get_id() => $workflow_3, ); $workflows = $repo->find_by( array( 'active' => true, ) ); // It should return 2 workflows $this->assertCount( 2, $workflows ); // And they should match with the ones we persisted foreach ( $workflows as $workflow ) { $this->assertInstanceOf( Automation_Workflow::class, $workflow ); $this->assertEquals( $workflows_persisted[ $workflow->get_id() ]->to_array(), $workflow->to_array() ); } } /** * @testdox Find by workflows using two criterias. */ public function test_find_by_with_two_criterias() { $workflow_data = Automation_Faker::instance()->workflow_with_condition_action(); $workflow_1 = new Automation_Workflow( $workflow_data ); $workflow_data['name'] = 'Workflow 2'; $workflow_2 = new Automation_Workflow( $workflow_data ); $workflow_data['name'] = 'Workflow 3'; $workflow_3 = new Automation_Workflow( $workflow_data ); $workflow_1->turn_on(); $workflow_2->turn_off(); $workflow_3->turn_on(); $workflow_3->set_category( 'category_1' ); $repo = new Workflow_Repository(); $repo->persist( $workflow_1 ); $repo->persist( $workflow_2 ); $repo->persist( $workflow_3 ); $workflows_persisted = array( $workflow_1->get_id() => $workflow_1, $workflow_2->get_id() => $workflow_2, $workflow_3->get_id() => $workflow_3, ); $workflows = $repo->find_by( array( 'active' => true, 'category' => 'category_1', ) ); // It should return 1 workflow #3 $this->assertCount( 1, $workflows ); // And they should match with the ones we persisted foreach ( $workflows as $workflow ) { $this->assertInstanceOf( Automation_Workflow::class, $workflow ); $this->assertEquals( $workflows_persisted[ $workflow->get_id() ]->to_array(), $workflow->to_array() ); } } /** * DataProvider for pagination tests. * * These scenarios assume that we always have 5 workflows when defining expectations. * * @return array Pagination criteria. */ public function dataprovider_pagination_criteria() { return array( 'return all if we provide default arguments' => array( array( 'limit' => 0, 'offset' => 0, ), 5, ), 'return a specific amount if we provide a limit' => array( array( 'limit' => 3, 'offset' => 0, ), 3, ), 'return the remaining workflows if we provide an offset' => array( array( 'limit' => 0, 'offset' => 1, ), 4, ), 'return the last two workflows if we use a combination of limit and workflow' => array( array( 'limit' => 3, 'offset' => 3, ), 2, ), ); } /** * Find by pagination criteria. * * @dataProvider dataprovider_pagination_criteria * * @since 6.2.0 * * @param array $args Dynamic criteria for pagination. * @param int $expected_count The expected number of returned workflows. */ public function test_find_by_pagination( array $args, int $expected_count ) { $workflow_data = Automation_Faker::instance()->workflow_with_condition_action(); $repo = new Workflow_Repository(); // Create 5 workflows. for ( $i = 0; $i < 5; $i++ ) { $workflow_data['name'] = sprintf( 'Workflow %d', $i ); $workflow = new Automation_Workflow( $workflow_data ); $repo->persist( $workflow ); } $this->assertCount( $expected_count, $repo->find_by( array(), 'id', $args['limit'], $args['offset'] ) ); } }
projects/plugins/crm/tests/php/automation/mocks/mock-class-contact-created-trigger.php
<?php namespace Automatic\Jetpack\CRM\Automation\Tests\Mocks; use Automattic\Jetpack\CRM\Automation\Base_Trigger; use Automattic\Jetpack\CRM\Automation\Data_Types\Contact_Data; use Automattic\Jetpack\CRM\Automation\Tests\Event_Emitter; class Contact_Created_Trigger extends Base_Trigger { /** Get the slug name of the trigger * @return string */ public static function get_slug(): string { return 'jpcrm/contact_created_mock'; } /** Get the title of the trigger * @return string */ public static function get_title(): ?string { return __( 'Contact Created', 'zero-bs-crm' ); } /** Get the description of the trigger * @return string */ public static function get_description(): ?string { return __( 'Triggered when a CRM contact is created', 'zero-bs-crm' ); } /** Get the category of the trigger * @return string */ public static function get_category(): ?string { return 'contact'; } public static function get_data_type(): string { return Contact_Data::class; } /** * Listen to the desired event * * @return void */ protected function listen_to_event(): void { $event_emitter = Event_Emitter::instance(); $event_emitter->on( 'contact_created', array( $this, 'execute_workflow' ) ); } }
projects/plugins/crm/tests/php/automation/mocks/mock-class-trigger-empty-slug.php
<?php namespace Automatic\Jetpack\CRM\Automation\Tests\Mocks; use Automattic\Jetpack\CRM\Automation\Base_Trigger; use Automattic\Jetpack\CRM\Automation\Data_Types\Contact_Data; use Automattic\Jetpack\CRM\Automation\Tests\Event_Emitter; class Empty_Slug_Trigger extends Base_Trigger { /** Get the slug name of the trigger * @return string */ public static function get_slug(): string { return ''; } /** Get the title of the trigger * @return string */ public static function get_title(): ?string { return __( 'Contact Created', 'zero-bs-crm' ); } /** Get the description of the trigger * @return string */ public static function get_description(): ?string { return __( 'Triggered when a CRM contact is created', 'zero-bs-crm' ); } /** Get the category of the trigger * @return string */ public static function get_category(): ?string { return 'contact'; } /** * Get the data type of the trigger. * * @return string */ public static function get_data_type(): string { return Contact_Data::class; } /** * Listen to the desired event */ protected function listen_to_event(): void { $event_emitter = Event_Emitter::instance(); $event_emitter->on( 'contact_created', array( $this, 'execute_workflow' ) ); } }
projects/plugins/crm/tests/php/automation/mocks/mock-class-contact-condition.php
<?php namespace Automattic\Jetpack\CRM\Automation\Tests\Mocks; use Automattic\Jetpack\CRM\Automation\Automation_Exception; use Automattic\Jetpack\CRM\Automation\Base_Condition; use Automattic\Jetpack\CRM\Automation\Data_Types\Contact_Data; use Automattic\Jetpack\CRM\Automation\Data_Types\Data_Type; use Automattic\Jetpack\CRM\Entities\Contact; use Automattic\Jetpack\CRM\Entities\Factories\Contact_Factory; class Contact_Condition extends Base_Condition { /** @var string[] Valid contact keys */ private $valid_contact_keys = array( 'id', 'name', 'email', 'status', 'data', ); /** @var string[] Valid operators */ protected $valid_operators = array( 'is', 'is_not', ); /** @var string[] Valid condition attributes */ private $valid_attributes = array( 'field', 'operator', 'value', ); /** * Override set_attributes method to add some checks. * * @throws Automation_Exception */ public function set_attributes( array $attributes ) { parent::set_attributes( $attributes ); if ( ! $this->has_valid_attributes() && ! $this->has_valid_operator() ) { throw new Automation_Exception( 'Invalid attributes for contact condition' ); } } /** * Validate the contact data * * @param array $contact_data * @return bool */ private function is_valid_contact_data( array $contact_data ): bool { // Check if the contact data has at least the required keys if ( ! array_intersect( $this->valid_contact_keys, array_keys( $contact_data ) ) ) { return false; } return true; } /** * Check if the condition has valid attributes * * @return bool */ private function has_valid_attributes(): bool { if ( ! array_intersect( $this->valid_attributes, array_keys( $this->get_attributes() ) ) ) { return false; } return true; } /** * Check if it has a valid operator * * @return bool */ private function has_valid_operator(): bool { $operator = $this->get_attributes()['operator']; if ( ! in_array( $operator, $this->valid_operators, true ) ) { return false; } return true; } /** * Execute the step * * @param Data_Type $data_type Data passed from the trigger. * @return void * * @throws Automation_Exception */ public function execute( Data_Type $data_type ): void { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable if ( ! $data_type instanceof Contact_Data ) { $this->logger->log( 'Invalid data type' ); $this->condition_met = false; return; } /** @var Contact $contact */ $contact = $data_type->get_data(); $data = Contact_Factory::tidy_data( $contact ); if ( ! $this->is_valid_contact_data( $data ) ) { $this->logger->log( 'Invalid contact data' ); $this->condition_met = false; return; } $field = $this->get_attributes()['field']; $operator = $this->get_attributes()['operator']; $value = $this->get_attributes()['value']; $this->logger->log( 'Condition: ' . $field . ' ' . $operator . ' ' . $value . ' => ' . $data[ $field ] ); switch ( $operator ) { case 'is': $this->condition_met = ( $data[ $field ] === $value ); $this->logger->log( 'Condition met?: ' . ( $this->condition_met ? 'true' : 'false' ) ); return; case 'is_not': $this->condition_met = ( $data[ $field ] !== $value ); $this->logger->log( 'Condition met?: ' . ( $this->condition_met ? 'true' : 'false' ) ); return; } $this->condition_met = false; $this->logger->log( 'Invalid operator: ' . $operator ); throw new Automation_Exception( 'Invalid operator: ' . $operator ); } public static function get_slug(): string { return 'contact_status'; } public static function get_title(): ?string { return 'Contact Status'; } public static function get_description(): ?string { return 'Check if a contact has a specific status'; } public static function get_data_type(): string { return Contact_Data::class; } public static function get_category(): ?string { return 'testing'; } }
projects/plugins/crm/tests/php/automation/mocks/mock-class-dummy-step.php
<?php namespace Automattic\Jetpack\CRM\Automation\Tests\Mocks; use Automattic\Jetpack\CRM\Automation\Automation_Logger; use Automattic\Jetpack\CRM\Automation\Base_Step; use Automattic\Jetpack\CRM\Automation\Data_Types\Contact_Data; use Automattic\Jetpack\CRM\Automation\Data_Types\Data_Type; class Dummy_Step extends Base_Step { /** * {@inheritDoc} */ public function execute( Data_Type $data ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable Automation_Logger::instance()->log( 'Dummy step executed' ); } public static function get_slug(): string { return 'dummy_step'; } public static function get_title(): ?string { return 'Dummy Step'; } public static function get_description(): ?string { return 'Dummy step for testing purposes'; } public static function get_data_type(): string { return Contact_Data::class; } public static function get_category(): ?string { return 'testing'; } }
projects/plugins/crm/tests/php/automation/tasks/class-task-trigger-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Automation\Tests; use Automattic\Jetpack\CRM\Automation\Automation_Engine; use Automattic\Jetpack\CRM\Automation\Automation_Workflow; use Automattic\Jetpack\CRM\Automation\Data_Types\Task_Data; use Automattic\Jetpack\CRM\Automation\Triggers\Task_Created; use Automattic\Jetpack\CRM\Automation\Triggers\Task_Deleted; use Automattic\Jetpack\CRM\Automation\Triggers\Task_Updated; use Automattic\Jetpack\CRM\Entities\Task; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Test_Case; require_once __DIR__ . '../../tools/class-automation-faker.php'; /** * Test Automation's task triggers * * @covers Automattic\Jetpack\CRM\Automation\Triggers\Task_Created * @covers Automattic\Jetpack\CRM\Automation\Triggers\Task_Deleted * @covers Automattic\Jetpack\CRM\Automation\Triggers\Task_Updated */ class Task_Trigger_Test extends JPCRM_Base_Test_Case { private $automation_faker; public function setUp(): void { parent::setUp(); $this->automation_faker = Automation_Faker::instance(); } /** * @testdox Test the task created trigger executes the workflow with an action */ public function test_task_created_trigger() { $workflow_data = $this->automation_faker->workflow_without_initial_step_customize_trigger( 'jpcrm/task_created' ); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); // Init the Task_Created trigger. $trigger = new Task_Created(); $trigger->init( $workflow ); /** @var Task $task */ $task = $this->automation_faker->task(); $task_data = new Task_Data( $task ); // We expect the workflow to be executed on task_created event with the task data. $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $trigger, $task_data ); // Run the task_created action. do_action( 'jpcrm_task_created', $task ); } /** * @testdox Test the task deleted trigger executes the workflow with an action */ public function test_task_deleted_trigger() { $workflow_data = $this->automation_faker->workflow_without_initial_step_customize_trigger( 'jpcrm/task_deleted' ); $trigger = new Task_Deleted(); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); // Init the Task_Deleted trigger. $trigger->init( $workflow ); /** @var Task $task */ $task = $this->automation_faker->task(); $task_data = new Task_Data( $task ); // We expect the workflow to be executed on task_deleted event with the task data. $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $trigger, $task_data ); // Run the task_deleted action. do_action( 'jpcrm_task_delete', $task ); } /** * @testdox Test the task updated trigger executes the workflow with an action */ public function test_task_updated_trigger() { $workflow_data = $this->automation_faker->workflow_without_initial_step_customize_trigger( 'jpcrm/task_updated' ); $trigger = new Task_Updated(); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); $workflow->set_engine( new Automation_Engine() ); // Init the Task_Updated trigger. $trigger->init( $workflow ); /** @var Task $task */ $task = $this->automation_faker->task(); $task_data = new Task_Data( $task ); // We expect the workflow to be executed on task_updated event with the task data. $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $trigger, $task_data ); // Run the task_updated action. do_action( 'jpcrm_task_updated', $task ); } }
projects/plugins/crm/tests/php/automation/tools/class-automation-faker.php
<?php namespace Automattic\Jetpack\CRM\Automation\Tests; use Automatic\Jetpack\CRM\Automation\Tests\Mocks\Contact_Created_Trigger; use Automattic\Jetpack\CRM\Automation\Automation_Engine; use Automattic\Jetpack\CRM\Automation\Automation_Logger; use Automattic\Jetpack\CRM\Automation\Conditions\Contact_Field_Changed; use Automattic\Jetpack\CRM\Automation\Data_Type_Exception; use Automattic\Jetpack\CRM\Automation\Tests\Mocks\Contact_Condition; use Automattic\Jetpack\CRM\Automation\Tests\Mocks\Dummy_Step; use Automattic\Jetpack\CRM\Entities\Company; use Automattic\Jetpack\CRM\Entities\Contact; use Automattic\Jetpack\CRM\Entities\Factories\Company_Factory; use Automattic\Jetpack\CRM\Entities\Factories\Contact_Factory; use Automattic\Jetpack\CRM\Entities\Factories\Invoice_Factory; use Automattic\Jetpack\CRM\Entities\Factories\Quote_Factory; use Automattic\Jetpack\CRM\Entities\Factories\Task_Factory; use Automattic\Jetpack\CRM\Entities\Factories\Transaction_Factory; use Automattic\Jetpack\CRM\Entities\Invoice; use Automattic\Jetpack\CRM\Entities\Quote; use Automattic\Jetpack\CRM\Entities\Tag; use Automattic\Jetpack\CRM\Entities\Task; use Automattic\Jetpack\CRM\Entities\Transaction; require_once __DIR__ . '/class-event-emitter.php'; class Automation_Faker { private static $instance; public static function instance(): Automation_Faker { if ( ! self::$instance ) { self::$instance = new self(); } return self::$instance; } /** * Automation_Faker constructor. */ public function __construct() { $this->load_mocks(); } public function reset_all() { // Reset the event emitter Event_Emitter::instance()->reset(); // Reset the Automation_Logger Automation_Logger::instance( true ); // Reset the Automation_Engine Automation_Engine::instance( true ); // Remove all WP actions, starting by jpcrm_. global $wp_filter; foreach ( $wp_filter as $tag => $actions ) { if ( str_starts_with( $tag, 'jpcrm_' ) ) { remove_all_actions( $tag ); } } } /** * Return a basic workflow * @return array */ public function basic_workflow(): array { return array( 'name' => 'Workflow Test: basic_workflow', 'description' => 'Test: the description of the workflow', 'category' => 'Test', 'active' => true, 'triggers' => array( Contact_Created_Trigger::get_slug(), ), 'initial_step' => 0, 'steps' => array( // Step 0 0 => array( 'slug' => 'send_email_action', 'attributes' => array( 'to' => 'admin@example.com', 'template' => 'send_welcome_email', ), 'next_step_true' => null, ), ), ); } /** * Return a basic workflow with a trigger and without initial step * @return array */ public function workflow_without_initial_step(): array { return array( 'name' => 'Workflow Test: without_initial_step', 'description' => 'Test: the description of the workflow', 'category' => 'Test', 'active' => true, 'triggers' => array( Contact_Created_Trigger::get_slug(), ), ); } /** * Return a basic workflow with a customizable trigger and without initial step * * @param string $trigger_name The name of the trigger to be included in the workflow. * * @return array */ public function workflow_without_initial_step_customize_trigger( $trigger_name ): array { return array( 'name' => 'Workflow Test: without_initial_step_customize_trigger', 'description' => 'Test: the description of the workflow', 'category' => 'Test', 'active' => true, 'triggers' => array( $trigger_name, ), ); } /** * Return dummy contact triggers name list * @return array */ public function contact_triggers(): array { return array( 'jpcrm/contact_created', 'jpcrm/contact_updated', 'jpcrm/contact_deleted', ); } /** * Return dummy quote triggers name list * @return array */ public function quote_triggers(): array { return array( 'jpcrm/quote_created', 'jpcrm/quote_accepted', 'jpcrm/quote_updated', 'jpcrm/quote_status_updated', 'jpcrm/quote_deleted', ); } /** * Return dummy invoice triggers name list * @return array */ public function invoice_triggers(): array { return array( 'invoice_created', 'invoice_updated', 'invoice_deleted', ); } /** * Return dummy task triggers name list * * @return array */ public function task_triggers(): array { return array( 'jpcrm/task_created', 'jpcrm/task_deleted', 'jpcrm/task_updated', ); } /** * Return dummy transaction triggers name list * * @return array */ public function transaction_triggers(): array { return array( 'jpcrm/transaction_created', 'jpcrm/transaction_updated', ); } /** * Return a workflow with a condition and an action * @return array */ public function workflow_with_condition_action(): array { return array( 'name' => 'Workflow Test: with_condition_action', 'description' => 'Test: the description of the workflow', 'category' => 'Test', 'active' => true, 'triggers' => array( Contact_Created_Trigger::get_slug(), ), 'initial_step' => 0, 'steps' => array( // Step 0 0 => array( 'slug' => Contact_Condition::get_slug(), 'next_step_true' => 1, 'next_step_false' => null, 'attributes' => array( 'field' => 'status', 'operator' => 'is', 'value' => 'lead', ), ), // Step 1 1 => array( 'slug' => Dummy_Step::get_slug(), 'next_step_true' => null, 'next_step_false' => null, 'attributes' => array(), ), ), ); } /** * Return a workflow with a condition and an action * @return array */ public function workflow_with_condition_customizable_trigger_action( $trigger_slug, $action_data ): array { return array( 'name' => 'Workflow Test: with_condition_customizable_trigger_action', 'description' => 'Test: the description of the workflow', 'category' => 'Test', 'active' => true, 'triggers' => array( $trigger_slug, ), 'initial_step' => 0, 'steps' => array( // Step 0 0 => array( 'slug' => Contact_Field_Changed::get_slug(), 'attributes' => array( 'field' => 'status', 'operator' => 'is', 'value' => 'Lead', ), 'next_step_true' => 1, 'next_step_false' => null, ), // Step 1 1 => $action_data, ), ); } /** * Load all mock classes present in the mocks folder * * @return void */ private function load_mocks() { $mocks_dir = __DIR__ . '/../mocks/'; $mocks = scandir( $mocks_dir ); foreach ( $mocks as $mock ) { if ( str_starts_with( $mock, 'mock-class-' ) ) { require_once $mocks_dir . $mock; } } } /** * Return a dummy Contact. * * @return Contact A Contact object. */ public function contact(): Contact { $data = array( 'id' => 1, 'owner' => '-1', 'status' => 'lead', 'fname' => 'John', 'lname' => 'Doe', 'email' => 'johndoe@example.com', 'prefix' => 'Mr', 'addr1' => 'My Street 1', 'addr2' => '', 'city' => 'San Francisco', 'county' => 'CA', 'postcode' => '94110', 'country' => 'US', 'secaddr_addr1' => '', 'secaddr_addr2' => '', 'secaddr_city' => '', 'secaddr_county' => '', 'secaddr_country' => '', 'secaddr_postcode' => '', 'hometel' => '', 'worktel' => '', 'mobtel' => '(877) 273-3049', 'wpid' => '', 'avatar' => '', 'tw' => '', 'li' => '', 'fb' => '', 'created' => '1691193339', 'lastupdated' => '1691193339', 'lastcontacted' => '', 'lastlog' => '', 'lastcontactlog' => '', 'tags' => array( array( 'id' => 1, 'objtype' => 1, 'name' => 'Name 1', 'slug' => 'name-1', 'created' => 1692663411, 'lastupdated' => 1692663411, ), array( 'id' => 2, 'objtype' => 1, 'name' => 'Name 2', 'slug' => 'name-2', 'created' => 1692663412, 'lastupdated' => 1692663412, ), ), ); return Contact_Factory::create( $data ); } /** * Return a dummy Invoice. * * @return Invoice A Invoice object. */ public function invoice(): Invoice { $data = array( 'id' => 1, 'id_override' => '1', 'parent' => '', 'status' => 'Unpaid', 'due_date' => 1690840800, 'hash' => 'ISSQndSUjlhJ8feWj2v', 'lineitems' => array( array( 'net' => 3.75, 'desc' => 'Dummy product', 'quantity' => '3', 'price' => '1.25', 'total' => 3.75, ), 'contacts' => array( 1 ), 'created' => -1, 'tags' => array( array( 'id' => 1, 'objtype' => 1, 'name' => 'Name 1', 'slug' => 'name-1', 'created' => 1692663411, 'lastupdated' => 1692663411, ), array( 'id' => 2, 'objtype' => 1, 'name' => 'Name 2', 'slug' => 'name-2', 'created' => 1692663412, 'lastupdated' => 1692663412, ), ), ), ); return Invoice_Factory::create( $data ); } /** * Return a dummy Quote. * * @return Quote A Quote object. */ public function quote(): Quote { $data = array( 'id' => 1, 'id_override' => '1', 'title' => 'Quote title', 'hash' => 'V8jAlsi0#$ksm0Plsxp', 'value' => 150.00, 'currency' => 'USD', 'template' => 1676923766, 'accepted' => 1676923766, 'created' => 1676000000, 'tags' => array( array( 'id' => 1, 'objtype' => 1, 'name' => 'Name 1', 'slug' => 'name-1', 'created' => 1692663411, 'lastupdated' => 1692663411, ), array( 'id' => 2, 'objtype' => 1, 'name' => 'Name 2', 'slug' => 'name-2', 'created' => 1692663412, 'lastupdated' => 1692663412, ), ), ); return Quote_Factory::create( $data ); } /** * Return a Company. * * @return Company A Company object. */ public function company(): Company { $data = array( 'id' => 1, 'name' => 'Dummy Company', 'email' => 'johndoe@dummycompany.com', 'addr1' => 'Address 1', 'status' => 'lead', 'tags' => array( array( 'id' => 1, 'objtype' => 1, 'name' => 'Name 1', 'slug' => 'name-1', 'created' => 1692663411, 'lastupdated' => 1692663411, ), array( 'id' => 2, 'objtype' => 1, 'name' => 'Name 2', 'slug' => 'name-2', 'created' => 1692663412, 'lastupdated' => 1692663412, ), ), ); return Company_Factory::create( $data ); } /** * Return dummy Task. * * @return Task A Task object. */ public function task(): Task { $data = array( 'id' => 1, 'title' => 'Some task title', 'desc' => 'Some desc', 'hash' => 'V8jAlsi0#$ksm0Plsxp', 'start' => 1676000000, 'end' => 1676923766, 'complete' => false, 'show_in_portal' => true, 'show_in_cal' => true, 'created' => 1675000000, 'lastupdated' => 1675000000, 'tags' => array( array( 'id' => 1, 'objtype' => 1, 'name' => 'Name 1', 'slug' => 'name-1', 'created' => 1692663411, 'lastupdated' => 1692663411, ), array( 'id' => 2, 'objtype' => 1, 'name' => 'Name 2', 'slug' => 'name-2', 'created' => 1692663412, 'lastupdated' => 1692663412, ), ), ); return Task_Factory::create( $data ); } /** * Return a dummy Transaction. * * @return Transaction A Transaction object. */ public function transaction(): Transaction { $data = array( 'id' => 1, 'title' => 'Some transaction title', 'desc' => 'Some desc', 'hash' => 'mASOpAnf334Pncl1px4', 'status' => 'Completed', 'type' => 'Sale', 'ref' => '123456', 'currency' => 'USD', 'total' => '150.00', 'tax' => '10.00', 'lineitems' => array(), 'date' => 1676000000, 'date_completed' => 1676923766, 'created' => 1675000000, 'lastupdated' => 1675000000, 'tags' => array( array( 'id' => 1, 'objtype' => 1, 'name' => 'Name 1', 'slug' => 'name-1', 'created' => 1692663411, 'lastupdated' => 1692663411, ), array( 'id' => 2, 'objtype' => 1, 'name' => 'Name 2', 'slug' => 'name-2', 'created' => 1692663412, 'lastupdated' => 1692663412, ), ), ); return Transaction_Factory::create( $data ); } /** * Return data for a dummy tag. * * @return Tag A sample Tag instance. */ public function tag(): Tag { $tag_data = array( 'id' => 1, 'name' => 'Some tag name', 'slug' => 'tag_slug', 'objtype' => 'Contact', 'created' => 1675000000, 'lastupdated' => 1675000000, ); // @todo: Use the factory when it is ready: return Tag_Factory::create( $tag ); $tag = new Tag(); foreach ( $tag_data as $key => $value ) { $tag->$key = $value; } return $tag; } /** * Return data for a dummy tag. * * @param array|null $additional_array An array with additional data to be added to the tag list. * * @return array * @throws Data_Type_Exception */ public function tag_list( array $additional_array = null ) { $data = array( array( 'id' => 1, 'objtype' => 1, 'name' => 'Name 1', 'slug' => 'name-1', 'created' => 1692663411, 'lastupdated' => 1692663411, ), array( 'id' => 2, 'objtype' => 1, 'name' => 'Name 2', 'slug' => 'name-2', 'created' => 1692663412, 'lastupdated' => 1692663412, ), ); if ( $additional_array !== null ) { $data[] = $additional_array; } return $data; } /** * Return a empty workflow, without triggers and initial step * * @return array */ public function empty_workflow(): array { return array( 'name' => 'Empty workflow Test', ); } }
projects/plugins/crm/tests/php/automation/tools/class-event-emitter.php
<?php namespace Automattic\Jetpack\CRM\Automation\Tests; class Event_Emitter { private $listeners = array(); private static $instance = null; public static function instance(): Event_Emitter { if ( ! self::$instance ) { self::$instance = new self(); } return self::$instance; } public static function on( $event, $listener ) { self::instance()->add_listener( $event, $listener ); } // Add a listener for an event public function add_listener( $event, $listener ) { if ( ! isset( $this->listeners[ $event ] ) ) { $this->listeners[ $event ] = array(); } $this->listeners[ $event ][] = $listener; } // emit an event public static function emit( $event, $data = null ) { self::instance()->emit_event( $event, $data ); } public function emit_event( $event, $data = null ) { if ( isset( $this->listeners[ $event ] ) ) { foreach ( $this->listeners[ $event ] as $listener ) { $listener( $data ); } } } /** * Reset the event emitter */ public function reset() { $this->listeners = array(); } }
projects/plugins/crm/tests/php/automation/invoices/class-invoice-trigger-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Automation\Tests; use Automattic\Jetpack\CRM\Automation\Automation_Workflow; use Automattic\Jetpack\CRM\Automation\Data_Types\Invoice_Data; use Automattic\Jetpack\CRM\Automation\Triggers\Invoice_Created; use Automattic\Jetpack\CRM\Automation\Triggers\Invoice_Deleted; use Automattic\Jetpack\CRM\Automation\Triggers\Invoice_Status_Updated; use Automattic\Jetpack\CRM\Automation\Triggers\Invoice_Updated; use Automattic\Jetpack\CRM\Entities\Invoice; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Test_Case; require_once __DIR__ . '../../tools/class-automation-faker.php'; /** * Test Automation Workflow functionalities * * @covers Automattic\Jetpack\CRM\Automation */ class Invoice_Trigger_Test extends JPCRM_Base_Test_Case { private $automation_faker; public function setUp(): void { parent::setUp(); $this->automation_faker = Automation_Faker::instance(); } /** * @testdox Test the invoice updated trigger executes the workflow with an action */ public function test_invoice_updated_trigger() { $workflow_data = $this->automation_faker->workflow_without_initial_step_customize_trigger( 'jpcrm/invoice_updated' ); $trigger = new Invoice_Updated(); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); // Init the Invoice_Updated trigger. $trigger->init( $workflow ); /** @var Invoice $invoice */ $invoice = $this->automation_faker->invoice(); $invoice_data = new Invoice_Data( $invoice ); // We expect the workflow to be executed on invoice_update event with the invoice data $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $trigger, $invoice_data ); // Run the invoice_update action. do_action( 'jpcrm_invoice_updated', $invoice ); } /** * @testdox Test the invoice status updated trigger executes the workflow with an action */ public function test_invoice_status_updated_trigger() { $workflow_data = $this->automation_faker->workflow_without_initial_step_customize_trigger( 'jpcrm/invoice_status_updated' ); $trigger = new Invoice_Status_Updated(); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); // Init the Invoice_Updated trigger. $trigger->init( $workflow ); /** @var Invoice $invoice */ $invoice = $this->automation_faker->invoice(); $invoice_data = new Invoice_Data( $invoice ); // We expect the workflow to be executed on invoice_status_update event with the invoice data $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $trigger, $invoice_data ); // Run the invoice_status_update action. do_action( 'jpcrm_invoice_status_updated', $invoice ); } /** * @testdox Test the invoice new trigger executes the workflow with an action */ public function test_invoice_created_trigger() { $workflow_data = $this->automation_faker->workflow_without_initial_step_customize_trigger( 'jpcrm/invoice_created' ); $trigger = new Invoice_Created(); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); // Init the Invoice_Created trigger. $trigger->init( $workflow ); /** @var Invoice $invoice */ $invoice = $this->automation_faker->invoice(); $invoice_data = new Invoice_Data( $invoice ); // We expect the workflow to be executed on invoice_created event with the invoice data $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $trigger, $invoice_data ); // Run the invoice_created action. do_action( 'jpcrm_invoice_created', $invoice ); } /** * @testdox Test the invoice deleted trigger executes the workflow with an action */ public function test_invoice_deleted_trigger() { $workflow_data = $this->automation_faker->workflow_without_initial_step_customize_trigger( 'jpcrm/invoice_deleted' ); $trigger = new Invoice_Deleted(); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); // Init the Invoice_Deleted trigger. $trigger->init( $workflow ); /** @var Invoice $invoice */ $invoice = $this->automation_faker->invoice(); $invoice_data = new Invoice_Data( $invoice ); // We expect the workflow to be executed on invoice_deleted event with the invoice data $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $trigger, $invoice_data ); // Run the invoice_deleted action. do_action( 'jpcrm_invoice_deleted', $invoice ); } }
projects/plugins/crm/tests/php/automation/invoices/class-invoice-condition-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Automation\Tests; use Automattic\Jetpack\CRM\Automation\Automation_Exception; use Automattic\Jetpack\CRM\Automation\Conditions\Invoice_Field_Contains; use Automattic\Jetpack\CRM\Automation\Conditions\Invoice_Status_Changed; use Automattic\Jetpack\CRM\Automation\Data_Types\Invoice_Data; use Automattic\Jetpack\CRM\Entities\Invoice; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Test_Case; require_once __DIR__ . '../../tools/class-automation-faker.php'; /** * Test Automation Invoice Conditions. * * @covers Automattic\Jetpack\CRM\Automation\Conditions\Invoice_Status_Changed * @covers Automattic\Jetpack\CRM\Automation\Conditions\Invoice_Field_Contains */ class Invoice_Condition_Test extends JPCRM_Base_Test_Case { private $automation_faker; public function setUp(): void { parent::setUp(); $this->automation_faker = Automation_Faker::instance(); $this->automation_faker->reset_all(); } private function get_invoice_status_changed_condition( $operator, $expected_value ) { $condition_data = array( 'slug' => 'jpcrm/condition/invoice_status_changed', 'attributes' => array( 'field' => 'status', 'operator' => $operator, 'value' => $expected_value, ), ); return new Invoice_Status_Changed( $condition_data ); } private function get_invoice_field_contains_condition( $field, $operator, $expected_value ) { $condition_data = array( 'slug' => 'jpcrm/condition/invoice_field_contains', 'attributes' => array( 'field' => $field, 'operator' => $operator, 'value' => $expected_value, ), ); return new Invoice_Field_Contains( $condition_data ); } /** * @testdox Test the update invoice status condition for the is operator. */ public function test_status_changed_is_operator() { $invoice_status_changed_condition = $this->get_invoice_status_changed_condition( 'is', 'paid' ); /** @var Invoice $invoice */ $invoice = $this->automation_faker->invoice(); $invoice_data = new Invoice_Data( $invoice ); // Testing when the condition has been met. $invoice->status = 'paid'; $invoice_status_changed_condition->validate_and_execute( $invoice_data ); $this->assertTrue( $invoice_status_changed_condition->condition_met() ); // Testing when the condition has not been met. $invoice->status = 'unpaid'; $invoice_status_changed_condition->validate_and_execute( $invoice_data ); $this->assertFalse( $invoice_status_changed_condition->condition_met() ); } /** * @testdox Test the update invoice status condition for the is_not operator. */ public function test_status_changed_is_not_operator() { $invoice_status_changed_condition = $this->get_invoice_status_changed_condition( 'is_not', 'paid' ); /** @var Invoice $invoice */ $invoice = $this->automation_faker->invoice(); $invoice_data = new Invoice_Data( $invoice ); // Testing when the condition has been met. $invoice->status = 'unpaid'; $invoice_status_changed_condition->validate_and_execute( $invoice_data ); $this->assertTrue( $invoice_status_changed_condition->condition_met() ); // Testing when the condition has not been met. $invoice->status = 'paid'; $invoice_status_changed_condition->validate_and_execute( $invoice_data ); $this->assertFalse( $invoice_status_changed_condition->condition_met() ); } /** * @testdox Test if an exception is being correctly thrown for wrong operators. */ public function test_status_changed_invalid_operator_throws_exception() { $invoice_status_changed_condition = $this->get_invoice_status_changed_condition( 'wrong_operator', 'paid' ); /** @var Invoice $invoice */ $invoice = $this->automation_faker->invoice(); $invoice_data = new Invoice_Data( $invoice ); $this->expectException( Automation_Exception::class ); $this->expectExceptionCode( Automation_Exception::CONDITION_INVALID_OPERATOR ); $invoice_status_changed_condition->validate_and_execute( $invoice_data ); } /** * @testdox Test the update invoice field contains condition for the contains operator. */ public function test_field_contains_contains_operator() { $invoice_field_contains_condition = $this->get_invoice_field_contains_condition( 'status', 'contains', 'ai' ); /** @var Invoice $invoice */ $invoice = $this->automation_faker->invoice(); $invoice_data = new Invoice_Data( $invoice ); // Testing when the condition has been met. $invoice->status = 'paid'; $invoice_field_contains_condition->validate_and_execute( $invoice_data ); $this->assertTrue( $invoice_field_contains_condition->condition_met() ); // Testing when the condition has not been met. $invoice->status = 'draft'; $invoice_field_contains_condition->validate_and_execute( $invoice_data ); $this->assertFalse( $invoice_field_contains_condition->condition_met() ); } /** * @testdox Test the update invoice field contains condition for the does_not_contain operator. */ public function test_field_contains_does_not_contain_operator() { $invoice_field_contains_condition = $this->get_invoice_field_contains_condition( 'status', 'does_not_contain', 'ai' ); /** @var Invoice $invoice */ $invoice = $this->automation_faker->invoice(); $invoice_data = new Invoice_Data( $invoice ); // Testing when the condition has been met. $invoice->status = 'draft'; $invoice_field_contains_condition->validate_and_execute( $invoice_data ); $this->assertTrue( $invoice_field_contains_condition->condition_met() ); // Testing when the condition has not been met. $invoice->status = 'paid'; $invoice_field_contains_condition->validate_and_execute( $invoice_data ); $this->assertFalse( $invoice_field_contains_condition->condition_met() ); } /** * @testdox Test if an exception is being correctly thrown for wrong operators. */ public function test_field_contains_invalid_operator_throws_exception() { $invoice_field_contains_condition = $this->get_invoice_field_contains_condition( 'status', 'wrong_operator', 'paid' ); /** @var Invoice $invoice */ $invoice = $this->automation_faker->invoice(); $invoice_data = new Invoice_Data( $invoice ); $this->expectException( Automation_Exception::class ); $this->expectExceptionCode( Automation_Exception::CONDITION_INVALID_OPERATOR ); $invoice_field_contains_condition->validate_and_execute( $invoice_data ); } }
projects/plugins/crm/tests/php/automation/invoices/actions/class-set-invoice-status-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Automation\Tests; use Automattic\Jetpack\CRM\Automation\Actions\Set_Invoice_Status; use Automattic\Jetpack\CRM\Automation\Automation_Engine; use Automattic\Jetpack\CRM\Automation\Automation_Workflow; use Automattic\Jetpack\CRM\Automation\Triggers\Invoice_Created; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Integration_Test_Case; /** * Test Automation Workflow functionalities * * @covers Automattic\Jetpack\CRM\Automation\Actions\Set_Invoice_Status_Test */ class Set_Invoice_Status_Test extends JPCRM_Base_Integration_Test_Case { /** * A helper class to generate data for the automation tests. * * @since 6.2.0 * * @var Automation_Faker */ private $automation_faker; /** * {@inheritdoc} */ public function setUp(): void { parent::setUp(); $this->automation_faker = Automation_Faker::instance(); $this->automation_faker->reset_all(); } /** * @testdox Test the set invoice status action executes the action, within a workflow. */ public function test_set_invoice_status_action_with_workflow() { global $zbs; $automation = new Automation_Engine(); $automation->register_trigger( Invoice_Created::class ); $automation->register_step( Set_Invoice_Status::class ); $workflow_data = array( 'name' => 'Set Invoice Action Workflow Test', 'description' => 'This is a test', 'category' => 'Test', 'active' => true, 'triggers' => array( Invoice_Created::get_slug(), ), 'initial_step' => 0, 'steps' => array( 0 => array( 'slug' => Set_Invoice_Status::get_slug(), 'attributes' => array( 'new_status' => 'Paid', ), 'next_step_true' => null, ), ), ); $workflow = new Automation_Workflow( $workflow_data ); $workflow->set_engine( $automation ); $automation->add_workflow( $workflow ); $automation->init_workflows(); $invoice_id = $this->add_invoice( array( 'status' => 'Draft' ) ); $invoice = $zbs->DAL->invoices->getInvoice( $invoice_id ); $this->assertSame( 'Paid', $invoice['status'] ); } }
projects/plugins/crm/tests/php/automation/wordpress/class-wp-user-trigger-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Automation\Tests; use Automattic\Jetpack\CRM\Automation\Automation_Workflow; use Automattic\Jetpack\CRM\Automation\Triggers\WP_User_Created; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Integration_Test_Case; require_once __DIR__ . '../../tools/class-automation-faker.php'; /** * Test Automation Workflow functionalities * * @covers Automattic\Jetpack\CRM\Automation */ class WP_User_Trigger_Test extends JPCRM_Base_Integration_Test_Case { /** @var Automation_Faker */ private $automation_faker; public function setUp(): void { parent::setUp(); $this->automation_faker = Automation_Faker::instance(); } /** * @testdox Test the create WP User trigger executes the workflow with an action */ public function test_wp_user_created_trigger() { $workflow_data = $this->automation_faker->workflow_without_initial_step_customize_trigger( 'jpcrm/wp_user_created' ); $trigger = new WP_User_Created(); // Build a PHPUnit mock Automation_Workflow. $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); // Init the WP_User_Created trigger. $trigger->init( $workflow ); // We expect the workflow to be executed on event with the WP User data. $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $trigger, $this->callback( function ( $object ) { return $object->get_data() instanceof \WP_User; } ) ); // User data captured from the WP User data creation. $this->add_wp_user(); } }
projects/plugins/crm/tests/php/automation/quotes/class-quote-condition-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Automation\Tests; use Automattic\Jetpack\CRM\Automation\Automation_Exception; use Automattic\Jetpack\CRM\Automation\Conditions\Quote_Status_Changed; use Automattic\Jetpack\CRM\Automation\Data_Types\Quote_Data; use Automattic\Jetpack\CRM\Entities\Quote; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Test_Case; require_once __DIR__ . '../../tools/class-automation-faker.php'; /** * Test Automation Quote Conditions. * * @covers Automattic\Jetpack\CRM\Automation\Conditions\Quote_Status_Changed */ class Quote_Condition_Test extends JPCRM_Base_Test_Case { private $automation_faker; public function setUp(): void { parent::setUp(); $this->automation_faker = Automation_Faker::instance(); $this->automation_faker->reset_all(); } private function get_quote_status_changed_condition( $operator, $expected_value ) { $condition_data = array( 'slug' => 'jpcrm/condition/quote_status_changed', 'attributes' => array( 'operator' => $operator, 'value' => $expected_value, ), ); return new Quote_Status_Changed( $condition_data ); } /** * @testdox Test the update quote status condition for the is operator. */ public function test_status_changed_is_operator() { $quote_status_changed_condition = $this->get_quote_status_changed_condition( 'is', 'accepted' ); /** @var Quote $quote */ $quote = $this->automation_faker->quote(); $quote_data = new Quote_Data( $quote ); // Testing when the condition has been met. $quote->accepted = '1'; $quote->template = '1'; $quote_status_changed_condition->validate_and_execute( $quote_data ); $this->assertTrue( $quote_status_changed_condition->condition_met() ); // Testing when the condition has not been met. $quote->accepted = '0'; $quote->template = '0'; $quote_status_changed_condition->validate_and_execute( $quote_data ); $this->assertFalse( $quote_status_changed_condition->condition_met() ); } /** * @testdox Test the update quote status condition for the is_not operator. */ public function test_status_changed_is_not_operator() { $quote_status_changed_condition = $this->get_quote_status_changed_condition( 'is_not', 'accepted' ); /** @var Quote $quote */ $quote = $this->automation_faker->quote(); $quote_data = new Quote_Data( $quote ); // Testing when the condition has been met. $quote->accepted = '0'; $quote->template = '0'; $quote_status_changed_condition->validate_and_execute( $quote_data ); $this->assertTrue( $quote_status_changed_condition->condition_met() ); // Testing when the condition has not been met. $quote->accepted = '1'; $quote->template = '1'; $quote_status_changed_condition->validate_and_execute( $quote_data ); $this->assertFalse( $quote_status_changed_condition->condition_met() ); } /** * @testdox Test if an exception is being correctly thrown for wrong operators. */ public function test_status_changed_invalid_operator_throws_exception() { $quote_status_changed_condition = $this->get_quote_status_changed_condition( 'wrong_operator', 'draft' ); /** @var Quote $quote */ $quote = $this->automation_faker->quote(); $quote_data = new Quote_Data( $quote ); $this->expectException( Automation_Exception::class ); $this->expectExceptionCode( Automation_Exception::CONDITION_INVALID_OPERATOR ); $quote_status_changed_condition->validate_and_execute( $quote_data ); } }
projects/plugins/crm/tests/php/automation/quotes/class-quote-trigger-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Automation\Tests; use Automattic\Jetpack\CRM\Automation\Automation_Workflow; use Automattic\Jetpack\CRM\Automation\Data_Types\Quote_Data; use Automattic\Jetpack\CRM\Automation\Triggers\Quote_Accepted; use Automattic\Jetpack\CRM\Automation\Triggers\Quote_Created; use Automattic\Jetpack\CRM\Automation\Triggers\Quote_Deleted; use Automattic\Jetpack\CRM\Automation\Triggers\Quote_Status_Updated; use Automattic\Jetpack\CRM\Automation\Triggers\Quote_Updated; use Automattic\Jetpack\CRM\Entities\Quote; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Test_Case; require_once __DIR__ . '../../tools/class-automation-faker.php'; /** * Test Automation's quote triggers * * @covers Automattic\Jetpack\CRM\Automation */ class Quote_Trigger_Test extends JPCRM_Base_Test_Case { private $automation_faker; public function setUp(): void { parent::setUp(); $this->automation_faker = Automation_Faker::instance(); } /** * @testdox Test the quote updated trigger executes the workflow with an action */ public function test_quote_updated_trigger() { $workflow_data = $this->automation_faker->workflow_without_initial_step_customize_trigger( 'jpcrm/quote_updated' ); $trigger = new Quote_Updated(); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); // Init the Quote_Updated trigger. $trigger->init( $workflow ); /** @var Quote $quote */ $quote = $this->automation_faker->quote(); $quote_data = new Quote_Data( $quote ); // We expect the workflow to be executed on quote_update event with the quote data $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $trigger, $quote_data ); // Run the quote_update action. do_action( 'jpcrm_quote_update', $quote ); } /** * @testdox Test the quote status updated trigger executes the workflow with an action */ public function test_quote_status_updated_trigger() { $workflow_data = $this->automation_faker->workflow_without_initial_step_customize_trigger( 'jpcrm/quote_status_updated' ); $trigger = new Quote_Status_Updated(); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); // Init the Quote_Updated trigger. $trigger->init( $workflow ); /** @var Quote $quote */ $quote = $this->automation_faker->quote(); $quote_data = new Quote_Data( $quote ); // We expect the workflow to be executed on quote_status_update event with the quote data $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $trigger, $quote_data ); // Run the quote_status_update action. do_action( 'jpcrm_quote_status_update', $quote ); } /** * @testdox Test the quote created trigger executes the workflow with an action */ public function test_quote_created_trigger() { $workflow_data = $this->automation_faker->workflow_without_initial_step_customize_trigger( 'jpcrm/quote_created' ); $trigger = new Quote_Created(); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); // Init the Quote_Created trigger. $trigger->init( $workflow ); /** @var Quote $quote */ $quote = $this->automation_faker->quote(); $quote_data = new Quote_Data( $quote ); // We expect the workflow to be executed on quote_created event with the quote data $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $trigger, $quote_data ); // Run the quote_created action. do_action( 'jpcrm_quote_created', $quote ); } /** * @testdox Test the quote new trigger executes the workflow with an action */ public function test_quote_accepted_trigger() { $workflow_data = $this->automation_faker->workflow_without_initial_step_customize_trigger( 'jpcrm/quote_accepted' ); $trigger = new Quote_Accepted(); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); // Init the Quote_Created trigger. $trigger->init( $workflow ); /** @var Quote $quote */ $quote = $this->automation_faker->quote(); $quote_data = new Quote_Data( $quote ); // We expect the workflow to be executed on quote_created event with the quote data $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $trigger, $quote_data ); // Notify the quote_accepted event. do_action( 'jpcrm_quote_accepted', $quote ); } /** * @testdox Test the quote deleted trigger executes the workflow with an action */ public function test_quote_deleted_trigger() { $workflow_data = $this->automation_faker->workflow_without_initial_step_customize_trigger( 'jpcrm/quote_deleted' ); $trigger = new Quote_Deleted(); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); // Init the Quote_Deleted trigger. $trigger->init( $workflow ); /** @var Quote $quote */ $quote = $this->automation_faker->quote(); $quote_data = new Quote_Data( $quote ); // We expect the workflow to be executed on quote_deleted event with the quote data $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $trigger, $quote_data ); // Run the quote_deleted action. do_action( 'jpcrm_quote_delete', $quote ); } }
projects/plugins/crm/tests/php/automation/contacts/class-contact-trigger-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Automation\Tests; use Automattic\Jetpack\CRM\Automation\Automation_Workflow; use Automattic\Jetpack\CRM\Automation\Data_Types\Contact_Data; use Automattic\Jetpack\CRM\Automation\Triggers\Contact_Before_Deleted; use Automattic\Jetpack\CRM\Automation\Triggers\Contact_Created; use Automattic\Jetpack\CRM\Automation\Triggers\Contact_Deleted; use Automattic\Jetpack\CRM\Automation\Triggers\Contact_Email_Updated; use Automattic\Jetpack\CRM\Automation\Triggers\Contact_Status_Updated; use Automattic\Jetpack\CRM\Automation\Triggers\Contact_Updated; use Automattic\Jetpack\CRM\Entities\Contact; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Test_Case; require_once __DIR__ . '../../tools/class-automation-faker.php'; /** * Test Automation Workflow functionalities * * @covers Automattic\Jetpack\CRM\Automation */ class Contact_Trigger_Test extends JPCRM_Base_Test_Case { private $automation_faker; public function setUp(): void { parent::setUp(); $this->automation_faker = Automation_Faker::instance(); $this->automation_faker->reset_all(); } /** * @testdox Test the contact updated trigger executes the workflow with an action */ public function test_contact_updated_trigger() { $workflow_data = $this->automation_faker->workflow_without_initial_step_customize_trigger( 'jpcrm/contact_updated' ); $trigger = new Contact_Updated(); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); // Init the Contact_Updated trigger. $trigger->init( $workflow ); // Fake event data. /** @var Contact $contact */ $contact = $this->automation_faker->contact(); $contact_data = new Contact_Data( $contact ); // We expect the workflow to be executed on contact_update event with the contact data $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $trigger, $contact_data ); // Run the contact_update action. do_action( 'jpcrm_contact_updated', $contact ); } /** * @testdox Test the contact status updated trigger executes the workflow with an action */ public function test_contact_status_updated_trigger() { $workflow_data = $this->automation_faker->workflow_without_initial_step_customize_trigger( 'jpcrm/contact_status_updated' ); $trigger = new Contact_Status_Updated(); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); // Init the Contact_Status_Updated trigger. $trigger->init( $workflow ); // Fake event data. /** @var Contact $contact */ $contact = $this->automation_faker->contact(); $previous_contact = clone $contact; $contact_data = new Contact_Data( $contact, $previous_contact ); $previous_contact->status = 'Refused'; // We expect the workflow to be executed on contact_status_update event with the contact data $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $trigger, $contact_data ); // Run the contact_status_update action. do_action( 'jpcrm_contact_status_updated', $contact, $previous_contact ); } /** * @testdox Test the contact new trigger executes the workflow with an action */ public function test_contact_created_trigger() { $workflow_data = $this->automation_faker->workflow_without_initial_step_customize_trigger( 'jpcrm/contact_created' ); $trigger = new Contact_Created(); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); // Init the Contact_Created trigger. $trigger->init( $workflow ); // Fake event data. /** @var Contact $contact */ $contact = $this->automation_faker->contact(); $contact_data = new Contact_Data( $contact ); // We expect the workflow to be executed on contact_created event with the contact data $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $trigger, $contact_data ); // Run the contact_created action. do_action( 'jpcrm_contact_created', $contact ); } /** * @testdox Test the contact email updated trigger executes the workflow with an action */ public function test_contact_email_updated_trigger() { $workflow_data = $this->automation_faker->workflow_without_initial_step_customize_trigger( 'jpcrm/contact_email_updated' ); $trigger = new Contact_Email_Updated(); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); // Init the Contact_Email_Updated trigger. $trigger->init( $workflow ); // Fake contact data /** @var Contact $contact */ $contact = $this->automation_faker->contact(); $contact_data = new Contact_Data( $contact ); // We expect the workflow to be executed on contact_email_update event with the contact data $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $trigger, $contact_data ); // Run the contact_email_update action. do_action( 'jpcrm_contact_email_updated', $contact ); } /** * @testdox Test the contact deleted trigger executes the workflow with an action */ public function test_contact_deleted_trigger() { $workflow_data = $this->automation_faker->workflow_without_initial_step_customize_trigger( 'jpcrm/contact_deleted' ); $trigger = new Contact_Deleted(); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); // Init the Contact_Deleted trigger. $trigger->init( $workflow ); // Fake event data. /** @var Contact $contact */ $contact = $this->automation_faker->contact(); $contact_data = new Contact_Data( $contact ); // We expect the workflow to be executed on contact_deleted event with the contact data $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $trigger, $contact_data ); // Run the contact_deleted action. do_action( 'jpcrm_contact_deleted', $contact ); } /** * @testdox Test the contact before deleted trigger executes the workflow with an action */ public function test_contact_before_deleted_trigger() { $workflow_data = $this->automation_faker->workflow_without_initial_step_customize_trigger( 'jpcrm/contact_before_deleted' ); $trigger = new Contact_Before_Deleted(); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); // Init the Contact_Before_Deleted trigger. $trigger->init( $workflow ); /** @var Contact $contact */ $contact = $this->automation_faker->contact(); $contact_data = new Contact_Data( $contact ); // We expect the workflow to be executed on contact_before_deleted event with the contact data $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $trigger, $contact_data ); // Run the contact_before_deleted action. do_action( 'jpcrm_contact_before_deleted', $contact ); } }
projects/plugins/crm/tests/php/automation/contacts/class-contact-condition-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Automation\Tests; use Automattic\Jetpack\CRM\Automation\Automation_Exception; use Automattic\Jetpack\CRM\Automation\Conditions\Contact_Field_Changed; use Automattic\Jetpack\CRM\Automation\Conditions\Contact_Tag; use Automattic\Jetpack\CRM\Automation\Conditions\Contact_Transitional_Status; use Automattic\Jetpack\CRM\Automation\Data_Types\Contact_Data; use Automattic\Jetpack\CRM\Entities\Contact; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Test_Case; require_once __DIR__ . '../../tools/class-automation-faker.php'; /** * Test Automation Workflow functionalities * * @covers Automattic\Jetpack\CRM\Automation\Conditions\Contact_Field_Changed * @covers Automattic\Jetpack\CRM\Automation\Conditions\Contact_Transitional_Status * @covers Automattic\Jetpack\CRM\Automation\Conditions\Contact_Tag */ class Contact_Condition_Test extends JPCRM_Base_Test_Case { private $automation_faker; public function setUp(): void { parent::setUp(); $this->automation_faker = Automation_Faker::instance(); $this->automation_faker->reset_all(); } private function get_contact_field_changed_condition( $operator, $expected_value ) { $condition_data = array( 'slug' => 'jpcrm/condition/contact_field_changed', 'attributes' => array( 'field' => 'status', 'operator' => $operator, 'value' => $expected_value, ), ); return new Contact_Field_Changed( $condition_data ); } private function get_contact_transitional_status_condition( $operator, $from_status, $to_status ) { $condition_data = array( 'slug' => 'jpcrm/condition/contact_status_transitional', 'attributes' => array( 'operator' => $operator, 'previous_status_was' => $from_status, 'new_status_is' => $to_status, ), ); return new Contact_Transitional_Status( $condition_data ); } private function get_contact_tag_condition( $operator, $tag ) { $condition_data = array( 'slug' => 'jpcrm/condition/contact_tag', 'attributes' => array( 'operator' => $operator, 'tag' => $tag, ), ); return new Contact_Tag( $condition_data ); } /** * @testdox Test the update contact field condition for the is operator. */ public function test_field_changed_is_operator() { $contact_field_changed_condition = $this->get_contact_field_changed_condition( 'is', 'customer' ); /** @var Contact $contact */ $contact = $this->automation_faker->contact(); // Any update on $contact instance will be reflected on $contact_data. $contact_data = new Contact_Data( $contact ); // Testing when the condition has been met. $contact->status = 'customer'; $contact_field_changed_condition->validate_and_execute( $contact_data ); $this->assertTrue( $contact_field_changed_condition->condition_met() ); // Testing when the condition has not been met. $contact->status = 'lead'; $contact_field_changed_condition->validate_and_execute( $contact_data ); $this->assertFalse( $contact_field_changed_condition->condition_met() ); } /** * @testdox Test the update contact field condition for the is_not operator. */ public function test_field_changed_is_not_operator() { $contact_field_changed_condition = $this->get_contact_field_changed_condition( 'is_not', 'customer' ); /** @var Contact $contact */ $contact = $this->automation_faker->contact(); $contact_data = new Contact_Data( $contact ); // Testing when the condition has been met. $contact->status = 'lead'; $contact_field_changed_condition->validate_and_execute( $contact_data ); $this->assertTrue( $contact_field_changed_condition->condition_met() ); // Testing when the condition has not been met. $contact->status = 'customer'; $contact_field_changed_condition->validate_and_execute( $contact_data ); $this->assertFalse( $contact_field_changed_condition->condition_met() ); } /** * @testdox Test if an exception is being correctly thrown for wrong operators. */ public function test_field_changed_invalid_operator_throws_exception() { $contact_field_changed_condition = $this->get_contact_field_changed_condition( 'wrong_operator', 'customer' ); /** @var Contact $contact */ $contact = $this->automation_faker->contact(); $this->expectException( Automation_Exception::class ); $this->expectExceptionCode( Automation_Exception::CONDITION_INVALID_OPERATOR ); $contact_field_changed_condition->validate_and_execute( new Contact_Data( $contact ) ); } /** * @testdox Test if an exception is being correctly thrown for wrong operators for transitional status. */ public function test_transitional_status_invalid_operator_throws_exception() { $contact_transitional_status_condition = $this->get_contact_transitional_status_condition( 'wrong_operator', 'old_status', 'new_status' ); $this->expectException( Automation_Exception::class ); $this->expectExceptionCode( Automation_Exception::CONDITION_INVALID_OPERATOR ); /** @var Contact $contact */ $contact = $this->automation_faker->contact(); $previous_contact = clone $contact; $previous_contact->status = 'old_status'; $contact_data = new Contact_Data( $contact, $previous_contact ); $contact_transitional_status_condition->validate_and_execute( $contact_data ); } /** * @testdox Test if transitional status correctly detects the correct statuses. */ public function test_transitional_status() { $contact_transitional_status_condition = $this->get_contact_transitional_status_condition( 'from_to', 'old_status', 'new_status' ); /** @var Contact $contact */ $contact = $this->automation_faker->contact(); // Create a previous state of a contact. $previous_contact = clone $contact; $contact_data = new Contact_Data( $contact, $previous_contact ); // Testing when the condition has been met. $contact->status = 'new_status'; $previous_contact->status = 'old_status'; $contact_transitional_status_condition->validate_and_execute( $contact_data ); $this->assertTrue( $contact_transitional_status_condition->condition_met() ); // Testing when the condition has been not been met for the to field. $contact->status = 'wrong_to'; $contact_transitional_status_condition->validate_and_execute( $contact_data ); $this->assertFalse( $contact_transitional_status_condition->condition_met() ); // Testing when the condition has been not been met for the from field $contact->status = 'new_status'; $previous_contact->status = 'wrong_from'; $contact_transitional_status_condition->validate_and_execute( $contact_data ); $this->assertFalse( $contact_transitional_status_condition->condition_met() ); } /** * @testdox Test contact tag added condition. */ public function test_contact_tag_added() { $contact_tag_condition = $this->get_contact_tag_condition( 'tag_added', 'Tag Added' ); /** @var Contact $contact */ $contact = $this->automation_faker->contact(); // Create a previous state of a contact. $previous_contact = clone $contact; $contact_data = new Contact_Data( $contact, $previous_contact ); // Generate the next tag id. $tag_id = end( $contact->tags )['id'] + 1; // Testing when the condition has been not been met because the contact does not have said tag. $contact_tag_condition->validate_and_execute( $contact_data ); $this->assertFalse( $contact_tag_condition->condition_met() ); // Testing when the condition has been met. $contact->tags[] = array( 'id' => $tag_id, 'objtype' => ZBS_TYPE_CONTACT, 'name' => 'Tag Added', 'slug' => 'tag-added', 'created' => 1692663412, 'lastupdated' => 1692663412, ); $contact_tag_condition->validate_and_execute( $contact_data ); $this->assertTrue( $contact_tag_condition->condition_met() ); // Testing when the condition has been not been met because the previous contact already had said tag. $previous_contact->tags[] = array( 'id' => $tag_id, 'objtype' => ZBS_TYPE_CONTACT, 'name' => 'Tag Added', 'slug' => 'tag-added', 'created' => 1692663412, 'lastupdated' => 1692663412, ); $contact_tag_condition->validate_and_execute( $contact_data ); $this->assertFalse( $contact_tag_condition->condition_met() ); } /** * @testdox Test contact tag removed condition. */ public function test_contact_tag_removed() { $contact_tag_condition = $this->get_contact_tag_condition( 'tag_removed', 'Tag to be removed' ); /** @var Contact $contact */ $contact = $this->automation_faker->contact(); $previous_contact = clone $contact; $contact_data = new Contact_Data( $contact, $previous_contact ); $tag_id = end( $contact->tags )['id'] + 1; // Testing when the condition has been not been met because the previous contact does not have said tag. $contact_tag_condition->validate_and_execute( $contact_data ); $this->assertFalse( $contact_tag_condition->condition_met() ); // Testing when the condition has been met. $previous_contact->tags[] = array( 'id' => $tag_id, 'objtype' => ZBS_TYPE_CONTACT, 'name' => 'Tag to be removed', 'slug' => 'tag-to-be-removed', 'created' => 1692663412, 'lastupdated' => 1692663412, ); $contact_tag_condition->validate_and_execute( $contact_data ); $this->assertTrue( $contact_tag_condition->condition_met() ); // Testing when the condition has been not been met because the current contact still has said tag. $contact->tags[] = array( 'id' => $tag_id, 'objtype' => ZBS_TYPE_CONTACT, 'name' => 'Tag to be removed', 'slug' => 'tag-to-be-removed', 'created' => 1692663412, 'lastupdated' => 1692663412, ); $contact_tag_condition->validate_and_execute( $contact_data ); $this->assertFalse( $contact_tag_condition->condition_met() ); } /** * @testdox Test contact has tag condition. */ public function test_contact_has_tag() { $contact_tag_condition = $this->get_contact_tag_condition( 'has_tag', 'Some Tag' ); /** @var Contact $contact */ $contact = $this->automation_faker->contact(); $previous_contact = clone $contact; $contact_data = new Contact_Data( $contact, $previous_contact ); // Generate the next tag id. $tag_id = end( $contact->tags )['id'] + 1; // Testing when the condition has been not been met because the contact does not have said tag. $contact_tag_condition->validate_and_execute( $contact_data ); $this->assertFalse( $contact_tag_condition->condition_met() ); // Testing when the condition has been met. $contact->tags[] = array( 'id' => $tag_id, 'objtype' => ZBS_TYPE_CONTACT, 'name' => 'Some Tag', 'slug' => 'some-tag', 'created' => 1692663412, 'lastupdated' => 1692663412, ); $contact_tag_condition->validate_and_execute( $contact_data ); $this->assertTrue( $contact_tag_condition->condition_met() ); } }
projects/plugins/crm/tests/php/automation/contacts/actions/class-add-remove-contact-tag-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Automation\Tests; use Automattic\Jetpack\CRM\Automation\Actions\Add_Remove_Contact_Tag; use Automattic\Jetpack\CRM\Automation\Automation_Engine; use Automattic\Jetpack\CRM\Automation\Automation_Workflow; use Automattic\Jetpack\CRM\Automation\Conditions\Contact_Field_Changed; use Automattic\Jetpack\CRM\Automation\Data_Types\Contact_Data; use Automattic\Jetpack\CRM\Automation\Triggers\Contact_Created; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Integration_Test_Case; /** * Test Automation Workflow functionalities * * @covers Automattic\Jetpack\CRM\Automation\Actions\Add_Remove_Contact_Tag */ class Add_Remove_Contact_Tag_Test extends JPCRM_Base_Integration_Test_Case { /** * A helper class to generate data for the automation tests. * * @since 6.2.0 * * @var Automation_Faker */ private $automation_faker; /** * {@inheritdoc} */ public function setUp(): void { parent::setUp(); $this->automation_faker = Automation_Faker::instance(); $this->automation_faker->reset_all(); } /** * @testdox Test that the 'adding or removing a tag from / to a contact' action executes the action. */ public function test_add_remove_contact_tag_action() { global $zbs; // Create a contact and tag. $contact_id = $this->add_contact(); $contact = $this->get_contact( $contact_id ); $tag_id = $zbs->DAL->addUpdateTag( array( 'data' => array( 'objtype' => ZBS_TYPE_CONTACT, 'name' => 'Test tag', ), ) ); // Setup action that is supposed to add our new tag to the contact. $action_add_remove_contact_tag = new Add_Remove_Contact_Tag( array( 'slug' => Add_Remove_Contact_Tag::get_slug(), 'attributes' => array( 'mode' => 'replace', 'tag_input' => array( $tag_id, ), ), ) ); $contact_data = new Contact_Data( $contact ); // Execute the action. $action_add_remove_contact_tag->validate_and_execute( $contact_data ); // Verify that our contact has the tag. $contact = $zbs->DAL->contacts->getContact( $contact_id, array( 'withTags' => true ) ); $this->assertSame( 'Test tag', $contact['tags'][0]['name'] ); } /** * @testdox Test that adding or removing a tag action executes the action, within a workflow. */ public function test_add_remove_contact_tag_action_with_workflow() { global $zbs; // Register dependencies. $automation = new Automation_Engine(); $automation->register_trigger( Contact_Created::class ); $automation->register_step( Contact_Field_Changed::class ); $automation->register_step( Add_Remove_Contact_Tag::class ); // Create a tag for our workflow. $tag_id = $zbs->DAL->addUpdateTag( array( 'data' => array( 'objtype' => ZBS_TYPE_COMPANY, 'name' => 'Test tag', ), ) ); // Create a workflow that adds the tag to newly created contacts. $workflow_data = $this->automation_faker->workflow_with_condition_customizable_trigger_action( Contact_Created::get_slug(), array( 'slug' => Add_Remove_Contact_Tag::get_slug(), 'attributes' => array( 'mode' => 'replace', 'tag_input' => array( $tag_id, ), ), 'next_step_true' => null, ) ); $workflow = new Automation_Workflow( $workflow_data ); $workflow->set_engine( $automation ); $automation->add_workflow( $workflow ); $automation->init_workflows(); // Create a new contact to trigger the workflow. $contact_id = $this->add_contact(); // Verify that our contact has the tag. $contact = $zbs->DAL->contacts->getContact( $contact_id, array( 'withTags' => true ) ); $this->assertSame( 'Test tag', $contact['tags'][0]['name'] ); } }
projects/plugins/crm/tests/php/automation/contacts/actions/class-delete-contact-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Automation\Tests; use Automattic\Jetpack\CRM\Automation\Actions\Delete_Contact; use Automattic\Jetpack\CRM\Automation\Automation_Engine; use Automattic\Jetpack\CRM\Automation\Automation_Workflow; use Automattic\Jetpack\CRM\Automation\Conditions\Contact_Field_Changed; use Automattic\Jetpack\CRM\Automation\Data_Types\Contact_Data; use Automattic\Jetpack\CRM\Automation\Triggers\Contact_Updated; use Automattic\Jetpack\CRM\Entities\Contact; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Integration_Test_Case; /** * Test Automation Workflow functionalities * * @covers Automattic\Jetpack\CRM\Automation\Actions\Delete_Contact */ class Delete_Contact_Test extends JPCRM_Base_Integration_Test_Case { /** * A helper class to generate data for the automation tests. * * @since 6.2.0 * * @var Automation_Faker */ private $automation_faker; /** * {@inheritdoc} */ public function setUp(): void { parent::setUp(); $this->automation_faker = Automation_Faker::instance(); $this->automation_faker->reset_all(); } /** * @testdox Test the delete contact action executes the action. */ public function test_delete_contact_action() { global $zbs; // Create a contact and verify it was created. $contact_id = $this->add_contact(); /** @var Contact $contact */ $contact = $this->get_contact( $contact_id ); // Setup action that is supposed to delete the contact. $action_delete_contact = new Delete_Contact( array( 'slug' => Delete_Contact::get_slug(), 'attributes' => array( 'keep_orphans' => true, ), ) ); // Execute the action. $action_delete_contact->validate_and_execute( new Contact_Data( $contact ) ); // Verify that the contact no longer exists. $contact = $zbs->DAL->contacts->getContact( $contact_id ); $this->assertFalse( $contact ); } /** * @testdox Test the delete contact action executes the action, within a workflow */ public function test_delete_contact_action_with_workflow() { global $zbs; // Register dependencies. $automation = new Automation_Engine(); $automation->register_trigger( Contact_Updated::class ); $automation->register_step( Contact_Field_Changed::class ); $automation->register_step( Delete_Contact::class ); // Create a contact to verify it existed before we delete it. $contact_id = $this->add_contact( array( 'status' => 'Anything but lead' ) ); $contact = $zbs->DAL->contacts->getContact( $contact_id ); $this->assertIsArray( $contact ); $workflow_data = $this->automation_faker->workflow_with_condition_customizable_trigger_action( Contact_Updated::get_slug(), array( 'slug' => Delete_Contact::get_slug(), 'attributes' => array( 'keep_orphans' => true, ), ) ); $workflow = new Automation_Workflow( $workflow_data ); $workflow->set_engine( $automation ); $automation->add_workflow( $workflow ); $automation->init_workflows(); // Change the status to "Lead" so the Contact Status Updated conditions defined in // Automation_Faker::workflow_with_condition_customizable_trigger_action() will be met. $zbs->DAL->contacts->addUpdateContact( array( 'id' => $contact_id, 'data' => array( 'status' => 'Lead', ), ) ); // Verify that the contact no longer exists. $contact = $zbs->DAL->contacts->getContact( $contact_id ); $this->assertFalse( $contact ); } }
projects/plugins/crm/tests/php/automation/contacts/actions/class-update-contact-status-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Automation\Tests; use Automattic\Jetpack\CRM\Automation\Actions\Update_Contact_Status; use Automattic\Jetpack\CRM\Automation\Automation_Engine; use Automattic\Jetpack\CRM\Automation\Automation_Workflow; use Automattic\Jetpack\CRM\Automation\Conditions\Contact_Field_Changed; use Automattic\Jetpack\CRM\Automation\Data_Types\Contact_Data; use Automattic\Jetpack\CRM\Automation\Triggers\Contact_Created; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Integration_Test_Case; /** * Test Automation Workflow functionalities * * @covers Automattic\Jetpack\CRM\Automation\Actions\Update_Contact_Status */ class Update_Contact_Status_Test extends JPCRM_Base_Integration_Test_Case { /** * A helper class to generate data for the automation tests. * * @since 6.2.0 * * @var Automation_Faker */ private $automation_faker; /** * {@inheritdoc} */ public function setUp(): void { parent::setUp(); $this->automation_faker = Automation_Faker::instance(); $this->automation_faker->reset_all(); } /** * @testdox Test the update contact status action executes the action. */ public function test_update_contact_status_action() { global $zbs; $contact_id = $this->add_contact( array( 'status' => 'Lead' ) ); $contact = $this->get_contact( $contact_id ); $this->assertSame( 'Lead', $contact->status ); $action_update_contact = new Update_Contact_Status( array( 'slug' => 'jpcrm/update_contact_status', 'attributes' => array( 'new_status' => 'Customer', ), ) ); $action_update_contact->validate_and_execute( new Contact_Data( $contact ) ); $contact = $zbs->DAL->contacts->getContact( $contact_id ); $this->assertSame( 'Customer', $contact['status'] ); } /** * @testdox Test the update contact status action executes the action, within a workflow. */ public function test_update_contact_status_action_with_workflow() { global $zbs; $automation = new Automation_Engine(); $automation->register_trigger( Contact_Created::class ); $automation->register_step( Contact_Field_Changed::class ); $automation->register_step( Update_Contact_Status::class ); $workflow_data = $this->automation_faker->workflow_with_condition_customizable_trigger_action( Contact_Created::get_slug(), array( 'slug' => Update_Contact_Status::get_slug(), 'attributes' => array( 'new_status' => 'Customer', ), ) ); $workflow = new Automation_Workflow( $workflow_data ); $workflow->set_engine( $automation ); $automation->add_workflow( $workflow ); $automation->init_workflows(); $contact_id = $this->add_contact( array( 'status' => 'Lead' ) ); $contact = $zbs->DAL->contacts->getContact( $contact_id ); $this->assertSame( 'Customer', $contact['status'] ); } }
projects/plugins/crm/tests/php/automation/contacts/actions/class-add-contact-log-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Automation\Tests; use Automattic\Jetpack\CRM\Automation\Actions\Add_Contact_Log; use Automattic\Jetpack\CRM\Automation\Automation_Engine; use Automattic\Jetpack\CRM\Automation\Automation_Workflow; use Automattic\Jetpack\CRM\Automation\Conditions\Contact_Field_Changed; use Automattic\Jetpack\CRM\Automation\Data_Types\Contact_Data; use Automattic\Jetpack\CRM\Automation\Triggers\Contact_Created; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Integration_Test_Case; /** * Test Automation Workflow functionalities * * @covers Automattic\Jetpack\CRM\Automation\Actions\Add_Contact_Log */ class Add_Contact_Log_Test extends JPCRM_Base_Integration_Test_Case { /** * A helper class to generate data for the automation tests. * * @since 6.2.0 * * @var Automation_Faker */ private $automation_faker; /** * {@inheritdoc} */ public function setUp(): void { parent::setUp(); $this->automation_faker = Automation_Faker::instance(); $this->automation_faker->reset_all(); } /** * @testdox Test that the 'adding a log to a contact' action executes the action. */ public function test_add_contact_log_action() { global $zbs; // Create a contact. $contact_id = $this->add_contact(); $contact = $this->get_contact( $contact_id ); // Prepare $action = new Add_Contact_Log( array( 'slug' => Add_Contact_Log::get_slug(), 'attributes' => array( 'type' => 'test-type', 'short-description' => 'Short description', 'long-description' => 'Long description', ), ) ); $contact_data = new Contact_Data( $contact ); // Execute the action. $action->validate_and_execute( $contact_data ); // Verify that our contact has a log. $logs = $zbs->DAL->logs->getLogsForObj( array( 'objtype' => ZBS_TYPE_CONTACT, 'objid' => $contact_id, 'notetype' => 'test-type', ) ); $this->assertCount( 1, $logs ); $test_log = current( $logs ); $this->assertSame( 'Short description', $test_log['shortdesc'] ); $this->assertSame( 'Long description', $test_log['longdesc'] ); } /** * @testdox Test that the 'adding a log to a contact' action executes the action, within a workflow. */ public function test_add_contact_log_action_with_workflow() { global $zbs; // Register dependencies. $automation = new Automation_Engine(); $automation->register_trigger( Contact_Created::class ); $automation->register_step( Contact_Field_Changed::class ); $automation->register_step( Add_Contact_Log::class ); // Setup action that is supposed to update newly created contacts. $workflow_data = $this->automation_faker->workflow_with_condition_customizable_trigger_action( Contact_Created::get_slug(), array( 'slug' => Add_Contact_Log::get_slug(), 'attributes' => array( 'type' => 'test-type', 'short-description' => 'Short description', 'long-description' => 'Long description', ), ) ); $workflow = new Automation_Workflow( $workflow_data ); $workflow->set_engine( $automation ); $automation->add_workflow( $workflow ); $automation->init_workflows(); // Create a new contact to trigger our workflow. $contact_id = $this->add_contact(); // Verify that our contact has a log. $logs = $zbs->DAL->logs->getLogsForObj( array( 'objtype' => ZBS_TYPE_CONTACT, 'objid' => $contact_id, 'notetype' => 'test-type', ) ); $this->assertCount( 1, $logs ); $test_log = current( $logs ); $this->assertSame( 'Short description', $test_log['shortdesc'] ); $this->assertSame( 'Long description', $test_log['longdesc'] ); } }
projects/plugins/crm/tests/php/automation/contacts/actions/class-update-contact-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Automation\Tests; use Automattic\Jetpack\CRM\Automation\Actions\Update_Contact; use Automattic\Jetpack\CRM\Automation\Automation_Engine; use Automattic\Jetpack\CRM\Automation\Automation_Workflow; use Automattic\Jetpack\CRM\Automation\Conditions\Contact_Field_Changed; use Automattic\Jetpack\CRM\Automation\Data_Types\Contact_Data; use Automattic\Jetpack\CRM\Automation\Triggers\Contact_Created; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Integration_Test_Case; /** * Test Automation Workflow functionalities * * @covers Automattic\Jetpack\CRM\Automation\Actions\Update_Contact */ class Update_Contact_Test extends JPCRM_Base_Integration_Test_Case { /** * A helper class to generate data for the automation tests. * * @since 6.2.0 * * @var Automation_Faker */ private $automation_faker; /** * {@inheritdoc} */ public function setUp(): void { parent::setUp(); $this->automation_faker = Automation_Faker::instance(); $this->automation_faker->reset_all(); } /** * @testdox Test the update contact action executes the action. */ public function test_update_contact_action() { global $zbs; // Create a contact that we can later update to verify the action works. $contact_id = $this->add_contact( array( 'fname' => 'This is definitely not a real first name', ) ); $contact = $this->get_contact( $contact_id ); $this->assertSame( 'This is definitely not a real first name', $contact->fname ); // Define what happens when the action is executed. $action = new Update_Contact( array( 'slug' => Update_Contact::get_slug(), 'attributes' => array( 'fname' => 'Samantha', ), ) ); // Execute action. $action->validate_and_execute( new Contact_Data( $contact ) ); // Fetch the contact again and verify the update was successful. $contact = $zbs->DAL->contacts->getContact( $contact_id ); $this->assertSame( 'Samantha', $contact['fname'] ); } /** * @testdox Test the update contact action executes the action, within a workflow. */ public function test_update_contact_action_with_workflow() { global $zbs; // Register dependencies. $automation = new Automation_Engine(); $automation->register_trigger( Contact_Created::class ); $automation->register_step( Contact_Field_Changed::class ); $automation->register_step( Update_Contact::class ); // Setup action that is supposed to update newly created contacts. $workflow_data = $this->automation_faker->workflow_with_condition_customizable_trigger_action( Contact_Created::get_slug(), array( 'slug' => Update_Contact::get_slug(), 'attributes' => array( 'fname' => 'Samantha', 'prefix' => 'Ms', ), ) ); $workflow = new Automation_Workflow( $workflow_data ); $workflow->set_engine( $automation ); $automation->add_workflow( $workflow ); $automation->init_workflows(); // Create a new contact with a first name and prefix that we expect to be modified. $contact_id = $this->add_contact( array( 'fname' => 'This is definitely not a real first name', 'prefix' => 'Mr', // Adding a last name to ensure its still the same after the update. 'lname' => 'Manhatten', ) ); // Verify that the contact was updated. $contact = $zbs->DAL->contacts->getContact( $contact_id ); $this->assertIsArray( $contact ); $this->assertSame( 'Samantha', $contact['fname'] ); $this->assertSame( 'Manhatten', $contact['lname'] ); $this->assertSame( 'Ms', $contact['prefix'] ); } }
projects/plugins/crm/tests/php/automation/tags/class-tag-condition-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Automation\Tests; use Automattic\Jetpack\CRM\Automation\Conditions\Entity_Tag; use Automattic\Jetpack\CRM\Automation\Data_Types\Tag_List_Data; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Test_Case; require_once __DIR__ . '../../tools/class-automation-faker.php'; /** * Test Automation Workflow functionalities * * @covers Automattic\Jetpack\CRM\Automation\Conditions\Entity_Tag */ class Tag_Condition_Test extends JPCRM_Base_Test_Case { private $automation_faker; public function setUp(): void { parent::setUp(); $this->automation_faker = Automation_Faker::instance(); $this->automation_faker->reset_all(); } private function get_tag_condition( $operator, $tag ) { $condition_data = array( 'slug' => 'jpcrm/condition/object_tag', 'attributes' => array( 'tag' => $tag, 'operator' => $operator, ), ); return new Entity_Tag( $condition_data ); } /** * @testdox Test tag added condition. */ public function test_tag_added() { $tag_condition = $this->get_tag_condition( 'tag_added', 'Tag Added' ); $tag_data = $this->automation_faker->tag_list(); // Create a previous state of a tag list. $previous_tag_data = $tag_data; // Testing when the condition has been not been met because the tag list does not have said tag. $tag_condition->execute( new Tag_List_Data( $tag_data, $previous_tag_data ) ); $this->assertFalse( $tag_condition->condition_met() ); // Testing when the condition has been met. $new_tag_data = array( 'id' => 3, 'objtype' => ZBS_TYPE_CONTACT, 'name' => 'Tag Added', 'slug' => 'tag-added', 'created' => 1692663412, 'lastupdated' => 1692663412, ); $tag_data = $this->automation_faker->tag_list( $new_tag_data ); $tag_condition->execute( new Tag_List_Data( $tag_data, $previous_tag_data ) ); $this->assertTrue( $tag_condition->condition_met() ); // Testing when the condition has been not been met because the previous tag list already had said tag. $previous_tag_data = $tag_data; $tag_condition->execute( new Tag_List_Data( $tag_data, $tag_data ) ); $this->assertFalse( $tag_condition->condition_met() ); } /** * @testdox Test tag removed condition. */ public function test_tag_removed() { $tag_condition = $this->get_tag_condition( 'tag_removed', 'Tag to be removed' ); $tag_data = $this->automation_faker->tag_list(); // Create a previous state of a tag list. $previous_tag_data = $tag_data; // Testing when the condition has been not been met because the previous tag list does not have said tag. $tag_condition->execute( new Tag_List_Data( $tag_data, $previous_tag_data ) ); $this->assertFalse( $tag_condition->condition_met() ); // Testing when the condition has been met. $new_tag_data = array( 'id' => 1, 'objtype' => ZBS_TYPE_CONTACT, 'name' => 'Tag to be removed', 'slug' => 'tag-to-be-removed', 'created' => 1692663412, 'lastupdated' => 1692663412, ); $previous_tag_data = $this->automation_faker->tag_list( $new_tag_data ); $tag_condition->execute( new Tag_List_Data( $tag_data, $previous_tag_data ) ); $this->assertTrue( $tag_condition->condition_met() ); // Testing when the condition has been not been met because the previous tag list already had said tag. $tag_condition->execute( new Tag_List_Data( $previous_tag_data, $previous_tag_data ) ); $this->assertFalse( $tag_condition->condition_met() ); } /** * @testdox Test tag list has tag condition. */ public function test_tag_list_has_tag() { $tag_condition = $this->get_tag_condition( 'has_tag', 'Some Tag' ); $tag_data = $this->automation_faker->tag_list(); // Testing when the condition has been not been met because the tag list does not have said tag. $tag_condition->execute( new Tag_List_Data( $tag_data ) ); $this->assertFalse( $tag_condition->condition_met() ); // Testing when the condition has been met: The tag exists. $new_tag_data = array( 'id' => 1, 'objtype' => ZBS_TYPE_CONTACT, 'name' => 'Some Tag', 'slug' => 'some-tag', 'created' => 1692663412, 'lastupdated' => 1692663412, ); $tag_data = $this->automation_faker->tag_list( $new_tag_data ); $tag_condition->execute( new Tag_List_Data( $tag_data ) ); $this->assertTrue( $tag_condition->condition_met() ); } /** * @testdox Test tag list does not have ('not has') tag condition. */ public function test_tag_list_not_has_tag() { $tag_condition = $this->get_tag_condition( 'not_has_tag', 'Some Tag' ); $tag_data = $this->automation_faker->tag_list(); // Testing when the condition has been met because the tag list does not have said tag. $tag_condition->execute( new Tag_List_Data( $tag_data ) ); $this->assertTrue( $tag_condition->condition_met() ); // Testing when the condition has not been met: The tag does exist. $new_tag_data = array( 'id' => 1, 'objtype' => ZBS_TYPE_CONTACT, 'name' => 'Some Tag', 'slug' => 'some-tag', 'created' => 1692663412, 'lastupdated' => 1692663412, ); $tag_data = $this->automation_faker->tag_list( $new_tag_data ); $tag_condition->execute( new Tag_List_Data( $tag_data ) ); $this->assertFalse( $tag_condition->condition_met() ); } }
projects/plugins/crm/tests/php/automation/transactions/class-transaction-condition-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Automation\Tests; use Automattic\Jetpack\CRM\Automation\Automation_Exception; use Automattic\Jetpack\CRM\Automation\Conditions\Transaction_Field; use Automattic\Jetpack\CRM\Automation\Data_Types\Transaction_Data; use Automattic\Jetpack\CRM\Entities\Transaction; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Test_Case; require_once __DIR__ . '../../tools/class-automation-faker.php'; /** * Test Automation Transaction Condition functionalities * * @covers Automattic\Jetpack\CRM\Automation */ class Transaction_Condition_Test extends JPCRM_Base_Test_Case { private $automation_faker; public function setUp(): void { parent::setUp(); $this->automation_faker = Automation_Faker::instance(); $this->automation_faker->reset_all(); } private function get_transaction_field_condition( $operator, $expected_value ) { $condition_data = array( 'slug' => 'jpcrm/condition/transaction_field', 'attributes' => array( 'field' => 'status', 'operator' => $operator, 'value' => $expected_value, ), ); return new Transaction_Field( $condition_data ); } /** * @testdox Test the update transaction field condition for the is operator. */ public function test_field_changed_is_operator() { $transaction_field_changed_condition = $this->get_transaction_field_condition( 'is', 'paid' ); /** @var Transaction $transaction */ $transaction = $this->automation_faker->transaction(); $transaction_data = new Transaction_Data( $transaction ); // Testing when the condition has been met. $transaction->status = 'paid'; $transaction_field_changed_condition->validate_and_execute( $transaction_data ); $this->assertTrue( $transaction_field_changed_condition->condition_met() ); // Testing when the condition has not been met. $transaction->status = 'draft'; $transaction_field_changed_condition->validate_and_execute( $transaction_data ); $this->assertFalse( $transaction_field_changed_condition->condition_met() ); } /** * @testdox Test the update transaction field condition for the is_not operator. */ public function test_field_changed_is_not_operator() { $transaction_field_changed_condition = $this->get_transaction_field_condition( 'is_not', 'paid' ); /** @var Transaction $transaction */ $transaction = $this->automation_faker->transaction(); $transaction_data = new Transaction_Data( $transaction ); // Testing when the condition has been met. $transaction->status = 'draft'; $transaction_field_changed_condition->validate_and_execute( $transaction_data ); $this->assertTrue( $transaction_field_changed_condition->condition_met() ); // Testing when the condition has not been met. $transaction->status = 'paid'; $transaction_field_changed_condition->validate_and_execute( $transaction_data ); $this->assertFalse( $transaction_field_changed_condition->condition_met() ); } /** * @testdox Test the update transaction field condition for the contains operator. */ public function test_field_changed_contains_operator() { $transaction_field_changed_condition = $this->get_transaction_field_condition( 'contains', 'ai' ); /** @var Transaction $transaction */ $transaction = $this->automation_faker->transaction(); $transaction_data = new Transaction_Data( $transaction ); // Testing when the condition has been met. $transaction->status = 'paid'; $transaction_field_changed_condition->validate_and_execute( $transaction_data ); $this->assertTrue( $transaction_field_changed_condition->condition_met() ); // Testing when the condition has not been met. $transaction->status = 'draft'; $transaction_field_changed_condition->validate_and_execute( $transaction_data ); $this->assertFalse( $transaction_field_changed_condition->condition_met() ); } /** * @testdox Test the update transaction field condition for the does_not_contain operator. */ public function test_field_changed_does_not_contain_operator() { $transaction_field_changed_condition = $this->get_transaction_field_condition( 'does_not_contain', 'ai' ); /** @var Transaction $transaction */ $transaction = $this->automation_faker->transaction(); $transaction_data = new Transaction_Data( $transaction ); // Testing when the condition has been met. $transaction->status = 'draft'; $transaction_field_changed_condition->validate_and_execute( $transaction_data ); $this->assertTrue( $transaction_field_changed_condition->condition_met() ); // Testing when the condition has not been met. $transaction->status = 'paid'; $transaction_field_changed_condition->validate_and_execute( $transaction_data ); $this->assertFalse( $transaction_field_changed_condition->condition_met() ); } /** * @testdox Test if an exception is being correctly thrown for wrong operators. */ public function test_field_changed_invalid_operator_throws_exception() { $transaction_field_changed_condition = $this->get_transaction_field_condition( 'wrong_operator', 'paid' ); /** @var Transaction $transaction */ $transaction = $this->automation_faker->transaction(); $transaction_data = new Transaction_Data( $transaction ); $this->expectException( Automation_Exception::class ); $this->expectExceptionCode( Automation_Exception::CONDITION_INVALID_OPERATOR ); $transaction_field_changed_condition->validate_and_execute( $transaction_data ); } }
projects/plugins/crm/tests/php/automation/transactions/class-transaction-trigger-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Automation\Tests; use Automattic\Jetpack\CRM\Automation\Automation_Engine; use Automattic\Jetpack\CRM\Automation\Automation_Workflow; use Automattic\Jetpack\CRM\Automation\Data_Types\Transaction_Data; use Automattic\Jetpack\CRM\Automation\Triggers\Transaction_Created; use Automattic\Jetpack\CRM\Automation\Triggers\Transaction_Updated; use Automattic\Jetpack\CRM\Entities\Transaction; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Test_Case; require_once __DIR__ . '../../tools/class-automation-faker.php'; /** * Test Automation's transaction triggers * * @covers Automattic\Jetpack\CRM\Automation\Triggers\Transaction_Updated * @covers Automattic\Jetpack\CRM\Automation\Triggers\Transaction_Created */ class Transaction_Trigger_Test extends JPCRM_Base_Test_Case { private $automation_faker; public function setUp(): void { parent::setUp(); $this->automation_faker = Automation_Faker::instance(); } /** * @testdox Test the transaction created trigger executes the workflow with an action */ public function test_transaction_created_trigger() { $workflow_data = $this->automation_faker->workflow_without_initial_step_customize_trigger( 'jpcrm/transaction_created' ); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data, new Automation_Engine() ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); // Init the Transaction_Created trigger. $trigger = new Transaction_Created(); $trigger->init( $workflow ); /** @var Transaction $transaction */ $transaction = $this->automation_faker->transaction(); $transaction_data = new Transaction_Data( $transaction ); // We expect the workflow to be executed on transaction_created transaction with the transaction data. $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $trigger, $transaction_data ); // Run the transaction_created action. do_action( 'jpcrm_transaction_created', $transaction ); } /** * @testdox Test the transaction updated trigger executes the workflow with an action */ public function test_transaction_updated_trigger() { $workflow_data = $this->automation_faker->workflow_without_initial_step_customize_trigger( 'jpcrm/transaction_updated' ); $trigger = new Transaction_Updated(); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data, new Automation_Engine() ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); // Init the Transaction_Updated trigger. $trigger->init( $workflow ); /** @var Transaction $transaction */ $transaction = $this->automation_faker->transaction(); $transaction_data = new Transaction_Data( $transaction ); // We expect the workflow to be executed on transaction_updated transaction with the transaction data. $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $trigger, $transaction_data ); // Run the transaction_updated action. do_action( 'jpcrm_transaction_updated', $transaction ); } }
projects/plugins/crm/tests/php/automation/transactions/actions/class-set-transaction-status-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Automation\Tests; use Automattic\Jetpack\CRM\Automation\Actions\Set_Transaction_Status; use Automattic\Jetpack\CRM\Automation\Automation_Engine; use Automattic\Jetpack\CRM\Automation\Automation_Workflow; use Automattic\Jetpack\CRM\Automation\Triggers\Transaction_Created; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Integration_Test_Case; /** * Test Automation Workflow functionalities * * @covers Automattic\Jetpack\CRM\Automation\Actions\Set_Transaction_Status_Test */ class Set_Transaction_Status_Test extends JPCRM_Base_Integration_Test_Case { /** * A helper class to generate data for the automation tests. * * @since 6.2.0 * * @var Automation_Faker */ private $automation_faker; /** * {@inheritdoc} */ public function setUp(): void { parent::setUp(); $this->automation_faker = Automation_Faker::instance(); $this->automation_faker->reset_all(); } /** * @testdox Test the set transaction status action executes the action, within a workflow. */ public function test_set_transaction_status_action_with_workflow() { global $zbs; $automation = new Automation_Engine(); $automation->register_trigger( Transaction_Created::class ); $automation->register_step( Set_Transaction_Status::class ); $workflow_data = array( 'name' => 'Set Transaction Action Workflow Test', 'description' => 'This is a test', 'category' => 'Test', 'active' => true, 'triggers' => array( Transaction_Created::get_slug(), ), 'initial_step' => 0, 'steps' => array( 0 => array( 'slug' => Set_Transaction_Status::get_slug(), 'attributes' => array( 'new_status' => 'Paid', ), 'next_step_true' => null, ), ), ); $workflow = new Automation_Workflow( $workflow_data ); $workflow->set_engine( $automation ); $automation->add_workflow( $workflow ); $automation->init_workflows(); $transaction_id = $this->add_transaction( array( 'status' => 'Draft' ) ); $transaction = $zbs->DAL->transactions->getTransaction( $transaction_id ); $this->assertSame( 'Paid', $transaction['status'] ); } }
projects/plugins/crm/tests/php/automation/companies/class-company-trigger-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Automation\Tests; use Automattic\Jetpack\CRM\Automation\Automation_Workflow; use Automattic\Jetpack\CRM\Automation\Data_Types\Company_Data; use Automattic\Jetpack\CRM\Automation\Triggers\Company_Created; use Automattic\Jetpack\CRM\Automation\Triggers\Company_Deleted; use Automattic\Jetpack\CRM\Automation\Triggers\Company_Status_Updated; use Automattic\Jetpack\CRM\Automation\Triggers\Company_Updated; use Automattic\Jetpack\CRM\Entities\Company; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Test_Case; require_once __DIR__ . '../../tools/class-automation-faker.php'; /** * Test Automation Workflow functionalities * * @covers Automattic\Jetpack\CRM\Automation */ class Company_Trigger_Test extends JPCRM_Base_Test_Case { private $automation_faker; public function setUp(): void { parent::setUp(); $this->automation_faker = Automation_Faker::instance(); } /** * @testdox Test the company updated trigger executes the workflow with an action */ public function test_company_updated_trigger() { $workflow_data = $this->automation_faker->workflow_without_initial_step_customize_trigger( 'jpcrm/company_updated' ); $trigger = new Company_Updated(); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); // Init the Company_Updated trigger. $trigger->init( $workflow ); // Fake event data. $company = $this->automation_faker->company(); // We expect the workflow to be executed on company_update event with the company data $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $trigger, new Company_Data( $company ) ); // Run the company_update action. do_action( 'jpcrm_company_updated', $company ); } /** * @testdox Test the company status updated trigger executes the workflow with an action */ public function test_company_status_updated_trigger() { $workflow_data = $this->automation_faker->workflow_without_initial_step_customize_trigger( 'jpcrm/company_status_updated' ); $trigger = new Company_Status_Updated(); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); // Init the Company_Status_Updated trigger. $trigger->init( $workflow ); // Fake event data. /** @var Company $company */ $company = $this->automation_faker->company(); // We expect the workflow to be executed on company_status_update event with the company data $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $trigger, new Company_Data( $company ) ); // Run the company_status_update action. do_action( 'jpcrm_company_status_updated', $company ); } /** * @testdox Test the company new trigger executes the workflow with an action */ public function test_company_created_trigger() { $workflow_data = $this->automation_faker->workflow_without_initial_step_customize_trigger( 'jpcrm/company_created' ); $trigger = new Company_Created(); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); // Init the Company_Created trigger. $trigger->init( $workflow ); // Fake event data. /** @var Company $company */ $company = $this->automation_faker->company(); // We expect the workflow to be executed on company_created event with the company data $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $trigger, new Company_Data( $company ) ); // Run the company_created action. do_action( 'jpcrm_company_created', $company ); } /** * @testdox Test the company deleted trigger executes the workflow with an action */ public function test_company_deleted_trigger() { $workflow_data = $this->automation_faker->workflow_without_initial_step_customize_trigger( 'jpcrm/company_deleted' ); $trigger = new Company_Deleted(); // Build a PHPUnit mock Automation_Workflow $workflow = $this->getMockBuilder( Automation_Workflow::class ) ->setConstructorArgs( array( $workflow_data ) ) ->onlyMethods( array( 'execute' ) ) ->getMock(); // Init the Company_Deleted trigger. $trigger->init( $workflow ); // Fake event data. /** @var Company $company */ $company = $this->automation_faker->company(); // We expect the workflow to be executed on company_deleted event with the company data $workflow->expects( $this->once() ) ->method( 'execute' ) ->with( $trigger, new Company_Data( $company ) ); // Run the company_deleted action. do_action( 'jpcrm_company_deleted', $company ); } }
projects/plugins/crm/tests/php/event-manager/class-event-manager-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Event_Manager\Tests; use Automattic\Jetpack\CRM\Automation\Tests\Automation_Faker; use Automattic\Jetpack\CRM\Entities\Contact; use Automattic\Jetpack\CRM\Entities\Factories\Contact_Factory; use Automattic\Jetpack\CRM\Entities\Factories\Invoice_Factory; use Automattic\Jetpack\CRM\Entities\Factories\Transaction_Factory; use Automattic\Jetpack\CRM\Entities\Invoice; use Automattic\Jetpack\CRM\Entities\Transaction; use Automattic\Jetpack\CRM\Event_Manager\Contact_Event; use Automattic\Jetpack\CRM\Event_Manager\Invoice_Event; use Automattic\Jetpack\CRM\Event_Manager\Transaction_Event; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Test_Case; require_once __DIR__ . '/../automation/tools/class-automation-faker.php'; /** * Test Event Manager system. * * @covers Automattic\Jetpack\CRM\Event_Manager */ class Event_Manager_Test extends JPCRM_Base_Test_Case { /** * @testdox Test that contact created event is fired */ public function test_notify_on_contact_created() { /** @var Contact $contact */ $contact = Automation_Faker::instance()->contact(); add_action( 'jpcrm_contact_created', function ( $contact_event ) use ( $contact ) { $contact->tags = $contact_event->tags; $this->assertEquals( $contact_event, $contact ); }, 10, 1 ); $contact_event = new Contact_Event(); $contact_event->created( Contact_Factory::tidy_data( $contact ) ); } /** * @testdox Test that contact status updated event is fired */ public function test_notify_on_contact_status_updated() { /** @var Contact $contact */ $contact = Automation_Faker::instance()->contact(); $contact_updated = clone $contact; $contact_updated->status = 'Customer'; add_action( 'jpcrm_contact_status_updated', function ( $contact, $previous_contact ) { $this->assertEquals( 'lead', $contact->status ); $this->assertEquals( 'Customer', $previous_contact->status ); }, 10, 2 ); $contact_event = new Contact_Event(); $contact_event->updated( Contact_Factory::tidy_data( $contact ), Contact_Factory::tidy_data( $contact_updated ) ); } /** * @testdox Test that contact multi fields updated event is fired */ public function test_notify_on_contact_multi_fields_updated() { /** @var Contact $contact */ $contact = Automation_Faker::instance()->contact(); $contact_updated = clone $contact; $contact_updated->status = 'Customer'; $contact_updated->fname = 'John2'; $contact_updated->email = 'johndoe2@example.com'; $contact_data = Contact_Factory::tidy_data( $contact ); $contact_updated_data = Contact_Factory::tidy_data( $contact_updated ); $assertions_ran = 0; // Listen and test the name was updated. add_action( 'jpcrm_contact_fname_updated', function ( $contact, $contact_updated ) use ( &$assertions_ran ) { $this->assertEquals( 'John', $contact->fname ); $this->assertEquals( 'John2', $contact_updated->fname ); $assertions_ran += 2; }, 10, 2 ); // Listen and test the email was updated. add_action( 'jpcrm_contact_email_updated', function ( $contact, $contact_updated ) use ( &$assertions_ran ) { $this->assertEquals( 'johndoe@example.com', $contact->email ); $this->assertEquals( 'johndoe2@example.com', $contact_updated->email ); $assertions_ran += 2; }, 10, 2 ); $contact_event = new Contact_Event(); $contact_event->updated( $contact_data, $contact_updated_data ); $this->assertEquals( 4, $assertions_ran, 'All assertions did not run!' ); } /** * @testdox Test that contact updated event is fired */ public function test_notify_on_contact_updated() { /** @var Contact $contact */ $contact = Automation_Faker::instance()->contact(); $contact_updated = clone $contact; $contact_updated->status = 'Customer'; add_action( 'jpcrm_contact_updated', function ( $contact ) { $this->assertEquals( 'Customer', $contact->status ); } ); $contact_event = new Contact_Event(); $contact_event->updated( Contact_Factory::tidy_data( $contact_updated ), Contact_Factory::tidy_data( $contact ) ); } /** * @testdox Test that contact deleted event is fired */ public function test_notify_on_contact_deleted() { /** @var Contact $contact */ $contact = Automation_Faker::instance()->contact(); add_action( 'jpcrm_contact_deleted', function ( $contact_to_delete ) use ( $contact ) { $this->assertEquals( $contact->id, $contact_to_delete ); } ); $contact_event = new Contact_Event(); $contact_event->deleted( $contact->id ); } /** * @testdox Test contact is about to be deleted event is fired */ public function test_notify_on_contact_before_delete() { /** @var Contact $contact */ $contact = Automation_Faker::instance()->contact(); add_action( 'jpcrm_contact_before_delete', function ( $contact_to_delete ) use ( $contact ) { $this->assertEquals( $contact->id, $contact_to_delete ); } ); $contact_event = new Contact_Event(); $contact_event->before_delete( $contact->id ); } /** * @testdox Test that invoice created event is fired */ public function test_notify_on_invoice_created() { /** @var Invoice $invoice */ $invoice = Automation_Faker::instance()->invoice(); $invoice_data = Invoice_Factory::tidy_data( $invoice ); add_action( 'jpcrm_invoice_created', function ( $invoice_created ) use ( $invoice ) { $this->assertEquals( $invoice_created, $invoice ); }, 10, 1 ); $invoice_event = new Invoice_Event(); $invoice_event->created( $invoice_data ); } /** * @testdox Test that invoice updated event is fired */ public function test_notify_on_invoice_updated() { /** @var Invoice $invoice */ $invoice = Automation_Faker::instance()->invoice(); $previous_invoice = clone $invoice; $invoice->currency = 'EUR'; $previous_invoice->currency = 'USD'; $invoice_data = Invoice_Factory::tidy_data( $invoice ); $previous_invoice_data = Invoice_Factory::tidy_data( $previous_invoice ); add_action( 'jpcrm_invoice_updated', function ( $invoice_updated, $previous_invoice ) { $this->assertEquals( 'EUR', $invoice_updated->currency ); $this->assertEquals( 'USD', $previous_invoice->currency ); }, 10, 2 ); $invoice_event = new Invoice_Event(); $invoice_event->updated( $invoice_data, $previous_invoice_data ); } /** * @testdox Test that transaction created event is fired */ public function test_notify_on_transaction_created() { /** @var Transaction $transaction */ $transaction = Automation_Faker::instance()->transaction(); $transaction_data = Transaction_Factory::tidy_data( $transaction ); add_action( 'jpcrm_transaction_created', function ( $transaction_created ) use ( $transaction ) { // @todo Matching tags for now, but we should investigate the factory / what the DAL is returning. $transaction_created->tags = $transaction->tags; $this->assertEquals( $transaction_created, $transaction ); }, 10, 1 ); $transaction_event = new Transaction_Event(); $transaction_event->created( $transaction_data ); } /** * @testdox Test that transaction created event is fired */ public function test_notify_on_transaction_updated() { /** @var Transaction $transaction */ $transaction = Automation_Faker::instance()->transaction(); $previous_transaction = clone $transaction; $transaction_data = Transaction_Factory::tidy_data( $transaction ); $previous_transaction_data = Transaction_Factory::tidy_data( $previous_transaction ); add_action( 'jpcrm_transaction_updated', function ( $transaction_updated ) use ( $transaction ) { // @todo Matching tags for now, but we should investigate the factory / what the DAL is returning. $transaction_updated->tags = $transaction->tags; $this->assertEquals( $transaction_updated, $transaction ); }, 10, 1 ); $transaction_event = new Transaction_Event(); $transaction_event->updated( $transaction_data, $previous_transaction_data ); } /** * @testdox Test that transaction deleted event is fired */ public function test_notify_on_transaction_deleted() { $transaction_deleted_id = 12345; add_action( 'jpcrm_transaction_deleted', function ( $invoice_id ) use ( $transaction_deleted_id ) { $this->assertEquals( $invoice_id, $transaction_deleted_id ); }, 10, 1 ); $transaction_event = new Transaction_Event(); $transaction_event->deleted( $transaction_deleted_id ); } }
projects/plugins/crm/tests/php/event-manager/class-event-manager-faker.php
<?php namespace Automattic\Jetpack\CRM\Event_Manager\Tests; class Event_Manager_Faker { private static $instance; public static function instance(): Event_Manager_Faker { if ( ! self::$instance ) { self::$instance = new self(); } return self::$instance; } public function contact_data() { return array( 'id' => 1, 'status' => 'Lead', 'name' => 'John Doe', 'email' => 'johndoe@example.com', 'lastupdated' => 1690385165, ); } /** * Return data for a dummy invoice. * * @param bool $get_as_data_type If true, return the data as a Data_Type_Invoice object. * @return array|Data_Type_Invoice */ public function invoice_data() { $data = array( 'id' => 1, 'data' => array( 'id_override' => '1', 'parent' => '', 'status' => 'Unpaid', 'due_date' => 1690840800, 'hash' => 'ISSQndSUjlhJ8feWj2v', 'lineitems' => array( array( 'net' => 3.75, 'desc' => 'Dummy product', 'quantity' => '3', 'price' => '1.25', 'total' => 3.75, ), ), 'contacts' => array( 1 ), 'created' => -1, ), ); return $data; } /** * Return data for a dummy transaction. * * @return array */ public function transaction_data() { $data = array( 'id' => 1, 'data' => array( 'title' => 'Some transaction title', 'ref' => 'transaction_reference_1', 'desc' => 'Some desc', 'hash' => 'mASOpAnf334Pncl1px4', 'status' => 'Completed', 'type' => 'Sale', 'currency' => 'USD', 'total' => '150.00', 'tax' => '10.00', 'lineitems' => array(), 'date' => 1676000000, 'date_completed' => 1676923766, 'created' => 1675000000, 'lastupdated' => 1675000000, ), ); return $data; } }
projects/plugins/crm/tests/php/entities/class-company-entity-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Entities\Tests; use Automattic\Jetpack\CRM\Entities\Company; use Automattic\Jetpack\CRM\Entities\Factories\Company_Factory; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Integration_Test_Case; /** * Test Event Manager system. * * @covers Automattic\Jetpack\CRM\Entities */ class Company_Entity_Test extends JPCRM_Base_Integration_Test_Case { /** * @testdox Test that company entity is created from input data. */ public function test_company_entity_from_input_data() { $company_data = $this->generate_company_data(); // Create the Company instance from the company data (tidy DAL format) $company = Company_Factory::create( $company_data ); $this->assertInstanceOf( Company::class, $company ); // Check that the company data field values are the same to the Company instance field values. foreach ( $company_data as $key => $value ) { if ( ! property_exists( $company, $key ) ) { continue; } $this->assertEquals( $value, $company->$key, "Company property $key does not match" ); } } /** * @testdox Test create company entity from input data and insert in DB via DAL. */ public function test_create_company_from_input_data_and_insert_into_DB() { $company_data = $this->generate_company_data(); // Create the Company instance from the company data (tidy DAL format) $company = Company_Factory::create( $company_data ); $this->assertInstanceOf( Company::class, $company ); // This is not necessary for this test, but we ensure we modify the entity $company->name = 'Factory Test'; global $zbs; // Prepare the Company data from the instance to save it via DAL $company_data_to_save = Company_Factory::data_for_dal( $company ); $id = $zbs->DAL->companies->addUpdateCompany( $company_data_to_save ); // Check that the Company is created and returns the id. $this->assertTrue( $id > 0 ); // Retrieve the company and check that the data is the same. $company_data_from_db = $zbs->DAL->companies->getCompany( $id ); // Create the instance from the company data retrieve from the DAL/DB. $company_instance = Company_Factory::create( $company_data_from_db ); $this->assertInstanceOf( Company::class, $company_instance ); $this->assertNotNull( $company_instance->id ); // List of fields to check their values $fields_to_check = array( 'name', 'email', 'status', 'addr1', 'addr2', 'city', 'country', 'postcode', 'maintel', 'sectel', ); foreach ( $fields_to_check as $field ) { $this->assertEquals( $company->$field, $company_instance->$field, "Company property $field does not match" ); } } }
projects/plugins/crm/tests/php/entities/class-transaction-entity-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Entities\Tests; use Automattic\Jetpack\CRM\Entities\Factories\Transaction_Factory; use Automattic\Jetpack\CRM\Entities\Transaction; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Integration_Test_Case; /** * Test Event Manager system. * * @covers Automattic\Jetpack\CRM\Entities */ class Transaction_Entity_Test extends JPCRM_Base_Integration_Test_Case { /** * @testdox Test that transaction entity is created from input data. */ public function test_transaction_entity_from_input_data() { $transaction_data = $this->generate_transaction_data(); // Create the Transaction instance from the transaction data (tidy DAL format) $transaction = Transaction_Factory::create( $transaction_data ); $this->assertInstanceOf( Transaction::class, $transaction ); // Check that the transaction data field values are the same to the Transaction instance field values. foreach ( $transaction_data as $key => $value ) { if ( ! property_exists( $transaction, $key ) ) { continue; } $this->assertEquals( $value, $transaction->$key, "Transaction property $key does not match" ); } } /** * @testdox Test create transaction entity from input data and insert in DB via DAL. */ public function test_create_transaction_from_input_data_and_insert_into_DB() { $transaction_data = $this->generate_transaction_data(); // Create the Transaction instance from the transaction data (tidy DAL format) $transaction = Transaction_Factory::create( $transaction_data ); $this->assertInstanceOf( Transaction::class, $transaction ); // This is not necessary for this test, but we ensure we modify the entity $transaction->title = 'Factory Test'; global $zbs; // Prepare the Transaction data from the instance to save it via DAL $transaction_data_to_save = Transaction_Factory::data_for_dal( $transaction ); $id = $zbs->DAL->transactions->addUpdateTransaction( $transaction_data_to_save ); // Check that the Transaction is created and returns the id. $this->assertTrue( $id > 0 ); // Retrieve the transaction and check that the data is the same. $transaction_data_from_db = $zbs->DAL->transactions->getTransaction( $id ); // Create the instance from the transaction data retrieve from the DAL/DB. $transaction_instance = Transaction_Factory::create( $transaction_data_from_db ); $this->assertInstanceOf( Transaction::class, $transaction_instance ); $this->assertNotNull( $transaction_instance->id ); // List of fields to check their values $fields_to_check = array( 'desc', 'title', 'hash', 'type', 'currency', 'total', 'tax', ); foreach ( $fields_to_check as $field ) { $this->assertEquals( $transaction->$field, $transaction_instance->$field, "Transaction property $field does not match" ); } } }
projects/plugins/crm/tests/php/entities/class-invoice-entity-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Entities\Tests; use Automattic\Jetpack\CRM\Entities\Factories\Invoice_Factory; use Automattic\Jetpack\CRM\Entities\Invoice; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Integration_Test_Case; /** * Test Event Manager system. * * @covers Automattic\Jetpack\CRM\Entities */ class Invoice_Entity_Test extends JPCRM_Base_Integration_Test_Case { /** * @testdox Test that invoice entity is created from input data. */ public function test_invoice_entity_from_input_data() { $invoice_data = $this->generate_invoice_data(); // Create the Invoice instance from the invoice data (tidy DAL format) $invoice = Invoice_Factory::create( $invoice_data ); $this->assertInstanceOf( Invoice::class, $invoice ); // Check that the invoice data field values are the same to the Invoice instance field values. foreach ( $invoice_data as $key => $value ) { if ( ! property_exists( $invoice, $key ) ) { continue; } $this->assertEquals( $value, $invoice->$key, "Invoice property $key does not match" ); } } /** * @testdox Test create invoice entity from input data and insert in DB via DAL. */ public function test_create_invoice_from_input_data_and_insert_into_DB() { $invoice_data = $this->generate_invoice_data(); // Create the Invoice instance from the invoice data (tidy DAL format) $invoice = Invoice_Factory::create( $invoice_data ); $this->assertInstanceOf( Invoice::class, $invoice ); // This is not necessary for this test, but we ensure we modify the entity $invoice->currency = 'AUD'; global $zbs; // Prepare the Invoice data from the instance to save it via DAL $invoice_data_to_save = Invoice_Factory::data_for_dal( $invoice ); $id = $zbs->DAL->invoices->addUpdateInvoice( $invoice_data_to_save ); // Check that the Invoice is created and returns the id. $this->assertTrue( $id > 0 ); // Retrieve the invoice and check that the data is the same. $invoice_data_from_db = $zbs->DAL->invoices->getInvoice( $id ); // Create the instance from the invoice data retrieve from the DAL/DB. $invoice_instance = Invoice_Factory::create( $invoice_data_from_db ); $this->assertInstanceOf( Invoice::class, $invoice_instance ); $this->assertNotNull( $invoice_instance->id ); // List of fields to check their values $fields_to_check = array( 'id_override', 'parent', 'status', 'hash', 'send_attachments', 'currency', 'date', 'due_date', 'total', ); foreach ( $fields_to_check as $field ) { $this->assertEquals( $invoice->$field, $invoice_instance->$field, "Invoice property $field does not match" ); } } }
projects/plugins/crm/tests/php/entities/class-task-entity-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Entities\Tests; use Automattic\Jetpack\CRM\Entities\Factories\Task_Factory; use Automattic\Jetpack\CRM\Entities\Task; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Integration_Test_Case; /** * Test Event Manager system. * * @covers Automattic\Jetpack\CRM\Entities */ class Task_Entity_Test extends JPCRM_Base_Integration_Test_Case { /** * @testdox Test that task entity is created from input data. */ public function test_task_entity_from_input_data() { $task_data = $this->generate_task_data(); // Create the Task instance from the task data (tidy DAL format) $task = Task_Factory::create( $task_data ); $this->assertInstanceOf( Task::class, $task ); // Check that the task data field values are the same to the Task instance field values. foreach ( $task_data as $key => $value ) { if ( ! property_exists( $task, $key ) ) { continue; } $this->assertEquals( $value, $task->$key, "Task property $key does not match" ); } } /** * @testdox Test create task entity from input data and insert in DB via DAL. */ public function test_create_task_from_input_data_and_insert_into_DB() { $task_data = $this->generate_task_data(); // Create the Task instance from the task data (tidy DAL format) $task = Task_Factory::create( $task_data ); $this->assertInstanceOf( Task::class, $task ); // This is not necessary for this test, but we ensure we modify the entity $task->title = 'Factory Test'; global $zbs; // Prepare the Task data from the instance to save it via DAL $task_data_to_save = Task_Factory::data_for_dal( $task ); $id = $zbs->DAL->events->addUpdateEvent( $task_data_to_save ); // Check that the Task is created and returns the id. $this->assertTrue( $id > 0 ); // Retrieve the task and check that the data is the same. $task_data_from_db = $zbs->DAL->events->getEvent( $id ); // Create the instance from the task data retrieve from the DAL/DB. $task_instance = Task_Factory::create( $task_data_from_db ); $this->assertInstanceOf( Task::class, $task_instance ); $this->assertNotNull( $task_instance->id ); // List of fields to check their values $fields_to_check = array( 'title', 'desc', 'start', 'end', 'complete', 'show_on_portal', 'show_on_calendar', ); foreach ( $fields_to_check as $field ) { $this->assertEquals( $task->$field, $task_instance->$field, "Task property $field does not match" ); } } }
projects/plugins/crm/tests/php/entities/class-quote-entity-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Entities\Tests; use Automattic\Jetpack\CRM\Entities\Factories\Quote_Factory; use Automattic\Jetpack\CRM\Entities\Quote; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Integration_Test_Case; /** * Test Event Manager system. * * @covers Automattic\Jetpack\CRM\Entities */ class Quote_Entity_Test extends JPCRM_Base_Integration_Test_Case { /** * @testdox Test that quote entity is created from input data. */ public function test_quote_entity_from_input_data() { $quote_data = $this->generate_quote_data(); // Create the Quote instance from the quote data (tidy DAL format) $quote = Quote_Factory::create( $quote_data ); $this->assertInstanceOf( Quote::class, $quote ); // Check that the quote data field values are the same to the Quote instance field values. foreach ( $quote_data as $key => $value ) { if ( ! property_exists( $quote, $key ) ) { continue; } $this->assertEquals( $value, $quote->$key, "Quote property $key does not match" ); } } /** * @testdox Test create quote entity from input data and insert in DB via DAL. */ public function test_create_quote_from_input_data_and_insert_into_DB() { $quote_data = $this->generate_quote_data(); // Create the Quote instance from the quote data (tidy DAL format) $quote = Quote_Factory::create( $quote_data ); $this->assertInstanceOf( Quote::class, $quote ); // This is not necessary for this test, but we ensure we modify the entity $quote->title = 'Factory Test'; global $zbs; // Prepare the Quote data from the instance to save it via DAL $quote_data_to_save = Quote_Factory::data_for_dal( $quote ); $id = $zbs->DAL->quotes->addUpdateQuote( $quote_data_to_save ); // Check that the Quote is created and returns the id. $this->assertTrue( $id > 0 ); // Retrieve the quote and check that the data is the same. $quote_data_from_db = $zbs->DAL->quotes->getQuote( $id ); // Create the instance from the quote data retrieve from the DAL/DB. $quote_instance = Quote_Factory::create( $quote_data_from_db ); $this->assertInstanceOf( Quote::class, $quote_instance ); $this->assertNotNull( $quote_instance->id ); // List of fields to check their values $fields_to_check = array( 'id_override', 'title', 'value', 'hash', 'template', 'currency', 'date', 'notes', 'send_attachments', ); foreach ( $fields_to_check as $field ) { $this->assertEquals( $quote->$field, $quote_instance->$field, "Quote property $field does not match" ); } } }
projects/plugins/crm/tests/php/entities/class-contact-entity-test.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack\CRM\Entities\Tests; use Automattic\Jetpack\CRM\Entities\Contact; use Automattic\Jetpack\CRM\Entities\Factories\Contact_Factory; use Automattic\Jetpack\CRM\Tests\JPCRM_Base_Integration_Test_Case; /** * Test Event Manager system. * * @covers Automattic\Jetpack\CRM\Entities */ class Contact_Entity_Test extends JPCRM_Base_Integration_Test_Case { /** * @testdox Test that contact entity is created from input data. */ public function test_contact_entity_from_input_data() { $contact_data = $this->generate_contact_data(); // Create the Contact instance from the contact data (tidy DAL format) $contact = Contact_Factory::create( $contact_data ); $this->assertInstanceOf( Contact::class, $contact ); // Check that the contact data field values are the same to the Contact instance field values. foreach ( $contact_data as $key => $value ) { if ( ! property_exists( $contact, $key ) ) { continue; } $this->assertEquals( $value, $contact->$key, "Contact property $key does not match" ); } } /** * @testdox Test create contact entity from input data and insert in DB via DAL. */ public function test_create_contact_from_input_data_and_insert_into_DB() { $contact_data = $this->generate_contact_data(); // Create the Contact instance from the contact data (tidy DAL format) $contact = Contact_Factory::create( $contact_data ); $this->assertInstanceOf( Contact::class, $contact ); // This is not necessary for this test, but we ensure we modify the entity $contact->fname = 'Factory Test'; global $zbs; // Prepare the Contact data from the instance to save it via DAL $contact_data_to_save = Contact_Factory::data_for_dal( $contact ); $id = $zbs->DAL->contacts->addUpdateContact( $contact_data_to_save ); // Check that the Contact is created and returns the id. $this->assertTrue( $id > 0 ); // Retrieve the contact and check that the data is the same. $contact_data_from_db = $zbs->DAL->contacts->getContact( $id ); // Create the instance from the contact data retrieve from the DAL/DB. $contact_instance = Contact_Factory::create( $contact_data_from_db ); $this->assertInstanceOf( Contact::class, $contact_instance ); $this->assertNotNull( $contact_instance->id ); // List of fields to check their values $fields_to_check = array( 'fname', 'lname', 'email', 'status', 'addr1', 'addr2', 'city', 'country', 'postcode', 'hometel', 'worktel', 'mobtel', ); foreach ( $fields_to_check as $field ) { $this->assertEquals( $contact->$field, $contact_instance->$field, "Contact property $field does not match" ); } } }