filename
stringlengths
11
137
content
stringlengths
6
292k
projects/plugins/crm/tests/php/rest-api/class-rest-base-test-case.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * Base class for API test cases. * * @package automattic/jetpack-crm */ namespace Automattic\Jetpack\CRM\Tests; /** * Base class for Jetpack CRM API tests. */ abstract class REST_Base_Test_Case extends JPCRM_Base_Integration_Test_Case { /** * Create WordPress user. * * @param array $args A list of arguments to create the WP user from. * * @return int */ public function create_wp_user( $args = array() ) { return wp_insert_user( wp_parse_args( $args, array( 'user_login' => 'dummy_user', 'user_pass' => 'dummy_pass', 'role' => 'administrator', ) ) ); } /** * Create WordPress user. * * This user will use the 'zerobs_admin' role by default and can be used * to test e.g. API endpoints. * * @param array $args A list of arguments to create the WP user from. * * @return int */ public function create_wp_jpcrm_admin( $args = array() ) { $user_id = $this->create_wp_user( $args ); return $user_id; } }
projects/plugins/crm/tests/php/rest-api/v4/class-rest-automation-workflows-controller-test.php
<?php namespace Automattic\Jetpack\CRM\Tests; use Automatic\Jetpack\CRM\Automation\Tests\Mocks\Contact_Created_Trigger; use Automattic\Jetpack\CRM\Automation\Automation_Engine; use Automattic\Jetpack\CRM\Automation\Automation_Workflow; use Automattic\Jetpack\CRM\Automation\Tests\Automation_Faker; use Automattic\Jetpack\CRM\Automation\Tests\Mocks\Contact_Condition; use Automattic\Jetpack\CRM\Automation\Tests\Mocks\Dummy_Step; use Automattic\Jetpack\CRM\Automation\Workflow\Workflow_Repository; use WP_REST_Request; use WP_REST_Server; require_once JETPACK_CRM_TESTS_ROOT . '/automation/tools/class-automation-faker.php'; /** * REST_Automation_Workflows_Controller_Test class. * * @covers \Automattic\Jetpack\CRM\REST_API\V4\REST_Automation_Workflows_Controller */ class REST_Automation_Workflows_Controller_Test extends REST_Base_Test_Case { /** * @var Automation_Faker Automation Faker instance. */ private $automation_faker; /** * Set up the test. * * @return void */ public function set_up(): void { parent::set_up(); $this->automation_faker = Automation_Faker::instance(); // Register mock steps, so we can test the API without duplicating declaration every // time we use Automation_Faker data. $engine = Automation_Engine::instance(); $engine->register_step( Contact_Condition::class ); $engine->register_step( Dummy_Step::class ); // Make sure the default test trigger is registered. // @todo Figure out why we have to check if it already exists. // Initial exploration doesn't seem to leak any information to the next test // (which is indirectly confirmed by the steps above not complaining). if ( ! isset( $engine->get_registered_triggers()[ Contact_Created_Trigger::get_slug() ] ) ) { $engine->register_trigger( Contact_Created_Trigger::class ); } } /** * DataProvider: Roles. */ public function dataprovider_user_roles(): array { return array( 'subscriber' => array( 'subscriber', false ), 'administrator' => array( 'administrator', true ), 'zerobs_admin' => array( 'zerobs_admin', true ), ); } /** * Auth: Test that specific roles has access to the API. * * We use the simple "get all workflows" endpoint to test this since * all endpoints currently share the same auth logic. * * @see REST_Automation_Workflows_Controller::get_items_permissions_check() * * @dataProvider dataprovider_user_roles */ public function test_role_access( $role, $expectation ) { // Create and set authenticated user. $jpcrm_admin_id = $this->create_wp_jpcrm_admin( array( 'role' => $role ) ); wp_set_current_user( $jpcrm_admin_id ); // Make request. $request = new WP_REST_Request( WP_REST_Server::READABLE, '/jetpack-crm/v4/automation/workflows' ); $response = rest_do_request( $request ); if ( $expectation ) { $this->assertSame( 200, $response->get_status(), sprintf( 'Role should be allowed: %s', $role ) ); } else { $this->assertSame( 403, $response->get_status(), sprintf( 'Role should not be allowed: %s', $role ) ); } } /** * GET Workflows: Test that we can successfully access the endpoint. * * @return void */ public function test_get_workflows_success() { // Create and set authenticated user. $jpcrm_admin_id = $this->create_wp_jpcrm_admin(); wp_set_current_user( $jpcrm_admin_id ); $workflow_1 = $this->create_workflow( array( 'name' => 'test_get_workflows_success_1', ) ); $workflow_2 = $this->create_workflow( array( 'name' => 'test_get_workflows_success_2', ) ); // Make request. $request = new WP_REST_Request( WP_REST_Server::READABLE, '/jetpack-crm/v4/automation/workflows' ); $response = rest_do_request( $request ); $this->assertSame( 200, $response->get_status() ); $response_data = $this->prune_multiple_workflows( $response->get_data() ); $this->assertIsArray( $response_data ); $this->assertEquals( $response_data, array( $workflow_1->to_array(), $workflow_2->to_array(), ) ); } /** * DataProvider for pagination criteria. * * These scenarios assume that we always have 5 workflows when defining expectations. * * @return array Pagination criteria. */ public function dataprovider_pagination() { return array( 'page: 1 | per_page: 4 | expect: 4/5' => array( array( 'page' => 1, 'per_page' => 4, ), 4, ), 'page: 2 | per_page: 4 | expect: 1/5' => array( array( 'page' => 2, 'per_page' => 4, ), 1, ), 'per_page: 4 | offset: 3 | expect: 2/5' => array( array( 'per_page' => 4, 'offset' => 3, ), 2, ), 'per_page: N/A | offset: 2 | expect: 3/5' => array( array( 'offset' => 2 ), 3, ), 'per_page: 2 | offset: 2 | expect: 2/5' => array( array( 'offset' => 2, 'per_page' => 2, ), 2, ), ); } /** * GET Workflows: Test pagination. * * @dataProvider dataprovider_pagination * * @return void */ public function test_get_workflows_pagination( $args, $expected_count ): void { // Create and set authenticated user. $jpcrm_admin_id = $this->create_wp_jpcrm_admin(); wp_set_current_user( $jpcrm_admin_id ); // Create 5 workflows. for ( $i = 0; $i < 5; $i++ ) { $this->create_workflow( array( 'name' => sprintf( 'Workflow %d', $i ), ) ); } // Make request. $request = new WP_REST_Request( WP_REST_Server::READABLE, '/jetpack-crm/v4/automation/workflows' ); foreach ( $args as $key => $value ) { $request->set_param( $key, $value ); } $response = rest_do_request( $request ); $this->assertSame( 200, $response->get_status() ); $response_data = $response->get_data(); $this->assertIsArray( $response_data ); $this->assertCount( $expected_count, $response_data ); } /** * GET Workflows: Test that we return an empty array if we do not have any results. * * @return void */ public function test_get_workflows_return_empty(): void { // Create and set authenticated user. $jpcrm_admin_id = $this->create_wp_jpcrm_admin(); wp_set_current_user( $jpcrm_admin_id ); // Make request. $request = new WP_REST_Request( WP_REST_Server::READABLE, '/jetpack-crm/v4/automation/workflows' ); $response = rest_do_request( $request ); $this->assertSame( 200, $response->get_status() ); // Verify we get an empty array if we do not have any results. $response_data = $response->get_data(); $this->assertIsArray( $response_data ); $this->assertCount( 0, $response_data ); } /** * GET (Single) Workflow: Test that we can successfully access the endpoint. * * @return void */ public function test_get_workflow_success() { // Create and set authenticated user. $jpcrm_admin_id = $this->create_wp_jpcrm_admin(); wp_set_current_user( $jpcrm_admin_id ); $workflow = $this->create_workflow( array( 'name' => 'test_get_workflow_success', ) ); // Make request. $request = new WP_REST_Request( WP_REST_Server::READABLE, sprintf( '/jetpack-crm/v4/automation/workflows/%d', $workflow->get_id() ) ); $response = rest_do_request( $request ); $this->assertSame( 200, $response->get_status() ); $response_data = $this->prune_workflow_response( $response->get_data() ); $this->assertIsArray( $response_data ); $this->assertEquals( $response_data, $workflow->to_array() ); // We hardcode the name in the workflow creation, so we can verify that we're // actually retrieving the correct workflow and not just a false-positive response. $this->assertSame( 'test_get_workflow_success', $response_data['name'] ); } /** * GET Workflow: Test that we get a 404 if ID does not exist. * * @return void */ public function test_get_workflow_return_404_if_id_do_not_exist() { // Create and set authenticated user. $jpcrm_admin_id = $this->create_wp_jpcrm_admin(); wp_set_current_user( $jpcrm_admin_id ); // Make request. $request = new WP_REST_Request( WP_REST_Server::READABLE, '/jetpack-crm/v4/automation/workflows/123' ); $response = rest_do_request( $request ); $this->assertSame( 404, $response->get_status() ); } /** * PUT (Single) Workflow: Test that we can successfully update an existing workflow. * * @return void */ public function test_update_workflow_success() { // Create and set authenticated user. $jpcrm_admin_id = $this->create_wp_jpcrm_admin(); wp_set_current_user( $jpcrm_admin_id ); // Create a workflow that we will update later. $workflow = $this->create_workflow(); // Define values to use for our update request and to verify that the workflow was updated. $update_data = array( 'name' => 'my updated name', 'description' => 'my updated description', 'category' => 'jpcrm/updated-category', 'active' => false, // We re-use the same trigger twice to verify that we can update the triggers data. // We could also use two unique triggers, but this makes it, so we don't have to // register more triggers to run the test. 'triggers' => array( Contact_Created_Trigger::get_slug(), Contact_Created_Trigger::get_slug(), ), 'initial_step' => 'updated_step_2', 'steps' => array( 'updated_step_1' => array( 'slug' => Contact_Condition::get_slug(), 'next_step_true' => 'updated_step_2', 'next_step_false' => null, 'attributes' => array(), ), 'updated_step_2' => array( 'slug' => Contact_Condition::get_slug(), 'next_step_true' => null, 'next_step_false' => null, 'attributes' => array(), ), ), ); // Make request. $request = new WP_REST_Request( 'PUT', sprintf( '/jetpack-crm/v4/automation/workflows/%d', $workflow->get_id() ) ); foreach ( $update_data as $param => $value ) { $request->set_param( $param, $value ); } $response = rest_do_request( $request ); $this->assertSame( 200, $response->get_status() ); // Verify that all the values we passed are returned as the updated workflow. $response_data = $this->prune_workflow_response( $response->get_data() ); $this->assertIsArray( $response_data ); foreach ( $update_data as $param => $value ) { $this->assertSame( $value, $response_data[ $param ], sprintf( 'The following param failed: %s', $param ) ); } // Verify that all the values we passed were persisted in the database. $repo = new Workflow_Repository(); $fetched_workflow = ( $repo->find( $response_data['id'] ) )->to_array(); $this->assertIsArray( $response_data ); foreach ( $update_data as $param => $value ) { $this->assertSame( $value, $fetched_workflow[ $param ], sprintf( 'The following param failed: %s', $param ) ); } } /** * Prune workflow API response data for comparisons purposes. * * @see prune_workflow_response * * @param array[] $workflows The returned workflows we wish to prune for direct comparison. * @return array The pruned workflows. */ protected function prune_multiple_workflows( $workflows ) { foreach ( $workflows as $index => $workflow ) { $workflows[ $index ] = $this->prune_workflow_response( $workflow ); } return $workflows; } /** * Prune workflow API response data for comparisons. * * The API endpoint will add additional data to workflow objects that we do not * necessarily care about (e.g.: "attribute_definitions"), so this method will * prune those data to make it easier to compare the original workflow and * the response. * * @since 6.2.0 * * @param array $workflow_data The returned workflow data. * @return array The pruned workflow data. */ protected function prune_workflow_response( array $workflow_data ): array { $static_step_fields = array( 'id', 'title', 'description', 'category', 'step_type', 'attribute_definitions', ); if ( ! empty( $workflow_data['steps'] ) && is_array( $workflow_data['steps'] ) ) { foreach ( $workflow_data['steps'] as $index => $step ) { foreach ( $static_step_fields as $field ) { if ( isset( $step[ $field ] ) ) { unset( $step[ $field ] ); } } $workflow_data['steps'][ $index ] = $step; } } // Revert the triggers to their original format. // We populate workflows with full trigger objects, but the Automation_Workflow class itself // only stores the trigger slug, so we have to reduce the trigger object from API responses to // slugs before we're able to do direct comparisons. if ( ! empty( $workflow_data['triggers'] ) && is_array( $workflow_data['triggers'] ) ) { foreach ( $workflow_data['triggers'] as $index => $trigger ) { $workflow_data['triggers'][ $index ] = $workflow_data['triggers'][ $index ]['slug']; } } return $workflow_data; } /** * DELETE Workflow: Test that we can successfully delete a workflow. * * @return void */ public function test_delete_workflow_success() { // Create and set authenticated user. $jpcrm_admin_id = $this->create_wp_jpcrm_admin(); wp_set_current_user( $jpcrm_admin_id ); $workflow = $this->create_workflow( array( 'name' => 'test_get_workflow_success', ) ); // Make request. $request = new WP_REST_Request( WP_REST_Server::DELETABLE, sprintf( '/jetpack-crm/v4/automation/workflows/%d', $workflow->get_id() ) ); $response = rest_do_request( $request ); $this->assertSame( 204, $response->get_status() ); // Verify that the workflow was deleted. $repo = new Workflow_Repository(); $this->assertFalse( $repo->find( $workflow->get_id() ) ); } /** * DELETE Workflow: Test that we return a 404 if the workflow does not exist. * * @return void */ public function test_delete_workflow_return_404_if_id_do_not_exist() { // Create and set authenticated user. $jpcrm_admin_id = $this->create_wp_jpcrm_admin(); wp_set_current_user( $jpcrm_admin_id ); // Make request. $request = new WP_REST_Request( WP_REST_Server::DELETABLE, '/jetpack-crm/v4/automation/workflows/%d' ); $response = rest_do_request( $request ); $this->assertSame( 404, $response->get_status() ); } /** * POST (Single) Workflow: Test that we can successfully create a workflow. * * @return void */ public function test_create_workflow_success() { // Create and set authenticated user. $jpcrm_admin_id = $this->create_wp_jpcrm_admin(); wp_set_current_user( $jpcrm_admin_id ); $workflow_data = Automation_Faker::instance()->workflow_with_condition_action(); // Make request. $request = new WP_REST_Request( 'POST', '/jetpack-crm/v4/automation/workflows' ); foreach ( $workflow_data as $param => $value ) { $request->set_param( $param, $value ); } $response = rest_do_request( $request ); $this->assertSame( 200, $response->get_status() ); // Verify that all our parameters are returned in the created workflow. $response_data = $this->prune_workflow_response( $response->get_data() ); $this->assertIsArray( $response_data ); foreach ( $workflow_data as $param => $value ) { $this->assertSame( $value, $response_data[ $param ], sprintf( 'The following param failed: %s', $param ) ); } // Verify that all of our parameters were persisted in the database. $repo = new Workflow_Repository(); $fetched_workflow = ( $repo->find( $response_data['id'] ) )->to_array(); $this->assertIsArray( $response_data ); foreach ( $workflow_data as $param => $value ) { $this->assertEquals( $value, $fetched_workflow[ $param ], sprintf( 'The following param failed: %s', $param ) ); } } /** * Generate a workflow for testing. * * @param array $data (Optional) Workflow data. * @return Automation_Workflow * * @throws \Automattic\Jetpack\CRM\Automation\Workflow_Exception */ protected function create_workflow( array $data = array() ) { $workflow_data = wp_parse_args( $data, $this->automation_faker->workflow_with_condition_action() ); $workflow_data['triggers'] = array( Contact_Created_Trigger::get_slug() ); $workflow = new Automation_Workflow( $workflow_data ); $repo = new Workflow_Repository(); $repo->persist( $workflow ); return $workflow; } }
projects/plugins/crm/tests/php/rest-api/v4/class-rest-authentication-test.php
<?php namespace Automattic\Jetpack\CRM\Tests; use WP_REST_Request; use WP_REST_Server; require_once __DIR__ . '/../class-rest-base-test-case.php'; /** * Authentication test. * * @covers \Automattic\Jetpack\CRM\REST_API\V4\REST_Contacts_Controller */ class REST_Authentication_Test extends REST_Base_Test_Case { /** * Return an array of URLs that require WP_User/cookie authentication. * * @return string[][] */ public function auth_user_url_provider() { return array( 'contacts_controller::get_item' => array( WP_REST_Server::READABLE, '/jetpack-crm/v4/contacts/123', array(), ), 'automation_workflows::get_items' => array( WP_REST_Server::READABLE, '/jetpack-crm/v4/automation/workflows', array(), ), 'automation_workflows::get_item' => array( WP_REST_Server::READABLE, '/jetpack-crm/v4/automation/workflows/123', array(), ), 'automation_workflows::update_item' => array( WP_REST_Server::CREATABLE, '/jetpack-crm/v4/automation/workflows/123', array(), ), 'automation_workflows::create_item' => array( WP_REST_Server::CREATABLE, '/jetpack-crm/v4/automation/workflows', array( 'name' => 'abc', 'description' => 'abc', 'category' => 'abc', 'active' => true, 'initial_step' => 0, 'steps' => array(), ), ), 'automation_workflows::delete_item' => array( WP_REST_Server::DELETABLE, '/jetpack-crm/v4/automation/workflows/123', array(), ), ); } /** * Return an array of all URLs that require authentication. * * @return string[][] */ public function auth_all_urls_provider() { // We don't have any POST/PATCH/DELETE requests yet, so we just return the // dataProvider containing GET requests that requires authentication. return $this->auth_user_url_provider(); } /** * Test that endpoints that require user auth returns 401 if accessed without a WP User. * * @dataProvider auth_all_urls_provider * * @param string $method HTTP verb. * @param string $url URL to send a request to. * @param array $params Request parameters. */ public function test_unauthenticated_endpoints_return_a_401( $method, $url, $params ) { $request = new WP_REST_Request( $method, $url ); foreach ( $params as $param => $value ) { $request->set_param( $param, $value ); } $response = rest_do_request( $request ); $this->assertSame( 401, $response->get_status() ); $this->assertSame( 'rest_cannot_view', $response->get_data()['code'] ); } /** * Test that endpoints returns 403 if a WP user have insufficient capabilities. * * @dataProvider auth_all_urls_provider * * @param string $method HTTP verb. * @param string $url URL to send a request to. * @param array $params Request parameters. */ public function test_auth_user_endpoints_return_403_with_insufficient_capabilities( $method, $url, $params ) { $wp_user_id = $this->create_wp_user( array( 'role' => 'subscriber' ) ); wp_set_current_user( $wp_user_id ); $request = new WP_REST_Request( $method, $url ); foreach ( $params as $param => $value ) { $request->set_param( $param, $value ); } $response = rest_do_request( $request ); $this->assertSame( 403, $response->get_status() ); $this->assertSame( 'rest_cannot_view', $response->get_data()['code'] ); } }
projects/plugins/crm/tests/php/rest-api/v4/class-rest-contacts-controller-test.php
<?php namespace Automattic\Jetpack\CRM\Tests; use Exception; use WP_REST_Request; use WP_REST_Server; use zbsDAL_contacts; require_once __DIR__ . '/../class-rest-base-test-case.php'; /** * Route_Scope class. * * @covers \Automattic\Jetpack\CRM\REST_API\V4\REST_Contacts_Controller */ class REST_Contacts_Controller_Test extends REST_Base_Test_Case { /** * GET Contact: Test that we can successfully access the endpoint. * * @return void */ public function test_get_item_success() { // Create and set authenticated user. $wp_user_id = $this->create_wp_user(); wp_set_current_user( $wp_user_id ); // Create a contact we can fetch. $contact_id = $this->add_contact( array( 'fname' => 'Joan', 'lname' => 'Smith', ) ); // Make request. $request = new WP_REST_Request( WP_REST_Server::READABLE, sprintf( '/jetpack-crm/v4/contacts/%d', $contact_id ) ); $response = rest_do_request( $request ); $this->assertSame( 200, $response->get_status() ); $contact = $response->get_data(); $this->assertIsArray( $contact ); $this->assertSame( 'Joan', $contact['fname'] ); $this->assertSame( 'Smith', $contact['lname'] ); } /** * GET Contact: Test that we return a 404 if the requested contact do not exist. * * @return void */ public function test_get_item_return_404_if_contact_do_not_exist() { // Create and set authenticated user. $wp_user_id = $this->create_wp_user(); wp_set_current_user( $wp_user_id ); // Make request for a contact ID that do not exist. $request = new WP_REST_Request( WP_REST_Server::READABLE, sprintf( '/jetpack-crm/v4/contacts/%d', 999 ) ); $response = rest_do_request( $request ); $this->assertSame( 404, $response->get_status() ); $this->assertSame( 'rest_invalid_contact_id', $response->get_data()['code'] ); } /** * GET Contact: Test that we catch unknown fatal errors. * * @return void */ public function test_get_item_unknown_fatal_error() { // Create a function that throws an exception, so we can test that // we successfully catch unexpected errors. $func = function () { throw new Exception( 'Mock fatal' ); }; // Mock contacts DAL service. $dal_mock = $this->createMock( zbsDAL_contacts::class ); $dal_mock->method( 'getContact' )->willReturnCallback( $func ); $GLOBALS['zbs']->DAL = new \stdClass(); $GLOBALS['zbs']->DAL->contacts = $dal_mock; // Create and set authenticated user. $wp_user_id = $this->create_wp_user(); wp_set_current_user( $wp_user_id ); // Make a (hopefully) successful request. $request = new WP_REST_Request( WP_REST_Server::READABLE, sprintf( '/jetpack-crm/v4/contacts/%d', 123 ) ); $response = rest_do_request( $request ); $this->assertSame( 500, $response->get_status() ); $this->assertSame( 'rest_unknown_error', $response->get_data()['code'] ); $this->assertSame( 'Mock fatal', $response->get_data()['message'] ); } }
projects/plugins/crm/includes/wh.countries.lib.php
<?php /*! * Woody Hayday Country Lib * V1.0 * * Copyright 2020 Automattic * * Date: 25/10/16 */ global $zeroBSCRM_countries; #https://gist.github.com/vxnick/380904 $zeroBSCRM_countries = array( 'AF' => 'Afghanistan', 'AX' => 'Aland Islands', 'AL' => 'Albania', 'DZ' => 'Algeria', 'AS' => 'American Samoa', 'AD' => 'Andorra', 'AO' => 'Angola', 'AI' => 'Anguilla', 'AQ' => 'Antarctica', 'AG' => 'Antigua and Barbuda', 'AR' => 'Argentina', 'AM' => 'Armenia', 'AW' => 'Aruba', 'AU' => 'Australia', 'AT' => 'Austria', 'AZ' => 'Azerbaijan', 'BS' => 'Bahamas', 'BH' => 'Bahrain', 'BD' => 'Bangladesh', 'BB' => 'Barbados', 'BY' => 'Belarus', 'BE' => 'Belgium', 'BZ' => 'Belize', 'BJ' => 'Benin', 'BM' => 'Bermuda', 'BT' => 'Bhutan', 'BO' => 'Bolivia', 'BQ' => 'Bonaire, Saint Eustatius and Saba', 'BA' => 'Bosnia and Herzegovina', 'BW' => 'Botswana', 'BV' => 'Bouvet Island', 'BR' => 'Brazil', 'IO' => 'British Indian Ocean Territory', 'VG' => 'British Virgin Islands', 'BN' => 'Brunei', 'BG' => 'Bulgaria', 'BF' => 'Burkina Faso', 'BI' => 'Burundi', 'KH' => 'Cambodia', 'CM' => 'Cameroon', 'CA' => 'Canada', 'CV' => 'Cape Verde', 'KY' => 'Cayman Islands', 'CF' => 'Central African Republic', 'TD' => 'Chad', 'CL' => 'Chile', 'CN' => 'China', 'CX' => 'Christmas Island', 'CC' => 'Cocos Islands', 'CO' => 'Colombia', 'KM' => 'Comoros', 'CK' => 'Cook Islands', 'CR' => 'Costa Rica', 'HR' => 'Croatia', 'CU' => 'Cuba', 'CW' => 'Curacao', 'CY' => 'Cyprus', 'CZ' => 'Czech Republic', 'CD' => 'Democratic Republic of the Congo', 'DK' => 'Denmark', 'DJ' => 'Djibouti', 'DM' => 'Dominica', 'DO' => 'Dominican Republic', 'TL' => 'East Timor', 'EC' => 'Ecuador', 'EG' => 'Egypt', 'SV' => 'El Salvador', 'GQ' => 'Equatorial Guinea', 'ER' => 'Eritrea', 'EE' => 'Estonia', 'ET' => 'Ethiopia', 'FK' => 'Falkland Islands', 'FO' => 'Faroe Islands', 'FJ' => 'Fiji', 'FI' => 'Finland', 'FR' => 'France', 'GF' => 'French Guiana', 'PF' => 'French Polynesia', 'TF' => 'French Southern Territories', 'GA' => 'Gabon', 'GM' => 'Gambia', 'GE' => 'Georgia', 'DE' => 'Germany', 'GH' => 'Ghana', 'GI' => 'Gibraltar', 'GR' => 'Greece', 'GL' => 'Greenland', 'GD' => 'Grenada', 'GP' => 'Guadeloupe', 'GU' => 'Guam', 'GT' => 'Guatemala', 'GG' => 'Guernsey', 'GN' => 'Guinea', 'GW' => 'Guinea-Bissau', 'GY' => 'Guyana', 'HT' => 'Haiti', 'HM' => 'Heard Island and McDonald Islands', 'HN' => 'Honduras', 'HK' => 'Hong Kong', 'HU' => 'Hungary', 'IS' => 'Iceland', 'IN' => 'India', 'ID' => 'Indonesia', 'IR' => 'Iran', 'IQ' => 'Iraq', 'IE' => 'Ireland', 'IM' => 'Isle of Man', 'IL' => 'Israel', 'IT' => 'Italy', 'CI' => 'Ivory Coast', 'JM' => 'Jamaica', 'JP' => 'Japan', 'JE' => 'Jersey', 'JO' => 'Jordan', 'KZ' => 'Kazakhstan', 'KE' => 'Kenya', 'KI' => 'Kiribati', 'XK' => 'Kosovo', 'KW' => 'Kuwait', 'KG' => 'Kyrgyzstan', 'LA' => 'Laos', 'LV' => 'Latvia', 'LB' => 'Lebanon', 'LS' => 'Lesotho', 'LR' => 'Liberia', 'LY' => 'Libya', 'LI' => 'Liechtenstein', 'LT' => 'Lithuania', 'LU' => 'Luxembourg', 'MO' => 'Macao', 'MK' => 'Macedonia', 'MG' => 'Madagascar', 'MW' => 'Malawi', 'MY' => 'Malaysia', 'MV' => 'Maldives', 'ML' => 'Mali', 'MT' => 'Malta', 'MH' => 'Marshall Islands', 'MQ' => 'Martinique', 'MR' => 'Mauritania', 'MU' => 'Mauritius', 'YT' => 'Mayotte', 'MX' => 'Mexico', 'FM' => 'Micronesia', 'MD' => 'Moldova', 'MC' => 'Monaco', 'MN' => 'Mongolia', 'ME' => 'Montenegro', 'MS' => 'Montserrat', 'MA' => 'Morocco', 'MZ' => 'Mozambique', 'MM' => 'Myanmar', 'NA' => 'Namibia', 'NR' => 'Nauru', 'NP' => 'Nepal', 'NL' => 'Netherlands', 'NC' => 'New Caledonia', 'NZ' => 'New Zealand', 'NI' => 'Nicaragua', 'NE' => 'Niger', 'NG' => 'Nigeria', 'NU' => 'Niue', 'NF' => 'Norfolk Island', 'KP' => 'North Korea', 'MP' => 'Northern Mariana Islands', 'NO' => 'Norway', 'OM' => 'Oman', 'PK' => 'Pakistan', 'PW' => 'Palau', 'PS' => 'Palestinian Territory', 'PA' => 'Panama', 'PG' => 'Papua New Guinea', 'PY' => 'Paraguay', 'PE' => 'Peru', 'PH' => 'Philippines', 'PN' => 'Pitcairn', 'PL' => 'Poland', 'PT' => 'Portugal', 'PR' => 'Puerto Rico', 'QA' => 'Qatar', 'CG' => 'Republic of the Congo', 'RE' => 'Reunion', 'RO' => 'Romania', 'RU' => 'Russia', 'RW' => 'Rwanda', 'BL' => 'Saint Barthelemy', 'SH' => 'Saint Helena', 'KN' => 'Saint Kitts and Nevis', 'LC' => 'Saint Lucia', 'MF' => 'Saint Martin', 'PM' => 'Saint Pierre and Miquelon', 'VC' => 'Saint Vincent and the Grenadines', 'WS' => 'Samoa', 'SM' => 'San Marino', 'ST' => 'Sao Tome and Principe', 'SA' => 'Saudi Arabia', 'SN' => 'Senegal', 'RS' => 'Serbia', 'SC' => 'Seychelles', 'SL' => 'Sierra Leone', 'SG' => 'Singapore', 'SX' => 'Sint Maarten', 'SK' => 'Slovakia', 'SI' => 'Slovenia', 'SB' => 'Solomon Islands', 'SO' => 'Somalia', 'ZA' => 'South Africa', 'GS' => 'South Georgia and the South Sandwich Islands', 'KR' => 'South Korea', 'SS' => 'South Sudan', 'ES' => 'Spain', 'LK' => 'Sri Lanka', 'SD' => 'Sudan', 'SR' => 'Suriname', 'SJ' => 'Svalbard and Jan Mayen', 'SZ' => 'Swaziland', 'SE' => 'Sweden', 'CH' => 'Switzerland', 'SY' => 'Syria', 'TW' => 'Taiwan', 'TJ' => 'Tajikistan', 'TZ' => 'Tanzania', 'TH' => 'Thailand', 'TG' => 'Togo', 'TK' => 'Tokelau', 'TO' => 'Tonga', 'TT' => 'Trinidad and Tobago', 'TN' => 'Tunisia', 'TR' => 'Turkey', 'TM' => 'Turkmenistan', 'TC' => 'Turks and Caicos Islands', 'TV' => 'Tuvalu', 'VI' => 'U.S. Virgin Islands', 'UG' => 'Uganda', 'UA' => 'Ukraine', 'AE' => 'United Arab Emirates', 'GB' => 'United Kingdom', 'US' => 'United States', 'UM' => 'United States Minor Outlying Islands', 'UY' => 'Uruguay', 'UZ' => 'Uzbekistan', 'VU' => 'Vanuatu', 'VA' => 'Vatican', 'VE' => 'Venezuela', 'VN' => 'Vietnam', 'WF' => 'Wallis and Futuna', 'EH' => 'Western Sahara', 'YE' => 'Yemen', 'ZM' => 'Zambia', 'ZW' => 'Zimbabwe', );
projects/plugins/crm/includes/ZeroBSCRM.InternalAutomator.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V1.1.15 * * Copyright 2020 Automattic * * Date: 30/08/16 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== Internal Automator ====================================================== */ #} Main automator func, this'll get run at the bottom of all the main actions #} e.g. when adding a new invoice: #} zeroBSCRM_FireInternalAutomator('invoice.new',$newInvoice); /* Current action str: log.new log.update log.delete customer.new company.new (not yet logging) quote.new invoice.new #} 1.2.7 added a catcher for dupes... if "quote.new" for example is fired with the same setup within 1 script run, it'll ignore second... */ global $zeroBSCRM_IA_ActiveAutomations, $zeroBSCRM_IA_Dupeblocks; $zeroBSCRM_IA_Dupeblocks = array('quote.new','invoice.new','transaction.new'); function zeroBSCRM_FireInternalAutomator($actionStr='',$obj=array()){ $goodToGo = true; global $zbs,$zeroBSCRM_IA_ActiveAutomations, $zeroBSCRM_IA_Dupeblocks; #} Some legacy support $actionStr = zeroBSCRM_InternalAutomatorLegacyActionCheck($actionStr); #} dupe catch if (in_array($actionStr,$zeroBSCRM_IA_Dupeblocks)){ if (gettype($obj) != "string" && gettype($obj) != "String"){ #$objStr = implode('.',$obj); $objStr = json_encode($obj); $objStr = md5($objStr); $actionHash = $actionStr.$objStr; } else $actionHash = $actionStr.md5($obj); if (isset($zeroBSCRM_IA_ActiveAutomations[$actionHash])) $goodToGo = false; #} DUPE else $zeroBSCRM_IA_ActiveAutomations[$actionHash] = time(); } #} Internal automator block (Migration routine first use) if ($zbs->internalAutomatorBlock) $goodToGo = false; if ($goodToGo && !empty($actionStr)){ #} Action str should be alphanumeric with periods #} Checks if there's a global variable (work list) for this $actionStr $actionHolderName = 'zeroBSCRM_IA_Action_'.str_replace('.','_',$actionStr); #} Exists? if (isset($GLOBALS[ $actionHolderName ]) && is_array($GLOBALS[ $actionHolderName ])){ #} If here, has an array foreach ($GLOBALS[ $actionHolderName ] as $action){ if (isset($action['act']) && !empty($action['act']) && isset($action['params'])){ #} ['params'] not used yet... future proofing. #} Fire any applicable if (function_exists($action['act'])){ #} call it, (and pass whatever was passed to this) call_user_func($action['act'],$obj); } } } } } return; } function zeroBSCRM_AddInternalAutomatorRecipe($actionStr='',$functionName='',$paramsObj=array()){ if (!empty($actionStr) && !empty($functionName)){ #} Some legacy support $actionStr = zeroBSCRM_InternalAutomatorLegacyActionCheck($actionStr); #} Action str should be alphanumeric with periods #} Checks if there's a global variable (work list) for this $actionStr $actionHolderName = 'zeroBSCRM_IA_Action_'.str_replace('.','_',$actionStr); #} Init? if (!isset($GLOBALS[ $actionHolderName ])) $GLOBALS[ $actionHolderName ] = array(); #} Append. array_push($GLOBALS[ $actionHolderName ],array('act'=>$functionName,'params'=>$paramsObj)); return true; } return false; } // checks for newer labels + converts function zeroBSCRM_InternalAutomatorLegacyActionCheck($actionStr = ''){ #} Some legacy support switch ($actionStr){ case 'contact.new': $actionStr = 'customer.new'; break; case 'contact.update': $actionStr = 'customer.update'; break; case 'contact.status.update': $actionStr = 'customer.status.update'; break; } return $actionStr; } /* ====================================================== / Internal Automator ====================================================== */
projects/plugins/crm/includes/ZeroBSCRM.AdminPages.Checks.php
<?php /* ! * Jetpack CRM * https://jetpackcrm.com * V1.20 * * Copyright 2020 Automattic * * Date: 01/11/16 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) { exit; } /* ====================================================== / Breaking Checks ====================================================== */ // ========= GENERIC ============================================ // Centralised func which does a lot of the lifting used throughout these check funcs function zeroBS_isPage( $pageArr = array(), $postTypes = false, $adminPages = false, $includeFrontEnd = false ) { global $pagenow; // make sure we are on the backend if ( ! $includeFrontEnd ) { if ( ! is_admin() ) { return false; } } // check in array (like array( 'post.php', 'post-new.php' )) if ( in_array( $pagenow, $pageArr ) ) { if ( is_array( $postTypes ) ) { $postID = -1; // catches get if ( isset( $_GET['post'] ) ) { $postID = (int) sanitize_text_field( $_GET['post'] ); } // catches post saving / update if ( isset( $_POST['post_ID'] ) ) { $postID = (int) sanitize_text_field( $_POST['post_ID'] ); } // check post type? if ( $postID !== -1 && in_array( get_post_type( $postID ), $postTypes ) ) { return true; } // WH added: needed for post-new.php etc. if ( isset( $_GET['post_type'] ) && in_array( sanitize_text_field( $_GET['post_type'] ), $postTypes ) ) { return true; } } elseif ( is_array( $adminPages ) ) { // check page slug if ( isset( $_GET['page'] ) && in_array( sanitize_text_field( $_GET['page'] ), $adminPages ) ) { return true; } } else { // no post types given, but page = $pageArr, so return true return true; } } return false; } // checks for presence of url params function zeroBS_hasGETParams( $pageArr = array(), $params = array() ) { global $pagenow; // make sure we are on the backend if ( ! is_admin() ) { return false; } // check in array (like array( 'post.php', 'post-new.php' )) if ( in_array( $pagenow, $pageArr ) ) { if ( is_array( $params ) && count( $params ) > 0 ) { // check params - return false if any not present foreach ( $params as $p ) { if ( ! isset( $_GET[ $p ] ) ) { return false; } } // has all params return true; } } return false; } // checks for presence of url params function zeroBS_hasGETParamsWithValues( $pageArr = array(), $params = array(), $noneOfTheseParams = array() ) { global $pagenow; // make sure we are on the backend if ( ! is_admin() ) { return false; } // check in array (like array( 'post.php', 'post-new.php' )) if ( in_array( $pagenow, $pageArr ) ) { if ( is_array( $params ) && count( $params ) > 0 ) { // check params against vals foreach ( $params as $p => $v ) { if ( ! isset( $_GET[ $p ] ) || $_GET[ $p ] != $v ) { return false; } } // check for $noneOfTheseParams foreach ( $noneOfTheseParams as $p ) { if ( isset( $_GET[ $p ] ) ) { return false; } } // has all params return true; } } return false; } function zeroBSCRM_isLoginPage() { // http://wordpress.stackexchange.com/questions/12863/check-if-were-on-the-wp-login-page // if ( in_array( $GLOBALS['pagenow'], array( 'wp-login.php', 'wp-register.php' ) ) ) return true; // return false; return zeroBS_isPage( array( 'wp-login.php', 'wp-register.php' ), false, false, true ); } function zeroBSCRM_isWelcomeWizPage() { global $zeroBSCRM_killDenied; if ( isset( $zeroBSCRM_killDenied ) && $zeroBSCRM_killDenied === true ) { return true; } return false; } function zeroBSCRM_isAPIRequest() { // SCRIPT_URL not present in $_SERVER on mine: https://stackoverflow.com/questions/24428981/serverscript-url-when-is-it-reliably-present // below is more reliable as QUERY_STRING will always be set for API requests. // lazy, non-wp way of doing this if ( isset( $_SERVER['QUERY_STRING'] ) && ( strpos( '#' . sanitize_text_field( wp_unslash( $_SERVER['QUERY_STRING'] ) ), 'api_key=zbscrm_' ) > 0 || strpos( '#' . sanitize_text_field( wp_unslash( $_SERVER['QUERY_STRING'] ) ), 'api_key=jpcrm_' ) ) ) { return true; } // Added REST api v2.94ish, so had to add this to skip dashcatch // https://wordpress.stackexchange.com/questions/221202/does-something-like-is-rest-exist if ( zeroBSCRM_isRestUrl() ) { return true; } return false; } // is a REST url // doesn't validate auth or anything, just 'LOOKS LIKE REST URL' // https://wordpress.stackexchange.com/questions/221202/does-something-like-is-rest-exist function zeroBSCRM_isRestUrl() { $is_rest_url = false; if ( function_exists( 'rest_url' ) && ! empty( $_SERVER['REQUEST_URI'] ) ) { $sRestUrlBase = get_rest_url( get_current_blog_id(), '/' ); $sRestPath = trim( parse_url( $sRestUrlBase, PHP_URL_PATH ), '/' ); $sRequestPath = trim( $_SERVER['REQUEST_URI'], '/' ); $is_rest_url = ( str_starts_with( $sRequestPath, $sRestPath ) ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } return $is_rest_url; } function zeroBSCRM_isClientPortalPage() { global $zbs; if ( property_exists( $zbs->modules, 'portal' ) ) { return $zbs->modules->portal->is_portal_page(); } return false; } // } Determines if we are on a ZBS Admin Page (i.e. app page, including the customer edit + other custom post pages) // } Have made a more generic check of the zeroBSCRM_is_customer_edit_page to cover all our custom post types // } such as zerobs_ticket (for Groove Sync) etc. etc. etc. function zeroBSCRM_is_ZBS_custom_post_page() { return zeroBS_isPage( array( 'post.php', 'post-new.php', 'edit-tags.php', 'edit.php' ), array( 'zerobs_customer', 'zerobs_quote', 'zerobs_invoice', 'zerobs_quo_template', 'zerobs_transaction', 'zerobs_company', 'zerobs_form', 'zerobs_event' ) ); } function zeroBSCRM_isAdminPage() { // make sure we are on the backend if ( ! is_admin() ) { return false; } global $zbs; // basic slug check if ( isset( $_GET['page'] ) ) { if ( in_array( $_GET['page'], $zbs->slugs ) ) { return true; } } // custom post type pages if ( zeroBSCRM_is_ZBS_custom_post_page() ) { return true; } // odd pages? if ( ( isset( $_GET['page'] ) ) && ( $_GET['page'] === 'zbs-noaccess' || $_GET['page'] === 'manage-customers' || $_GET['page'] === 'manage-invoices-crm' ) ) { return true; } // custom slug checks? if ( isset( $_GET['zbsslug'] ) ) { if ( in_array( sanitize_text_field( $_GET['zbsslug'] ), $zbs->slugs ) ) { return true; } } // lastly... grasping at straws... check for defined global (defined in global admin script) if ( defined( 'ZBS_PAGE' ) ) { $isOurPage = true; } // use a filter to catch return's for ext pages $return = false; $return = apply_filters( 'zbs-page-check', $return ); return $return; } function zeroBSCRM_is_edit_page( $new_edit = null ) { // make sure we are on the backend if ( ! is_admin() ) { return false; } global $pagenow; if ( $new_edit == 'edit' ) { return in_array( $pagenow, array( 'post.php' ) ); } elseif ( $new_edit == 'new' ) { // check for new post page return in_array( $pagenow, array( 'post-new.php' ) ); } else { // check for either new or edit return in_array( $pagenow, array( 'post.php', 'post-new.php' ) ); } } // returns true if on a zbs edit page // (for any obj) function zeroBSCRM_is_zbs_edit_page( $specificType = false, $isNew = false ) { // make sure we are on the backend if ( ! is_admin() ) { return false; } // then if we have these, it's an edit page if ( $specificType !== false ) { // check with type if ( zeroBS_hasGETParamsWithValues( array( 'admin.php' ), array( 'page' => 'zbs-add-edit', 'action' => 'edit', 'zbstype' => $specificType, ) ) ) { // looking to see if is new page? if ( $isNew ) { if ( ! isset( $_GET['zbsid'] ) ) { return true; } } else { return true; } } } elseif ( zeroBS_hasGETParamsWithValues( array( 'admin.php' ), array( 'page' => 'zbs-add-edit', 'action' => 'edit', ) ) ) { return true; } // if not, then nope. return false; } // is a "delete x?" page function zeroBSCRM_is_delete_page( $new_edit = null ) { // make sure we are on the backend if ( ! is_admin() ) { return false; } // then if we have these, it's an edit page if ( zeroBS_hasGETParamsWithValues( array( 'admin.php' ), array( 'page' => 'zbs-add-edit', 'action' => 'delete', ) ) ) { return true; } // if not, then nope. return false; } // ========= / GENERIC ============================================ // ========= CONTACTS ============================================= // generic check for any page concerning 'contacts' function zeroBSCRM_isAnyContactPage() { if ( zeroBSCRM_is_contact_list_page() ) { return true; } if ( zeroBSCRM_is_customer_edit_page() ) { return true; } if ( zeroBSCRM_is_customer_new_page() ) { return true; } if ( zeroBSCRM_is_customertags_page() ) { return true; } // for now we count co's as here: if ( zeroBSCRM_is_company_list_page() ) { return true; } if ( zeroBSCRM_is_company_new_page() ) { return true; } if ( zeroBSCRM_is_company_edit_page() ) { return true; } if ( zeroBSCRM_is_companytags_page() ) { return true; } return false; } function zeroBSCRM_is_contact_list_page() { global $zbs; return zeroBS_isPage( array( 'admin.php' ), false, array( $zbs->slugs['managecontacts'] ) ); } function zeroBSCRM_is_existingcustomer_edit_page() { $isPage = zeroBS_isPage( array( 'post.php' ), array( 'zerobs_customer' ) ); // 'post-new.php' if ( $isPage ) { return true; } elseif ( zeroBS_hasGETParamsWithValues( array( 'admin.php' ), array( 'page' => 'zbs-add-edit', 'action' => 'edit', ) ) ) { if ( isset( $_GET['zbsid'] ) ) { return true; } } return false; } function zeroBSCRM_is_customer_edit_page() { $isPage = zeroBS_isPage( array( 'post.php' ), array( 'zerobs_customer' ) ); // 'post-new.php' if ( $isPage ) { return true; } else { // return zeroBS_hasGETParamsWithValues(array( 'admin.php' ),array('page'=>'zbs-add-edit','action'=>'edit')); // either has zbstype = contact, or no zbstype (as is default) if ( ( zeroBS_hasGETParamsWithValues( array( 'admin.php' ), array( 'page' => 'zbs-add-edit', 'action' => 'edit', 'zbstype' => 'contact', ) ) ) || ( zeroBS_hasGETParamsWithValues( array( 'admin.php' ), array( 'page' => 'zbs-add-edit', 'action' => 'edit', ), array( 'zbstype' ) ) ) ) { return true; } } return false; } function zeroBSCRM_is_customer_view_page() { // DAL 2+ // return zeroBS_hasGETParamsWithValues(array( 'admin.php' ),array('page'=>'zbs-add-edit','action'=>'view')); // either has zbstype = contact, or no zbstype (as is default) if ( ( zeroBS_hasGETParamsWithValues( array( 'admin.php' ), array( 'page' => 'zbs-add-edit', 'action' => 'view', 'zbstype' => 'contact', ) ) ) || ( zeroBS_hasGETParamsWithValues( array( 'admin.php' ), array( 'page' => 'zbs-add-edit', 'action' => 'view', ), array( 'zbstype' ) ) ) ) { return true; } return false; } function zeroBSCRM_is_customer_new_page() { // DAL 2 support $isPage = zeroBS_isPage( array( 'post-new.php' ), array( 'zerobs_customer' ) ); // 'post-new.php' if ( $isPage ) { return true; } else { // either has zbstype = contact, or no zbstype (as is default) if ( ( zeroBS_hasGETParamsWithValues( array( 'admin.php' ), array( 'page' => 'zbs-add-edit', 'action' => 'edit', 'zbstype' => 'contact', ) ) ) || ( zeroBS_hasGETParamsWithValues( array( 'admin.php' ), array( 'page' => 'zbs-add-edit', 'action' => 'edit', ), array( 'zbstype' ) ) ) ) { if ( ! isset( $_GET['zbsid'] ) || $_GET['zbsid'] == -1 ) { return true; } } } return false; } function zeroBSCRM_is_customertags_page() { // DAL 2 support $isPage = zeroBS_isPage( array( 'edit-tags.php' ), array( 'zerobs_customer' ) ); if ( $isPage ) { return true; } else { global $zbs; return zeroBS_hasGETParamsWithValues( array( 'admin.php' ), array( 'page' => $zbs->slugs['tagmanager'], 'tagtype' => 'contact', ) ); } return false; } // ========= / CONTACTS ============================================= // ========= COMPANIES ============================================== function zeroBSCRM_is_company_list_page() { global $zbs; return zeroBS_isPage( array( 'admin.php' ), false, array( $zbs->slugs['managecompanies'] ) ); } function zeroBSCRM_is_company_view_page() { // either has zbstype = company, or no go if ( zeroBS_hasGETParamsWithValues( array( 'admin.php' ), array( 'page' => 'zbs-add-edit', 'action' => 'view', 'zbstype' => 'company', ) ) ) { return true; } return false; } function zeroBSCRM_is_company_new_page() { // <v3.0 if ( zeroBS_isPage( array( 'post-new.php' ), array( 'zerobs_company' ) ) ) { return true; } else { // v3.0 return zeroBSCRM_is_zbs_edit_page( 'company', true ); } } function zeroBSCRM_is_company_edit_page() { // <v3.0 if ( zeroBS_isPage( array( 'post.php' ), array( 'zerobs_company' ) ) ) { return true; } else { // v3.0 return zeroBSCRM_is_zbs_edit_page( 'company', false ); } } function zeroBSCRM_is_existingcompany_edit_page() { return zeroBSCRM_is_company_edit_page(); } function zeroBSCRM_is_companytags_page() { // DAL 2 support $isPage = zeroBS_isPage( array( 'edit-tags.php' ), array( 'zerobs_company' ) ); if ( $isPage ) { return true; } else { global $zbs; return zeroBS_hasGETParamsWithValues( array( 'admin.php' ), array( 'page' => $zbs->slugs['tagmanager'], 'tagtype' => 'company', ) ); } return false; } // ========= / COMPANIES =============================================== // ========= TRANSACTIONS ============================================== // generic check for any page concerning 'trans' function zeroBSCRM_isAnyTransactionPage() { if ( zeroBSCRM_is_transaction_list_page() ) { return true; } if ( zeroBSCRM_is_transaction_new_page() ) { return true; } if ( zeroBSCRM_is_transaction_edit_page() ) { return true; } if ( zeroBSCRM_is_transactiontags_page() ) { return true; } return false; } function zeroBSCRM_is_transaction_list_page() { global $zbs; return zeroBS_isPage( array( 'admin.php' ), false, array( $zbs->slugs['managetransactions'] ) ); } function zeroBSCRM_is_transaction_new_page() { // <v3.0 if ( zeroBS_isPage( array( 'post-new.php' ), array( 'zerobs_transaction' ) ) ) { return true; } else { // v3.0 return zeroBSCRM_is_zbs_edit_page( 'transaction', true ); } } function zeroBSCRM_is_transaction_edit_page() { // <v3.0 if ( zeroBS_isPage( array( 'post.php' ), array( 'zerobs_transaction' ) ) ) { return true; } else { // v3.0 return zeroBSCRM_is_zbs_edit_page( 'transaction', false ); } } function zeroBSCRM_is_transactiontags_page() { // DAL 2 support $isPage = zeroBS_isPage( array( 'edit-tags.php' ), array( 'zerobs_transaction' ) ); if ( $isPage ) { return true; } else { global $zbs; return zeroBS_hasGETParamsWithValues( array( 'admin.php' ), array( 'page' => $zbs->slugs['tagmanager'], 'tagtype' => 'transaction', ) ); } return false; } // ========= / TRANSACTIONS =============================================== // ========= INVOICES ===================================================== // generic check for any page concerning 'invs' function zeroBSCRM_isAnyInvoicePage() { if ( zeroBSCRM_is_invoice_list_page() ) { return true; } if ( zeroBSCRM_is_invoice_new_page() ) { return true; } if ( zeroBSCRM_is_invoice_edit_page() ) { return true; } return false; } function zeroBSCRM_is_invoice_list_page() { global $zbs; return zeroBS_isPage( array( 'admin.php' ), false, array( $zbs->slugs['manageinvoices'] ) ); } function zeroBSCRM_is_invoice_new_page() { // <v3.0 if ( zeroBS_isPage( array( 'post-new.php' ), array( 'zerobs_invoice' ) ) ) { return true; } else { // v3.0 return zeroBSCRM_is_zbs_edit_page( 'invoice', true ); } } function zeroBSCRM_is_invoice_edit_page() { // <v3.0 if ( zeroBS_isPage( array( 'post.php' ), array( 'zerobs_invoice' ) ) ) { return true; } else { // v3.0 return zeroBSCRM_is_zbs_edit_page( 'invoice', false ); } } function zeroBSCRM_is_invoicetags_page() { // v3.0+ only global $zbs; if ( $zbs->isDAL3() ) { return zeroBS_hasGETParamsWithValues( array( 'admin.php' ), array( 'page' => $zbs->slugs['tagmanager'], 'tagtype' => 'invoice', ) ); } return false; } // ========= / INVOICES ================================================= // ========= QUOTES ===================================================== // generic check for any page concerning 'quotes' function zeroBSCRM_isAnyQuotePage() { if ( zeroBSCRM_is_quote_list_page() ) { return true; } if ( zeroBSCRM_is_quo_new_page() ) { return true; } if ( zeroBSCRM_is_quo_edit_page() ) { return true; } if ( zeroBSCRM_is_quotetemplate_new_page() ) { return true; } if ( zeroBSCRM_is_quotetemplate_edit_page() ) { return true; } return false; } function zeroBSCRM_is_quote_list_page() { global $zbs; return zeroBS_isPage( array( 'admin.php' ), false, array( $zbs->slugs['managequotes'] ) ); } function zeroBSCRM_is_quo_new_page() { // <v3.0 if ( zeroBS_isPage( array( 'post-new.php' ), array( 'zerobs_quote' ) ) ) { return true; } else { // v3.0 return zeroBSCRM_is_zbs_edit_page( 'quote', true ); } } function zeroBSCRM_is_quo_edit_page() { // <v3.0 if ( zeroBS_isPage( array( 'post.php' ), array( 'zerobs_quote' ) ) ) { return true; } else { // v3.0 return zeroBSCRM_is_zbs_edit_page( 'quote', false ); } } function zeroBSCRM_is_quotetags_page() { // v3.0+ only global $zbs; if ( $zbs->isDAL3() ) { return zeroBS_hasGETParamsWithValues( array( 'admin.php' ), array( 'page' => $zbs->slugs['tagmanager'], 'tagtype' => 'quote', ) ); } return false; } // ========= / QUOTES ================================================= // ========= QUOTE TEMPLATES ========================================== // backward compat function zeroBSCRM_is_quotem_new_page() { zeroBSCRM_DEPRECATEDMSG( 'zeroBSCRM_is_quotem_new_page was deprecated in v4.10, please use zeroBSCRM_is_quotetemplate_new_page()' ); return zeroBSCRM_is_quotetemplate_new_page(); } function zeroBSCRM_is_quotem_edit_page() { zeroBSCRM_DEPRECATEDMSG( 'zeroBSCRM_is_quotem_edit_page was deprecated in v4.10, please use zeroBSCRM_is_quotetemplate_edit_page()' ); return zeroBSCRM_is_quotetemplate_edit_page(); } function zeroBSCRM_is_quotetemplate_new_page() { // <v3.0 if ( zeroBS_isPage( array( 'post-new.php' ), array( 'zerobs_quo_template' ) ) ) { return true; } else { // v3.0 return zeroBSCRM_is_zbs_edit_page( 'quotetemplate', true ); } } function zeroBSCRM_is_quotetemplate_edit_page() { // <v3.0 if ( zeroBS_isPage( array( 'post.php' ), array( 'zerobs_quo_template' ) ) ) { return true; } else { // v3.0 return zeroBSCRM_is_zbs_edit_page( 'quotetemplate', false ); } } // ========= / QUOTE TEMPLATES ========================================= // ========= TASKS ==================================================== // generic check for any page concerning tasks function zeroBSCRM_isAnyTaskPage() { if ( zeroBSCRM_is_task_new_page() ) { return true; } if ( zeroBSCRM_is_task_edit_page() ) { return true; } if ( zeroBSCRM_is_task_calendar_page() ) { return true; } if ( zeroBSCRM_is_task_list_page() ) { return true; } if ( zeroBSCRM_is_tasktags_page() ) { return true; } return false; } function zeroBSCRM_is_task_new_page() { // <v3.0 if ( zeroBS_isPage( array( 'post-new.php' ), array( 'zerobs_event' ) ) ) { return true; } else { // v3.0 return zeroBSCRM_is_zbs_edit_page( 'event', true ); } } function zeroBSCRM_is_task_edit_page() { // <v3.0 if ( zeroBS_isPage( array( 'post.php' ), array( 'zerobs_event' ) ) ) { return true; } else { // v3.0 return zeroBSCRM_is_zbs_edit_page( 'event', false ); } } function zeroBSCRM_is_task_calendar_page() { global $zbs; return zeroBS_isPage( array( 'admin.php' ), false, array( $zbs->slugs['manage-tasks'] ) ); } function zeroBSCRM_is_task_list_page() { global $zbs; return zeroBS_isPage( array( 'admin.php' ), false, array( $zbs->slugs['manage-tasks-list'] ) ); } function zeroBSCRM_is_tasktags_page() { // v3.0+ only global $zbs; if ( $zbs->isDAL3() ) { return zeroBS_hasGETParamsWithValues( array( 'admin.php' ), array( 'page' => $zbs->slugs['tagmanager'], 'tagtype' => 'event', ) ); } return false; } // ========= / TASKS ================================================= // ========= FORMS ==================================================== // generic check for any page concerning 'forms' function zeroBSCRM_isAnyFormPage() { if ( zeroBSCRM_is_form_new_page() ) { return true; } if ( zeroBSCRM_is_form_edit_page() ) { return true; } if ( zeroBSCRM_is_form_list_page() ) { return true; } if ( zeroBSCRM_is_formtags_page() ) { return true; } if ( zeroBSCRM_is_task_list_page() ) { return true; } if ( zeroBSCRM_is_tasktags_page() ) { return true; } return false; } function zeroBSCRM_is_form_new_page() { // <v3.0 if ( zeroBS_isPage( array( 'post-new.php' ), array( 'zerobs_form' ) ) ) { return true; } else { // v3.0 return zeroBSCRM_is_zbs_edit_page( 'form', true ); } } function zeroBSCRM_is_form_edit_page() { // <v3.0 if ( zeroBS_isPage( array( 'post.php' ), array( 'zerobs_form' ) ) ) { return true; } else { // v3.0 return zeroBSCRM_is_zbs_edit_page( 'form', false ); } } function zeroBSCRM_is_form_list_page() { return zeroBS_isPage( array( 'edit.php' ), array( 'zerobs_form' ) ); } function zeroBSCRM_is_formtags_page() { // v3.0+ only global $zbs; if ( $zbs->isDAL3() ) { return zeroBS_hasGETParamsWithValues( array( 'admin.php' ), array( 'page' => $zbs->slugs['tagmanager'], 'tagtype' => 'form', ) ); } return false; } // ========= / FORMS ================================================= // ========= SEGMENTS ================================================= function zeroBSCRM_is_segment_edit_page() { // v3.0 return zeroBSCRM_is_zbs_edit_page( 'segment', true ); } function zeroBSCRM_is_segment_new_page() { // v3.0 return zeroBSCRM_is_zbs_edit_page( 'segment', false ); } // ========= / SEGMENTS ================================================= function zeroBSCRM_is_profile_page() { global $zbs; return zeroBS_isPage( array( 'admin.php' ), false, array( $zbs->slugs['your-profile'] ) ); } function jpcrm_is_settings_page() { global $zbs; return zeroBS_isPage( array( 'admin.php' ), false, array( $zbs->slugs['settings'] ) ); } /** * Checks if a page is designated as a full-width page in Jetpack CRM. * * @param string $page_name The name of the page to check (usually this is the http `page` GET param). * * @return bool Whether the page should be displayed in full width. */ function jpcrm_is_full_width_page( $page_name ) { global $zbs; if ( $zbs->settings->get( 'showfullwidthforlisting' ) !== 1 ) { return false; } $full_width_pages = array( 'tag-manager', 'manage-customers', 'manage-companies', 'manage-segments', 'manage-quotes', 'manage-invoices', 'manage-quote-templates', 'manage-transactions', 'manage-tasks', 'manage-forms', ); $full_width_pages = apply_filters( 'jetpack_crm_full_width_pages', $full_width_pages ); return in_array( $page_name, $full_width_pages, true ); }
projects/plugins/crm/includes/ZeroBSCRM.Edit.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V2.52+ * * Copyright 2020 Automattic * * Date: 26/02/18 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ class zeroBSCRM_Edit{ private $objID = false; private $obj = false; private $objTypeID = false; // ZBS_TYPE_CONTACT - v3.0+ // following now FILLED OUT by objTypeID above, v3.0+ private $objType = false; // 'contact' private $singular = false; private $plural = false; // renamed listViewSlug v3.0+ private $postPage = false; private $listViewSlug = false; private $langLabels = false; private $bulkActions = false; private $sortables = false; private $unsortables = false; private $extraBoxes = ''; private $isGhostRecord = false; private $isNewRecord = false; // permissions private $has_permissions_to_edit = false; function __construct($args=array()) { #} =========== LOAD ARGS ============== $defaultArgs = array( 'objID' => false, 'objTypeID' => false, //5 // these are now retrieved from DAL centralised vars by objTypeID above, v3.0+ // ... unless hard typed here. 'objType' => false, //transaction 'singular' => false, //Transaction 'plural' => false, //Transactions 'listViewSlug' => false, //manage-transactions 'langLabels' => array( ), 'extraBoxes' => '' // html for extra boxes e.g. upsells :) ); foreach ($defaultArgs as $argK => $argV){ $this->$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $this->$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$this->$argK = $newData;} else { $this->$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= // NOTE: here these vars are passed like: // $this->objID // .. NOT // $objID global $zbs; // we load from DAL defaults, if objTypeID passed (overriding anything passed, if empty/false) if (isset($this->objTypeID)){ //$zbs->isDAL3() && $objTypeID = (int)$this->objTypeID; if ($objTypeID > 0){ // obj type (contact) $objTypeStr = $zbs->DAL->objTypeKey($objTypeID); if ((!isset($this->objType) || $this->objType == false) && !empty($objTypeStr)) $this->objType = $objTypeStr; // singular $objSingular = $zbs->DAL->typeStr($objTypeID); if ((!isset($this->singular) || $this->singular == false) && !empty($objSingular)) $this->singular = $objSingular; // plural $objPlural = $zbs->DAL->typeStr($objTypeID,true); if ((!isset($this->plural) || $this->plural == false) && !empty($objPlural)) $this->plural = $objPlural; // listViewSlug $objSlug = $zbs->DAL->listViewSlugFromObjID($objTypeID); if ((!isset($this->listViewSlug) || $this->listViewSlug == false) && !empty($objSlug)) $this->listViewSlug = $objSlug; } //echo 'loading from '.$this->objTypeID.':<pre>'.print_r(array($objTypeStr,$objSingular,$objPlural,$objSlug),1).'</pre>'; exit(); } else $this->isNewRecord = true; // if objid - load $post $this->loadObject(); // Ghost? if ($this->objID !== -1 && !$this->isNewRecord && isset($this->objTypeID) && !is_array($this->obj)) $this->isGhostRecord = true; // anything to save? $this->catchPost(); // include any 'post learn menu' code add_action( 'zerobscrm-subtop-menu', array( $this, 'post_learn_menu_output' ) ); } // automatically, generically, loads the single obj public function loadObject(){ // if objid - load $post if ( isset( $this->objID ) && !empty( $this->objID ) && $this->objID > 0 ) { global $zbs; if ( $this->objTypeID > 0 ){ // got permissions? if ( zeroBSCRM_permsObjType( $this->objTypeID ) ){ // this gets $zbs->DAL->contacts->getSingle() $this->obj = $zbs->DAL->getObjectLayerByType($this->objTypeID)->getSingle($this->objID); // has permissions $this->has_permissions_to_edit = true; } } } } public function catchPost(){ // If post, fire do_action if (isset($_POST['zbs-edit-form-master']) && $_POST['zbs-edit-form-master'] == $this->objType){ // make sure we have perms to save if ($this->preChecks()) { // fire it do_action('zerobs_save_'.$this->objType, $this->objID, $this->obj); // after catching post, we need to reload data :) (as may be changed) $this->loadObject(); } } } // check ownership, access etc. public function preChecks(){ global $zbs; // only do this stuff v3.0+ if ($zbs->isDAL3()){ $is_malformed_obj = false; if (is_array($this->obj) && isset($this->obj['owner'])){ $objOwner = (int)$this->obj['owner']; } else { // if $this->obj is not an array, somehow it's not been loaded properly (probably perms) // get owner info anyway $is_malformed_obj = true; $objOwner = $zbs->DAL->getObjectOwner(array( 'objID' => $this->objID, 'objTypeID' => $this->objTypeID )); } // get current user $currentUserID = get_current_user_id(); if ($objOwner > 0 && $objOwner != $currentUserID){ // not current user // does user have perms to edit? $canEditAllContacts = current_user_can('admin_zerobs_customers') && $zbs->settings->get('perusercustomers') == 0; $canGiveOwnership = $zbs->settings->get('usercangiveownership') == 1; $canChangeOwner = ($canGiveOwnership || current_user_can('administrator') || $canEditAllContacts); if (!$canChangeOwner){ // owners can't be changed with user's perms, so denied msg $this->preCheckFail( sprintf( __( 'You do not have permission to edit this %s.', 'zero-bs-crm' ), $zbs->DAL->typeStr( $this->objTypeID ) ) ); return false; } if ( !$this->has_permissions_to_edit ){ // user does not have a role which can edit this object type $this->preCheckFail( sprintf( __( 'You do not have permission to edit this %s.', 'zero-bs-crm' ), $zbs->DAL->typeStr( $this->objTypeID ) ) ); return false; } if ( $is_malformed_obj ) { // not a perms issue, so show general error $this->preCheckFail( sprintf( __( 'There was an error loading this %s.', 'zero-bs-crm' ), $zbs->DAL->typeStr( $this->objTypeID ) ) ); return false; } } } //load if is legit return true; } public function preCheckFail($msg=''){ echo '<div id="zbs-obj-edit-precheck-fail" class="ui grid"><div class="row"><div class="two wide column"></div><div class="twelve wide column">'; echo zeroBSCRM_UI2_messageHTML('warning',$msg,'','disabled warning sign','failRetrieving'); echo '</div></div>'; // grim quick hack to hide save button echo '<style>#zbs-edit-save{display:none}</style>'; } /* * Code added to this function will be called just after the learn menu is output * (where we're on an edit page) */ public function post_learn_menu_output(){ // put screen options out zeroBSCRM_screenOptionsPanel(); } public function drawEditView(){ // run pre-checks which verify ownership etc. $okayToDraw = $this->preChecks(); // draw if okay :) if ($okayToDraw) $this->drawEditViewHTML(); } public function drawEditViewHTML(){ if (empty($this->objType) || empty($this->listViewSlug) || empty($this->singular) || empty($this->plural)){ echo zeroBSCRM_UI2_messageHTML('warning','Error Retrieving '.$this->singular,'There has been a problem retrieving your '.$this->singular.', if this issue persists, please contact support.','disabled warning sign','zbsCantLoadData'); return false; } // catch id's passed where no contact exists for them. if ($this->isGhostRecord){ // brutal hide, then msg #ghostrecord ?><style type="text/css">#zbs-edit-save, #zbs-nav-view, #zbs-nav-prev, #zbs-nav-next { display:none; }</style> <div id="zbs-edit-warnings-wrap"><?php echo zeroBSCRM_UI2_messageHTML('warning','Error Retrieving '.$this->singular,'There does not appear to be a '.$this->singular.' with this ID.','disabled warning sign','zbsCantLoadData'); ?></div><?php return false; } // catch if is new record + hide zbs-nav-view if ($this->isNewRecord){ // just hide button via css. Should just stop this via learn in time ?><style type="text/css">#zbs-nav-view { display:none; }</style><?php } global $zbs; // run pre-checks which verify ownership etc. $this->preChecks(); ?><div id="zbs-edit-master-wrap"><form method="post" id="zbs-edit-form" enctype="multipart/form-data"><input type="hidden" name="zbs-edit-form-master" value="<?php echo esc_attr( $this->objType ); ?>" /> <div id="zbs-edit-warnings-wrap"> <?php #} Pre-loaded msgs, because I wrote the helpers in php first... should move helpers to js and fly these echo zeroBSCRM_UI2_messageHTML('warning hidden','Error Retrieving '.$this->plural,'There has been a problem retrieving your '.$this->singular.', if this issue persists, please ask your administrator to reach out to Jetpack CRM.','disabled warning sign','zbsCantLoadData'); echo zeroBSCRM_UI2_messageHTML('warning hidden','Error Retrieving '.$this->singular,'There has been a problem retrieving your '.$this->singular.', if this issue persists, please ask your administrator to reach out to Jetpack CRM.','disabled warning sign','zbsCantLoadDataSingle'); ?> </div> <!-- main view: list + sidebar --> <div id="zbs-edit-wrap" class="ui divided grid <?php echo 'zbs-edit-wrap-'. esc_attr( $this->objType ); ?>"> <?php if (count($zbs->pageMessages) > 0){ #} Updated Msgs // was doing like this, but need control over styling // do_action( 'zerobs_updatemsg_contact'); // so for now just using global :) echo '<div class="row" style="padding-bottom: 0 !important;" id="zbs-edit-notification-row"><div class="sixteen wide column" id="zbs-edit-notification-wrap">'; foreach ($zbs->pageMessages as $msg){ // for now these can be any html :) echo $msg; } echo '</div></div>'; } ?> <div class="row"> <!-- record list --> <div class="twelve wide column" id="zbs-edit-table-wrap"> <?php #} Main Metaboxes zeroBSCRM_do_meta_boxes( 'zbs-add-edit-'.$this->objType.'-edit', 'normal', $this->obj ); ?> </div> <!-- side bar --> <div class="four wide column" id="zbs-edit-sidebar-wrap"> <?php #} Sidebar metaboxes zeroBSCRM_do_meta_boxes( 'zbs-add-edit-'.$this->objType.'-edit', 'side', $this->obj ); ?> <?php ##WLREMOVE ?> <?php echo $this->extraBoxes; ?> <?php ##/WLREMOVE ?> </div> </div> <!-- could use this for mobile variant?) <div class="two column mobile only row" style="display:none"></div> --> </div> <!-- / mainlistview wrap --> </form></div> <script type="text/javascript"> jQuery(function($){ console.log("======= EDIT VIEW UI ========="); jQuery('.show-more-tags').on("click",function(e){ jQuery('.more-tags').show(); jQuery(this).hide(); }); }); // General options for edit page var zbsEditSettings = { objid: <?php echo esc_js( $this->objID ); ?>, objdbname: '<?php echo esc_js( $this->objType ); ?>', nonce: '<?php echo esc_js( wp_create_nonce( 'edit-nonce-'. $this->objType ) ); ?>' }; var zbsDrawEditViewBlocker = false; var zbsDrawEditAJAXBlocker = false; <?php // these are all legacy, move over to zeroBSCRMJS_obj_editLink in global js: ?> var zbsObjectViewLinkPrefixCustomer = '<?php echo jpcrm_esc_link( 'view', -1, 'zerobs_customer', true ); ?>'; var zbsObjectEditLinkPrefixCustomer = '<?php echo jpcrm_esc_link( 'edit', -1, 'zerobs_customer', true ); ?>'; var zbsObjectViewLinkPrefixCompany = '<?php echo jpcrm_esc_link( 'view', -1, 'zerobs_company', true ); ?>'; var zbsListViewLink = '<?php echo jpcrm_esc_link( $this->listViewSlug ); ?>'; var zbsClick2CallType = parseInt('<?php echo esc_html( zeroBSCRM_getSetting('clicktocalltype') ); ?>'); var zbsEditViewLangLabels = { 'today': '<?php echo esc_html( zeroBSCRM_slashOut(__('Today',"zero-bs-crm")) ); ?>', 'view': '<?php echo esc_html( zeroBSCRM_slashOut(__('View',"zero-bs-crm")) ); ?>', 'contact': '<?php echo esc_html( zeroBSCRM_slashOut(__('Contact',"zero-bs-crm")) ); ?>', 'company': '<?php echo esc_html( zeroBSCRM_slashOut(jpcrm_label_company()) ); ?>', <?php $labelCount = 0; if (count($this->langLabels) > 0) foreach ($this->langLabels as $labelK => $labelV){ if ($labelCount > 0) echo ','; echo esc_html( $labelK ).":'". esc_html( zeroBSCRM_slashOut($labelV,true) )."'"; $labelCount++; } ?> }; <?php #} Nonce for AJAX echo "var zbscrmjs_secToken = '" . esc_js( wp_create_nonce( 'zbscrmjs-ajax-nonce' ) ) . "';"; ?></script><?php } // /draw func } // class
projects/plugins/crm/includes/ZeroBSCRM.DAL3.Obj.Invoices.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V3.0+ * * Copyright 2020 Automattic * * Date: 14/01/19 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ use Automattic\Jetpack\CRM\Event_Manager\Events_Manager; /** * ZBS DAL >> Invoices * * @author Woody Hayday <hello@jetpackcrm.com> * @version 2.0 * @access public * @see https://jetpackcrm.com/kb */ class zbsDAL_invoices extends zbsDAL_ObjectLayer { protected $objectType = ZBS_TYPE_INVOICE; protected $objectDBPrefix = 'zbsi_'; protected $include_in_templating = true; protected $objectModel = array( /* NOTE: $zbsCustomerInvoiceFields Removed as of v3.0, invoice builder is very custom, UI wise, .. and as the model can deal with saving + custom fields WITHOUT the global, there's no need (whereas other objects input views are directed by these globals, Invs is separate, way MS made it) OLD hard-typed: $zbsCustomerInvoiceFields = array( 'status' => array( 'select', 'Status','',array( 'Draft', 'Unpaid', 'Paid', 'Overdue', 'Deleted' ), 'essential' => true ), # NOTE! 'no' should now be ignored, (deprecated), moved to seperate meta 'zbsid' // NOTE WH: when I hit this with column manager, loads didn't need to be shown // so plz leave ,'nocolumn'=>true in tact :) //'name' => array('text','Quote title','e.g. Chimney Rebuild'), 'no' => array('text',__('Invoice number',"zero-bs-crm"),'e.g. 123456', 'essential' => true), #} No is ignored by edit routines :) 'val'=> array('hidden',__('Invoice value',"zero-bs-crm"),'e.g. 500.00', 'essential' => true), 'date' => array('date',__('Invoice date',"zero-bs-crm"),'', 'essential' => true), 'notes' => array('textarea',__('Notes',"zero-bs-crm"),'','nocolumn'=>true), 'ref' => array('text', __('Reference number',"zero-bs-crm"), 'e.g. Ref-123'), 'due' => array('text', __('Invoice due',"zero-bs-crm"), ''), 'logo' => array('text', __('logo url',"zero-bs-crm"), 'e.g. URL','nocolumn'=>true), 'bill' => array('text',__('invoice to',"zero-bs-crm"), 'e.g. mike@epicplugins.com','nocolumn'=>true), 'ccbill' => array('text',__('copy invoice to',"zero-bs-crm"), 'e.g. you@you.com','nocolumn'=>true), ); */ // ID 'ID' => array('fieldname' => 'ID', 'format' => 'int'), // site + team generics 'zbs_site' => array('fieldname' => 'zbs_site', 'format' => 'int'), 'zbs_team' => array('fieldname' => 'zbs_team', 'format' => 'int'), 'zbs_owner' => array('fieldname' => 'zbs_owner', 'format' => 'int'), // other fields 'id_override' => array( 'fieldname' => 'zbsi_id_override', 'format' => 'str', 'force_unique' => true, // must be unique. This is required and breaking if true 'can_be_blank' => true, // can be blank (if not unique) 'max_len' => 128 ), 'parent' => array('fieldname' => 'zbsi_parent', 'format' => 'int'), 'status' => array( 'fieldname' => 'zbsi_status', 'format' => 'str', 'max_len' => 50 ), 'hash' => array('fieldname' => 'zbsi_hash', 'format' => 'str'), 'pdf_template' => array('fieldname' => 'zbsi_pdf_template', 'format' => 'str'), 'portal_template' => array('fieldname' => 'zbsi_portal_template', 'format' => 'str'), 'email_template' => array('fieldname' => 'zbsi_email_template', 'format' => 'str'), 'invoice_frequency' => array('fieldname' => 'zbsi_invoice_frequency', 'format' => 'int'), 'currency' => array('fieldname' => 'zbsi_currency', 'format' => 'curr'), 'pay_via' => array('fieldname' => 'zbsi_pay_via', 'format' => 'int'), /* -1 = bacs/can'tpay online 0 = default/no setting 1 = paypal 2 = stripe 3 = worldpay */ 'logo_url' => array( 'fieldname' => 'zbsi_logo_url', 'format' => 'str', 'max_len' => 300 ), 'address_to_objtype' => array('fieldname' => 'zbsi_address_to_objtype', 'format' => 'int'), 'addressed_from' => array( 'fieldname' => 'zbsi_addressed_from', 'format' => 'str', 'max_len' => 600 ), 'addressed_to' => array( 'fieldname' => 'zbsi_addressed_to', 'format' => 'str', 'max_len' => 600 ), 'allow_partial' => array('fieldname' => 'zbsi_allow_partial', 'format' => 'bool'), 'allow_tip' => array('fieldname' => 'zbsi_allow_tip', 'format' => 'bool'), 'send_attachments' => array('fieldname' => 'zbsi_send_attachments', 'format' => 'bool'), // note, from 4.0.9 we removed this from the front-end ui as we now show a modal option pre-send allowing user to chose which pdf's to attach 'hours_or_quantity' => array('fieldname' => 'zbsi_hours_or_quantity', 'format' => 'bool'), 'date' => array('fieldname' => 'zbsi_date', 'format' => 'uts'), 'due_date' => array('fieldname' => 'zbsi_due_date', 'format' => 'uts'), 'paid_date' => array('fieldname' => 'zbsi_paid_date', 'format' => 'uts'), 'hash_viewed' => array('fieldname' => 'zbsi_hash_viewed', 'format' => 'uts'), 'hash_viewed_count' => array('fieldname' => 'zbsi_hash_viewed_count', 'format' => 'int'), 'portal_viewed' => array('fieldname' => 'zbsi_portal_viewed', 'format' => 'uts'), 'portal_viewed_count' => array('fieldname' => 'zbsi_portal_viewed_count', 'format' => 'int'), 'net' => array('fieldname' => 'zbsi_net', 'format' => 'decimal'), 'discount' => array('fieldname' => 'zbsi_discount', 'format' => 'decimal'), 'discount_type' => array('fieldname' => 'zbsi_discount_type', 'format' => 'str'), 'shipping' => array('fieldname' => 'zbsi_shipping', 'format' => 'decimal'), 'shipping_taxes' => array('fieldname' => 'zbsi_shipping_taxes', 'format' => 'str'), 'shipping_tax' => array('fieldname' => 'zbsi_shipping_tax', 'format' => 'decimal'), 'taxes' => array('fieldname' => 'zbsi_taxes', 'format' => 'str'), 'tax' => array('fieldname' => 'zbsi_tax', 'format' => 'decimal'), 'total' => array('fieldname' => 'zbsi_total', 'format' => 'decimal'), 'created' => array('fieldname' => 'zbsi_created', 'format' => 'uts'), 'lastupdated' => array('fieldname' => 'zbsi_lastupdated', 'format' => 'uts'), ); // hardtyped list of types this object type is commonly linked to protected $linkedToObjectTypes = array( ZBS_TYPE_CONTACT, ZBS_TYPE_COMPANY ); /** * Events_Manager instance. Manages CRM events. * * @since 6.2.0 * * @var Events_Manager */ private $events_manager; function __construct($args=array()) { #} =========== LOAD ARGS ============== $defaultArgs = array( //'tag' => false, ); foreach ($defaultArgs as $argK => $argV){ $this->$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $this->$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$this->$argK = $newData;} else { $this->$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= $this->events_manager = new Events_Manager(); add_filter( 'jpcrm_listview_filters', array( $this, 'add_listview_filters' ) ); } /** * Adds items to listview filter using `jpcrm_listview_filters` hook. * * @param array $listview_filters Listview filters. */ public function add_listview_filters( $listview_filters ) { global $zbs; // Add statuses if enabled. if ( $zbs->settings->get( 'filtersfromstatus' ) === 1 ) { $statuses = array( 'draft' => __( 'Draft', 'zero-bs-crm' ), 'unpaid' => __( 'Unpaid', 'zero-bs-crm' ), 'paid' => __( 'Paid', 'zero-bs-crm' ), 'overdue' => __( 'Overdue', 'zero-bs-crm' ), 'deleted' => __( 'Deleted', 'zero-bs-crm' ), ); foreach ( $statuses as $status_slug => $status_label ) { $listview_filters[ ZBS_TYPE_INVOICE ]['status'][ 'status_' . $status_slug ] = $status_label; } } return $listview_filters; } // =============================================================================== // =========== INVOICE ======================================================= // generic get Company (by ID) // Super simplistic wrapper used by edit page etc. (generically called via dal->contacts->getSingle etc.) public function getSingle($ID=-1){ return $this->getInvoice($ID); } // generic get (by ID list) // Super simplistic wrapper used by MVP Export v3.0 public function getIDList($IDs=false){ return $this->getInvoices(array( 'inArr' => $IDs, 'withOwner' => true, 'withAssigned' => true, 'page' => -1, 'perPage' => -1 )); } // generic get (EVERYTHING) // expect heavy load! public function getAll($IDs=false){ return $this->getInvoices(array( 'withOwner' => true, 'withAssigned' => true, 'sortByField' => 'ID', 'sortOrder' => 'ASC', 'page' => -1, 'perPage' => -1, )); } // generic get count of (EVERYTHING) public function getFullCount(){ return $this->getInvoices(array( 'count' => true, 'page' => -1, 'perPage' => -1, )); } /** * returns full invoice line +- details * * @param int id invoice id * @param array $args Associative array of arguments * * @return array invoice object */ public function getInvoice($id=-1,$args=array()){ global $zbs; #} =========== LOAD ARGS ============== $defaultArgs = array( // if theset wo passed, will search based on these 'idOverride' => false, // directly checks 1:1 match id_override 'externalSource' => false, 'externalSourceUID' => false, 'hash' => false, // with what? 'withLineItems' => true, 'withCustomFields' => true, 'withTransactions' => false, // gets trans associated with inv as well 'withAssigned' => false, // return ['contact'] & ['company'] objs if has link 'withTags' => false, 'withOwner' => false, 'withFiles' => false, 'withTotals' => false, // uses $this->generateTotalsTable to also calc discount + taxes on fly // permissions 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_INVOICE), // this'll let you not-check the owner of obj // returns scalar ID of line 'onlyID' => false, 'fields' => false // false = *, array = fieldnames ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} Check ID $id = (int)$id; if ( (!empty($id) && $id > 0) || (!empty($email)) || (!empty($hash)) || (!empty($externalSource) && !empty($externalSourceUID)) ){ global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); $extraSelect = ''; #} ============= PRE-QUERY ============ #} Custom Fields if ($withCustomFields && !$onlyID){ #} Retrieve any cf $custFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_INVOICE)); #} Cycle through + build into query if (is_array($custFields)) foreach ($custFields as $cK => $cF){ // add as subquery $extraSelect .= ',(SELECT zbscf_objval FROM '.$ZBSCRM_t['customfields']." WHERE zbscf_objid = invoice.ID AND zbscf_objkey = %s AND zbscf_objtype = %d LIMIT 1) '".$cK."'"; // add params $params[] = $cK; $params[] = ZBS_TYPE_INVOICE; } } $selector = 'invoice.*'; if (isset($fields) && is_array($fields)) { $selector = ''; // always needs id, so add if not present if (!in_array('ID',$fields)) $selector = 'invoice.ID'; foreach ($fields as $f) { if (!empty($selector)) $selector .= ','; $selector .= 'invoice.'.$f; } } else if ($onlyID){ $selector = 'invoice.ID'; } #} ============ / PRE-QUERY =========== #} Build query $query = "SELECT ".$selector.$extraSelect." FROM ".$ZBSCRM_t['invoices'].' as invoice'; #} ============= WHERE ================ if (!empty($id) && $id > 0){ #} Add ID $wheres['ID'] = array('ID','=','%d',$id); } if (!empty($idOverride) && $idOverride > 0){ #} Add idOverride $wheres['idOverride'] = array('zbsi_id_override','=','%d',$idOverride); } /* 3.0.13 WH removed - individual getInvoice should not have searchPhrase. #} Add Search phrase if (!empty($searchPhrase)){ // search? - ALL THESE COLS should probs have index of FULLTEXT in db? $searchWheres = array(); $searchWheres['search_ref'] = array('zbsi_id_override','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_total'] = array('zbsi_total','LIKE','%s',$searchPhrase.'%'); // 3.0.13 - Added ability to search custom fields (optionally) $customFieldSearch = zeroBSCRM_getSetting('customfieldsearch'); if ($customFieldSearch == 1){ // simplistic add // NOTE: This IGNORES ownership of custom field lines. $searchWheres['search_customfields'] = array('ID','IN',"(SELECT zbscf_objid FROM ".$ZBSCRM_t['customfields']." WHERE zbscf_objval LIKE %s AND zbscf_objtype = ".ZBS_TYPE_INVOICE.")",'%'.$searchPhrase.'%'); } // This generates a query like 'zbsf_fname LIKE %s OR zbsf_lname LIKE %s', // which we then need to include as direct subquery (below) in main query :) $searchQueryArr = $this->buildWheres($searchWheres,'',array(),'OR',false); if (is_array($searchQueryArr) && isset($searchQueryArr['where']) && !empty($searchQueryArr['where'])){ // add it $wheres['direct'][] = array('('.$searchQueryArr['where'].')',$searchQueryArr['params']); } } */ if (!empty($hash)){ #} Add hash $wheres['hash'] = array('zbsi_hash','=','%s',$hash); } if (!empty($externalSource) && !empty($externalSourceUID)){ $wheres['extsourcecheck'] = array('ID','IN','(SELECT DISTINCT zbss_objid FROM '.$ZBSCRM_t['externalsources']." WHERE zbss_objtype = ".ZBS_TYPE_INVOICE." AND zbss_source = %s AND zbss_uid = %s)",array($externalSource,$externalSourceUID)); } #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort('ID','DESC') . $this->buildPaging(0,1); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_row($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret Results (ROW) if (isset($potentialRes) && isset($potentialRes->ID)) { #} Has results, tidy + return #} Only ID? return it directly if ($onlyID) return $potentialRes->ID; // tidy if (is_array($fields)){ // guesses fields based on table col names $res = $this->lazyTidyGeneric($potentialRes); } else { // proper tidy $res = $this->tidy_invoice($potentialRes,$withCustomFields); } if ($withLineItems){ // add all line item lines $res['lineitems'] = $this->DAL()->lineitems->getLineitems(array('associatedObjType'=>ZBS_TYPE_INVOICE,'associatedObjID'=>$potentialRes->ID,'perPage'=>1000,'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_LINEITEM))); } if ($withTransactions){ // add all transaction item lines $res['transactions'] = $this->DAL()->transactions->getTransactions(array('assignedInvoice'=>$potentialRes->ID,'perPage'=>1000,'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_TRANSACTION))); } if ($withAssigned){ /* This is for MULTIPLE (e.g. multi contact/companies assigned to an inv) // add all assigned contacts/companies $res['contacts'] = $this->DAL()->contacts->getContacts(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_INVOICE, 'hasObjIDLinkedTo'=>$resDataLine->ID, 'perPage'=>-1, 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); $res['companies'] = $this->DAL()->companies->getCompanies(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_INVOICE, 'hasObjIDLinkedTo'=>$resDataLine->ID, 'perPage'=>-1, 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_COMPANY))); .. but we use 1:1, at least now: */ // add all assigned contacts/companies $res['contact'] = $this->DAL()->contacts->getContacts(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_INVOICE, 'hasObjIDLinkedTo'=>$potentialRes->ID, 'page' => 0, 'perPage'=>1, // FORCES 1 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); $res['company'] = $this->DAL()->companies->getCompanies(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_INVOICE, 'hasObjIDLinkedTo'=>$potentialRes->ID, 'page' => 0, 'perPage'=>1, // FORCES 1 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_COMPANY))); } if ($withTags){ // add all tags lines $res['tags'] = $this->DAL()->getTagsForObjID(array('objtypeid'=>ZBS_TYPE_INVOICE,'objid'=>$potentialRes->ID)); } if ($withFiles){ $res['files'] = zeroBSCRM_files_getFiles('invoice',$potentialRes->ID); } if ($withTotals){ // add all tags lines $res['totals'] = $this->generateTotalsTable($res); } return $res; } } // / if ID return false; } /** * returns invoice detail lines * * @param array $args Associative array of arguments * * @return array of invoice lines */ public function getInvoices($args=array()){ global $zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( // Search/Filtering (leave as false to ignore) 'searchPhrase' => '', // searches id_override (ref) (not lineitems yet) 'inArr' => false, 'isTagged' => false, // 1x INT OR array(1,2,3) 'isNotTagged' => false, // 1x INT OR array(1,2,3) 'ownedBy' => false, 'externalSource' => false, // e.g. paypal 'olderThan' => false, // uts 'newerThan' => false, // uts 'hasStatus' => false, // Lead (this takes over from the quick filter post 19/6/18) 'otherStatus' => false, // status other than 'Lead' 'assignedContact' => false, // assigned to contact id (int) 'assignedCompany' => false, // assigned to company id (int) 'quickFilters' => false, // booo // returns 'count' => false, 'withLineItems' => true, 'withCustomFields' => true, 'withTransactions' => false, // gets trans associated with inv as well 'withTags' => false, 'withOwner' => false, 'withAssigned' => false, // return ['contact'] & ['company'] objs if has link 'withFiles' => false, 'onlyColumns' => false, // if passed (array('fname','lname')) will return only those columns (overwrites some other 'return' options). NOTE: only works for base fields (not custom fields) 'withTotals' => false, // uses $this->generateTotalsTable to also calc discount + taxes on fly 'sortByField' => 'ID', 'sortOrder' => 'ASC', 'page' => 0, // this is what page it is (gets * by for limit) 'perPage' => 100, 'whereCase' => 'AND', // DEFAULT = AND // permissions 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_INVOICE), // this'll let you not-check the owner of obj ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= global $ZBSCRM_t,$wpdb,$zbs; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); $joinQ = ''; $extraSelect = ''; #} ============= PRE-QUERY ============ #} Capitalise this $sortOrder = strtoupper($sortOrder); #} If just count, turn off any extra gumpf if ($count) { $withCustomFields = false; $withTags = false; $withTransactions = false; $withOwner = false; $withAssigned = false; } #} If onlyColumns, validate if ($onlyColumns){ #} onlyColumns build out a field arr if (is_array($onlyColumns) && count($onlyColumns) > 0){ $onlyColumnsFieldArr = array(); foreach ($onlyColumns as $col){ // find db col key from field key (e.g. fname => zbsc_fname) $dbCol = ''; if (isset($this->objectModel[$col]) && isset($this->objectModel[$col]['fieldname'])) $dbCol = $this->objectModel[$col]['fieldname']; if (!empty($dbCol)){ $onlyColumnsFieldArr[$dbCol] = $col; } } } // if legit cols: if (isset($onlyColumnsFieldArr) && is_array($onlyColumnsFieldArr) && count($onlyColumnsFieldArr) > 0){ $onlyColumns = true; // If onlyColumns, turn off extras $withCustomFields = false; $withTags = false; $withTransactions = false; $withOwner = false; $withAssigned = false; $withTotals = false; } else { // deny $onlyColumns = false; } } #} Custom Fields if ($withCustomFields){ #} Retrieve any cf $custFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_INVOICE)); #} Cycle through + build into query if (is_array($custFields)) foreach ($custFields as $cK => $cF){ // custom field (e.g. 'third name') it'll be passed here as 'third-name' // ... problem is mysql does not like that :) so we have to chage here: // in this case we prepend cf's with cf_ and we switch - for _ $cKey = 'cf_'.str_replace('-','_',$cK); // we also check the $sortByField in case that's the same cf if ($cK == $sortByField){ // sort by $sortByField = $cKey; // check if sort needs any CAST (e.g. numeric): $sortByField = $this->DAL()->build_custom_field_order_by_str( $sortByField, $cF ); } // add as subquery $extraSelect .= ',(SELECT zbscf_objval FROM '.$ZBSCRM_t['customfields']." WHERE zbscf_objid = invoice.ID AND zbscf_objkey = %s AND zbscf_objtype = %d LIMIT 1) ".$cKey; // add params $params[] = $cK; $params[] = ZBS_TYPE_INVOICE; } } #} ============ / PRE-QUERY =========== #} Build query $query = "SELECT invoice.*".$extraSelect." FROM ".$ZBSCRM_t['invoices'].' as invoice'.$joinQ; #} Count override if ($count) $query = "SELECT COUNT(invoice.ID) FROM ".$ZBSCRM_t['invoices'].' as invoice'.$joinQ; #} onlyColumns override if ($onlyColumns && is_array($onlyColumnsFieldArr) && count($onlyColumnsFieldArr) > 0){ $columnStr = ''; foreach ($onlyColumnsFieldArr as $colDBKey => $colStr){ if (!empty($columnStr)) $columnStr .= ','; // this presumes str is db-safe? could do with sanitation? $columnStr .= $colDBKey; } $query = "SELECT ".$columnStr." FROM ".$ZBSCRM_t['invoices'].' as invoice'.$joinQ; } #} ============= WHERE ================ #} Add Search phrase if (!empty($searchPhrase)){ // search? - ALL THESE COLS should probs have index of FULLTEXT in db? $searchWheres = array(); $searchWheres['search_ID'] = array('ID','=','%d',$searchPhrase); $searchWheres['search_ref'] = array('zbsi_id_override','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_total'] = array('zbsi_total','LIKE','%s',$searchPhrase.'%'); // 3.0.13 - Added ability to search custom fields (optionally) $customFieldSearch = zeroBSCRM_getSetting('customfieldsearch'); if ($customFieldSearch == 1){ // simplistic add // NOTE: This IGNORES ownership of custom field lines. $searchWheres['search_customfields'] = array('ID','IN',"(SELECT zbscf_objid FROM ".$ZBSCRM_t['customfields']." WHERE zbscf_objval LIKE %s AND zbscf_objtype = ".ZBS_TYPE_INVOICE.")",'%'.$searchPhrase.'%'); } // This generates a query like 'zbsi_fname LIKE %s OR zbsi_lname LIKE %s', // which we then need to include as direct subquery (below) in main query :) $searchQueryArr = $this->buildWheres($searchWheres,'',array(),'OR',false); if (is_array($searchQueryArr) && isset($searchQueryArr['where']) && !empty($searchQueryArr['where'])){ // add it $wheres['direct'][] = array('('.$searchQueryArr['where'].')',$searchQueryArr['params']); } } #} In array (if inCompany passed, this'll currently overwrite that?! (todo2.5)) if (is_array($inArr) && count($inArr) > 0){ // clean for ints $inArrChecked = array(); foreach ($inArr as $x){ $inArrChecked[] = (int)$x; } // add where $wheres['inarray'] = array('ID','IN','('.implode(',',$inArrChecked).')'); } #} Owned by if (!empty($ownedBy) && $ownedBy > 0){ // would never hard-type this in (would make generic as in buildWPMetaQueryWhere) // but this is only here until MIGRATED to db2 globally //$wheres['incompany'] = array('ID','IN','(SELECT DISTINCT post_id FROM '.$wpdb->prefix."postmeta WHERE meta_key = 'zbs_company' AND meta_value = %d)",$inCompany); // Use obj links now $wheres['ownedBy'] = array('zbs_owner','=','%s',$ownedBy); } // External sources if ( !empty( $externalSource ) ){ // NO owernship built into this, check when roll out multi-layered ownsership $wheres['externalsource'] = array('ID','IN','(SELECT DISTINCT zbss_objid FROM '.$ZBSCRM_t['externalsources']." WHERE zbss_objtype = ".ZBS_TYPE_INVOICE." AND zbss_source = %s)",$externalSource); } // quick addition for mike #} olderThan if (!empty($olderThan) && $olderThan > 0 && $olderThan !== false) $wheres['olderThan'] = array('zbsi_created','<=','%d',$olderThan); #} newerThan if (!empty($newerThan) && $newerThan > 0 && $newerThan !== false) $wheres['newerThan'] = array('zbsi_created','>=','%d',$newerThan); // status if (!empty($hasStatus) && $hasStatus !== false) $wheres['hasStatus'] = array('zbsi_status','=','%s',$hasStatus); if (!empty($otherStatus) && $otherStatus !== false) $wheres['otherStatus'] = array('zbsi_status','<>','%s',$otherStatus); // assignedContact + assignedCompany if (!empty($assignedContact) && $assignedContact !== false && $assignedContact > 0) $wheres['assignedContact'] = array('ID','IN','(SELECT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = ".ZBS_TYPE_INVOICE." AND zbsol_objtype_to = ".ZBS_TYPE_CONTACT." AND zbsol_objid_to = %d)",$assignedContact); if (!empty($assignedCompany) && $assignedCompany !== false && $assignedCompany > 0) $wheres['assignedCompany'] = array('ID','IN','(SELECT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = ".ZBS_TYPE_INVOICE." AND zbsol_objtype_to = ".ZBS_TYPE_COMPANY." AND zbsol_objid_to = %d)",$assignedCompany); #} Quick filters - adapted from DAL1 (probs can be slicker) if (is_array($quickFilters) && count($quickFilters) > 0){ // cycle through foreach ($quickFilters as $qFilter){ // where status = x // USE hasStatus above now... if ( str_starts_with( $qFilter, 'status_' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $quick_filter_status = substr( $qFilter, 7 ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $wheres['quickfilterstatus'] = array( 'zbsi_status', '=', 'convert(%s using utf8mb4) collate utf8mb4_bin', $quick_filter_status ); } else { // if we've hit no filter query, let external logic hook in to provide alternatives // First used in WooSync module $wheres = apply_filters( 'jpcrm_invoice_query_quickfilter', $wheres, $qFilter ); } } } // / quickfilters #} Any additionalWhereArr? if (isset($additionalWhereArr) && is_array($additionalWhereArr) && count($additionalWhereArr) > 0){ // add em onto wheres (note these will OVERRIDE if using a key used above) // Needs to be multi-dimensional $wheres = array_merge($wheres,$additionalWhereArr); $wheres = array_merge_recursive($wheres,$additionalWhereArr); } #} Is Tagged (expects 1 tag ID OR array) // catch 1 item arr if (is_array($isTagged) && count($isTagged) == 1) $isTagged = $isTagged[0]; if (!is_array($isTagged) && !empty($isTagged) && $isTagged > 0){ // add where tagged // 1 int: $wheres['direct'][] = array('((SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = invoice.ID AND zbstl_tagid = %d) > 0)',array(ZBS_TYPE_INVOICE,$isTagged)); } else if (is_array($isTagged) && count($isTagged) > 0){ // foreach in array :) $tagStr = ''; foreach ($isTagged as $iTag){ $i = (int)$iTag; if ($i > 0){ if ($tagStr !== '') $tagStr .','; $tagStr .= $i; } } if (!empty($tagStr)){ $wheres['direct'][] = array('((SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = invoice.ID AND zbstl_tagid IN (%s)) > 0)',array(ZBS_TYPE_INVOICE,$tagStr)); } } #} Is NOT Tagged (expects 1 tag ID OR array) // catch 1 item arr if (is_array($isNotTagged) && count($isNotTagged) == 1) $isNotTagged = $isNotTagged[0]; if (!is_array($isNotTagged) && !empty($isNotTagged) && $isNotTagged > 0){ // add where tagged // 1 int: $wheres['direct'][] = array('((SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = invoice.ID AND zbstl_tagid = %d) = 0)',array(ZBS_TYPE_INVOICE,$isNotTagged)); } else if (is_array($isNotTagged) && count($isNotTagged) > 0){ // foreach in array :) $tagStr = ''; foreach ($isNotTagged as $iTag){ $i = (int)$iTag; if ($i > 0){ if ($tagStr !== '') $tagStr .','; $tagStr .= $i; } } if (!empty($tagStr)){ $wheres['direct'][] = array('((SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = invoice.ID AND zbstl_tagid IN (%s)) = 0)',array(ZBS_TYPE_INVOICE,$tagStr)); } } #} ============ / WHERE =============== #} ============ SORT ============== // Obj Model based sort conversion // converts 'addr1' => 'zbsco_addr1' generically if (isset($this->objectModel[$sortByField]) && isset($this->objectModel[$sortByField]['fieldname'])) $sortByField = $this->objectModel[$sortByField]['fieldname']; // Mapped sorts // This catches listview and other exception sort cases $sort_map = array( // field aliases 'ref' => 'zbsi_id_override', 'value' => 'zbsi_total', // Note: "customer" here could be company or contact, so it's not a true sort (as no great way of doing this beyond some sort of prefix comparing) 'customer' => '(SELECT ID FROM '.$ZBSCRM_t['contacts'].' WHERE ID IN (SELECT zbsol_objid_to FROM '.$ZBSCRM_t['objlinks'].' WHERE zbsol_objtype_from = '.ZBS_TYPE_INVOICE.' AND zbsol_objtype_to = '.ZBS_TYPE_CONTACT.' AND zbsol_objid_from = invoice.ID))', ); if ( array_key_exists( $sortByField, $sort_map ) ) { $sortByField = $sort_map[ $sortByField ]; } #} ============ / SORT ============== #} CHECK this + reset to default if faulty if (!in_array($whereCase,array('AND','OR'))) $whereCase = 'AND'; #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params,$whereCase); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner,'contact'); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort($sortByField,$sortOrder) . $this->buildPaging($page,$perPage); try { #} Prep & run query $queryObj = $this->prepare($query,$params); #} Catch count + return if requested if ($count) return $wpdb->get_var($queryObj); #} else continue.. $potentialRes = $wpdb->get_results($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret results (Result Set - multi-row) if (isset($potentialRes) && is_array($potentialRes) && count($potentialRes) > 0) { #} Has results, tidy + return foreach ($potentialRes as $resDataLine) { // using onlyColumns filter? if ($onlyColumns && is_array($onlyColumnsFieldArr) && count($onlyColumnsFieldArr) > 0){ // only coumns return. $resArr = array(); foreach ($onlyColumnsFieldArr as $colDBKey => $colStr){ if (isset($resDataLine->$colDBKey)) $resArr[$colStr] = $resDataLine->$colDBKey; } } else { // tidy $resArr = $this->tidy_invoice($resDataLine,$withCustomFields); } if ($withLineItems){ // add all line item lines $resArr['lineitems'] = $this->DAL()->lineitems->getLineitems(array('associatedObjType'=>ZBS_TYPE_INVOICE,'associatedObjID'=>$resDataLine->ID,'perPage'=>1000,'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_LINEITEM))); } if ($withTransactions){ // add all line item lines $resArr['transactions'] = $this->DAL()->transactions->getTransactions(array('assignedInvoice'=>$resDataLine->ID,'perPage'=>1000,'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_TRANSACTION))); } if ($withTags){ // add all tags lines $resArr['tags'] = $this->DAL()->getTagsForObjID(array('objtypeid'=>ZBS_TYPE_INVOICE,'objid'=>$resDataLine->ID)); } if ($withOwner){ $resArr['owner'] = zeroBS_getOwner($resDataLine->ID,true,ZBS_TYPE_INVOICE,$resDataLine->zbs_owner); } if ($withAssigned){ /* This is for MULTIPLE (e.g. multi contact/companies assigned to an inv) // add all assigned contacts/companies $res['contacts'] = $this->DAL()->contacts->getContacts(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_INVOICE, 'hasObjIDLinkedTo'=>$resDataLine->ID, 'perPage'=>-1, 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); $res['companies'] = $this->DAL()->companies->getCompanies(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_INVOICE, 'hasObjIDLinkedTo'=>$resDataLine->ID, 'perPage'=>-1, 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_COMPANY))); .. but we use 1:1, at least now: */ // add all assigned contacts/companies $resArr['contact'] = $this->DAL()->contacts->getContacts(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_INVOICE, 'hasObjIDLinkedTo'=>$resDataLine->ID, 'page' => 0, 'perPage'=>1, // FORCES 1 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); $resArr['company'] = $this->DAL()->companies->getCompanies(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_INVOICE, 'hasObjIDLinkedTo'=>$resDataLine->ID, 'page' => 0, 'perPage'=>1, // FORCES 1 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_COMPANY))); } if ($withFiles){ $resArr['files'] = zeroBSCRM_files_getFiles('invoice',$resDataLine->ID); } if ($withTotals){ // add all tags lines $resArr['totals'] = $this->generateTotalsTable($resArr); } $res[] = $resArr; } } return $res; } /** * Returns a count of invoices (owned) * .. inc by status * * @return int count */ public function getInvoiceCount($args=array()){ #} ============ LOAD ARGS ============= $defaultArgs = array( // Search/Filtering (leave as false to ignore) 'withStatus' => false, // will be str if used // permissions 'ignoreowner' => true, // this'll let you not-check the owner of obj ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= $whereArr = array(); if ($withStatus !== false && !empty($withStatus)) $whereArr['status'] = array('zbsi_status','=','%s',$withStatus); return $this->DAL()->getFieldByWHERE(array( 'objtype' => ZBS_TYPE_INVOICE, 'colname' => 'COUNT(ID)', 'where' => $whereArr, 'ignoreowner' => $ignoreowner)); } /** * adds or updates a invoice object * * @param array $args Associative array of arguments * id (if update), owner, data (array of field data) * * @return int line ID */ public function addUpdateInvoice($args=array()){ global $ZBSCRM_t,$wpdb,$zbs; #} Retrieve any cf $customFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_INVOICE)); // not req. here$addrCustomFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_ADDRESS)); #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'owner' => -1, // fields (directly) 'data' => array( 'id_override' => '', 'parent' => '', 'status' => '', 'hash' => '', 'pdf_template' => '', 'portal_template' => '', 'email_template' => '', 'invoice_frequency' => '', 'currency' => '', 'pay_via' => '', 'logo_url' => '', 'address_to_objtype' => '', 'addressed_from' => '', 'addressed_to' => '', 'allow_partial' => -1, 'allow_tip' => -1, 'send_attachments' => -1, 'hours_or_quantity' => '', 'date' => '', 'due_date' => '', 'paid_date' => '', 'hash_viewed' => '', 'hash_viewed_count' => '', 'portal_viewed' => '', 'portal_viewed_count' => '', 'net' => '', 'discount' => '', 'discount_type' => '', 'shipping' => '', 'shipping_taxes' => '', 'shipping_tax' => '', 'taxes' => '', 'tax' => '', 'total' => '', // lineitems: 'lineitems' => false, // will be an array of lineitem lines (as per matching lineitem database model) // note: if no change desired, pass "false" // if removal of all/change, pass empty array // obj links: 'contacts' => false, // array of id's 'companies' => false, // array of id's // Note Custom fields may be passed here, but will not have defaults so check isset() // tags 'tags' => -1, // pass an array of tag ids or tag strings 'tag_mode' => 'replace', // replace|append|remove 'externalSources' => -1, // if this is an array(array('source'=>src,'uid'=>uid),multiple()) it'll add :) 'created' => -1, 'lastupdated' => '', ), 'limitedFields' => -1, // if this is set it OVERRIDES data (allowing you to set specific fields + leave rest in tact) // ^^ will look like: array(array('key'=>x,'val'=>y,'type'=>'%s')). the key needs to match the DB table, i.e. zbsi_status and not // just status. For full key references see developer docs (link to follow). // this function as DAL1 func did. 'extraMeta' => -1, 'automatorPassthrough' => -1, 'silentInsert' => false, // this was for init Migration - it KILLS all IA for newInvoice (because is migrating, not creating new :) this was -1 before 'do_not_update_blanks' => false, // this allows you to not update fields if blank (same as fieldoverride for extsource -> in) 'calculate_totals' => false // This allows us to recalculate tax, subtotal, total via php (e.g. if added via api). Only works if not using limitedFields ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } // Needs this to grab custom fields (if passed) too :) if ( is_array( $customFields ) ) { foreach ( $customFields as $cK => $cF ) { // only for data, limited fields below if ( is_array( $data ) ) { if ( isset( $args['data'][$cK] ) ) { $data[$cK] = $args['data'][$cK]; } } } } // this takes limited fields + checks through for custom fields present // (either as key zbsi_source or source, for example) // then switches them into the $data array, for separate update // where this'll fall over is if NO normal contact data is sent to update, just custom fields if (is_array($limitedFields) && is_array($customFields)){ //$customFieldKeys = array_keys($customFields); $newLimitedFields = array(); // cycle through foreach ($limitedFields as $field){ // some weird case where getting empties, so added check if (isset($field['key']) && !empty($field['key'])){ $dePrefixed = ''; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase if ( str_starts_with( $field['key'], 'zbsi_' ) ) { $dePrefixed = substr( $field['key'], strlen( 'zbsi_' ) ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } if (isset($customFields[$field['key']])){ // is custom, move to data $data[$field['key']] = $field['val']; } else if (!empty($dePrefixed) && isset($customFields[$dePrefixed])){ // is custom, move to data $data[$dePrefixed] = $field['val']; } else { // add it to limitedFields (it's not dealt with post-update) $newLimitedFields[] = $field; } } } // move this back in $limitedFields = $newLimitedFields; unset($newLimitedFields); } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ $id = (int)$id; // here we check that the potential owner CAN even own if ($owner > 0 && !user_can($owner,'admin_zerobs_usr')) $owner = -1; // if owner = -1, add current if (!isset($owner) || $owner === -1) { $owner = zeroBSCRM_user(); } if (is_array($limitedFields)){ // LIMITED UPDATE (only a few fields.) if (!is_array($limitedFields) || count ($limitedFields) <= 0) return false; // REQ. ID too (can only update) if (empty($id) || $id <= 0) return false; } else { // NORMAL, FULL UPDATE } #} If no status, and default is specified in settings, add that in :) if (is_null($data['status']) || !isset($data['status']) || empty($data['status'])){ // Default status for obj? -> this one gets for contacts -> $zbsCustomerMeta['status'] = zeroBSCRM_getSetting('defaultstatus'); // For now we force 'Draft' $data['status'] = __('Draft','zero-bs-crm'); } #} ========= / CHECK FIELDS =========== #} ========= OVERRIDE SETTING (Deny blank overrides) =========== // this only functions if externalsource is set (e.g. api/form, etc.) if (isset($data['externalSources']) && is_array($data['externalSources']) && count($data['externalSources']) > 0) { if (zeroBSCRM_getSetting('fieldoverride') == "1"){ $do_not_update_blanks = true; } } // either ext source + setting, or set by the func call if ($do_not_update_blanks){ // this setting says 'don't override filled-out data with blanks' // so here we check through any passed blanks + convert to limitedFields // only matters if $id is set (there is somt to update not add if (isset($id) && !empty($id) && $id > 0){ // get data to copy over (for now, this is required to remove 'fullname' etc.) $dbData = $this->db_ready_invoice($data); //unset($dbData['id']); // this is unset because we use $id, and is update, so not req. legacy issue //unset($dbData['created']); // this is unset because this uses an obj which has been 'updated' against original details, where created is output in the WRONG format :) $origData = $data; //$data = array(); $limitedData = array(); // array(array('key'=>'zbsi_x','val'=>y,'type'=>'%s')) // cycle through + translate into limitedFields (removing any blanks, or arrays (e.g. externalSources)) // we also have to remake a 'faux' data (removing blanks for tags etc.) for the post-update updates foreach ($dbData as $k => $v){ $intV = (int)$v; // only add if valuenot empty if (!is_array($v) && !empty($v) && $v != '' && $v !== 0 && $v !== -1 && $intV !== -1){ // add to update arr $limitedData[] = array( 'key' => 'zbsi_'.$k, // we have to add zbsi_ here because translating from data -> limited fields 'val' => $v, 'type' => $this->getTypeStr('zbsi_'.$k) ); // add to remade $data for post-update updates $data[$k] = $v; } } // copy over $limitedFields = $limitedData; } // / if ID } // / if do_not_update_blanks #} ========= / OVERRIDE SETTING (Deny blank overrides) =========== #} ========= BUILD DATA =========== $update = false; $dataArr = array(); $typeArr = array(); if (is_array($limitedFields)){ // LIMITED FIELDS $update = true; // cycle through foreach ($limitedFields as $field){ // some weird case where getting empties, so added check if (!empty($field['key'])){ $dataArr[$field['key']] = $field['val']; $typeArr[] = $field['type']; } } // add update time if (!isset($dataArr['zbsi_lastupdated'])){ $dataArr['zbsi_lastupdated'] = time(); $typeArr[] = '%d'; } } else { // FULL UPDATE/INSERT // (re)calculate the totals etc? if (isset($calculate_totals) && $calculate_totals){ $data = $this->recalculate($data); } // contacts - avoid dupes if (isset($data['contacts']) && is_array($data['contacts'])){ $coArr = array(); foreach ($data['contacts'] as $c){ $cI = (int)$c; if ($cI > 0 && !in_array($cI, $coArr)) $coArr[] = $cI; } // reset the main if (count($coArr) > 0) $data['contacts'] = $coArr; else $data['contacts'] = 'unset'; unset($coArr); } // companies - avoid dupes if (isset($data['companies']) && is_array($data['companies'])){ $coArr = array(); foreach ($data['companies'] as $c){ $cI = (int)$c; if ($cI > 0 && !in_array($cI, $coArr)) $coArr[] = $cI; } // reset the main if (count($coArr) > 0) $data['companies'] = $coArr; else $data['companies'] = 'unset'; unset($coArr); } // UPDATE $dataArr = array( // ownership // no need to update these (as of yet) - can't move teams etc. //'zbs_site' => zeroBSCRM_installSite(), //'zbs_team' => zeroBSCRM_installTeam(), //'zbs_owner' => $owner, 'zbsi_id_override' => $data['id_override'], 'zbsi_parent' => $data['parent'], 'zbsi_status' => $data['status'], 'zbsi_hash' => $data['hash'], 'zbsi_pdf_template' => $data['pdf_template'], 'zbsi_portal_template' => $data['portal_template'], 'zbsi_email_template' => $data['email_template'], 'zbsi_invoice_frequency' => $data['invoice_frequency'], 'zbsi_currency' => $data['currency'], 'zbsi_pay_via' => $data['pay_via'], 'zbsi_logo_url' => $data['logo_url'], 'zbsi_address_to_objtype' => $data['address_to_objtype'], 'zbsi_addressed_from' => $data['addressed_from'], 'zbsi_addressed_to' => $data['addressed_to'], 'zbsi_allow_partial' => $data['allow_partial'], 'zbsi_allow_tip' => $data['allow_tip'], 'zbsi_send_attachments' => $data['send_attachments'], 'zbsi_hours_or_quantity' => $data['hours_or_quantity'], 'zbsi_date' => $data['date'], 'zbsi_due_date' => $data['due_date'], 'zbsi_paid_date' => $data['paid_date'], 'zbsi_hash_viewed' => $data['hash_viewed'], 'zbsi_hash_viewed_count' => $data['hash_viewed_count'], 'zbsi_portal_viewed' => $data['portal_viewed'], 'zbsi_portal_viewed_count' => $data['portal_viewed_count'], 'zbsi_net' => $data['net'], 'zbsi_discount' => $data['discount'], 'zbsi_discount_type' => $data['discount_type'], 'zbsi_shipping' => $data['shipping'], 'zbsi_shipping_taxes' => $data['shipping_taxes'], 'zbsi_shipping_tax' => $data['shipping_tax'], 'zbsi_taxes' => $data['taxes'], 'zbsi_tax' => $data['tax'], 'zbsi_total' => $data['total'], 'zbsi_lastupdated' => time(), ); $typeArr = array( // field data types //'%d', // site //'%d', // team //'%d', // owner '%s', // id_override '%d', // parent '%s', // status '%s', // hash '%s', // pdf template '%s', // portal template '%s', // email template '%d', // zbsi_invoice_frequency '%s', // curr '%d', // pay via '%s', // logo url '%d', // addr to obj type '%s', // addr from '%s', // addr to '%d', // zbsi_allow_partial '%d', // allow_tip '%d', // hours or quantity '%d', // zbsi_send_attachments '%d', // date '%d', // due date '%d', // paid date '%d', // hash viewed '%d', // hash viewed count '%d', // portal viewed '%d', // portal viewed count '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', ); if (!empty($id) && $id > 0){ // is update $update = true; } else { // INSERT (get's few extra :D) $update = false; $dataArr['zbs_site'] = zeroBSCRM_site(); $typeArr[] = '%d'; $dataArr['zbs_team'] = zeroBSCRM_team(); $typeArr[] = '%d'; $dataArr['zbs_owner'] = $owner; $typeArr[] = '%d'; if (isset($data['created']) && !empty($data['created']) && $data['created'] !== -1){ $dataArr['zbsi_created'] = $data['created'];$typeArr[] = '%d'; } else { $dataArr['zbsi_created'] = time(); $typeArr[] = '%d'; } } // if a blank hash is passed, generate a new one if (isset($dataArr['zbsi_hash']) && $dataArr['zbsi_hash'] == '') $dataArr['zbsi_hash'] = zeroBSCRM_generateHash(20); } #} ========= / BUILD DATA =========== #} ============================================================ #} ========= CHECK force_uniques & not_empty & max_len ======== // if we're passing limitedFields we skip these, for now // #v3.1 - would make sense to unique/nonempty check just the limited fields. #gh-145 if (!is_array($limitedFields)){ // verify uniques if (!$this->verifyUniqueValues($data,$id)) return false; // / fails unique field verify // verify not_empty if (!$this->verifyNonEmptyValues($data)) return false; // / fails empty field verify } // whatever we do we check for max_len breaches and abbreviate to avoid wpdb rejections $dataArr = $this->wpdbChecks($dataArr); #} ========= / CHECK force_uniques & not_empty ================ #} ============================================================ #} Check if ID present if ($update){ #} Check if obj exists (here) - for now just brutal update (will error when doesn't exist) $originalStatus = $this->getInvoiceStatus($id); $previous_invoice_obj = $this->getInvoice( $id ); // log any change of status if (isset($dataArr['zbsi_status']) && !empty($dataArr['zbsi_status']) && !empty($originalStatus) && $dataArr['zbsi_status'] != $originalStatus){ // status change $statusChange = array( 'from' => $originalStatus, 'to' => $dataArr['zbsi_status'] ); } #} Attempt update if ($wpdb->update( $ZBSCRM_t['invoices'], $dataArr, array( // where 'ID' => $id ), $typeArr, array( // where data types '%d' )) !== false){ // if passing limitedFields instead of data, we ignore the following // this doesn't work, because data is in args default as arr //if (isset($data) && is_array($data)){ // so... if (!isset($limitedFields) || !is_array($limitedFields) || $limitedFields == -1){ // Line Items ==== // line item work if (isset($data['lineitems']) && is_array($data['lineitems'])){ // if array passed, update, even if removing if (count($data['lineitems']) > 0){ // passed, for now this is BRUTAL and just clears old ones + readds // once live, discuss how to refactor to be less brutal. // delete all lineitems $this->DAL()->lineitems->deleteLineItemsForObject(array('objID'=>$id,'objType'=>ZBS_TYPE_INVOICE)); // addupdate each foreach ($data['lineitems'] as $lineitem) { // slight rejig of passed so works cleanly with data array style $lineItemID = false; if (isset($lineitem['ID'])) $lineItemID = $lineitem['ID']; $this->DAL()->lineitems->addUpdateLineitem(array( 'id'=>$lineItemID, 'linkedObjType' => ZBS_TYPE_INVOICE, 'linkedObjID' => $id, 'data'=>$lineitem, 'calculate_totals' => true )); } } else { // delete all lineitems $this->DAL()->lineitems->deleteLineItemsForObject(array('objID'=>$id,'objType'=>ZBS_TYPE_INVOICE)); } } // / Line Items ==== // OBJ LINKS - to contacts/companies if (!is_array($data['contacts'])) $this->addUpdateObjectLinks($id,'unset',ZBS_TYPE_CONTACT); else $this->addUpdateObjectLinks($id,$data['contacts'],ZBS_TYPE_CONTACT); if (!is_array($data['companies'])) $this->addUpdateObjectLinks($id,'unset',ZBS_TYPE_COMPANY); else $this->addUpdateObjectLinks($id,$data['companies'],ZBS_TYPE_COMPANY); // IA also gets 'againstid' historically, but we'll pass as 'against id's' $againstIDs = array('contacts'=>$data['contacts'],'companies'=>$data['companies']); // tags if (isset($data['tags']) && is_array($data['tags'])) { $this->addUpdateInvoiceTags( array( 'id' => $id, 'tag_input' => $data['tags'], 'mode' => $data['tag_mode'] ) ); } // externalSources $approvedExternalSource = $this->DAL()->addUpdateExternalSources( array( 'obj_id' => $id, 'obj_type_id' => ZBS_TYPE_INVOICE, 'external_sources' => isset($data['externalSources']) ? $data['externalSources'] : array(), ) ); // for IA below // Custom fields? #} Cycle through + add/update if set if (is_array($customFields)) foreach ($customFields as $cK => $cF){ // any? if (isset($data[$cK])){ // add update $cfID = $this->DAL()->addUpdateCustomField(array( 'data' => array( 'objtype' => ZBS_TYPE_INVOICE, 'objid' => $id, 'objkey' => $cK, 'objval' => $data[$cK] ))); } } // / Custom Fields } // / if $data #} Any extra meta keyval pairs? // BRUTALLY updates (no checking) $confirmedExtraMeta = false; if (isset($extraMeta) && is_array($extraMeta)) { $confirmedExtraMeta = array(); foreach ($extraMeta as $k => $v){ #} This won't fix stupid keys, just catch basic fails... $cleanKey = strtolower(str_replace(' ','_',$k)); #} Brutal update //update_post_meta($postID, 'zbs_customer_extra_'.$cleanKey, $v); $this->DAL()->updateMeta(ZBS_TYPE_INVOICE,$id,'extra_'.$cleanKey,$v); #} Add it to this, which passes to IA $confirmedExtraMeta[$cleanKey] = $v; } } #} INTERNAL AUTOMATOR #} & #} FALLBACKS // UPDATING CONTACT if (!$silentInsert){ // catch dirty flag (update of status) (note, after update_post_meta - as separate) //if (isset($_POST['zbsi_status_dirtyflag']) && $_POST['zbsi_status_dirtyflag'] == "1"){ // actually here, it's set above if (isset($statusChange) && is_array($statusChange)){ // status has changed // IA zeroBSCRM_FireInternalAutomator('invoice.status.update',array( 'id'=>$id, 'againstids'=>array(), //$againstIDs, 'data'=> $data, 'from' => $statusChange['from'], 'to' => $statusChange['to'] )); } // IA General invoice update (2.87+) zeroBSCRM_FireInternalAutomator('invoice.update',array( 'id'=>$id, 'data'=>$data, 'againstids'=>array(), //$againstIDs, 'extsource'=>false, //$approvedExternalSource 'automatorpassthrough'=>$automatorPassthrough, #} This passes through any custom log titles or whatever into the Internal automator recipe. 'extraMeta' => $confirmedExtraMeta, // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase -- Also this is the "extraMeta" passed (as saved) 'prev_invoice' => $previous_invoice_obj, )); $data['id'] = $id; $previous_invoice_obj['id'] = $id; $this->events_manager->invoice()->updated( $data, $previous_invoice_obj ); } // Successfully updated - Return id return $id; } else { $msg = __('DB Update Failed','zero-bs-crm'); $zbs->DAL->addError(302,$this->objectType,$msg,$dataArr); // FAILED update return false; } } else { #} No ID - must be an INSERT if ($wpdb->insert( $ZBSCRM_t['invoices'], $dataArr, $typeArr ) > 0){ #} Successfully inserted, lets return new ID $newID = $wpdb->insert_id; // Line Items ==== // line item work if (isset($data['lineitems']) && is_array($data['lineitems'])){ // if array passed, update, even if removing if (count($data['lineitems']) > 0){ // passed, for now this is BRUTAL and just clears old ones + readds // once live, discuss how to refactor to be less brutal. // delete all lineitems $this->DAL()->lineitems->deleteLineItemsForObject(array('objID'=>$newID,'objType'=>ZBS_TYPE_INVOICE)); // addupdate each foreach ($data['lineitems'] as $lineitem) { // slight rejig of passed so works cleanly with data array style $lineItemID = false; if (isset($lineitem['ID'])) $lineItemID = $lineitem['ID']; $this->DAL()->lineitems->addUpdateLineitem(array( 'id'=>$lineItemID, 'linkedObjType' => ZBS_TYPE_INVOICE, 'linkedObjID' => $newID, 'data'=>$lineitem, 'calculate_totals' => true )); } } else { // delete all lineitems $this->DAL()->lineitems->deleteLineItemsForObject(array('objID'=>$newID,'objType'=>ZBS_TYPE_INVOICE)); } } // / Line Items ==== // OBJ LINKS - to contacts/companies $this->addUpdateObjectLinks($newID,$data['contacts'],ZBS_TYPE_CONTACT); $this->addUpdateObjectLinks($newID,$data['companies'],ZBS_TYPE_COMPANY); // IA also gets 'againstid' historically, but we'll pass as 'against id's' $againstIDs = array('contacts'=>$data['contacts'],'companies'=>$data['companies']); // tags if (isset($data['tags']) && is_array($data['tags'])) { $this->addUpdateInvoiceTags( array( 'id' => $newID, 'tag_input' => $data['tags'], 'mode' => $data['tag_mode'] ) ); } // externalSources $approvedExternalSource = $this->DAL()->addUpdateExternalSources( array( 'obj_id' => $newID, 'obj_type_id' => ZBS_TYPE_INVOICE, 'external_sources' => isset($data['externalSources']) ? $data['externalSources'] : array(), ) ); // for IA below // Custom fields? #} Cycle through + add/update if set if ( is_array( $customFields ) ) { foreach ( $customFields as $cK => $cF ) { // any? if ( isset( $data[$cK] ) ) { // add update $cfID = $this->DAL()->addUpdateCustomField(array( 'data' => array( 'objtype' => ZBS_TYPE_INVOICE, 'objid' => $newID, 'objkey' => $cK, 'objval' => $data[$cK] ))); } } } // / Custom Fields #} Any extra meta keyval pairs? // BRUTALLY updates (no checking) $confirmedExtraMeta = false; if (isset($extraMeta) && is_array($extraMeta)) { $confirmedExtraMeta = array(); foreach ($extraMeta as $k => $v){ #} This won't fix stupid keys, just catch basic fails... $cleanKey = strtolower(str_replace(' ','_',$k)); #} Brutal update //update_post_meta($postID, 'zbs_customer_extra_'.$cleanKey, $v); $this->DAL()->updateMeta(ZBS_TYPE_INVOICE,$newID,'extra_'.$cleanKey,$v); #} Add it to this, which passes to IA $confirmedExtraMeta[$cleanKey] = $v; } } #} INTERNAL AUTOMATOR #} & #} FALLBACKS // NEW CONTACT if (!$silentInsert){ #} Add to automator zeroBSCRM_FireInternalAutomator('invoice.new',array( 'id'=>$newID, 'data'=>$data, 'againstids'=>$againstIDs, 'extsource'=>$approvedExternalSource, 'automatorpassthrough'=>$automatorPassthrough, #} This passes through any custom log titles or whatever into the Internal automator recipe. 'extraMeta'=>$confirmedExtraMeta #} This is the "extraMeta" passed (as saved) )); $data['id'] = $newID; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $this->events_manager->invoice()->created( $data ); } return $newID; } else { $msg = __('DB Insert Failed','zero-bs-crm'); $zbs->DAL->addError(303,$this->objectType,$msg,$dataArr); #} Failed to Insert return false; } } return false; } /** * adds or updates a invoice's tags * ... this is really just a wrapper for addUpdateObjectTags * * @param array $args Associative array of arguments * id (if update), owner, data (array of field data) * * @return int line ID */ public function addUpdateInvoiceTags($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, // generic pass-through (array of tag strings or tag IDs): 'tag_input' => -1, // or either specific: 'tagIDs' => -1, 'tags' => -1, 'mode' => 'append' ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ // check id $id = (int)$id; if (empty($id) || $id <= 0) return false; #} ========= / CHECK FIELDS =========== return $this->DAL()->addUpdateObjectTags( array( 'objtype' => ZBS_TYPE_INVOICE, 'objid' => $id, 'tag_input' => $tag_input, 'tags' => $tags, 'tagIDs' => $tagIDs, 'mode' => $mode ) ); } /** * updates status for an invoice (no blanks allowed) * * @param int id Invoice ID * @param string Invoice Status * * @return bool */ public function setInvoiceStatus($id=-1,$status=-1){ global $zbs; $id = (int)$id; if ($id > 0 && !empty($status) && $status !== -1){ return $this->addUpdateInvoice(array( 'id'=>$id, 'limitedFields'=>array( array('key'=>'zbsi_status','val' => $status,'type' => '%s') ))); } return false; } /** * deletes a invoice object * * @param array $args Associative array of arguments * id * * @return int success; */ public function deleteInvoice($args=array()){ global $ZBSCRM_t,$wpdb,$zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'saveOrphans' => false ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} Check ID & Delete :) $id = (int)$id; if (!empty($id) && $id > 0) { // delete orphans? if ($saveOrphans === false){ // delete any tag links $this->DAL()->deleteTagObjLinks(array( 'objtype' => ZBS_TYPE_INVOICE, 'objid' => $id )); // delete any external source information $this->DAL()->delete_external_sources( array( 'obj_type' => ZBS_TYPE_INVOICE, 'obj_id' => $id, 'obj_source' => 'all', ) ); // delete any links to contacts $this->DAL()->deleteObjLinks( array( 'objtypefrom' => ZBS_TYPE_INVOICE, 'objtypeto' => ZBS_TYPE_CONTACT, 'objtofrom' => $id, ) ); // delete any links to transactions $this->DAL()->deleteObjLinks( array( 'objtypefrom' => ZBS_TYPE_TRANSACTION, 'objtypeto' => ZBS_TYPE_INVOICE, 'objtoid' => $id, ) ); // delete all orphaned lineitems $this->DAL()->lineitems->deleteLineItemsForObject( array( 'objID' => $id, 'objType' => ZBS_TYPE_INVOICE ) ); // delete all orphaned line items obj links $this->DAL()->deleteObjLinks( array( 'objtypefrom' => ZBS_TYPE_LINEITEM, 'objtypeto' => ZBS_TYPE_INVOICE, 'objtoid' => $id, ) ); } $del = zeroBSCRM_db2_deleteGeneric($id,'invoices'); #} Add to automator zeroBSCRM_FireInternalAutomator('invoice.delete',array( 'id'=>$id, 'saveOrphans'=>$saveOrphans )); return $del; } return false; } /** * tidy's the object from wp db into clean array * * @param array $obj (DB obj) * * @return array invoice (clean obj) */ private function tidy_invoice($obj=false,$withCustomFields=false){ $res = false; if (isset($obj->ID)){ $res = array(); $res['id'] = $obj->ID; /* `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, */ $res['owner'] = $obj->zbs_owner; $res['id_override'] = $this->stripSlashes($obj->zbsi_id_override); $res['parent'] = (int)$obj->zbsi_parent; $res['status'] = $this->stripSlashes($obj->zbsi_status); $res['status_label'] = __( $res['status'], 'zero-bs-crm' ); // phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText $res['hash'] = $this->stripSlashes($obj->zbsi_hash); $res['pdf_template'] = $this->stripSlashes($obj->zbsi_pdf_template); $res['portal_template'] = $this->stripSlashes($obj->zbsi_portal_template); $res['email_template'] = $this->stripSlashes($obj->zbsi_email_template); $res['invoice_frequency'] = (int)$obj->zbsi_invoice_frequency; $res['currency'] = $this->stripSlashes($obj->zbsi_currency); $res['pay_via'] = (int)$obj->zbsi_pay_via; $res['logo_url'] = $this->stripSlashes($obj->zbsi_logo_url); $res['address_to_objtype'] = (int)$obj->zbsi_address_to_objtype; $res['addressed_from'] = $this->stripSlashes($obj->zbsi_addressed_from); $res['addressed_to'] = $this->stripSlashes($obj->zbsi_addressed_to); $res['allow_partial'] = (bool)$obj->zbsi_allow_partial; $res['allow_tip'] = (bool)$obj->zbsi_allow_tip; $res['send_attachments'] = (bool)$obj->zbsi_send_attachments; $res['hours_or_quantity'] = $this->stripSlashes($obj->zbsi_hours_or_quantity); $res['date'] = (int)$obj->zbsi_date; $res['date_date'] = (isset($obj->zbsi_date) && $obj->zbsi_date > 0) ? jpcrm_uts_to_date_str( $obj->zbsi_date ) : false; $res['due_date'] = (int)$obj->zbsi_due_date; $res['due_date_date'] = (isset($obj->zbsi_due_date) && $obj->zbsi_due_date > 0) ? jpcrm_uts_to_date_str( $obj->zbsi_due_date ) : false; $res['paid_date'] = (int)$obj->zbsi_paid_date; $res['paid_date_date'] = (isset($obj->zbsi_paid_date) && $obj->zbsi_paid_date > 0) ? zeroBSCRM_date_i18n(-1,$obj->zbsi_paid_date,false,true) : false; $res['hash_viewed'] = (int)$obj->zbsi_hash_viewed; $res['hash_viewed_date'] = (isset($obj->zbsi_hash_viewed) && $obj->zbsi_hash_viewed > 0) ? zeroBSCRM_date_i18n(-1,$obj->zbsi_hash_viewed,false,true) : false; $res['hash_viewed_count'] = (int)$obj->zbsi_hash_viewed_count; $res['portal_viewed'] = (int)$obj->zbsi_portal_viewed; $res['portal_viewed_date'] = (isset($obj->zbsi_portal_viewed) && $obj->zbsi_portal_viewed > 0) ? zeroBSCRM_date_i18n(-1,$obj->zbsi_portal_viewed,false,true) : false; $res['portal_viewed_count'] = (int)$obj->zbsi_portal_viewed_count; $res['net'] = $this->stripSlashes($obj->zbsi_net); $res['discount'] = $this->stripSlashes($obj->zbsi_discount); $res['discount_type'] = $this->stripSlashes($obj->zbsi_discount_type); $res['shipping'] = $this->stripSlashes($obj->zbsi_shipping); $res['shipping_taxes'] = $this->stripSlashes($obj->zbsi_shipping_taxes); $res['shipping_tax'] = $this->stripSlashes($obj->zbsi_shipping_tax); $res['taxes'] = $this->stripSlashes($obj->zbsi_taxes); $res['tax'] = $this->stripSlashes($obj->zbsi_tax); $res['total'] = $this->stripSlashes($obj->zbsi_total); $res['created'] = (int)$obj->zbsi_created; $res['created_date'] = (isset($obj->zbsi_created) && $obj->zbsi_created > 0) ? zeroBSCRM_locale_utsToDatetime($obj->zbsi_created) : false; $res['lastupdated'] = (int)$obj->zbsi_lastupdated; $res['lastupdated_date'] = (isset($obj->zbsi_lastupdated) && $obj->zbsi_lastupdated > 0) ? zeroBSCRM_locale_utsToDatetime($obj->zbsi_lastupdated) : false; // custom fields - tidy any that are present: if ($withCustomFields) $res = $this->tidyAddCustomFields(ZBS_TYPE_INVOICE,$obj,$res,false); } return $res; } /** * Takes whatever invoice data available and re-calculates net, total, tax etc. * .. returning same obj with updated vals * .. This is a counter to the js func which does this in-UI, so changes need to be replicated in either or * * @param array $invoice_data Invoice data. * * @return array */ public function recalculate( $invoice_data = false ) { if ( is_array( $invoice_data ) ) { global $zbs; // we pass any discount saved against main invoice DOWN to the lineitems, first: if ( isset( $invoice_data['lineitems'] ) && is_array( $invoice_data['lineitems'] ) ) { $final_line_items = array(); // if not discounted, still recalc net if ( ! isset( $invoice_data['discount'] ) && $invoice_data['discount'] <= 0 ) { // recalc line items, but no discount to apply foreach ( $invoice_data['lineitems'] as $line_item ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase $final_line_items[] = $zbs->DAL->lineitems->recalculate( $line_item ); } } else { $discount_value = (float) $invoice_data['discount']; $discount_type = 'value'; if ( $invoice_data['discount_type'] === '%' ) { $discount_type = 'percentage'; } $calc_line_items = array(); if ( $discount_type === 'percentage' ) { $discount_percentage = ( (float) $invoice_data['discount'] ) / 100; // percentage discount foreach ( $invoice_data['lineitems'] as $line_item ) { $n = $line_item; if ( ! isset( $line_item['fee'] ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase $n = $zbs->DAL->lineitems->recalculate( $line_item ); $n['discount'] = $n['net'] * $discount_percentage; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase $n = $zbs->DAL->lineitems->recalculate( $n ); } else { $n['net'] = $line_item['total']; } $final_line_items[] = $n; } } else { // first calc + // accumulate a line-item net, so can pro-rata discounts $line_item_sum = 0; foreach ( $invoice_data['lineitems'] as $line_item ) { if ( ! isset( $line_item['fee'] ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase $n = $zbs->DAL->lineitems->recalculate( $line_item ); $line_item_sum += $n['net']; $calc_line_items[] = $n; } else { $line_item['net'] = $line_item['total']; $calc_line_items[] = $line_item; } } // now actually correct em foreach ( $calc_line_items as $n ) { $nl = $n; if ( ! isset( $n['fee'] ) ) { // calc pro-rata discount in absolute 0.00 // so this takes the net of all line item values // and then proportionally discounts a part of it (this line item net) // ... where have net if ( $n['net'] > 0 && $line_item_sum > 0 ) { $nl['discount'] = round( $discount_value * ( $n['net'] / $line_item_sum ), 2 ); } // final recalc to deal with new discount val // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase $nl = $zbs->DAL->lineitems->recalculate( $nl ); } // pass it $final_line_items[] = $nl; } } // / absolute discount } // / if lineitems + discount to apply // reset $invoice_data['lineitems'] = $final_line_items; unset( $final_line_items, $calc_line_items ); } // subtotal (zbsi_net) // == line item Quantity * rate * tax% // ... also calc tax as we go for 'total' below $sub_total = 0.0; $items_tax = 0.0; $discount = 0.0; // cycle through (any) line items if ( isset( $invoice_data ) && is_array( $invoice_data['lineitems'] ) ) { foreach ( $invoice_data['lineitems'] as $line_item ) { // can then directly use the recalced numbers :) if ( isset( $line_item['net'] ) ) { $sub_total += $line_item['net']; } if ( isset( $line_item['discount'] ) ) { $discount += (float) $line_item['discount']; } $items_tax += $line_item['tax']; } } // set it $invoice_data['net'] = $sub_total; // discount is accumulated from line items (applied at top) $total = $invoice_data['net'] - $discount; $shipping = 0.0; $tax_on_shipping = 0.0; // shipping subtotal if ( isset( $invoice_data['shipping'] ) && ! empty( $invoice_data['shipping'] ) ) { $shipping = (float) $invoice_data['shipping']; } if ( $shipping > 0 && empty( $invoice_data['shipping_tax'] ) ) { // tax on shipping - recalc. if ( isset( $invoice_data['shipping_taxes'] ) ) { $tax_on_shipping = zeroBSCRM_taxRates_getTaxValue( $shipping, $invoice_data['shipping_taxes'] ); } // set it $invoice_data['shipping_tax'] = $tax_on_shipping; // shipping total $shipping += $tax_on_shipping; } elseif ( is_numeric( $invoice_data['shipping_tax'] ) ) { $shipping += $invoice_data['shipping_tax']; } $total += $shipping; // tax - this is (re)calculated by line item recalc above $total += $items_tax; // total tax for invoice = lineitem tax + any tax on shipping $invoice_data['tax'] = $items_tax + $tax_on_shipping; // set it $invoice_data['total'] = $total; return $invoice_data; } return false; } /** * Takes whatever invoice data available and generates correct totals table (discount, shipping, tax vals) * * @param array $invoiceData * * @return array $invoiceTotals */ public function generateTotalsTable($invoice=false){ $totals = array( // not req. as part of main obj 'net' 'discount' => 0.0, 'taxes' => array(), // not req. as part of main obj 'shipping' // not req. as part of main obj 'total' ); // settings global $zbs; $invsettings = $zbs->settings->getAll(); // Discount if (isset($invoice["discount"]) && !empty($invoice["discount"])) { if ($invsettings['invdis'] == 1){ // v3.0+ we have discount type ('m' or '%') $discountType = 'value'; if (isset($invoice["discount_type"]) && !empty($invoice["discount_type"])){ if ($invoice["discount_type"] == '%') $discountType = 'percentage'; } if ($discountType == 'value'){ // value out $£ if (isset($invoice["discount"]) && !empty($invoice["discount"])){ $totals['discount'] = $invoice["discount"]; } } else { // percentage out - calc if (isset($invoice["discount"]) && !empty($invoice["discount"]) && isset($invoice['net'])){ $discountAmount = 0; $invDiscount = (float)$invoice["discount"]; if ($invDiscount > 0) $discountAmount = ($invDiscount/100)*$invoice['net']; $totals['discount'] = $discountAmount; } } } } if ($invsettings['invtax'] == 1){ // this output's tax in 1 number //if(isset($invoice["tax"]) && !empty($invoice["tax"])){ $totalsTable .= zeroBSCRM_formatCurrency($invoice["tax"]); }else{ $totalsTable .= zeroBSCRM_formatCurrency(0); } // ... but local taxes need splitting, so recalc & display by lineitems. $taxLines = false; if (isset($invoice['lineitems']) && is_array($invoice['lineitems']) && count($invoice['lineitems']) > 0){ // here we use this summarising func to retrieve $taxLines = $zbs->DAL->lineitems->getLineitemsTaxSummary(array('lineItems' => $invoice['lineitems'])); } // add any shipping tax :) if ($invsettings['invpandp'] == 1){ // shipping (if used) $shippingV = 0.0; $taxOnShipping = 0.0; // shipping subtotal if (isset($invoice["shipping"]) && !empty($invoice["shipping"])){ $shippingV = (float)$invoice["shipping"]; } if ($shippingV > 0){ // tax on shipping - recalc. if (isset($invoice['shipping_taxes'])) $taxOnShipping = zeroBSCRM_taxRates_getTaxValue($shippingV,$invoice['shipping_taxes']); // shipping can only have 1 tax at the moment, so find that tax and add to summary: $shippingRate = zeroBSCRM_taxRates_getTaxRate($invoice['shipping_taxes']); if (is_array($shippingRate) && isset($shippingRate['id'])){ // add to summary if (!isset($taxLines[$shippingRate['id']])){ // new, add $taxLines[$shippingRate['id']] = array( 'name' => $shippingRate['name'], 'rate' => $shippingRate['rate'], 'value' => $taxOnShipping ); } else { // += $taxLines[$shippingRate['id']]['value'] += $taxOnShipping; } } } } if (isset($taxLines) && is_array($taxLines) && count($taxLines) > 0) { $totals['taxes'] = $taxLines; } else { // simple fallback // ...just use $invoice["tax"] } } return $totals; } /** * Wrapper, use $this->getInvoiceMeta($contactID,$key) for easy retrieval of singular invoice * Simplifies $this->getMeta * * @param int objtype * @param int objid * @param string key * * @return array invoice meta result */ public function getInvoiceMeta($id=-1,$key='',$default=false){ global $zbs; if (!empty($key)){ return $this->DAL()->getMeta(array( 'objtype' => ZBS_TYPE_INVOICE, 'objid' => $id, 'key' => $key, 'fullDetails' => false, 'default' => $default, 'ignoreowner' => true // for now !! )); } return $default; } /** * Returns an ownerid against a invoice * * @param int id invoice ID * * @return int invoice owner id */ public function getInvoiceOwner($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_INVOICE, 'colname' => 'zbs_owner', 'ignoreowner'=>true)); } return false; } /** * Returns the first contact associated with an invoice * * @param int id quote ID * * @return int quote invoice id */ public function getInvoiceContactID($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ $contacts = $this->DAL()->getObjsLinkedToObj(array( 'objtypefrom' => ZBS_TYPE_INVOICE, 'objtypeto' => ZBS_TYPE_CONTACT, 'objfromid' => $id, 'count' => false, )); if (is_array($contacts)) foreach ($contacts as $c){ // first return $c['id']; } } return false; } /** * Returns a contact obj assigned to this invoice * * @param int id invoice ID * * @return int invoice owner id */ public function getInvoiceContact($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ $contacts = $this->DAL()->contacts->getContacts(array( // link 'hasObjTypeLinkedTo'=>ZBS_TYPE_INVOICE, 'hasObjIDLinkedTo'=>$resDataLine->ID, // query bits 'perPage'=>-1, 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); if (is_array($contacts) && isset($contacts[0])) return $contacts[0]; } return false; } /** * Returns a company obj assigned to this invoice * * @param int id invoice ID * * @return int invoice owner id */ public function getInvoiceCompany($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ $companies = $this->DAL()->companies->getCompanies(array( 'hasObjTypeLinkedTo' => ZBS_TYPE_INVOICE, 'hasObjIDLinkedTo' => $resDataLine->ID, 'perPage'=>-1, 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_COMPANY)) ); if (is_array($companies) && isset($companies[0])) return $companies[0]; } return false; } /** * Returns an status against a invoice * * @param int id invoice ID * * @return str invoice status string */ public function getInvoiceStatus($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_INVOICE, 'colname' => 'zbsi_status', 'ignoreowner'=>true)); } return false; } /** * Returns an SQL query addition which will allow filtering of invoices * that should be included in "total value" fields, excluding 'deleted' status invoices. * * @param str $table_alias_sql - if using a table alias pass that here, e.g. `invoices.`. * @return array */ public function get_invoice_status_except_deleted_for_query( $table_alias_sql = '' ) { $invoice_statuses_except_deleted = array( 'Draft', 'Unpaid', 'Paid', 'Overdue' ); $inv_statuses_str = $this->build_csv( $invoice_statuses_except_deleted ); $query_addition = ' AND ' . $table_alias_sql . 'zbsi_status IN (' . $inv_statuses_str . ')'; return $query_addition; } /** * Returns an hash against a invoice * * @param int id invoice ID * * @return str invoice hash string */ public function getInvoiceHash($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_INVOICE, 'colname' => 'zbsi_hash', 'ignoreowner'=>true)); } return false; } /** * Retrieves outstanding balanace against an invoice, based on transactions assigned to it. * * @param int id invoice ID * * @return float invoice outstanding balance */ public function getOutstandingBalance($invoiceID=-1){ if ($invoiceID > 0){ $invoice = $this->getInvoice($invoiceID,array( 'withTransactions' => true // so we can see other partials and check if paid. )); if (is_array($invoice)){ // get total due $invoice_total_value = 0.0; if ( isset( $invoice['total'] ) ) { $invoice_total_value = (float) $invoice['total']; // this one'll be a rolling sum $transactions_total_value = 0.0; // cycle through trans + calc existing balance if ( isset( $invoice['transactions'] ) && is_array( $invoice['transactions'] ) ) { // got trans foreach ( $invoice['transactions'] as $transaction ) { // should we also check for status=completed/succeeded? (leaving for now, will let check all): // get amount $transaction_amount = 0.0; if ( isset( $transaction['total'] ) ) { $transaction_amount = (float) $transaction['total']; if ( $transaction_amount > 0 ) { switch ( $transaction['type'] ) { case __( 'Sale', 'zero-bs-crm' ): // these count as debits against invoice. $transactions_total_value -= $transaction_amount; break; case __( 'Refund', 'zero-bs-crm' ): case __( 'Credit Note', 'zero-bs-crm' ): // these count as credits against invoice. $transactions_total_value += $transaction_amount; break; } // / switch on type (sale/refund) } // / if trans > 0 } // / if isset } // / each trans // should now have $transactions_total_value & $invoice_total_value // ... so we sum + return. return $invoice_total_value + $transactions_total_value; } // / if has trans } // if isset invoice total } // / if retrieved inv } // / if invoice_id > 0 return false; } /** * remove any non-db fields from the object * basically takes array like array('owner'=>1,'fname'=>'x','fullname'=>'x') * and returns array like array('owner'=>1,'fname'=>'x') * This does so based on the objectModel! * * @param array $obj (clean obj) * * @return array (db ready arr) */ private function db_ready_invoice($obj=false){ // use the generic? (override here if necessary) return $this->db_ready_obj($obj); } /** * Takes full object and makes a "list view" boiled down version * Used to generate listview objs * * @param array $obj (clean obj) * * @return array (listview ready obj) */ public function listViewObj($invoice=false,$columnsRequired=array()){ if (is_array($invoice) && isset($invoice['id'])){ $resArr = $invoice; // a lot of this is legacy <DAL3 stuff just mapped. def could do with an improvement for efficacy's sake. //$resArr['id'] = $invoice['id']; //$resArr['zbsid'] = $invoice['zbsid']; if (isset($invoice['id_override']) && $invoice['id_override'] !== null) $resArr['zbsid'] = $invoice['id_override']; else $resArr['zbsid'] = $invoice['id']; // title... I suspect you mean ref? // WH note: I suspect we mean id_override now. $resArr['title'] = ''; //if (isset($invoice['name'])) $resArr['title'] = $invoice['name']; if (isset($invoice['id_override']) && empty($resArr['title'])) $resArr['title'] = $invoice['id_override']; #} Convert $contact arr into list-view-digestable 'customer'// & unset contact for leaner data transfer if ( array_key_exists( 'contact', $invoice ) ) { $resArr['customer'] = zeroBSCRM_getSimplyFormattedContact($invoice['contact'], (in_array('assignedobj', $columnsRequired))); } #} Convert $contact arr into list-view-digestable 'customer'// & unset contact for leaner data transfer if ( array_key_exists( 'company', $invoice ) ) { $resArr['company'] = zeroBSCRM_getSimplyFormattedCompany($invoice['company'], (in_array('assignedobj', $columnsRequired))); } //format currency handles if the amount is blank (sends it to 0) // WH: YES but it doesn't check if isset / stop php notice $resArr['value'] = zeroBSCRM_formatCurrency($invoice['meta']['val']); $resArr['total'] = zeroBSCRM_formatCurrency(0); if (isset($invoice['total'])) $resArr['total'] = zeroBSCRM_formatCurrency($invoice['total']); return $resArr; } return false; } // =========== / INVOICE ======================================================= // =============================================================================== } // / class
projects/plugins/crm/includes/jpcrm-language.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V4.0.7 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ // gets 'Contact' (legacy/deprecated) // Unless this is used in any extensions this can be removed. function zeroBSCRM_getContactOrCustomer(){ return __('Contact',"zero-bs-crm"); } // gets company label, backward compatibility: function zeroBSCRM_getCompanyOrOrg(){ return jpcrm_label_company(false); } function zeroBSCRM_getCompanyOrOrgPlural(){ return jpcrm_label_company(true); } /** * Returns global label used to differentiate b2b mode objects (Companies) * Replaces old functions zeroBSCRM_getCompanyOrOrg and zeroBSCRM_getCompanyOrOrgPlural * Note, I still prefer this to using a gettext filter (as we do in rebrandr) * * @param array $plural return singular or plural * * @return string label */ function jpcrm_label_company($plural=false){ // retrieve type. $organisationType = zeroBSCRM_getSetting('coororg'); if (!$plural){ // singular $s = __('Company',"zero-bs-crm"); if ($organisationType == 'org') $s = __('Organisation',"zero-bs-crm"); if ($organisationType == 'domain') $s = __('Domain',"zero-bs-crm"); } else { // plural $s = __('Companies',"zero-bs-crm"); if ($organisationType == 'org') $s = __('Organisations',"zero-bs-crm"); if ($organisationType == 'domain') $s = __('Domains',"zero-bs-crm"); } return $s; }
projects/plugins/crm/includes/ZeroBSCRM.DAL3.Obj.Contacts.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V3.0+ * * Copyright 2020 Automattic * * Date: 14/01/19 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ use Automattic\Jetpack\CRM\Event_Manager\Events_Manager; /** * ZBS DAL >> Contacts * * @author Woody Hayday <hello@jetpackcrm.com> * @version 2.0 * @access public * @see https://jetpackcrm.com/kb */ class zbsDAL_contacts extends zbsDAL_ObjectLayer { protected $objectType = ZBS_TYPE_CONTACT; protected $objectDBPrefix = 'zbsc_'; protected $objectIncludesAddresses = true; protected $include_in_templating = true; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.PropertyNotSnakeCase, Squiz.Commenting.VariableComment.Missing -- to be refactored. protected $objectModel = array(); /** @var Events_Manager To manage the CRM events */ private $events_manager; // hardtyped list of types this object type is commonly linked to protected $linkedToObjectTypes = array( ZBS_TYPE_COMPANY ); // phpcs:ignore Squiz.Commenting.FunctionComment.Missing, Squiz.Scope.MethodScope.Missing -- to be refactored. function __construct( $args = array() ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- to be refactored. $this->objectModel = array( // ID 'ID' => array( 'fieldname' => 'ID', 'format' => 'int', ), // site + team generics 'zbs_site' => array( 'fieldname' => 'zbs_site', 'format' => 'int', ), 'zbs_team' => array( 'fieldname' => 'zbs_team', 'format' => 'int', ), 'zbs_owner' => array( 'fieldname' => 'zbs_owner', 'format' => 'int', ), // other fields 'status' => array( // db model: 'fieldname' => 'zbsc_status', 'format' => 'str', // output model 'input_type' => 'select', 'label' => __( 'Status', 'zero-bs-crm' ), 'placeholder' => '', 'options' => array( 'Lead', 'Customer', 'Refused' ), 'essential' => true, 'max_len' => 100, 'do_not_show_on_portal' => true, ), 'email' => array( // db model: 'fieldname' => 'zbsc_email', 'format' => 'str', // output model 'input_type' => 'email', 'label' => __( 'Email', 'zero-bs-crm' ), 'placeholder' => 'e.g. john@gmail.com', 'essential' => true, 'force_unique' => true, // must be unique. This is required and breaking if true 'can_be_blank' => true, 'max_len' => 200, // removed due to some users using mobile/other as unique field? see #gh-153 // 'not_empty' => true, 'do_not_show_on_portal' => true, ), 'prefix' => array( // db model: 'fieldname' => 'zbsc_prefix', 'format' => 'str', // output model 'input_type' => 'select', 'label' => __( 'Prefix', 'zero-bs-crm' ), 'placeholder' => '', 'options' => array( 'Mr', 'Mrs', 'Ms', 'Miss', 'Mx', 'Dr', 'Prof', 'Mr & Mrs' ), 'essential' => true, 'max_len' => 30, ), 'fname' => array( // db model: 'fieldname' => 'zbsc_fname', 'format' => 'str', // output model 'input_type' => 'text', 'label' => __( 'First Name', 'zero-bs-crm' ), 'placeholder' => 'e.g. John', 'essential' => true, 'max_len' => 100, ), 'lname' => array( // db model: 'fieldname' => 'zbsc_lname', 'format' => 'str', // output model 'input_type' => 'text', 'label' => __( 'Last Name', 'zero-bs-crm' ), 'placeholder' => 'e.g. Doe', 'essential' => true, 'max_len' => 100, ), 'addr1' => array( // db model: 'fieldname' => 'zbsc_addr1', 'format' => 'str', // output model 'input_type' => 'text', 'label' => __( 'Address Line 1', 'zero-bs-crm' ), 'placeholder' => '', 'area' => 'Main Address', 'migrate' => 'addresses', 'max_len' => 200, ), 'addr2' => array( // db model: 'fieldname' => 'zbsc_addr2', 'format' => 'str', // output model 'input_type' => 'text', 'label' => __( 'Address Line 2', 'zero-bs-crm' ), 'placeholder' => '', 'area' => 'Main Address', 'migrate' => 'addresses', 'max_len' => 200, ), 'city' => array( // db model: 'fieldname' => 'zbsc_city', 'format' => 'str', // output model 'input_type' => 'text', 'label' => __( 'City', 'zero-bs-crm' ), 'placeholder' => 'e.g. New York', 'area' => 'Main Address', 'migrate' => 'addresses', 'max_len' => 100, ), 'county' => array( // db model: 'fieldname' => 'zbsc_county', 'format' => 'str', // output model 'input_type' => 'text', 'label' => __( 'County', 'zero-bs-crm' ), 'placeholder' => 'e.g. Kings County', 'area' => 'Main Address', 'migrate' => 'addresses', 'max_len' => 200, ), 'postcode' => array( // db model: 'fieldname' => 'zbsc_postcode', 'format' => 'str', // output model 'input_type' => 'text', 'label' => __( 'Post Code', 'zero-bs-crm' ), 'placeholder' => 'e.g. 10019', 'area' => 'Main Address', 'migrate' => 'addresses', 'max_len' => 50, ), 'country' => array( // db model: 'fieldname' => 'zbsc_country', 'format' => 'str', // output model 'input_type' => 'selectcountry', 'label' => __( 'Country', 'zero-bs-crm' ), 'placeholder' => '', 'area' => 'Main Address', 'migrate' => 'addresses', 'max_len' => 200, ), 'secaddr1' => array( // db model: 'fieldname' => 'zbsc_addr1', 'format' => 'str', // output model 'input_type' => 'text', 'label' => __( 'Address Line 1', 'zero-bs-crm' ), 'placeholder' => '', 'area' => 'Second Address', 'migrate' => 'addresses', 'opt' => 'secondaddress', 'max_len' => 200, 'dal1key' => 'secaddr_addr1', // previous field name ), 'secaddr2' => array( // db model: 'fieldname' => 'zbsc_addr2', 'format' => 'str', // output model 'input_type' => 'text', 'label' => __( 'Address Line 2', 'zero-bs-crm' ), 'placeholder' => '', 'area' => 'Second Address', 'migrate' => 'addresses', 'opt' => 'secondaddress', 'max_len' => 200, 'dal1key' => 'secaddr_addr2', // previous field name ), 'seccity' => array( // db model: 'fieldname' => 'zbsc_city', 'format' => 'str', // output model 'input_type' => 'text', 'label' => __( 'City', 'zero-bs-crm' ), 'placeholder' => 'e.g. Los Angeles', 'area' => 'Second Address', 'migrate' => 'addresses', 'opt' => 'secondaddress', 'max_len' => 100, 'dal1key' => 'secaddr_city', // previous field name ), 'seccounty' => array( // db model: 'fieldname' => 'zbsc_county', 'format' => 'str', // output model 'input_type' => 'text', 'label' => __( 'County', 'zero-bs-crm' ), 'placeholder' => 'e.g. Los Angeles', 'area' => 'Second Address', 'migrate' => 'addresses', 'opt' => 'secondaddress', 'max_len' => 200, 'dal1key' => 'secaddr_county', // previous field name ), 'secpostcode' => array( // db model: 'fieldname' => 'zbsc_postcode', 'format' => 'str', // output model 'input_type' => 'text', 'label' => __( 'Post Code', 'zero-bs-crm' ), 'placeholder' => 'e.g. 90001', 'area' => 'Second Address', 'migrate' => 'addresses', 'opt' => 'secondaddress', 'max_len' => 50, 'dal1key' => 'secaddr_postcode', // previous field name ), 'seccountry' => array( // db model: 'fieldname' => 'zbsc_country', 'format' => 'str', // output model 'input_type' => 'selectcountry', 'label' => __( 'Country', 'zero-bs-crm' ), 'placeholder' => '', 'area' => 'Second Address', 'migrate' => 'addresses', 'opt' => 'secondaddress', 'max_len' => 200, 'dal1key' => 'secaddr_country', // previous field name ), 'hometel' => array( // db model: 'fieldname' => 'zbsc_hometel', 'format' => 'str', // output model 'input_type' => 'tel', 'label' => __( 'Home Telephone', 'zero-bs-crm' ), 'placeholder' => 'e.g. 877 2733049', 'max_len' => 40, ), 'worktel' => array( // db model: 'fieldname' => 'zbsc_worktel', 'format' => 'str', // output model 'input_type' => 'tel', 'label' => __( 'Work Telephone', 'zero-bs-crm' ), 'placeholder' => 'e.g. 877 2733049', 'max_len' => 40, ), 'mobtel' => array( // db model: 'fieldname' => 'zbsc_mobtel', 'format' => 'str', // output model 'input_type' => 'tel', 'label' => __( 'Mobile Telephone', 'zero-bs-crm' ), 'placeholder' => 'e.g. 877 2733050', 'max_len' => 40, ), // ... just removed for DAL3 :) should be custom field anyway by this point 'wpid' => array( // db model: 'fieldname' => 'zbsc_wpid', 'format' => 'int', // output model // NONE, not exposed via standard input ), 'avatar' => array( // db model: 'fieldname' => 'zbsc_avatar', 'format' => 'str', // output model // NONE, not exposed via standard input ), 'tw' => array( // db model: 'fieldname' => 'zbsc_tw', 'format' => 'str', 'max_len' => 100, // output model // NONE, not exposed via standard input ), 'li' => array( // db model: 'fieldname' => 'zbsc_li', 'format' => 'str', 'max_len' => 300, // output model // NONE, not exposed via standard input ), 'fb' => array( // db model: 'fieldname' => 'zbsc_fb', 'format' => 'str', 'max_len' => 200, // output model // NONE, not exposed via standard input ), 'created' => array( // db model: 'fieldname' => 'zbsc_created', 'format' => 'uts', // output model // NONE, not exposed via db ), 'lastupdated' => array( // db model: 'fieldname' => 'zbsc_lastupdated', 'format' => 'uts', // output model // NONE, not exposed via db ), 'lastcontacted' => array( // db model: 'fieldname' => 'zbsc_lastcontacted', 'format' => 'uts', // output model // NONE, not exposed via db ), ); #} =========== LOAD ARGS ============== $defaultArgs = array( //'tag' => false, ); foreach ($defaultArgs as $argK => $argV){ $this->$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $this->$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$this->$argK = $newData;} else { $this->$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= $this->events_manager = new Events_Manager(); add_filter( 'jpcrm_listview_filters', array( $this, 'add_listview_filters' ) ); } /** * Adds items to listview filter using `jpcrm_listview_filters` hook. * * @param array $listview_filters Listview filters. */ public function add_listview_filters( $listview_filters ) { global $zbs; // Add "assigned"/"not assigned" filters. $listview_filters[ ZBS_TYPE_CONTACT ]['general']['assigned_to_me'] = __( 'Assigned to me', 'zero-bs-crm' ); $listview_filters[ ZBS_TYPE_CONTACT ]['general']['not_assigned'] = __( 'Not assigned', 'zero-bs-crm' ); $quick_filter_settings = $zbs->settings->get( 'quickfiltersettings' ); // Add 'not-contacted-in-x-days'. if ( ! empty( $quick_filter_settings['notcontactedinx'] ) && $quick_filter_settings['notcontactedinx'] > 0 ) { $days = (int) $quick_filter_settings['notcontactedinx']; $listview_filters[ ZBS_TYPE_CONTACT ]['general'][ 'notcontactedin' . $days ] = sprintf( // translators: %s is the number of days __( 'Not Contacted in %s days', 'zero-bs-crm' ), $days ); } // Add 'olderthan-x-days'. if ( ! empty( $quick_filter_settings['olderthanx'] ) && $quick_filter_settings['olderthanx'] > 0 ) { $days = (int) $quick_filter_settings['olderthanx']; $listview_filters[ ZBS_TYPE_CONTACT ]['general'][ 'olderthan' . $days ] = sprintf( // translators: %s is the number of days __( 'Older than %s days', 'zero-bs-crm' ), $days ); } // Add statuses if enabled. if ( $zbs->settings->get( 'filtersfromstatus' ) === 1 ) { $statuses = zeroBSCRM_getCustomerStatuses( true ); foreach ( $statuses as $status ) { $listview_filters[ ZBS_TYPE_CONTACT ]['status'][ 'status_' . $status ] = $status; } } // Add segments if enabled. if ( $zbs->settings->get( 'filtersfromsegments' ) === 1 ) { $segments = $zbs->DAL->segments->getSegments( -1, 100, 0, false, '', '', 'zbsseg_name', 'ASC' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase foreach ( $segments as $segment ) { $listview_filters[ ZBS_TYPE_CONTACT ]['segment'][ 'segment_' . $segment['slug'] ] = $segment['name']; } } return $listview_filters; } // generic get Company (by ID) // Super simplistic wrapper used by edit page etc. (generically called via dal->contacts->getSingle etc.) public function getSingle($ID=-1){ return $this->getContact($ID); } // generic get contact (by ID list) // Super simplistic wrapper used by MVP Export v3.0 public function getIDList($IDs=false){ return $this->getContacts(array( 'inArr' => $IDs, 'withCustomFields' => true, 'withValues' => true, 'withAssigned' => true, 'page' => -1, 'perPage' => -1 )); } // generic get (EVERYTHING) // expect heavy load! public function getAll($IDs=false){ return $this->getContacts(array( 'withCustomFields' => true, 'withValues' => true, 'withAssigned' => true, 'sortByField' => 'ID', 'sortOrder' => 'ASC', 'page' => -1, 'perPage' => -1, )); } // generic get count of (EVERYTHING) public function getFullCount(){ return $this->getContacts(array( 'count' => true, 'page' => -1, 'perPage' => -1, )); } /* * Returns an (int) count of all contacts with an external source */ public function getTotalExtSourceCount(){ global $ZBSCRM_t,$wpdb; $query = "SELECT COUNT(contacts.id) FROM " . $ZBSCRM_t['contacts'] . " contacts" . " INNER JOIN " . $ZBSCRM_t['externalsources'] . " ext_sources" . " ON contacts.id = ext_sources.zbss_objid" . " WHERE ext_sources.zbss_objtype = " . ZBS_TYPE_CONTACT; /* SELECT COUNT(contacts.id) FROM wp_zbs_contacts contacts INNER JOIN wp_zbs_externalsources ext_sources ON contacts.id = ext_sources.zbss_objid WHERE ext_sources.zbss_objtype = 1 */ return $wpdb->get_var( $query ); } /** * returns full contact line +- details * Replaces many funcs, inc zeroBS_getCustomerIDFromWPID, zeroBS_getCustomerIDWithEmail etc. * * @param int id contact id * @param array $args Associative array of arguments * withQuotes, withInvoices, withTransactions, withLogs * * @return array result */ public function getContact($id=-1,$args=array()){ global $zbs; #} =========== LOAD ARGS ============== $defaultArgs = array( 'email' => false, // if id -1 and email given, will return based on email search 'WPID' => false, // if id -1 and wpid given, will return based on wpid search // if theset wo passed, will search based on these 'externalSource' => false, 'externalSourceUID' => false, // with what? 'withCustomFields' => true, 'withQuotes' => false, 'withInvoices' => false, 'withTransactions' => false, 'withTasks' => false, 'withLogs' => false, 'withLastLog' => false, 'withTags' => false, 'withCompanies' => false, 'withOwner' => false, 'withValues' => false, // if passed, returns with 'total' 'invoices_total' 'transactions_total' etc. (requires getting all obj, use sparingly) 'withAliases' => false, 'withExternalSources' => false, 'withExternalSourcesGrouped' => false, 'with_obj_limit' => false, // if (int) specified, this will limit the count of quotes, invoices, transactions, and tasks returned // permissions 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT), // this'll let you not-check the owner of obj // returns scalar ID of line 'onlyID' => false, 'fields' => false // false = *, array = fieldnames ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} Check ID $id = (int)$id; if ( (!empty($id) && $id > 0) || (!empty($WPID) && $WPID > 0) || (!empty($email)) || (!empty($externalSource) && !empty($externalSourceUID)) ){ global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); $extraSelect = ''; #} ============= PRE-QUERY ============ #} Custom Fields if ($withCustomFields && !$onlyID){ #} Retrieve any cf $custFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_CONTACT)); #} Cycle through + build into query if (is_array($custFields)) foreach ($custFields as $cK => $cF){ // add as subquery $extraSelect .= ',(SELECT zbscf_objval FROM '.$ZBSCRM_t['customfields']." WHERE zbscf_objid = contact.ID AND zbscf_objkey = %s AND zbscf_objtype = %d LIMIT 1) '".$cK."'"; // add params $params[] = $cK; $params[] = ZBS_TYPE_CONTACT; } } #} Aliases if ($withAliases){ #} Retrieve these as a CSV :) $extraSelect .= ',(SELECT ' . $this->DAL()->build_group_concat( 'aka_alias', ',' ) . ' FROM ' . $ZBSCRM_t['aka'] . ' WHERE aka_type = ' . ZBS_TYPE_CONTACT . ' AND aka_id = contact.ID) aliases'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } // Add any addr custom fields for addr1+addr2 $addrCustomFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_ADDRESS)); if ($withCustomFields && !$onlyID && is_array($addrCustomFields) && count($addrCustomFields) > 0){ foreach ($addrCustomFields as $cK => $cF){ // custom field key $cfKey = 'addr_'.$cK; $cfKey2 = 'secaddr_'.$cK; // address custom field (e.g. 'house name') it'll be passed here as 'house-name' // ... problem is mysql does not like that :) so we have to chage here: // in this case we prepend address cf's with addr_ and we switch - for _ $cKey = 'addrcf_'.str_replace('-','_',$cK); $cKey2 = 'secaddrcf_'.str_replace('-','_',$cK); // addr 1 // add as subquery $extraSelect .= ',(SELECT zbscf_objval FROM '.$ZBSCRM_t['customfields']." WHERE zbscf_objid = contact.ID AND zbscf_objkey = %s AND zbscf_objtype = %d) ".$cKey; // add params $params[] = $cfKey; $params[] = ZBS_TYPE_CONTACT; // addr 2 // add as subquery $extraSelect .= ',(SELECT zbscf_objval FROM '.$ZBSCRM_t['customfields']." WHERE zbscf_objid = contact.ID AND zbscf_objkey = %s AND zbscf_objtype = %d) ".$cKey2; // add params $params[] = $cfKey2; $params[] = ZBS_TYPE_CONTACT; } } // ==== TOTAL VALUES // Calculate total vals etc. with SQL if ($withValues && !$onlyID){ // only include transactions with statuses which should be included in total value: $transStatusQueryAdd = $this->DAL()->transactions->getTransactionStatusesToIncludeQuery(); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // include invoices without deleted status in the total value for invoices_total_inc_deleted: $inv_status_query_add = $this->DAL()->invoices->get_invoice_status_except_deleted_for_query(); // quotes: $extraSelect .= ',(SELECT SUM(quotestotal.zbsq_value) FROM '.$ZBSCRM_t['quotes'].' as quotestotal WHERE quotestotal.ID IN (SELECT DISTINCT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = ".ZBS_TYPE_QUOTE." AND zbsol_objtype_to = ".ZBS_TYPE_CONTACT." AND zbsol_objid_to = contact.ID)) as quotes_total"; // invs not including deleted: $extraSelect .= ',(SELECT IFNULL(SUM(invstotal.zbsi_total),0) FROM ' . $ZBSCRM_t['invoices'] . ' as invstotal WHERE invstotal.ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_INVOICE . ' AND zbsol_objtype_to = ' . ZBS_TYPE_CONTACT . ' AND zbsol_objid_to = contact.ID)' . $inv_status_query_add . ') as invoices_total'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // invs including deleted: $extraSelect .= ',(SELECT SUM(invstotalincdeleted.zbsi_total) FROM ' . $ZBSCRM_t['invoices'] . ' as invstotalincdeleted WHERE invstotalincdeleted.ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_INVOICE . ' AND zbsol_objtype_to = ' . ZBS_TYPE_CONTACT . ' AND zbsol_objid_to = contact.ID)) as invoices_total_inc_deleted'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // invs count: $extraSelect .= ',(SELECT COUNT(ID) FROM ' . $ZBSCRM_t['invoices'] . ' WHERE ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_INVOICE . ' AND zbsol_objtype_to = ' . ZBS_TYPE_CONTACT . ' AND zbsol_objid_to = contact.ID)' . $inv_status_query_add . ') as invoices_count'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // invs count including deleted: $extraSelect .= ',(SELECT COUNT(ID) FROM ' . $ZBSCRM_t['invoices'] . ' WHERE ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_INVOICE . ' AND zbsol_objtype_to = ' . ZBS_TYPE_CONTACT . ' AND zbsol_objid_to = contact.ID)) as invoices_count_inc_deleted'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // trans (with status): $extraSelect .= ',(SELECT SUM(transtotal.zbst_total) FROM '.$ZBSCRM_t['transactions'].' as transtotal WHERE transtotal.ID IN (SELECT DISTINCT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = ".ZBS_TYPE_TRANSACTION." AND zbsol_objtype_to = ".ZBS_TYPE_CONTACT." AND zbsol_objid_to = contact.ID)".$transStatusQueryAdd.") as transactions_total"; // paid balance against invs (also in getContacts) // (this allows us to subtract from totals to get a true figure where transactions are part/whole payments for invs) /* This selects transactions where there is a link to an invoice where that invoice has a link to this contact: ========== SELECT * FROM wp_zbs_transactions trans WHERE trans.ID IN ( SELECT DISTINCT zbsol_objid_from FROM `wp_zbs_object_links` WHERE zbsol_objtype_from = 5 AND zbsol_objtype_to = 4 AND zbsol_objid_to IN ( SELECT DISTINCT zbsol_objid_from FROM `wp_zbs_object_links` WHERE zbsol_objtype_from = 4 AND zbsol_objtype_to = 1 AND zbsol_objid_to = 1 ) ) */ $extraSelect .= ',(SELECT SUM(assignedtranstotal.zbst_total) FROM '.$ZBSCRM_t['transactions'].' assignedtranstotal WHERE assignedtranstotal.ID IN '; $extraSelect .= '(SELECT DISTINCT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks'].' WHERE zbsol_objtype_from = '.ZBS_TYPE_TRANSACTION.' AND zbsol_objtype_to = '.ZBS_TYPE_INVOICE.' AND zbsol_objid_to IN '; $extraSelect .= '(SELECT DISTINCT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks'].' WHERE zbsol_objtype_from = '.ZBS_TYPE_INVOICE.' AND zbsol_objtype_to = '.ZBS_TYPE_CONTACT.' AND zbsol_objid_to = contact.ID)'; $extraSelect .= ')'.$transStatusQueryAdd.') as transactions_paid_total'; } // ==== / TOTAL VALUES $selector = 'contact.*'; if (isset($fields) && is_array($fields)) { $selector = ''; // always needs id, so add if not present if (!in_array('ID',$fields)) $selector = 'contact.ID'; foreach ($fields as $f) { if (!empty($selector)) $selector .= ','; $selector .= 'contact.'.$f; } } else if ($onlyID){ $selector = 'contact.ID'; } #} ============ / PRE-QUERY =========== #} Build query $query = "SELECT ".$selector.$extraSelect." FROM ".$ZBSCRM_t['contacts'].' as contact'; #} ============= WHERE ================ if (!empty($id) && $id > 0){ #} Add ID $wheres['ID'] = array('ID','=','%d',$id); } if (!empty($email)){ // where we're seeking the ID from an email we can override the query for performance benefits (#gh-2450): if ( $onlyID ){ $query = 'SELECT contact.ID FROM ( SELECT contact.ID FROM ' . $ZBSCRM_t['contacts'] . ' as contact WHERE zbsc_email = %s UNION ALL SELECT aka_id AS ID FROM ' . $ZBSCRM_t['aka'] . ' WHERE aka_type = 1 AND aka_alias = %s) contact'; $wheres = array( 'direct' => array() ); $params = array( $email, $email ); } else { $emailWheres = array(); #} Add ID $emailWheres['emailcheck'] = array('zbsc_email','=','%s',$email); #} Check AKA $emailWheres['email_alias'] = array('ID','IN',"(SELECT aka_id FROM ".$ZBSCRM_t['aka']." WHERE aka_type = ".ZBS_TYPE_CONTACT." AND aka_alias = %s)",$email); // This generates a query like 'zbsc_email = %s OR zbsc_email2 = %s', // which we then need to include as direct subquery (below) in main query :) $emailSearchQueryArr = $this->buildWheres($emailWheres,'',array(),'OR',false); if (is_array($emailSearchQueryArr) && isset($emailSearchQueryArr['where']) && !empty($emailSearchQueryArr['where'])){ // add it $wheres['direct'][] = array('('.$emailSearchQueryArr['where'].')',$emailSearchQueryArr['params']); } } } if (!empty($WPID) && $WPID > 0){ #} Add ID $wheres['WPID'] = array('zbsc_wpid','=','%d',$WPID); } if (!empty($externalSource) && !empty($externalSourceUID)){ $wheres['extsourcecheck'] = array('ID','IN','(SELECT DISTINCT zbss_objid FROM '.$ZBSCRM_t['externalsources']." WHERE zbss_objtype = ".ZBS_TYPE_CONTACT." AND zbss_source = %s AND zbss_uid = %s)",array($externalSource,$externalSourceUID)); } #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort('ID','DESC') . $this->buildPaging(0,1); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_row($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret Results (ROW) if (isset($potentialRes) && isset($potentialRes->ID)) { #} Has results, tidy + return #} Only ID? return it directly if ($onlyID) return $potentialRes->ID; // tidy if (is_array($fields)){ // guesses fields based on table col names $res = $this->lazyTidyGeneric($potentialRes); } else { // proper tidy $res = $this->tidy_contact($potentialRes,$withCustomFields); } if ($withTags){ // add all tags lines $res['tags'] = $this->DAL()->getTagsForObjID(array('objtypeid'=>ZBS_TYPE_CONTACT,'objid'=>$potentialRes->ID)); } // =================================================== // ========== #} #DB1LEGACY (TOMOVE) // == Following is all using OLD DB stuff, here until we migrate inv etc. // =================================================== #} With most recent log? #DB1LEGACY (TOMOVE) if ($withLastLog){ $res['lastlog'] = $this->DAL()->logs->getLogsForObj(array( 'objtype' => ZBS_TYPE_CONTACT, 'objid' => $potentialRes->ID, 'incMeta' => true, 'sortByField' => 'zbsl_created', 'sortOrder' => 'DESC', 'page' => 0, 'perPage' => 1 )); } #} With Assigned? if ($withOwner){ $res['owner'] = zeroBS_getOwner($potentialRes->ID,true,'zerobs_customer',$potentialRes->zbs_owner); } // Objects: return all, unless $with_obj_limit $objs_page = -1; $objs_per_page = -1; $with_obj_limit = (int)$with_obj_limit; if ( $with_obj_limit > 0 ){ $objs_page = 0; $objs_per_page = $with_obj_limit; } if ($withInvoices){ #} only gets first 100? //DAL3 ver, more perf, gets all $res['invoices'] = $zbs->DAL->invoices->getInvoices(array( 'assignedContact' => $potentialRes->ID, // assigned to company id (int) 'page' => $objs_page, 'perPage' => $objs_per_page, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_INVOICE), 'sortByField' => 'ID', 'sortOrder' => 'DESC', 'withAssigned' => false // no need, it's assigned to this obj already )); } if ($withQuotes){ //DAL3 ver, more perf, gets all $res['quotes'] = $zbs->DAL->quotes->getQuotes(array( 'assignedContact' => $potentialRes->ID, // assigned to company id (int) 'page' => $objs_page, 'perPage' => $objs_per_page, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_QUOTE), 'sortByField' => 'ID', 'sortOrder' => 'DESC', 'withAssigned' => false // no need, it's assigned to this obj already )); } #} ... brutal for mvp #DB1LEGACY (TOMOVE) if ($withTransactions){ //DAL3 ver, more perf, gets all $res['transactions'] = $zbs->DAL->transactions->getTransactions(array( 'assignedContact' => $potentialRes->ID, // assigned to company id (int) 'page' => $objs_page, 'perPage' => $objs_per_page, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_TRANSACTION), 'sortByField' => 'ID', 'sortOrder' => 'DESC', 'withAssigned' => false // no need, it's assigned to this obj already )); } //} #} With co's? if ($withCompanies){ // add all company lines $res['companies'] = $this->DAL()->getObjsLinkedToObj(array( 'objtypefrom' => ZBS_TYPE_CONTACT, // contact 'objtypeto' => ZBS_TYPE_COMPANY, // company 'objfromid' => $potentialRes->ID)); } #} ... brutal for mvp #DB1LEGACY (TOMOVE) if ($withTasks){ //DAL3 ver, more perf, gets all $res['tasks'] = $zbs->DAL->events->getEvents(array( 'assignedContact' => $potentialRes->ID, // assigned to company id (int) 'page' => $objs_page, 'perPage' => $objs_per_page, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_TASK), 'sortByField' => 'zbse_start', 'sortOrder' => 'DESC', 'withAssigned' => false // no need, it's assigned to this obj already )); } // simplistic, could be optimised (though low use means later.) if ( $withExternalSources ){ $res['external_sources'] = $zbs->DAL->contacts->getExternalSourcesForContact(array( 'contactID'=> $potentialRes->ID, 'sortByField' => 'ID', 'sortOrder' => 'ASC', 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership( ZBS_TYPE_CONTACT ) )); } if ( $withExternalSourcesGrouped ){ $res['external_sources'] = $zbs->DAL->getExternalSources( -1, array( 'objectID' => $potentialRes->ID, 'objectType' => ZBS_TYPE_CONTACT, 'grouped_by_source' => true, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership( ZBS_TYPE_CONTACT ) )); } // =================================================== // ========== / #DB1LEGACY (TOMOVE) // =================================================== return $res; } } // / if ID return false; } // TODO $argsOverride=false /** * returns contact detail lines * * @param array $args Associative array of arguments * withQuotes, withInvoices, withTransactions, withLogs, searchPhrase, sortByField, sortOrder, page, perPage * * @return array of contact lines */ public function getContacts($args=array()){ global $zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( // Search/Filtering (leave as false to ignore) 'searchPhrase' => '', // searches which fields? 'inCompany' => false, // will be an ID if used 'inArr' => false, 'quickFilters' => false, 'isTagged' => false, // 1x INT OR array(1,2,3) 'isNotTagged' => false, // 1x INT OR array(1,2,3) 'ownedBy' => false, 'externalSource' => false, // e.g. paypal 'olderThan' => false, // uts 'newerThan' => false, // uts 'hasStatus' => false, // Lead (this takes over from the quick filter post 19/6/18) 'otherStatus' => false, // status other than 'Lead' // last contacted 'contactedBefore' => false, // uts 'contactedAfter' => false, // uts // email 'hasEmail' => false, // 'x@y.com' either in main field or as AKA // addr 'inCounty' => false, // Hertfordshire 'inPostCode' => false, // AL1 1AA 'inCountry' => false, // United Kingdom 'notInCounty' => false, // Hertfordshire 'notInPostCode' => false, // AL1 1AA 'notInCountry' => false, // United Kingdom // generic assignments - requires both // Where the link relationship is OBJECT -> CONTACT 'hasObjIDLinkedTo' => false, // e.g. quoteid 123 'hasObjTypeLinkedTo' => false, // e.g. ZBS_TYPE_QUOTE // generic assignments - requires both // Where the link relationship is CONTACT -> OBJECT 'isLinkedToObjID' => false, // e.g. quoteid 123 'isLinkedToObjType' => false, // e.g. ZBS_TYPE_QUOTE // returns 'count' => false, 'onlyObjTotals' => false, // if passed, returns for group: 'total' 'invoices_total' 'transactions_total' etc. (requires getting a lot of objs, use sparingly) 'withCustomFields' => true, 'withQuotes' => false, 'withInvoices' => false, 'withTransactions' => false, 'withTasks' => false, 'withLogs' => false, 'withLastLog' => false, 'withTags' => false, 'withOwner' => false, 'withAssigned' => false, // return ['company'] objs if has link 'withDND' => false, // if true, returns getContactDoNotMail as well :) 'simplified' => false, // returns just id,name,created,email (for typeaheads) 'withValues' => false, // if passed, returns with 'total' 'invoices_total' 'transactions_total' etc. (requires getting all obj, use sparingly) 'onlyColumns' => false, // if passed (array('fname','lname')) will return only those columns (overwrites some other 'return' options). NOTE: only works for base fields (not custom fields) 'withAliases' => false, 'withExternalSources' => false, 'withExternalSourcesGrouped' => false, 'sortByField' => 'ID', 'sortOrder' => 'ASC', 'page' => 0, // this is what page it is (gets * by for limit) 'perPage' => 100, // permissions 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT), // this'll let you not-check the owner of obj // 'argsOverride' => ?? Still req? // specifics // NOTE: this is ONLY for use where a sql query is 1 time use, otherwise add as argument // ... for later use, (above) // PLEASE do not use the or switch without discussing case with WH 'additionalWhereArr' => false, 'whereCase' => 'AND' // DEFAULT = AND ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= global $ZBSCRM_t,$wpdb,$zbs; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); $joinQ = ''; $extraSelect = ''; #} ============= PRE-QUERY ============ #} Capitalise this $sortOrder = strtoupper($sortOrder); if ( ! in_array( $sortOrder, array( 'ASC', 'DESC' ) ) ) { $sortOrder = 'ASC'; } // If just count or simplified, turn off any extras if ( $count || $simplified || $onlyObjTotals ) { $withCustomFields = false; $withQuotes = false; $withInvoices = false; $withTransactions = false; $withTasks = false; $withLogs = false; $withLastLog = false; $withTags = false; $withOwner = false; $withAssigned = false; $withDND = false; $withAliases = false; $withExternalSources = false; $withExternalSourcesGrouped = false; } #} If onlyColumns, validate if ($onlyColumns){ #} onlyColumns build out a field arr if (is_array($onlyColumns) && count($onlyColumns) > 0){ $onlyColumnsFieldArr = array(); foreach ($onlyColumns as $col){ // find db col key from field key (e.g. fname => zbsc_fname) $dbCol = ''; if (isset($this->objectModel[$col]) && isset($this->objectModel[$col]['fieldname'])) $dbCol = $this->objectModel[$col]['fieldname']; if (!empty($dbCol)){ $onlyColumnsFieldArr[$dbCol] = $col; } } } // if legit cols: if (isset($onlyColumnsFieldArr) && is_array($onlyColumnsFieldArr) && count($onlyColumnsFieldArr) > 0){ $onlyColumns = true; // If onlyColumns, turn off extras $withCustomFields = false; $withQuotes = false; $withInvoices = false; $withTransactions = false; $withTasks = false; $withLogs = false; $withLastLog = false; $withTags = false; $withOwner = false; $withAssigned = false; $withDND = false; $withAliases = false; $withExternalSources = false; $withExternalSourcesGrouped = false; } else { // deny $onlyColumns = false; } } #} Custom Fields if ($withCustomFields){ #} Retrieve any cf $custFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_CONTACT)); #} Cycle through + build into query if (is_array($custFields)) foreach ($custFields as $cK => $cF){ // custom field (e.g. 'third name') it'll be passed here as 'third-name' // ... problem is mysql does not like that :) so we have to chage here: // in this case we prepend cf's with cf_ and we switch - for _ $cKey = 'cf_'.str_replace('-','_',$cK); // we also check the $sortByField in case that's the same cf if ($cK == $sortByField){ // sort by $sortByField = $cKey; // check if sort needs any CAST (e.g. numeric): $sortByField = $this->DAL()->build_custom_field_order_by_str( $sortByField, $cF ); } // add as subquery $extraSelect .= ',(SELECT zbscf_objval FROM '.$ZBSCRM_t['customfields']." WHERE zbscf_objid = contact.ID AND zbscf_objkey = %s AND zbscf_objtype = %d LIMIT 1) ".$cKey; // add params $params[] = $cK; $params[] = ZBS_TYPE_CONTACT; } } #} Aliases if ($withAliases){ #} Retrieve these as a CSV :) $extraSelect .= ',(SELECT ' . $this->DAL()->build_group_concat( 'aka_alias', ',' ) . ' FROM ' . $ZBSCRM_t['aka'] . ' WHERE aka_type = ' . ZBS_TYPE_CONTACT . ' AND aka_id = contact.ID) aliases'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } // Add any addr custom fields for addr1+addr2 // no need if simpliefied or count parameters passed if ( !$simplified && !$count && !$onlyColumns && !$onlyObjTotals ){ $addrCustomFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_ADDRESS)); if (is_array($addrCustomFields) && count($addrCustomFields) > 0){ foreach ($addrCustomFields as $cK => $cF){ // custom field key $cfKey = 'addr_'.$cK; $cfKey2 = 'secaddr_'.$cK; // address custom field (e.g. 'house name') it'll be passed here as 'house-name' // ... problem is mysql does not like that :) so we have to chage here: // in this case we prepend address cf's with addr_ and we switch - for _ $cKey = 'addrcf_'.str_replace('-','_',$cK); $cKey2 = 'secaddrcf_'.str_replace('-','_',$cK); // we also check the $sortByField in case that's the same cf (contacts need the prefix 'zbsc_' :rolls-eyes:) if ('zbsc_'.$cfKey == $sortByField) $sortByField = $cKey; if ('zbsc_'.$cfKey2 == $sortByField) $sortByField = $cKey2; // addr 1 // add as subquery $extraSelect .= ',(SELECT zbscf_objval FROM '.$ZBSCRM_t['customfields']." WHERE zbscf_objid = contact.ID AND zbscf_objkey = %s AND zbscf_objtype = %d) ".$cKey; // add params $params[] = $cfKey; $params[] = ZBS_TYPE_CONTACT; // addr 2 // add as subquery $extraSelect .= ',(SELECT zbscf_objval FROM '.$ZBSCRM_t['customfields']." WHERE zbscf_objid = contact.ID AND zbscf_objkey = %s AND zbscf_objtype = %d) ".$cKey2; // add params $params[] = $cfKey2; $params[] = ZBS_TYPE_CONTACT; } } } // ==== TOTAL VALUES // If we're sorting by total value, we need the values if ( $sortByField === 'totalvalue' ) { $withValues = true; } // Calculate total vals etc. with SQL if ( !$simplified && !$count && $withValues && !$onlyColumns ){ // arguably, if getting $withInvoices etc. may be more performant to calc this in php in AFTER loop, // ... for now as a fair guess, this'll be most performant: // ... we calc total by adding invs + trans below :) // only include transactions with statuses which should be included in total value: $transStatusQueryAdd = $this->DAL()->transactions->getTransactionStatusesToIncludeQuery(); // include invoices without deleted status in the total value for invoices_total_inc_deleted: $inv_status_query_add = $this->DAL()->invoices->get_invoice_status_except_deleted_for_query(); // quotes: $extraSelect .= ',(SELECT SUM(quotestotal.zbsq_value) FROM '.$ZBSCRM_t['quotes'].' as quotestotal WHERE quotestotal.ID IN (SELECT DISTINCT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = ".ZBS_TYPE_QUOTE." AND zbsol_objtype_to = ".ZBS_TYPE_CONTACT." AND zbsol_objid_to = contact.ID)) as quotes_total"; // invs: $extraSelect .= ',(SELECT IFNULL(SUM(invstotal.zbsi_total),0) FROM ' . $ZBSCRM_t['invoices'] . ' as invstotal WHERE invstotal.ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_INVOICE . ' AND zbsol_objtype_to = ' . ZBS_TYPE_CONTACT . ' AND zbsol_objid_to = contact.ID)' . $inv_status_query_add . ') as invoices_total'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // invs including deleted: $extraSelect .= ',(SELECT SUM(invstotalincdeleted.zbsi_total) FROM ' . $ZBSCRM_t['invoices'] . ' as invstotalincdeleted WHERE invstotalincdeleted.ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_INVOICE . ' AND zbsol_objtype_to = ' . ZBS_TYPE_CONTACT . ' AND zbsol_objid_to = contact.ID)) as invoices_total_inc_deleted'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // invs count: $extraSelect .= ',(SELECT COUNT(ID) FROM ' . $ZBSCRM_t['invoices'] . ' WHERE ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_INVOICE . ' AND zbsol_objtype_to = ' . ZBS_TYPE_CONTACT . ' AND zbsol_objid_to = contact.ID)' . $inv_status_query_add . ') as invoices_count'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // invs count including deleted: $extraSelect .= ',(SELECT COUNT(ID) FROM ' . $ZBSCRM_t['invoices'] . ' WHERE ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_INVOICE . ' AND zbsol_objtype_to = ' . ZBS_TYPE_CONTACT . ' AND zbsol_objid_to = contact.ID)) as invoices_count_inc_deleted'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // trans (with status): $extraSelect .= ',(SELECT SUM(transtotal.zbst_total) FROM '.$ZBSCRM_t['transactions'].' as transtotal WHERE transtotal.ID IN (SELECT DISTINCT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = ".ZBS_TYPE_TRANSACTION." AND zbsol_objtype_to = ".ZBS_TYPE_CONTACT." AND zbsol_objid_to = contact.ID)".$transStatusQueryAdd.") as transactions_total"; // paid balance against invs (also in getContact) // (this allows us to subtract from totals to get a true figure where transactions are part/whole payments for invs) /* This selects transactions where there is a link to an invoice where that invoice has a link to this contact: ========== SELECT * FROM wp_zbs_transactions trans WHERE trans.ID IN ( SELECT DISTINCT zbsol_objid_from FROM `wp_zbs_object_links` WHERE zbsol_objtype_from = 5 AND zbsol_objtype_to = 4 AND zbsol_objid_to IN ( SELECT DISTINCT zbsol_objid_from FROM `wp_zbs_object_links` WHERE zbsol_objtype_from = 4 AND zbsol_objtype_to = 1 AND zbsol_objid_to = 1 ) ) */ $extraSelect .= ',(SELECT SUM(assignedtranstotal.zbst_total) FROM '.$ZBSCRM_t['transactions'].' assignedtranstotal WHERE assignedtranstotal.ID IN '; $extraSelect .= '(SELECT DISTINCT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks'].' WHERE zbsol_objtype_from = '.ZBS_TYPE_TRANSACTION.' AND zbsol_objtype_to = '.ZBS_TYPE_INVOICE.' AND zbsol_objid_to IN '; $extraSelect .= '(SELECT DISTINCT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks'].' WHERE zbsol_objtype_from = '.ZBS_TYPE_INVOICE.' AND zbsol_objtype_to = '.ZBS_TYPE_CONTACT.' AND zbsol_objid_to = contact.ID)'; $extraSelect .= ')'.$transStatusQueryAdd.') as transactions_paid_total'; } // ==== / TOTAL VALUES if ($withDND){ // add as subquery $extraSelect .= ',(SELECT zbsm_val FROM '.$ZBSCRM_t['meta']." WHERE zbsm_objid = contact.ID AND zbsm_key = %s AND zbsm_objtype = ".ZBS_TYPE_CONTACT." LIMIT 1) dnd"; // add params $params[] = 'do-not-email'; } #} ============ / PRE-QUERY =========== #} Build query $query = "SELECT contact.*".$extraSelect." FROM ".$ZBSCRM_t['contacts'].' as contact'.$joinQ; #} Count override if ($count) $query = "SELECT COUNT(contact.ID) FROM ".$ZBSCRM_t['contacts'].' as contact'.$joinQ; #} simplified override if ($simplified) $query = "SELECT contact.ID as id,CONCAT(contact.zbsc_fname,\" \",contact.zbsc_lname) as name,contact.zbsc_created as created, contact.zbsc_email as email FROM ".$ZBSCRM_t['contacts'].' as contact'.$joinQ; #} onlyColumns override if ($onlyColumns && is_array($onlyColumnsFieldArr) && count($onlyColumnsFieldArr) > 0){ $columnStr = ''; foreach ($onlyColumnsFieldArr as $colDBKey => $colStr){ if (!empty($columnStr)) $columnStr .= ','; // this presumes str is db-safe? could do with sanitation? $columnStr .= $colDBKey; } $query = "SELECT ".$columnStr." FROM ".$ZBSCRM_t['contacts'].' as contact'.$joinQ; } #} ============= WHERE ================ #} Add Search phrase if (!empty($searchPhrase)){ // inefficient searching all fields. Maybe get settings from user "which fields to search" // ... and auto compile for each contact ahead of time $searchWheres = array(); $searchWheres['search_fullname'] = array('CONCAT(zbsc_prefix, " ", zbsc_fname, " ", zbsc_lname)','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_fname'] = array('zbsc_fname','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_lname'] = array('zbsc_lname','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_email'] = array('zbsc_email','LIKE','%s','%'.$searchPhrase.'%'); // address elements $searchWheres['search_addr1'] = array('zbsc_addr1','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_addr2'] = array('zbsc_addr2','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_city'] = array('zbsc_city','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_county'] = array('zbsc_county','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_country'] = array('zbsc_country','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_postcode'] = array('zbsc_postcode','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_secaddr1'] = array('zbsc_secaddr1','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_secaddr2'] = array('zbsc_secaddr2','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_seccity'] = array('zbsc_seccity','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_seccounty'] = array('zbsc_seccounty','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_seccountry'] = array('zbsc_seccountry','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_secpostcode'] = array('zbsc_secpostcode','LIKE','%s','%'.$searchPhrase.'%'); // social $searchWheres['search_tw'] = array('zbsc_tw','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_li'] = array('zbsc_li','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_fb'] = array('zbsc_fb','LIKE','%s','%'.$searchPhrase.'%'); // phones // ultimately when search is refactored, we should probably store the "clean" version of the phone numbers in the database $searchWheres['search_hometel'] = array('REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(zbsc_hometel," ",""),".",""),"-",""),"(",""),")","")','LIKE','%s','%'.(str_replace(array(' ','.','-','(',')'),'',$searchPhrase)).'%'); $searchWheres['search_worktel'] = array('REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(zbsc_worktel," ",""),".",""),"-",""),"(",""),")","")','LIKE','%s','%'.(str_replace(array(' ','.','-','(',')'),'',$searchPhrase)).'%'); $searchWheres['search_mobtel'] = array('REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(zbsc_mobtel," ",""),".",""),"-",""),"(",""),")","")','LIKE','%s','%'.(str_replace(array(' ','.','-','(',')'),'',$searchPhrase)).'%'); // We also add this, which finds AKA emails if using email $searchWheres['search_alias'] = array('ID','IN',"(SELECT aka_id FROM ".$ZBSCRM_t['aka']." WHERE aka_type = ".ZBS_TYPE_CONTACT." AND aka_alias = %s)",$searchPhrase); // 2.99.9.11 - Added ability to search custom fields (optionally) $customFieldSearch = zeroBSCRM_getSetting('customfieldsearch'); if ($customFieldSearch == 1){ // simplistic add // NOTE: This IGNORES ownership of custom field lines. // use FULLTEXT index if available (MySQL 5.6+), otherwise use fallback if ( jpcrm_migration_table_has_index( $ZBSCRM_t['customfields'], 'search' ) ) { $searchWheres['search_customfields'] = array('ID','IN',"(SELECT zbscf_objid FROM ".$ZBSCRM_t['customfields']." WHERE MATCH(zbscf_objval) AGAINST(%s) AND zbscf_objtype = ".ZBS_TYPE_CONTACT.")",$searchPhrase); } else { $searchWheres['search_customfields'] = array('ID','IN',"(SELECT zbscf_objid FROM ".$ZBSCRM_t['customfields']." WHERE zbscf_objval LIKE %s AND zbscf_objtype = ".ZBS_TYPE_CONTACT.")",'%'.$searchPhrase.'%'); } } // also search "company name" where assigned $b2bMode = zeroBSCRM_getSetting('companylevelcustomers'); // OWNERSHIP TODO - next query doesn't USE OWNERSHIP!!!!: if ($b2bMode == 1) $searchWheres['incompanywithname'] = array('ID','IN','(SELECT DISTINCT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = ".ZBS_TYPE_CONTACT." AND zbsol_objtype_to = ".ZBS_TYPE_COMPANY." AND zbsol_objid_to IN (SELECT ID FROM ".$ZBSCRM_t['companies']." WHERE zbsco_name LIKE %s))",'%'.$searchPhrase.'%'); // This generates a query like 'zbsc_fname LIKE %s OR zbsc_lname LIKE %s', // which we then need to include as direct subquery (below) in main query :) $searchQueryArr = $this->buildWheres($searchWheres,'',array(),'OR',false); if (is_array($searchQueryArr) && isset($searchQueryArr['where']) && !empty($searchQueryArr['where'])){ // add it $wheres['direct'][] = array('('.$searchQueryArr['where'].')',$searchQueryArr['params']); } } #} In company? #DB1LEGACY (TOMOVE -> where) if (!empty($inCompany) && $inCompany > 0){ // would never hard-type this in (would make generic as in buildWPMetaQueryWhere) // but this is only here until MIGRATED to db2 globally //$wheres['incompany'] = array('ID','IN','(SELECT DISTINCT post_id FROM '.$wpdb->prefix."postmeta WHERE meta_key = 'zbs_company' AND meta_value = %d)",$inCompany); // Use obj links now $wheres['incompany'] = array('ID','IN','(SELECT DISTINCT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = ".ZBS_TYPE_CONTACT." AND zbsol_objtype_to = ".ZBS_TYPE_COMPANY." AND zbsol_objid_to = %d)",$inCompany); } #} In array (if inCompany passed, this'll currently overwrite that?! (todo2.5)) if (is_array($inArr) && count($inArr) > 0){ // clean for ints $inArrChecked = array(); foreach ($inArr as $x){ $inArrChecked[] = (int)$x; } // add where $wheres['inarray'] = array('ID','IN','('.implode(',',$inArrChecked).')'); } #} Owned by if (!empty($ownedBy) && $ownedBy > 0){ // would never hard-type this in (would make generic as in buildWPMetaQueryWhere) // but this is only here until MIGRATED to db2 globally //$wheres['incompany'] = array('ID','IN','(SELECT DISTINCT post_id FROM '.$wpdb->prefix."postmeta WHERE meta_key = 'zbs_company' AND meta_value = %d)",$inCompany); // Use obj links now $wheres['ownedBy'] = array('zbs_owner','=','%s',$ownedBy); } // External sources if ( !empty( $externalSource ) ){ // NO owernship built into this, check when roll out multi-layered ownsership $wheres['externalsource'] = array('ID','IN','(SELECT DISTINCT zbss_objid FROM '.$ZBSCRM_t['externalsources']." WHERE zbss_objtype = ".ZBS_TYPE_CONTACT." AND zbss_source = %s)",$externalSource); } // quick addition for mike #} olderThan if (!empty($olderThan) && $olderThan > 0 && $olderThan !== false) $wheres['olderThan'] = array('zbsc_created','<=','%d',$olderThan); #} newerThan if (!empty($newerThan) && $newerThan > 0 && $newerThan !== false) $wheres['newerThan'] = array('zbsc_created','>=','%d',$newerThan); // status if (!empty($hasStatus) && $hasStatus !== false) $wheres['hasStatus'] = array('zbsc_status','=','%s',$hasStatus); if (!empty($otherStatus) && $otherStatus !== false) $wheres['otherStatus'] = array('zbsc_status','<>','%s',$otherStatus); #} contactedBefore if (!empty($contactedBefore) && $contactedBefore > 0 && $contactedBefore !== false) $wheres['contactedBefore'] = array('zbsc_lastcontacted','<=','%d',$contactedBefore); #} contactedAfter if (!empty($contactedAfter) && $contactedAfter > 0 && $contactedAfter !== false) $wheres['contactedAfter'] = array('zbsc_lastcontacted','>=','%d',$contactedAfter); #} hasEmail if (!empty($hasEmail) && !empty($hasEmail) && $hasEmail !== false) { $wheres['hasEmail'] = array('zbsc_email','=','%s',$hasEmail); $wheres['hasEmailAlias'] = array('ID','IN',"(SELECT aka_id FROM ".$ZBSCRM_t['aka']." WHERE aka_type = ".ZBS_TYPE_CONTACT." AND aka_alias = %s)",$hasEmail); } #} inCounty if (!empty($inCounty) && !empty($inCounty) && $inCounty !== false) { $wheres['inCounty'] = array('zbsc_county','=','%s',$inCounty); $wheres['inCountyAddr2'] = array('zbsc_secaddrcounty','=','%s',$inCounty); } #} inPostCode if (!empty($inPostCode) && !empty($inPostCode) && $inPostCode !== false) { $wheres['inPostCode'] = array('zbsc_postcode','=','%s',$inPostCode); $wheres['inPostCodeAddr2'] = array('zbsc_secaddrpostcode','=','%s',$inPostCode); } #} inCountry if (!empty($inCountry) && !empty($inCountry) && $inCountry !== false) { $wheres['inCountry'] = array('zbsc_country','=','%s',$inCountry); $wheres['inCountryAddr2'] = array('zbsc_secaddrcountry','=','%s',$inCountry); } #} notInCounty if (!empty($notInCounty) && !empty($notInCounty) && $notInCounty !== false) { $wheres['notInCounty'] = array('zbsc_county','<>','%s',$notInCounty); $wheres['notInCountyAddr2'] = array('zbsc_secaddrcounty','<>','%s',$notInCounty); } #} notInPostCode if (!empty($notInPostCode) && !empty($notInPostCode) && $notInPostCode !== false) { $wheres['notInPostCode'] = array('zbsc_postcode','<>','%s',$notInPostCode); $wheres['notInPostCodeAddr2'] = array('zbsc_secaddrpostcode','<>','%s',$notInPostCode); } #} notInCountry if (!empty($notInCountry) && !empty($notInCountry) && $notInCountry !== false) { $wheres['notInCountry'] = array('zbsc_country','<>','%s',$notInCountry); $wheres['notInCountryAddr2'] = array('zbsc_secaddrcountry','<>','%s',$notInCountry); } // generic obj links, e.g. quotes, invs, trans // e.g. contact(s) assigned to inv 123 // Where the link relationship is OBJECT -> CONTACT if (!empty($hasObjIDLinkedTo) && $hasObjIDLinkedTo !== false && $hasObjIDLinkedTo > 0 && !empty($hasObjTypeLinkedTo) && $hasObjTypeLinkedTo !== false && $hasObjTypeLinkedTo > 0) { $wheres['hasObjIDLinkedTo'] = array('ID','IN','(SELECT zbsol_objid_to FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = %d AND zbsol_objtype_to = ".ZBS_TYPE_CONTACT." AND zbsol_objid_from = %d AND zbsol_objid_to = contact.ID)",array($hasObjTypeLinkedTo,$hasObjIDLinkedTo)); } // generic obj links, e.g. companies // Where the link relationship is CONTACT -> OBJECT if (!empty($isLinkedToObjID) && $isLinkedToObjID !== false && $isLinkedToObjID > 0 && !empty($isLinkedToObjType) && $isLinkedToObjType !== false && $isLinkedToObjType > 0) { $wheres['isLinkedToObjID'] = array('ID','IN','(SELECT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = ".ZBS_TYPE_CONTACT." AND zbsol_objtype_to = %d AND zbsol_objid_from = contact.ID AND zbsol_objid_to = %d)",array($isLinkedToObjType,$isLinkedToObjID)); } #} Any additionalWhereArr? if (isset($additionalWhereArr) && is_array($additionalWhereArr) && count($additionalWhereArr) > 0){ // add em onto wheres (note these will OVERRIDE if using a key used above) // Needs to be multi-dimensional $wheres = array_merge($wheres,$additionalWhereArr); $wheres = array_merge_recursive($wheres,$additionalWhereArr); } #} Quick filters - adapted from DAL1 (probs can be slicker) if (is_array($quickFilters) && count($quickFilters) > 0){ // cycle through foreach ($quickFilters as $qFilter){ // where status = x // USE hasStatus above now... if ( str_starts_with( $qFilter, 'status_' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $quick_filter_status = substr( $qFilter, 7 ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $wheres['quickfilterstatus'] = array( 'zbsc_status', '=', 'convert(%s using utf8mb4) collate utf8mb4_bin', $quick_filter_status ); } elseif ( $qFilter === 'assigned_to_me' ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $wheres['assigned_to_me'] = array( 'zbs_owner', '=', zeroBSCRM_user() ); } elseif ( $qFilter === 'not_assigned' ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $wheres['not_assigned'] = array( 'zbs_owner', '<=', '0' ); } elseif ( str_starts_with( $qFilter, 'notcontactedin' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // check $notcontactedinDays = (int)substr($qFilter,14); $notcontactedinDaysSeconds = $notcontactedinDays*86400; $wheres['notcontactedinx'] = array('zbsc_lastcontacted','<','%d',time()-$notcontactedinDaysSeconds); } elseif ( str_starts_with( $qFilter, 'olderthan' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // check $olderThanDays = (int)substr($qFilter,9); $olderThanDaysSeconds = $olderThanDays*86400; $wheres['olderthanx'] = array('zbsc_created','<','%d',time()-$olderThanDaysSeconds); } elseif ( str_starts_with( $qFilter, 'segment_' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // a SEGMENT $qFilterSegmentSlug = substr($qFilter,8); #} Retrieve segment + conditions $segment = $this->DAL()->segments->getSegmentBySlug($qFilterSegmentSlug,true,false); $conditions = array(); if (isset($segment['conditions'])) $conditions = $segment['conditions']; $matchType = 'all'; if (isset($segment['matchtype'])) $matchType = $segment['matchtype']; // retrieve getContacts arguments from a list of segment conditions // as at launch of segments (26/6/18) - these are all $additionalWhere args // ... if it stays that way, this is nice and simple, so going to proceed with that. // be aware if $this->segmentConditionArgs() changes, will affect this. $contactGetArgs = $this->DAL()->segments->segmentConditionsToArgs($conditions,$matchType); // as at above, contactGetArgs should have this: if (isset($contactGetArgs['additionalWhereArr']) && is_array($contactGetArgs['additionalWhereArr'])){ // This was required to work with OR and AND situs, along with the usual getContacts vars as well // ----------------------- // match type ALL is default, this switches to ANY $segmentOperator = 'AND'; if ($matchType == 'one') $segmentOperator = 'OR'; // This generates a query like 'zbsc_fname LIKE %s OR/AND zbsc_lname LIKE %s', // which we then need to include as direct subquery (below) in main query :) $segmentQueryArr = $this->buildWheres($contactGetArgs['additionalWhereArr'],'',array(),$segmentOperator,false); if (is_array($segmentQueryArr) && isset($segmentQueryArr['where']) && !empty($segmentQueryArr['where'])){ // add it $wheres['direct'][] = array('('.$segmentQueryArr['where'].')',$segmentQueryArr['params']); } // ----------------------- // following didn't work for OR situations: (worked for most situations though, is a shame) // ----------------------- // so we MERGE that into our wheres... :o // this'll override any settings above. // Needs to be multi-dimensional //$wheres = array_merge_recursive($wheres,$contactGetArgs['additionalWhereArr']); // ----------------------- } } else { // normal/hardtyped switch ($qFilter){ case 'lead': // hack "leads only" - adapted from DAL1 (probs can be slicker) $wheres['quickfilterlead'] = array('zbsc_status','LIKE','%s','Lead'); break; case 'customer': // hack - adapted from DAL1 (probs can be slicker) $wheres['quickfiltercustomer'] = array( 'zbsc_status', 'LIKE', '%s', 'Customer' ); break; default: // if we've hit no filter query, let external logic hook in to provide alternatives // First used in WooSync module $wheres = apply_filters( 'jpcrm_contact_query_quickfilter', $wheres, $qFilter ); break; } // / switch } // / hardtyped } } // / quickfilters #} Is Tagged (expects 1 tag ID OR array) // catch 1 item arr if (is_array($isTagged) && count($isTagged) == 1) $isTagged = $isTagged[0]; if (!is_array($isTagged) && !empty($isTagged) && $isTagged > 0){ // add where tagged // 1 int: $wheres['direct'][] = array('((SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = contact.ID AND zbstl_tagid = %d) > 0)',array(ZBS_TYPE_CONTACT,$isTagged)); } else if (is_array($isTagged) && count($isTagged) > 0){ // foreach in array :) $tagStr = ''; foreach ($isTagged as $iTag){ $i = (int)$iTag; if ($i > 0){ if ($tagStr !== '') $tagStr .','; $tagStr .= $i; } } if (!empty($tagStr)){ $wheres['direct'][] = array('((SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = contact.ID AND zbstl_tagid IN (%s)) > 0)',array(ZBS_TYPE_CONTACT,$tagStr)); } } #} Is NOT Tagged (expects 1 tag ID OR array) // catch 1 item arr if (is_array($isNotTagged) && count($isNotTagged) == 1) $isNotTagged = $isNotTagged[0]; if (!is_array($isNotTagged) && !empty($isNotTagged) && $isNotTagged > 0){ // add where tagged // 1 int: $wheres['direct'][] = array('((SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = contact.ID AND zbstl_tagid = %d) = 0)',array(ZBS_TYPE_CONTACT,$isNotTagged)); } else if (is_array($isNotTagged) && count($isNotTagged) > 0){ // foreach in array :) $tagStr = ''; foreach ($isNotTagged as $iTag){ $i = (int)$iTag; if ($i > 0){ if ($tagStr !== '') $tagStr .','; $tagStr .= $i; } } if (!empty($tagStr)){ $wheres['direct'][] = array('((SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = contact.ID AND zbstl_tagid IN (%s)) = 0)',array(ZBS_TYPE_CONTACT,$tagStr)); } } #} ============ / WHERE =============== #} ============ SORT ============== // latest log // Latest Contact Log (as sort) needs an additional SQL where str: $contact_log_types_str = ''; $sort_function = 'MAX'; if ( $sortOrder !== 'DESC' ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $sort_function = 'MIN'; } if ( $withLastLog ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // retrieve log types to include $contact_log_types = $zbs->DAL->logs->contact_log_types; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase // build sql if ( is_array( $contact_log_types ) ) { // create escaped csv $contact_log_types_str = $this->build_csv( $contact_log_types ); } } // include invoices without deleted status in the total value for invoices_total_inc_deleted: $inv_status_query_add = $this->DAL()->invoices->get_invoice_status_except_deleted_for_query(); // Mapped sorts // This catches listview and other specific sort cases // Note: Prefix here is a legacy leftover from the fact the AJAX List view retrieve goes through zeroBS_getCustomers() which prefixes zbsc_ $sort_map = array( 'zbsc_id' => 'ID', 'zbsc_owner' => 'zbs_owner', 'zbsc_zbs_owner' => 'zbs_owner', // company (name) 'zbsc_company' => '(SELECT zbsco_name FROM ' . $ZBSCRM_t['companies'] . ' WHERE ID IN (SELECT DISTINCT zbsol_objid_to FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_CONTACT . ' AND zbsol_objtype_to = ' . ZBS_TYPE_COMPANY . ' AND zbsol_objid_from = contact.ID) ORDER BY zbsco_name ' . $sortOrder . ' LIMIT 0,1)', // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // sort by subquery: Logs // sort by latest log is effectively 'sort by last log added' 'zbsc_latestlog' => '(SELECT ' . $sort_function . '(zbsl_created) FROM ' . $ZBSCRM_t['logs'] . ' WHERE zbsl_objid = contact.ID AND zbsl_objtype = ' . ZBS_TYPE_CONTACT . ')', // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // sort by latest contact log is effectively 'sort by last contact log added' (requires $withLastLog = true) 'zbsc_lastcontacted' => '(SELECT ' . $sort_function . '(zbsl_created) FROM ' . $ZBSCRM_t['logs'] . ' WHERE zbsl_objid = contact.ID AND zbsl_objtype = ' . ZBS_TYPE_CONTACT . ' AND zbsl_type IN (' . $contact_log_types_str . '))', // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // has & counts (same queries) // phpcs:disable WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase 'zbsc_hasquote' => '(SELECT COUNT(ID) FROM ' . $ZBSCRM_t['quotes'] . ' WHERE ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_QUOTE . ' AND zbsol_objtype_to = ' . ZBS_TYPE_CONTACT . ' AND zbsol_objid_to = contact.ID))', 'zbsc_hasinvoice' => '(SELECT COUNT(ID) FROM ' . $ZBSCRM_t['invoices'] . ' WHERE ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_INVOICE . ' AND zbsol_objtype_to = ' . ZBS_TYPE_CONTACT . ' AND zbsol_objid_to = contact.ID))', 'zbsc_hastransaction' => '(SELECT COUNT(ID) FROM ' . $ZBSCRM_t['transactions'] . ' WHERE ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_TRANSACTION . ' AND zbsol_objtype_to = ' . ZBS_TYPE_CONTACT . ' AND zbsol_objid_to = contact.ID))', 'zbsc_quotecount' => '(SELECT COUNT(ID) FROM ' . $ZBSCRM_t['quotes'] . ' WHERE ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_QUOTE . ' AND zbsol_objtype_to = ' . ZBS_TYPE_CONTACT . ' AND zbsol_objid_to = contact.ID))', 'zbsc_invoicecount_inc_deleted' => '(SELECT COUNT(ID) FROM ' . $ZBSCRM_t['invoices'] . ' WHERE ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_INVOICE . ' AND zbsol_objtype_to = ' . ZBS_TYPE_CONTACT . ' AND zbsol_objid_to = contact.ID))', 'zbsc_invoicecount' => '(SELECT COUNT(ID) FROM ' . $ZBSCRM_t['invoices'] . ' WHERE ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_INVOICE . ' AND zbsol_objtype_to = ' . ZBS_TYPE_CONTACT . ' AND zbsol_objid_to = contact.ID)' . $inv_status_query_add . ')', 'zbsc_transactioncount' => '(SELECT COUNT(ID) FROM ' . $ZBSCRM_t['transactions'] . ' WHERE ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_TRANSACTION . ' AND zbsol_objtype_to = ' . ZBS_TYPE_CONTACT . ' AND zbsol_objid_to = contact.ID))', // phpcs:enable WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // following will only work if obj total value subqueries triggered above ^ 'zbsc_totalvalue' => '((IFNULL(invoices_total,0) + IFNULL(transactions_total,0)) - IFNULL(transactions_paid_total,0))', // custom sort by total invoice value + transaction value - paid transactions (as mimicking tidy_contact php logic into SQL) 'zbsc_transactiontotal' => 'transactions_total', 'zbsc_quotetotal' => 'quotes_total', 'zbsc_invoicetotal' => 'invoices_total', ); // either from $sort_map, or multi-dimensional name search if ( array_key_exists( $sortByField, $sort_map ) ) { $sortByField = $sort_map[ $sortByField ]; } elseif ( $sortByField === 'zbsc_fullname' || $sortByField === 'fullname' ) { $sortByField = array( 'zbsc_lname' => $sortOrder, 'zbsc_fname' => $sortOrder ); } #} ============ / SORT ============== #} CHECK this + reset to default if faulty if (!in_array($whereCase,array('AND','OR'))) $whereCase = 'AND'; #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params,$whereCase); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner,'contact'); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort($sortByField,$sortOrder) . $this->buildPaging($page,$perPage); try { // Prep & run query $queryObj = $this->prepare($query,$params); // Catch count + return if requested if ( $count ) return $wpdb->get_var( $queryObj ); // Totals override if ( $onlyObjTotals ){ $contact_query = "SELECT contact.ID FROM " . $ZBSCRM_t['contacts'] . " AS contact" . $this->buildWhereStr( $whereStr, $additionalWhere ); $contact_query = $this->prepare($contact_query,$params); $query = "SELECT "; if ( zeroBSCRM_getSetting( 'feat_quotes' ) == 1 ){ $query .= "(SELECT SUM(q.zbsq_value) FROM " . $ZBSCRM_t['quotes'] . " AS q INNER JOIN " . $ZBSCRM_t['objlinks'] . " AS ol ON q.ID = ol.zbsol_objid_from WHERE ol.zbsol_objtype_from = " . ZBS_TYPE_QUOTE . " AND ol.zbsol_objtype_to = " . ZBS_TYPE_CONTACT . " AND ol.zbsol_objid_to IN ( " . $contact_query . " )) AS quotes_total"; } if ( zeroBSCRM_getSetting( 'feat_invs' ) == 1 ){ // if previous query, add comma if ( $query !== "SELECT " ){ $query .= ", "; } // include invoices without deleted status in the total value for invoices_total_inc_deleted: $inv_status_query_add = $this->DAL()->invoices->get_invoice_status_except_deleted_for_query(); // phpcs:disable WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $query .= '(SELECT SUM(i.zbsi_total) FROM ' . $ZBSCRM_t['invoices'] . ' AS i INNER JOIN ' . $ZBSCRM_t['objlinks'] . ' AS ol ON i.ID = ol.zbsol_objid_from WHERE ol.zbsol_objtype_from = ' . ZBS_TYPE_INVOICE . ' AND ol.zbsol_objtype_to = ' . ZBS_TYPE_CONTACT . ' AND ol.zbsol_objid_to IN ( ' . $contact_query . ' ) ' . $inv_status_query_add . ') AS invoices_total,'; $query .= '(SELECT SUM(inc_deleted_invoices.zbsi_total) FROM ' . $ZBSCRM_t['invoices'] . ' AS inc_deleted_invoices INNER JOIN ' . $ZBSCRM_t['objlinks'] . ' AS ol ON inc_deleted_invoices.ID = ol.zbsol_objid_from WHERE ol.zbsol_objtype_from = ' . ZBS_TYPE_INVOICE . ' AND ol.zbsol_objtype_to = ' . ZBS_TYPE_CONTACT . ' AND ol.zbsol_objid_to IN ( ' . $contact_query . ' )) AS invoices_total_inc_deleted'; // phpcs:enable WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } if ( zeroBSCRM_getSetting( 'feat_transactions' ) == 1 ){ // if previous query, add comma if ( $query !== "SELECT " ){ $query .= ", "; } // only include transactions with statuses which should be included in total value: $transaction_status_query_addition = $this->DAL()->transactions->getTransactionStatusesToIncludeQuery(); $query .= "(SELECT SUM(t.zbst_total) FROM " . $ZBSCRM_t['transactions'] . " AS t INNER JOIN " . $ZBSCRM_t['objlinks'] . " AS ol ON t.ID = ol.zbsol_objid_from WHERE ol.zbsol_objtype_from = " . ZBS_TYPE_TRANSACTION . " AND ol.zbsol_objtype_to = " . ZBS_TYPE_CONTACT . " AND ol.zbsol_objid_to IN ( " . $contact_query . " ) " . $transaction_status_query_addition . ") AS transactions_total, "; $query .= "(SELECT SUM(assigned_transactions.zbst_total) FROM " . $ZBSCRM_t['transactions'] . " AS assigned_transactions WHERE assigned_transactions.ID IN ( SELECT DISTINCT zbsol_objid_from FROM " . $ZBSCRM_t['objlinks'] . " WHERE zbsol_objtype_from = " . ZBS_TYPE_TRANSACTION . " AND zbsol_objtype_to = " . ZBS_TYPE_INVOICE . " AND zbsol_objid_to IN ( SELECT DISTINCT zbsol_objid_from FROM " . $ZBSCRM_t['objlinks'] . " WHERE zbsol_objtype_from = " . ZBS_TYPE_INVOICE . " AND zbsol_objtype_to = " . ZBS_TYPE_CONTACT . " AND zbsol_objid_to IN ( " . $contact_query . " ) ) )) AS assigned_transactions_total"; } if ( $query !== "SELECT " ){ $totals_data = $wpdb->get_row( $query ); if ( zeroBSCRM_getSetting( 'feat_invs' ) == 1 && zeroBSCRM_getSetting( 'feat_transactions' ) == 1 ){ // calculate a total sum (invoices + unassigned transactions) $totals_data->total_sum = (float)$totals_data->invoices_total + (float)$totals_data->transactions_total - (float)$totals_data->assigned_transactions_total; //total_sum_inc_deleted currently factors in deleted invoices $totals_data->total_sum_inc_deleted = (float) $totals_data->invoices_total_inc_deleted + (float) $totals_data->transactions_total - (float) $totals_data->assigned_transactions_total; } elseif ( zeroBSCRM_getSetting( 'feat_invs' ) == 1 ){ // just include invoices in total $totals_data->total_sum = (float) $totals_data->invoices_total; $totals_data->total_sum_inc_deleted = (float) $totals_data->invoices_total_inc_deleted; } elseif ( zeroBSCRM_getSetting( 'feat_quotes' ) == 1 ){ // just include quotes in total $totals_data->total_sum = (float)$totals_data->quotes_total; } // provide formatted equivilents if ( zeroBSCRM_getSetting( 'feat_quotes' ) == 1 ){ $totals_data->quotes_total_formatted = zeroBSCRM_formatCurrency( $totals_data->quotes_total ); } if ( zeroBSCRM_getSetting( 'feat_invs' ) == 1 ){ $totals_data->invoices_total_formatted = zeroBSCRM_formatCurrency( $totals_data->invoices_total ); } if ( zeroBSCRM_getSetting( 'feat_transactions' ) == 1 ){ $totals_data->transactions_total_formatted = zeroBSCRM_formatCurrency( $totals_data->transactions_total ); $totals_data->assigned_transactions_total_formatted = zeroBSCRM_formatCurrency( $totals_data->assigned_transactions_total ); } if ( isset( $totals_data->total_sum ) ){ $totals_data->total_sum_formatted = zeroBSCRM_formatCurrency( $totals_data->total_sum ); } } else { $totals_data = null; } return $totals_data; } #} else continue.. $potentialRes = $wpdb->get_results($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret results (Result Set - multi-row) if (isset($potentialRes) && is_array($potentialRes) && count($potentialRes) > 0) { #} Has results, tidy + return foreach ($potentialRes as $resDataLine) { #} simplified override if ($simplified){ $resArr = array( 'id' => $resDataLine->id, 'name' => $resDataLine->name, 'created' => $resDataLine->created, 'email' => $resDataLine->email ); } else if ($onlyColumns && is_array($onlyColumnsFieldArr) && count($onlyColumnsFieldArr) > 0){ // only coumns return. $resArr = array(); foreach ($onlyColumnsFieldArr as $colDBKey => $colStr){ if (isset($resDataLine->$colDBKey)) $resArr[$colStr] = $resDataLine->$colDBKey; } } else { // tidy (normal) $resArr = $this->tidy_contact($resDataLine,$withCustomFields); } if ($withTags){ // add all tags lines $resArr['tags'] = $this->DAL()->getTagsForObjID(array('objtypeid'=>ZBS_TYPE_CONTACT,'objid'=>$resDataLine->ID)); } if ($withDND){ // retrieve :) (paranoia mode) $dnd = -1; $potentialDND = $this->stripSlashes($this->decodeIfJSON($resDataLine->dnd)); if ($potentialDND == "1") $dnd = 1; $resArr['dnd'] = $dnd; } // =================================================== // ========== #} #DB1LEGACY (TOMOVE) // == Following is all using OLD DB stuff, here until we migrate inv etc. // =================================================== #} With most recent log? #DB1LEGACY (TOMOVE) if ($withLastLog){ // doesn't return singular, for now using arr $potentialLogs = $this->DAL()->logs->getLogsForObj(array( 'objtype' => ZBS_TYPE_CONTACT, 'objid' => $resDataLine->ID, 'incMeta' => true, 'sortByField' => 'zbsl_created', 'sortOrder' => 'DESC', 'page' => 0, 'perPage' => 1 )); if (is_array($potentialLogs) && count($potentialLogs) > 0) $resArr['lastlog'] = $potentialLogs[0]; // CONTACT logs specifically // doesn't return singular, for now using arr $potentialLogs = $this->DAL()->logs->getLogsForObj( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase array( 'objtype' => ZBS_TYPE_CONTACT, 'objid' => $resDataLine->ID, // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase 'notetypes' => $zbs->DAL->logs->contact_log_types, // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase 'incMeta' => true, 'sortByField' => 'zbsl_created', 'sortOrder' => 'DESC', 'page' => 0, 'perPage' => 1, ) ); if (is_array($potentialLogs) && count($potentialLogs) > 0) $resArr['lastcontactlog'] = $potentialLogs[0]; } #} With Assigned? if ($withOwner){ $resArr['owner'] = zeroBS_getOwner($resDataLine->ID,true,'zerobs_customer',$resDataLine->zbs_owner); } if ($withAssigned){ /* This is for MULTIPLE (e.g. multi companies assigned to a contact) // add all assigned companies $res['companies'] = $this->DAL()->companies->getCompanies(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_INVOICE, 'hasObjIDLinkedTo'=>$resDataLine->ID, 'perPage'=>-1, 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_COMPANY))); .. but we use 1:1, at least now: */ // add all assigned companies $resArr['company'] = $zbs->DAL->companies->getCompanies(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_CONTACT, 'hasObjIDLinkedTo'=>$resDataLine->ID, 'page' => 0, 'perPage'=>1, // FORCES 1 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); } if ($withInvoices){ #} only gets first 100? //DAL3 ver, more perf, gets all $resArr['invoices'] = $zbs->DAL->invoices->getInvoices(array( 'assignedContact' => $resDataLine->ID, // assigned to company id (int) 'page' => -1, 'perPage' => -1, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_INVOICE), 'sortByField' => 'ID', 'sortOrder' => 'DESC' )); } if ($withQuotes){ //DAL3 ver, more perf, gets all $resArr['quotes'] = $zbs->DAL->quotes->getQuotes(array( 'assignedContact' => $resDataLine->ID, // assigned to company id (int) 'page' => -1, 'perPage' => -1, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_QUOTE), 'sortByField' => 'ID', 'sortOrder' => 'DESC' )); } #} ... brutal for mvp #DB1LEGACY (TOMOVE) if ($withTransactions){ //DAL3 ver, more perf, gets all $resArr['transactions'] = $zbs->DAL->transactions->getTransactions(array( 'assignedContact' => $resDataLine->ID, // assigned to company id (int) 'page' => -1, 'perPage' => -1, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_TRANSACTION), 'sortByField' => 'ID', 'sortOrder' => 'DESC' )); } #} ... brutal for mvp #DB1LEGACY (TOMOVE) if ($withTasks){ //DAL3 ver, more perf, gets all $res['tasks'] = $zbs->DAL->events->getEvents(array( 'assignedContact' => $resDataLine->ID, // assigned to company id (int) 'page' => -1, 'perPage' => -1, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_TASK), 'sortByField' => 'zbse_start', 'sortOrder' => 'DESC', 'withAssigned' => false // no need, it's assigned to this obj already )); } // simplistic, could be optimised (though low use means later.) if ( $withExternalSources ){ $res['external_sources'] = $zbs->DAL->contacts->getExternalSourcesForContact(array( 'contactID'=> $resDataLine->ID, 'sortByField' => 'ID', 'sortOrder' => 'ASC', 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership( ZBS_TYPE_CONTACT ) )); } if ( $withExternalSourcesGrouped ){ $res['external_sources'] = $zbs->DAL->getExternalSources( -1, array( 'objectID' => $resDataLine->ID, 'objectType' => ZBS_TYPE_CONTACT, 'grouped_by_source' => true, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership( ZBS_TYPE_CONTACT ) )); } //} // =================================================== // ========== / #DB1LEGACY (TOMOVE) // =================================================== $res[] = $resArr; } } return $res; } /** * adds or updates a contact object * * @param array $args Associative array of arguments * id (if update), owner, data (array of field data) * * @return int line ID */ // Previously DAL->addUpdateContact public function addUpdateContact($args=array()){ global $ZBSCRM_t,$wpdb,$zbs; #} Retrieve any cf $customFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_CONTACT)); $addrCustomFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_ADDRESS)); #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'owner' => -1, // fields (directly) 'data' => array( 'email' => '', // Unique Field ! 'status' => '', 'prefix' => '', 'fname' => '', 'lname' => '', 'addr1' => '', 'addr2' => '', 'city' => '', 'county' => '', 'country' => '', 'postcode' => '', 'secaddr1' => '', 'secaddr2' => '', 'seccity' => '', 'seccounty' => '', 'seccountry' => '', 'secpostcode' => '', 'hometel' => '', 'worktel' => '', 'mobtel' => '', 'wpid' => -1, 'avatar' => '', // social basics :) 'tw' => '', 'fb' => '', 'li' => '', // Note Custom fields may be passed here, but will not have defaults so check isset() // tags 'tags' => -1, // pass an array of tag ids or tag strings 'tag_mode' => 'replace', // replace|append|remove 'externalSources' => -1, // if this is an array(array('source'=>src,'uid'=>uid),multiple()) it'll add :) 'companies' => -1, // array of co id's :) // wh added for later use. 'lastcontacted' => -1, // allow this to be set for MS sync etc. 'created' => -1, // add/update aliases 'aliases' => -1, // array of email strings (will be verified) ), 'limitedFields' => -1, // if this is set it OVERRIDES data (allowing you to set specific fields + leave rest in tact) // ^^ will look like: array(array('key'=>x,'val'=>y,'type'=>'%s')) // this function as DAL1 func did. 'extraMeta' => -1, 'automatorPassthrough' => -1, 'fallBackLog' => -1, 'silentInsert' => false, // this was for init Migration - it KILLS all IA for newContact (because is migrating, not creating new :) this was -1 before 'do_not_update_blanks' => false // this allows you to not update fields if blank (same as fieldoverride for extsource -> in) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } // Needs this to grab custom fields (if passed) too :) if (is_array($customFields)) foreach ($customFields as $cK => $cF){ // only for data, limited fields below if (is_array($data)) { if (isset($args['data'][$cK])) $data[$cK] = $args['data'][$cK]; } } /* NOT REQ: // Needs this to grab custom addr fields (if passed) too :) if (is_array($addrCustomFields)) foreach ($addrCustomFields as $cK => $cF){ // only for data, limited fields below if (is_array($data)) { //if (isset($args['data'][$cK])) $data[$cK] = $args['data'][$cK]; } } */ // this takes limited fields + checks through for custom fields present // (either as key zbsc_source or source, for example) // then switches them into the $data array, for separate update // where this'll fall over is if NO normal contact data is sent to update, just custom fields if (is_array($limitedFields) && is_array($customFields)){ //$customFieldKeys = array_keys($customFields); $newLimitedFields = array(); // cycle through foreach ($limitedFields as $field){ // some weird case where getting empties, so added check if (isset($field['key']) && !empty($field['key'])){ $dePrefixed = ''; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase if ( str_starts_with( $field['key'], 'zbsc_' ) ) { $dePrefixed = substr( $field['key'], strlen( 'zbsc_' ) ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } if (isset($customFields[$field['key']])){ // is custom, move to data $data[$field['key']] = $field['val']; } else if (!empty($dePrefixed) && isset($customFields[$dePrefixed])){ // is custom, move to data $data[$dePrefixed] = $field['val']; } else { // add it to limitedFields (it's not dealt with post-update) $newLimitedFields[] = $field; } } } // move this back in $limitedFields = $newLimitedFields; unset($newLimitedFields); } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ $id = (int)$id; // here we check that the potential owner CAN even own if ( // no owner specified !isset($owner) || // specified owner is not an admin !user_can($owner,'admin_zerobs_usr') ) { $owner = -1; } if (is_array($limitedFields)){ // LIMITED UPDATE (only a few fields.) // phpcs:ignore if ( count( $limitedFields ) === 0 ) { return false; } // REQ. ID too (can only update) if (empty($id) || $id <= 0) return false; } else { // NORMAL, FULL UPDATE // check email + load that user if present if (!isset($data['email']) || empty($data['email'])){ // no email // Allow users without emails? WH removed this for db1->2 migration // leaving this in breaks MIGRATIONS from DAL 1 // in that those contacts without emails will not be copied in // return false; } else { // email present, check if it matches ID? if (!empty($id) && $id > 0){ // if ID + email, check if existing contact with email, (e.g. in use) // ... allow it if the ID of that email contact matches the ID given here // (else e.g. add email x to ID y without checking) $potentialUSERID = (int)$this->getContact(-1,array('email'=>$data['email'],'ignoreOwner'=>1,'onlyID'=>1)); if (!empty($potentialUSERID) && $potentialUSERID > 0 && $id > 0 && $potentialUSERID != $id){ // email doesn't match ID return false; } // also check if has rights?!? Could be just email passed here + therefor got around owner check? hmm. } else { // no ID, check if email present, and then update that user if so $potentialUSERID = (int)$this->getContact(-1,array('email'=>$data['email'],'ignoreOwner'=>1,'onlyID'=>1)); if (isset($potentialUSERID) && !empty($potentialUSERID) && $potentialUSERID > 0) { $id = $potentialUSERID; } } } // companies if (isset($data['companies']) && is_array($data['companies'])){ $coArr = array(); /* there was a bug happening here where same company could get dude at a few times... so for now only use the first company */ /* foreach ($data['companies'] as $c){ $cI = (int)$c; if ($cI > 0 && !in_array($cI, $coArr)) $coArr[] = $cI; }*/ $cI = (int)$data['companies'][0]; if ($cI > 0 && !in_array($cI, $coArr)) $coArr[] = $cI; // reset the main if (count($coArr) > 0) $data['companies'] = $coArr; else $data['companies'] = 'unset'; unset($coArr); } } // If no status passed or previously set, use the default status if ( empty($data['status'] ) ) { // copy any previously set $data['status'] = $this->getContactStatus($id); // if not previously set, use default if (empty($data['status'])) $data['status'] = zeroBSCRM_getSetting('defaultstatus'); } #} ========= / CHECK FIELDS =========== #} ========= OVERRIDE SETTING (Deny blank overrides) =========== // this only functions if externalsource is set (e.g. api/form, etc.) if (isset($data['externalSources']) && is_array($data['externalSources']) && count($data['externalSources']) > 0) { if (zeroBSCRM_getSetting('fieldoverride') == "1"){ $do_not_update_blanks = true; } } // either ext source + setting, or set by the func call if ( $do_not_update_blanks ) { // this setting says 'don't override filled-out data with blanks' // so here we check through any passed blanks + convert to limitedFields // only matters if $id is set (there is somt to update not add if (isset($id) && !empty($id) && $id > 0){ // get data to copy over (for now, this is required to remove 'fullname' etc.) $dbData = $this->db_ready_contact($data); //unset($dbData['id']); // this is unset because we use $id, and is update, so not req. legacy issue //unset($dbData['created']); // this is unset because this uses an obj which has been 'updated' against original details, where created is output in the WRONG format :) $origData = $data; //$data = array(); $limitedData = array(); // array(array('key'=>'zbsc_x','val'=>y,'type'=>'%s')) // cycle through + translate into limitedFields (removing any blanks, or arrays (e.g. externalSources)) // we also have to remake a 'faux' data (removing blanks for tags etc.) for the post-update updates foreach ($dbData as $k => $v){ $intV = (int)$v; // only add if valuenot empty if (!is_array($v) && !empty($v) && $v != '' && $v !== 0 && $v !== -1 && $intV !== -1){ // add to update arr $limitedData[] = array( 'key' => 'zbsc_'.$k, // we have to add zbsc_ here because translating from data -> limited fields 'val' => $v, 'type' => $this->getTypeStr('zbsc_'.$k) ); // add to remade $data for post-update updates $data[$k] = $v; } } // copy over $limitedFields = $limitedData; } // / if ID } // / if do_not_update_blanks // ========= / OVERRIDE SETTING (Deny blank overrides) =========== // ========= BUILD DATA =========== // phpcs:disable WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase -- to be refactoerd later. $update = false; $dataArr = array(); $typeArr = array(); $contactsPreUpdateSegments = array(); if ( is_array( $limitedFields ) ) { // LIMITED FIELDS $update = true; // cycle through foreach ( $limitedFields as $field ) { // some weird case where getting empties, so added check if ( empty( $field['key'] ) ) { continue; } // Created date field is immutable. Skip. if ( $field['key'] === 'zbsc_created' ) { continue; } $dataArr[ $field['key'] ] = $field['val']; $typeArr[] = $field['type']; } // add update time if ( ! isset( $dataArr['zbsc_lastupdated'] ) ) { $dataArr['zbsc_lastupdated'] = time(); $typeArr[] = '%d'; } } else { // FULL UPDATE/INSERT // UPDATE $dataArr = array( 'zbs_owner' => $owner, // phpcs:disable VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable -- to be refactored. // fields 'zbsc_status' => $data['status'], 'zbsc_email' => $data['email'], 'zbsc_prefix' => $data['prefix'], 'zbsc_fname' => $data['fname'], 'zbsc_lname' => $data['lname'], 'zbsc_addr1' => $data['addr1'], 'zbsc_addr2' => $data['addr2'], 'zbsc_city' => $data['city'], 'zbsc_county' => $data['county'], 'zbsc_country' => $data['country'], 'zbsc_postcode' => $data['postcode'], 'zbsc_secaddr1' => $data['secaddr1'], 'zbsc_secaddr2' => $data['secaddr2'], 'zbsc_seccity' => $data['seccity'], 'zbsc_seccounty' => $data['seccounty'], 'zbsc_seccountry' => $data['seccountry'], 'zbsc_secpostcode' => $data['secpostcode'], 'zbsc_hometel' => $data['hometel'], 'zbsc_worktel' => $data['worktel'], 'zbsc_mobtel' => $data['mobtel'], 'zbsc_wpid' => $data['wpid'], 'zbsc_avatar' => $data['avatar'], 'zbsc_tw' => $data['tw'], 'zbsc_fb' => $data['fb'], 'zbsc_li' => $data['li'], 'zbsc_lastupdated' => time(), ); // if set. if ( $data['lastcontacted'] !== -1 ) { $dataArr['zbsc_lastcontacted'] = $data['lastcontacted']; } $typeArr = array( // field data types // '%d', // site // '%d', // team '%d', // owner '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%d', // last updated ); // if set if ( $data['lastcontacted'] !== -1 ) { $typeArr[] = '%d'; } if ( ! empty( $id ) && $id > 0 ) { // is update $update = true; } else { // INSERT (get's few extra :D) $update = false; $dataArr['zbs_site'] = zeroBSCRM_site(); $typeArr[] = '%d'; $dataArr['zbs_team'] = zeroBSCRM_team(); $typeArr[] = '%d'; if ( isset( $data['created'] ) && ! empty( $data['created'] ) && $data['created'] !== -1 ) { $dataArr['zbsc_created'] = $data['created']; $typeArr[] = '%d'; } else { $dataArr['zbsc_created'] = time(); $typeArr[] = '%d'; } $dataArr['zbsc_lastcontacted'] = -1; $typeArr[] = '%d'; } } #} ========= / BUILD DATA =========== #} ============================================================ #} ========= CHECK force_uniques & not_empty & max_len ======== // if we're passing limitedFields we skip these, for now // #v3.1 - would make sense to unique/nonempty check just the limited fields. #gh-145 if (!is_array($limitedFields)){ // verify uniques if (!$this->verifyUniqueValues($data,$id)) return false; // / fails unique field verify // verify not_empty if (!$this->verifyNonEmptyValues($data)) return false; // / fails empty field verify } // whatever we do we check for max_len breaches and abbreviate to avoid wpdb rejections $dataArr = $this->wpdbChecks( $dataArr ); // CHECK force_uniques & not_empty // Check if ID present if ( $update ) { // Check if obj exists (here) - for now just brutal update (will error when doesn't exist) $originalStatus = $this->getContactStatus( $id ); $previous_contact_obj = $this->getContact( $id ); // get any segments (whom counts may be affected by changes) // $contactsPreUpdateSegments = $this->DAL()->segments->getSegmentsContainingContact($id,true); // log any change of status if ( isset( $dataArr['zbsc_status'] ) && ! empty( $dataArr['zbsc_status'] ) && ! empty( $originalStatus ) && $dataArr['zbsc_status'] !== $originalStatus ) { // status change $statusChange = array( 'from' => $originalStatus, 'to' => $dataArr['zbsc_status'], ); } // Attempt update if ($wpdb->update( $ZBSCRM_t['contacts'], $dataArr, array( // where 'ID' => $id ), $typeArr, array( // where data types '%d' )) !== false){ // if passing limitedFields instead of data, we ignore the following // this doesn't work, because data is in args default as arr //if (isset($data) && is_array($data)){ // so... if (!isset($limitedFields) || !is_array($limitedFields) || $limitedFields == -1){ // tags if (isset($data['tags']) && is_array($data['tags'])) { $this->addUpdateContactTags( array( 'id' => $id, 'tag_input' => $data['tags'], 'mode' => $data['tag_mode'] ) ); } // externalSources $approvedExternalSource = $this->DAL()->addUpdateExternalSources( array( 'obj_id' => $id, 'obj_type_id' => ZBS_TYPE_CONTACT, 'external_sources' => isset($data['externalSources']) ? $data['externalSources'] : array(), ) ); // for IA below // co's work? // OBJ LINKS - to companies (1liner now as genericified) $this->addUpdateObjectLinks($id,$data['companies'],ZBS_TYPE_COMPANY); // Aliases // Maintain an array of AKA emails if (isset($data['aliases']) && is_array($data['aliases'])){ $existingAliasesSimple = array(); $existingAliases = zeroBS_getObjAliases(ZBS_TYPE_CONTACT,$id); if (!is_array($existingAliases)) $existingAliases = array(); // compare if (is_array($existingAliases)) foreach ($existingAliases as $alias){ // is this alias in the new list? if (in_array($alias['aka_alias'], $data['aliases'])) { $existingAliasesSimple[] = $alias['aka_alias']; continue; } // it's not in the new list, thus, remove it: // this could be a smidgen more performant if it just deleted the line zeroBS_removeObjAlias(ZBS_TYPE_CONTACT,$id,$alias['aka_alias']); } foreach ($data['aliases'] as $alias){ // valid? if (zeroBS_canUseCustomerAlias($alias)){ // is this alias in the existing list? (nothing to do) if (in_array($alias, $existingAliasesSimple)) continue; // it's not in the existing list, thus, add it: zeroBS_addObjAlias(ZBS_TYPE_CONTACT,$id,$alias); } else { // err - tried to use an invalid alias $msg = __('Could not add alias (unavailable or invalid):','zero-bs-crm').' '.$alias; $zbs->DAL->addError(307,$this->objectType,$msg,$alias); } } } } // / if $data/limitedData // 2.98.1+ ... custom fields should update if present, regardless of limitedData rule // ... UNLESS BLANK! // Custom fields? #} Cycle through + add/update if set if (is_array($customFields)) foreach ($customFields as $cK => $cF){ // any? if (isset($data[$cK])){ // updating blanks? if ($do_not_update_blanks && empty($data[$cK])){ // skip it } else { // it's either not in do_not_update_blank mode, or it has a val // add update $cfID = $this->addUpdateCustomField(array( 'data' => array( 'objtype' => ZBS_TYPE_CONTACT, 'objid' => $id, 'objkey' => $cK, 'objval' => $data[$cK] ))); } } } // Also got to catch any 'addr' custom fields :) if (is_array($addrCustomFields) && count($addrCustomFields) > 0){ // cycle through addr custom fields + save // see #ZBS-518, not easy until addr's get DAL2 // WH deferring here // WH later added via the addUpdateContactField method - should work fine if we catch properly in get foreach ($addrCustomFields as $cK => $cF){ // v2: //$cKN = (int)$cK+1; //$cKey = 'addr_cf'.$cKN; //$cKey2 = 'secaddr_cf'.$cKN; // v3: $cKey = 'addr_'.$cK; $cKey2 = 'secaddr_'.$cK; if (isset($data[$cKey])){ // updating blanks? if ($do_not_update_blanks && empty($data[$cKey])){ // skip it } else { // it's either not in do_not_update_blank mode, or it has a val // add update $cfID = $this->addUpdateCustomField(array( 'data' => array( 'objtype' => ZBS_TYPE_CONTACT, 'objid' => $id, 'objkey' => $cKey, 'objval' => $data[$cKey] ))); } } // any? if (isset($data[$cKey2])){ // updating blanks? if ($do_not_update_blanks && empty($data[$cKey2])){ // skip it } else { // it's either not in do_not_update_blank mode, or it has a val // add update $cfID = $this->addUpdateCustomField(array( 'data' => array( 'objtype' => ZBS_TYPE_CONTACT, 'objid' => $id, 'objkey' => $cKey2, 'objval' => $data[$cKey2] ))); } } } } // / Custom Fields #} Any extra meta keyval pairs? // BRUTALLY updates (no checking) $confirmedExtraMeta = false; if (isset($extraMeta) && is_array($extraMeta)) { $confirmedExtraMeta = array(); foreach ($extraMeta as $k => $v){ #} This won't fix stupid keys, just catch basic fails... $cleanKey = strtolower(str_replace(' ','_',$k)); #} Brutal update //update_post_meta($postID, 'zbs_customer_extra_'.$cleanKey, $v); $this->DAL()->updateMeta(ZBS_TYPE_CONTACT,$id,'extra_'.$cleanKey,$v); #} Add it to this, which passes to IA $confirmedExtraMeta[$cleanKey] = $v; } } #} INTERNAL AUTOMATOR #} & #} FALLBACKS // UPDATING CONTACT if (!$silentInsert){ #} FALLBACK #} (This fires for customers that weren't added because they already exist.) #} e.g. x@g.com exists, so add log "x@g.com filled out form" #} Requires a type and a shortdesc if ( isset($fallBackLog) && is_array($fallBackLog) && isset($fallBackLog['type']) && !empty($fallBackLog['type']) && isset($fallBackLog['shortdesc']) && !empty($fallBackLog['shortdesc']) ){ #} Brutal add, maybe validate more?! #} Long desc if present: $zbsNoteLongDesc = ''; if (isset($fallBackLog['longdesc']) && !empty($fallBackLog['longdesc'])) $zbsNoteLongDesc = $fallBackLog['longdesc']; #} Only raw checked... but proceed. $newOrUpdatedLogID = zeroBS_addUpdateContactLog($id,-1,-1,array( #} Anything here will get wrapped into an array and added as the meta vals 'type' => $fallBackLog['type'], 'shortdesc' => $fallBackLog['shortdesc'], 'longdesc' => $zbsNoteLongDesc )); } // catch dirty flag (update of status) (note, after update_post_meta - as separate) //if (isset($_POST['zbsc_status_dirtyflag']) && $_POST['zbsc_status_dirtyflag'] == "1"){ // actually here, it's set above if (isset($statusChange) && is_array($statusChange)){ // status has changed // IA zeroBSCRM_FireInternalAutomator('contact.status.update',array( 'id'=>$id, 'againstid' => $id, 'userMeta'=> $dataArr, 'from' => $statusChange['from'], 'to' => $statusChange['to'] )); } // IA General contact update (2.87+) zeroBSCRM_FireInternalAutomator('contact.update',array( 'id'=>$id, 'againstid' => $id, 'userMeta'=> $dataArr, 'prevSegments' => $contactsPreUpdateSegments, 'prev_contact' => $previous_contact_obj, )); $dataArr['id'] = $id; $this->events_manager->contact()->updated( $dataArr, $previous_contact_obj ); } // Successfully updated - Return id return $id; } else { $msg = __('DB Update Failed','zero-bs-crm'); $zbs->DAL->addError(302,$this->objectType,$msg,$dataArr); // FAILED update return false; } } else { #} No ID - must be an INSERT if ($wpdb->insert( $ZBSCRM_t['contacts'], $dataArr, $typeArr ) > 0){ #} Successfully inserted, lets return new ID $newID = $wpdb->insert_id; // tags if (isset($data['tags']) && is_array($data['tags'])) { $this->addUpdateContactTags( array( 'id' => $newID, 'tag_input' => $data['tags'], 'mode' => $data['tag_mode'] ) ); } // externalSources $approvedExternalSource = $this->DAL()->addUpdateExternalSources( array( 'obj_id' => $newID, 'obj_type_id' => ZBS_TYPE_CONTACT, 'external_sources' => isset($data['externalSources']) ? $data['externalSources'] : array(), ) ); // for IA below // co's work? // OBJ LINKS - to companies (1liner now as genericified) $this->addUpdateObjectLinks($newID,$data['companies'],ZBS_TYPE_COMPANY); /* if (isset($data['companies']) && is_array($data['companies']) && count($data['companies']) > 0) $this->DAL()->addUpdateObjLinks(array( 'objtypefrom' => ZBS_TYPE_CONTACT, 'objtypeto' => ZBS_TYPE_COMPANY, 'objfromid' => $newID, 'objtoids' => $data['companies'])); */ // Aliases // Maintain an array of AKA emails if (isset($data['aliases']) && is_array($data['aliases'])){ $existingAliasesSimple = array(); $existingAliases = zeroBS_getObjAliases(ZBS_TYPE_CONTACT,$newID); if (!is_array($existingAliases)) $existingAliases = array(); // compare if (is_array($existingAliases)) foreach ($existingAliases as $alias){ // is this alias in the new list? if (in_array($alias['aka_alias'], $data['aliases'])) { $existingAliasesSimple[] = $alias['aka_alias']; continue; } // it's not in the new list, thus, remove it: // this could be a smidgen more performant if it just deleted the line zeroBS_removeObjAlias(ZBS_TYPE_CONTACT,$newID,$alias['aka_alias']); } foreach ($data['aliases'] as $alias){ // valid? if (zeroBS_canUseCustomerAlias($alias)){ // is this alias in the existing list? (nothing to do) if (in_array($alias, $existingAliasesSimple)) continue; // it's not in the existing list, thus, add it: zeroBS_addObjAlias(ZBS_TYPE_CONTACT,$newID,$alias); } else { // err - tried to use an invalid alias $msg = __('Could not add alias (unavailable or invalid):','zero-bs-crm').' '.$alias; $zbs->DAL->addError(307,$this->objectType,$msg,$alias); } } } // Custom fields? #} Cycle through + add/update if set if (is_array($customFields)) foreach ($customFields as $cK => $cF){ // any? if (isset($data[$cK])){ // add update $cfID = $this->DAL()->addUpdateCustomField(array( 'data' => array( 'objtype' => ZBS_TYPE_CONTACT, 'objid' => $newID, 'objkey' => $cK, 'objval' => $data[$cK] ))); } } // Also got to catch any 'addr' custom fields :) if (is_array($addrCustomFields) && count($addrCustomFields) > 0){ // cycle through addr custom fields + save // see #ZBS-518, not easy until addr's get DAL2 // WH deferring here // WH later added via the addUpdateContactField method - should work fine if we catch properly in get foreach ($addrCustomFields as $cK => $cF){ // v2: //$cKN = (int)$cK+1; //$cKey = 'addr_cf'.$cKN; //$cKey2 = 'secaddr_cf'.$cKN; // v3: $cKey = 'addr_'.$cK; $cKey2 = 'secaddr_'.$cK; if (isset($data[$cKey])){ // add update $cfID = $this->DAL()->addUpdateCustomField(array( 'data' => array( 'objtype' => ZBS_TYPE_CONTACT, 'objid' => $newID, 'objkey' => $cKey, 'objval' => $data[$cKey] ))); } // any? if (isset($data[$cKey2])){ // add update $cfID = $this->DAL()->addUpdateCustomField(array( 'data' => array( 'objtype' => ZBS_TYPE_CONTACT, 'objid' => $newID, 'objkey' => $cKey2, 'objval' => $data[$cKey2] ))); } // phpcs:enable VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable } } // / Custom Fields #} Any extra meta keyval pairs? // BRUTALLY updates (no checking) $confirmedExtraMeta = false; if (isset($extraMeta) && is_array($extraMeta)) { $confirmedExtraMeta = array(); foreach ($extraMeta as $k => $v){ #} This won't fix stupid keys, just catch basic fails... $cleanKey = strtolower(str_replace(' ','_',$k)); #} Brutal update //update_post_meta($postID, 'zbs_customer_extra_'.$cleanKey, $v); $this->DAL()->updateMeta(ZBS_TYPE_CONTACT,$newID,'extra_'.$cleanKey,$v); #} Add it to this, which passes to IA $confirmedExtraMeta[$cleanKey] = $v; } } #} INTERNAL AUTOMATOR #} & #} FALLBACKS // NEW CONTACT // zbs_write_log("ABOUT TO HIT THE AUTOMATOR... " . $silentInsert); if (!$silentInsert){ //zbs_write_log("HITTING IT NOW..."); #} Add to automator zeroBSCRM_FireInternalAutomator('contact.new',array( 'id'=>$newID, 'customerMeta'=>$dataArr, 'extsource'=>$approvedExternalSource, 'automatorpassthrough'=>$automatorPassthrough, #} This passes through any custom log titles or whatever into the Internal automator recipe. 'customerExtraMeta'=>$confirmedExtraMeta #} This is the "extraMeta" passed (as saved) )); $dataArr['ID'] = $newID; // phpcs:ignore Generic.WhiteSpace.ScopeIndent.Incorrect $this->events_manager->contact()->created( $dataArr ); // phpcs:ignore Generic.WhiteSpace.ScopeIndent.Incorrect } return $newID; } else { $msg = __('DB Insert Failed','zero-bs-crm'); $zbs->DAL->addError(303,$this->objectType,$msg,$dataArr); // phpcs:enable WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase #} Failed to Insert return false; } } return false; } /** * adds or updates a contact's tags * ... this is really just a wrapper for addUpdateObjectTags * * @param array $args Associative array of arguments * id (if update), owner, data (array of field data) * * @return int line ID */ public function addUpdateContactTags($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, // generic pass-through (array of tag strings or tag IDs): 'tag_input' => -1, // or either specific: 'tagIDs' => -1, 'tags' => -1, 'mode' => 'append' ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ // check id $id = (int)$id; if (empty($id) || $id <= 0) return false; #} ========= / CHECK FIELDS =========== return $this->DAL()->addUpdateObjectTags( array( 'objtype' => ZBS_TYPE_CONTACT, 'objid' => $id, 'tag_input' => $tag_input, 'tags' => $tags, 'tagIDs' => $tagIDs, 'mode' => $mode ) ); } /** * adds or updates a contact's company links * ... this is really just a wrapper for addUpdateObjLinks * fill in for zbsCRM_addUpdateCustomerCompany + zeroBS_setCustomerCompanyID * * @param array $args Associative array of arguments * id (if update), owner, data (array of field data) * * @return int line ID */ public function addUpdateContactCompanies($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'companyIDs' => -1 ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ // check id $id = (int)$id; if (empty($id) || $id <= 0) return false; // if owner = -1, add current if (!isset($owner) || $owner === -1) $owner = zeroBSCRM_user(); // check co id's if (!is_array($companyIDs)) $companyIDs = array(); #} ========= / CHECK FIELDS =========== return $this->DAL()->addUpdateObjLinks(array( 'objtypefrom' => ZBS_TYPE_CONTACT, 'objtypeto' => ZBS_TYPE_COMPANY, 'objfromid' => $id, 'objtoids' => $companyIDs)); } /** * adds or updates a contact's WPID * ... this is really just a wrapper for addUpdateContact * ... and replaces zeroBS_setCustomerWPID * * @param array $args Associative array of arguments * id (if update), owner, data (array of field data) * * @return int line ID */ public function addUpdateContactWPID($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'WPID' => -1 ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ // if owner = -1, add current if (!isset($owner) || $owner === -1) $owner = zeroBSCRM_user(); // check id $id = (int)$id; if (empty($id) || $id <= 0) return false; // WPID may be -1 (NULL) // -1 does okay here if ($WPID == -1) $WPID = ''; #} ========= / CHECK FIELDS =========== #} Enact return $this->addUpdateContact(array( 'id' => $id, 'limitedFields' =>array( array('key'=>'zbsc_wpid','val'=>$WPID,'type'=>'%d') ))); } /** * deletes a contact object * * @param array $args Associative array of arguments * id * * @return int success; */ public function deleteContact($args=array()){ global $zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'saveOrphans' => true ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} Before we actually delete - allow a hook and pass the args (which is just the id and whether saveOrphans or not) zeroBSCRM_FireInternalAutomator('contact.before.delete',array( 'id'=>$id, 'saveOrphans'=>$saveOrphans )); // phpcs:ignore $this->events_manager->contact()->before_delete( $id ); #} Check ID & Delete :) $id = (int)$id; if (!empty($id) && $id > 0) { // delete orphans? if ($saveOrphans === false){ #DB1LEGACY (TOMOVE -> where) // delete quotes $qs = zeroBS_getQuotesForCustomer($id,false,1000000,0,false,false); foreach ($qs as $q){ // delete post if ($zbs->isDAL3()){ $res = $zbs->DAL->quotes->deleteQuote(array('id'=>$q['id'],'saveOrphans'=>false)); } else // DAL2 < - not forced? $res = wp_delete_post($q['id'],false); } unset($qs); #DB1LEGACY (TOMOVE -> where) // delete invoices $is = zeroBS_getInvoicesForCustomer($id,false,1000000,0,false); foreach ($is as $i){ // delete post if ($zbs->isDAL3()){ $res = $zbs->DAL->invoices->deleteInvoice(array('id'=>$i['id'],'saveOrphans'=>false)); } else // DAL2 < not forced? $res = wp_delete_post($i['id'],false); } unset($qs); #DB1LEGACY (TOMOVE -> where) // delete transactions $trans = zeroBS_getTransactionsForCustomer($id,false,1000000,0,false); foreach ($trans as $tran){ // delete post if ($zbs->isDAL3()){ $res = $zbs->DAL->transactions->deleteTransaction(array('id'=>$tran['id'],'saveOrphans'=>false)); } else // DAL2 < - not forced? $res = wp_delete_post($tran['id'],false); } unset($trans); // delete events $events = zeroBS_getEventsByCustomerID($id,false,1000000,0,false); foreach ($events as $event){ // delete post if ($zbs->isDAL3()){ $res = $zbs->DAL->events->deleteEvent(array('id'=>$event['id'],'saveOrphans'=>false)); } else { // DAL2 < - not forced? // this wasn't ever written. } } unset($events); // delete any tag links $this->DAL()->deleteTagObjLinks(array( 'objtype' => ZBS_TYPE_CONTACT, 'objid' => $id )); // delete any external source information $this->DAL()->delete_external_sources( array( 'obj_type' => ZBS_TYPE_CONTACT, 'obj_id' => $id, 'obj_source' => 'all', )); } // delete any alias information (must delete regardless of // $saveOrphans because there isn't a place where aliases are // listed, so they would block forever usage of aliased emails) $existing_aliases = zeroBS_getObjAliases( ZBS_TYPE_CONTACT, $id ); if ( is_array( $existing_aliases ) ) { foreach ( $existing_aliases as $alias ) { zeroBS_removeObjAlias( ZBS_TYPE_CONTACT, $id, $alias['aka_alias'] ); } } $del = zeroBSCRM_db2_deleteGeneric($id,'contacts'); #} Add to automator zeroBSCRM_FireInternalAutomator('contact.delete',array( 'id'=>$id, 'saveOrphans'=>$saveOrphans )); $this->events_manager->contact()->deleted( $id ); return $del; } return false; } /** * tidy's the object from wp db into clean array * * @param array $obj (DB obj) * * @return array (clean obj) */ public function tidy_contact( $obj = false, $withCustomFields = false ) { // phpcs:ignore global $zbs; $res = false; if (isset($obj->ID)){ $res = array(); $res['id'] = $obj->ID; /* `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, */ $res['owner'] = $obj->zbs_owner; $res['status'] = $this->stripSlashes($obj->zbsc_status); $res['email'] = $obj->zbsc_email; $res['prefix'] = $this->stripSlashes($obj->zbsc_prefix); $res['fname'] = $this->stripSlashes($obj->zbsc_fname); $res['lname'] = $this->stripSlashes($obj->zbsc_lname); $res['addr1'] = $this->stripSlashes($obj->zbsc_addr1); $res['addr2'] = $this->stripSlashes($obj->zbsc_addr2); $res['city'] = $this->stripSlashes($obj->zbsc_city); $res['county'] = $this->stripSlashes($obj->zbsc_county); $res['country'] = $this->stripSlashes($obj->zbsc_country); $res['postcode'] = $this->stripSlashes($obj->zbsc_postcode); // until we add multi-addr support, these get translated into old field names (secaddr_) $res['secaddr_addr1'] = $this->stripSlashes($obj->zbsc_secaddr1); $res['secaddr_addr2'] = $this->stripSlashes($obj->zbsc_secaddr2); $res['secaddr_city'] = $this->stripSlashes($obj->zbsc_seccity); $res['secaddr_county'] = $this->stripSlashes($obj->zbsc_seccounty); $res['secaddr_country'] = $this->stripSlashes($obj->zbsc_seccountry); $res['secaddr_postcode'] = $this->stripSlashes($obj->zbsc_secpostcode); $res['hometel'] = $obj->zbsc_hometel; $res['worktel'] = $obj->zbsc_worktel; $res['mobtel'] = $obj->zbsc_mobtel; //$res['notes'] = $obj->zbsc_notes; $res['worktel'] = $obj->zbsc_worktel; $res['wpid'] = $obj->zbsc_wpid; $res['avatar'] = $obj->zbsc_avatar; $res['tw'] = $obj->zbsc_tw; $res['li'] = $obj->zbsc_li; $res['fb'] = $obj->zbsc_fb; // gross backward compat if ($zbs->db1CompatabilitySupport) $res['meta'] = $res; // to maintain old obj more easily, here we refine created into datestamp $res['created'] = zeroBSCRM_locale_utsToDatetime($obj->zbsc_created); if ($obj->zbsc_lastcontacted != -1 && !empty($obj->zbsc_lastcontacted) && $obj->zbsc_lastcontacted > 0) $res['lastcontacted'] = zeroBSCRM_locale_utsToDatetime($obj->zbsc_lastcontacted); else $res['lastcontacted'] = -1; $res['createduts'] = $obj->zbsc_created; // this is the UTS (int14) // this is in v3.0+ format. $res['created_date'] = ( isset( $obj->zbsc_created ) && $obj->zbsc_created > 0 ) ? zeroBSCRM_date_i18n( -1, $obj->zbsc_created ) : false; $res['lastupdated'] = $obj->zbsc_lastupdated; $res['lastupdated_date'] = ( isset( $obj->zbsc_lastupdated ) && $obj->zbsc_lastupdated > 0 ) ? zeroBSCRM_date_i18n( -1, $obj->zbsc_lastupdated ) : false; $res['lastcontacteduts'] = $obj->zbsc_lastcontacted; // this is the UTS (int14) $res['lastcontacted_date'] = ( isset( $obj->zbsc_lastcontacted ) && $obj->zbsc_lastcontacted > 0 ) ? zeroBSCRM_date_i18n( -1, $obj->zbsc_lastcontacted ) : false; // latest logs if (isset($obj->lastlog)) $res['lastlog'] = $obj->lastlog; if (isset($obj->lastcontactlog)) $res['lastcontactlog'] = $obj->lastcontactlog; // Build any extra formats (using fields) $res['fullname'] = $this->format_fullname($res); $res['name'] = $res['fullname']; // this one is for backward compat (pre db2) // if have totals, pass them :) if (isset($obj->quotes_total)) $res['quotes_total'] = $obj->quotes_total; if ( isset( $obj->invoices_total ) ) { $res['invoices_total'] = $obj->invoices_total; $res['invoices_total_inc_deleted'] = $obj->invoices_total_inc_deleted; $res['invoices_count'] = $obj->invoices_count; $res['invoices_count_inc_deleted'] = $obj->invoices_count_inc_deleted; } if ( isset( $obj->transactions_total ) ) { $res['transactions_total'] = $obj->transactions_total; } if (isset($obj->transactions_paid_total)) $res['transactions_paid_total'] = $obj->transactions_paid_total; // and if have invs + trans totals, add to make total val // This now accounts for "part payments" where trans are part/whole payments against invs if (isset($res['invoices_total']) || isset($res['transactions_total'])){ $res['total_value'] = jpcrm_get_total_value_from_contact_or_company( $res ); } // custom fields - tidy any that are present: if ($withCustomFields) $res = $this->tidyAddCustomFields(ZBS_TYPE_CONTACT,$obj,$res,true); // Aliases if (isset($obj->aliases) && is_string($obj->aliases) && !empty($obj->aliases)){ // csv => array $res['aliases'] = explode(',',$obj->aliases); } } return $res; } /** * remove any non-db fields from the object * basically takes array like array('owner'=>1,'fname'=>'x','fullname'=>'x') * and returns array like array('owner'=>1,'fname'=>'x') * * @param array $obj (clean obj) * * @return array (db ready arr) */ private function db_ready_contact($obj=false){ global $zbs; /* if (is_array($obj)){ $removeNonDBFields = array('meta','fullname','name'); foreach ($removeNonDBFields as $fKey){ if (isset($obj[$fKey])) unset($obj[$fKey]); } } */ $legitFields = array( 'owner','status','email','prefix','fname','lname', 'addr1','addr2','city','county','country','postcode', // WH corrected 13/06/18 2.84 'secaddr_addr1','secaddr_addr2','secaddr_city','secaddr_county','secaddr_country','secaddr_postcode', 'secaddr1','secaddr2','seccity','seccounty','seccountry','secpostcode', 'hometel','worktel','mobtel', 'wpid','avatar', 'tw','fb','li', 'created','lastupdated','lastcontacted'); $ret = array(); if (is_array($obj)){ foreach ($legitFields as $fKey){ if (isset($obj[$fKey])) $ret[$fKey] = $obj[$fKey]; } } return $ret; } /** * Wrapper, use $this->getContactMeta($contactID,$key) for easy retrieval of singular * Simplifies $this->getMeta * * @param int objtype * @param int objid * @param string key * * @return bool result */ public function getContactMeta($id=-1,$key='',$default=false){ global $zbs; if (!empty($key)){ return $this->DAL()->getMeta(array( 'objtype' => ZBS_TYPE_CONTACT, 'objid' => $id, 'key' => $key, 'fullDetails' => false, 'default' => $default, 'ignoreowner' => true // for now !! )); } return $default; } /** * returns external source detail lines for a contact * * @param array $args Associative array of arguments * withStats, searchPhrase, sortByField, sortOrder, page, perPage * * @return array of tag lines */ public function getExternalSourcesForContact($args=array()){ global $zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( 'contactID' => -1, 'sortByField' => 'ID', 'sortOrder' => 'ASC', 'page' => 0, 'perPage' => 100, // permissions 'ignoreowner' => false // this'll let you not-check the owner of obj ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} ========== CHECK FIELDS ============ $contactID = (int)$contactID; #} ========= / CHECK FIELDS =========== global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); #} Build query $query = "SELECT * FROM ".$ZBSCRM_t['externalsources']; #} ============= WHERE ================ #} contactID if (!empty($contactID) && $contactID > 0) $wheres['zbss_objid'] = array('zbss_objid','=','%d',$contactID); // type $wheres['zbss_objtype'] = array('zbss_objtype','=','%d',1); #} ============ / WHERE =============== #} Build out any WHERE clauses $wheresArr= $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort($sortByField,$sortOrder) . $this->buildPaging($page,$perPage); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_results($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret results (Result Set - multi-row) if (isset($potentialRes) && is_array($potentialRes) && count($potentialRes) > 0) { #} Has results, tidy + return foreach ($potentialRes as $resDataLine) { // tidy $resArr = $this->DAL()->tidy_externalsource($resDataLine); $res[] = $resArr; } } return $res; } /** * returns tracking detail lines for a contact * * @param array $args Associative array of arguments * withStats, searchPhrase, sortByField, sortOrder, page, perPage * * @return array of tag lines */ public function getTrackingForContact($args=array()){ global $zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( 'contactID' => -1, // optional 'action' => '', 'sortByField' => 'ID', 'sortOrder' => 'ASC', 'page' => 0, 'perPage' => 100, // permissions 'ignoreowner' => false // this'll let you not-check the owner of obj ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} ========== CHECK FIELDS ============ $contactID = (int)$contactID; #} ========= / CHECK FIELDS =========== global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); #} Build query $query = "SELECT * FROM ".$ZBSCRM_t['tracking']; #} ============= WHERE ================ #} contactID if (!empty($contactID) && $contactID > 0) $wheres['zbst_contactid'] = array('zbst_contactid','=','%d',$contactID); #} action if (!empty($action)) $wheres['zbst_action'] = array('zbst_action','=','%s',$action); #} ============ / WHERE =============== #} Build out any WHERE clauses $wheresArr= $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort($sortByField,$sortOrder) . $this->buildPaging($page,$perPage); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_results($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret results (Result Set - multi-row) if (isset($potentialRes) && is_array($potentialRes) && count($potentialRes) > 0) { #} Has results, tidy + return foreach ($potentialRes as $resDataLine) { // tidy $resArr = $this->DAL()->tidy_tracking($resDataLine); $res[] = $resArr; } } return $res; } /** * Returns an ownerid against a contact * * @param int id Contact ID * * @return int contact owner id */ public function getContactOwner($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_CONTACT, 'colname' => 'zbs_owner', 'ignoreowner'=>true)); } return false; } /** * Returns an status against a contact * * @param int id Contact ID * * @return str contact status string */ public function getContactStatus($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_CONTACT, 'colname' => 'zbsc_status', 'ignoreowner'=>true)); } return false; } /** * Sets the status of a contact * * @param int id Contact ID * @param str status Contact status * * @return int changed */ public function setContactStatus( $id=-1, $status=-1 ){ global $zbs; $id = (int)$id; if ($id > 0 && !empty($status) && $status !== -1){ return $this->addUpdateContact(array( 'id'=>$id, 'limitedFields'=>array( array('key'=>'zbsc_status','val' => $status,'type' => '%s') ))); } return false; } /** * Sets the owner of a contact * * @param int id Contact ID * @param int owner Contact owner * * @return int changed */ public function setContactOwner( $id=-1, $owner=-1 ){ global $zbs; $id = (int)$id; $owner = (int)$owner; if ( $id > 0 && $owner > 0 ){ return $this->addUpdateContact(array( 'id'=>$id, 'limitedFields'=>array( array('key'=>'zbs_owner','val' => $owner,'type' => '%d') ))); } return false; } /** * Returns an email addr against a contact * Replaces getContactEmail * * @param int id Contact ID * * @return string Contact email */ public function getContactEmail($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_CONTACT, 'colname' => 'zbsc_email', 'ignoreowner' => true)); } return false; } /** * Updates an email address against a contact * * @param int id Contact ID * @param string $email_address * * @return bool success */ public function update_contact_email( $id, $email_address ){ global $zbs; $id = (int)$id; if ( $id > 0 && zeroBSCRM_validateEmail( $email_address ) ){ $this->DAL()->addUpdateContact( array( 'id' => $id, 'limitedFields' => array( array( 'key' => 'zbsc_email', 'val' => $email_address, 'type' => '%s' ) ) )); return true; } return false; } /** * Returns all email addrs against a contact * ... including aliases * * @param int id Contact ID * * @return array of strings (Contact emails) */ public function getContactEmails($id=-1){ global $zbs; $id = (int)$id; $emails = array(); if ($id > 0){ // main record $mainEmail = $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_CONTACT, 'colname' => 'zbsc_email', 'ignoreowner' => true)); if (zeroBSCRM_validateEmail($mainEmail)) $emails[] = $mainEmail; // aliases $aliases = zeroBS_getObjAliases(ZBS_TYPE_CONTACT,$id); if (is_array($aliases)) foreach ($aliases as $alias) if (!in_array($alias['aka_alias'],$emails)) $emails[] = $alias['aka_alias']; } return $emails; } /** * Returns an email addr against a contact * Replaces zeroBS_customerMobile * * @param int id Contact ID * * @return string Contact email */ public function getContactMobile($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_CONTACT, 'colname' => 'zbsc_mobtel', 'ignoreowner' => true)); } return false; } /** * Returns a formatted fullname of a * Replaces zeroBS_customerName * * @param int id Contact ID * @param array Contact array (if already loaded can pass) * @param array args (see format_fullname func) * * @return string Contact full name */ public function getContactFullName($id=-1,$contactArr=false){ global $zbs; $id = (int)$id; if ($id > 0){ // get a limited-fields contact obj $contact = $this->getContact($id,array('withCustomFields' => false,'fields'=>array('zbsc_prefix','zbsc_fname','zbsc_lname'),'ignoreowner' => true)); if (isset($contact) && is_array($contact) && isset($contact['prefix'])) return $this->format_fullname($contact); } elseif (is_array($contactArr)){ // pass through return $this->format_fullname($contactArr); } return false; } /** * Returns a formatted fullname (optionally including ID + first line of addr) * Replaces zeroBS_customerName more fully than getContactFullName * Also replaces zeroBS_getCustomerName * * @param int id Contact ID * @param array Contact array (if already loaded can pass) * @param array args (see format_fullname func) * * @return string Contact full name */ public function getContactFullNameEtc($id=-1,$contactArr=false,$args=array()){ global $zbs; $id = (int)$id; if ($id > 0){ // get a limited-fields contact obj $contact = $this->getContact($id,array('withCustomFields' => false,'fields'=>array('zbsc_addr1','zbsc_prefix','zbsc_fname','zbsc_lname'),'ignoreowner' => true)); if (isset($contact) && is_array($contact) && isset($contact['prefix'])) return $this->format_name_etc($contact,$args); } elseif (is_array($contactArr)){ // pass through return $this->format_name_etc($contactArr,$args); } return false; } /** * Returns a formatted name (e.g. Dave Davids) or fallback * If there is no name, return "Contact #" or a provided hard-coded fallback. Optionally return an email if it exists. * * @param int $id Contact ID * @param array $contactArr (if already loaded can pass) * @param boolean $do_email_fallback * @param string $hardcoded_fallback * * @return string name or fallback */ public function getContactNameWithFallback( $id=-1, $contactArr=false, $do_email_fallback=true, $hardcoded_fallback=''){ global $zbs; $id = (int)$id; if ($id > 0){ // get a limited-fields contact obj $contact = $this->getContact( $id, array( 'withCustomFields' => false, 'fields'=>array( 'zbsc_fname', 'zbsc_lname', 'zbsc_email', ), 'ignoreowner' => true ) ); if ( isset( $contact ) && is_array( $contact ) ) { return $this->format_name_with_fallback( $contact, $do_email_fallback, $hardcoded_fallback ); } } elseif ( is_array( $contactArr ) ) { // pass through return $this->format_name_with_fallback( $contactArr, $do_email_fallback, $hardcoded_fallback ); } return false; } /** * Returns a formatted address of a contact * Replaces zeroBS_customerAddr * * @param int id Contact ID * @param array Contact array (if already loaded can pass) * @param array args (see format_address func) * * @return string Contact addr html */ public function getContactAddress($id=-1,$contactArr=false,$args=array()){ global $zbs; $id = (int)$id; if ($id > 0){ // get a limited-fields contact obj // this is hacky, but basically get whole basic contact record for this for now, because // this doesn't properly get addr custom fields: // $contact = $this->getContact($id,array('withCustomFields' => false,'fields'=>$this->field_list_address,'ignoreowner'=>true)); $contact = $this->getContact($id,array('withCustomFields' => true,'ignoreowner'=>true)); if (isset($contact) && is_array($contact) && isset($contact['addr1'])) return $this->format_address($contact,$args); } elseif (is_array($contactArr)){ // pass through return $this->format_address($contactArr,$args); } return false; } /** * Returns a formatted address of a contact (2nd addr) * Replaces zeroBS_customerAddr * * @param int id Contact ID * @param array Contact array (if already loaded can pass) * @param array args (see format_address func) * * @return string Contact addr html */ public function getContact2ndAddress($id=-1,$contactArr=false,$args=array()){ global $zbs; $id = (int)$id; $args['secondaddr'] = true; if ($id > 0){ // get a limited-fields contact obj // this is hacky, but basically get whole basic contact record for this for now, because // this doesn't properly get addr custom fields: // $contact = $this->getContact($id,array('withCustomFields' => false,'fields'=>$this->field_list_address2,'ignoreowner'=>true)); $contact = $this->getContact($id,array('withCustomFields' => true,'ignoreowner'=>true)); if (isset($contact) && is_array($contact) && isset($contact['addr1'])) return $this->format_address($contact,$args); } elseif (is_array($contactArr)){ // pass through return $this->format_address($contactArr,$args); } return false; } /** * Returns a contacts tag array * Replaces zeroBSCRM_getCustomerTags AND zeroBSCRM_getContactTagsArr * * @param int id Contact ID * * @return mixed */ public function getContactTags($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getTagsForObjID(array('objtypeid'=>ZBS_TYPE_CONTACT,'objid'=>$id)); } return false; } /** * Returns last contacted uts against a contact * * @param int id Contact ID * * @return int Contact last contacted date as uts (or -1) */ public function getContactLastContactUTS($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_CONTACT, 'colname' => 'zbsc_lastcontacted', 'ignoreowner' => true)); } return false; } /** * updates lastcontacted date for a contact * * @param int id Contact ID * @param int uts last contacted * * @return bool */ public function setContactLastContactUTS($id=-1,$lastContactedUTS=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->addUpdateContact(array( 'id'=>$id, 'limitedFields'=>array( array('key'=>'zbsc_lastcontacted','val' => $lastContactedUTS,'type' => '%d') ))); } return false; } /** * Returns a set of social accounts for a contact (tw,li,fb) * * @param int id Contact ID * * @return array social acc's */ public function getContactSocials($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ // lazy 3 queries, optimise later $tw = $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_CONTACT, 'colname' => 'zbsc_tw', 'ignoreowner' => true)); $li = $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_CONTACT, 'colname' => 'zbsc_li', 'ignoreowner' => true)); $fb = $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_CONTACT, 'colname' => 'zbsc_fb', 'ignoreowner' => true)); return array('tw'=>$tw,'li' => $li, 'fb' => $fb); } return false; } /** * Returns a linked WP ID against a contact * Replaces zeroBS_getCustomerWPID * * @param int id Contact ID * * @return int Contact wp id */ public function getContactWPID( $id=-1 ){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_CONTACT, 'colname' => 'zbsc_wpid', 'ignoreowner' => true)); } return false; } /** * Returns true/false whether or not user has 'do-not-email' flag (from unsub email link click) * * @param int id Contact ID * * @return bool */ public function getContactDoNotMail($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->meta(ZBS_TYPE_CONTACT,$id,'do-not-email',false); } return false; } /** * updates true/false whether or not user has 'do-not-email' flag (from unsub email link click) * * @param int id Contact ID * @param bool whether or not to set donotmail * * @return bool */ public function setContactDoNotMail($id=-1,$doNotMail=true){ global $zbs; $id = (int)$id; if ($id > 0){ if ($doNotMail) return $this->DAL()->updateMeta(ZBS_TYPE_CONTACT,$id,'do-not-email',true); else // remove return $this->DAL()->deleteMeta(array( 'objtype' => ZBS_TYPE_CONTACT, 'objid' => $id, 'key' => 'do-not-email')); } return false; } /** * Returns an url to contact avatar (Gravatar if not set?) * For now just returns the field * Replaces zeroBS_getCustomerIcoHTML? * * @param int id Contact ID * * @return int Contact wp id */ public function getContactAvatarURL($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_CONTACT, 'colname' => 'zbsc_avatar', 'ignoreowner' => true)); } return false; } /** * Returns an url to contact avatar (Gravatar if not set?) * Or empty if 'show default empty' = false * * @param int id Contact ID * @param bool showPlaceholder does what it says on tin * * @return string URL for img */ public function getContactAvatar($id=-1,$showPlaceholder=true){ global $zbs; $id = (int)$id; if ($id > 0){ $avatarMode = zeroBSCRM_getSetting('avatarmode'); switch ($avatarMode){ case 1: // gravitar $potentialEmail = $this->getContactEmail($id); if (!empty($potentialEmail)) return zeroBSCRM_getGravatarURLfromEmail($potentialEmail); // default return zeroBSCRM_getDefaultContactAvatar(); break; case 2: // custom img $dbURL = $this->getContactAvatarURL($id); if (!empty($dbURL)) return $dbURL; // default return zeroBSCRM_getDefaultContactAvatar(); break; case 3: // none return ''; break; } } // fallback if ($showPlaceholder) return zeroBSCRM_getDefaultContactAvatar(); return false; } /** * Returns html of contact avatar (Gravatar if not set?) * Or empty if 'show default empty' = false * * @param int id Contact ID * * @return string HTML */ public function getContactAvatarHTML($id=-1,$size=100,$extraClasses=''){ $id = (int)$id; if ($id > 0){ $avatarMode = zeroBSCRM_getSetting('avatarmode'); switch ($avatarMode){ case 1: // gravitar $potentialEmail = $this->getContactEmail($id); if (!empty($potentialEmail)) return '<img src="'.zeroBSCRM_getGravatarURLfromEmail($potentialEmail,$size).'" class="'.$extraClasses.' zbs-gravatar" alt="" />'; // default return zeroBSCRM_getDefaultContactAvatarHTML(); break; case 2: // custom img $dbURL = $this->getContactAvatarURL($id); if (!empty($dbURL)) return '<img src="'.$dbURL.'" class="'.$extraClasses.' zbs-custom-avatar" alt="" />'; // default return zeroBSCRM_getDefaultContactAvatarHTML(); break; case 3: // none return ''; break; } } return ''; } /** * Returns a count of contacts (owned) * Replaces zeroBS_customerCount AND zeroBS_getCustomerCount AND zeroBS_customerCountByStatus * * * @return int count */ public function getContactCount($args=array()){ #} ============ LOAD ARGS ============= $defaultArgs = array( // Search/Filtering (leave as false to ignore) 'inCompany' => false, // will be an ID if used 'withStatus' => false, // will be str if used // permissions 'ignoreowner' => true, // this'll let you not-check the owner of obj ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= $whereArr = array(); if ($inCompany) $whereArr['incompany'] = array('ID','IN','(SELECT DISTINCT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = ".ZBS_TYPE_CONTACT." AND zbsol_objtype_to = ".ZBS_TYPE_COMPANY." AND zbsol_objid_to = %d)",$inCompany); // phpcs:disable VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable, WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase if ( $withStatus !== false && ! empty( $withStatus ) ) { $whereArr['status'] = array( 'zbsc_status', '=', 'convert(%s using utf8mb4) collate utf8mb4_bin', $withStatus ); } // phpcs:enable VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable, WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase return $this->DAL()->getFieldByWHERE(array( 'objtype' => ZBS_TYPE_CONTACT, 'colname' => 'COUNT(ID)', 'where' => $whereArr, 'ignoreowner' => $ignoreowner)); return 0; } /** * Returns a customer's associated company ID's * Replaces zeroBS_getCustomerCompanyID (via LEGACY func) * * @param int id * * @return array int id */ public function getContactCompanies($id=-1){ if (!empty($id)){ /* $contact = $this->getContact($id,array( 'withCompanies' => true, 'fields' => array('ID'))); if (is_array($contact) && isset($contact['companies'])) return $contact['companies']; */ // cleaner: return $this->DAL()->getObjsLinkedToObj(array( 'objtypefrom' => ZBS_TYPE_CONTACT, // contact 'objtypeto' => ZBS_TYPE_COMPANY, // company 'objfromid' => $id, 'ignoreowner' => true)); } return array(); } /** * Returns a bool whether contact has a quote linked to them * NOTE: this only counts objlinks, so if the obj is deleted and they're not tidied, this'll give false positive * (Shorthand for contactHasObjLink) * * @param int contactID * @param int obj type id * * @return bool */ public function contactHasQuote($contactID=-1){ if ($contactID > 0){ // cleaner: $c = $this->contactHasObjLink($contactID,ZBS_TYPE_QUOTE); if ($c > 0) return true; } return false; } /** * Returns a bool whether contact has a Invoice linked to them * NOTE: this only counts objlinks, so if the obj is deleted and they're not tidied, this'll give false positive * (Shorthand for contactHasObjLink) * * @param int contactID * @param int obj type id * * @return bool */ public function contactHasInvoice($contactID=-1){ if ($contactID > 0){ // cleaner: $c = $this->contactHasObjLink($contactID,ZBS_TYPE_INVOICE); if ($c > 0) return true; } return false; } /** * Returns a bool whether contact has a transaction linked to them * NOTE: this only counts objlinks, so if the obj is deleted and they're not tidied, this'll give false positive * (Shorthand for contactHasObjLink) * * @param int contactID * @param int obj type id * * @return bool */ public function contactHasTransaction($contactID=-1){ if ($contactID > 0){ // cleaner: $c = $this->contactHasObjLink($contactID,ZBS_TYPE_TRANSACTION); if ($c > 0) return true; } return false; } /** * Returns a bool whether contact has objtype linked to them * specifically *obj -> THIS (contact) * NOTE: this only counts objlinks, so if the obj is deleted and they're not tidied, this'll give false positive * * @param int id * @param int obj type id * * @return bool */ private function contactHasObjLink($id=-1,$objTypeID=-1){ if ($id > 0 && $objTypeID > 0){ // cleaner: $c = $this->DAL()->getObjsLinksLinkedToObj(array( 'objtypefrom' => $objTypeID, // obj type 'objtypeto' => ZBS_TYPE_CONTACT, // contact 'objtoid' => $id, 'count' => true, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); if ($c > 0) return true; } return false; } /** * Returns the next customer ID and the previous customer ID * Used for the navigation between contacts. * * @param int id * * @return array int id */ public function getContactPrevNext($id=-1){ global $ZBSCRM_t, $wpdb; if($id > 0){ //then run the queries.. $nextSQL = $this->prepare("SELECT MIN(ID) FROM ".$ZBSCRM_t['contacts']." WHERE ID > %d", $id); $res['next'] = $wpdb->get_var($nextSQL); $prevSQL = $this->prepare("SELECT MAX(ID) FROM ".$ZBSCRM_t['contacts']." WHERE ID < %d", $id); $res['prev'] = $wpdb->get_var($prevSQL); return $res; } return false; } /** * Takes full object and makes a "list view" boiled down version * Used to generate listview objs * * @param array $obj (clean obj) * * @return array (listview ready obj) */ public function listViewObj($contact=false,$columnsRequired=array()){ if (is_array($contact) && isset($contact['id'])){ global $zbs; $resArr = $contact; $resArr['avatar'] = zeroBS_customerAvatar($resArr['id']); // use created original $resArr['created'] = zeroBSCRM_date_i18n(-1, $resArr['createduts']); #} Custom columns #} Total value if (in_array('totalvalue', $columnsRequired)){ #} Calc total value + add to return array $resArr['totalvalue'] = zeroBSCRM_formatCurrency(0); if (isset($contact['total_value'])) $resArr['totalvalue'] = zeroBSCRM_formatCurrency($contact['total_value']); } #} Quotes if ( in_array( 'quotetotal', $columnsRequired ) ) { if ( isset( $contact['quotes_total'] ) ) { $resArr['quotestotal'] = zeroBSCRM_formatCurrency( $contact['quotes_total'] ); } else { $resArr['quotestotal'] = zeroBSCRM_formatCurrency( 0 ); } } #} Invoices if ( in_array('invoicetotal', $columnsRequired ) ) { if ( isset( $contact['invoices_total'] ) ) { $resArr['invoicestotal'] = zeroBSCRM_formatCurrency( $contact['invoices_total'] ); } else { $resArr['invoicestotal'] = zeroBSCRM_formatCurrency( 0 ); } } #} Transactions if (in_array('transactiontotal', $columnsRequired)){ $resArr['transactionstotal'] = zeroBSCRM_formatCurrency(0); if (isset($contact['transactions_value'])) $resArr['transactionstotal'] = zeroBSCRM_formatCurrency($contact['transactions_value']); } // v3.0 if (isset($contact['transactions_total'])){ // DAL2 way, brutal effort. $resArr['transactions_total'] = zeroBSCRM_formatCurrency($contact['transactions_total']); // also pass total without formatting (used for hastransactions check) $resArr['transactions_total_value'] = $contact['transactions_total']; } #} Company if (in_array('company',$columnsRequired)){ $resArr['company'] = false; #} Co Name Default $coName = ''; // glob as used above 1 step in ajax. not pretty global $companyNameCache; // get $coID = zeroBS_getCustomerCompanyID($resArr['id']);//get_post_meta($post->ID,'zbs_company',true); if (!empty($coID)){ // cache as we go if (!isset($companyNameCache[$coID])){ // get $co = zeroBS_getCompany($coID); if (isset($co) && isset($co['name'])) $coName = $co['name']; if (empty($coName)) $coName = jpcrm_label_company().' #'.$co['id']; // cache $companyNameCache[$coID] = $coName; } else { $coName = $companyNameCache[$coID]; } } if ($coID > 0){ $resArr['company'] = array('id'=>$coID,'name'=>$coName); } } // Object view. Escaping JS for Phone link attr to avoid XSS // phpcs:disable $resArr['hometel'] = isset( $resArr['hometel'] ) ? esc_js( $resArr['hometel'] ) : ''; $resArr['worktel'] = isset( $resArr['worktel'] ) ? esc_js( $resArr['worktel'] ) : ''; $resArr['mobtel'] = isset( $resArr['mobtel'] ) ? esc_js( $resArr['mobtel'] ) : ''; // phpcs:enable return $resArr; } return false; } // =============================================================================== // ============ Formatting =================================================== /** * Returns a formatted full name (e.g. Mr. Dave Davids) * * @param array $obj (tidied db obj) * * @return string fullname */ public function format_fullname($contactArr=array()){ $usePrefix = zeroBSCRM_getSetting('showprefix'); $str = ''; if($usePrefix){ if (isset($contactArr['prefix'])) $str .= $contactArr['prefix']; } if (isset($contactArr['fname'])) { if (!empty($str)) $str .= ' '; $str .= $contactArr['fname']; } if (isset($contactArr['lname'])) { if (!empty($str)) $str .= ' '; $str .= $contactArr['lname']; } return $str; } /** * Returns a formatted full name +- id, address (e.g. Mr. Dave Davids 12 London Street #23) * Replaces zeroBS_customerName from DAL1 more realistically than format_fullname * * @param array $obj (tidied db obj) * * @return string fullname */ public function format_name_etc($contactArr=array(),$args=array()){ #} =========== LOAD ARGS ============== $defaultArgs = array( 'incFirstLineAddr' => false, 'incID' => false ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= // full name first $str = $this->format_fullname($contactArr); // First line of addr? if ($incFirstLineAddr) if (isset($contactArr['addr1']) && !empty($contactArr['addr1'])) $str .= ' ('.$contactArr['addr1'].')'; // ID? if ($incID) $str .= ' #'.$contactArr['id']; return $str; } /** * Returns a formatted name (e.g. Dave Davids) or fallback * If there is no name, return "Contact #" or a provided hard-coded fallback. Optionally return an email if it exists. * * @param array $contactArr (tidied db obj) * @param boolean $do_email_fallback * @param string $hardcoded_fallback * * @return string name or fallback * */ public function format_name_with_fallback( $contactArr=array(), $do_email_fallback=true, $hardcoded_fallback='') { $str = $this->format_fullname( $contactArr ); if ($do_email_fallback && empty( $str ) && !empty( $contactArr['email']) ) { $str = $contactArr['email']; } if ( empty($str) ) { if ( !empty( $hardcoded_fallback ) ) { return $hardcoded_fallback; } else { return __('Contact','zero-bs-crm') . ' #' . $contactArr['id']; } } return $str; } // =========== / Formatting =================================================== // =============================================================================== } // / class
projects/plugins/crm/includes/jpcrm-mail-templating.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V1.2.5 * * Copyright 2020 Automattic * * Date: 09/01/2017 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ function zeroBSCRM_mailTemplate_processEmailHTML($content){ global $zbs; //acceptable html here is a bit flawed as it needs to be specifically done otherwise it will strip a <b> //inside a <p> if not defined carefully, better to just do wp_kses_post() //https://codex.wordpress.org/Function_Reference/wp_kses_post also sanitizes. $content = wp_kses_post($content); return $content; } function zeroBSCRM_mailTemplate_emailPreview($templateID=-1){ global $zbs; $html = ''; $bodyHTML = ''; if ( $templateID > 0 ){ // retrieve template $html = jpcrm_retrieve_template( 'emails/default-email.html', false ); $message_content = zeroBSCRM_mailTemplate_get($templateID); if (isset($message_content->zbsmail_body)) $bodyHTML = $message_content->zbsmail_body; // load templater $placeholder_templating = $zbs->get_templating(); // build replacements array // ... start with generic replaces (e.g. loginlink, loginbutton) $replacements = $placeholder_templating->get_generic_replacements(); if (isset($message_content->zbsmail_body)) $bodyHTML = $message_content->zbsmail_body; // preview sublne $subLine = __("This is a <b>Jetpack CRM email template preview</b><br/><em>This footer text is not shown in live emails</em>.",'zero-bs-crm'); $html = $placeholder_templating->replace_single_placeholder( 'msg-content', $bodyHTML, $html ); $replacements['unsub-line'] = $subLine; $replacements['powered-by'] = zeroBSCRM_mailTemplate_poweredByHTML(); $replacements['email-from-name'] = zeroBSCRM_mailDelivery_defaultFromname(); //process the template specific ##PLACEHOLDER## to actual viewable stuff... if ( $templateID == 1 ){ // client portal // Replace some common ones with generic examples too: $replacements['email'] = 'your.user@email.com'; $replacements['login-url'] = site_url('clients/login'); //echo 'rep:<pre>'.print_r($replacements,1).'</pre>'; exit(); // replace vars $html = $placeholder_templating->replace_placeholders( array( 'global', 'contact' ), $html, $replacements ); } if ( $templateID == 2 ){ // quote accepted $replacements['quote-title'] = __('Example Quotation #101','zero-bs-crm'); $replacements['quote-url'] = site_url('clients/login'); $replacements['quote-edit-url'] = admin_url(); // replace vars $html = $placeholder_templating->replace_placeholders( array( 'global', 'quote', 'contact' ), $html, $replacements ); } if ( $templateID == 3 ){ //invoice template $i=0; $logo_url = ''; ##WLREMOVE $logo_url = $zbs->urls['crm-logo']; ##/WLREMOVE $lineitems = array( array( 'title' => __( 'Your Invoice Item', 'zero-bs-crm' ), 'desc' => __( 'Your invoice item description goes here', 'zero-bs-crm' ), 'quantity' => 5, 'price' => 20, 'net' => 100, ), array( 'title' => __( 'Another Item', 'zero-bs-crm' ), 'desc' => __( 'Some other description', 'zero-bs-crm' ), 'quantity' => 3, 'price' => 17, 'net' => 51, ), ); $lineitems_header_html = zeroBSCRM_invoicing_generateInvPart_tableHeaders( 1 ); $lineitem_html = zeroBSCRM_invoicing_generateInvPart_lineitems( $lineitems ); $replacements['title'] = __( 'Invoice Template', 'zero-bs-crm' ); $replacements['invoice-title'] = __( 'Invoice', 'zero-bs-crm' ); $replacements['logo-url'] = esc_url( $logo_url ); $inv_number = '2468'; $inv_date_str = jpcrm_uts_to_date_str( 1931212800, false, true ); $ref = '920592qz-42'; $totals_table = ''; $biz_info_table = ''; ##WLREMOVE $biz_info_table = '<div style="text-align:right"><b>John Doe</b><br/>' . __( 'This is replaced<br>with the contacts details<br>from their profile.', 'zero-bs-crm' ) . '</div>'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ##/WLREMOVE $replacements['invoice-number'] = $inv_number; $replacements['invoice-date'] = $inv_date_str; $replacements['invoice-ref'] = $ref; $replacements['invoice-due-date'] = $inv_date_str; $replacements['invoice-table-headers'] = $lineitems_header_html; $replacements['invoice-line-items'] = $lineitem_html; $replacements['invoice-totals-table'] = $totals_table; $replacements['biz-info'] = $biz_info_table; $viewInPortal = ''; $invoiceID = ''; // got portal? //if (isset($invsettings['feat_portal']) && !empty($invsettings['feat_portal'])){ if (zeroBSCRM_isExtensionInstalled('portal')){ // view on portal (hashed?) $viewInPortalURL = zeroBSCRM_portal_linkObj($invoiceID,ZBS_TYPE_INVOICE); //zeroBS_portal_link('invoices',$invoiceID); // if viewing in portal? $viewInPortal = '<div style="text-align:center;margin:1em;margin-top:2em">'.zeroBSCRM_mailTemplate_emailSafeButton($viewInPortalURL,__('View Invoice','zero-bs-crm')).'</div>'; } // view in portal? $replacements['portal-view-button'] = $viewInPortal; // replace vars $html = $placeholder_templating->replace_placeholders( array( 'global', 'invoice', 'contact', 'company' ), $html, $replacements ); } // new proposal if ( $templateID == 4 ){ $replacements['quote-title'] = __('Example Quotation #101','zero-bs-crm'); $replacements['quote-url'] = site_url('clients/login'); $viewInPortal = ''; $quoteID = ''; // got portal? //if (isset($invsettings['feat_portal']) && !empty($invsettings['feat_portal'])){ if (zeroBSCRM_isExtensionInstalled('portal')){ // view on portal (hashed?) $viewInPortalURL = zeroBSCRM_portal_linkObj($quoteID,ZBS_TYPE_QUOTE); // if viewing in portal? $viewInPortal = '<div style="text-align:center;margin:1em;margin-top:2em">'.zeroBSCRM_mailTemplate_emailSafeButton($viewInPortalURL,__('View Proposal','zero-bs-crm')).'</div>'; } // view in portal? $replacements['portal-view-button'] = $viewInPortal; // replace vars $html = $placeholder_templating->replace_placeholders( array( 'global', 'quote', 'contact' ), $html, $replacements ); } // task if ( $templateID == 5 ){ $replacements['task-title'] = __( 'Example Task #101', 'zero-bs-crm' ); $replacements['task-link'] = '<div style="text-align:center;margin:1em;margin-top:2em">' . zeroBSCRM_mailTemplate_emailSafeButton( admin_url(), __( 'View Task', 'zero-bs-crm' ) ) . '</div>'; $replacements['contact-fname'] = __( 'First-Name', 'zero-bs-crm' ); $replacements['contact-lname'] = __( 'Last-Name', 'zero-bs-crm' ); $replacements['contact-fullname'] = __( 'Full-Name', 'zero-bs-crm' ); // replace vars $html = $placeholder_templating->replace_placeholders( array( 'global', 'event' ), $html, $replacements ); } // Your Client Portal Password if ( $templateID == 6 ){ $replacements['password'] = '********'; $replacements['email'] = 'your.user@email.com'; // replace vars $html = $placeholder_templating->replace_placeholders( array( 'global' ), $html, $replacements ); } // Your Statement if ( $templateID == 7 ){ // replace vars $html = $placeholder_templating->replace_placeholders( array( 'global' ), $html, $replacements ); } } return $html; } // Check if attempting to preview email template function zeroBSCRM_preview_email_template(){ global $zbs; // if trying to preview if (isset($_GET['zbsmail-template-preview']) && $_GET['zbsmail-template-preview'] == 1){ // if rights if ( current_user_can( 'admin_zerobs_manage_options' ) ) { $html = ''; if (isset( $_GET['template_id'] ) && !empty( $_GET['template_id'] ) ){ $templateID = (int)sanitize_text_field( $_GET['template_id'] ); echo zeroBSCRM_mailTemplate_emailPreview($templateID); } else { // load templater $placeholder_templating = $zbs->get_templating(); // retrieve template $html = jpcrm_retrieve_template( 'emails/default-email.html', false ); $message_content = ''; $unsub_line = ''; ##WLREMOVE## $message_content = "<h3 style='text-align:center;text-transform:uppercase'>Welcome to Jetpack CRM Email Templates</h3>"; $unsub_line = __("Thanks for using Jetpack CRM",'zero-bs-crm'); ##/WLREMOVE## $message_content .= "<div style='text-align:center'>" . __("This is example content for the email template preview. <p>This content will be replaced by what you have in your system email templates</p>", 'zero-bs-crm') . "</div>"; // replacements echo $placeholder_templating->replace_placeholders( array( 'global', 'invoice' ), $html, array( 'title' => esc_html__('Template Preview','zero-bs-crm'), 'msg-content' => $message_content, 'unsub-line' => esc_html( $unsub_line ), 'powered-by' => zeroBSCRM_mailTemplate_poweredByHTML(), 'email-from-name' => esc_html( zeroBSCRM_mailDelivery_defaultFromname() ) )); } die(); } } } add_action('init','zeroBSCRM_preview_email_template'); /* =========================================================== ZBS Templating - Load Default Templates / Restore Default ========================================================== Noting here that although zeroBSCRM_mail_retrieveWrapTemplate has been deprecated (4.5.0), This one is not, the thinking being these are used to load specific email bodies which (as of now) are loaded into the DB via zeroBSCRM_populateEmailTemplateList() and then edited via UI ...so there is probably no need to move these out of UI into templated files. */ function zeroBSCRM_mail_retrieveDefaultBodyTemplate($template='maintemplate'){ $templatedHTML = ''; if (function_exists('file_get_contents')){ #} templates $acceptableTemplates = array( 'maintemplate', 'clientportal', 'invoicesent', 'quoteaccepted', 'quotesent', 'tasknotification', 'clientportalpwreset', 'invoicestatementsent' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase if (in_array($template, $acceptableTemplates)){ // 2.98.6+ translated. maintemplate was a misnomer if ($template == 'maintemplate') $template = 'email-body'; try { #} Build from default template - see the useful - http://www.leemunroe.com/responsive-html-email-template/ $templatedHTML = file_get_contents(ZEROBSCRM_PATH.'html/templates/'.$template.'.html'); } catch (Exception $e){ #} Nada } } } return $templatedHTML; } // v2.98.6 - change default from /html/notifications/email-default/ to /html/templates/_responsivewrap.html // v4.5.0 - deprecated in favour of core variant function zeroBSCRM_mail_retrieveWrapTemplate( $template = 'default' ) { zeroBSCRM_DEPRECATEDMSG( 'zeroBSCRM_mail_retrieveWrapTemplate was deprecated in v4.5.0, please use the core function retrieve_template' ); return ''; } /* ====================================================== / ZBS Templating - Load Initial HTML ====================================================== */ /* ====================================================== ZBS Quotes - Generate HTML (notification emails) ====================================================== */ function zeroBSCRM_quote_generateNotificationHTML( $quoteID = -1, $return = true ) { global $zbs; if ( !empty( $quoteID ) ) { $quote_contact_id = $zbs->DAL->quotes->getQuoteContactID( $quoteID ); $quote_contact = $zbs->DAL->contacts->getContact( $quote_contact_id ); $html = ''; $pWrap = '<p style="font-family:sans-serif;font-size:14px;font-weight:normal;margin:0;Margin-bottom:15px;">'; // retrieve template $templatedHTML = jpcrm_retrieve_template( 'emails/default-email.html', false ); // Act if ( !empty( $templatedHTML ) ) { // Actual body: $bodyHTML = ''; // load templater $placeholder_templating = $zbs->get_templating(); // get initial replacements arr $replacements = $placeholder_templating->get_generic_replacements(); // Retrieve quote (for title + URL) $quote = zeroBS_getQuote( $quoteID, true ); if ( isset( $quote ) && is_array( $quote ) ) { $proposalTitle = ''; if ( !empty( $quote['title'] ) ) { $proposalTitle = $quote['title']; } // vars $zbs_biz_name = zeroBSCRM_getSetting( 'businessname' ); $zbs_biz_yourname = zeroBSCRM_getSetting( 'businessyourname' ); $zbs_biz_extra = zeroBSCRM_getSetting( 'businessextra' ); $zbs_biz_youremail = zeroBSCRM_getSetting( 'businessyouremail' ); $zbs_biz_yoururl = zeroBSCRM_getSetting( 'businessyoururl' ); $zbs_settings_slug = admin_url( 'admin.php?page=' . $zbs->slugs['settings'] ) . '&tab=quotes'; $quote_url = zeroBSCRM_portal_linkObj( $quoteID, ZBS_TYPE_QUOTE ); $proposalEmailTitle = __( 'Proposal Notification', 'zero-bs-crm' ); // build content $message_content = zeroBSCRM_mailTemplate_get( ZBSEMAIL_NEWQUOTE ); $bodyHTML = $message_content->zbsmail_body; // replacements $bodyHTML $replacements['quote-url'] = $quote_url; $replacements['quote-title'] = $proposalTitle; $replacements['quote-value'] = $quote['value'] ? zeroBSCRM_formatCurrency( $quote['value'] ) : ''; $viewInPortal = ''; $quoteID = ''; // got portal? if ( zeroBSCRM_isExtensionInstalled( 'portal' ) ) { // view on portal (hashed?) $viewInPortalURL = zeroBSCRM_portal_linkObj( $quoteID, ZBS_TYPE_QUOTE ); // if viewing in portal? $viewInPortal = '<div style="text-align:center;margin:1em;margin-top:2em">' . zeroBSCRM_mailTemplate_emailSafeButton( $viewInPortalURL, __( 'View Proposal', 'zero-bs-crm' ) ) . '</div>'; } // view in portal? $replacements['portal-view-button'] = $viewInPortal; // build msg-content html $bodyHTML = $placeholder_templating->replace_placeholders( array( 'global', 'quote', 'contact' ), $bodyHTML, $replacements, array( ZBS_TYPE_QUOTE => $quote, ZBS_TYPE_CONTACT => $quote_contact ) ); // For now, use this, ripped from invoices: // (We need to centralise) $bizInfoTable = '<table class="table zbs-table" style="width:100%;">'; $bizInfoTable .= '<tbody>'; $bizInfoTable .= '<tr><td style="font-family:sans-serif;font-size:14px;vertical-align:top;padding-bottom:5px;"><strong>' . $zbs_biz_name . '</strong></td></tr>'; $bizInfoTable .= '<tr><td style="font-family:sans-serif;font-size:14px;vertical-align:top;padding-bottom:5px;">' . $zbs_biz_yourname . '</td></tr>'; $bizInfoTable .= '<tr><td style="font-family:sans-serif;font-size:14px;vertical-align:top;padding-bottom:5px;">' . $zbs_biz_extra . '</td></tr>'; $bizInfoTable .= '</tbody>'; $bizInfoTable .= '</table>'; // phony - needs unsub $unsub_line = __( 'You have received this notification because a proposal has been sent to you', 'zero-bs-crm' ); if ( isset( $zbs_biz_name ) && !empty( $zbs_biz_name ) ) { $unsub_line .= ' by ' . $zbs_biz_name; } $unsub_line .= '. ' . __( 'If you believe this was sent in error, please reply and let us know.', 'zero-bs-crm' ); // build body html $replacements = $placeholder_templating->get_generic_replacements(); $replacements['title'] = $proposalEmailTitle; $replacements['msg-content'] = $bodyHTML; $replacements['unsub-line'] = $unsub_line; $replacements['biz-info'] = $bizInfoTable; $settings = $zbs->settings->getAll(); if ( $settings['currency'] && $settings['currency']['strval'] ) { $replacements['quote-currency'] = $settings['currency']['strval']; } $html = $placeholder_templating->replace_placeholders( array( 'global', 'quote' ), $templatedHTML, $replacements ); } // return if ( !$return ) { echo $html; exit(); } } return $html; } // FAIL return; } #} sent to quote creator function zeroBSCRM_quote_generateAcceptNotifHTML( $quoteID = -1, $quoteSignedBy = '', $return = true ) { global $zbs; if ( !empty( $quoteID ) ) { $quote_contact_id = $zbs->DAL->quotes->getQuoteContactID( $quoteID ); $quote_contact = $zbs->DAL->contacts->getContact( $quote_contact_id ); $html = ''; $pWrap = '<p style="font-family:sans-serif;font-size:14px;font-weight:normal;margin:0;Margin-bottom:15px;">'; // retrieve template $templatedHTML = jpcrm_retrieve_template( 'emails/default-email.html', false ); // load templater $placeholder_templating = $zbs->get_templating(); // get initial replacements arr $replacements = $placeholder_templating->get_generic_replacements(); // Act if ( !empty( $templatedHTML ) ) { // Actual body: $bodyHTML = ''; // Retrieve quote (for title + URL) $quote = zeroBS_getQuote( $quoteID, true ); if ( isset( $quote ) && is_array( $quote ) ) { $proposalTitle = ''; if ( !empty( $quote['title'] ) ) { $proposalTitle = $quote['title']; } $message_content = zeroBSCRM_mailTemplate_get( ZBSEMAIL_QUOTEACCEPTED ); $bodyHTML = $message_content->zbsmail_body; $proposalEmailTitle = __( 'Proposal Notification', 'zero-bs-crm' ); $zbs_biz_name = zeroBSCRM_getSetting( 'businessname' ); $zbs_biz_yourname = zeroBSCRM_getSetting( 'businessyourname' ); $zbs_biz_extra = zeroBSCRM_getSetting( 'businessextra' ); $zbs_biz_youremail = zeroBSCRM_getSetting( 'businessyouremail' ); $zbs_biz_yoururl = zeroBSCRM_getSetting( 'businessyoururl' ); // build msg-content html $bodyHTML = $placeholder_templating->replace_placeholders( array( 'global', 'quote', 'contact' ), $bodyHTML, $replacements, array( ZBS_TYPE_QUOTE => $quote, ZBS_TYPE_CONTACT => $quote_contact ) ); // For now, use this, ripped from invoices: // (We need to centralise) $bizInfoTable = '<table class="table zbs-table" style="width:100%;">'; $bizInfoTable .= '<tbody>'; $bizInfoTable .= '<tr><td style="font-family:sans-serif;font-size:14px;vertical-align:top;padding-bottom:5px;"><strong>' . $zbs_biz_name . '</strong></td></tr>'; $bizInfoTable .= '<tr><td style="font-family:sans-serif;font-size:14px;vertical-align:top;padding-bottom:5px;">' . $zbs_biz_yourname . '</td></tr>'; $bizInfoTable .= '<tr><td style="font-family:sans-serif;font-size:14px;vertical-align:top;padding-bottom:5px;">' . $zbs_biz_extra . '</td></tr>'; // $bizInfoTable .= '<tr class="top-pad"><td>'.$zbs_biz_youremail.'</td></tr>'; // $bizInfoTable .= '<tr><td>'.$zbs_biz_yoururl.'</td></tr>'; $bizInfoTable .= '</tbody>'; $bizInfoTable .= '</table>'; // unsub line $unsub_line = __( 'You have received this notification because your proposal has been accepted in CRM', 'zero-bs-crm' ); ##WLREMOVE $unsub_line = __( 'You have received this notification because your proposal has been accepted in Jetpack CRM', 'zero-bs-crm' ); ##/WLREMOVE $unsub_line .= __( '. If you believe this was sent in error, please reply and let us know.', 'zero-bs-crm' ); // build body html $replacements = $placeholder_templating->get_generic_replacements(); $replacements['title'] = $proposalEmailTitle; $replacements['msg-content'] = $bodyHTML; $replacements['unsub-line'] = $unsub_line; $replacements['biz-info'] = $bizInfoTable; $replacements['quote-url'] = zeroBSCRM_portal_linkObj( $quoteID, ZBS_TYPE_QUOTE ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $replacements['quote-edit-url'] = jpcrm_esc_link( 'edit', $quoteID, 'zerobs_quote' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $replacements['quote-value'] = $quote['value'] ? zeroBSCRM_formatCurrency( $quote['value'] ) : ''; $settings = $zbs->settings->getAll(); if ( $settings['currency'] && $settings['currency']['strval'] ) { $replacements['quote-currency'] = $settings['currency']['strval']; } $html = $placeholder_templating->replace_placeholders( array( 'global', 'quote' ), $templatedHTML, $replacements ); } // return if ( !$return ) { echo $html; exit(); } } return $html; } // FAIL return; } /* ====================================================== / ZBS Quotes - Generate HTML (notification email) ====================================================== */ /* ====================================================== ZBS Invoices - Generate HTML (notification emails) ====================================================== */ function zeroBSCRM_invoice_generateNotificationHTML( $invoiceID = -1, $return = true ) { if ( !empty( $invoiceID ) && $invoiceID > 0 ) { global $zbs; $invoice = $zbs->DAL->invoices->getInvoice( $invoiceID ); // load templater $placeholder_templating = $zbs->get_templating(); // body template $mailTemplate = zeroBSCRM_mailTemplate_get( ZBSEMAIL_EMAILINVOICE ); $bodyHTML = $mailTemplate->zbsmail_body; // html template $html = jpcrm_retrieve_template( 'emails/default-email.html', false ); $html = $placeholder_templating->replace_single_placeholder( 'msg-content', $bodyHTML, $html ); // Act if ( !empty( $html ) ) { // this was refactored as was duplicate code. // now all wired through zeroBSCRM_invoicing_generateInvoiceHTML $html = zeroBSCRM_invoicing_generateInvoiceHTML( $invoiceID, 'notification', $html ); // get generics $replacements = $placeholder_templating->get_generic_replacements(); // replacements $html = $placeholder_templating->replace_placeholders( array( 'global', 'invoice' ), $html, $replacements, array( ZBS_TYPE_INVOICE => $invoice ) ); // return if ( !$return ) { echo $html; exit(); } } return $html; } // FAIL return; } // generates statement email html based on template in sys mail function zeroBSCRM_statement_generateNotificationHTML( $contact_id = -1, $return = true ) { global $zbs; if ( !empty( $contact_id ) ) { $contact = $zbs->DAL->contacts->getContact( $contact_id ); $pWrap = '<p style="font-family:sans-serif;font-size:14px;font-weight:normal;margin:0;Margin-bottom:15px;">'; // load templater $placeholder_templating = $zbs->get_templating(); // Get templated notify email // body template $mailTemplate = zeroBSCRM_mailTemplate_get( ZBSEMAIL_STATEMENT ); $bodyHTML = $mailTemplate->zbsmail_body; // html template $html = jpcrm_retrieve_template( 'emails/default-email.html', false ); $html = $placeholder_templating->replace_single_placeholder( 'msg-content', $bodyHTML, $html ); // Act if ( !empty( $html ) ) { // the business info from the settings $zbs_biz_name = zeroBSCRM_getSetting( 'businessname' ); $zbs_biz_yourname = zeroBSCRM_getSetting( 'businessyourname' ); $zbs_biz_extra = zeroBSCRM_getSetting( 'businessextra' ); // For now, use this, ripped from invoices: // (We need to centralise) $bizInfoTable = '<table class="table zbs-table" style="width:100%;">'; $bizInfoTable .= '<tbody>'; $bizInfoTable .= '<tr><td style="font-family:sans-serif;font-size:14px;vertical-align:top;padding-bottom:5px;"><strong>' . $zbs_biz_name . '</strong></td></tr>'; $bizInfoTable .= '<tr><td style="font-family:sans-serif;font-size:14px;vertical-align:top;padding-bottom:5px;">' . $zbs_biz_yourname . '</td></tr>'; $bizInfoTable .= '<tr><td style="font-family:sans-serif;font-size:14px;vertical-align:top;padding-bottom:5px;">' . $zbs_biz_extra . '</td></tr>'; $bizInfoTable .= '</tbody>'; $bizInfoTable .= '</table>'; // get generics $replacements = $placeholder_templating->get_generic_replacements(); // view in portal? $replacements['title'] = __( 'Statement', 'zero-bs-crm' ); $replacements['biz-info'] = $bizInfoTable; // replacements $html = $placeholder_templating->replace_placeholders( array( 'global', 'contact' ), $html, $replacements, array( ZBS_TYPE_CONTACT => $contact ) ); // return if ( !$return ) { echo $html; exit(); } } return $html; } // FAIL return; } /* ====================================================== / ZBS Invoices - Generate HTML (notification email) ====================================================== */ /* ====================================================== ZBS Portal - Generate HTML (notification emails) ====================================================== */ function zeroBSCRM_Portal_generateNotificationHTML( $pwd = -1, $return = true, $email = null, $contact_id = false ) { global $zbs; if ( ! empty( $pwd ) ) { $html = ''; $pWrap = '<p style="font-family:sans-serif;font-size:14px;font-weight:normal;margin:0;Margin-bottom:15px;">'; // Get templated notify email $templatedHTML = jpcrm_retrieve_template( 'emails/default-email.html', false ); // load templater $placeholder_templating = $zbs->get_templating(); // Act if ( !empty( $templatedHTML ) ) { // body $message_content = zeroBSCRM_mailTemplate_get( ZBSEMAIL_CLIENTPORTALWELCOME ); $bodyHTML = $message_content->zbsmail_body; $html = $placeholder_templating->replace_single_placeholder( 'msg-content', $bodyHTML, $templatedHTML ); // get replacements $replacements = $placeholder_templating->get_generic_replacements(); // replacements $replacements['title'] = __( 'Welcome to your Client Portal', 'zero-bs-crm' ); $replacements['email'] = $email; // if got contact_id (DAL3+) pass the contact object (so user can use ##ASSIGNED-TO-NAME##) $replacement_objects = array(); if ( $contact_id > 0 ) { $replacement_objects[ ZBS_TYPE_CONTACT ] = zeroBS_getCustomer( $contact_id ); } // replacements $html = $placeholder_templating->replace_placeholders( array( 'global', 'contact' ), $html, $replacements, $replacement_objects ); // return if ( !$return ) { echo $html; exit(); } } return $html; } // FAIL return; } #} adapted from above. pw reset email function zeroBSCRM_Portal_generatePWresetNotificationHTML( $pwd, $return, $contact ) { global $zbs; if ( !empty( $pwd ) ) { $html = ''; $pWrap = '<p style="font-family:sans-serif;font-size:14px;font-weight:normal;margin:0;Margin-bottom:15px;">'; // Get templated notify email $templatedHTML = jpcrm_retrieve_template( 'emails/default-email.html', false ); // load templater $placeholder_templating = $zbs->get_templating(); // Act if ( !empty( $templatedHTML ) ) { $message_content = zeroBSCRM_mailTemplate_get( ZBSEMAIL_CLIENTPORTALPWREST ); $bodyHTML = $message_content->zbsmail_body; $html = $placeholder_templating->replace_single_placeholder( 'msg-content', $bodyHTML, $templatedHTML ); // get replacements $replacements = $placeholder_templating->get_generic_replacements(); // replacements $replacements['title'] = __( 'Your Client Portal Password has been reset', 'zero-bs-crm' ); $replacements['email'] = $contact['email']; $replacements['password'] = $pwd; // replacements $html = $placeholder_templating->replace_placeholders( array( 'global', 'contact' ), $html, $replacements, array( ZBS_TYPE_CONTACT => $contact ) ); // return if ( !$return ) { echo $html; exit(); } } return $html; } // FAIL return; } function jpcrm_task_generate_notification_html( $return = true, $email = false, $task_id = -1, $task = false ) { global $zbs; // checks if ( !zeroBSCRM_validateEmail( $email ) || $task_id < 1 ) { return false; } // Get templated notify email $templatedHTML = jpcrm_retrieve_template( 'emails/default-email.html', false ); // prep $html = ''; $pWrap = '<p style="font-family:sans-serif;font-size:14px;font-weight:normal;margin:0;Margin-bottom:15px;">'; // load templater $placeholder_templating = $zbs->get_templating(); // Act if ( !empty( $templatedHTML ) ) { // retrieve task notification $message_content = zeroBSCRM_mailTemplate_get( ZBSEMAIL_TASK_NOTIFICATION ); $bodyHTML = $message_content->zbsmail_body; $html = $placeholder_templating->replace_single_placeholder( 'msg-content', $bodyHTML, $templatedHTML ); // get replacements $replacements = $placeholder_templating->get_generic_replacements(); // retrieve task (if not passed) if ( !is_array( $task ) ) { $task = $zbs->DAL->events->getEvent( $task_id ); } // vars / html gen $task_url = jpcrm_esc_link( 'edit', $task['id'], ZBS_TYPE_TASK ); $task_html = '<p>' . nl2br( $task['desc'] ) . '</p>'; $task_html .= '<hr /><p style="text-align:center">'; $task_html .= __( 'Your task starts at ', 'zero-bs-crm' ) . '<strong>' . $task['start_date'] . '</strong><br/>'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // $task_html .= __( 'to: ', 'zero-bs-crm' ) . $task['end_date']; $task_html .= '</p><hr />'; // replacements $replacements['title'] = __( 'Your Task is starting soon', 'zero-bs-crm' ); $replacements['task-title'] = '<h2>' . $task['title'] . '</h2>'; $replacements['task-body'] = $task_html; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $replacements['task-link-button'] = '<div style="text-align:center;margin:1em;margin-top:2em">' . __( 'You can view your task at the following URL: ', 'zero-bs-crm' ) . '<br />' . zeroBSCRM_mailTemplate_emailSafeButton( $task_url, __( 'View Task', 'zero-bs-crm' ) ) . '</div>'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // replacements $html = $placeholder_templating->replace_placeholders( array( 'global', 'event', 'contact', 'company', ), $html, $replacements, array( ZBS_TYPE_TASK => $task, ZBS_TYPE_CONTACT => isset( $task['contact'] ) ? $task['contact'][0] : null, ZBS_TYPE_COMPANY => isset( $task['company'] ) ? $task['company'][0] : null, ) ); // return if ( !$return ) { echo $html; exit(); } } return $html; } /* ====================================================== / ZBS Invoices - Generate HTML (notification emails) ====================================================== */ /* ====================================================== ZBS Single Send Emails - Generate HTML ====================================================== */ /* * Deprecated, included to avoid Error 500's in outdated extensions */ function zeroBSCRM_mailTemplates_directMsg( $return = true, $content = '', $title = '' ) { zeroBSCRM_DEPRECATEDMSG( 'zeroBSCRM_mailTemplates_directMsg was deprecated in 4.4.0, Please use jpcrm_mailTemplates_single_send_templated()' ); return jpcrm_mailTemplates_single_send_templated( $return, $content, $title ); } /** * Creates the html of a single send email based on passed details * Note this diverges from jpcrm_mailTemplates_generic_msg because it takes in $contact_object * ... and makes sense to have it's own abstraction in any case (as later we can apply specific theming etc.) * Replaces zeroBSCRM_mailTemplates_directMsg */ function jpcrm_mailTemplates_single_send_templated( $return=true, $content='', $title = '', $contact_object = false ){ global $zbs; $html = ''; $pWrap = '<p style="font-family:sans-serif;font-size:14px;font-weight:normal;margin:0;Margin-bottom:15px;">'; // load templater $placeholder_templating = $zbs->get_templating(); // Get templated notify email $templatedHTML = jpcrm_retrieve_template( 'emails/default-email.html', false ); // Act if (!empty($templatedHTML)){ // replacements (initial templating) $html = $placeholder_templating->replace_single_placeholder( 'msg-content', $content, $templatedHTML ); // get replacements $replacements = $placeholder_templating->get_generic_replacements(); $replacements['title'] = $title; // enact replacements $html = $placeholder_templating->replace_placeholders( array( 'global', 'contact', 'company' ), $html, $replacements, array( ZBS_TYPE_CONTACT => $contact_object ) ); // return if ( !$return ) { echo $html; exit(); } } return $html; } /* ====================================================== / ZBS Single Send Emails - Generate HTML ====================================================== */ /* ====================================================== ZBS Generic Emails - Generate HTML ====================================================== */ function jpcrm_mailTemplates_generic_msg($return=true, $content='', $title = ''){ global $zbs; $html = ''; $pWrap = '<p style="font-family:sans-serif;font-size:14px;font-weight:normal;margin:0;Margin-bottom:15px;">'; // load templater $placeholder_templating = $zbs->get_templating(); // Get templated notify email $templatedHTML = jpcrm_retrieve_template( 'emails/default-email.html', false ); // Act if (!empty($templatedHTML)){ // replacements (initial templating) $html = $placeholder_templating->replace_single_placeholder( 'msg-content', $content, $templatedHTML ); // get replacements $replacements = $placeholder_templating->get_generic_replacements(); $replacements['title'] = $title; // replacements $html = $placeholder_templating->replace_placeholders( array( 'global', 'contact', 'company' ), $html, $replacements ); // return if ( !$return ) { echo $html; exit(); } } return $html; } /* ====================================================== / ZBS Generic Emails - Generate HTML ====================================================== */ /* ====================================================== ZBS Mail Delivery Tests ====================================================== */ function zeroBSCRM_mailDelivery_generateTestHTML($return=true){ global $zbs; $html = ''; $pWrap = '<p style="font-family:sans-serif;font-size:14px;font-weight:normal;margin:0;Margin-bottom:15px;">'; // load templater $placeholder_templating = $zbs->get_templating(); // Get templated notify email $templatedHTML = jpcrm_retrieve_template( 'emails/default-email.html', false ); #} Act if (!empty($templatedHTML)){ #} Actual body: $bodyHTML = ''; $bodyHTML = "<div style='text-align:center'><h1>".__('Testing Mail Delivery Option',"zero-bs-crm")."</h1>"; $bodyHTML .= '<p>'.__("This is a test email, sent to you by Jetpack CRM. If you're receiving this loud and clear, it means your mail delivery setup has been successful, congratulations!","zero-bs-crm").'</p>'; ##WLREMOVE $bodyHTML .= '<p>'.__("Why not follow us on twitter to celebrate?","zero-bs-crm").'</p>'; $bodyHTML .= '<p><a href="https://twitter.com/jetpackcrm">@jetpackcrm</a></p>'; ##/WLREMOVE $bodyHTML .= "</div>"; // replacements (initial templating) $html = $placeholder_templating->replace_single_placeholder( 'msg-content', $bodyHTML, $templatedHTML ); // get replacements $replacements = $placeholder_templating->get_generic_replacements(); $replacements['title'] = __( 'Testing Mail Delivery Option', 'zero-bs-crm' ); $replacements['biz-info'] = '<p>'.__( "Sent from your friendly neighbourhood CRM.", "zero-bs-crm" ).'</p>'; $replacements['unsub-line'] = '<p>'.__( "Have a great day.", "zero-bs-crm" ).'</p>'; // replacements $html = $placeholder_templating->replace_placeholders( array( 'global', 'contact', 'company' ), $html, $replacements ); // return if ( !$return ) { echo $html; exit(); } } return $html; } /* ====================================================== / ZBS Mail Delivery Tests ====================================================== */ /* ====================================================== ZBS Mail Templating General ====================================================== */ function zeroBSCRM_mailTemplate_poweredByHTML( $type='html' ) { ##WLREMOVE global $zbs; $showpoweredby_public = $zbs->settings->get( 'showpoweredby_public' ) === 1 ? true : false; if ( $showpoweredby_public ) { if ( $type == 'html' ) { global $zbs; return sprintf( __( 'Powered by <a href="%s">Jetpack CRM</a>', 'zero-bs-crm' ), $zbs->urls['home'] ); } elseif ( $type == 'text' ) { return __( 'Powered by Jetpack CRM', 'zero-bs-crm' ); } } ##/WLREMOVE return ''; } function zeroBSCRM_mailTemplate_getHeaders($templateID = -1){ if($templateID > 0){ $mailTemplate = zeroBSCRM_mailTemplate_get($templateID); //headers being set... $headers = array('Content-Type: text/html; charset=UTF-8'); //extra header settings.. // We don't use these now, as mail is sent out properly via Mail Delivery //$headers[] = 'From: '. esc_html($mailTemplate->zbsmail_fromname).' <'.sanitize_email($mailTemplate->zbsmail_fromaddress).'>'; //$headers[] = 'Reply-To: ' . sanitize_email($mailTemplate->zbsmail_replyto); // but we use this :) if (isset($mailTemplate->zbsmail_bccto) && !empty($mailTemplate->zbsmail_bccto)) $headers[] = 'Bcc: ' . sanitize_email($mailTemplate->zbsmail_bccto); }else{ $headers = array('Content-Type: text/html; charset=UTF-8'); } return $headers; } // adapted from https://buttons.cm/ function zeroBSCRM_mailTemplate_emailSafeButton($url='',$str=''){ return '<div><!--[if mso]> <v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="'.$url.'" style="height:53px;v-text-anchor:middle;width:200px;" arcsize="8%" stroke="f" fillcolor="#49a9ce"> <w:anchorlock/> <center> <![endif]--> <a href="'.$url.'" style="background-color:#49a9ce;border-radius:4px;color:#ffffff;display:inline-block;font-family:sans-serif;font-size:13px;font-weight:700;line-height:53px;text-align:center;text-decoration:none;width:200px;-webkit-text-size-adjust:none;">'.$str.'</a> <!--[if mso]> </center> </v:roundrect> <![endif]--></div>'; } // replaces generic attrs in one place, e.g. loginlink, loginurl // note as placeholder templates hard-override empty placeholders not passed, // here we pass true as the forth variable to leave existing ##PLACEHOLDERS## intact // (if leave_existing_placeholders = true) // // TL;DR; Phase out using this function, instead get the replacements for use with 'replace_placeholders' // ... from ->get_generic_replacements() function zeroBSCRM_mailTemplate_genericReplaces( $html='', $leave_existing_placeholders = true ){ global $zbs; // load templater $placeholder_templating = $zbs->get_templating(); // get replacements $replacements = $placeholder_templating->get_generic_replacements(); // replace return $placeholder_templating->replace_placeholders( array( 'global' ), $html, $replacements, $leave_existing_placeholders ); } /* ====================================================== / ZBS Mail Templating General ====================================================== */
projects/plugins/crm/includes/ZeroBSCRM.DAL3.Obj.Segments.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V3.0+ * * Copyright 2020 Automattic * * Date: 14/01/19 */ use Automattic\JetpackCRM\Segment_Condition_Exception; defined( 'ZEROBSCRM_PATH' ) || exit; /** * ZBS DAL >> Segments * * @author Woody Hayday <hello@jetpackcrm.com> * @version 2.0 * @access public * @see https://jetpackcrm.com/kb */ class zbsDAL_segments extends zbsDAL_ObjectLayer { protected $objectType = ZBS_TYPE_SEGMENT; protected $objectModel = array( // ID 'ID' => array('fieldname' => 'ID', 'format' => 'int'), // site + team generics 'zbs_site' => array('fieldname' => 'zbs_site', 'format' => 'int'), 'zbs_team' => array('fieldname' => 'zbs_team', 'format' => 'int'), 'zbs_owner' => array('fieldname' => 'zbs_owner', 'format' => 'int'), // other fields 'name' => array('fieldname' => 'zbsseg_name', 'format' => 'str'), 'slug' => array('fieldname' => 'zbsseg_slug', 'format' => 'str'), 'matchtype' => array('fieldname' => 'zbsseg_matchtype', 'format' => 'str'), 'created' => array('fieldname' => 'zbsseg_created', 'format' => 'uts'), 'lastupdated' => array('fieldname' => 'zbsseg_lastupdated', 'format' => 'uts'), 'compilecount' => array('fieldname' => 'zbsseg_compilecount', 'format' => 'int'), 'lastcompiled' => array('fieldname' => 'zbsseg_lastcompiled', 'format' => 'uts'), ); function __construct($args=array()) { #} =========== LOAD ARGS ============== $defaultArgs = array( //'tag' => false, ); foreach ($defaultArgs as $argK => $argV){ $this->$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $this->$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$this->$argK = $newData;} else { $this->$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= } // =============================================================================== // =========== SEGMENTS ======================================================= // generic get Company (by ID) // Super simplistic wrapper used by edit page etc. (generically called via dal->contacts->getSingle etc.) public function getSingle($ID=-1){ return $this->getSegment($ID); } // This was actually written pre DAL2 and so still has some legacy layout of func // etc. To be slowly refined if needed. /** * get a segment (header line) */ public function getSegment($segmentID=-1,$withConditions=false,$checkOwnershipID=false){ if ($segmentID > 0){ global $ZBSCRM_t,$wpdb; $additionalWHERE = ''; $queryVars = array($segmentID); // check ownership // THIS ShoULD BE STANDARDISED THROUGHOUT DAL (ON DB2) // $checkOwnershipID = ID = check against that ID // $checkOwnershipID = true = check against get_current_user_id // $checkOwnershipID = false = do not check if ($checkOwnershipID === true){ $segmentOwner = get_current_user_id(); } elseif ($checkOwnershipID > 0){ $segmentOwner = (int)$checkOwnershipID; } // else is false, don't test if (isset($segmentOwner)){ // add check $additionalWHERE = 'AND zbs_owner = %d'; $queryVars[] = $segmentOwner; } $potentialSegment = $wpdb->get_row( $this->prepare("SELECT * FROM ".$ZBSCRM_t['segments']." WHERE ID = %d ".$additionalWHERE."ORDER BY ID ASC LIMIT 0,1",$queryVars), OBJECT ); if (isset($potentialSegment) && isset($potentialSegment->ID)){ #} Retrieved :) fill + return // tidy $segment = $this->tidy_segment($potentialSegment); if ($withConditions) { $segment['conditions'] = $this->getSegmentConditions($segment['id']); } // this catches any 'broken' state segments. // ... for now this is done via a setting, later we should build an error stack via DAL #refined-error-stack $error_string = $this->segment_error( $segment['id'] ); if ( !empty( $error_string ) ){ $segment['error'] = zeroBSCRM_textExpose( $error_string ); } return $segment; } } return false; } /** * get Sements Pass -1 for $perPage and $page and this'll return ALL */ public function getSegments($ownerID=-1,$perPage=10,$page=0,$withConditions=false,$searchPhrase='',$inArr='',$sortByField='',$sortOrder='DESC'){ global $zbs,$ZBSCRM_t,$wpdb; $segments = false; // build query $sql = "SELECT * FROM ".$ZBSCRM_t['segments']; $wheres = array(); $params = array(); $orderByStr = ''; // Owner // escape (all) if ($ownerID != -99){ if ($ownerID === -1) $ownerID = get_current_user_id(); if (!empty($ownerID)) $wheres['zbs_owner'] = array('=',$ownerID,'%d'); } // search phrase if (!empty($searchPhrase)){ $wheres['zbsseg_name'] = array('LIKE','%'.$searchPhrase.'%','%s'); } // in array if (is_array($inArr) && count($inArr) > 0){ $wheres['ID'] = array('IN','('.implode(',', $inArr).')','%s'); } // add where's to SQL // + // feed in params $whereStr = ''; if (count($wheres) > 0) foreach ($wheres as $key => $whereArr) { if (!empty($whereStr)) $whereStr .= ' AND '; else $whereStr .= ' WHERE '; // add in - NOTE: this is TRUSTING key + whereArr[0] $whereStr .= $key.' '.$whereArr[0].' '.$whereArr[2]; // feed in params $params[] = $whereArr[1]; } // append to sql $sql .= $whereStr; // sort by if (!empty($sortByField)){ if (!in_array($sortOrder, array('DESC','ASC'))) $sortOrder = 'DESC'; // parametise order field as is unchecked //$orderByStr = ' ORDER BY %s '.$sortOrder; //$params[] = $sortByField; $orderByStr = ' ORDER BY '.$sortByField.' '.$sortOrder; } // pagination if ($page == -1 && $perPage == -1){ // NO LIMITS :o } else { // Because SQL USING zero indexed page numbers, we remove -1 here // ... DO NOT change this without seeing usage of the function (e.g. list view) - which'll break $page = (int)$page-1; if ($page < 0) $page = 0; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $orderByStr .= sprintf( ' LIMIT %d, %d ', (int) $page * (int) $perPage, (int) $perPage ); } // append to sql $sql .= $orderByStr; $query = $this->prepare($sql,$params); try { $potentialSegments = $wpdb->get_results( $query, OBJECT ); } catch (Exception $e){ // error with sql :/ for now nothin } if (isset($potentialSegments) && is_array($potentialSegments)) $segments = $potentialSegments; // TIDY $res = array(); if (count($segments) > 0) foreach ($segments as $segment) { // tidy $resArr = $this->tidy_segment($segment); // TO ADD to query / here withConditions // TODO: REFACTOR into query? More efficient? if ($withConditions) $resArr['conditions'] = $this->getSegmentConditions($segment->ID); // this catches any 'broken' state segments. // ... for now this is done via a setting, later we should build an error stack via DAL #refined-error-stack $error_string = $this->segment_error( $segment->ID ); if ( !empty( $error_string ) ){ $resArr['error'] = zeroBSCRM_textExpose( $error_string ); } $res[] = $resArr; } return $res; } // brutal simple temp func (should be a wrapper really. segments to tidy up post DAL2 other obj) public function getSegmentCount(){ global $ZBSCRM_t,$wpdb; // build query $sql = "SELECT COUNT(ID) FROM ".$ZBSCRM_t['segments']; return $wpdb->get_var($sql); } /** * deletes a Segment object (and its conditions) * * @param array $args Associative array of arguments * id * * @return int success; */ public function deleteSegment($args=array()){ global $ZBSCRM_t, $wpdb, $zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'saveOrphans' => -1 ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} Check ID & Delete :) $id = (int)$id; if (!empty($id) && $id > 0) { $segment = $this->getSegment( $id ); $deleted = zeroBSCRM_db2_deleteGeneric($id,'segments'); // delete segment conditions? // check $deleted? $del = $wpdb->delete( $ZBSCRM_t['segmentsconditions'], array( // where 'zbscondition_segmentid' => $id ), array( '%d' ) ); #} Add to automator zeroBSCRM_FireInternalAutomator('segment.delete',array( 'id' => $id, 'saveOrphans' => $saveOrphans, )); return $del; } return false; } /** * tidys a segment */ public function tidy_segment($obj=false){ $res = false; if (isset($obj->ID)){ $res = array(); $res['id'] = $obj->ID; $res['name'] = $obj->zbsseg_name; $res['slug'] = $obj->zbsseg_slug; $res['matchtype'] = $obj->zbsseg_matchtype; $res['created'] = $obj->zbsseg_created; $res['lastupdated'] = $obj->zbsseg_lastupdated; $res['compilecount'] = $obj->zbsseg_compilecount; $res['lastcompiled'] = $obj->zbsseg_lastcompiled; // pretty date outputs for list viw $res['createddate'] = zeroBSCRM_locale_utsToDate($obj->zbsseg_created); $res['lastcompileddate'] = zeroBSCRM_locale_utsToDate($obj->zbsseg_lastcompiled); } return $res; } /** * tidys a segment condition */ public function tidy_segment_condition($obj=false){ $res = false; if (isset($obj->ID)){ $res = array(); $res['id'] = $obj->ID; $res['segmentID'] = $obj->zbscondition_segmentid; $res['type'] = $obj->zbscondition_type; $res['operator'] = $obj->zbscondition_op; $res['value'] = zeroBSCRM_textExpose($obj->zbscondition_val); $res['value2'] = zeroBSCRM_textExpose($obj->zbscondition_val_secondary); // applies any necessary conversions e.g. uts -> date $res['valueconv'] = zeroBSCRM_segments_typeConversions($res['value'],$res['type'],$res['operator'],'out'); $res['value2conv'] = zeroBSCRM_segments_typeConversions($res['value2'],$res['type'],$res['operator'],'out'); } return $res; } /** * This is designed to mimic zeroBS_getSegments, but only to return a total count :) */ public function getSegmentsCountIncParams($ownerID=-1,$perPage=10,$page=0,$withConditions=false,$searchPhrase='',$inArr='',$sortByField='',$sortOrder='DESC'){ global $zbs,$ZBSCRM_t,$wpdb; $segmentCount = false; // build query $sql = "SELECT COUNT(ID) segcount FROM ".$ZBSCRM_t['segments']; $wheres = array(); $params = array(); $orderByStr = ''; // Owner // escape (all) if ($ownerID != -99){ if ($ownerID === -1) $ownerID = get_current_user_id(); if (!empty($ownerID)) $wheres['zbs_owner'] = array('=',$ownerID,'%d'); } // search phrase if (!empty($searchPhrase)){ $wheres['zbsseg_name'] = array('LIKE',$searchPhrase,'%s'); } // in array if (is_array($inArr) && count($inArr) > 0){ $wheres['ID'] = array('IN','('.implode(',', $inArr).')','%s'); } // add where's to SQL // + // feed in params $whereStr = ''; if (count($wheres) > 0) foreach ($wheres as $key => $whereArr) { if (!empty($whereStr)) $whereStr .= ' AND '; else $whereStr .= ' WHERE '; // add in - NOTE: this is TRUSTING key + whereArr[0] $whereStr .= $key.' '.$whereArr[0].' '.$whereArr[2]; // feed in params $params[] = $whereArr[1]; } // append to sql $sql .= $whereStr; $query = $this->prepare($sql,$params); try { $potentialSegmentCount = $wpdb->get_row( $query, OBJECT ); } catch (Exception $e){ // error with sql :/ for now nothin } if (isset($potentialSegmentCount) && isset($potentialSegmentCount->segcount)) $segmentCount = $potentialSegmentCount->segcount; return $segmentCount; } /** * builds a preview (top 5 + count) of a set of conditions which could be against a segment * expects a filtered list of conditions (e.g. zeroBSCRM_segments_filterConditions if sent through POST) * * Throws @Segment_Condition_Exception */ public function previewSegment($conditions=array(),$matchType='all',$countOnly=false){ // retrieve getContacts arguments from a list of segment conditions $contactGetArgs = $this->segmentConditionsToArgs($conditions,$matchType); // add top 5 + count params $contactGetArgs['sortByField'] = 'RAND()'; $contactGetArgs['sortOrder'] = ''; $contactGetArgs['page'] = 0; $contactGetArgs['perPage'] = 5; $contactGetArgs['ignoreowner'] = zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT); // count ver $countContactGetArgs = $contactGetArgs; $countContactGetArgs['perPage'] = 100000; $countContactGetArgs['count'] = true; // count only if ( $countOnly ) { return $this->DAL()->contacts->getContacts($countContactGetArgs); } // Retrieve return array( // DEBUG //'conditions' => $conditions, // TEMP - remove this //'args' => $contactGetArgs, // TEMP - remove this 'count'=>$this->DAL()->contacts->getContacts($countContactGetArgs), 'list'=>$this->DAL()->contacts->getContacts($contactGetArgs) ); } /** * used by previewSegment and getSegmentAudience to build condition args */ public function segmentConditionsToArgs($conditions=array(),$matchType='all'){ if (is_array($conditions) && count($conditions) > 0){ $contactGetArgs = array(); $conditionIndx = 0; // this allows multiple queries for SAME field (e.g. status = x or status = y) // cycle through & add to contact request arr foreach ($conditions as $condition){ $newArgs = $this->segmentConditionArgs($condition,$conditionIndx); $additionalWHERE = false; // legit? merge (must be recursive) if (is_array($newArgs)) $contactGetArgs = array_merge_recursive($contactGetArgs,$newArgs); $conditionIndx++; } // match type ALL is default, this switches to ANY if ($matchType == 'one') $contactGetArgs['whereCase'] = 'OR'; return $contactGetArgs; } return array(); } /** * get a segment (header line) */ public function getSegmentBySlug($segmentSlug=-1,$withConditions=false,$checkOwnershipID=false){ if (!empty($segmentSlug)){ global $ZBSCRM_t,$wpdb; $additionalWHERE = ''; $queryVars = array($segmentSlug); // check ownership // THIS ShoULD BE STANDARDISED THROUGHOUT DAL (ON DB2) // $checkOwnershipID = ID = check against that ID // $checkOwnershipID = true = check against get_current_user_id // $checkOwnershipID = false = do not check if ($checkOwnershipID === true){ $segmentOwner = get_current_user_id(); } elseif ($checkOwnershipID > 0){ $segmentOwner = (int)$checkOwnershipID; } // else is false, don't test if (isset($segmentOwner)){ // add check $additionalWHERE = 'AND zbs_owner = %d'; $queryVars[] = $segmentOwner; } $potentialSegment = $wpdb->get_row( $this->prepare("SELECT * FROM ".$ZBSCRM_t['segments']." WHERE zbsseg_slug = %s ".$additionalWHERE."ORDER BY ID ASC LIMIT 0,1",$queryVars), OBJECT ); if (isset($potentialSegment) && isset($potentialSegment->ID)){ #} Retrieved :) fill + return // tidy $segment = $this->tidy_segment($potentialSegment); if ($withConditions) { $segment['conditions'] = $this->getSegmentConditions($segment['id']); } return $segment; } } return false; } /* * Compatibility for typo: * #backward-compatibility */ public function getSegementAudience($segmentID=-1,$page=0,$perPage=20,$sortByField='ID',$sortOrder='DESC',$onlyCount=false,$withDND=false){ return $this->getSegmentAudience( $segmentID, $page, $perPage, $sortByField, $sortOrder, $onlyCount, $withDND ); } /** * Runs a filtered search on customers based on a segment's condition * * @param int $segment_id ID of segment. * @param int $page Page number. * @param int $per_page Number of objects per page. * @param int $sort_by_field Field to sort by. * @param int $sort_order Sort order. * @param int $only_count Only return counts. * @param int $with_dnd Return DND info. * @param int $limited_fields Only return specific fields. * * @return array or count ($onlyCount) */ public function getSegmentAudience( $segment_id = -1, $page = 0, $per_page = 20, $sort_by_field = 'ID', $sort_order = 'DESC', $only_count = false, $with_dnd = false, $limited_fields = false ) { // assumes sensible paging + sort vars... no checking of them if ( $segment_id > 0 ) { #} Retrieve segment + conditions $segment = $this->getSegment( $segment_id, true ); $conditions = array(); if ( isset( $segment['conditions'] ) ) { $conditions = $segment['conditions']; } $match_type = 'all'; if ( isset( $segment['matchtype'] ) ) { $match_type = $segment['matchtype']; } try { // retrieve getContacts arguments from a list of segment conditions $contact_get_args = $this->segmentConditionsToArgs( $conditions, $match_type ); // Remove any segment area error notice $this->remove_segment_error( $segment_id ); } catch ( Segment_Condition_Exception $exception ) { // We're missing the condition class for one or more of this segment's conditions. $this->segment_error_condition_missing( $segment_id, $exception ); // return fail return false; } // needs to be ownerless for now $contact_get_args['ignoreowner'] = zeroBSCRM_DAL2_ignoreOwnership( ZBS_TYPE_CONTACT ); // add paging params $contact_get_args['sortByField'] = $sort_by_field; $contact_get_args['sortOrder'] = $sort_order; $contact_get_args['page'] = $page; if ( $per_page !== -1 ) { $contact_get_args['perPage'] = $per_page; // over 100k? :o } else { // no limits $contact_get_args['page'] = -1; $contact_get_args['perPage'] = -1; } // count ver if ( $only_count ) { $contact_get_args['page'] = -1; $contact_get_args['perPage'] = -1; $contact_get_args['count'] = true; $count = $this->DAL()->contacts->getContacts( $contact_get_args ); // effectively a compile, so update compiled no on record $this->updateSegmentCompiled( $segment_id, $count, time() ); return $count; } // got dnd? if ( $with_dnd ) { $contact_get_args['withDND'] = true; } // limited fields? if ( is_array( $limited_fields ) ) { $contact_get_args['onlyColumns'] = $limited_fields; } $contact_get_args['withAssigned'] = true; $contacts = $this->DAL()->contacts->getContacts( $contact_get_args ); // if no limits, update compile record (effectively a compile) if ( $contact_get_args['page'] === -1 && $contact_get_args['perPage'] === -1 ) { $this->updateSegmentCompiled( $segment_id, count( $contacts ), time() ); } // Retrieve return $contacts; } return false; } /** * checks all segments against a contact */ public function getSegmentsContainingContact($contactID=-1,$justIDs=false){ $ret = array(); if ($contactID > 0){ // get all segments $segments = $this->getSegments(-1,1000,0,true); if (count($segments) > 0) { foreach ($segments as $segment){ // pass obj to check (saves it querying) if ($this->isContactInSegment($contactID, $segment['id'],$segment)){ // is in segment if ($justIDs) $ret[] = $segment['id']; else $ret[] = $segment; } } // foreach segment } // if segments } // if contact id return $ret; } /** * Checks if a contact matches segment conditions * ... can pass $segmentObj to avoid queries (performance) if already have it */ public function isContactInSegment($contactID=-1,$segmentID=-1,$segmentObj=false){ if ($segmentID > 0 && $contactID > 0){ #} Retrieve segment + conditions if (is_array($segmentObj)) $segment = $segmentObj; else $segment = $this->getSegment($segmentID,true); #} Set these $conditions = array(); if (isset($segment['conditions'])) $conditions = $segment['conditions']; $matchType = 'all'; if (isset($segment['matchtype'])) $matchType = $segment['matchtype']; try { // retrieve getContacts arguments from a list of segment conditions $contactGetArgs = $this->segmentConditionsToArgs($conditions,$matchType); } catch ( Segment_Condition_Exception $exception ){ // We're missing the condition class for one or more of this segment's conditions. $this->segment_error_condition_missing( $segmentID, $exception ); // return false, because of the segment error, we cannot be sure. return false; } // add paging params $contactGetArgs['page'] = -1; $contactGetArgs['perPage'] = -1; $contactGetArgs['count'] = true; // add id check (via rough additionalWhere) if (!isset($contactGetArgs['additionalWhereArr'])) $contactGetArgs['additionalWhereArr'] = array(); $contactGetArgs['additionalWhereArr']['idCheck'] = array("ID",'=','%d',$contactID); // should only ever be 1 or 0 $count = $this->DAL()->contacts->getContacts($contactGetArgs); if ($count == 1) return true; // nope. return false; } return false; } /** * Compiles all segments */ public function compile_all_segments(){ // get all segments $segments = $this->getSegments(-1,1000,0,true); if (count($segments) > 0) foreach ($segments as $segment){ // compile this segment $this->compileSegment( $segment['id'] ); } // foreach segment return false; } /** * Compiles any segments which are affected by a single contact change * includeSegments is an array of id's - this allows you to pass 'what contact was in before' (because these need --1) */ public function compileSegmentsAffectedByContact($contactID=-1,$includeSegments=array()){ if ($contactID > 0){ // get all segments $segments = $this->getSegments(-1,1000,0,true); if (count($segments) > 0) foreach ($segments as $segment){ // pass obj to check (saves it querying) if ($this->isContactInSegment($contactID, $segment['id'],$segment) || in_array($segment['id'], $includeSegments)){ // is in segment // compile this segment $this->compileSegment($segment['id']); } } // foreach segment } // if contact id return false; } /* * Compiles any segments which are affected by a quote change * * This means segments with conditions of type: * quotecount * * Here we accept a @param of @quote to allow future refinements where by exact conditions are compared. */ public function compileSegmentsAffectedByQuote( $quote = array() ){ if ( is_array( $quote ) ){ // get all segments $segments = $this->getSegments(-1,1000,0,true); if (count($segments) > 0) foreach ($segments as $segment){ // does this segment have a condition we're watching for if ( $this->segmentHasConditionType( $segment, array( 'quotecount' ) ) ){ // recompile the segment $this->compileSegment($segment['id']); } } // foreach segment } // if contact id return false; } /* * Compiles any segments which are affected by an invoice change * * This means segments with conditions of type: * invcount * successtotaltransval * * Here we accept a @param of @invoice to allow future refinements where by exact conditions are compared. */ public function compileSegmentsAffectedByInvoice( $invoice = array() ){ if ( is_array( $invoice ) ){ // get all segments $segments = $this->getSegments(-1,1000,0,true); if (count($segments) > 0) foreach ($segments as $segment){ // does this segment have a condition we're watching for if ( $this->segmentHasConditionType( $segment, array( 'invcount', 'successtotaltransval' ) ) ){ // recompile the segment $this->compileSegment($segment['id']); } } // foreach segment } // if contact id return false; } /* * Compiles any segments which are affected by a transaction change * * This means segments with conditions of type: * trancount * successsingletransval * successtotaltransval * successtransref * successtransname * successtransstr * * Here we accept a @param of @transaction to allow future refinements where by exact conditions are compared. * */ public function compileSegmentsAffectedByTransaction( $transaction = array() ){ if ( is_array( $transaction ) ){ // get all segments $segments = $this->getSegments(-1,1000,0,true); if (count($segments) > 0) foreach ($segments as $segment){ // does this segment have a condition we're watching for if ( $this->segmentHasConditionType( $segment, array( 'trancount', 'successsingletransval', 'successtotaltransval', 'successtransref', 'successtransname', 'successtransstr' ) ) ){ // recompile the segment $this->compileSegment($segment['id']); } } // foreach segment } // if contact id return false; } /** * */ public function getSegmentConditions($segmentID=-1){ if ($segmentID > 0){ global $ZBSCRM_t,$wpdb; $potentialSegmentConditions = $wpdb->get_results( $this->prepare("SELECT * FROM ".$ZBSCRM_t['segmentsconditions']." WHERE zbscondition_segmentid = %d",$segmentID) ); if (is_array($potentialSegmentConditions) && count($potentialSegmentConditions) > 0) { $returnConditions = array(); foreach ($potentialSegmentConditions as $condition){ $returnConditions[] = $this->tidy_segment_condition($condition); } return $returnConditions; } } return false; } /** * Simple func to update the segment compiled count (says how many contacts currently in segment) */ public function updateSegmentCompiled($segmentID=-1,$segmentCount=0,$compiledUTS=-1){ global $ZBSCRM_t,$wpdb; if ($segmentID > 0){ // checks $count = 0; if ($segmentCount > 0) $count = (int)$segmentCount; $compiled = time(); if ($compiledUTS > 0) $compiled = (int)$compiledUTS; if ($wpdb->update( $ZBSCRM_t['segments'], array( 'zbsseg_compilecount' => $count, 'zbsseg_lastcompiled' => $compiled ), array( // where 'ID' => $segmentID ), array( '%d', '%d' ), array( '%d' ) ) !== false){ // udpdated return true; } else { // could not update?! return false; } } } /** * */ public function addUpdateSegment($segmentID=-1,$segmentOwner=-1,$segmentName='',$segmentConditions=array(),$segmentMatchType='all',$forceCompile=false){ global $ZBSCRM_t,$wpdb; #} After ops, shall I compile audience? $toCompile = $forceCompile; if ($segmentID > 0){ #} Update a segment #} Owner - if -1 then use current user if ($segmentOwner <= 0) $segmentOwner = get_current_user_id(); #} Empty name = untitled if (empty($segmentName)) $segmentName = __('Untitled Segment',"zero-bs-crm"); // slug auto-updates with name, (fix later if issue) // in fact, just leave as whatever first set? (affects quickfilter URLs etc?) // just did in end #} Generate slug $segmentSlug = $this->makeSlug($segmentName); #} update header line if ($wpdb->update( $ZBSCRM_t['segments'], array( 'zbs_owner' => $segmentOwner, 'zbsseg_name' => $segmentName, 'zbsseg_slug' => $segmentSlug, 'zbsseg_matchtype' => $segmentMatchType, 'zbsseg_lastupdated' => time() ), array( // where 'ID' => $segmentID ), array( '%d', '%s', '%s', '%s', '%d' ), array( '%d' ) ) !== false){ // updated, move on.. // add segment conditions $this->addUpdateSegmentConditions($segmentID,$segmentConditions); // return id $returnID = $segmentID; // force to compile $toCompile = true; $compileID = $segmentID; } else { // could not update?! return false; } } else { #} Add a new segment #} Owner - if -1 then use current user if ($segmentOwner <= 0) $segmentOwner = get_current_user_id(); #} Empty name = untitled (should never happen because of UI) if (empty($segmentName)) $segmentName = __('Untitled Segment',"zero-bs-crm"); #} Generate slug $segmentSlug = $this->makeSlug($segmentName); #} Add header line if ($wpdb->insert( $ZBSCRM_t['segments'], array( 'zbs_owner' => $segmentOwner, 'zbsseg_name' => $segmentName, 'zbsseg_slug' => $segmentSlug, 'zbsseg_matchtype' => $segmentMatchType, 'zbsseg_created' => time(), 'zbsseg_lastupdated' => time(), 'zbsseg_lastcompiled' => time(), // we'll compile it shortly, set as now :) ), array( '%d', '%s', '%s', '%s', '%d', '%d', '%d' ) ) > 0){ // inserted, let's move on $newSegmentID = $wpdb->insert_id; // add segment conditions $this->addUpdateSegmentConditions($newSegmentID,$segmentConditions); // force to compile $toCompile = true; $compileID = $newSegmentID; // return id $returnID = $newSegmentID; } else { // could not insert?! return false; } } // / new // "compile" segments? if ($toCompile && !empty($compileID)){ // compiles + logs how many in segment against record $totalInSegment = $this->compileSegment($compileID); } if (isset($returnID)) return $returnID; else return false; } public function addUpdateSegmentConditions($segmentID=-1,$conditions=array()){ if ($segmentID > 0 && is_array($conditions)){ // lazy - here I NUKE all existing conditions then readd... $this->removeSegmentConditions($segmentID); if (is_array($conditions) && count($conditions) > 0){ $retConditions = array(); foreach ($conditions as $sCondition){ $newConditionID = $this->addUpdateSegmentCondition(-1,$segmentID,$sCondition); if (!empty($newConditionID)){ // new condition added, insert $retConditions[$newConditionID] = $sCondition; } else { // error inserting condition?! return false; } } return $retConditions; } } return array(); } /** * */ public function addUpdateSegmentCondition($conditionID=-1,$segmentID=-1,$conditionDetails=array()){ global $ZBSCRM_t,$wpdb; #} Check/build empty condition details $condition = array( 'type' => '', 'operator' => '', 'val' => '', 'valsecondary' => '' ); if (isset($conditionDetails['type'])) $condition['type'] = $conditionDetails['type']; if (isset($conditionDetails['value'])) $condition['val'] = $conditionDetails['value']; if (isset($conditionDetails['operator']) && $conditionDetails['operator'] !== -1) $condition['operator'] = $conditionDetails['operator']; if (isset($conditionDetails['value2'])) $condition['valsecondary'] = $conditionDetails['value2']; // update or insert? if ($conditionID > 0){ #} Update a segment condition #} update line if ($wpdb->update( $ZBSCRM_t['segmentsconditions'], array( 'zbscondition_segmentid' => $segmentID, 'zbscondition_type' => $condition['type'], 'zbscondition_op' => $condition['operator'], 'zbscondition_val' => $condition['val'], 'zbscondition_val_secondary' => $condition['valsecondary'] ), array( // where 'ID' => $conditionID ), array( '%d', '%s', '%s', '%s', '%s' ), array( '%d' ) ) !== false){ return $conditionID; } else { // could not update?! return false; } } else { #} Add a new segmentcondition #} Add condition line if ($wpdb->insert( $ZBSCRM_t['segmentsconditions'], array( 'zbscondition_segmentid' => $segmentID, 'zbscondition_type' => $condition['type'], 'zbscondition_op' => $condition['operator'], 'zbscondition_val' => $condition['val'], 'zbscondition_val_secondary' => $condition['valsecondary'] ), array( '%d', '%s', '%s', '%s', '%s' ) ) > 0){ // inserted return $wpdb->insert_id; } else { // could not insert?! return false; } } // / new return false; } /** * Does the segment have a condition of type x? * * @param array segment - segment obj as returned by getSegment(s) * @param array condition_type - array of condition types to check for */ public function segmentHasConditionType( $segment = array(), $condition_types = array() ){ // got a legit segment, and some conditions? if ( is_array( $segment ) && isset( $segment['conditions'] ) && is_array( $segment['conditions'] ) && is_array( $condition_types ) ){ // cycle through segment conditions & check foreach ( $segment['conditions'] as $condition ){ if ( in_array( $condition['type'], $condition_types ) ) return true; } } return false; } /** * empty all conditions against seg */ public function removeSegmentConditions($segmentID=-1){ if (!empty($segmentID)) { global $ZBSCRM_t,$wpdb; return $wpdb->delete( $ZBSCRM_t['segmentsconditions'], array( // where 'zbscondition_segmentid' => $segmentID ), array( '%d' ) ); } return false; } /** * Segment rules * takes a condition + returns a contact dal2 get arr param * */ public function segmentConditionArgs($condition=array(),$conditionKeySuffix=''){ if (is_array($condition) && isset($condition['type']) && isset($condition['operator'])){ global $zbs,$wpdb,$ZBSCRM_t; if ( ! empty( $condition['type'] ) ) { // normalise type string $condition_type = preg_replace( '/^zbsc_/', '', $condition['type'] ); $filter_tag = $this->makeSlug( $condition_type ) . '_zbsSegmentArgumentBuild'; $potential_args = apply_filters( $filter_tag, false, $condition, $conditionKeySuffix ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // got anything back? if ( $potential_args !== false ) { return $potential_args; } } switch ( $condition['type'] ) { case 'status': case 'zbsc_status': /* while this is right, it doesn't allow for MULTIPLE status cond lines, so do via sql: if ($condition['operator'] == 'equal') return array('hasStatus'=>$condition['value']); else return array('otherStatus'=>$condition['value']); */ if ($condition['operator'] == 'equal') return array('additionalWhereArr'=> array('statusEqual'.$conditionKeySuffix=>array("zbsc_status",'=','%s',$condition['value'])) ); else return array('additionalWhereArr'=> array('statusEqual'.$conditionKeySuffix=>array("zbsc_status",'<>','%s',$condition['value'])) ); break; case 'fullname': // 'equal','notequal','contains' if ($condition['operator'] == 'equal') return array('additionalWhereArr'=> array('fullnameEqual'.$conditionKeySuffix=>array("CONCAT(zbsc_fname,' ',zbsc_lname)",'=','%s',$condition['value'])) ); elseif ($condition['operator'] == 'notequal') return array('additionalWhereArr'=> array('fullnameEqual'.$conditionKeySuffix=>array("CONCAT(zbsc_fname,' ',zbsc_lname)",'<>','%s',$condition['value'])) ); elseif ($condition['operator'] == 'contains') return array('additionalWhereArr'=> array('fullnameEqual'.$conditionKeySuffix=>array("CONCAT(zbsc_fname,' ',zbsc_lname)",'LIKE','%s','%'.$condition['value'].'%')) ); break; case 'email': case 'zbsc_email': if ($condition['operator'] == 'equal'){ // while this is right, it doesn't allow for MULTIPLE status cond lines, so do via sql: // return array('hasEmail'=>$condition['value']); /* // this was good, but was effectively AND return array('additionalWhereArr'=> array( 'email'.$conditionKeySuffix=>array('zbsc_email','=','%s',$condition['value']), 'emailAKA'.$conditionKeySuffix=>array('ID','IN',"(SELECT aka_id FROM ".$ZBSCRM_t['aka']." WHERE aka_type = ".ZBS_TYPE_CONTACT." AND aka_alias = %s)",$condition['value']) ) ); */ // This was required to work with OR (e.g. postcode 1 = x or postcode 2 = x) // ----------------------- // This generates a query like 'zbsc_fname LIKE %s OR zbsc_lname LIKE %s', // which we then need to include as direct subquery /* THIS WORKS: but refactored below $conditionQArr = $this->buildWheres(array( 'email'.$conditionKeySuffix=>array('zbsc_email','=','%s',$condition['value']), 'emailAKA'.$conditionKeySuffix=>array('ID','IN',"(SELECT aka_id FROM ".$ZBSCRM_t['aka']." WHERE aka_type = ".ZBS_TYPE_CONTACT." AND aka_alias = %s)",$condition['value']) ),'',array(),'OR',false); if (is_array($conditionQArr) && isset($conditionQArr['where']) && !empty($conditionQArr['where'])){ return array('additionalWhereArr'=>array('direct'=>array(array('('.$conditionQArr['where'].')',$conditionQArr['params'])))); } return array(); */ // this way for OR situations return $this->segmentBuildDirectOrClause(array( 'email'.$conditionKeySuffix=>array('zbsc_email','=','%s',$condition['value']), 'emailAKA'.$conditionKeySuffix=>array('ID','IN',"(SELECT aka_id FROM ".$ZBSCRM_t['aka']." WHERE aka_type = ".ZBS_TYPE_CONTACT." AND aka_alias = %s)",$condition['value']) ),'OR'); // ----------------------- } elseif ($condition['operator'] == 'notequal') return array('additionalWhereArr'=> array( 'notEmail'.$conditionKeySuffix=>array('zbsc_email','<>','%s',$condition['value']), 'notEmailAka'.$conditionKeySuffix=>array('ID','NOT IN',"(SELECT aka_id FROM ".$ZBSCRM_t['aka']." WHERE aka_type = ".ZBS_TYPE_CONTACT." AND aka_alias = %s)",$condition['value']) ) ); elseif ($condition['operator'] == 'contains') return array('additionalWhereArr'=> array('emailContains'.$conditionKeySuffix=>array("zbsc_email",'LIKE','%s','%'.$condition['value'].'%')) ); break; // TBA (When DAL2 trans etc.) case 'totalval': // 'equal','notequal','larger','less','floatrange' break; case 'dateadded': // 'before','after','daterange','datetimerange','beforeequal','afterequal','previousdays' // date added if ($condition['operator'] == 'before') return array('additionalWhereArr'=> array('olderThan'.$conditionKeySuffix=>array('zbsc_created','<','%d',$condition['value'])) ); elseif ($condition['operator'] == 'beforeequal') return array('additionalWhereArr'=> array( 'olderThanEqual' . $conditionKeySuffix => array( 'zbsc_created', '<=', '%d', $condition['value'] ) ) ); elseif ($condition['operator'] == 'after') return array('additionalWhereArr'=> array('newerThan'.$conditionKeySuffix=>array('zbsc_created','>','%d',$condition['value'])) ); elseif ($condition['operator'] == 'afterequal') return array('additionalWhereArr'=> array( 'newerThanEqual' . $conditionKeySuffix => array( 'zbsc_created', '>=', '%d', $condition['value'] ) ) ); elseif ( $condition['operator'] == 'daterange' || $condition['operator'] == 'datetimerange' ){ $before = false; $after = false; // split out the value if (isset($condition['value']) && !empty($condition['value'])) $after = (int)$condition['value']; if (isset($condition['value2']) && !empty($condition['value2'])) $before = (int)$condition['value2']; // while this is right, it doesn't allow for MULTIPLE status cond lines, so do via sql: // return array('newerThan'=>$after,'olderThan'=>$before); return array('additionalWhereArr'=> array( 'newerThan' . $conditionKeySuffix => array( 'zbsc_created', '>=', '%d', $condition['value'] ), 'olderThan' . $conditionKeySuffix => array( 'zbsc_created', '<=', '%d', $condition['value2'] ) ) ); } elseif ($condition['operator'] == 'previousdays'){ $days_value = (int)$condition['value']; $midnight = strtotime( "midnight" ); $previous_days_uts = $midnight - ( ( 60 * 60 * 24 ) * $days_value ); return array('additionalWhereArr'=> array( 'newerThanPreviousDays' . $conditionKeySuffix => array( 'zbsc_created', '<=', '%d', time() ), 'olderThanPreviousDays' . $conditionKeySuffix => array( 'zbsc_created', '>=', '%d', $previous_days_uts ) ) ); } break; case 'datelastcontacted': // 'before','after','daterange','datetimerange','beforeequal','afterequal','previousdays' // contactedAfter if ($condition['operator'] == 'before') // datetime return array('additionalWhereArr'=> array('contactedBefore'.$conditionKeySuffix=>array('zbsc_lastcontacted','<','%d',$condition['value'])) ); elseif ($condition['operator'] == 'beforeequal') // date return array('additionalWhereArr'=> array( 'contactedBeforeEqual' . $conditionKeySuffix => array( 'zbsc_lastcontacted', '<=', '%d', $condition['value'] ) ) ); elseif ($condition['operator'] == 'after') //datetime return array('additionalWhereArr'=> array('contactedAfter'.$conditionKeySuffix=>array('zbsc_lastcontacted','>','%d',$condition['value'])) ); elseif ($condition['operator'] == 'afterequal') // date return array('additionalWhereArr'=> array( 'contactedAfterEqual' . $conditionKeySuffix => array( 'zbsc_lastcontacted', '>=', '%d', $condition['value'] ) ) ); elseif ( $condition['operator'] == 'daterange' || $condition['operator'] == 'datetimerange' ){ $before = false; $after = false; // split out the value if (isset($condition['value']) && !empty($condition['value'])) $after = (int)$condition['value']; if (isset($condition['value2']) && !empty($condition['value2'])) $before = (int)$condition['value2']; // while this is right, it doesn't allow for MULTIPLE status cond lines, so do via sql: // return array('contactedAfter'=>$after,'contactedBefore'=>$before); return array('additionalWhereArr'=> array( 'contactedAfter'.$conditionKeySuffix=>array('zbsc_lastcontacted','>=','%d',$after), 'contactedBefore'.$conditionKeySuffix=>array('zbsc_lastcontacted','<=','%d',$before) ) ); } elseif ( $condition['operator'] == 'previousdays' ){ $days_value = (int)$condition['value']; $previous_days_uts = strtotime( "-" . $days_value . " days" ); return array('additionalWhereArr'=> array( 'contactedAfterPreviousDays' . $conditionKeySuffix => array( 'zbsc_lastcontacted', '<=', '%d', time() ), 'contactedBeforePreviousDays' . $conditionKeySuffix => array( 'zbsc_lastcontacted', '>=', '%d', $previous_days_uts ) ) ); } break; case 'tagged': // 'tag' // while this is right, it doesn't allow for MULTIPLE status cond lines, so do via sql: // return array('isTagged'=>$condition['value']); // NOTE // ... this is a DIRECT query, so format for adding here is a little diff // ... and only works (not overriding existing ['direct']) because the calling func of this func has to especially copy separately return array('additionalWhereArr'=> array('direct' => array( array('(SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = contact.ID AND zbstl_tagid = %d) > 0',array(ZBS_TYPE_CONTACT,$condition['value'])) ) ) ); break; case 'nottagged': // 'tag' // while this is right, it doesn't allow for MULTIPLE status cond lines, so do via sql: // return array('isNotTagged'=>$condition['value']); // NOTE // ... this is a DIRECT query, so format for adding here is a little diff // ... and only works (not overriding existing ['direct']) because the calling func of this func has to especially copy separately return array('additionalWhereArr'=> array('direct' => array( array('(SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = contact.ID AND zbstl_tagid = %d) = 0',array(ZBS_TYPE_CONTACT,$condition['value'])) ) ) ); break; default: break; } } // if we get here we've failed to create any arguments for this condiition // ... to avoid scenarios such as mail campaigns going out to 'less filtered than intended' audiences // ... we throw an error $this->error_condition_exception( 'segment_condition_produces_no_args', __( 'Segment Condition produces no filtering arguments', 'zero-bs-crm'), array( 'condition' => $condition ) ); return false; } // ONLY USED FOR SEGMENT SQL BUILING CURRENTLY, deep. // ----------------------- // This was required to work with OR (e.g. postcode 1 = x or postcode 2 = x) // ----------------------- // This generates a query like 'zbsc_fname LIKE %s OR zbsc_lname LIKE %s', // which we then need to include as direct subquery public function segmentBuildDirectOrClause($directQueries=array(),$andOr='OR'){ /* this works, in segmentConditionArgs(), adapted below to fit generic func to keep it DRY $conditionQArr = $this->buildWheres(array( 'email'.$conditionKeySuffix=>array('zbsc_email','=','%s',$condition['value']), 'emailAKA'.$conditionKeySuffix=>array('ID','IN',"(SELECT aka_id FROM ".$ZBSCRM_t['aka']." WHERE aka_type = ".ZBS_TYPE_CONTACT." AND aka_alias = %s)",$condition['value']) ),'',array(),'OR',false); if (is_array($conditionQArr) && isset($conditionQArr['where']) && !empty($conditionQArr['where'])){ return array('additionalWhereArr'=>array('direct'=>array(array('('.$conditionQArr['where'].')',$conditionQArr['params'])))); } return array(); */ $directArr = $this->buildWheres($directQueries,'',array(),$andOr,false); if (is_array($directArr) && isset($directArr['where']) && !empty($directArr['where'])){ return array('additionalWhereArr'=>array('direct'=>array(array('('.$directArr['where'].')',$directArr['params'])))); } return array(); } /** * Compile a segment () */ public function compileSegment($segmentID=-1){ if ( !empty( $segmentID ) ) { // 'GET' the segment count without paging limits // ... this func then automatically updates the compile record, so nothing to do :) return $this->getSegementAudience($segmentID,-1,-1,'ID','DESC',true); } return false; } /** * Throw an exception */ protected function error_condition_exception($code, $message, $data){ throw new Segment_Condition_Exception( $code, $message, $data ); } /** * Checks that a segment audience can be compiled or if it has any outstanding errors * ... returning as a string if so. * ... for now this is done via a setting, later we should build an error stack via DAL #refined-error-stack */ public function segment_error( $segment_id ){ global $zbs; // sanitise and check $segment_id = (int)$segment_id; if ( $segment_id <= 0 ) return ''; // Retrieve any setting value return $zbs->settings->get( 'segment-error-' . $segment_id ); } /** * Updates any stored segment audience error * ... for now this is done via a setting, later we should build an error stack via DAL #refined-error-stack */ public function add_segment_error( $segment_id, $error_string ){ global $zbs; // sanitise and check $segment_id = (int)$segment_id; if ( $segment_id <= 0 ) return false; // Set segment area error notice $zbs->settings->update( 'segment-error-' . $segment_id, $error_string ); } /** * Removes any stored segment audience error * ... for now this is done via a setting, later we should build an error stack via DAL #refined-error-stack */ public function remove_segment_error( $segment_id ){ global $zbs; // sanitise and check $segment_id = (int)$segment_id; if ( $segment_id <= 0 ) return false; // Remove any segment area error notice $zbs->settings->delete( 'segment-error-' . $segment_id ); } /** * Flags up a segment error where a used condition was missing in building a segment * * @param int - Segment ID * @param Exception - the related exception */ public function segment_error_condition_missing( $segmentID, $exception ){ // Not all conditions were able to produce arguments // Here we are best to return an empty audience and alert the admin // e.g. building a segment for a mail campaign without all conditions // and sending to a larger-than-expected audience is more dangerous than sending to zero. $error_string = $exception->get_error_code(); // Set an admin notification to warn admin (max once every 2 days) $transient_flag = get_transient( 'crm-segment-condition-missing-arg' ); if ( !$transient_flag ){ // insert notification zeroBSCRM_notifyme_insert_notification( get_current_user_id(), -999, -1, 'segments.orphaned.conditions', 'segmentconditionmissing' ); // set transient set_transient( 'crm-segment-condition-missing-arg', 1, 24 * 2 * HOUR_IN_SECONDS ); } // Set segment area error notice $this->add_segment_error( $segmentID, $error_string ); } /** * Migrates a superseded condition in the db to an up to date condition key * * @param string $superseded_key - the key of the old condition which has been replaced * @param string $new_key - the key to replace it with */ public function migrate_superseded_condition( $superseded_key, $new_key ){ global $zbs, $ZBSCRM_t, $wpdb; // very short and brutal. Ignores any ownership $query = "UPDATE " . $ZBSCRM_t['segmentsconditions'] . " SET zbscondition_type = %s WHERE zbscondition_type = %s"; $q = $wpdb->prepare( $query, array( $new_key, $superseded_key ) ); return $wpdb->query( $q ); } // =========== / SEGMENTS =================================================== // =============================================================================== } // / class
projects/plugins/crm/includes/ZeroBSCRM.Core.Menus.Top.php
<?php /* ! * Jetpack CRM * https://jetpackcrm.com * V2.4+ * * Copyright 2020 Automattic * * Date: 05/02/2017 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) { exit; } /* ====================================================== / Breaking Checks ====================================================== */ /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! THIS FILE IS FOR JPCRM Top Menu related changes - later to be unified into one .Menu file !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ /* xxx // Top menu add_action("wp_after_admin_bar_render","zeroBSCRM_admin_top_menu", 10); // Learn menu function jpcrm_initialise_learn_menu(){ new Learn_Menu(); } // Note the priority here. This causes the "learn" block to present after the top menu add_action( "wp_after_admin_bar_render", "jpcrm_initialise_learn_menu", 11 ); */ // } Admin head for the top menu (i.e. remembering the toggle mode) - modified for custom admin function zeroBSCRM_admin_menu_settings() { $cid = get_current_user_id(); $hiding_wp = get_user_meta( $cid, 'zbs-hide-wp-menus', true ); if ( zeroBSCRM_isAdminPage() ) { // if hiding, append class to body :)- this should be a single js call really, fudged for now :) // jQuery('body').addClass('zbs-fullscreen'); - NOW NOT NEEDED (see zeroBSCRM_bodyClassMods - added via php for less visual lag) // left in for cases like material admin not using proper admin_body_class if ( $hiding_wp ) { ?> <script type="text/javascript">jQuery(function(){ jQuery('body').addClass('zbs-fullscreen'); jQuery('#wpcontent').addClass('zbs-menu-open'); });</script> <?php } } } add_action( 'admin_head', 'zeroBSCRM_admin_menu_settings' ); add_filter( 'admin_body_class', 'zeroBSCRM_bodyClassMods' ); function zeroBSCRM_bodyClassMods( $classes = '' ) { // show hide fullscreen mode $hiding_wp = get_user_meta( get_current_user_id(), 'zbs-hide-wp-menus', true ); if ( zeroBSCRM_isAdminPage() ) { $classes .= ' jpcrm-admin'; // if hiding, append class to body if ( $hiding_wp ) { $classes .= ' zbs-fullscreen '; } if ( isset( $_GET['page'] ) && jpcrm_is_full_width_page( $_GET['page'] ) ) { //phpcs:ignore $classes .= ' jpcrm-full-width '; } } return $classes; } // } THIS IS THE PENDING COUNT FOR ZBS DASHBOARD (akin to pending posts red number) // } USED TO HIGHLIGHT NOTIFICATIONS - WHICH WILL ALSO BE IN TOP MENU UI - can use it here too add_filter( 'add_menu_classes', 'zeroBSCRM_show_pending_number' ); function zeroBSCRM_show_pending_number( $menu ) { $pending_count = 0; // update this with count of UNREAD notifications if we want to use here. // build string to match in $menu array $menu_str = 'zerobscrm-dash'; // loop through $menu items, find match, add indicator foreach ( $menu as $menu_key => $menu_data ) { if ( $menu_str != $menu_data[2] ) { continue; } $menu[ $menu_key ][0] .= ' <span class="update-plugins count-' . $pending_count . '"><span class="plugin-count">' . number_format_i18n( $pending_count ) . '</span></span>'; } return $menu; } // } This is NEW UI for the top menu. Helpful links in the top menu = Improved UI function zeroBSCRM_admin_top_menu( $branding = 'zero-bs-crm', $page = 'dash' ) { // } restrict to ONLY Jetpack CRM pages - NOTE our EXTENSIONS will need to use the same // } $zbs->slugs global. Some of mine use $zeroBSCRM_extension_slugs // } will update the extensions to use the probably $zbs->slugs global // } WH: All good. if ( zeroBSCRM_isAdminPage() ) { global $zbs; // } Check whether we want to run the hopscotch tour $uid = get_current_user_id(); $zbs_hopscoth = get_user_meta( $uid, 'zbs-hopscotch-tour', true ); if ( $zbs_hopscoth == '' && ! isset( $_GET['zbs-welcome-tour'] ) ) { // first load.. update_user_meta( $uid, 'zbs-hopscotch-tour', 0 ); ?> <script type="text/javascript">var zbscrmjs_hopscotch_virgin=1;</script> <?php } else { // not first time... ?> <script type="text/javascript">var zbscrmjs_hopscotch_virgin=0;</script> <?php } if ( isset( $_GET['zbs-welcome-tour'] ) && $_GET['zbs-welcome-tour'] == 1 ) { // user-initiated: ?> <script type="text/javascript">var zbscrmjs_hopscotch_virgin=1;</script> <?php } // } passing "branding" for the logo top :-) $branding = ''; ##WLREMOVE $branding = 'zero-bs-crm'; ##/WLREMOVE // } AJAX nonce, rest is dealt with in the admin global js :) ?> <script type="text/javascript">var zbscrmjs_topMenuSecToken = '<?php echo esc_js( wp_create_nonce( 'zbscrmjs-ajax-nonce-topmenu' ) ); ?>';</script> <?php // } Menu hidden? - maybe we can cookie this? for now this is slick. $hiding_wp = get_user_meta( $uid, 'zbs-hide-wp-menus', true ); if ( $hiding_wp ) { $admin_menu_state = 'menu-closed'; } else { $admin_menu_state = 'menu-open'; } // } Other Prep $currentUser = wp_get_current_user(); $alsoCo = ''; // } WH added to fix php warnings - what\s this? $b2bMode = zeroBSCRM_getSetting( 'companylevelcustomers' ); // pre-collate tools so can hide if none :) $toolsMenu = array(); // calendar if ( zeroBSCRM_perms_tasks() && zeroBSCRM_getSetting( 'feat_calendar' ) > 0 ) { $toolsMenu[] = '<a href="' . zeroBSCRM_getAdminURL( $zbs->slugs['manage-tasks'] ) . '" class="item"><i class="icon calendar outline"></i> ' . __( 'Task Scheduler', 'zero-bs-crm' ) . '</a>'; } // forms if ( zeroBSCRM_permsForms() && zeroBSCRM_getSetting( 'feat_forms' ) > 0 ) { $toolsMenu[] = '<a href="' . zeroBSCRM_getAdminURL( $zbs->slugs['manageformscrm'] ) . '" class="item"><i class="icon file outline"></i> ' . __( 'Forms', 'zero-bs-crm' ) . '</a>'; } // removes data-tools page for everyone except WP Admin + zbs admin if ( zeroBSCRM_isZBSAdminOrAdmin() ) { $toolsMenu[] = '<a href="' . zeroBSCRM_getAdminURL( $zbs->slugs['datatools'] ) . '" class="item"><i class="icon configure"></i> ' . __( 'Data Tools', 'zero-bs-crm' ) . '</a>'; } // filter items (allows additions from ext etc.) $toolsMenu = apply_filters( 'zbs-tools-menu', $toolsMenu ); // } Add extensions to base, always :) more upsell. if ( zeroBSCRM_isZBSAdminOrAdmin() ) { $toolsMenu[] = '<a class="item" id="zbs-manage-modules-tour" href="' . zeroBSCRM_getAdminURL( $zbs->slugs['modules'] ) . '"><i class="icon th" aria-hidden="true"></i> ' . __( 'Core Modules', 'zero-bs-crm' ) . '</a>'; ##WLREMOVE $toolsMenu[] = '<a class="item" id="zbs-manage-ext-tour" href="' . zeroBSCRM_getAdminURL( $zbs->slugs['extensions'] ) . '"><i class="icon plug" aria-hidden="true"></i> ' . __( 'Extensions', 'zero-bs-crm' ) . '</a>'; ##/WLREMOVE } ?> <!--- mobile only menu --> <div class="ui mobile tablet only" id="zbs-mobile-nav"> <div id="zbs-main-logo-mobile"> <div class="zbs-face-1-mobile"> <img id="zbs-main-logo-mobby" alt="Jetpack CRM mobile logo" src="<?php echo esc_url( jpcrm_get_logo( false, 'white' ) ); ?>" style="cursor:pointer;"> </div> </div> <?php // Dev mode? add ui label if ( zeroBSCRM_isLocal() ) { // no id etc. to stop people hiding with css ?> <div class="item" style="float: right;color: #FFF;margin-top: -2.5em;"><?php esc_html_e( 'Developer Mode', 'zero-bs-crm' ); ?></div> <?php } ?> <div class="ui stackable menu inverted" id="zbs-mobile-navigation-toggle"> <!-- basic menu tabs for mobile --> <a class="item<?php zeroBS_menu_active( $zbs->slugs['dash'] ); ?>" href="<?php echo esc_url( zeroBSCRM_getAdminURL( $zbs->slugs['dash'] ) ); ?>"><i class="icon dashboard"></i><?php esc_html_e( 'Dashboard', 'zero-bs-crm' ); ?></a> <a class="item" href="<?php echo esc_url( zeroBSCRM_getAdminURL( $zbs->slugs['managecontacts'] ) ); ?>"><i class="icon users"></i> <?php esc_html_e( 'Contacts', 'zero-bs-crm' ); ?></a> <?php if ( $b2bMode == 1 ) { ?> <a class="item" href="<?php echo esc_url( zeroBSCRM_getAdminURL( $zbs->slugs['managecompanies'] ) ); ?>"><i class="icon building outline"></i> <?php echo esc_html( jpcrm_label_company( true ) ); ?></a> <?php } ?> <?php if ( zeroBSCRM_permsViewQuotes() && zeroBSCRM_getSetting( 'feat_quotes' ) > 0 ) { ?> <a class="item" href="<?php echo esc_url( zeroBSCRM_getAdminURL( $zbs->slugs['managequotes'] ) ); ?>"><i class="icon file outline"></i> <?php esc_html_e( 'Quotes', 'zero-bs-crm' ); ?></a> <?php } ?> <?php if ( zeroBSCRM_permsViewInvoices() && zeroBSCRM_getSetting( 'feat_invs' ) > 0 ) { ?> <a class="item" href="<?php echo esc_url( zeroBSCRM_getAdminURL( $zbs->slugs['manageinvoices'] ) ); ?>"><i class="icon file alternate outline"></i> <?php esc_html_e( 'Invoices', 'zero-bs-crm' ); ?></a> <?php } ?> <?php if ( zeroBSCRM_permsViewTransactions() && zeroBSCRM_getSetting( 'feat_transactions' ) > 0 ) { ?> <a class="item" href="<?php echo esc_url( zeroBSCRM_getAdminURL( $zbs->slugs['managetransactions'] ) ); ?>"><i class="icon shopping cart"></i> <?php esc_html_e( 'Transactions', 'zero-bs-crm' ); ?></a> <?php } ?> <?php // tools menu added 29/6/18, because Brian needs access to his, maybe we need to rethink this whole menu setup if ( count( $toolsMenu ) > 0 ) { foreach ( $toolsMenu as $menuItem ) { // wh quick hack to avoid clashing ID's $menuItemHTML = str_replace( 'id="', 'id="mob-', $menuItem ); $menuItemHTML = str_replace( "id='", "id='mob-", $menuItemHTML ); echo $menuItemHTML; } } ?> </div> </div> <script type="text/javascript"> jQuery(function(){ jQuery('#zbs-main-logo-mobby').on("click",function(e){ jQuery("#zbs-mobile-navigation-toggle").toggle(); }); }) </script> <!--- // mobile only menu --> <div id="jpcrm-top-menu"> <div class="logo-cube <?php echo esc_attr( $admin_menu_state ); ?>"> <div class="cube-side side1"> <img alt="Jetpack CRM logo" src="<?php echo esc_url( jpcrm_get_logo( false ) ); ?>"> </div> <div class="cube-side side2"> <i class="expand icon fa-flip-horizontal"></i> </div> </div> <menu-bar> <menu-section> <a class="item<?php esc_attr( zeroBS_menu_active( $zbs->slugs['dash'] ) ); ?>" href="<?php echo esc_url( zeroBSCRM_getAdminURL( $zbs->slugs['dash'] ) ); ?>"><?php esc_html_e( 'Dashboard', 'zero-bs-crm' ); ?></a> <div class="ui simple dropdown item select<?php esc_attr( zeroBS_menu_active_type( 'contact' ) ); ?>" id="zbs-contacts-topmenu" style="min-width:114px;z-index:5"> <span class="text"><?php esc_html_e( 'Contacts', 'zero-bs-crm' ); ?></span> <i class="dropdown icon"></i> <div class="menu ui"> <?php if ( zeroBSCRM_permsCustomers() ) { // ADD CUSTOMER //esc_url( 'post-new.php?post_type=zerobs_customer'.$alsoCo ) echo ' <a href="' . jpcrm_esc_link( 'create', -1, 'zerobs_customer', false ) . $alsoCo . '" class="item"><i class="icon plus"></i> ' . esc_html__( 'Add New', 'zero-bs-crm' ) . '</a>'; } ?> <a class="item" href="<?php echo esc_url( zeroBSCRM_getAdminURL( $zbs->slugs['managecontacts'] ) ); ?>"><i class="icon list"></i> <?php esc_html_e( 'View all', 'zero-bs-crm' ); ?></a> <?php if ( zeroBSCRM_permsCustomers() ) { // CONTACT TAGS ?> <a class="item" href="<?php echo jpcrm_esc_link( 'tags', -1, 'zerobs_customer', false, 'contact' ); ?>"><i class="icon tags"></i> <?php esc_html_e( 'Tags', 'zero-bs-crm' ); ?></a> <?php } ?> <?php if ( zeroBSCRM_permsCustomers() && $zbs->isDAL2() ) { // CONTACT SEGMENTS ?> <a class="item" href="<?php echo jpcrm_esc_link( $zbs->slugs['segments'], -1, 'zerobs_customer', false, 'contact' ); ?>"><i class="chart pie icon"></i> <?php esc_html_e( 'Segments', 'zero-bs-crm' ); ?></a> <?php } ?> <?php if ( $b2bMode == 1 ) { ?> <div class="ui divider"></div> <div class="ui simple dropdown item " id="zbs-companies-topmenu"> <?php echo esc_html( jpcrm_label_company( true ) ); ?><i class="dropdown icon zbs-subsub-ico"></i> <div class="menu ui"> <?php if ( zeroBSCRM_permsCustomers() ) { echo ' <a href="' . jpcrm_esc_link( 'create', -1, 'zerobs_company', false ) . '" class="item"><i class="icon plus"></i> ' . esc_html__( 'Add New', 'zero-bs-crm' ) . '</a>'; } ?> <a class="item" href="<?php echo esc_url( zeroBSCRM_getAdminURL( $zbs->slugs['managecompanies'] ) ); ?>"><i class="icon list"></i> <?php esc_html_e( 'View all', 'zero-bs-crm' ); ?></a> <a class="item" href="<?php echo jpcrm_esc_link( 'tags', -1, 'zerobs_company', false, 'zerobscrm_companytag' ); ?>"><i class="icon tags"></i> <?php esc_html_e( 'Tags', 'zero-bs-crm' ); ?></a> </div> </div> <?php } ?> <div class="ui divider"></div> <?php if ( ! zeroBSCRM_isExtensionInstalled( 'csvpro' ) && zeroBSCRM_isExtensionInstalled( 'csvimporterlite' ) ) { ?> <a class="item" href="<?php echo esc_url( admin_url( 'admin.php?page=' . $zbs->slugs['csvlite'] ) ); ?>"><i class="icon cloud upload"></i> <?php esc_html_e( 'Import', 'zero-bs-crm' ); ?></a> <?php } else { // if csvpro installed if ( zeroBSCRM_isExtensionInstalled( 'csvpro' ) ) { global $zeroBSCRM_CSVImporterslugs; // got slug if ( isset( $zeroBSCRM_CSVImporterslugs ) && is_array( $zeroBSCRM_CSVImporterslugs ) && isset( $zeroBSCRM_CSVImporterslugs['app'] ) ) { ?> <a class="item" href="<?php echo esc_url( admin_url( 'admin.php?page=' . $zeroBSCRM_CSVImporterslugs['app'] ) ); ?>"><i class="icon cloud upload"></i> <?php esc_html_e( 'Import', 'zero-bs-crm' ); ?></a> <?php } } } ?> <a class="item" href="<?php echo esc_url( zeroBSCRM_getAdminURL( $zbs->slugs['export-tools'] ) ); ?>"><i class="icon cloud download"></i> <?php esc_html_e( 'Export', 'zero-bs-crm' ); ?></a> <?php // filter items (allows additions from ext etc.) // for now empty (could contain the above) - so can add custom for log report (miguel) $contactsMenu = array(); $contactsMenu = apply_filters( 'zbs-contacts-menu', $contactsMenu ); if ( count( $contactsMenu ) > 0 ) { // show divider? ?> <div class="ui divider"></div> <?php foreach ( $contactsMenu as $menuItem ) { echo $menuItem; } } ?> </div> </div> <?php if ( zeroBSCRM_permsViewQuotes() && zeroBSCRM_getSetting( 'feat_quotes' ) > 0 ) { ?> <div class="ui simple dropdown item select<?php zeroBS_menu_active_type( 'quote' ); ?>" id="zbs-quotes-topmenu" style="z-index:5"> <span class="text"><?php esc_html_e( 'Quotes', 'zero-bs-crm' ); ?></span> <i class="dropdown icon"></i> <div class="menu ui"> <?php if ( zeroBSCRM_permsQuotes() ) { echo ' <a href="' . jpcrm_esc_link( 'create', -1, 'zerobs_quote', false ) . $alsoCo . '" class="item"><i class="icon plus"></i> ' . esc_html__( 'Add New', 'zero-bs-crm' ) . '</a>'; } ?> <a class="item" href="<?php echo esc_url( zeroBSCRM_getAdminURL( $zbs->slugs['managequotes'] ) ); ?>"><i class="icon list"></i> <?php esc_html_e( 'View all', 'zero-bs-crm' ); ?></a> <?php if ( zeroBSCRM_permsQuotes() && $zbs->isDAL3() ) { // TAGS ?> <a class="item" href="<?php echo jpcrm_esc_link( 'tags', -1, ZBS_TYPE_QUOTE, false, 'quote' ); ?>"><i class="icon tags"></i> <?php esc_html_e( 'Tags', 'zero-bs-crm' ); ?></a> <?php } ?> <?php if ( zeroBSCRM_permsQuotes() ) { ?> <a class="item" href="<?php echo esc_url( zeroBSCRM_getAdminURL( $zbs->slugs['quote-templates'] ) ); ?>"><i class="icon file text"></i> <?php esc_html_e( 'Templates', 'zero-bs-crm' ); ?></a> <?php } ?> <?php if ( zeroBSCRM_permsQuotes() ) { ?> <a class="item" href="<?php echo esc_url( zeroBSCRM_getAdminURL( $zbs->slugs['export-tools'] ) ); ?>&zbstype=quote"><i class="icon cloud download"></i> <?php esc_html_e( 'Export', 'zero-bs-crm' ); ?></a> <?php } ?> <?php // filter items (allows additions from ext etc.) // for now empty (could contain the above) $quotesMenu = array(); $quotesMenu = apply_filters( 'zbs-quotes-menu', $quotesMenu ); if ( count( $quotesMenu ) > 0 ) { // show divider? ?> <div class="ui divider"></div> <?php foreach ( $quotesMenu as $menuItem ) { echo $menuItem; } } ?> </div> </div> <?php } ?> <?php if ( zeroBSCRM_permsViewInvoices() && zeroBSCRM_getSetting( 'feat_invs' ) > 0 ) { ?> <div class="ui simple dropdown item select<?php zeroBS_menu_active_type( 'invoice' ); ?>" id="zbs-invoices-topmenu" style="z-index:5"> <span class="text"><?php esc_html_e( 'Invoices', 'zero-bs-crm' ); ?></span> <i class="dropdown icon"></i> <div class="menu ui"> <?php if ( zeroBSCRM_permsInvoices() ) { echo ' <a href="' . jpcrm_esc_link( 'create', -1, 'zerobs_invoice', false ) . $alsoCo . '" class="item"><i class="icon plus"></i> ' . esc_html__( 'Add New', 'zero-bs-crm' ) . '</a>'; } ?> <a class="item" href="<?php echo esc_url( zeroBSCRM_getAdminURL( $zbs->slugs['manageinvoices'] ) ); ?>"><i class="icon list"></i> <?php esc_html_e( 'View all', 'zero-bs-crm' ); ?></a> <?php if ( zeroBSCRM_permsInvoices() && $zbs->isDAL3() ) { // TAGS ?> <a class="item" href="<?php echo jpcrm_esc_link( 'tags', -1, ZBS_TYPE_INVOICE, false, 'invoice' ); ?>"><i class="icon tags"></i> <?php esc_html_e( 'Tags', 'zero-bs-crm' ); ?></a> <?php } ?> <?php if ( zeroBSCRM_permsInvoices() ) { ?> <a class="item" href="<?php echo esc_url( zeroBSCRM_getAdminURL( $zbs->slugs['export-tools'] ) ); ?>&zbstype=invoice"><i class="icon cloud download"></i> <?php esc_html_e( 'Export', 'zero-bs-crm' ); ?></a> <?php } ?> <?php // filter items (allows additions from ext etc.) // for now empty (could contain the above) $invoicesMenu = array(); $invoicesMenu = apply_filters( 'zbs-invoices-menu', $invoicesMenu ); if ( count( $invoicesMenu ) > 0 ) { // show divider? ?> <div class="ui divider"></div> <?php foreach ( $invoicesMenu as $menuItem ) { echo $menuItem; } } ?> </div> </div> <?php } ?> <?php if ( zeroBSCRM_permsViewTransactions() && zeroBSCRM_getSetting( 'feat_transactions' ) > 0 ) { $transactions_menu = array(); ?> <div class="ui simple dropdown item select<?php zeroBS_menu_active_type( 'transaction' ); ?>" id="zbs-transactions-topmenu" style="z-index:5"> <span class="text"><?php esc_html_e( 'Transactions', 'zero-bs-crm' ); ?></span> <i class="dropdown icon"></i> <div class="menu ui"> <?php if ( zeroBSCRM_permsTransactions() ) { echo ' <a href="' . jpcrm_esc_link( 'create', -1, 'zerobs_transaction', false ) . $alsoCo . '" class="item"><i class="icon plus"></i> ' . esc_html__( 'Add New', 'zero-bs-crm' ) . '</a>'; } ?> <a class="item" href="<?php echo esc_url( zeroBSCRM_getAdminURL( $zbs->slugs['managetransactions'] ) ); ?>"><i class="icon list"></i> <?php esc_html_e( 'View all', 'zero-bs-crm' ); ?></a> <?php if ( zeroBSCRM_permsTransactions() ) { ?> <a class="item" href="<?php echo jpcrm_esc_link( 'tags', -1, 'zerobs_transaction', false, 'zerobscrm_transactiontag' ); ?>"><i class="icon tags"></i> <?php esc_html_e( 'Tags', 'zero-bs-crm' ); ?></a> <?php // If CSV Pro is installed and active it will add an Import menu item to the zbs-transactions-menu filter - we'll then add that here $transactions_menu = apply_filters( 'zbs-transactions-menu', $transactions_menu ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores $import_menu_item = preg_grep( '/\bpage\=zerobscrm\-csvimporter\-app\b/i', $transactions_menu ); if ( count( $import_menu_item ) > 0 ) { echo wp_kses( $import_menu_item[0], $zbs->acceptable_html ); $transactions_menu = array_diff( $transactions_menu, $import_menu_item ); } ?> <a class="item" href="<?php echo esc_url( zeroBSCRM_getAdminURL( $zbs->slugs['export-tools'] ) ); ?>&zbstype=transaction"><i class="icon cloud download"></i> <?php esc_html_e( 'Export', 'zero-bs-crm' ); ?></a> <?php } ?> <?php // Display remaining menu items added via the zbs-transactions-menu filter if ( count( $transactions_menu ) > 0 ) { // show divider? ?> <div class="ui divider"></div> <?php foreach ( $transactions_menu as $menu_item ) { echo wp_kses( $menu_item, $zbs->acceptable_html ); } } ?> </div> </div> <?php } // tools menu added to mobile menu above, so collated at top now ^^ if ( count( $toolsMenu ) > 0 ) { ?> <div class="ui simple dropdown item" id="top-bar-tools-menu"> <span class="text"><?php esc_html_e( 'Tools', 'zero-bs-crm' ); ?></span> <i class="dropdown icon"></i> <div class="menu ui"> <?php foreach ( $toolsMenu as $menuItem ) { echo $menuItem; } ?> </div> </div> <?php } ?> </menu-section> <menu-section> <?php do_action( 'zbs-crm-notify' ); ?> <div class="ui simple dropdown item" id="jpcrm-user-menu-item"> <span class="text"> <?php $uid = get_current_user_id(); echo jpcrm_get_avatar( $uid, 30 ); ?> </span> <i class="dropdown icon"></i> </div> <?php // } Build pop-out $popout_menu = array( 'col1' => array(), ##WLREMOVE 'col2' => array(), ##/WLREMOVE 'col3' => array(), ); // if admin, settings + datatools if ( zeroBSCRM_isZBSAdminOrAdmin() ) { $popout_menu['col1'][] = sprintf( '<div class="jpcrm-user-menu-link"><a id="zbs-settings2-top-menu" href="%s" class="item"><i class="settings icon"></i> %s</a></div>', zeroBSCRM_getAdminURL( $zbs->slugs['settings'] ), __( 'Settings', 'zero-bs-crm' ) ); ##WLREMOVE $popout_menu['col1'][] = sprintf( '<div class="jpcrm-user-menu-link"><a id="zbs-datatools-top-menu" href="%s" class="item"><i class="wrench icon"></i> %s</a></div>', zeroBSCRM_getAdminURL( $zbs->slugs['datatools'] ), __( 'Data Tools', 'zero-bs-crm' ) ); ##/WLREMOVE } // teams page for WP Admin or Jetpack CRM Full Admin. if ( current_user_can( 'manage_options' ) ) { $popout_menu['col1'][] = sprintf( '<div class="jpcrm-user-menu-link"><a id="zbs-team-top-menu" href="%s" class="item"><i class="icon users"></i> %s</a></div>', zeroBSCRM_getAdminURL( $zbs->slugs['team'] ), __( 'Team', 'zero-bs-crm' ) ); } // if admin, system status + extensions if ( zeroBSCRM_isZBSAdminOrAdmin() ) { $popout_menu['col1'][] = sprintf( '<div class="jpcrm-user-menu-link"><a class="item" href="%s"><i class="server icon" aria-hidden="true"></i> %s</a></div>', zeroBSCRM_getAdminURL( $zbs->slugs['systemstatus'] ), __( 'System Assistant', 'zero-bs-crm' ) ); $popout_menu['col1'][] = sprintf( '<div class="jpcrm-user-menu-link"><a class="item" href="%s"><i class="envelope icon" aria-hidden="true"></i> %s</a></div>', zeroBSCRM_getAdminURL( $zbs->slugs['emails'] ), __( 'Emails', 'zero-bs-crm' ) ); $popout_menu['col1'][] = sprintf( '<div class="jpcrm-user-menu-link"><a class="item" href="%s"><i class="icon th" aria-hidden="true"></i> %s</a></div>', zeroBSCRM_getAdminURL( $zbs->slugs['modules'] ), __( 'Core Modules', 'zero-bs-crm' ) ); ##WLREMOVE $popout_menu['col1'][] = sprintf( '<div class="jpcrm-user-menu-link"><a class="item" href="%s"><i class="icon plug" aria-hidden="true"></i> %s</a></div>', zeroBSCRM_getAdminURL( $zbs->slugs['extensions'] ), __( 'Extensions', 'zero-bs-crm' ) ); ##/WLREMOVE } // remove the col if nothing in there if ( count( $popout_menu['col1'] ) === 0 ) { unset( $popout_menu['col1'] ); } ?> <div class="ui popup" id="jpcrm-user-menu"> <?php switch ( count( $popout_menu ) ) { case 3: $menu_style = 'three'; break; case 2: $menu_style = 'two'; break; default: $menu_style = 'one'; } ?> <div class="ui <?php echo esc_attr( $menu_style ); ?> column equal height divided grid"> <?php if ( isset( $popout_menu['col1'] ) && count( $popout_menu['col1'] ) > 0 ) { ?> <div class="column"> <h4 class="ui header"><?php esc_html_e( 'CRM Admin', 'zero-bs-crm' ); ?></h4> <div class="ui link list"> <?php foreach ( $popout_menu['col1'] as $link ) { echo $link; } ?> </div> </div> <?php } ##WLREMOVE // no need for support column if white label ?> <div class="column"> <h4 class="ui header"><?php esc_html_e( 'Support', 'zero-bs-crm' ); ?></h4> <div class="ui link list"> <div class="jpcrm-user-menu-link"> <a href="<?php echo esc_url( $zbs->urls['docs'] ); ?>" class="item" target="_blank"><i class="file text outline icon"></i> <?php esc_html_e( 'Knowledge base', 'zero-bs-crm' ); ?></a> </div> <div class="jpcrm-user-menu-link"> <a href="<?php echo esc_url( zeroBSCRM_getAdminURL( $zbs->slugs['support'] ) ); ?>" class="item"><i class="icon user md"></i> <?php esc_html_e( 'Support', 'zero-bs-crm' ); ?></a> </div> <div class="jpcrm-user-menu-link"> <a href="<?php echo esc_url( $zbs->urls['twitter'] ); ?>" class="item" target="_blank"><i class="icon twitter"></i> <?php esc_html_e( '@jetpackcrm', 'zero-bs-crm' ); ?></a> </div> <div class="jpcrm-user-menu-link"> <a class="item" href="<?php echo esc_url( $zbs->urls['rateuswporg'] ); ?>"><i class="star icon" aria-hidden="true"></i> <?php esc_html_e( 'Leave a review', 'zero-bs-crm' ); ?></a> </div> <?php // welcome tour and crm resources page for admins :) if ( zeroBSCRM_isZBSAdminOrAdmin() ) { ?> <div class="jpcrm-user-menu-link"> <a id="zbs-tour-top-menu-dash" href="<?php echo esc_url( zeroBSCRM_getAdminURL( $zbs->slugs['dash'] ) ); ?>&zbs-welcome-tour=1" class="item"><i class="icon magic"></i> <?php esc_html_e( 'Welcome Tour', 'zero-bs-crm' ); ?></a> </div> <div class="jpcrm-user-menu-link"> <a id="crm-resources-top-menu-dash" href="<?php echo esc_url( zeroBSCRM_getAdminURL( $zbs->slugs['crmresources'] ) ); ?>" class="item"><i class="icon building"></i> <?php esc_html_e( 'Resources', 'zero-bs-crm' ); ?></a> </div> <?php } ?> </div> </div> <?php ##/WLREMOVE ?> <div class="column"> <h4 class="ui header"><?php echo esc_html( $currentUser->display_name ); ?></h4> <div class="ui link list"> <div class="jpcrm-user-menu-link"> <a id="zbs-profile-top-menu" href="<?php echo esc_url( zeroBSCRM_getAdminURL( $zbs->slugs['your-profile'] ) ); ?>" class="item"><i class="icon user"></i> <?php esc_html_e( 'Your Profile', 'zero-bs-crm' ); ?></a> </div> <?php if ( zeroBSCRM_getSetting( 'feat_calendar' ) > 0 ) { $cID = get_current_user_id(); ?> <div class="jpcrm-user-menu-link"> <a id="jpcrm-tasks-top-menu" href="<?php echo esc_url( zeroBSCRM_getAdminURL( $zbs->slugs['manage-tasks'] ) ); ?>&zbsowner=<?php echo esc_attr( $cID ); // phpcs:ignore ?>" class="item"><i class="icon tasks"></i> <?php esc_html_e( 'Your Tasks', 'zero-bs-crm' ); ?></a> </div> <?php } ?> <?php ##WLREMOVE //upsell if ( ! zeroBSCRM_hasPaidExtensionActivated() && zeroBSCRM_isZBSAdminOrAdmin() ) { ?> <div class="jpcrm-user-menu-link"> <a class="item" href="<?php echo esc_url( $zbs->urls['pricing'] ); ?>" target="_blank"><i class="rocket icon" aria-hidden="true"></i> <?php esc_html_e( 'Plans', 'zero-bs-crm' ); ?></a> </div> <?php } ##/WLREMOVE ?> <div class="ui divider"></div> <div class="jpcrm-user-menu-link"> <a href="<?php echo esc_url( wp_logout_url() ); ?>" class="item"><i class="icon sign out"></i> <?php esc_html_e( 'Log Out', 'zero-bs-crm' ); ?></a> </div> </div> </div> </div> </div> </menu-section> </menu-bar><!-- end .menu-bar --> </div> <?php } } // dumps out 'active' class if slug matches loaded page // note 'active' seems to open drop downs, so now using: current_menu_item function zeroBS_menu_active( $slug = '' ) { if ( ( isset( $_GET['page'] ) && $_GET['page'] == $slug ) || ( isset( $_GET['zbsslug'] ) && $_GET['zbsslug'] == $slug ) ) { echo ' current_menu_item'; } } // dumps out 'active' class if slug is within a 'section' // note 'active' seems to open drop downs, so now using: current_menu_item function zeroBS_menu_active_type( $type = '' ) { switch ( $type ) { case 'contact': if ( zeroBSCRM_isAnyContactPage() ) { echo ' current_menu_item'; } break; case 'quote': if ( zeroBSCRM_isAnyQuotePage() ) { echo ' current_menu_item'; } break; case 'invoice': if ( zeroBSCRM_isAnyInvoicePage() ) { echo ' current_menu_item'; } break; case 'transaction': if ( zeroBSCRM_isAnyTransactionPage() ) { echo ' current_menu_item'; } break; } }
projects/plugins/crm/includes/ZeroBSCRM.DAL3.Obj.Quotes.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V3.0+ * * Copyright 2020 Automattic * * Date: 14/01/19 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /** * ZBS DAL >> Quotes * * @author Woody Hayday <hello@jetpackcrm.com> * @version 2.0 * @access public * @see https://jetpackcrm.com/kb */ class zbsDAL_quotes extends zbsDAL_ObjectLayer { protected $objectType = ZBS_TYPE_QUOTE; protected $objectDBPrefix = 'zbsq_'; protected $include_in_templating = true; protected $objectModel = array( // ID 'ID' => array('fieldname' => 'ID', 'format' => 'int'), // site + team generics 'zbs_site' => array('fieldname' => 'zbs_site', 'format' => 'int'), 'zbs_team' => array('fieldname' => 'zbs_team', 'format' => 'int'), 'zbs_owner' => array('fieldname' => 'zbs_owner', 'format' => 'int'), // other fields 'id_override' => array( 'fieldname' => 'zbsq_id_override', 'format' => 'str', 'max_len' => 128 ), 'title' => array( // db model: 'fieldname' => 'zbsq_title', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'Quote Title', 'placeholder'=> 'e.g. New Website', 'essential' => true, 'dal1key' => 'name', 'max_len' => 255 ), 'currency' => array( 'fieldname' => 'zbsq_currency', 'format' => 'curr', 'max_len' => 4 ), 'value' => array( // db model: 'fieldname' => 'zbsq_value', 'format' => 'decimal', // output model 'input_type' => 'price', 'label' => 'Quote Value', 'placeholder'=> 'e.g. 500.00', 'essential' => true, 'dal1key' => 'val' ), 'date' => array( // db model: 'fieldname' => 'zbsq_date', 'format' => 'uts', 'autoconvert'=>'date', // NOTE autoconvert makes buildObjArr autoconvert from a 'date' using localisation rules, to a GMT timestamp (UTS) // output model 'input_type' => 'date', 'label' => 'Quote Date', 'placeholder'=>'', 'essential' => true ), 'template' => array('fieldname' => 'zbsq_template', 'format' => 'str'), 'content' => array('fieldname' => 'zbsq_content', 'format' => 'str'), 'notes' => array( // db model: 'fieldname' => 'zbsq_notes', 'format' => 'str', // output model 'input_type' => 'textarea', 'label' => 'Notes', 'placeholder'=>'' ), 'send_attachments' => array('fieldname' => 'zbsq_send_attachments', 'format' => 'bool'), // note, from 4.0.9 we removed this from the front-end ui as we now show a modal option pre-send allowing user to chose which pdf's to attach 'hash' => array('fieldname' => 'zbsq_hash', 'format' => 'str'), 'lastviewed' => array('fieldname' => 'zbsq_lastviewed', 'format' => 'uts'), 'viewed_count' => array('fieldname' => 'zbsq_viewed_count', 'format' => 'int'), 'accepted' => array('fieldname' => 'zbsq_accepted', 'format' => 'uts'), 'acceptedsigned' => array( 'fieldname' => 'zbsq_acceptedsigned', 'format' => 'str', 'max_len' => 200 ), 'acceptedip' => array( 'fieldname' => 'zbsq_acceptedip', 'format' => 'str', 'max_len' => 64 ), 'created' => array('fieldname' => 'zbsq_created', 'format' => 'uts'), 'lastupdated' => array('fieldname' => 'zbsq_lastupdated', 'format' => 'uts'), ); // hardtyped list of types this object type is commonly linked to protected $linkedToObjectTypes = array( ZBS_TYPE_CONTACT ); function __construct($args=array()) { #} =========== LOAD ARGS ============== $defaultArgs = array( //'tag' => false, ); foreach ($defaultArgs as $argK => $argV){ $this->$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $this->$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$this->$argK = $newData;} else { $this->$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= add_filter( 'jpcrm_listview_filters', array( $this, 'add_listview_filters' ) ); } /** * Adds items to listview filter using `jpcrm_listview_filters` hook. * * @param array $listview_filters Listview filters. */ public function add_listview_filters( $listview_filters ) { global $zbs; // Add statuses if enabled. if ( $zbs->settings->get( 'filtersfromstatus' ) === 1 ) { $statuses = array( 'draft' => __( 'Draft', 'zero-bs-crm' ), 'accepted' => __( 'Accepted', 'zero-bs-crm' ), 'notaccepted' => __( 'Not Accepted', 'zero-bs-crm' ), ); foreach ( $statuses as $status_slug => $status_label ) { $listview_filters[ ZBS_TYPE_QUOTE ]['status'][ 'status_' . $status_slug ] = $status_label; } } return $listview_filters; } // =============================================================================== // =========== QUOTE ======================================================= // generic get Company (by ID) // Super simplistic wrapper used by edit page etc. (generically called via dal->contacts->getSingle etc.) public function getSingle($ID=-1){ return $this->getQuote($ID); } // generic get (by ID list) // Super simplistic wrapper used by MVP Export v3.0 public function getIDList($IDs=false){ return $this->getQuotes(array( 'inArr' => $IDs, 'withOwner' => true, 'withAssigned' => true, 'page' => -1, 'perPage' => -1 )); } // generic get (EVERYTHING) // expect heavy load! public function getAll($IDs=false){ return $this->getQuotes(array( 'withOwner' => true, 'withAssigned' => true, 'sortByField' => 'ID', 'sortOrder' => 'ASC', 'page' => -1, 'perPage' => -1, )); } // generic get count of (EVERYTHING) public function getFullCount(){ return $this->getQuotes(array( 'count' => true, 'page' => -1, 'perPage' => -1, )); } /** * returns full quote line +- details * * @param int id quote id * @param array $args Associative array of arguments * * @return array quote object */ public function getQuote($id=-1,$args=array()){ global $zbs; #} =========== LOAD ARGS ============== $defaultArgs = array( // if these are passed, will search based on these 'id_override' => false, 'externalSource' => false, 'externalSourceUID' => false, 'hash' => false, // with what? 'withLineItems' => true, 'withCustomFields' => true, 'withAssigned' => true, // return ['contact'] & ['company'] objs if has link 'withTags' => false, 'withFiles' => false, 'withOwner' => false, // permissions 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_QUOTE), // this'll let you not-check the owner of obj // returns scalar ID of line 'onlyID' => false, 'fields' => false // false = *, array = fieldnames ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} Check ID $id = (int)$id; if ( (!empty($id) && $id > 0) || (!empty($email)) || (!empty($hash)) || (!empty($externalSource) && !empty($externalSourceUID)) ){ global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); $extraSelect = ''; #} ============= PRE-QUERY ============ #} Custom Fields if ($withCustomFields && !$onlyID){ #} Retrieve any cf $custFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_QUOTE)); #} Cycle through + build into query if (is_array($custFields)) foreach ($custFields as $cK => $cF){ // add as subquery $extraSelect .= ',(SELECT zbscf_objval FROM '.$ZBSCRM_t['customfields']." WHERE zbscf_objid = quote.ID AND zbscf_objkey = %s AND zbscf_objtype = %d LIMIT 1) '".$cK."'"; // add params $params[] = $cK; $params[] = ZBS_TYPE_QUOTE; } } $selector = 'quote.*'; if (isset($fields) && is_array($fields)) { $selector = ''; // always needs id, so add if not present if (!in_array('ID',$fields)) $selector = 'quote.ID'; foreach ($fields as $f) { if (!empty($selector)) $selector .= ','; $selector .= 'quote.'.$f; } } else if ($onlyID){ $selector = 'quote.ID'; } #} ============ / PRE-QUERY =========== #} Build query $query = "SELECT ".$selector.$extraSelect." FROM ".$ZBSCRM_t['quotes'].' as quote'; #} ============= WHERE ================ if (!empty($id) && $id > 0){ #} Add ID $wheres['ID'] = array('ID','=','%d',$id); } if (!empty($id_override) && $id_override > 0){ #} Add id_override //$wheres['search_id'] = array('ID','LIKE','%s','%'.$id_override.'%'); $wheres['search_id2'] = array('zbsq_id_override','LIKE','%s','%'.$id_override.'%'); } if (!empty($hash)){ #} Add hash $wheres['hash'] = array('zbsq_hash','=','%s',$hash); } if (!empty($externalSource) && !empty($externalSourceUID)){ $wheres['extsourcecheck'] = array('ID','IN','(SELECT DISTINCT zbss_objid FROM '.$ZBSCRM_t['externalsources']." WHERE zbss_objtype = ".ZBS_TYPE_QUOTE." AND zbss_source = %s AND zbss_uid = %s)",array($externalSource,$externalSourceUID)); } #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner,'quote'); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort('ID','DESC') . $this->buildPaging(0,1); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_row($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret Results (ROW) if (isset($potentialRes) && isset($potentialRes->ID)) { #} Has results, tidy + return #} Only ID? return it directly if ($onlyID) return $potentialRes->ID; // tidy if (is_array($fields)){ // guesses fields based on table col names $res = $this->lazyTidyGeneric($potentialRes); } else { // proper tidy $res = $this->tidy_quote($potentialRes,$withCustomFields); } if ($withLineItems){ // add all line item lines $res['lineitems'] = $this->DAL()->lineitems->getLineitems(array('associatedObjType'=>ZBS_TYPE_QUOTE,'associatedObjID'=>$potentialRes->ID,'perPage'=>1000,'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_LINEITEM))); } if ($withAssigned){ /* This is for MULTIPLE (e.g. multi contact/companies assigned to an inv) // add all assigned contacts/companies $res['contacts'] = $this->DAL()->contacts->getContacts(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_QUOTE, 'hasObjIDLinkedTo'=>$resDataLine->ID, 'perPage'=>-1, 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); $res['companies'] = $this->DAL()->companies->getCompanies(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_QUOTE, 'hasObjIDLinkedTo'=>$resDataLine->ID, 'perPage'=>-1, 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_COMPANY))); .. but we use 1:1, at least now: */ // add all assigned contacts/companies $res['contact'] = $this->DAL()->contacts->getContacts(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_QUOTE, 'hasObjIDLinkedTo'=>$potentialRes->ID, 'page' => 0, 'perPage'=>1, // FORCES 1 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); $res['company'] = $this->DAL()->companies->getCompanies(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_QUOTE, 'hasObjIDLinkedTo'=>$potentialRes->ID, 'page' => 0, 'perPage'=>1, // FORCES 1 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_COMPANY))); } if ($withFiles){ $res['files'] = zeroBSCRM_files_getFiles('quote',$potentialRes->ID); } if ($withTags){ // add all tags lines $res['tags'] = $this->DAL()->getTagsForObjID(array('objtypeid'=>ZBS_TYPE_QUOTE,'objid'=>$potentialRes->ID)); } return $res; } } // / if ID return false; } /** * returns quote detail lines * * @param array $args Associative array of arguments * * @return array of quote lines */ public function getQuotes($args=array()){ global $zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( // Search/Filtering (leave as false to ignore) 'searchPhrase' => '', // searches id, id override, title, content 'inArr' => false, 'isTagged' => false, // 1x INT OR array(1,2,3) 'isNotTagged' => false, // 1x INT OR array(1,2,3) 'ownedBy' => false, 'externalSource' => false, // e.g. paypal 'olderThan' => false, // uts 'newerThan' => false, // uts 'hasAccepted' => false, // if TRUE only returns accepted 'hasNotAccepted' => false, // if TRUE only returns not-accepted 'assignedContact' => false, // assigned to contact id (int) 'assignedCompany' => false, // assigned to company id (int) 'quickFilters' => false, // booo // returns 'count' => false, 'withLineItems' => true, 'withCustomFields' => true, 'withTags' => false, 'withOwner' => false, 'withAssigned' => false, // return ['contact'] & ['company'] objs if has link 'withFiles' => false, 'suppressContent' => false, // do not return html 'onlyColumns' => false, // if passed (array('fname','lname')) will return only those columns (overwrites some other 'return' options). NOTE: only works for base fields (not custom fields) 'sortByField' => 'ID', 'sortOrder' => 'ASC', 'page' => 0, // this is what page it is (gets * by for limit) 'perPage' => 100, 'whereCase' => 'AND', // DEFAULT = AND // permissions 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_QUOTE), // this'll let you not-check the owner of obj ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= global $ZBSCRM_t,$wpdb,$zbs; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); $joinQ = ''; $extraSelect = ''; #} ============= PRE-QUERY ============ #} Capitalise this $sortOrder = strtoupper($sortOrder); #} If just count, turn off any extra gumpf if ($count) { $withCustomFields = false; $withTags = false; $withFiles = false; $withOwner = false; $withAssigned = false; } #} If onlyColumns, validate if ($onlyColumns){ #} onlyColumns build out a field arr if (is_array($onlyColumns) && count($onlyColumns) > 0){ $onlyColumnsFieldArr = array(); foreach ($onlyColumns as $col){ // find db col key from field key (e.g. fname => zbsc_fname) $dbCol = ''; if (isset($this->objectModel[$col]) && isset($this->objectModel[$col]['fieldname'])) $dbCol = $this->objectModel[$col]['fieldname']; if (!empty($dbCol)){ $onlyColumnsFieldArr[$dbCol] = $col; } } } // if legit cols: if (isset($onlyColumnsFieldArr) && is_array($onlyColumnsFieldArr) && count($onlyColumnsFieldArr) > 0){ $onlyColumns = true; // If onlyColumns, turn off extras $withCustomFields = false; $withTags = false; $withFiles = false; $withOwner = false; $withAssigned = false; } else { // deny $onlyColumns = false; } } #} Custom Fields if ($withCustomFields){ #} Retrieve any cf $custFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_QUOTE)); #} Cycle through + build into query if (is_array($custFields)) foreach ($custFields as $cK => $cF){ // custom field (e.g. 'third name') it'll be passed here as 'third-name' // ... problem is mysql does not like that :) so we have to chage here: // in this case we prepend cf's with cf_ and we switch - for _ $cKey = 'cf_'.str_replace('-','_',$cK); // we also check the $sortByField in case that's the same cf if ($cK == $sortByField){ // sort by $sortByField = $cKey; // check if sort needs any CAST (e.g. numeric): $sortByField = $this->DAL()->build_custom_field_order_by_str( $sortByField, $cF ); } // add as subquery $extraSelect .= ',(SELECT zbscf_objval FROM '.$ZBSCRM_t['customfields']." WHERE zbscf_objid = quote.ID AND zbscf_objkey = %s AND zbscf_objtype = %d LIMIT 1) ".$cKey; // add params $params[] = $cK; $params[] = ZBS_TYPE_QUOTE; } } #} ============ / PRE-QUERY =========== #} Build query $query = "SELECT quote.*".$extraSelect." FROM ".$ZBSCRM_t['quotes'].' as quote'.$joinQ; #} Count override if ($count) $query = "SELECT COUNT(quote.ID) FROM ".$ZBSCRM_t['quotes'].' as quote'.$joinQ; #} onlyColumns override if ($onlyColumns && is_array($onlyColumnsFieldArr) && count($onlyColumnsFieldArr) > 0){ $columnStr = ''; foreach ($onlyColumnsFieldArr as $colDBKey => $colStr){ if (!empty($columnStr)) $columnStr .= ','; // this presumes str is db-safe? could do with sanitation? $columnStr .= $colDBKey; } $query = "SELECT ".$columnStr." FROM ".$ZBSCRM_t['quotes'].' as quote'.$joinQ; } #} ============= WHERE ================ #} Add Search phrase if (!empty($searchPhrase)){ // search? - ALL THESE COLS should probs have index of FULLTEXT in db? $searchWheres = array(); $searchWheres['search_id'] = array('ID','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_id_override'] = array('zbsq_id_override','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_title'] = array('zbsq_title','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_content'] = array('zbsq_content','LIKE','%s','%'.$searchPhrase.'%'); // 3.0.13 - Added ability to search custom fields (optionally) $customFieldSearch = zeroBSCRM_getSetting('customfieldsearch'); if ($customFieldSearch == 1){ // simplistic add // NOTE: This IGNORES ownership of custom field lines. $searchWheres['search_customfields'] = array('ID','IN',"(SELECT zbscf_objid FROM ".$ZBSCRM_t['customfields']." WHERE zbscf_objval LIKE %s AND zbscf_objtype = ".ZBS_TYPE_QUOTE.")",'%'.$searchPhrase.'%'); } // This generates a query like 'zbsq_fname LIKE %s OR zbsq_lname LIKE %s', // which we then need to include as direct subquery (below) in main query :) $searchQueryArr = $this->buildWheres($searchWheres,'',array(),'OR',false); if (is_array($searchQueryArr) && isset($searchQueryArr['where']) && !empty($searchQueryArr['where'])){ // add it $wheres['direct'][] = array('('.$searchQueryArr['where'].')',$searchQueryArr['params']); } } #} In array (if inCompany passed, this'll currently overwrite that?! (todo2.5)) if (is_array($inArr) && count($inArr) > 0){ // clean for ints $inArrChecked = array(); foreach ($inArr as $x){ $inArrChecked[] = (int)$x; } // add where $wheres['inarray'] = array('ID','IN','('.implode(',',$inArrChecked).')'); } #} Owned by if (!empty($ownedBy) && $ownedBy > 0){ // would never hard-type this in (would make generic as in buildWPMetaQueryWhere) // but this is only here until MIGRATED to db2 globally //$wheres['incompany'] = array('ID','IN','(SELECT DISTINCT post_id FROM '.$wpdb->prefix."postmeta WHERE meta_key = 'zbs_company' AND meta_value = %d)",$inCompany); // Use obj links now $wheres['ownedBy'] = array('zbs_owner','=','%s',$ownedBy); } // External sources if ( !empty( $externalSource ) ){ // NO owernship built into this, check when roll out multi-layered ownsership $wheres['externalsource'] = array('ID','IN','(SELECT DISTINCT zbss_objid FROM '.$ZBSCRM_t['externalsources']." WHERE zbss_objtype = ".ZBS_TYPE_QUOTE." AND zbss_source = %s)",$externalSource); } // quick addition for mike #} olderThan if (!empty($olderThan) && $olderThan > 0 && $olderThan !== false) $wheres['olderThan'] = array('zbsq_created','<=','%d',$olderThan); #} newerThan if (!empty($newerThan) && $newerThan > 0 && $newerThan !== false) $wheres['newerThan'] = array('zbsq_created','>=','%d',$newerThan); // status if (!empty($hasAccepted) && $hasAccepted) $wheres['hasAccepted'] = array('zbsq_accepted','>','%d',0); if (!empty($hasNotAccepted) && $hasNotAccepted) $wheres['hasnotAccepted'] = array('zbsq_accepted','<=','%d',0); // assignedContact + assignedCompany if (!empty($assignedContact) && $assignedContact !== false && $assignedContact > 0) $wheres['assignedContact'] = array('ID','IN','(SELECT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = ".ZBS_TYPE_QUOTE." AND zbsol_objtype_to = ".ZBS_TYPE_CONTACT." AND zbsol_objid_to = %d)",$assignedContact); if (!empty($assignedCompany) && $assignedCompany !== false && $assignedCompany > 0) $wheres['assignedCompany'] = array('ID','IN','(SELECT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = ".ZBS_TYPE_QUOTE." AND zbsol_objtype_to = ".ZBS_TYPE_COMPANY." AND zbsol_objid_to = %d)",$assignedCompany); #} Quick filters - adapted from DAL1 (probs can be slicker) if (is_array($quickFilters) && count($quickFilters) > 0){ // cycle through foreach ( $quickFilters as $quick_filter ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable if ( $quick_filter === 'status_accepted' ) { $wheres['quickfilterstatus'] = array( 'zbsq_accepted', '>', '0' ); $wheres['quickfilterstatus2'] = array( 'zbsq_template', '>', '0' ); } elseif ( $quick_filter === 'status_notaccepted' ) { $wheres['quickfilterstatus'] = array( 'zbsq_accepted', '<=', '0' ); $wheres['quickfilterstatus2'] = array( 'zbsq_template', '>', '0' ); } elseif ( $quick_filter === 'status_draft' ) { $wheres['quickfilterstatus'] = array( 'zbsq_template', '<=', '0' ); } } } // / quickfilters #} Any additionalWhereArr? if (isset($additionalWhereArr) && is_array($additionalWhereArr) && count($additionalWhereArr) > 0){ // add em onto wheres (note these will OVERRIDE if using a key used above) // Needs to be multi-dimensional $wheres = array_merge($wheres,$additionalWhereArr); $wheres = array_merge_recursive($wheres,$additionalWhereArr); } #} Is Tagged (expects 1 tag ID OR array) // catch 1 item arr if (is_array($isTagged) && count($isTagged) == 1) $isTagged = $isTagged[0]; if (!is_array($isTagged) && !empty($isTagged) && $isTagged > 0){ // add where tagged // 1 int: $wheres['direct'][] = array('((SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = quote.ID AND zbstl_tagid = %d) > 0)',array(ZBS_TYPE_QUOTE,$isTagged)); } else if (is_array($isTagged) && count($isTagged) > 0){ // foreach in array :) $tagStr = ''; foreach ($isTagged as $iTag){ $i = (int)$iTag; if ($i > 0){ if ($tagStr !== '') $tagStr .','; $tagStr .= $i; } } if (!empty($tagStr)){ $wheres['direct'][] = array('((SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = quote.ID AND zbstl_tagid IN (%s)) > 0)',array(ZBS_TYPE_QUOTE,$tagStr)); } } #} Is NOT Tagged (expects 1 tag ID OR array) // catch 1 item arr if (is_array($isNotTagged) && count($isNotTagged) == 1) $isNotTagged = $isNotTagged[0]; if (!is_array($isNotTagged) && !empty($isNotTagged) && $isNotTagged > 0){ // add where tagged // 1 int: $wheres['direct'][] = array('((SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = quote.ID AND zbstl_tagid = %d) = 0)',array(ZBS_TYPE_QUOTE,$isNotTagged)); } else if (is_array($isNotTagged) && count($isNotTagged) > 0){ // foreach in array :) $tagStr = ''; foreach ($isNotTagged as $iTag){ $i = (int)$iTag; if ($i > 0){ if ($tagStr !== '') $tagStr .','; $tagStr .= $i; } } if (!empty($tagStr)){ $wheres['direct'][] = array('((SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = quote.ID AND zbstl_tagid IN (%s)) = 0)',array(ZBS_TYPE_QUOTE,$tagStr)); } } #} ============ / WHERE =============== #} ============ SORT ============== // Obj Model based sort conversion // converts 'addr1' => 'zbsco_addr1' generically if (isset($this->objectModel[$sortByField]) && isset($this->objectModel[$sortByField]['fieldname'])) $sortByField = $this->objectModel[$sortByField]['fieldname']; // Mapped sorts // This catches listview and other exception sort cases $sort_map = array( 'customer' => '(SELECT zbsol_objid_to FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_QUOTE . ' AND zbsol_objtype_to = ' . ZBS_TYPE_CONTACT . ' AND zbsol_objid_from = quote.ID)', // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // hack to support quote statuses (for here only, 2 is accepted, 1 is unaccepted, 0 is draft) 'status' => '(CASE WHEN zbsq_accepted > 0 THEN 2 WHEN zbsq_template > 0 THEN 1 ELSE 0 END)', ); if ( array_key_exists( $sortByField, $sort_map ) ) { $sortByField = $sort_map[ $sortByField ]; } #} ============ / SORT ============== #} CHECK this + reset to default if faulty if (!in_array($whereCase,array('AND','OR'))) $whereCase = 'AND'; #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params,$whereCase); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner,'quote'); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort($sortByField,$sortOrder) . $this->buildPaging($page,$perPage); try { #} Prep & run query $queryObj = $this->prepare($query,$params); #} Catch count + return if requested if ($count) return $wpdb->get_var($queryObj); #} else continue.. $potentialRes = $wpdb->get_results($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret results (Result Set - multi-row) if (isset($potentialRes) && is_array($potentialRes) && count($potentialRes) > 0) { #} Has results, tidy + return foreach ($potentialRes as $resDataLine) { // using onlyColumns filter? if ($onlyColumns && is_array($onlyColumnsFieldArr) && count($onlyColumnsFieldArr) > 0){ // only coumns return. $resArr = array(); foreach ($onlyColumnsFieldArr as $colDBKey => $colStr){ if (isset($resDataLine->$colDBKey)) $resArr[$colStr] = $resDataLine->$colDBKey; } } else { // tidy $resArr = $this->tidy_quote($resDataLine,$withCustomFields); } if ($withLineItems){ // add all line item lines $resArr['lineitems'] = $this->DAL()->lineitems->getLineitems(array('associatedObjType'=>ZBS_TYPE_QUOTE,'associatedObjID'=>$resDataLine->ID,'perPage'=>1000,'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_LINEITEM))); } if ($withFiles){ $resArr['files'] = zeroBSCRM_files_getFiles('quote',$resDataLine->ID); } if ($withTags){ // add all tags lines $resArr['tags'] = $this->DAL()->getTagsForObjID(array('objtypeid'=>ZBS_TYPE_QUOTE,'objid'=>$resDataLine->ID)); } if ($withAssigned){ /* This is for MULTIPLE (e.g. multi contact/companies assigned to an inv) // add all assigned contacts/companies $res['contacts'] = $this->DAL()->contacts->getContacts(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_QUOTE, 'hasObjIDLinkedTo'=>$resDataLine->ID, 'perPage'=>-1, 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); $res['companies'] = $this->DAL()->companies->getCompanies(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_QUOTE, 'hasObjIDLinkedTo'=>$resDataLine->ID, 'perPage'=>-1, 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_COMPANY))); .. but we use 1:1, at least now: */ // add all assigned contacts/companies $resArr['contact'] = $this->DAL()->contacts->getContacts(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_QUOTE, 'hasObjIDLinkedTo'=>$resDataLine->ID, 'page' => 0, 'perPage'=>1, // FORCES 1 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); $resArr['company'] = $this->DAL()->companies->getCompanies(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_QUOTE, 'hasObjIDLinkedTo'=>$resDataLine->ID, 'page' => 0, 'perPage'=>1, // FORCES 1 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_COMPANY))); } if ($suppressContent) unset($resArr['content']); $res[] = $resArr; } } return $res; } /** * Returns a count of quotes (owned) * .. inc by status * * @return int count */ public function getQuoteCount($args=array()){ #} ============ LOAD ARGS ============= $defaultArgs = array( // Search/Filtering (leave as false to ignore) 'withStatus' => false, // will be str if used // permissions 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_QUOTE), // this'll let you not-check the owner of obj ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= $whereArr = array(); if ($withStatus !== false && !empty($withStatus)) $whereArr['status'] = array('zbsq_status','=','%s',$withStatus); return $this->DAL()->getFieldByWHERE(array( 'objtype' => ZBS_TYPE_QUOTE, 'colname' => 'COUNT(ID)', 'where' => $whereArr, 'ignoreowner' => $ignoreowner)); } /** * adds or updates a quote object * * @param array $args Associative array of arguments * id (if update), owner, data (array of field data) * * @return int line ID */ public function addUpdateQuote($args=array()){ global $ZBSCRM_t,$wpdb,$zbs; #} Retrieve any cf $customFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_QUOTE)); $addrCustomFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_ADDRESS)); #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'owner' => -1, // fields (directly) 'data' => array( 'id_override' => '', 'title' => '', 'currency' => '', 'value' => '', 'date' => '', 'template' => '', 'content' => '', 'notes' => '', 'send_attachments' => -1, 'hash' => '', 'lastviewed' => '', 'viewed_count' => '', 'accepted' => '', 'acceptedsigned' => '', 'acceptedip' => '', // lineitems: 'lineitems' => false, // will be an array of lineitem lines (as per matching lineitem database model) // note: if no change desired, pass "false" // if removal of all/change, pass empty array // Note Custom fields may be passed here, but will not have defaults so check isset() // obj links: 'contacts' => false, // array of id's 'companies' => false, // array of id's // tags 'tags' => -1, // pass an array of tag ids or tag strings 'tag_mode' => 'replace', // replace|append|remove 'externalSources' => -1, // if this is an array(array('source'=>src,'uid'=>uid),multiple()) it'll add :) // allow this to be set for MS sync, Migrations etc. 'created' => -1, 'lastupdated' => '', ), 'limitedFields' => -1, // if this is set it OVERRIDES data (allowing you to set specific fields + leave rest in tact) // ^^ will look like: array(array('key'=>x,'val'=>y,'type'=>'%s')) // this function as DAL1 func did. 'extraMeta' => -1, 'automatorPassthrough' => -1, 'silentInsert' => false, // this was for init Migration - it KILLS all IA for newQuote (because is migrating, not creating new :) this was -1 before 'do_not_update_blanks' => false // this allows you to not update fields if blank (same as fieldoverride for extsource -> in) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } // Needs this to grab custom fields (if passed) too :) if (is_array($customFields)) foreach ($customFields as $cK => $cF){ // only for data, limited fields below if (is_array($data)) { if (isset($args['data'][$cK])) $data[$cK] = $args['data'][$cK]; } } // this takes limited fields + checks through for custom fields present // (either as key zbsq_source or source, for example) // then switches them into the $data array, for separate update // where this'll fall over is if NO normal contact data is sent to update, just custom fields if (is_array($limitedFields) && is_array($customFields)){ //$customFieldKeys = array_keys($customFields); $newLimitedFields = array(); // cycle through foreach ($limitedFields as $field){ // some weird case where getting empties, so added check if (isset($field['key']) && !empty($field['key'])){ $dePrefixed = ''; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase if ( str_starts_with( $field['key'], 'zbsq_' ) ) { $dePrefixed = substr( $field['key'], strlen( 'zbsq_' ) ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } if (isset($customFields[$field['key']])){ // is custom, move to data $data[$field['key']] = $field['val']; } else if (!empty($dePrefixed) && isset($customFields[$dePrefixed])){ // is custom, move to data $data[$dePrefixed] = $field['val']; } else { // add it to limitedFields (it's not dealt with post-update) $newLimitedFields[] = $field; } } } // move this back in $limitedFields = $newLimitedFields; unset($newLimitedFields); } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ $id = (int)$id; // here we check that the potential owner CAN even own if (!user_can($owner,'admin_zerobs_usr')) $owner = -1; // if owner = -1, add current if (!isset($owner) || $owner === -1) { $owner = zeroBSCRM_user(); } // if no date is passed, use current date if ( empty( $data['date'] ) ) { $data['date'] = time(); // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable } if (is_array($limitedFields)){ // LIMITED UPDATE (only a few fields.) if (!is_array($limitedFields) || count ($limitedFields) <= 0) return false; // REQ. ID too (can only update) if (empty($id) || $id <= 0) return false; } else { // NORMAL, FULL UPDATE } #} ========= / CHECK FIELDS =========== #} ========= OVERRIDE SETTING (Deny blank overrides) =========== // this only functions if externalsource is set (e.g. api/form, etc.) if (isset($data['externalSources']) && is_array($data['externalSources']) && count($data['externalSources']) > 0) { if (zeroBSCRM_getSetting('fieldoverride') == "1"){ $do_not_update_blanks = true; } } // either ext source + setting, or set by the func call if ($do_not_update_blanks){ // this setting says 'don't override filled-out data with blanks' // so here we check through any passed blanks + convert to limitedFields // only matters if $id is set (there is somt to update not add if (isset($id) && !empty($id) && $id > 0){ // get data to copy over (for now, this is required to remove 'fullname' etc.) $dbData = $this->db_ready_quote($data); //unset($dbData['id']); // this is unset because we use $id, and is update, so not req. legacy issue //unset($dbData['created']); // this is unset because this uses an obj which has been 'updated' against original details, where created is output in the WRONG format :) $origData = $data; //$data = array(); $limitedData = array(); // array(array('key'=>'zbsq_x','val'=>y,'type'=>'%s')) // cycle through + translate into limitedFields (removing any blanks, or arrays (e.g. externalSources)) // we also have to remake a 'faux' data (removing blanks for tags etc.) for the post-update updates foreach ($dbData as $k => $v){ $intV = (int)$v; // only add if valuenot empty if (!is_array($v) && !empty($v) && $v != '' && $v !== 0 && $v !== -1 && $intV !== -1){ // add to update arr $limitedData[] = array( 'key' => 'zbsq_'.$k, // we have to add zbsq_ here because translating from data -> limited fields 'val' => $v, 'type' => $this->getTypeStr('zbsq_'.$k) ); // add to remade $data for post-update updates $data[$k] = $v; } } // copy over $limitedFields = $limitedData; } // / if ID } // / if do_not_update_blanks #} ========= / OVERRIDE SETTING (Deny blank overrides) =========== #} ========= BUILD DATA =========== $update = false; $dataArr = array(); $typeArr = array(); $was_accepted_before = $this->getQuoteAccepted( $id ); if (is_array($limitedFields)){ // LIMITED FIELDS $update = true; // cycle through foreach ($limitedFields as $field){ // some weird case where getting empties, so added check if (!empty($field['key'])){ $dataArr[$field['key']] = $field['val']; $typeArr[] = $field['type']; } } // add update time if (!isset($dataArr['zbsq_lastupdated'])){ $dataArr['zbsq_lastupdated'] = time(); $typeArr[] = '%d'; } } else { // FULL UPDATE/INSERT // contacts - avoid dupes if (isset($data['contacts']) && is_array($data['contacts'])){ $coArr = array(); foreach ($data['contacts'] as $c){ $cI = (int)$c; if ($cI > 0 && !in_array($cI, $coArr)) $coArr[] = $cI; } // reset the main if (count($coArr) > 0) $data['contacts'] = $coArr; else $data['contacts'] = 'unset'; unset($coArr); } // companies - avoid dupes if (isset($data['companies']) && is_array($data['companies'])){ $coArr = array(); foreach ($data['companies'] as $c){ $cI = (int)$c; if ($cI > 0 && !in_array($cI, $coArr)) $coArr[] = $cI; } // reset the main if (count($coArr) > 0) $data['companies'] = $coArr; else $data['companies'] = 'unset'; unset($coArr); } // UPDATE $dataArr = array( // ownership // no need to update these (as of yet) - can't move teams etc. //'zbs_site' => zeroBSCRM_installSite(), //'zbs_team' => zeroBSCRM_installTeam(), //'zbs_owner' => $owner, 'zbsq_id_override' => $data['id_override'], 'zbsq_title' => $data['title'], 'zbsq_currency' => $data['currency'], 'zbsq_value' => $data['value'], 'zbsq_date' => $data['date'], 'zbsq_template' => $data['template'], 'zbsq_content' => $data['content'], 'zbsq_notes' => $data['notes'], 'zbsq_send_attachments' => $data['send_attachments'], 'zbsq_hash' => $data['hash'], 'zbsq_lastviewed' => $data['lastviewed'], 'zbsq_viewed_count' => $data['viewed_count'], 'zbsq_accepted' => $data['accepted'], 'zbsq_acceptedsigned' => $data['acceptedsigned'], 'zbsq_acceptedip' => $data['acceptedip'], 'zbsq_lastupdated' => time(), ); $typeArr = array( // field data types //'%d', // site //'%d', // team //'%d', // owner '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%d', // send_attachment '%s', '%d', '%d', '%d', '%s', '%s', '%d', ); if (!empty($id) && $id > 0){ // is update $update = true; } else { // INSERT (get's few extra :D) $update = false; $dataArr['zbs_site'] = zeroBSCRM_site(); $typeArr[] = '%d'; $dataArr['zbs_team'] = zeroBSCRM_team(); $typeArr[] = '%d'; $dataArr['zbs_owner'] = $owner; $typeArr[] = '%d'; if (isset($data['created']) && !empty($data['created']) && $data['created'] !== -1){ $dataArr['zbsq_created'] = $data['created'];$typeArr[] = '%d'; } else { $dataArr['zbsq_created'] = time(); $typeArr[] = '%d'; } // and on new inserts, if no hash passed, it gen's one if (isset($dataArr['zbsq_hash']) && $dataArr['zbsq_hash'] == '') $dataArr['zbsq_hash'] = zeroBSCRM_generateHash(20); } } #} ========= / BUILD DATA =========== #} ============================================================ #} ========= CHECK force_uniques & not_empty & max_len ======== // if we're passing limitedFields we skip these, for now // #v3.1 - would make sense to unique/nonempty check just the limited fields. #gh-145 if (!is_array($limitedFields)){ // verify uniques if (!$this->verifyUniqueValues($data,$id)) return false; // / fails unique field verify // verify not_empty if (!$this->verifyNonEmptyValues($data)) return false; // / fails empty field verify } // whatever we do we check for max_len breaches and abbreviate to avoid wpdb rejections $dataArr = $this->wpdbChecks($dataArr); #} ========= / CHECK force_uniques & not_empty ================ #} ============================================================ #} Check if ID present if ($update){ /* WH included this "for now" - status change for IA, not sure if used for this obj,? #} Check if obj exists (here) - for now just brutal update (will error when doesn't exist) $originalStatus = $this->getQuoteStatus($id); // log any change of status if (isset($dataArr['zbsq_status']) && !empty($dataArr['zbsq_status']) && !empty($originalStatus) && $dataArr['zbsq_status'] != $originalStatus){ // status change $statusChange = array( 'from' => $originalStatus, 'to' => $dataArr['zbsq_status'] ); } */ #} Attempt update if ($wpdb->update( $ZBSCRM_t['quotes'], $dataArr, array( // where 'ID' => $id ), $typeArr, array( // where data types '%d' )) !== false){ // if passing limitedFields instead of data, we ignore the following // this doesn't work, because data is in args default as arr //if (isset($data) && is_array($data)){ // so... if (!isset($limitedFields) || !is_array($limitedFields) || $limitedFields == -1){ // Line Items ==== // line item work if (isset($data['lineitems']) && is_array($data['lineitems'])){ // if array passed, update, even if removing if (count($data['lineitems']) > 0){ // passed, for now this is BRUTAL and just clears old ones + readds // once live, discuss how to refactor to be less brutal. // delete all lineitems $this->DAL()->lineitems->deleteLineItemsForObject(array('objID'=>$id,'objType'=>ZBS_TYPE_QUOTE)); // addupdate each foreach ($data['lineitems'] as $lineitem) { // slight rejig of passed so works cleanly with data array style $lineItemID = false; if (isset($lineitem['ID'])) $lineItemID = $lineitem['ID']; $this->DAL()->lineitems->addUpdateLineitem(array( 'id'=>$lineItemID, 'linkedObjType' => ZBS_TYPE_QUOTE, 'linkedObjID' => $id, 'data'=>$lineitem )); } } else { // delete all lineitems $this->DAL()->lineitems->deleteLineItemsForObject(array('objID'=>$id,'objType'=>ZBS_TYPE_QUOTE)); } } // / Line Items ==== // OBJ LINKS - to contacts/companies $this->addUpdateObjectLinks($id,$data['contacts'],ZBS_TYPE_CONTACT); ///13567 $this->addUpdateObjectLinks($id,$data['companies'],ZBS_TYPE_COMPANY); // IA also gets 'againstid' historically, but we'll pass as 'against id's' $againstIDs = array('contacts'=>$data['contacts'],'companies'=>$data['companies']); // tags if (isset($data['tags']) && is_array($data['tags'])) { $this->addUpdateQuoteTags( array( 'id' => $id, 'tag_input' => $data['tags'], 'mode' => $data['tag_mode'] ) ); } // externalSources $approvedExternalSource = $this->DAL()->addUpdateExternalSources( array( 'obj_id' => $id, 'obj_type_id' => ZBS_TYPE_QUOTE, 'external_sources' => isset($data['externalSources']) ? $data['externalSources'] : array(), ) ); // for IA below // Custom fields? #} Cycle through + add/update if set if (is_array($customFields)) foreach ($customFields as $cK => $cF){ // any? if (isset($data[$cK])){ // add update $cfID = $this->DAL()->addUpdateCustomField(array( 'data' => array( 'objtype' => ZBS_TYPE_QUOTE, 'objid' => $id, 'objkey' => $cK, 'objval' => $data[$cK] ))); } } // / Custom Fields } // / if $data #} Any extra meta keyval pairs? // BRUTALLY updates (no checking) $confirmedExtraMeta = false; if (isset($extraMeta) && is_array($extraMeta)) { $confirmedExtraMeta = array(); foreach ($extraMeta as $k => $v){ #} This won't fix stupid keys, just catch basic fails... $cleanKey = strtolower(str_replace(' ','_',$k)); #} Brutal update //update_post_meta($postID, 'zbs_customer_extra_'.$cleanKey, $v); $this->DAL()->updateMeta(ZBS_TYPE_QUOTE,$id,'extra_'.$cleanKey,$v); #} Add it to this, which passes to IA $confirmedExtraMeta[$cleanKey] = $v; } } #} INTERNAL AUTOMATOR #} & #} FALLBACKS // UPDATING CONTACT if (!$silentInsert){ // IA General quote update (2.87+) zeroBSCRM_FireInternalAutomator('quote.update',array( 'id'=>$id, 'data'=>$data, 'againstids'=>array(),//$againstIDs, 'extsource'=>false, //$approvedExternalSource, 'automatorpassthrough'=>$automatorPassthrough, #} This passes through any custom log titles or whatever into the Internal automator recipe. 'extraMeta'=>$confirmedExtraMeta #} This is the "extraMeta" passed (as saved) )); // First check if the quote status is new before fire the event if ( empty( $was_accepted_before ) && $data['accepted'] ) { // IA quote.accepted zeroBSCRM_FireInternalAutomator('quote.accepted', array( 'id' => $id, 'data' => $data, 'againstids' => false, 'extsource' => false, 'automatorpassthrough' => false, 'extraMeta' => $confirmedExtraMeta, )); } } // Successfully updated - Return id return $id; } else { $msg = __('DB Update Failed','zero-bs-crm'); $zbs->DAL->addError(302,$this->objectType,$msg,$dataArr); // FAILED update return false; } } else { #} No ID - must be an INSERT if ($wpdb->insert( $ZBSCRM_t['quotes'], $dataArr, $typeArr ) > 0){ #} Successfully inserted, lets return new ID $newID = $wpdb->insert_id; // Line Items ==== // line item work if (isset($data['lineitems']) && is_array($data['lineitems'])){ // if array passed, update, even if removing if (count($data['lineitems']) > 0){ // passed, for now this is BRUTAL and just clears old ones + readds // once live, discuss how to refactor to be less brutal. // delete all lineitems $this->DAL()->lineitems->deleteLineItemsForObject(array('objID'=>$newID,'objType'=>ZBS_TYPE_QUOTE)); // addupdate each foreach ($data['lineitems'] as $lineitem) { // slight rejig of passed so works cleanly with data array style $lineItemID = false; if (isset($lineitem['ID'])) $lineItemID = $lineitem['ID']; $this->DAL()->lineitems->addUpdateLineitem(array( 'id'=>$lineItemID, 'linkedObjType' => ZBS_TYPE_QUOTE, 'linkedObjID' => $newID, 'data'=>$lineitem )); } } else { // delete all lineitems $this->DAL()->lineitems->deleteLineItemsForObject(array('objID'=>$newID,'objType'=>ZBS_TYPE_QUOTE)); } } // / Line Items ==== // OBJ LINKS - to contacts/companies $this->addUpdateObjectLinks($newID,$data['contacts'],ZBS_TYPE_CONTACT); $this->addUpdateObjectLinks($newID,$data['companies'],ZBS_TYPE_COMPANY); // IA also gets 'againstid' historically, but we'll pass as 'against id's' $againstIDs = array('contacts'=>$data['contacts'],'companies'=>$data['companies']); // tags if (isset($data['tags']) && is_array($data['tags'])) { $this->addUpdateQuoteTags( array( 'id' => $newID, 'tag_input' => $data['tags'], 'mode' => $data['tag_mode'] ) ); } // externalSources $approvedExternalSource = $this->DAL()->addUpdateExternalSources( array( 'obj_id' => $newID, 'obj_type_id' => ZBS_TYPE_QUOTE, 'external_sources' => isset($data['externalSources']) ? $data['externalSources'] : array(), ) ); // for IA below // Custom fields? #} Cycle through + add/update if set if (is_array($customFields)) foreach ($customFields as $cK => $cF){ // any? if (isset($data[$cK])){ // add update $cfID = $this->DAL()->addUpdateCustomField(array( 'data' => array( 'objtype' => ZBS_TYPE_QUOTE, 'objid' => $newID, 'objkey' => $cK, 'objval' => $data[$cK] ))); } } // / Custom Fields #} Any extra meta keyval pairs? // BRUTALLY updates (no checking) $confirmedExtraMeta = false; if (isset($extraMeta) && is_array($extraMeta)) { $confirmedExtraMeta = array(); foreach ($extraMeta as $k => $v){ #} This won't fix stupid keys, just catch basic fails... $cleanKey = strtolower(str_replace(' ','_',$k)); #} Brutal update //update_post_meta($postID, 'zbs_customer_extra_'.$cleanKey, $v); $this->DAL()->updateMeta(ZBS_TYPE_QUOTE,$newID,'extra_'.$cleanKey,$v); #} Add it to this, which passes to IA $confirmedExtraMeta[$cleanKey] = $v; } } #} INTERNAL AUTOMATOR #} & #} FALLBACKS // NEW CONTACT if (!$silentInsert){ #} Add to automator zeroBSCRM_FireInternalAutomator('quote.new',array( 'id'=>$newID, 'data'=>$data, 'againstids'=>$againstIDs, 'extsource'=>$approvedExternalSource, 'automatorpassthrough'=>$automatorPassthrough, #} This passes through any custom log titles or whatever into the Internal automator recipe. 'extraMeta'=>$confirmedExtraMeta #} This is the "extraMeta" passed (as saved) )); } return $newID; } else { $msg = __('DB Insert Failed','zero-bs-crm'); $zbs->DAL->addError(303,$this->objectType,$msg,$dataArr); #} Failed to Insert return false; } } return false; } /** * adds or updates a quote's tags * ... this is really just a wrapper for addUpdateObjectTags * * @param array $args Associative array of arguments * id (if update), owner, data (array of field data) * * @return int line ID */ public function addUpdateQuoteTags($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, // generic pass-through (array of tag strings or tag IDs): 'tag_input' => -1, // or either specific: 'tagIDs' => -1, 'tags' => -1, 'mode' => 'append' ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ // check id $id = (int)$id; if (empty($id) || $id <= 0) return false; #} ========= / CHECK FIELDS =========== return $this->DAL()->addUpdateObjectTags( array( 'objtype' => ZBS_TYPE_QUOTE, 'objid' => $id, 'tag_input' => $tag_input, 'tags' => $tags, 'tagIDs' => $tagIDs, 'mode' => $mode ) ); } /** * updates template for a quote * * @param int id quote ID * @param int template ID * * @return bool */ public function setQuoteTemplate($id=-1,$template=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->addUpdateQuote(array( 'id'=>$id, 'limitedFields'=>array( array('key'=>'zbsq_template','val' => $template,'type' => '%d') ))); } return false; } /** * accepts/unaccepts a quote * ... this is really just a wrapper for addUpdateQuote * ... and replaces zeroBS_markQuoteAccepted + zeroBS_markQuoteUnAccepted * * @param array $args Associative array of arguments * id (if update), owner, data (array of field data) * * @return int line ID */ public function addUpdateQuoteAccepted($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'accepted' => -1, 'signedby' => '', 'ip' => '' ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ // check id $id = (int)$id; if (empty($id) || $id <= 0) return false; // WPID may be -1 (NULL) // -1 does okay here if ($WPID == -1) $WPID = ''; #} ========= / CHECK FIELDS =========== #} Enact $r = $this->addUpdateQuote(array( 'id' => $id, 'limitedFields' =>array( array('key'=>'zbsq_accepted','val'=>$accepted,'type'=>'%d'), array('key'=>'zbsq_acceptedsigned','val'=>$signedby,'type'=>'%s'), array('key'=>'zbsq_acceptedip','val'=>$ip,'type'=>'%s') ))); // if quote was accepted, run internal automator quote.accepted if ( $accepted ){ // fire automator zeroBSCRM_FireInternalAutomator('quote.accepted',array( 'id'=>$id, 'data'=>array('signed'=>$signedby,'ip'=>$ip), 'againstids'=>false, 'extsource'=>false, 'automatorpassthrough'=>false, 'extraMeta'=>false )); } return $r; } /** * updates status for an quote (no blanks allowed) * * @param int id quote ID * @param string quote Status * * @return bool */ public function setQuoteStatus($id=-1,$status=-1){ global $zbs; $id = (int)$id; if ($id > 0 && !empty($status) && $status !== -1){ return $this->addUpdateQuote(array( 'id'=>$id, 'limitedFields'=>array( array('key'=>'zbsq_status','val' => $status,'type' => '%s') ))); } return false; } /** * deletes a quote object * * @param array $args Associative array of arguments * id * * @return int success; */ public function deleteQuote($args=array()){ global $ZBSCRM_t,$wpdb,$zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'saveOrphans' => false ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} Check ID & Delete :) $id = (int)$id; if (!empty($id) && $id > 0) { // delete orphans? if ($saveOrphans === false){ // delete any tag links $this->DAL()->deleteTagObjLinks(array( 'objtype' => ZBS_TYPE_QUOTE, 'objid' => $id )); // delete any external source information $this->DAL()->delete_external_sources( array( 'obj_type' => ZBS_TYPE_FORM, 'obj_id' => $id, 'obj_source' => 'all', )); } $del = zeroBSCRM_db2_deleteGeneric($id,'quotes'); #} Add to automator zeroBSCRM_FireInternalAutomator('quote.delete',array( 'id'=>$id, 'saveOrphans'=>$saveOrphans )); return $del; } return false; } /** * tidy's the object from wp db into clean array * * @param array $obj (DB obj) * * @return array quote (clean obj) */ public function tidy_quote( $obj = false, $withCustomFields = false ) { // phpcs:ignore $res = false; if (isset($obj->ID)){ $res = array(); $res['id'] = $obj->ID; /* `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, */ $res['owner'] = $obj->zbs_owner; $res['id_override'] = $this->stripSlashes($obj->zbsq_id_override); $res['title'] = $this->stripSlashes($obj->zbsq_title); $res['currency'] = $this->stripSlashes($obj->zbsq_currency); $res['value'] = $this->stripSlashes($obj->zbsq_value); $res['date'] = (int)$obj->zbsq_date; $res['date_date'] = (isset($obj->zbsq_date) && $obj->zbsq_date > 0) ? zeroBSCRM_date_i18n(-1,$obj->zbsq_date,false,true) : false; $res['template'] = (int)$this->stripSlashes($obj->zbsq_template); $res['content'] = $this->stripSlashes($obj->zbsq_content); $res['notes'] = $this->stripSlashes($obj->zbsq_notes); $res['send_attachments'] = (bool)$obj->zbsq_send_attachments; $res['hash'] = $this->stripSlashes($obj->zbsq_hash); $res['lastviewed'] = (int)$obj->zbsq_lastviewed; $res['lastviewed_date'] = (isset($obj->zbsq_lastviewed) && $obj->zbsq_lastviewed > 0) ? zeroBSCRM_date_i18n(-1,$obj->zbsq_lastviewed,false,true) : false; $res['viewed_count'] = (int)$obj->zbsq_viewed_count; $res['accepted'] = (int)$obj->zbsq_accepted; $res['accepted_date'] = (isset($obj->zbsq_accepted) && $obj->zbsq_accepted > 0) ? zeroBSCRM_date_i18n(-1,$obj->zbsq_accepted,false,true) : false; $res['acceptedsigned'] = (int)$obj->zbsq_accepted; $res['acceptedip'] = (int)$obj->zbsq_accepted; $res['created'] = (int)$obj->zbsq_created; $res['created_date'] = (isset($obj->zbsq_created) && $obj->zbsq_created > 0) ? zeroBSCRM_date_i18n(-1,$obj->zbsq_created,false,true) : false; $res['lastupdated'] = (int)$obj->zbsq_lastupdated; $res['lastupdated_date'] = (isset($obj->zbsq_lastupdated) && $obj->zbsq_lastupdated > 0) ? zeroBSCRM_date_i18n(-1,$obj->zbsq_lastupdated,false,true) : false; // determine status :) $res['status'] = -1; // not yet pub if (isset($res['template']) && $res['template'] > 0) $res['status'] = -2; // published not accepted if (isset($res['accepted']) && $res['accepted'] > 0) $res['status'] = 1; // accepted // custom fields - tidy any that are present: if ($withCustomFields) $res = $this->tidyAddCustomFields(ZBS_TYPE_QUOTE,$obj,$res,false); } return $res; } /** * Wrapper, use $this->getQuoteMeta($contactID,$key) for easy retrieval of singular quote * Simplifies $this->getMeta * * @param int objtype * @param int objid * @param string key * * @return array quote meta result */ public function getQuoteMeta($id=-1,$key='',$default=false){ global $zbs; if (!empty($key)){ return $this->DAL()->getMeta(array( 'objtype' => ZBS_TYPE_QUOTE, 'objid' => $id, 'key' => $key, 'fullDetails' => false, 'default' => $default, 'ignoreowner' => true // for now !! )); } return $default; } /** * Returns content body against a quote * ... Replaces zeroBS_getQuoteBuilderContent() really * * @param int id quote ID * * @return int quote owner id */ public function getQuoteContent($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_QUOTE, 'colname' => 'zbsq_content', 'ignoreowner'=>true)); } return false; } /** * Returns quote template ID, or 0 * * @param int id quote ID * * @return int quote template ID, or 0 */ public function getQuoteTemplateID($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_QUOTE, 'colname' => 'zbsq_template', 'ignoreowner'=>true)); } return false; } /** * Returns quote accepted UTC time, if accepted * * @param int id quote ID * * @return int UTC accepted, or 0 */ public function getQuoteAcceptedTime($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_QUOTE, 'colname' => 'zbsq_accepted', 'ignoreowner'=>true)); } return false; } /** * Returns quote accepted details, if accepted * * @param int id quote ID * * @return array (Accepted deets) */ public function getQuoteAccepted($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ $ret = array( 'accepted' => $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_QUOTE, 'colname' => 'zbsq_accepted', 'ignoreowner'=>true)), 'acceptedsigned' => $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_QUOTE, 'colname' => 'zbsq_acceptedsigned', 'ignoreowner'=>true)), 'acceptedip' => $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_QUOTE, 'colname' => 'zbsq_acceptedip', 'ignoreowner'=>true)) ); } return false; } /** * Returns an ownerid against a quote * * @param int id quote ID * * @return int quote owner id */ public function getQuoteOwner($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_QUOTE, 'colname' => 'zbs_owner', 'ignoreowner'=>true)); } return false; } /** * Returns the first contact associated with a quote * * @param int id quote ID * * @return int quote contact id */ public function getQuoteContactID($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ $contacts = $this->DAL()->getObjsLinkedToObj(array( 'objtypefrom' => ZBS_TYPE_QUOTE, 'objtypeto' => ZBS_TYPE_CONTACT, 'objfromid' => $id, 'count' => false, )); if (is_array($contacts)) foreach ($contacts as $c){ // first return $c['id']; } } return false; } /** * Returns an hash against a quote * * @param int id quote ID * * @return str quote hash string */ public function getQuoteHash($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_QUOTE, 'colname' => 'zbsq_hash', 'ignoreowner'=>true)); } return false; } /** * Returns an status against a quote * * @param int id quote ID * * @return str quote status string */ /* IS THIS USED? public function getQuoteStatus($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_QUOTE, 'colname' => 'zbsq_status', 'ignoreowner'=>true)); } return false; }*/ /** * remove any non-db fields from the object * basically takes array like array('owner'=>1,'fname'=>'x','fullname'=>'x') * and returns array like array('owner'=>1,'fname'=>'x') * This does so based on the objectModel! * * @param array $obj (clean obj) * * @return array (db ready arr) */ private function db_ready_quote($obj=false){ // use the generic? (override here if necessary) return $this->db_ready_obj($obj); } /** * Takes full object and makes a "list view" boiled down version * Used to generate listview objs * * @param array $obj (clean obj) * * @return array (listview ready obj) */ public function listViewObj($quote=false,$columnsRequired=array()){ if (is_array($quote) && isset($quote['id'])){ $resArr = $quote; if (isset($quote['id_override']) && $quote['id_override'] !== null) $resArr['zbsid'] = $quote['id_override']; else $resArr['zbsid'] = $quote['id']; #} Custom columns #} Status $resArr['statusint'] = -2; // def // determine status - this is now done in tidy_quote if (isset($quote['status'])) $resArr['statusint'] = $quote['status']; if ($resArr['statusint'] == -2){ #} is published $resArr['status'] = '<span class="ui label orange">'.__('Not accepted yet',"zero-bs-crm").'</span>'; } else if ($resArr['statusint'] == -1){ #} not yet published $resArr['status'] = '<span class="ui label grey">'.__('Draft',"zero-bs-crm").'</span>'; } else { #} Accepted $resArr['status'] = '<span class="ui label green">'.__('Accepted',"zero-bs-crm").' ' . date(zeroBSCRM_getDateFormat(),$quote['accepted']) . '</span>'; } #} customer if (in_array('customer', $columnsRequired)){ #} Convert $contact arr into list-view-digestable 'customer'// & unset contact for leaner data transfer $resArr['customer'] = zeroBSCRM_getSimplyFormattedContact($quote['contact'],(in_array('assignedobj', $columnsRequired))); #} Convert $contact arr into list-view-digestable 'customer'// & unset contact for leaner data transfer // not yet. $resArr['company'] = zeroBSCRM_getSimplyFormattedCompany($transaction['company'],(in_array('assignedobj', $columnsRequired))); } // let it use proper obj. //$resArr['added'] = $quote['created_date']; // prev was 'val' $resArr['value'] = zeroBSCRM_formatCurrency($resArr['value']); return $resArr; } return false; } // =========== / QUOTE ======================================================= // =============================================================================== } // / class
projects/plugins/crm/includes/ZeroBSCRM.Jetpack.php
<?php // phpcs:ignore WordPress.Files.FileName.NotHyphenatedLowercase /** * Jetpack CRM * https://jetpackcrm.com * V1.20 * * Date: 24th January 2020 * * This file will house any functionality related to Jetpack */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) { exit; } /* ====================================================== / Breaking Checks ====================================================== */ /** * * JETPACK CONTACT FORM CAPTURE => Jetpack CRM * * This intercepts the jetpack form submission. Capturing the lead in Jetpack CRM. * This is the only action that appears to pass the field values in $all_values and * oddly named $extra_values which are contact form fields not in all values * so... all values is "almost all values :-)" */ add_action( 'grunion_after_feedback_post_inserted', 'zero_bs_crm_capture_jetpack_form', 10, 4 ); /** * Creates a ZBS contact from a Jetpack form submission. * * @param integer $post_id The post id that contains the contact form data. * @param array $all_field_data An array containg the form's Grunion_Contact_Form_Field objects. * @param bool $is_spam Whether the form submission has been identified as spam. * @param array $entry_values The feedback entry values. */ function zero_bs_crm_capture_jetpack_form( $post_id, $all_field_data, $is_spam, $entry_values ) { global $zbs; if ( $is_spam || ! is_array( $all_field_data ) || empty( $all_field_data ) ) { return; } $first_field = reset( $all_field_data ); if ( isset( $first_field->form->attributes['jetpackCRM'] ) && ! $first_field->form->attributes['jetpackCRM'] ) { // The Jetpack contact form CRM integration toggle is set to off, so bail. return; } $contact_data = array(); /* * These keys are used by ZBS internally. Don't allow users to set them * using form fields. */ $restricted_keys = array( 'externalSources', 'companies', 'lastcontacted', 'created', 'aliases', ); /* * Try to process the fields using user-specified 'jetpackcrm-' ids. * This is the ideal situation: the user has specified ids with * a 'jetpackcrm-' prefix for each form field, so the fields should map * directly to the CRM contact fields. */ $jpcrm_field_prefix = 'jetpackcrm-'; foreach ( (array) $all_field_data as $field_data ) { $field_id = $field_data->get_attribute( 'id' ); if ( str_starts_with( $field_id, $jpcrm_field_prefix ) && isset( $field_data->value ) && $field_data->value !== '' ) { $data_key = substr( $field_id, strlen( $jpcrm_field_prefix ) ); if ( ! in_array( $data_key, $restricted_keys, true ) ) { if ( $data_key === 'tags' ) { if ( is_array( $field_data->value ) ) { $contact_data[ $data_key ] = $field_data->value; } else { $contact_data[ $data_key ] = explode( ',', $field_data->value ); } } elseif ( $field_data->get_attribute( 'type' ) === 'date' ) { $contact_data[ $data_key ] = jpcrm_date_str_wp_format_to_uts( $field_data->value, true ); } else { $contact_data[ $data_key ] = $field_data->value; } } } } if ( empty( $contact_data['email'] ) ) { /* * If the field ids aren't prefixed with 'jetpackcrm-', try to get an * email, phone, and name using the field types. */ foreach ( (array) $all_field_data as $field_data ) { if ( 'email' === $field_data->get_attribute( 'type' ) && ! isset( $contact_data['email'] ) && ! empty( $field_data->value ) ) { // Use the first email field that's found. $contact_data['email'] = $field_data->value; } if ( 'telephone' === $field_data->get_attribute( 'type' ) && ! isset( $contact_data['hometel'] ) && ! empty( $field_data->value ) ) { // Use the first phone field that's found. $contact_data['hometel'] = $field_data->value; } if ( 'name' === $field_data->get_attribute( 'type' ) && ! isset( $contact_data['fname'] ) && ! empty( $field_data->value ) ) { // Use the first name field that's found. $name = explode( ' ', $field_data->value, 2 ); $contact_data['fname'] = $name[0]; if ( ! empty( $name[1] ) ) { $contact_data['lname'] = $name[1]; } } } } // If we couldn't find an email, bail. if ( empty( $contact_data['email'] ) ) { return; } // Add the external source. $contact_data['externalSources'] = array( array( 'source' => 'jetpack_form', 'origin' => $zbs->DAL->add_origin_prefix( site_url(), 'domain' ), // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase 'uid' => $contact_data['email'], ), ); /* * Get the form entry info for extra meta. */ $entry_title = isset( $entry_values['entry_title'] ) ? $entry_values['entry_title'] : null; $entry_permalink = isset( $entry_values['entry_permalink'] ) ? $entry_values['entry_permalink'] : null; $feedback_id = isset( $entry_values['feedback_id'] ) ? $entry_values['feedback_id'] : null; $extra_meta = array( 'jp_form_entry_title' => $entry_title, 'jp_form_entry_permalink' => $entry_permalink, 'jp_form_feedback_id' => $feedback_id, ); $new_user_form_source_short = 'Created from Jetpack Form <i class="fa fa-wpforms"></i>'; $new_user_form_source_long = 'User created from the form <span class="zbsEmphasis">' . $entry_title . '</span>,' . ' on page: <span class="zbsEmphasis">' . $entry_permalink . '</span>'; $success_log = array( 'note_override' => array( 'type' => 'Form Filled', 'shortdesc' => $new_user_form_source_short, 'longdesc' => $new_user_form_source_long, ), ); $existing_user_form_source_short = 'User completed Jetpack form <i class="fa fa-wpforms"></i>'; $existing_user_form_source_long = 'Form <span class="zbsEmphasis">' . $entry_title . '</span>,' . ' which was filled out from the page: <span class="zbsEmphasis">' . $entry_permalink . '</span>'; $exists_log = array( 'type' => 'Form Filled', 'shortdesc' => $existing_user_form_source_short, 'longdesc' => $existing_user_form_source_long, ); //phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase $zbs->DAL->contacts->addUpdateContact( array( 'data' => $contact_data, 'automatorPassthrough' => $success_log, 'fallBackLog' => $exists_log, 'extraMeta' => $extra_meta, ) ); }
projects/plugins/crm/includes/ZeroBSCRM.REST.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V2.94+ * * Copyright 2020 Automattic * * Date: 31/08/2018 */ /** * This is really the way we should be doing anything AJAX'y in the CORE * It's more stable and better than admin-ajax.php * */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== Admin WP REST API ====================================================== */ /** * urls become get_rest_url() . /zbscrm/v1/companies/ * urls become get_rest_url() . /zbscrm/v1/contacts/ */ /* For developers making manual Ajax requests, the nonce will need to be passed with each request. The API uses nonces with the action set to wp_rest. These can then be passed to the API via the _wpnonce data parameter (either POST data or in the query for GET requests), or via the X-WP-Nonce header. If no nonce is provided the API will set the current user to 0, turning the request into an unauthenticated request, even if you’re logged into WordPress. http://v2.wp-api.org/extending/adding/#permissions-callback */ add_action( 'rest_api_init', function () { #} sites come with this enabled (but require non-plain permalinks) register_rest_route( 'zbscrm/v1', '/companies/', array( 'methods' => 'GET', 'callback' => 'zeroBSCRM_rest_getCompanies', 'args' => array( /* not implemented? wh, see http://v2.wp-api.org/extending/adding/ arguments 'id' => array( 'validate_callback' => 'is_numeric' ), */ ), 'permission_callback' => function () { return zeroBSCRM_permsCustomers(); //permissions. } ) ); register_rest_route( 'zbscrm/v1', '/contacts/', array( 'methods' => 'GET', 'callback' => 'zeroBSCRM_rest_getContacts', 'args' => array( /*'id' => array( 'validate_callback' => 'is_numeric' ),*/ ), 'permission_callback' => function () { return zeroBSCRM_permsCustomers(); //permissions. } ) ); #}additional here for v3.0 type-ahead. Used to get both companies AND contacts the array will hold #} ID, email, object_id #} concom = con[tact]com[pany] register_rest_route( 'zbscrm/v1', '/concom/', array( 'methods' => 'POST, GET', 'callback' => 'zeroBSCRM_rest_getConCom', 'args' => array( /*'id' => array( 'validate_callback' => 'is_numeric' ),*/ ), 'permission_callback' => function () { return zeroBSCRM_permsCustomers(); //permissions. } ) ); /** * Feature flag to conditionally load in development API. * * @ignore * @since 6.1.0 * * @param bool Determine if we should initialize the new REST APIs. */ if ( apply_filters( 'jetpack_crm_feature_flag_api_v4', false ) ) { $controller = new Automattic\Jetpack\CRM\REST_API\V4\REST_Contacts_Controller(); $controller->register_routes(); $automation_controller = new Automattic\Jetpack\CRM\REST_API\V4\REST_Automation_Workflows_Controller(); $automation_controller->register_routes(); } }); //the callbacks (for the above URLS - restricted by the permission_callback above). function zeroBSCRM_rest_getCompanies(WP_REST_Request $request){ // as per http://v2.wp-api.org/extending/adding/ (argument section): $searchQuery = ''; if (isset($request['s'])) $searchQuery = sanitize_text_field( $request['s'] ); $potentialID = -1; if (isset($request['id'])) $potentialID = (int)sanitize_text_field( $request['id'] ); // if id, pass back obj singular if ($potentialID > 0) return zeroBS_getCompany($potentialID); $ret = array(); // $ret = zeroBS_getCompanies(true,100000,0); $ret = zeroBS_getCompaniesForTypeahead($searchQuery); // limitless simplified query (for now) $retA = array(); foreach ($ret as $r){ if (isset($r['name']) && $r['name'] !== 'Auto Draft') $retA[] = $r; } $ret = $retA; unset($retA); return $ret; } function zeroBSCRM_rest_getContacts(WP_REST_Request $request){ global $zbs; // as per http://v2.wp-api.org/extending/adding/ (argument section): $searchQuery = ''; if (isset($request['s'])) $searchQuery = sanitize_text_field( $request['s'] ); $potentialID = -1; if (isset($request['id'])) $potentialID = (int)sanitize_text_field( $request['id'] ); // if id, pass back obj singular if ($potentialID > 0) return zeroBS_getCustomer($potentialID); /* WH temp rewrite. This shouldn't really be autocaching 100k contacts... but for now, at least get via LEAN SQL, if DAL3+ */ if ($zbs->isDAL3()){ // DAL3: // Contacts $retA = $zbs->DAL->contacts->getContacts(array( 'simplified' => true, 'searchPhrase' => $searchQuery )); // quickly cycle through + add obj_type + name/email ... inefficient /* not req here if (is_array($retA) && count($retA) > 0) for ($i = 0; $i < count($retA); $i++){ $retA[$i]['name_email'] = $retA[$i]['email'].' '.$retA[$i]['name']; $retA[$i]['obj_type'] = 1; } else $retA = array(); */ } else { // pre DAL3 $ret = zeroBS_getCustomers(true,100000,0,false,false,$searchQuery,false,false,false); $retA = array(); foreach ($ret as $r){ if (isset($r['name']) && $r['name'] !== 'Auto Draft') $retA[] = $r; } } return $retA; } function zeroBSCRM_rest_getConCom(WP_REST_Request $request){ global $zbs; // as per http://v2.wp-api.org/extending/adding/ (argument section): $searchQuery = ''; if (isset($request['s'])) $searchQuery = sanitize_text_field( $request['s'] ); $potentialID = -1; if (isset($request['id'])) $potentialID = (int)sanitize_text_field( $request['id'] ); $objectType = -1; if (isset($request['obj_type'])) $potentialID = (int)sanitize_text_field( $request['obj_type'] ); // if id, pass back obj simpler, but now also take in objectType too. if ($potentialID > 0 && $objectType == ZBS_TYPE_CONTACT) return zeroBS_getCustomer($potentialID); if ($potentialID > 0 && $objectType == ZBS_TYPE_COMPANY) return zeroBS_getCompany($potentialID); // ultimate return $retA = array(); /* WH temp rewrite. This shouldn't really be autocaching 100k contacts... but for now, at least get via LEAN SQL, if DAL3+ */ if ($zbs->isDAL3()){ // DAL3: // Contacts $retA = $zbs->DAL->contacts->getContacts(array( 'simplified' => true, 'searchPhrase' => $searchQuery, 'sortByField' => 'ID', 'sortOrder' => 'DESC', 'page' => 0, 'perPage' => 300, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT) )); // quickly cycle through + add obj_type + name/email ... inefficient if (is_array($retA) && count($retA) > 0) for ($i = 0; $i < count($retA); $i++){ $retA[$i]['name_email'] = $retA[$i]['email'].' '.$retA[$i]['name']; $retA[$i]['obj_type'] = 1; } else $retA = array(); // Companies $retB = array(); $retB = $zbs->DAL->companies->getCompanies(array( 'simplified' => true, 'searchPhrase' => $searchQuery, 'sortByField' => 'ID', 'sortOrder' => 'DESC', 'page' => 0, 'perPage' => 300, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_COMPANY) )); // quickly cycle through + add obj_type + name/email ... inefficient if (is_array($retB) && count($retB) > 0) for ($i = 0; $i < count($retB); $i++){ $retB[$i]['name_email'] = $retB[$i]['email'].' '.$retB[$i]['name']; $retB[$i]['obj_type'] = 2; } $retA = array_merge($retA,$retB); unset($retB); } else { // pre DAL3 #} FYI - we have a limit here of 100k contacts (even though we say no limits in the sales material) $ret = zeroBS_getCustomers(true,100000,0,false,false,$searchQuery,false,false,false); //first get 100k contacts ans put them into an array if (is_array($ret)) foreach ($ret as $r){ if (isset($r['name']) && $r['name'] !== 'Auto Draft'){ $t['name'] = $r['name']; $t['email'] = $r['email']; $t['name_email'] = $r['email'] . " " . $r['name']; $t['id'] = $r['id']; $t['obj_type'] = 1; $retA[] = $t; } } $b2bMode = zeroBSCRM_getSetting('companylevelcustomers'); if ( $b2bMode == 1 ){ $ret = zeroBS_getCompaniesForTypeahead($searchQuery); // limitless simplified query (for now) if (is_array($ret)) foreach ($ret as $r){ if (isset($r['name']) && $r['name'] !== 'Auto Draft'){ $r['name_email'] = $r['email'] . " " . $r['name']; $r['obj_type'] = 2; $retA[] = $r; } } } // incase its huge, take outa memory unset($ret); } // / <DAL3 return $retA; }
projects/plugins/crm/includes/ZeroBSCRM.DAL3.Obj.QuoteTemplates.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V3.0+ * * Copyright 2020 Automattic * * Date: 14/01/19 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /** * ZBS DAL >> Quote Templates * * @author Woody Hayday <hello@jetpackcrm.com> * @version 2.0 * @access public * @see https://jetpackcrm.com/kb */ class zbsDAL_quotetemplates extends zbsDAL_ObjectLayer { protected $objectType = ZBS_TYPE_QUOTETEMPLATE; protected $objectDBPrefix = 'zbsqt_'; protected $objectModel = array( // ID 'ID' => array('fieldname' => 'ID', 'format' => 'int'), // site + team generics 'zbs_site' => array('fieldname' => 'zbs_site', 'format' => 'int'), 'zbs_team' => array('fieldname' => 'zbs_team', 'format' => 'int'), 'zbs_owner' => array('fieldname' => 'zbs_owner', 'format' => 'int'), // other fields 'title' => array( 'fieldname' => 'zbsqt_title', 'format' => 'str', 'max_len' => 255 ), 'value' => array('fieldname' => 'zbsqt_value', 'format' => 'decimal'), 'date_str' => array('fieldname' => 'zbsqt_date_str', 'format' => 'str'), 'date' => array('fieldname' => 'zbsqt_date', 'format' => 'uts'), 'content' => array('fieldname' => 'zbsqt_content', 'format' => 'str'), 'notes' => array('fieldname' => 'zbsqt_notes', 'format' => 'str'), 'currency' => array( 'fieldname' => 'zbsqt_currency', 'format' => 'curr', 'max_len' => 4 ), 'created' => array('fieldname' => 'zbsqt_created', 'format' => 'uts'), 'lastupdated' => array('fieldname' => 'zbsqt_lastupdated', 'format' => 'uts'), ); function __construct($args=array()) { #} =========== LOAD ARGS ============== $defaultArgs = array( //'tag' => false, ); foreach ($defaultArgs as $argK => $argV){ $this->$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $this->$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$this->$argK = $newData;} else { $this->$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= } // =============================================================================== // =========== QUOTETEMPLATE ======================================================= // generic get Company (by ID) // Super simplistic wrapper used by edit page etc. (generically called via dal->contacts->getSingle etc.) public function getSingle($ID=-1){ return $this->getQuotetemplate($ID); } /** * returns full quotetemplate line +- details * * @param int id quotetemplate id * @param array $args Associative array of arguments * * @return array quotetemplate object */ public function getQuotetemplate($id=-1,$args=array()){ global $zbs; #} =========== LOAD ARGS ============== $defaultArgs = array( // with what? 'withOwner' => false, // permissions 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_QUOTETEMPLATE), // this'll let you not-check the owner of obj // returns scalar ID of line 'onlyID' => false, 'fields' => false // false = *, array = fieldnames ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} Check ID $id = (int)$id; if ( (!empty($id) && $id > 0) || (!empty($email)) || (!empty($externalSource) && !empty($externalSourceUID)) ){ global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); $extraSelect = ''; #} ============= PRE-QUERY ============ $selector = 'quotetemplate.*'; if (isset($fields) && is_array($fields)) { $selector = ''; // always needs id, so add if not present if (!in_array('ID',$fields)) $selector = 'quotetemplate.ID'; foreach ($fields as $f) { if (!empty($selector)) $selector .= ','; $selector .= 'quotetemplate.'.$f; } } else if ($onlyID){ $selector = 'quotetemplate.ID'; } #} ============ / PRE-QUERY =========== #} Build query $query = "SELECT ".$selector.$extraSelect." FROM ".$ZBSCRM_t['quotetemplates'].' as quotetemplate'; #} ============= WHERE ================ if (!empty($id) && $id > 0){ #} Add ID $wheres['ID'] = array('ID','=','%d',$id); } #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner,'quotetemplate'); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort('ID','DESC') . $this->buildPaging(0,1); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_row($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret Results (ROW) if (isset($potentialRes) && isset($potentialRes->ID)) { #} Has results, tidy + return #} Only ID? return it directly if ($onlyID) return $potentialRes->ID; // tidy if (is_array($fields)){ // guesses fields based on table col names $res = $this->lazyTidyGeneric($potentialRes); } else { // proper tidy $res = $this->tidy_quotetemplate($potentialRes,false); } /*if ($withTags){ // add all tags lines $res['tags'] = $this->DAL()->getTagsForObjID(array('objtypeid'=>ZBS_TYPE_QUOTETEMPLATE,'objid'=>$potentialRes->ID)); }*/ return $res; } } // / if ID return false; } /** * returns quotetemplate detail lines * * @param array $args Associative array of arguments * * @return array of quotetemplate lines */ public function getQuotetemplates($args=array()){ global $zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( // Search/Filtering (leave as false to ignore) 'searchPhrase' => '', // searches which fields? 'inArr' => false, //'isTagged' => false, // 1x INT OR array(1,2,3) //'isNotTagged' => false, // 1x INT OR array(1,2,3) 'ownedBy' => false, 'olderThan' => false, // uts 'newerThan' => false, // uts //'hasStatus' => false, // Lead (this takes over from the quick filter post 19/6/18) //'otherStatus' => false, // status other than 'Lead' // returns 'count' => false, 'withOwner' => false, 'checkDefaults' => false, // if true returns 'default' value too (is one of our defaults) 'sortByField' => 'ID', 'sortOrder' => 'ASC', 'page' => 0, // this is what page it is (gets * by for limit) 'perPage' => 100, 'whereCase' => 'AND', // DEFAULT = AND // permissions 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_QUOTETEMPLATE), // this'll let you not-check the owner of obj - GLOBAL FOR NOW ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= global $ZBSCRM_t,$wpdb,$zbs; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); $joinQ = ''; $extraSelect = ''; #} ============= PRE-QUERY ============ #} Capitalise this $sortOrder = strtoupper($sortOrder); #} If just count, turn off any extra gumpf if ($count) { $withOwner = false; } #} ============ / PRE-QUERY =========== #} Build query $query = "SELECT quotetemplate.*".$extraSelect." FROM ".$ZBSCRM_t['quotetemplates'].' as quotetemplate'.$joinQ; #} Count override if ($count) $query = "SELECT COUNT(quotetemplate.ID) FROM ".$ZBSCRM_t['quotetemplates'].' as quotetemplate'.$joinQ; #} ============= WHERE ================ #} Add Search phrase if (!empty($searchPhrase)){ // search? - ALL THESE COLS should probs have index of FULLTEXT in db? $searchWheres = array(); $searchWheres['search_title'] = array('zbsqt_title','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_content'] = array('zbsqt_content','LIKE','%s','%'.$searchPhrase.'%'); // This generates a query like 'zbsqt_fname LIKE %s OR zbsqt_lname LIKE %s', // which we then need to include as direct subquery (below) in main query :) $searchQueryArr = $this->buildWheres($searchWheres,'',array(),'OR',false); if (is_array($searchQueryArr) && isset($searchQueryArr['where']) && !empty($searchQueryArr['where'])){ // add it $wheres['direct'][] = array('('.$searchQueryArr['where'].')',$searchQueryArr['params']); } } #} In array (if inCompany passed, this'll currently overwrite that?! (todo2.5)) if (is_array($inArr) && count($inArr) > 0){ // clean for ints $inArrChecked = array(); foreach ($inArr as $x){ $inArrChecked[] = (int)$x; } // add where $wheres['inarray'] = array('ID','IN','('.implode(',',$inArrChecked).')'); } #} Owned by if (!empty($ownedBy) && $ownedBy > 0){ // would never hard-type this in (would make generic as in buildWPMetaQueryWhere) // but this is only here until MIGRATED to db2 globally //$wheres['incompany'] = array('ID','IN','(SELECT DISTINCT post_id FROM '.$wpdb->prefix."postmeta WHERE meta_key = 'zbs_company' AND meta_value = %d)",$inCompany); // Use obj links now $wheres['ownedBy'] = array('zbs_owner','=','%s',$ownedBy); } // quick addition for mike #} olderThan if (!empty($olderThan) && $olderThan > 0 && $olderThan !== false) $wheres['olderThan'] = array('zbsqt_created','<=','%d',$olderThan); #} newerThan if (!empty($newerThan) && $newerThan > 0 && $newerThan !== false) $wheres['newerThan'] = array('zbsqt_created','>=','%d',$newerThan); // status //if (!empty($hasStatus) && $hasStatus !== false) $wheres['hasStatus'] = array('XXXX_status','=','%s',$hasStatus); //if (!empty($otherStatus) && $otherStatus !== false) $wheres['otherStatus'] = array('XXXX_status','<>','%s',$otherStatus); #} Any additionalWhereArr? if (isset($additionalWhereArr) && is_array($additionalWhereArr) && count($additionalWhereArr) > 0){ // add em onto wheres (note these will OVERRIDE if using a key used above) // Needs to be multi-dimensional $wheres = array_merge($wheres,$additionalWhereArr); $wheres = array_merge_recursive($wheres,$additionalWhereArr); } #} Is Tagged (expects 1 tag ID OR array) /* // catch 1 item arr if (is_array($isTagged) && count($isTagged) == 1) $isTagged = $isTagged[0]; if (!is_array($isTagged) && !empty($isTagged) && $isTagged > 0){ // add where tagged // 1 int: $wheres['direct'][] = array('((SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = quotetemplate.ID AND zbstl_tagid = %d) > 0)',array(ZBS_TYPE_QUOTETEMPLATE,$isTagged)); } else if (is_array($isTagged) && count($isTagged) > 0){ // foreach in array :) $tagStr = ''; foreach ($isTagged as $iTag){ $i = (int)$iTag; if ($i > 0){ if ($tagStr !== '') $tagStr .','; $tagStr .= $i; } } if (!empty($tagStr)){ $wheres['direct'][] = array('((SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = quotetemplate.ID AND zbstl_tagid IN (%s)) > 0)',array(ZBS_TYPE_QUOTETEMPLATE,$tagStr)); } } #} Is NOT Tagged (expects 1 tag ID OR array) // catch 1 item arr if (is_array($isNotTagged) && count($isNotTagged) == 1) $isNotTagged = $isNotTagged[0]; if (!is_array($isNotTagged) && !empty($isNotTagged) && $isNotTagged > 0){ // add where tagged // 1 int: $wheres['direct'][] = array('((SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = quotetemplate.ID AND zbstl_tagid = %d) = 0)',array(ZBS_TYPE_QUOTETEMPLATE,$isNotTagged)); } else if (is_array($isNotTagged) && count($isNotTagged) > 0){ // foreach in array :) $tagStr = ''; foreach ($isNotTagged as $iTag){ $i = (int)$iTag; if ($i > 0){ if ($tagStr !== '') $tagStr .','; $tagStr .= $i; } } if (!empty($tagStr)){ $wheres['direct'][] = array('((SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = quotetemplate.ID AND zbstl_tagid IN (%s)) = 0)',array(ZBS_TYPE_QUOTETEMPLATE,$tagStr)); } } */ #} ============ / WHERE =============== #} CHECK this + reset to default if faulty if (!in_array($whereCase,array('AND','OR'))) $whereCase = 'AND'; #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params,$whereCase); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner,'quotetemplate'); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort($sortByField,$sortOrder) . $this->buildPaging($page,$perPage); try { #} Prep & run query $queryObj = $this->prepare($query,$params); #} Catch count + return if requested if ($count) return $wpdb->get_var($queryObj); #} else continue.. $potentialRes = $wpdb->get_results($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret results (Result Set - multi-row) if (isset($potentialRes) && is_array($potentialRes) && count($potentialRes) > 0) { #} Has results, tidy + return foreach ($potentialRes as $resDataLine) { // tidy $resArr = $this->tidy_quotetemplate($resDataLine); //withCustomFields // here we also grab this meta to see if is default if ($checkDefaults) $resArr['default'] = $this->DAL()->meta(ZBS_TYPE_QUOTETEMPLATE,$resDataLine->ID,'zbsdefault',false); /*if ($withTags){ // add all tags lines $resArr['tags'] = $this->DAL()->getTagsForObjID(array('objtypeid'=>ZBS_TYPE_QUOTETEMPLATE,'objid'=>$resDataLine->ID)); }*/ $res[] = $resArr; } } return $res; } /** * Returns a count of contacts (owned) * Replaces zeroBS_customerCount AND zeroBS_getCustomerCount AND zeroBS_customerCountByStatus * * * @return int count */ public function getQuotetemplateCount($args=array()){ #} ============ LOAD ARGS ============= $defaultArgs = array( // Search/Filtering (leave as false to ignore) // permissions 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_QUOTETEMPLATE), // this'll let you not-check the owner of obj ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= $whereArr = array(); //if ($withStatus !== false && !empty($withStatus)) $whereArr['status'] = array('zbsqt_status','=','%s',$withStatus); return $this->DAL()->getFieldByWHERE(array( 'objtype' => ZBS_TYPE_QUOTETEMPLATE, 'colname' => 'COUNT(ID)', 'where' => $whereArr, 'ignoreowner' => $ignoreowner)); return 0; } /** * adds or updates a quotetemplate object * * @param array $args Associative array of arguments * id (if update), owner, data (array of field data) * * @return int line ID */ public function addUpdateQuotetemplate($args=array()){ global $ZBSCRM_t,$wpdb,$zbs; #} Retrieve any cf //$customFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_QUOTETEMPLATE)); #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'owner' => -1, // fields (directly) 'data' => array( 'title' => '', 'value' => '', 'date_str' => '', 'date' => '', 'content' => '', 'notes' => '', 'currency' => '', // Note Custom fields may be passed here, but will not have defaults so check isset() // allow this to be set for MS sync etc. 'created' => -1, 'lastupdated' => '', ), 'limitedFields' => -1, // if this is set it OVERRIDES data (allowing you to set specific fields + leave rest in tact) // ^^ will look like: array(array('key'=>x,'val'=>y,'type'=>'%s')) // this function as DAL1 func did. 'extraMeta' => -1, 'automatorPassthrough' => -1, 'fallBackLog' => -1, 'silentInsert' => false, // this was for init Migration - it KILLS all IA for newQuotetemplate (because is migrating, not creating new :) this was -1 before 'do_not_update_blanks' => false // this allows you to not update fields if blank (same as fieldoverride for extsource -> in) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ $id = (int)$id; // here we check that the potential owner CAN even own if ($owner > 0 && !user_can($owner,'admin_zerobs_usr')) $owner = -1; // if owner = -1, add current if (!isset($owner) || $owner === -1) { $owner = zeroBSCRM_user(); } if (is_array($limitedFields)){ // LIMITED UPDATE (only a few fields.) if (!is_array($limitedFields) || count ($limitedFields) <= 0) return false; // REQ. ID too (can only update) if (empty($id) || $id <= 0) return false; } else { // NORMAL, FULL UPDATE } #} ========= / CHECK FIELDS =========== #} ========= OVERRIDE SETTING (Deny blank overrides) =========== // either ext source + setting, or set by the func call if ($do_not_update_blanks){ // this setting says 'don't override filled-out data with blanks' // so here we check through any passed blanks + convert to limitedFields // only matters if $id is set (there is somt to update not add if (isset($id) && !empty($id) && $id > 0){ // get data to copy over (for now, this is required to remove 'fullname' etc.) $dbData = $this->db_ready_quotetemplate($data); //unset($dbData['id']); // this is unset because we use $id, and is update, so not req. legacy issue //unset($dbData['created']); // this is unset because this uses an obj which has been 'updated' against original details, where created is output in the WRONG format :) $origData = $data; //$data = array(); $limitedData = array(); // array(array('key'=>'zbsqt_x','val'=>y,'type'=>'%s')) // cycle through + translate into limitedFields (removing any blanks, or arrays (e.g. externalSources)) // we also have to remake a 'faux' data (removing blanks for tags etc.) for the post-update updates foreach ($dbData as $k => $v){ $intV = (int)$v; // only add if valuenot empty if (!is_array($v) && !empty($v) && $v != '' && $v !== 0 && $v !== -1 && $intV !== -1){ // add to update arr $limitedData[] = array( 'key' => 'zbsqt_'.$k, // we have to add zbsqt_ here because translating from data -> limited fields 'val' => $v, 'type' => $this->getTypeStr('zbsqt_'.$k) ); // add to remade $data for post-update updates $data[$k] = $v; } } // copy over $limitedFields = $limitedData; } // / if ID } // / if do_not_update_blanks #} ========= / OVERRIDE SETTING (Deny blank overrides) =========== #} ========= BUILD DATA =========== $update = false; $dataArr = array(); $typeArr = array(); if (is_array($limitedFields)){ // LIMITED FIELDS $update = true; // cycle through foreach ($limitedFields as $field){ // some weird case where getting empties, so added check if (!empty($field['key'])){ $dataArr[$field['key']] = $field['val']; $typeArr[] = $field['type']; } } // add update time if (!isset($dataArr['zbsqt_lastupdated'])){ $dataArr['zbsqt_lastupdated'] = time(); $typeArr[] = '%d'; } } else { // FULL UPDATE/INSERT // UPDATE $dataArr = array( // ownership // no need to update these (as of yet) - can't move teams etc. //'zbs_site' => zeroBSCRM_installSite(), //'zbs_team' => zeroBSCRM_installTeam(), //'zbs_owner' => $owner, 'zbsqt_title' => $data['title'], 'zbsqt_value' => $data['value'], 'zbsqt_date_str' => $data['date_str'], 'zbsqt_date' => $data['date'], 'zbsqt_content' => $data['content'], 'zbsqt_notes' => $data['notes'], 'zbsqt_currency' => $data['currency'], 'zbsqt_lastupdated' => time(), ); $typeArr = array( // field data types //'%d', // site //'%d', // team //'%d', // owner '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%d', ); if (!empty($id) && $id > 0){ // is update $update = true; } else { // INSERT (get's few extra :D) $update = false; $dataArr['zbs_site'] = zeroBSCRM_site(); $typeArr[] = '%d'; $dataArr['zbs_team'] = zeroBSCRM_team(); $typeArr[] = '%d'; $dataArr['zbs_owner'] = $owner; $typeArr[] = '%d'; if (isset($data['created']) && !empty($data['created']) && $data['created'] !== -1){ $dataArr['zbsqt_created'] = $data['created'];$typeArr[] = '%d'; } else { $dataArr['zbsqt_created'] = time(); $typeArr[] = '%d'; } } } #} ========= / BUILD DATA =========== #} ============================================================ #} ========= CHECK force_uniques & not_empty & max_len ======== // if we're passing limitedFields we skip these, for now // #v3.1 - would make sense to unique/nonempty check just the limited fields. #gh-145 if (!is_array($limitedFields)){ // verify uniques if (!$this->verifyUniqueValues($data,$id)) return false; // / fails unique field verify // verify not_empty if (!$this->verifyNonEmptyValues($data)) return false; // / fails empty field verify } // whatever we do we check for max_len breaches and abbreviate to avoid wpdb rejections $dataArr = $this->wpdbChecks($dataArr); #} ========= / CHECK force_uniques & not_empty ================ #} ============================================================ #} Check if ID present if ($update){ #} Attempt update if ($wpdb->update( $ZBSCRM_t['quotetemplates'], $dataArr, array( // where 'ID' => $id ), $typeArr, array( // where data types '%d' )) !== false){ // if passing limitedFields instead of data, we ignore the following // this doesn't work, because data is in args default as arr //if (isset($data) && is_array($data)){ // so... if (!isset($limitedFields) || !is_array($limitedFields) || $limitedFields == -1){ /* // tag work? if (isset($data['tags']) && is_array($data['tags'])) $this->addUpdateQuotetemplateTags(array('id'=>$id,'tagIDs'=>$data['tags'])); // Custom fields? #} Cycle through + add/update if set if (is_array($customFields)) foreach ($customFields as $cK => $cF){ // any? if (isset($data[$cK])){ // add update $cfID = $this->DAL()->addUpdateCustomField(array( 'data' => array( 'objtype' => ZBS_TYPE_QUOTETEMPLATE, 'objid' => $id, 'objkey' => $cK, 'objval' => $data[$cK] ))); } } // / Custom Fields */ } // / if $data #} Any extra meta keyval pairs? // BRUTALLY updates (no checking) $confirmedExtraMeta = false; if (isset($extraMeta) && is_array($extraMeta)) { $confirmedExtraMeta = array(); foreach ($extraMeta as $k => $v){ #} This won't fix stupid keys, just catch basic fails... $cleanKey = strtolower(str_replace(' ','_',$k)); #} Brutal update //update_post_meta($postID, 'zbs_customer_extra_'.$cleanKey, $v); $this->DAL()->updateMeta(ZBS_TYPE_QUOTETEMPLATE,$id,'extra_'.$cleanKey,$v); #} Add it to this, which passes to IA $confirmedExtraMeta[$cleanKey] = $v; } } #} INTERNAL AUTOMATOR #} & #} FALLBACKS // UPDATING CONTACT if (!$silentInsert){ // IA General quotetemplate update (2.87+) zeroBSCRM_FireInternalAutomator('quotetemplate.update',array( 'id'=>$id, 'againstid' => $id, 'data'=> $dataArr )); } // Successfully updated - Return id return $id; } else { $msg = __('DB Update Failed','zero-bs-crm'); $zbs->DAL->addError(302,$this->objectType,$msg,$dataArr); // FAILED update return false; } } else { #} No ID - must be an INSERT if ($wpdb->insert( $ZBSCRM_t['quotetemplates'], $dataArr, $typeArr ) > 0){ #} Successfully inserted, lets return new ID $newID = $wpdb->insert_id; /* // tag work? if (isset($data['tags']) && is_array($data['tags'])) $this->addUpdateQuotetemplateTags(array('id'=>$newID,'tagIDs'=>$data['tags'])); // Custom fields? #} Cycle through + add/update if set if (is_array($customFields)) foreach ($customFields as $cK => $cF){ // any? if (isset($data[$cK])){ // add update $cfID = $this->DAL()->addUpdateCustomField(array( 'data' => array( 'objtype' => ZBS_TYPE_QUOTETEMPLATE, 'objid' => $newID, 'objkey' => $cK, 'objval' => $data[$cK] ))); } } // / Custom Fields */ #} Any extra meta keyval pairs? // BRUTALLY updates (no checking) $confirmedExtraMeta = false; if (isset($extraMeta) && is_array($extraMeta)) { $confirmedExtraMeta = array(); foreach ($extraMeta as $k => $v){ #} This won't fix stupid keys, just catch basic fails... $cleanKey = strtolower(str_replace(' ','_',$k)); #} Brutal update //update_post_meta($postID, 'zbs_customer_extra_'.$cleanKey, $v); $this->DAL()->updateMeta(ZBS_TYPE_QUOTETEMPLATE,$id,'extra_'.$cleanKey,$v); #} Add it to this, which passes to IA $confirmedExtraMeta[$cleanKey] = $v; } } #} INTERNAL AUTOMATOR #} & #} FALLBACKS // NEW CONTACT if (!$silentInsert){ #} Add to automator zeroBSCRM_FireInternalAutomator('quotetemplate.new',array( 'id'=>$newID, 'data'=>$dataArr, //'extsource'=>array(), 'automatorpassthrough'=>$automatorPassthrough, #} This passes through any custom log titles or whatever into the Internal automator recipe. 'extraMeta'=>$confirmedExtraMeta #} This is the "extraMeta" passed (as saved) )); } return $newID; } else { $msg = __('DB Insert Failed','zero-bs-crm'); $zbs->DAL->addError(303,$this->objectType,$msg,$dataArr); #} Failed to Insert return false; } } return false; } /** * adds or updates a quotetemplate's tags * ... this is really just a wrapper for addUpdateObjectTags * * @param array $args Associative array of arguments * id (if update), owner, data (array of field data) * * @return int line ID */ /* public function addUpdateQuotetemplateTags($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, // EITHER of the following: 'tagIDs' => -1, 'tags' => -1, 'mode' => 'append' ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ // check id $id = (int)$id; if (empty($id) || $id <= 0) return false; #} ========= / CHECK FIELDS =========== return $this->DAL()->addUpdateObjectTags(array( 'objtype' =>ZBS_TYPE_QUOTETEMPLATE, 'objid' =>$id, 'tags' =>$tags, 'tagIDs' =>$tagIDs, 'mode' =>$mode)); } */ /** * deletes a quotetemplate object * * @param array $args Associative array of arguments * id * * @return int success; */ public function deleteQuotetemplate($args=array()){ global $ZBSCRM_t,$wpdb,$zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'saveOrphans' => true ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} Check ID & Delete :) $id = (int)$id; if (!empty($id) && $id > 0) { // delete orphans? if ($saveOrphans === false){ } return zeroBSCRM_db2_deleteGeneric($id,'quotetemplates'); } return false; } /** * tidy's the object from wp db into clean array * * @param array $obj (DB obj) * * @return array quotetemplate (clean obj) */ private function tidy_quotetemplate($obj=false,$withCustomFields=false){ global $zbs; $res = false; if (isset($obj->ID)){ $res = array(); $res['id'] = $obj->ID; /* `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, */ $res['owner'] = $obj->zbs_owner; $res['title'] = wp_kses( html_entity_decode( $obj->zbsqt_title, ENT_QUOTES, 'UTF-8' ), $zbs->acceptable_restricted_html ); $res['value'] = $this->stripSlashes($obj->zbsqt_value); $res['date_str'] = $this->stripSlashes($obj->zbsqt_date_str); $res['date'] = (int)$obj->zbsqt_date; $res['date_date'] = (isset($obj->zbsqt_date) && $obj->zbsqt_date > 0) ? zeroBSCRM_locale_utsToDatetime($obj->zbsqt_date) : false; $res['content'] = $this->stripSlashes($obj->zbsqt_content); $res['notes'] = wp_kses( html_entity_decode( $obj->zbsqt_notes, ENT_QUOTES, 'UTF-8' ), $zbs->acceptable_restricted_html ); $res['currency'] = $this->stripSlashes($obj->zbsqt_currency); $res['created'] = (int)$obj->zbsqt_created; $res['created_date'] = (isset($obj->zbsqt_created) && $obj->zbsqt_created > 0) ? zeroBSCRM_locale_utsToDatetime($obj->zbsqt_created) : false; $res['lastupdated'] = (int)$obj->zbsqt_lastupdated; $res['lastupdated_date'] = (isset($obj->zbsqt_lastupdated) && $obj->zbsqt_lastupdated > 0) ? zeroBSCRM_locale_utsToDatetime($obj->zbsqt_lastupdated) : false; // custom fields - tidy any that are present: if ($withCustomFields) $res = $this->tidyAddCustomFields(ZBS_TYPE_QUOTETEMPLATE,$obj,$res,false); } return $res; } /** * Wrapper, use $this->getQuotetemplateMeta($contactID,$key) for easy retrieval of singular quotetemplate * Simplifies $this->getMeta * * @param int objtype * @param int objid * @param string key * * @return array quotetemplate meta result */ public function getQuotetemplateMeta($id=-1,$key='',$default=false){ global $zbs; if (!empty($key)){ return $this->DAL()->getMeta(array( 'objtype' => ZBS_TYPE_QUOTETEMPLATE, 'objid' => $id, 'key' => $key, 'fullDetails' => false, 'default' => $default, 'ignoreowner' => true // for now !! )); } return $default; } /** * Returns an ownerid against a quotetemplate * * @param int id quotetemplate ID * * @return int quotetemplate owner id */ public function getQuotetemplateOwner($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_QUOTETEMPLATE, 'colname' => 'zbs_owner', 'ignoreowner'=>true)); } return false; } /** * remove any non-db fields from the object * basically takes array like array('owner'=>1,'fname'=>'x','fullname'=>'x') * and returns array like array('owner'=>1,'fname'=>'x') * This does so based on the objectModel! * * @param array $obj (clean obj) * * @return array (db ready arr) */ private function db_ready_quotetemplate($obj=false){ // use the generic? (override here if necessary) return $this->db_ready_obj($obj); } /** * Takes full object and makes a "list view" boiled down version * Used to generate listview objs * * @param array $obj (clean obj) * * @return array (listview ready obj) */ public function listViewObj($quotetemplate=false,$columnsRequired=array()){ if (is_array($quotetemplate) && isset($quotetemplate['id'])){ $resArr = $quotetemplate; return $resArr; } return false; } // =========== / QUOTETEMPLATE ======================================================= // =============================================================================== }
projects/plugins/crm/includes/ZeroBSCRM.Encryption.php
<?php /*! * Jetpack CRM * http://zerobscrm.com * V2.2+ * * Copyright 2020 Automattic * * Date: 12/09/2017 */ /* DEPRECATED - The following should be left in place for migrations to 5.3 Thereafter all encryption should go through class-encryption.php class */ define( 'ZBS_ENCRYPTION_METHOD', "AES-256-CBC" ); // NOTE - NOT GOOD for hard encryption, for now used basically // https://gist.github.com/joashp/a1ae9cb30fa533f4ad94 function zeroBSCRM_encryption_unsafe_process( $action, $string, $key, $iv, $hide_deprecation = false ) { if ( !$hide_deprecation ) zeroBSCRM_DEPRECATEDMSG('CRM Function Deprecated in v5.3: zeroBSCRM_encryption_unsafe_process'); $output = false; $encrypt_method = ZBS_ENCRYPTION_METHOD; // catch cases where IV length is wrong // openssl truncates already, but this catches it before logging $max_iv_length = openssl_cipher_iv_length( ZBS_ENCRYPTION_METHOD ); if ( strlen( $iv ) > $max_iv_length ) { $iv = substr( $iv, $max_iv_length ); } if ( $action == 'encrypt' ) { $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv); } else if( $action == 'decrypt' ) { $output = openssl_decrypt( $string, $encrypt_method, $key, 0, $iv); } return $output; } function zeroBSCRM_get_iv( $hide_deprecation = false ) { if ( !$hide_deprecation ) zeroBSCRM_DEPRECATEDMSG('CRM Function Deprecated in v5.3: zeroBSCRM_get_iv'); static $iv = null; if ( null === $iv ) { $iv = pack( 'C*', ...array_slice( unpack( 'C*', AUTH_KEY ), 0, openssl_cipher_iv_length( ZBS_ENCRYPTION_METHOD ) ) ); } return $iv; } function zeroBSCRM_encrypt( $string, $key, $hide_deprecation = false ){ if ( !$hide_deprecation ) zeroBSCRM_DEPRECATEDMSG('CRM Function Deprecated in v5.3: zeroBSCRM_encrypt'); return zeroBSCRM_encryption_unsafe_process( 'encrypt', $string, $key, zeroBSCRM_get_iv() ); } function zeroBSCRM_decrypt( $string, $key, $hide_deprecation = false ) { if ( !$hide_deprecation ) zeroBSCRM_DEPRECATEDMSG('CRM Function Deprecated in v5.3: zeroBSCRM_decrypt'); return zeroBSCRM_encryption_unsafe_process( 'decrypt', $string, $key, zeroBSCRM_get_iv() ); }
projects/plugins/crm/includes/ZeroBSCRM.Permissions.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V1.20 * * Copyright 2020 Automattic * * Date: 01/11/16 */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) { exit; } /** * Remove user roles */ function zeroBSCRM_clearUserRoles() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid remove_role( 'zerobs_admin' ); remove_role( 'zerobs_customermgr' ); remove_role( 'zerobs_quotemgr' ); remove_role( 'zerobs_invoicemgr' ); remove_role( 'zerobs_transactionmgr' ); remove_role( 'zerobs_customer' ); remove_role( 'zerobs_mailmgr' ); } /** * Build User Roles */ function zeroBSCRM_addUserRoles() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid // Jetpack CRM Admin add_role( 'zerobs_admin', __( 'Jetpack CRM Admin (Full CRM Permissions)', 'zero-bs-crm' ), array( 'read' => true, // true allows this capability 'edit_posts' => false, // Allows user to edit their own posts 'edit_pages' => false, // Allows user to edit pages 'edit_others_posts' => false, // Allows user to edit others posts not just their own 'create_posts' => false, // Allows user to create new posts 'manage_categories' => false, // Allows user to manage post categories 'publish_posts' => false, // Allows the user to publish, otherwise posts stays in draft mode ) ); // gets the role from WP $role = get_role( 'zerobs_admin' ); $role->add_cap( 'read' ); $role->remove_cap( 'edit_posts' ); $role->add_cap( 'upload_files' ); // added 21/5/18 to ensure can upload media $role->add_cap( 'admin_zerobs_usr' ); #} For all zerobs users :) // NOTE. Adding this adds a random "Post categories / not posts" to menu // will have to remove programattically :( $role->add_cap( 'manage_categories' ); $role->add_cap( 'manage_sales_dash' ); #mike added $role->add_cap( 'admin_zerobs_mailcampaigns' ); $role->add_cap( 'zbs_dash' ); # WH added 1.2 - has rights to view ZBS Dash // give permission to edit settings $role->add_cap( 'admin_zerobs_manage_options' ); // CRM object view capabilities $role->add_cap( 'admin_zerobs_view_customers' ); $role->add_cap( 'admin_zerobs_view_quotes' ); $role->add_cap( 'admin_zerobs_view_invoices' ); $role->add_cap( 'admin_zerobs_view_events' ); $role->add_cap( 'admin_zerobs_view_transactions' ); // CRM object edit capabilities $role->add_cap( 'admin_zerobs_customers' ); $role->add_cap( 'admin_zerobs_customers_tags' ); $role->add_cap( 'admin_zerobs_quotes' ); $role->add_cap( 'admin_zerobs_events' ); $role->add_cap( 'admin_zerobs_invoices' ); $role->add_cap( 'admin_zerobs_transactions' ); $role->add_cap( 'admin_zerobs_forms' ); // logs $role->add_cap( 'admin_zerobs_logs_addedit' ); $role->add_cap( 'admin_zerobs_logs_delete' ); // emails $role->add_cap( 'admin_zerobs_sendemails_contacts' ); // paranoia unset( $role ); // give WP admins extra capabilities $role = get_role( 'administrator' ); // this is for users who've removed 'administrator' role type // WH temp catch anyhow, for Nimitz. if ( $role !== null ) { // Caps $role->add_cap( 'manage_sales_dash' ); $role->add_cap( 'admin_zerobs_mailcampaigns' ); $role->add_cap( 'admin_zerobs_forms' ); $role->add_cap( 'zbs_dash' ); # WH added 1.2 - has rights to view ZBS Dash // give permission to edit settings $role->add_cap( 'admin_zerobs_manage_options' ); // CRM object view capabilities $role->add_cap( 'admin_zerobs_view_customers' ); $role->add_cap( 'admin_zerobs_view_quotes' ); $role->add_cap( 'admin_zerobs_view_invoices' ); $role->add_cap( 'admin_zerobs_view_events' ); $role->add_cap( 'admin_zerobs_view_transactions' ); // CRM object edit capabilities $role->add_cap( 'admin_zerobs_customers' ); $role->add_cap( 'admin_zerobs_customers_tags' ); $role->add_cap( 'admin_zerobs_quotes' ); $role->add_cap( 'admin_zerobs_invoices' ); $role->add_cap( 'admin_zerobs_events' ); $role->add_cap( 'admin_zerobs_transactions' ); // needed for notifications $role->add_cap( 'admin_zerobs_notifications' ); // logs $role->add_cap( 'admin_zerobs_logs_addedit' ); $role->add_cap( 'admin_zerobs_logs_delete' ); // all users $role->add_cap( 'admin_zerobs_usr' ); // emails $role->add_cap( 'admin_zerobs_sendemails_contacts' ); // paranoia unset( $role ); } // CRM Contact Manager add_role( 'zerobs_customermgr', __( 'Jetpack CRM Contact Manager', 'zero-bs-crm' ), array( 'read' => true, // true allows this capability 'edit_posts' => false, // Allows user to edit their own posts 'edit_pages' => false, // Allows user to edit pages 'edit_others_posts' => false, // Allows user to edit others posts not just their own 'create_posts' => false, // Allows user to create new posts 'manage_categories' => false, // Allows user to manage post categories 'publish_posts' => false, // Allows the user to publish, otherwise posts stays in draft mode ) ); // gets the role from WP $role = get_role( 'zerobs_customermgr' ); // caps $role->add_cap( 'read' ); $role->remove_cap( 'edit_posts' ); $role->add_cap( 'upload_files' ); // added 21/5/18 to ensure can upload media $role->add_cap( 'admin_zerobs_usr' ); #} For all zerobs users :) $role->add_cap( 'manage_categories' ); $role->add_cap( 'zbs_dash' ); # WH added 1.2 - has rights to view ZBS Dash // CRM object view capabilities $role->add_cap( 'admin_zerobs_view_customers' ); $role->add_cap( 'admin_zerobs_view_quotes' ); $role->add_cap( 'admin_zerobs_view_invoices' ); $role->add_cap( 'admin_zerobs_view_events' ); $role->add_cap( 'admin_zerobs_view_transactions' ); // CRM object edit capabilities $role->add_cap( 'admin_zerobs_customers' ); $role->add_cap( 'admin_zerobs_customers_tags' ); $role->add_cap( 'admin_zerobs_quotes' ); $role->add_cap( 'admin_zerobs_events' ); $role->add_cap( 'admin_zerobs_invoices' ); $role->add_cap( 'admin_zerobs_transactions' ); // needed for notifications $role->add_cap( 'admin_zerobs_notifications' ); // logs $role->add_cap( 'admin_zerobs_logs_addedit' ); // emails $role->add_cap( 'admin_zerobs_sendemails_contacts' ); unset( $role ); // CRM Quote Manager add_role( 'zerobs_quotemgr', __( 'Jetpack CRM Quote Manager', 'zero-bs-crm' ), array( 'read' => true, // true allows this capability 'edit_posts' => false, // Allows user to edit their own posts 'edit_pages' => false, // Allows user to edit pages 'edit_others_posts' => false, // Allows user to edit others posts not just their own 'create_posts' => false, // Allows user to create new posts 'manage_categories' => false, // Allows user to manage post categories 'publish_posts' => false, // Allows the user to publish, otherwise posts stays in draft mode ) ); // gets the role from WP $role = get_role( 'zerobs_quotemgr' ); // caps $role->add_cap( 'read' ); $role->remove_cap( 'edit_posts' ); $role->add_cap( 'upload_files' ); // added 21/5/18 to ensure can upload media $role->add_cap( 'admin_zerobs_usr' ); #} For all zerobs users :) $role->add_cap( 'manage_categories' ); $role->add_cap( 'zbs_dash' ); # WH added 1.2 - has rights to view ZBS Dash // CRM object view capabilities $role->add_cap( 'admin_zerobs_view_customers' ); $role->add_cap( 'admin_zerobs_view_quotes' ); // CRM object edit capabilities $role->add_cap( 'admin_zerobs_customers' ); $role->add_cap( 'admin_zerobs_quotes' ); // needed for notifications $role->add_cap( 'admin_zerobs_notifications' ); // logs $role->add_cap( 'admin_zerobs_logs_addedit' ); // paranoia unset( $role ); // CRM Invoice Manager add_role( 'zerobs_invoicemgr', __( 'Jetpack CRM Invoice Manager', 'zero-bs-crm' ), array( 'read' => true, // true allows this capability 'edit_posts' => false, // Allows user to edit their own posts 'edit_pages' => false, // Allows user to edit pages 'edit_others_posts' => false, // Allows user to edit others posts not just their own 'create_posts' => false, // Allows user to create new posts 'manage_categories' => false, // Allows user to manage post categories 'publish_posts' => false, // Allows the user to publish, otherwise posts stays in draft mode ) ); // gets the role from WP $role = get_role( 'zerobs_invoicemgr' ); // caps $role->add_cap( 'read' ); $role->remove_cap( 'edit_posts' ); $role->add_cap( 'upload_files' ); // added 21/5/18 to ensure can upload media $role->add_cap( 'admin_zerobs_usr' ); #} For all zerobs users :) $role->add_cap( 'manage_categories' ); $role->add_cap( 'zbs_dash' ); # WH added 1.2 - has rights to view ZBS Dash // CRM object view capabilities $role->add_cap( 'admin_zerobs_view_customers' ); $role->add_cap( 'admin_zerobs_view_invoices' ); $role->add_cap( 'admin_zerobs_view_transactions' ); // CRM object edit capabilities $role->add_cap( 'admin_zerobs_customers' ); $role->add_cap( 'admin_zerobs_invoices' ); $role->add_cap( 'admin_zerobs_transactions' ); // needed for notifications $role->add_cap( 'admin_zerobs_notifications' ); // logs $role->add_cap( 'admin_zerobs_logs_addedit' ); // paranoia unset( $role ); // CRM Transaction Manager add_role( 'zerobs_transactionmgr', __( 'Jetpack CRM Transaction Manager', 'zero-bs-crm' ), array( 'read' => false, // true allows this capability 'edit_posts' => false, // Allows user to edit their own posts 'edit_pages' => false, // Allows user to edit pages 'edit_others_posts' => false, // Allows user to edit others posts not just their own 'create_posts' => false, // Allows user to create new posts 'manage_categories' => false, // Allows user to manage post categories 'publish_posts' => false, // Allows the user to publish, otherwise posts stays in draft mode ) ); // gets the role from WP $role = get_role( 'zerobs_transactionmgr' ); // caps $role->add_cap( 'read' ); $role->remove_cap( 'edit_posts' ); $role->add_cap( 'upload_files' ); // added 21/5/18 to ensure can upload media $role->add_cap( 'admin_zerobs_usr' ); #} For all zerobs users :) $role->add_cap( 'manage_categories' ); $role->add_cap( 'zbs_dash' ); # WH added 1.2 - has rights to view ZBS Dash // CRM object view capabilities $role->add_cap( 'admin_zerobs_view_customers' ); $role->add_cap( 'admin_zerobs_view_transactions' ); // CRM object edit capabilities $role->add_cap( 'admin_zerobs_customers' ); $role->add_cap( 'admin_zerobs_transactions' ); // needed for notifications $role->add_cap( 'admin_zerobs_notifications' ); // logs $role->add_cap( 'admin_zerobs_logs_addedit' ); // paranoia unset( $role ); // CRM Customer add_role( 'zerobs_customer', __( 'Jetpack CRM Contact', 'zero-bs-crm' ), array( 'read' => true, // true allows this capability 'edit_posts' => false, // Allows user to edit their own posts 'edit_pages' => false, // Allows user to edit pages 'edit_others_posts' => false, // Allows user to edit others posts not just their own 'create_posts' => false, // Allows user to create new posts 'manage_categories' => false, // Allows user to manage post categories 'publish_posts' => false, // Allows the user to publish, otherwise posts stays in draft mode ) ); // paranoia unset( $role ); // CRM Mail Manager - Manages campaigns, customers / companies add_role( 'zerobs_mailmgr', __( 'Jetpack CRM Mail Manager', 'zero-bs-crm' ), array( 'read' => false, // true allows this capability 'edit_posts' => false, // Allows user to edit their own posts 'edit_pages' => false, // Allows user to edit pages 'edit_others_posts' => false, // Allows user to edit others posts not just their own 'create_posts' => false, // Allows user to create new posts 'manage_categories' => false, // Allows user to manage post categories 'publish_posts' => false, // Allows the user to publish, otherwise posts stays in draft mode ) ); // gets the role from WP $role = get_role( 'zerobs_mailmgr' ); // caps $role->add_cap( 'read' ); $role->remove_cap( 'edit_posts' ); $role->add_cap( 'upload_files' ); // added 21/5/18 to ensure can upload media $role->add_cap( 'admin_zerobs_usr' ); #} For all zerobs users :) $role->add_cap( 'admin_zerobs_mailcampaigns' ); $role->add_cap( 'manage_categories' ); $role->add_cap( 'zbs_dash' ); # WH added 1.2 - has rights to view ZBS Dash // CRM object view capabilities $role->add_cap( 'admin_zerobs_view_customers' ); $role->add_cap( 'admin_zerobs_view_quotes' ); $role->add_cap( 'admin_zerobs_view_invoices' ); $role->add_cap( 'admin_zerobs_view_events' ); $role->add_cap( 'admin_zerobs_view_transactions' ); // CRM object edit capabilities $role->add_cap( 'admin_zerobs_customers' ); $role->add_cap( 'admin_zerobs_customers_tags' ); $role->add_cap( 'admin_zerobs_events' ); // needed for notifications $role->add_cap( 'admin_zerobs_notifications' ); // emails $role->add_cap( 'admin_zerobs_sendemails_contacts' ); unset( $role ); } /* ====================================================== / Add + Remove Roles ====================================================== */ /* ====================================================== Role Helpers ====================================================== */ // note this returns true if is any ZBS role, INCLUDING zbs customer // if need just 'backend' user, use zeroBSCRM_permsIsZBSBackendUser function zeroBSCRM_permsIsZBSUser(){ #} Set a global var for this load, (sometimes multi-called) global $zeroBSCRM_isZBSUser; if (isset($zeroBSCRM_isZBSUser)) return $zeroBSCRM_isZBSUser; #} ... else $zeroBSCRM_isZBSUser = false; $cu = wp_get_current_user(); if ($cu->has_cap('admin_zerobs_usr')) $zeroBSCRM_isZBSUser = true; if ($cu->has_cap('zerobs_customer')) $zeroBSCRM_isZBSUser = true; return $zeroBSCRM_isZBSUser; } // note this returns true if is any wp-admin based zbs user // if want zbs customer roles too, use zeroBSCRM_permsIsZBSUser function zeroBSCRM_permsIsZBSBackendUser(){ #} Set a global var for this load, (sometimes multi-called) global $zeroBSCRM_isZBSBackendUser; if (isset($zeroBSCRM_isZBSBackendUser)) return $zeroBSCRM_isZBSBackendUser; #} ... else $zeroBSCRM_isZBSBackendUser = false; $cu = wp_get_current_user(); if ($cu->has_cap('admin_zerobs_usr')) $zeroBSCRM_isZBSBackendUser = true; return $zeroBSCRM_isZBSBackendUser; } /* * Checks whether current user (or specified WP ID) is backend user, or wp admin * * @param $wordpress_users_id - bool|int; if passed, will check this WordPress user ID rather than current user */ function zeroBSCRM_permsIsZBSUserOrAdmin( $wordpress_user_id = false ) { // param passed? if ( $wordpress_user_id == false ) { // if using current wordpress user: // Maintain a global var for this load, (sometimes called multiple times) // (Only for current user checks) global $zeroBSCRM_isZBSBackendUser; // check if already checked if ( isset( $zeroBSCRM_isZBSBackendUser ) ){ return $zeroBSCRM_isZBSBackendUser; } // else check: $zeroBSCRM_isZBSBackendUser = false; $user = wp_get_current_user(); } else { // using passed user id $user = get_userdata( $wordpress_user_id ); } // user isn't logged in, or the passed user ID no longer exists or is an invalid value if ( !$user ) { return false; } // crm user check if ( $user->has_cap( 'admin_zerobs_usr' ) ){ $zeroBSCRM_isZBSBackendUser = true; return true; } // admin check if ( $user->has_cap( 'manage_options' ) ){ return true; } return false; } function zeroBSCRM_isZBSAdmin(){ $cu = wp_get_current_user(); //https://wordpress.stackexchange.com/questions/5047/how-to-check-if-a-user-is-in-a-specific-role if (in_array( 'zerobs_admin', (array) $cu->roles )) return true; return false; } function zeroBSCRM_isWPAdmin(){ $cu = wp_get_current_user(); #} adm if ($cu->has_cap('manage_options')) return true; return false; } function zeroBSCRM_isZBSAdminOrAdmin(){ $cu = wp_get_current_user(); //https://wordpress.stackexchange.com/questions/5047/how-to-check-if-a-user-is-in-a-specific-role if (in_array( 'zerobs_admin', (array) $cu->roles )) return true; #} or adm if ($cu->has_cap('manage_options')) return true; return false; } function zeroBSCRM_wooCommerceRemoveBlock(){ #} Add Filter for WooCommerce $cu = wp_get_current_user(); if ($cu->has_cap('admin_zerobs_usr')){ add_filter( 'woocommerce_prevent_admin_access', '__return_false' ); } } function zeroBSCRM_getWordPressRoles(){ global $wp_roles; $all_roles = $wp_roles->roles; return $all_roles; } // return current user capabilities function zeroBSCRM_getCurrentUserCaps(){ $data = get_userdata( get_current_user_id() ); if ( is_object( $data) ) { return array_keys($data->allcaps); } return array(); } /** * Determine if the current user is allowed to manage contacts. * * @param int $obj_type_id Object type ID. * * @return bool */ function zeroBSCRM_permsObjType( $obj_type_id = -1 ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid switch ( $obj_type_id ) { case ZBS_TYPE_CONTACT: case ZBS_TYPE_COMPANY: case ZBS_TYPE_SEGMENT: return zeroBSCRM_permsCustomers(); case ZBS_TYPE_QUOTE: case ZBS_TYPE_QUOTETEMPLATE: return zeroBSCRM_permsQuotes(); case ZBS_TYPE_INVOICE: return zeroBSCRM_permsInvoices(); case ZBS_TYPE_TRANSACTION: return zeroBSCRM_permsTransactions(); case ZBS_TYPE_FORM: return zeroBSCRM_permsForms(); case ZBS_TYPE_TASK: return zeroBSCRM_perms_tasks(); } return false; } /** * Determine if a user is allowed to manage contacts. * * @since 6.1.0 * * @param WP_User $user The WP User to check permission access for. * @param int $contact_id (Optional) The ID of the CRM contact. * @return bool Returns a bool representing a user permission state. */ function jpcrm_can_user_manage_contacts( WP_User $user, $contact_id = null ) { /** * Allow third party plugins to modify the permission conditions for contacts. * * @since 6.1.0 * * @param boolean $allowed A boolean that represents the permission state. * @param WP_User $user The WP User to check permission access for. * @param int|null $contact_id (Optional) The ID of the CRM contact. */ return (bool) apply_filters( 'jpcrm_can_user_manage_contacts', $user->has_cap( 'admin_zerobs_customers' ), $user, $contact_id ); } /** * Determine if the current user is allowed to manage contacts. * * @deprecated 6.1.0 Use jpcrm_can_user_manage_contacts() * * @return bool * * @phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase */ function zeroBSCRM_permsCustomers() { $current_user = wp_get_current_user(); if ( ! $current_user instanceof WP_User ) { return false; } return jpcrm_can_user_manage_contacts( $current_user ) === true; } function zeroBSCRM_permsSendEmailContacts(){ $cu = wp_get_current_user(); if ($cu->has_cap('admin_zerobs_sendemails_contacts')) return true; return false; } function zeroBSCRM_permsViewCustomers(){ $cu = wp_get_current_user(); if ($cu->has_cap('admin_zerobs_view_customers')) return true; return false; } function zeroBSCRM_permsCustomersTags(){ $cu = wp_get_current_user(); if ($cu->has_cap('admin_zerobs_customers_tags')) return true; return false; } function zeroBSCRM_permsQuotes(){ $cu = wp_get_current_user(); if ($cu->has_cap('admin_zerobs_quotes')) return true; return false; } function zeroBSCRM_permsViewQuotes(){ $cu = wp_get_current_user(); if ($cu->has_cap('admin_zerobs_view_quotes')) return true; return false; } function zeroBSCRM_permsInvoices(){ $cu = wp_get_current_user(); if ($cu->has_cap('admin_zerobs_invoices')) return true; return false; } function zeroBSCRM_permsViewInvoices(){ $cu = wp_get_current_user(); if ($cu->has_cap('admin_zerobs_view_invoices')) return true; return false; } function zeroBSCRM_permsTransactions(){ $cu = wp_get_current_user(); if ($cu->has_cap('admin_zerobs_transactions')) return true; return false; } function zeroBSCRM_permsViewTransactions(){ $cu = wp_get_current_user(); if ($cu->has_cap('admin_zerobs_view_transactions')) return true; return false; } function zeroBSCRM_permsMailCampaigns(){ $cu = wp_get_current_user(); if ($cu->has_cap('admin_zerobs_mailcampaigns')) return true; return false; } function zeroBSCRM_permsForms(){ $cu = wp_get_current_user(); if ($cu->has_cap('admin_zerobs_forms')) return true; return false; } function zeroBSCRM_perms_tasks(){ $cu = wp_get_current_user(); if ($cu->has_cap('admin_zerobs_events')) return true; return false; } function zeroBSCRM_permsNotify(){ $cu = wp_get_current_user(); if ($cu->has_cap('admin_zerobs_notifications')) return true; return false; } // NEEDS it's own cap when we get granular. function zeroBSCRM_permsExport(){ $cu = wp_get_current_user(); if ($cu->has_cap('admin_zerobs_customers')) return true; return false; } // LOGS // can add/edit logs function zeroBSCRM_permsLogsAddEdit(){ $cu = wp_get_current_user(); if ($cu->has_cap('admin_zerobs_logs_addedit')) return true; return false; } // can delete logs function zeroBSCRM_permsLogsDelete(){ $cu = wp_get_current_user(); if ($cu->has_cap('admin_zerobs_logs_delete')) return true; return false; } function zeroBSCRM_permsClient(){ //using Client to not confuse with Customer and Customer Manager $cu = wp_get_current_user(); if ($cu->has_cap('zerobs_customer')) return true; return false; } function zeroBSCRM_permsWPEditPosts(){ $cu = wp_get_current_user(); if ($cu->has_cap('edit_posts')) return true; return false; } function zeroBS_getPossibleCustomerOwners(){ return zeroBS_getPossibleOwners(array('zerobs_admin','zerobs_customermgr')); } function zeroBS_getPossibleCompanyOwners(){ return zeroBS_getPossibleOwners(array('zerobs_admin','zerobs_customermgr')); } function zeroBS_getPossibleQuoteOwners(){ return zeroBS_getPossibleOwners(array('zerobs_admin','zerobs_customermgr')); } function zeroBS_getPossibleInvoiceOwners(){ return zeroBS_getPossibleOwners(array('zerobs_admin','zerobs_customermgr')); } function zeroBS_getPossibleTransactionOwners(){ return zeroBS_getPossibleOwners(array('zerobs_admin','zerobs_customermgr')); } function zeroBS_getPossibleTaskOwners(){ return zeroBS_getPossibleOwners(array('zerobs_admin','admin_zerobs_events')); } // added this because Multi-site doesn't reliably // return on current_user_can('zerobs_customer') // https://wordpress.stackexchange.com/questions/5047/how-to-check-if-a-user-is-in-a-specific-role function zeroBSCRM_isRole($role=''){ $user = wp_get_current_user(); if ( in_array( $role, (array) $user->roles ) ) { return true; } return false; } /** * Checks a user object (or current user if false passed) * has roles in first array, and none of the roles in second array **/ function jpcrm_role_check( $user_object = false, $has_roles = array(), $hasnt_roles = array(), $only_these_roles = array() ){ // load current user if not passed if ( !$user_object ){ $user_object = wp_get_current_user(); } // got object? if ( !$user_object ){ return false; } // verify has_roles if ( count( $has_roles ) > 0 ){ foreach ( $has_roles as $role ){ if ( !in_array( $role, $user_object->roles ) ) { return false; } } } // verify hasnt_roles if ( count( $hasnt_roles ) > 0 ){ foreach ( $hasnt_roles as $role ){ if ( in_array( $role, $user_object->roles ) ) { return false; } } } // verify only_roles if ( count( $only_these_roles ) > 0 ){ $role_match_count = 0; foreach ( $user_object->roles as $role ){ if ( !in_array( $role, $only_these_roles ) ) { return false; } else { $role_match_count++; } } if ( $role_match_count != count( $only_these_roles ) ){ return false; } } return true; } function zeroBS_getPossibleOwners($permsReq='',$simplify=false){ // https://codex.wordpress.org/Function_Reference/get_users /* possible args.. $args = array( 'blog_id' => $GLOBALS['blog_id'], 'role' => '', 'role__in' => array('administrator','zerobs_admin','zerobs_customermgr','zerobs_quotemgr','zerobs_invoicemgr','zerobs_transactionmgr',''), 'role__not_in' => array(), 'meta_key' => '', 'meta_value' => '', 'meta_compare' => '', 'meta_query' => array(), 'date_query' => array(), 'include' => array(), 'exclude' => array(), 'orderby' => 'login', 'order' => 'ASC', 'offset' => '', 'search' => '', 'number' => '', 'count_total' => false, 'fields' => 'all', 'who' => '', ); */ if (empty($permsReq) || !in_array($permsReq, array('zerobs_admin','zerobs_customermgr','zerobs_quotemgr','zerobs_invoicemgr','zerobs_transactionmgr'))){ // all zbs users + admin $args = array('role__in' => array('administrator','zerobs_admin','zerobs_customermgr','zerobs_quotemgr','zerobs_invoicemgr','zerobs_transactionmgr')); } else { // specific roles :) (+- admin?) $args = array('role__in' => array('administrator',$permsReq)); } $users = get_users( $args ); // this is used by inline editing on list view, be careful if editing if ($simplify){ if (is_array($users)){ $ret = array(); foreach ($users as $u){ $ret[] = array( 'id' => $u->ID, 'name' => $u->data->display_name, 'email' => $u->data->user_email ); } $users = $ret; } } return $users; } /* ====================================================== / Role Helpers ====================================================== */ /** * Checks whether a WP user has permissions to view an object * * @param obj $wp_user WP user object * @param int $obj_id * @param int $obj_type_id * * @return bool indicating whether the WP user can view the current object */ function jpcrm_can_wp_user_view_object( $wp_user, $obj_id, $obj_type_id ) { // unsupported object type if ( !in_array( $obj_type_id, array( ZBS_TYPE_QUOTE, ZBS_TYPE_INVOICE ) ) ) { return false; } // retrieve object switch ($obj_type_id) { case ZBS_TYPE_QUOTE: $is_quote_admin = $wp_user->has_cap( 'admin_zerobs_quotes' ); $obj_data = zeroBS_getQuote( $obj_id ); // draft quote if ( is_array($obj_data) && $obj_data['template'] == -1 && !$is_quote_admin ) { return false; } $assigned_contact_id = zeroBSCRM_quote_getContactAssigned( $obj_id ); break; case ZBS_TYPE_INVOICE: $is_invoice_admin = $wp_user->has_cap( 'admin_zerobs_invoices' ); $obj_data = zeroBS_getInvoice( $obj_id ); // draft invoice if ( is_array( $obj_data ) && $obj_data['status'] === 'Draft' && ! $is_invoice_admin ) { return false; } $assigned_contact_id = zeroBSCRM_invoice_getContactAssigned( $obj_id ); break; } // no such object! if ( !$obj_data ) { return false; } // not logged in if ( !$wp_user ) { return false; } // grant access if user has full permissions to view object type if ( $obj_type_id == ZBS_TYPE_QUOTE && $is_quote_admin || $obj_type_id == ZBS_TYPE_INVOICE && $is_invoice_admin ) { return true; } // object is not assigned if ( !$assigned_contact_id ) { return false; } // verify current user is assigned user $contact_id = zeroBS_getCustomerIDWithEmail( $wp_user->user_email ); if ( $assigned_contact_id != $contact_id ) { return false; } // passed all checks, so go for liftoff return true; } /** * Pass-thru helper function to get current user for use with jpcrm_can_wp_user_view_object() * Particularly useful for client portal functions. * * @param int $obj_id * @param int $obj_type_id * * @return bool indicating whether the current user can view the current object */ function jpcrm_can_current_wp_user_view_object( $obj_id, $obj_type_id ) { $current_wp_user = wp_get_current_user(); return jpcrm_can_wp_user_view_object( $current_wp_user, $obj_id, $obj_type_id ); } /** * Determines if client portal access is allowed via easy-access hashes. * * @param int $obj_type_id * * @return bool */ function jpcrm_can_access_portal_via_hash( $obj_type_id ) { // easy access is disabled if ( zeroBSCRM_getSetting( 'easyaccesslinks' ) != 1 ) { return false; } $security_request_name = jpcrm_get_easy_access_security_request_name_by_obj_type( $obj_type_id ); // unsupported object type if ( !$security_request_name ) { return false; } // fail if already blocked (this is a nefarious user or bot) if ( zeroBSCRM_security_blockRequest( $security_request_name ) ) { return false; } // access via hash is allowed return true; } /** * Returns security request name by object type. * * @param int $obj_type_id * * @return str * @return bool false if no match */ function jpcrm_get_easy_access_security_request_name_by_obj_type( $obj_type_id ) { switch ( $obj_type_id ) { case ZBS_TYPE_INVOICE: $security_request_name = 'inveasy'; break; case ZBS_TYPE_QUOTE: $security_request_name = 'quoeasy'; break; default: $security_request_name = false; } return $security_request_name; } // show an error if bad permissions function jpcrm_perms_error() { echo zeroBSCRM_UI2_messageHTML( 'warning', __( 'Access Denied', 'zero-bs-crm' ), __('You do not have permission to access this page.', 'zero-bs-crm' ), 'disabled warning sign', 'bad_perms' ); die(); } /** * Verifies a given path is within allowed base paths. * * @param string $path Path to check. * @param array|string $allowed_base_paths Paths to check. * * @return bool True if it's an allowed path, false if not. */ function jpcrm_is_allowed_path( $path, $allowed_base_paths ) { // Convert to array if not already one. if ( ! is_array( $allowed_base_paths ) ) { $allowed_base_paths = array( $allowed_base_paths ); } $real_path = realpath( $path ); // Invalid path. if ( ! $real_path ) { return false; } foreach ( $allowed_base_paths as $base_path ) { $real_base_path = realpath( $base_path ); // If file belongs to a valid base_path, all is well. // This base path is sometimes a non-existent path, so we test for its existence as well. if ( $real_base_path && strpos( $real_path, $real_base_path ) === 0 ) { return true; } } // doesn't match an allowed base path return false; }
projects/plugins/crm/includes/ZeroBSCRM.API.php
<?php /* ! * Jetpack CRM * https://jetpackcrm.com * V2.0 * * Copyright 2020 Automattic * * Date: 05/04/2017 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) { exit; } /* ====================================================== / Breaking Checks ====================================================== */ // } We can do this below in the templater or templates? add_action( 'wp_enqueue_scripts', 'zeroBS_portal_enqueue_stuff' ); // } ... in the end we can just dump the above line into the templates before get_header() - hacky but works // Adds the Rewrite Endpoint for the 'clients' area of the CRM. // } WH - this is dumped here now, because this whole thing is fired just AFTER init (to allow switch/on/off in main ZeroBSCRM.php) function zeroBS_api_rewrite_endpoint() { add_rewrite_endpoint( 'zbs_api', EP_ROOT ); } add_action( 'init', 'zeroBS_api_rewrite_endpoint' ); /** * Process the query and get page and items per page */ function jpcrm_api_process_pagination() { if ( isset( $_GET['page'] ) && (int) $_GET['page'] >= 0 ) { $page = (int) $_GET['page']; } else { $page = 0; } if ( isset( $_GET['perpage'] ) && (int) $_GET['perpage'] >= 0 ) { $per_page = (int) $_GET['perpage']; } else { $per_page = 10; } return array( $page, $per_page ); } /** * Check and process if there is a search in the query */ function jpcrm_api_process_search() { return ( isset( $_GET['zbs_query'] ) ? sanitize_text_field( $_GET['zbs_query'] ) : '' ); } /** * If there is a `replace_hyphens_with_underscores_in_json_keys` parameter in * the request, it is returned as an int. Otherwise returns 0. * * @return int Parameter `replace_hyphens_with_underscores_in_json_keys` from request. 0 if it isn't set. */ function jpcrm_api_process_replace_hyphens_in_json_keys() { return ( isset( $_GET['replace_hyphens_with_underscores_in_json_keys'] ) ? (int) $_GET['replace_hyphens_with_underscores_in_json_keys'] : 0 ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended } /** * If there is a `external_api_name` parameter in * the request, it is returned as a string. Otherwise returns the bool false. * * @return string|bool Parameter `external_api_name` from request. Returns false if it isn't set. */ function jpcrm_api_process_external_api_name() { return ( isset( $_GET['external_api_name'] ) ? sanitize_text_field( wp_unslash( $_GET['external_api_name'] ) ) : false ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended } /** * Generate API invalid request error */ function jpcrm_api_invalid_request() { $reply = array( 'status' => __( 'Bad request', 'zero-bs-crm' ), 'message' => __( 'The API request was invalid.', 'zero-bs-crm' ), ); wp_send_json_error( $reply, 400 ); } /** * Generate API unauthorised request error */ function jpcrm_api_unauthorised_request() { $reply = array( 'status' => __( 'Unauthorized', 'zero-bs-crm' ), 'message' => __( 'Please ensure your Jetpack CRM API key and secret are correctly configured.', 'zero-bs-crm' ), ); wp_send_json_error( $reply, 401 ); } /** * Generate API forbidden request error */ function jpcrm_api_forbidden_request() { $reply = array( 'status' => __( 'Forbidden', 'zero-bs-crm' ), 'message' => __( 'You do not have permission to access this resource.', 'zero-bs-crm' ), ); wp_send_json_error( $reply, 403 ); } /** * Generate API invalid method error */ function jpcrm_api_invalid_method() { $reply = array( 'status' => __( 'Method not allowed', 'zero-bs-crm' ), 'message' => __( 'Please ensure you are using the proper method (e.g. POST or GET).', 'zero-bs-crm' ), ); wp_send_json_error( $reply, 405 ); } /** * Generate API teapot error */ function jpcrm_api_teapot() { $reply = array( 'status' => 'I\'m a teapot', 'message' => 'As per RFC 2324 (section 2.3.2), this response is short and stout.', ); wp_send_json_error( $reply, 418 ); } /** * Check if the request is authorised via the API key/secret * * @return bool or error */ function jpcrm_api_check_authentication() { if ( ! jpcrm_is_api_request_authorised() ) { jpcrm_api_unauthorised_request(); } return true; } /** * Check if the request matches the expected HTTP methods * * @param array $methods_allowed List of the request HTTP methods (GET, POST, PUSH, DELETE) * @return bool or error */ function jpcrm_api_check_http_method( $methods_allowed = array( 'GET' ) ) { if ( ! in_array( $_SERVER['REQUEST_METHOD'], $methods_allowed ) ) { if ( $_SERVER['REQUEST_METHOD'] == 'BREW' ) { jpcrm_api_teapot(); } else { jpcrm_api_invalid_method(); } } return true; } /** * Manage an API Error response with the correct headers and encode the data to JSON * * @param string $errorMsg * @param int $headerCode */ function zeroBSCRM_API_error( $errorMsg = 'Error', $header_code = 400 ) { // } 400 = general error // } 403 = perms wp_send_json( array( 'error' => $errorMsg ), $header_code ); } // now to locate the templates... // http://jeroensormani.com/how-to-add-template-files-in-your-plugin/ /** * Locate template. * * Locate the called template. * Search Order: * 1. /templates not over-ridable * * @since 1.2.7 * * @param string $template_name Template to load. * @param string $string $template_path Path to templates. * @param string $default_path Default path to template files. * @return string Path to the template file. */ function zeroBSCRM_API_locate_api_endpoint( $template_name, $template_path = '', $default_path = '' ) { // Set variable to search in zerobscrm-plugin-templates folder of theme. if ( ! $template_path ) { $template_path = 'zerobscrm-plugin-templates/'; } // Set default plugin templates path. if ( ! $default_path ) { $default_path = ZEROBSCRM_PATH . 'api/'; // Path to the template folder } // Search template file in theme folder. $template = locate_template( array( $template_path . $template_name, $template_name, ) ); // Get plugins template file. if ( ! $template ) { $template = $default_path . $template_name; } return apply_filters( 'zeroBSCRM_API_locate_api_endpoint', $template, $template_name, $template_path, $default_path ); } /** * Get template. * * Search for the template and include the file. * * @since 1.2.7 * * @see zeroBSCRM_API_get_template() * * @param string $template_name Template to load. * @param array $args Args passed for the template file. * @param string $string $template_path Path to templates. * @param string $default_path Default path to template files. */ function zeroBSCRM_API_get_api_endpoint( $template_name, $args = array(), $tempate_path = '', $default_path = '' ) { if ( is_array( $args ) && isset( $args ) ) { extract( $args ); } $template_file = zeroBSCRM_API_locate_api_endpoint( $template_name, $tempate_path, $default_path ); if ( ! file_exists( $template_file ) ) { _doing_it_wrong( __FUNCTION__, sprintf( '<code>%s</code> does not exist.', esc_html( $template_file ) ), '1.0.0' ); return; } include $template_file; } // function similar to is_user_logged_in() function jpcrm_is_api_request_authorised() { // WH - I've added api_secret here to bolster security, // We should switch authentication method to "headers" not parameters - will be cleaner :) // unclear if we're still needing this... // we are coming from GROOVE HQ - define in wp-config.php if ( defined( 'GROOVE_API_TOKEN' ) && ! empty( $_GET['api_token'] ) ) { if ( hash_equals( sanitize_text_field( $_GET['api_token'], GROOVE_API_TOKEN ) ) ) { // and define that we've checked if ( ! defined( 'ZBSGROOVECHECKED' ) ) { define( 'ZBSGROOVECHECKED', time() ); } return true; } } // the the API key/secret are currently in the URL $possible_api_key = isset( $_GET['api_key'] ) ? sanitize_text_field( $_GET['api_key'] ) : ''; $possible_api_secret = isset( $_GET['api_secret'] ) ? sanitize_text_field( $_GET['api_secret'] ) : ''; // a required value is empty, so not authorised if ( empty( $possible_api_key ) || empty( $possible_api_secret ) ) { return false; } $api_key = zeroBSCRM_getAPIKey(); // provided key doesn't match, so not authorised if ( ! hash_equals( $possible_api_key, $api_key ) ) { return false; } global $zbs; $zbs->load_encryption(); $hashed_possible_api_secret = $zbs->encryption->hash( $possible_api_secret ); $hashed_api_secret = zeroBSCRM_getAPISecret(); // provided secret doesn't match, so not authorised if ( ! hash_equals( $hashed_possible_api_secret, $hashed_api_secret ) ) { return false; } return true; } function zeroBSCRM_getAPIEndpoint() { return site_url( '/zbs_api/' ); // , 'https' ); } function jpcrm_generate_api_publishable_key() { global $zbs; $zbs->load_encryption(); $api_publishable_key = 'jpcrm_pk_' . $zbs->encryption->get_rand_hex(); return $api_publishable_key; } function jpcrm_generate_api_secret_key() { global $zbs; $zbs->load_encryption(); $api_secret_key = 'jpcrm_sk_' . $zbs->encryption->get_rand_hex(); return $api_secret_key; } /* SAME CODE AS IN PORTAL, BUT REPLACED WITH api_endpoint stuff. Templates (to return the JSON) are in /api/endpoints/ folder */ add_filter( 'template_include', 'zeroBSCRM_API_api_endpoint', 99 ); function zeroBSCRM_API_api_endpoint( $template ) { $zbsAPIQuery = get_query_var( 'zbs_api', false ); // We only want to interfere where zbs_api is set :) // ... as this is called for ALL page loads if ( $zbsAPIQuery === false ) { return $template; } // check if API key/secret are correct, or die with 403 jpcrm_api_check_authentication(); // Break it up if / present if ( strpos( $zbsAPIQuery, '/' ) ) { $zbsAPIRequest = explode( '/', $zbsAPIQuery ); } else { // no / in it, so must just be a 1 worder like "invoices", here just jam in array so it matches prev exploded req. $zbsAPIRequest = array( $zbsAPIQuery ); } // no endpoint was specified, so die with 400 if ( empty( $zbsAPIRequest[0] ) ) { jpcrm_api_invalid_request(); } // hard-coded valid endpoints; we could at some point do this dynamically $valid_api_endpoints = array( 'status', 'webhook', 'create_customer', 'create_transaction', 'create_event', 'create_company', 'customer_search', 'customers', 'invoices', 'quotes', 'events', 'companies', 'transactions', ); // invalid endpoint was specified, so die with 400 if ( ! in_array( $zbsAPIRequest[0], $valid_api_endpoints ) ) { jpcrm_api_invalid_request(); } return zeroBSCRM_API_get_api_endpoint( $zbsAPIRequest[0] . '.php' ); } if ( ! function_exists( 'hash_equals' ) ) { function hash_equals( $str1, $str2 ) { if ( strlen( $str1 ) != strlen( $str2 ) ) { return false; } else { $res = $str1 ^ $str2; $ret = 0; for ( $i = strlen( $res ) - 1; $i >= 0; $i-- ) { $ret |= ord( $res[ $i ] ); } return ! $ret; } } } // generate new API credentials function jpcrm_generate_api_creds() { global $zbs; $new_publishable_key = jpcrm_generate_api_publishable_key(); $zbs->DAL->updateSetting( 'api_key', $new_publishable_key ); $new_secret_key = jpcrm_generate_api_secret_key(); $hashed_api_secret = $zbs->encryption->hash( $new_secret_key ); $zbs->DAL->updateSetting( 'api_secret', $hashed_api_secret ); return array( 'key' => $new_publishable_key, 'secret' => $new_secret_key, ); } // each CRM is only given one API (for now) function zeroBSCRM_getAPIKey() { global $zbs; return $zbs->DAL->setting( 'api_key' ); } // each CRM is only given one API (for now) function zeroBSCRM_getAPISecret() { global $zbs; return $zbs->DAL->setting( 'api_secret' ); } /** * Replaces hyphens in key identifiers from a json array with underscores. * Some services do not accept hyphens in their key identifiers, e.g. Zapier: * https://github.com/zapier/zapier-platform/blob/master/packages/schema/docs/build/schema.md#keyschema * * If we expand use of this, we should consider making it recursive. * * @param array $input_array The array with keys needing to be changed, e.g.: [ { "id":"1", "custom-price":"10" }, { "id":"2", "custom-price":"20" }, ]. * @return array Array with changed keys, e.g.: [ { "id":"1", "custom_price":"10" }, { "id":"2", "custom_price":"20" }, ]. */ function jpcrm_api_replace_hyphens_in_json_keys_with_underscores( $input_array ) { $new_array = array(); foreach ( $input_array as $original_item ) { $new_array[] = array_combine( array_map( function ( $key ) { return str_replace( '-', '_', $key ); }, array_keys( $original_item ) ), $original_item ); } return $new_array; }
projects/plugins/crm/includes/ZeroBSCRM.DAL2.Mail.php
<?php /* ! * Jetpack CRM * https://jetpackcrm.com * V1.20 * * Copyright 2020 Automattic * * Date: 01/11/16 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) { exit; } /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== DB GENERIC/OBJ Helpers (not DAL GET etc.) ====================================================== */ function zeroBSCRM_getMailDeliveryAccs() { $zbsSMTPAccs = zeroBSCRM_getSetting( 'smtpaccs' ); if ( ! is_array( $zbsSMTPAccs ) ) { $zbsSMTPAccs = array(); } return $zbsSMTPAccs; } function zeroBSCRM_getMailDeliveryDefault() { return zeroBSCRM_getSetting( 'smtpaccsdef' ); } // NOTE a number of these fields are now dummy (not used) // WH has refined func below. /* function zeroBSCRM_insertEmailTemplate($ID=-1,$from_name='',$from_address='',$reply_to='', $cc='', $bcc='',$subject='',$content='',$active=0){ global $wpdb, $ZBSCRM_t; #} Add header line if ($wpdb->insert( $ZBSCRM_t['system_mail_templates'], array( 'zbs_site' => -1, 'zbs_team' => -1, 'zbs_owner' => -1, 'zbsmail_id' => $ID, 'zbsmail_active' => $active, 'zbsmail_fromname' => $from_name, 'zbsmail_fromaddress' => $from_address, 'zbsmail_replyto' => $reply_to, 'zbsmail_ccto' => $cc, 'zbsmail_bccto' => $bcc, 'zbsmail_subject' => $subject, 'zbsmail_body' => $content, 'zbsmail_created' => time(), 'zbsmail_lastupdated' => time(), ), array( '%d', //zbs_site '%d', //zbs_team '%d', //zbs_owner '%d', //zbs_id '%d', //active '%s', //fromname '%s', //fromaddress '%s', //replyto '%s', //ccto '%s', //bccto '%s', //subject '%s', //body '%d', //created '%d', //lastupdated ) ) > 0){ // inserted, let's move on $newSysTemplate = $wpdb->insert_id; } else { // could not insert?! return false; } } */ function zeroBSCRM_insertEmailTemplate( $ID = -1, $deliverymethod = '', $bcc = '', $subject = '', $content = '', $active = 0 ) { global $wpdb, $ZBSCRM_t; // } Add header line if ( $wpdb->insert( $ZBSCRM_t['system_mail_templates'], array( 'zbs_site' => -1, 'zbs_team' => -1, 'zbs_owner' => -1, 'zbsmail_id' => $ID, 'zbsmail_active' => $active, 'zbsmail_fromname' => '', 'zbsmail_fromaddress' => '', 'zbsmail_replyto' => '', 'zbsmail_deliverymethod' => $deliverymethod, 'zbsmail_ccto' => '', 'zbsmail_bccto' => $bcc, 'zbsmail_subject' => $subject, 'zbsmail_body' => $content, 'zbsmail_created' => time(), 'zbsmail_lastupdated' => time(), ), array( '%d', // zbs_site '%d', // zbs_team '%d', // zbs_owner '%d', // zbs_id '%d', // active '%s', // fromname '%s', // fromaddress '%s', // replyto '%s', // deliverymethod '%s', // ccto '%s', // bccto '%s', // subject '%s', // body '%d', // created '%d', // lastupdated ) ) > 0 ) { // inserted, let's move on $newSysTemplate = $wpdb->insert_id; } else { // could not insert?! return false; } } // NOTE a number of these fields are now dummy (not used) // WH has refined func below. /* function zeroBSCRM_updateEmailTemplate($ID=-1,$from_name='',$from_address='',$reply_to='', $cc='', $bcc='',$subject='',$content=''){ global $wpdb, $ZBSCRM_t; if ($wpdb->update( $ZBSCRM_t['system_mail_templates'], array( 'zbs_site' => -1, 'zbs_team' => -1, 'zbs_owner' => -1, 'zbsmail_fromname' => $from_name, 'zbsmail_fromaddress' => $from_address, 'zbsmail_replyto' => $reply_to, 'zbsmail_ccto' => $cc, 'zbsmail_bccto' => $bcc, 'zbsmail_subject' => $subject, 'zbsmail_body' => $content, 'zbsmail_lastupdated' => time(), ), array( // where 'zbsmail_id' => $ID, ), array( '%d', //zbs_site '%d', //zbs_team '%d', //zbs_owner '%s', //fromname '%s', //fromaddress '%s', //replyto '%s', //ccto '%s', //bccto '%s', //subject '%s', //body '%d', //lastupdated ), array( '%d' ) ) !== false){ } else { return false; } } */ function zeroBSCRM_updateEmailTemplate( $ID = -1, $deliverymethod = '', $bcc = '', $subject = '', $content = '' ) { global $wpdb, $ZBSCRM_t; if ( $wpdb->update( $ZBSCRM_t['system_mail_templates'], array( 'zbs_site' => -1, 'zbs_team' => -1, 'zbs_owner' => -1, 'zbsmail_deliverymethod' => $deliverymethod, 'zbsmail_bccto' => $bcc, 'zbsmail_subject' => $subject, 'zbsmail_body' => $content, 'zbsmail_lastupdated' => time(), ), array( // where 'zbsmail_id' => $ID, ), array( '%d', // zbs_site '%d', // zbs_team '%d', // zbs_owner '%s', // deliverymethod '%s', // bccto '%s', // subject '%s', // body '%d', // lastupdated ), array( '%d', ) ) !== false ) { } else { return false; } } function zeroBSCRM_mailTemplate_exists( $ID ) { global $wpdb, $ZBSCRM_t; $ID = (int) $ID; $sql = $wpdb->prepare( 'SELECT zbsmail_id FROM ' . $ZBSCRM_t['system_mail_templates'] . ' WHERE zbsmail_id = %d', $ID ); $r = $wpdb->get_results( $sql ); return count( $r ); } // Returns the total count of mail templates function zeroBSCRM_mailTemplate_count() { global $wpdb, $ZBSCRM_t; return $wpdb->get_var( 'SELECT COUNT(zbsmail_id) FROM ' . $ZBSCRM_t['system_mail_templates'] ); } function zeroBSCRM_mailTemplate_get( $ID = -1 ) { global $wpdb, $ZBSCRM_t; $ID = (int) $ID; if ( $ID > 0 ) { $sql = $wpdb->prepare( 'SELECT * FROM ' . $ZBSCRM_t['system_mail_templates'] . ' WHERE zbsmail_id = %d', $ID ); return zeroBSCRM_mailTemplate_tidy( $wpdb->get_row( $sql ) ); } else { return false; } } /** * tidy's the object from wp db into clean array * Especially necessary so we can stripslashes. * WH Note: For speed today, am just going to override that which need it. These hsould all be proper tidy_ funcs eventually :( * Hope MS does in future. * * @param array $obj (DB obj) * * @return array (clean obj) */ function zeroBSCRM_mailTemplate_tidy( $obj = false ) { if ( isset( $obj->ID ) ) { // these need escaping $obj->zbsmail_fromname = zeroBSCRM_stripSlashes( $obj->zbsmail_fromname, true ); $obj->zbsmail_subject = zeroBSCRM_stripSlashes( $obj->zbsmail_subject, true ); $obj->zbsmail_body = zeroBSCRM_stripSlashes( $obj->zbsmail_body, true ); } return $obj; } function zeroBSCRM_mailTemplate_getAll() { global $wpdb, $ZBSCRM_t; $sql = 'SELECT zbsmail_id, zbsmail_active FROM ' . $ZBSCRM_t['system_mail_templates']; $r = $wpdb->get_results( $sql ); return $r; } function zeroBSCRM_mailTemplate_getSubject( $ID ) { // used for system emails only global $wpdb, $ZBSCRM_t; $sql = $wpdb->prepare( 'SELECT zbsmail_subject FROM ' . $ZBSCRM_t['system_mail_templates'] . ' WHERE zbsmail_id = %d', $ID ); /* $r = $wpdb->get_results($sql); if(count($r) > 0){ return $r[0]->zbsmail_subject; }else{ return false; } */ return zeroBSCRM_stripSlashes( $wpdb->get_var( $sql ) ); } function zeroBSCRM_mailTemplate_getMailDelMethod( $ID ) { // used for system emails only global $wpdb, $ZBSCRM_t; $sql = $wpdb->prepare( 'SELECT zbsmail_deliverymethod FROM ' . $ZBSCRM_t['system_mail_templates'] . ' WHERE zbsmail_id = %d', $ID ); return $wpdb->get_var( $sql ); } /* ====================================================== ZBS Template List Population ====================================================== */ // MS function which populates the database with the standard HTML templates for each system email // listing the templates into an array + our recommended content // WH 2.97.4 - added $wpdb->delete's below, as somehow someone was re-firing this func a second time // ... not really an elegant way of ensuring templates are there in the db. Leaving for now // ... but when more free time, clean up this routine, bringing in all templates :) function zeroBSCRM_populateEmailTemplateList() { global $wpdb,$ZBSCRM_t; // need to define this if using it below.. how did this slip through checks? // IDs // 0 - the template itself.... can allow this to be edited.. or upsell it to be edited :/ $ID = 0; // } default is admin email and CRM name // now all done via zeroBSCRM_mailDelivery_defaultFromname $from_name = zeroBSCRM_mailDelivery_defaultFromname(); /* This wasn't used in end, switched to default mail delivery opt $from_address = zeroBSCRM_mailDelivery_defaultEmail();; //default WordPress admin email ? $reply_to = ''; $cc = ''; */ $deliveryMethod = zeroBSCRM_getMailDeliveryDefault(); $bcc = ''; // } The email stuff... $subject = ''; $content = zeroBSCRM_mail_retrieveDefaultBodyTemplate( 'maintemplate' ); // BRUTAL DELETE old one (avoids dupes) $wpdb->delete( $ZBSCRM_t['system_mail_templates'], array( 'zbsmail_id' => $ID ) ); $active = 1; // 1 = true.. if ( zeroBSCRM_mailTemplate_exists( $ID ) == 0 ) { $content = zeroBSCRM_mailTemplate_processEmailHTML( $content ); // zeroBSCRM_insertEmailTemplate($ID,$from_name,$from_address,$reply_to,$cc,$bcc,$subject,$content,$active); zeroBSCRM_insertEmailTemplate( $ID, $deliveryMethod, $bcc, $subject, $content, $active ); } // IDs // 1 - Client Portal Welcome Email $ID = 1; $reply_to = ''; $cc = ''; $bcc = ''; // } The email stuff... $subject = __( 'Your Client Portal', 'zero-bs-crm' ); $content = zeroBSCRM_mail_retrieveDefaultBodyTemplate( 'clientportal' ); // BRUTAL DELETE old one (avoids dupes) $wpdb->delete( $ZBSCRM_t['system_mail_templates'], array( 'zbsmail_id' => $ID ) ); $active = 1; // 1 = true.. if ( zeroBSCRM_mailTemplate_exists( $ID ) == 0 ) { $content = zeroBSCRM_mailTemplate_processEmailHTML( $content ); // zeroBSCRM_insertEmailTemplate($ID,$from_name,$from_address,$reply_to,$cc,$bcc,$subject,$content,$active); zeroBSCRM_insertEmailTemplate( $ID, $deliveryMethod, $bcc, $subject, $content, $active ); } // IDs // 2 - Quote Accepted Email $ID = 2; $reply_to = ''; $cc = ''; $bcc = ''; // } The email stuff... $subject = __( 'Quote Accepted', 'zero-bs-crm' ); $content = zeroBSCRM_mail_retrieveDefaultBodyTemplate( 'quoteaccepted' ); // BRUTAL DELETE old one (avoids dupes) $wpdb->delete( $ZBSCRM_t['system_mail_templates'], array( 'zbsmail_id' => $ID ) ); $active = 1; // 1 = true.. if ( zeroBSCRM_mailTemplate_exists( $ID ) == 0 ) { $content = zeroBSCRM_mailTemplate_processEmailHTML( $content ); // zeroBSCRM_insertEmailTemplate($ID,$from_name,$from_address,$reply_to,$cc,$bcc,$subject,$content,$active); zeroBSCRM_insertEmailTemplate( $ID, $deliveryMethod, $bcc, $subject, $content, $active ); } // IDs // 3 - Email Invoice $ID = 3; $reply_to = ''; $cc = ''; $bcc = ''; // } The email stuff... $subject = __( 'You have received an Invoice', 'zero-bs-crm' ); $content = zeroBSCRM_mail_retrieveDefaultBodyTemplate( 'invoicesent' ); // BRUTAL DELETE old one (avoids dupes) $wpdb->delete( $ZBSCRM_t['system_mail_templates'], array( 'zbsmail_id' => $ID ) ); $active = 1; // 1 = true.. if ( zeroBSCRM_mailTemplate_exists( $ID ) == 0 ) { $content = zeroBSCRM_mailTemplate_processEmailHTML( $content ); // zeroBSCRM_insertEmailTemplate($ID,$from_name,$from_address,$reply_to,$cc,$bcc,$subject,$content,$active); zeroBSCRM_insertEmailTemplate( $ID, $deliveryMethod, $bcc, $subject, $content, $active ); } // IDs // 4 - New Quote $ID = 4; $reply_to = ''; $cc = ''; $bcc = ''; // } The email stuff... $subject = __( 'You have received a new Proposal', 'zero-bs-crm' ); $content = zeroBSCRM_mail_retrieveDefaultBodyTemplate( 'quotesent' ); // BRUTAL DELETE old one (avoids dupes) $wpdb->delete( $ZBSCRM_t['system_mail_templates'], array( 'zbsmail_id' => $ID ) ); $active = 1; // 1 = true.. if ( zeroBSCRM_mailTemplate_exists( $ID ) == 0 ) { $content = zeroBSCRM_mailTemplate_processEmailHTML( $content ); // zeroBSCRM_insertEmailTemplate($ID,$from_name,$from_address,$reply_to,$cc,$bcc,$subject,$content,$active); zeroBSCRM_insertEmailTemplate( $ID, $deliveryMethod, $bcc, $subject, $content, $active ); } // IDs // 5 - Task Notification (leave for now)... $ID = 5; $reply_to = ''; $cc = ''; $bcc = ''; // } The email stuff... $subject = __( 'Your scheduled Task starts soon', 'zero-bs-crm' ); $content = zeroBSCRM_mail_retrieveDefaultBodyTemplate( 'tasknotification' ); // BRUTAL DELETE old one (avoids dupes) $wpdb->delete( $ZBSCRM_t['system_mail_templates'], array( 'zbsmail_id' => $ID ) ); $active = 1; // 1 = true.. if ( zeroBSCRM_mailTemplate_exists( $ID ) == 0 ) { $content = zeroBSCRM_mailTemplate_processEmailHTML( $content ); // zeroBSCRM_insertEmailTemplate($ID,$from_name,$from_address,$reply_to,$cc,$bcc,$subject,$content,$active); zeroBSCRM_insertEmailTemplate( $ID, $deliveryMethod, $bcc, $subject, $content, $active ); } // 6 - Client Portal Password Reset // this will be added via a migration for those who've not already got it :) /* just add via migration :) 2962 $ID = 6; $reply_to = ''; $cc = ''; $bcc = ''; #} The email stuff... $subject = __("Your Client Portal Password", 'zero-bs-crm'); $content = zeroBSCRM_mail_retrieveDefaultBodyTemplate('clientportalpwreset'); $active = 1; //1 = true.. if(zeroBSCRM_mailTemplate_exists($ID) == 0){ $content = zeroBSCRM_mailTemplate_processEmailHTML($content); //zeroBSCRM_insertEmailTemplate($ID,$from_name,$from_address,$reply_to,$cc,$bcc,$subject,$content,$active); zeroBSCRM_insertEmailTemplate($ID,$deliveryMethod,$bcc,$subject,$content,$active); } */ } /* ====================================================== / Mail Template DAL ====================================================== */
projects/plugins/crm/includes/jpcrm-templating-placeholders.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * Copyright 2021 Automattic */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* WIP: each placeholder record will have an array such as: {placeholder_model}: array( 'description' => 'Contact ID', 'origin' => 'Contact Object model', 'replace_str' => '##CONTACT-ID##', 'aliases' => array('##CID##'), 'associated_type' => ZBS_TYPE_CONTACT, 'expected_format' => 'str' // future proofing 'available_in' => array( // tooling allowed to use this, from: // if specified, otherwise areas may use type to identify which placeholders are available 'system_email_templates', 'mail_campaigns', 'quote' e.g: 'quote_templates', 'quote_editor', 'invoice' e.g: 'invoice_editor', 'single_email', ) ) */ /** * jpcrm_templating_placeholders is the placeholder layer in Jetpack CRM 4+ * * @author Woody Hayday <hello@jetpackcrm.com> * @version 4.0 * @access public * @see https://kb.jetpackcrm.com */ class jpcrm_templating_placeholders { // default set of placeholders, to get amended on init (Custom fields etc.) private $placeholders = array(); // stores common links e.g. contact fields in quotes // for now these repreresent the 1:1 relational links in the db // later, as the DAL is extended, this could take advantage of // a better mapping integral to the DAL, perhaps extending // the $linkedToObjectTypes system. // for now it's an exception, so hard-typing: private $available_in_links = array( 'contact' => array( 'quote', 'invoice', 'transaction', 'event' ), 'company' => array( // 'quote', 'invoice', 'transaction', 'event' ) ); // =============================================================================== // =========== INIT ============================================================= function __construct($args=array()) { // Build out list of placeholders $this->build_placeholders(); } // =========== / INIT =========================================================== // =============================================================================== /** * Fills out default placeholders * This is executed on init because we want to include the full translatable strings * ... which we cannot set as constants because we want the __() * * @return array of all placeholders */ private function default_placeholders(){ $this->placeholders = array( // CRM global placeholders, e.g. business name (from settings) 'global' => array( 'biz-name' => array( 'description' => __( 'Business name', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##BIZ-NAME##', 'aliases' => array( '###BIZNAME###', '##BIZNAME##' ) ), 'biz-state' => array( 'description' => __( 'Business state', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##BIZ-STATE##', 'aliases' => array( '##BIZSTATE##' ) ), 'biz-logo' => array( 'description' => __( 'Business logo', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##BIZ-LOGO##' ), 'biz-info' => array( 'description' => __( 'Table with your business information (HTML)', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##BIZ-INFO##', 'aliases' => array( '###BIZINFOTABLE###', '###BIZ-INFO###', '###FOOTERBIZDEETS###', '##INVOICE-BIZ-INFO##' ) ), 'biz-your-name' => array( 'description' => __( 'Business: Your Name', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##BIZ-YOUR-NAME##', 'aliases' => array( ) ), 'biz-your-email' => array( 'description' => __( 'Business: Your Email', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##BIZ-YOUR-EMAIL##', 'aliases' => array( ) ), 'biz-your-url' => array( 'description' => __( 'Business: Your URL', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##BIZ-YOUR-URL##', 'aliases' => array( ) ), 'biz-extra' => array( 'description' => __( 'Business: Extra Info', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##BIZ-EXTRA-INFO##', 'aliases' => array( ) ), 'social-links' => array( 'description' => __( 'Social links', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##SOCIAL-LINKS##' ), 'unsub-line' => array( 'description' => __( 'Unsubscribe line', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##UNSUB-LINE##', 'aliases' => array( '###UNSUB-LINE###', '###UNSUB###', '###UNSUBSCRIBE###', '###FOOTERUNSUBDEETS###' ) ), 'powered-by' => array( 'description' => __( 'Powered by', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##POWERED-BY##', 'aliases' => array( '###POWEREDBYDEETS###' ) ), 'login-link' => array( 'description' => __( 'CRM login link (HTML)', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##LOGIN-LINK##', 'aliases' => array( '###LOGINLINK###' ) ), 'login-button' => array( 'description' => __( 'CRM login link button (HTML)', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##LOGIN-BUTTON##', 'aliases' => array( '###LOGINBUTTON###' ) ), 'login-url' => array( 'description' => __( 'CRM login URL', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##LOGIN-URL##', 'aliases' => array( '###LOGINURL###', '###ADMINURL###' ) ), 'portal-link' => array( 'description' => __( 'Portal link (HTML)', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##PORTAL-LINK##', 'aliases' => array( '###PORTALLINK###' ) ), 'portal-view-button' => array( 'description' => __( '"View in Portal" button (HTML)', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##PORTAL-VIEW-BUTTON##', 'aliases' => array( '###VIEWINPORTAL###' ) ), 'portal-button' => array( 'description' => __( 'Portal link button (HTML)', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##PORTAL-BUTTON##', 'aliases' => array( '###PORTALBUTTON###' ) ), 'portal-url' => array( 'description' => __( 'Portal URL', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##PORTAL-URL##', 'aliases' => array( '###PORTALURL###' ) ), 'css' => array( 'description' => __( 'CSS (restricted to HTML templates)', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##CSS##', 'aliases' => array( '###CSS###' ) ), 'title' => array( 'description' => __( 'Generally used to fill HTML title tags', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##TITLE##', 'aliases' => array( '###TITLE###' ) ), 'msg-content' => array( 'description' => __( 'Message content (restricted to some email templates)', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##MSG-CONTENT##', 'aliases' => array( '###MSGCONTENT###' ) ), 'email' => array( 'description' => __( 'Email (generally used to insert user email)', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##EMAIL##', 'aliases' => array( '###EMAIL###' ) ), 'password' => array( 'description' => __( 'Inserts a link where one can reset their password', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##PASSWORD##', 'aliases' => array( '##PASSWORD-RESET-LINK##', '###PASSWORD###' ) ), 'email-from-name' => array( 'description' => __( '"From" Name when sending email', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'email', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##EMAIL-FROM-NAME##', 'aliases' => array( '###FROMNAME###' ) ), ), 'contact' => array( 'contact-fullname' => array( 'description' => __( 'Contact full name', 'zero-bs-crm' ), 'origin' => __( 'Contact Information', 'zero-bs-crm' ), 'available_in' => array(), 'associated_type' => ZBS_TYPE_CONTACT, 'replace_str' => '##CONTACT-FULLNAME##', 'expected_format' => 'str', 'aliases' => array( '##CUSTOMERNAME##', '##CUSTOMER-FULLNAME##' ) ), ), 'company' => array( ), 'quote' => array( 'quote-content' => array( 'description' => __( 'Quote content (HTML)', 'zero-bs-crm' ), 'origin' => __( 'Quote Builder', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => ZBS_TYPE_QUOTE, 'replace_str' => '##QUOTE-CONTENT##', 'aliases' => array( '###QUOTECONTENT###' ) ), 'quote-title' => array( 'description' => __( 'Quote title', 'zero-bs-crm' ), 'origin' => __( 'Quote Builder', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => ZBS_TYPE_QUOTE, 'replace_str' => '##QUOTE-TITLE##', 'aliases' => array( '###QUOTETITLE###', '##QUOTETITLE##' ) ), 'quote-value' => array( 'description' => __( 'Quote value', 'zero-bs-crm' ), 'origin' => __( 'Quote Builder', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => ZBS_TYPE_QUOTE, 'replace_str' => '##QUOTE-VALUE##', 'aliases' => array( '###QUOTEVALUE###', '##QUOTEVALUE##' ) ), 'quote-date' => array( 'description' => __( 'Quote date', 'zero-bs-crm' ), 'origin' => __( 'Quote Builder', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => ZBS_TYPE_QUOTE, 'replace_str' => '##QUOTE-DATE##', 'aliases' => array( '###QUOTEDATE###', '##QUOTEDATE##' ) ), 'quote-url' => array( 'description' => __( 'Quote URL', 'zero-bs-crm' ), 'origin' => __( 'Quote Builder', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => ZBS_TYPE_QUOTE, 'replace_str' => '##QUOTE-URL##', 'aliases' => array( '###QUOTEURL###' ) ), 'quote-edit-url' => array( 'description' => __( 'Quote edit URL', 'zero-bs-crm' ), 'origin' => __( 'Quote Builder', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => ZBS_TYPE_QUOTE, 'replace_str' => '##QUOTE-EDIT-URL##', 'aliases' => array( '###QUOTEEDITURL###' ) ), ), 'invoice' => array( 'invoice-title' => array( 'description' => __( 'Invoice title', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-TITLE##', 'aliases' => array( '###INVOICETITLE###' ) ), 'logo-class' => array( 'description' => __( 'Invoice logo CSS class', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##LOGO-CLASS##', 'aliases' => array( '###LOGOCLASS###' ) ), 'logo-url' => array( 'description' => __( 'Invoice logo URL', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##LOGO-URL##', 'aliases' => array( '###LOGOURL###' ) ), 'invoice-number' => array( 'description' => __( 'Invoice number', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-NUMBER##', 'aliases' => array( '###INVNOSTR###' ) ), 'invoice-date' => array( 'description' => __( 'Invoice date', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-DATE##', 'aliases' => array( '###INVDATESTR###' ) ), 'invoice-id-styles' => array( 'description' => __( 'Invoice ID styles', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-ID-STYLES##', 'aliases' => array( '###INVIDSTYLES###' ) ), 'invoice-ref' => array( 'description' => __( 'Invoice reference', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-REF##', 'aliases' => array( '###REF###' ) ), 'invoice-due-date' => array( 'description' => __( 'Invoice due date', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-DUE-DATE##', 'aliases' => array( '###DUEDATE###' ) ), 'invoice-biz-class' => array( 'description' => __( 'CSS class for table with your business info', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-BIZ-CLASS##', 'aliases' => array( '###BIZCLASS###' ) ), 'invoice-customer-info' => array( 'description' => __( 'Table with assigned contact information (HTML)', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-CUSTOMER-INFO##', 'aliases' => array( '###CUSTINFOTABLE###' ) ), 'invoice-from-name' => array( 'description' => __( 'Name of company issuing the invoice', 'zero-bs-crm' ), 'origin' => __( 'Statement Builder', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-FROM-NAME##', 'aliases' => array() ), 'invoice-table-headers' => array( 'description' => __( 'Table headers for invoice line items (HTML)', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-TABLE-HEADERS##', 'aliases' => array( '###TABLEHEADERS###' ) ), 'invoice-line-items' => array( 'description' => __( 'Invoice line items (HTML)', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-LINE-ITEMS##', 'aliases' => array( '###LINEITEMS###' ) ), 'invoice-totals-table' => array( 'description' => __( 'Invoice totals table (HTML)', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-TOTALS-TABLE##', 'aliases' => array( '###TOTALSTABLE###' ) ), 'pre-invoice-payment-details' => array( 'description' => __( 'Text before invoice payment details', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##PRE-INVOICE-PAYMENT-DETAILS##', 'aliases' => array( '###PREPARTIALS###' ) ), 'invoice-payment-details' => array( 'description' => __( 'Invoice payment details', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-PAYMENT-DETAILS##', 'aliases' => array( '###PAYMENTDEETS###', '###PAYDETAILS###', ) ), 'invoice-partials-table' => array( 'description' => __( 'Invoice partials table (HTML)', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-PARTIALS-TABLE##', 'aliases' => array( '###PARTIALSTABLE###' ) ), 'invoice-label-inv-number' => array( 'description' => __( 'Label for invoice number', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-LABEL-INV-NUMBER##', 'aliases' => array( '###LANGINVNO###' ) ), 'invoice-label-inv-date' => array( 'description' => __( 'Label for invoice date', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-LABEL-INV-DATE##', 'aliases' => array( '###LANGINVDATE###' ) ), 'invoice-label-inv-ref' => array( 'description' => __( 'Label for invoice reference', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-LABEL-INV-REF##', 'aliases' => array( '###LANGINVREF###' ) ), 'invoice-label-from' => array( 'description' => __( 'Label for name of company issuing invoice', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-LABEL-FROM##', 'aliases' => array( '###LANGFROM###' ) ), 'invoice-label-to' => array( 'description' => __( 'Label for name of contact receiving invoice', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-LABEL-TO##', 'aliases' => array( '###LANGTO###' ) ), 'invoice-label-due-date' => array( 'description' => __( 'Label for invoice due date', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-LABEL-DUE-DATE##', 'aliases' => array( '###LANGDUEDATE###' ) ), 'invoice-label-status' => array( 'description' => __( 'Label for invoice status', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-LABEL-STATUS##', 'aliases' => array() ), 'invoice-html-status' => array( 'description' => __( 'Invoice status (HTML)', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-HTML-STATUS##', 'aliases' => array( '###TOPSTATUS###' ) ), 'invoice-pay-button' => array( 'description' => __( 'Invoice pay button (HTML)', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-PAY-BUTTON##', 'aliases' => array( '###PAYPALBUTTON###' ) ), 'invoice-pay-thanks' => array( 'description' => __( 'Invoice payment thanks message (HTML)', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-PAY-THANKS##', 'aliases' => array( '###PAYTHANKS###' ) ), 'invoice-pay-terms' => array( 'description' => __( 'Invoice payment terms (HTML)', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-PAY-TERMS##', 'aliases' => array( '###PAYMENTTERMS###' ) ), 'invoice-statement-html' => array( 'description' => __( 'Invoice statement (HTML)', 'zero-bs-crm' ), 'origin' => __( 'Statement Builder', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-STATEMENT-HTML##', 'aliases' => array( '###STATEMENTHTML###' ) ), 'invoice-ref-styles' => array( 'description' => __( 'CSS attributes applied to invoice reference label', 'zero-bs-crm' ), 'origin' => __( 'Statement Builder', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INVOICE-REF-STYLES##', 'aliases' => array( '###INVREFSTYLES###' ) ), 'invoice-custom-fields' => array( 'description' => __( 'Any custom fields associated with invoice (if enabled in Invoice Settings)', 'zero-bs-crm' ), 'origin' => __( 'Invoice Builder', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => ZBS_TYPE_INVOICE, 'replace_str' => '##INV-CUSTOM-FIELDS##', 'aliases' => array() ), ), 'transaction' => array( ), 'event' => array( 'task-title' => array( 'description' => __( 'Task title', 'zero-bs-crm' ), 'origin' => __( 'Task Scheduler', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => ZBS_TYPE_TASK, 'replace_str' => '##TASK-TITLE##', 'aliases' => array( '###EVENTTITLE###', '##EVENT-TITLE##' ) ), 'task-link' => array( 'description' => __( 'Task link (HTML)', 'zero-bs-crm' ), 'origin' => __( 'Task Scheduler', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => ZBS_TYPE_TASK, 'replace_str' => '##TASK-LINK##', 'aliases' => array( '###EVENTLINK###' ) ), 'task-link-button' => array( 'description' => __( 'Task link button (HTML)', 'zero-bs-crm' ), 'origin' => __( 'Task Scheduler', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => ZBS_TYPE_TASK, 'replace_str' => '##TASK-LINK-BUTTON##', 'aliases' => array( '###EVENTLINKBUTTON###' ) ), 'task-body' => array( 'description' => __( 'Task content (HTML)', 'zero-bs-crm' ), 'origin' => __( 'Task Scheduler', 'zero-bs-crm' ), 'expected_format' => 'html', 'available_in' => array(), 'associated_type' => ZBS_TYPE_TASK, 'replace_str' => '##TASK-BODY##', 'aliases' => array( '###EVENTBODY###' ) ), ), // probably not req. yet: /* 'address', 'form', 'segment', 'log', 'lineitem', 'eventreminder', 'quotetemplate', */ ); return $this->placeholders; } /** * Builds initial list of placeholders using defaults, object-models, custom fields, and filters * * @return array of all placeholders */ public function build_placeholders( $include_custom_fields = true ){ global $zbs; // any hard-typed defaults $placeholders = $this->default_placeholders(); // load fields from DAL object models $placeholders = $this->load_from_object_models( $placeholders, $include_custom_fields ); // some backward compat tweaks: if ( isset( $placeholders['quote']['title'] ) ) $placeholders['quote']['title']['aliases'] = array( '##QUOTE-TITLE##', '##QUOTETITLE##' ); if ( isset( $placeholders['quote']['value'] ) ) $placeholders['quote']['value']['aliases'] = array( '##QUOTEVALUE##' ); if ( isset( $placeholders['quote']['date'] ) ) $placeholders['quote']['date']['aliases'] = array( '##QUOTEDATE##' ); // add setting dependent placeholders $placeholders = $this->add_setting_dependent_placeholders( $placeholders ); // here we fill in any 'available-in' crossovers // e.g. you can reference contacts in quotes. $placeholders = $this->add_available_in( $placeholders ); // filter (to allow extensions to ammend) $this->placeholders = apply_filters( 'jpcrm_templating_placeholders', $placeholders ); // return return $this->placeholders; } /** * Add setting-dependent placeholders * * @return array of all placeholders */ public function add_setting_dependent_placeholders( $placeholders = array() ){ // remove tooling where inactive modules $placeholders = $this->strip_inactive_tooling( $placeholders ); // if ownership model enabled, add 'owner' fields // this is simplistic for now and appears outwardly to only encompasses contacts // ... in fact it works for all object types (provided the object is passed to replace_placeholders()) // as per #1531 this could later be expanded to encompass all objects, perhaps in sites & teams extension $using_ownership = zeroBSCRM_getSetting( 'perusercustomers' ); if ( $using_ownership ){ if ( isset( $placeholders['global'] ) ){ // note, these are auto-populated using the first `owner` field that our replacement function comes across in $replacement_objects $placeholders['global']['assigned-to-name'] = array( 'description' => __( 'Where available, the display name of the WordPress user who owns the object', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'str', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##ASSIGNED-TO-NAME##', 'aliases' => array( '##ASSIGNED-TO-SIGNATURE##' ) ); $placeholders['global']['assigned-to-email'] = array( 'description' => __( 'Where available, the email of the WordPress user who owns the object', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'email', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##ASSIGNED-TO-EMAIL##', 'aliases' => array() ); $placeholders['global']['assigned-to-username'] = array( 'description' => __( 'Where available, the username of the WordPress user who owns the object', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'email', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##ASSIGNED-TO-USERNAME##', 'aliases' => array() ); $placeholders['global']['assigned-to-mob'] = array( 'description' => __( 'Where available, the mobile phone of the WordPress user who owns the object', 'zero-bs-crm' ), 'origin' => __( 'Global', 'zero-bs-crm' ), 'expected_format' => 'tel', 'available_in' => array(), 'associated_type' => false, 'replace_str' => '##ASSIGNED-TO-MOB##', 'aliases' => array() ); } } return $placeholders; } /** * Remove object types where that module is not active, e.g. invoices * This needs to fire before this->add_available_in in the build queue * * @return array of all placeholders */ public function strip_inactive_tooling( $placeholders = array() ){ $setting_map = array( 'form' => 'feat_forms', 'quote' => 'feat_quotes', 'invoice' => 'feat_invs', 'event' => 'feat_calendar', 'transaction' => 'feat_transactions', ); // make a quick state list for simplicity $tooling_states = array(); foreach ( $setting_map as $tooling_area => $setting_key ){ $tooling_states[ $tooling_area ] = (zeroBSCRM_getSetting( $setting_key ) == "1") ? true : false; // remove from placeholder list if ( !$tooling_states[ $tooling_area ] && isset( $placeholders[ $tooling_area ] ) ){ // remove unset( $placeholders[ $tooling_area ] ); } } // remove from $available_in_links too $available_in = array(); foreach ( $this->available_in_links as $object_type_key => $tooling_area_array ){ if ( !isset( $tooling_states[ $object_type_key ] ) || $tooling_states[ $object_type_key ] ){ $tooling_available = array(); foreach ( $tooling_area_array as $tooling_area ){ // add back if not in the list if ( !array_key_exists( $tooling_area, $tooling_states) || $tooling_states[ $tooling_area ] ){ $tooling_available[] = $tooling_area; } } $available_in[ $object_type_key ] = $tooling_available; } } $this->available_in_links = $available_in; // return return $placeholders; } /** * Appends to passed placeholder model based on DAL object models * (optionally) including custom fields where applicable * * @param bool include_custom_fields * * @return int count */ private function load_from_object_models( $placeholders, $include_custom_fields = false, $excluded_slugs = array( // global 'zbs_site', 'zbs_team', 'zbs_owner', 'id_override', 'parent', 'send_attachments', 'hash', // contact 'alias', // quote 'template', 'acceptedsigned', 'acceptedip', // invoice 'pay_via', 'allow_tip', 'allow_partial', 'hash_viewed', 'hash_viewed_count', 'portal_viewed', 'portal_viewed_count', 'pdf_template', 'portal_template', 'email_template', 'invoice_frequency', 'address_to_objtype', // event 'show_on_cal', 'show_on_portal', 'title', ) ){ global $zbs; // retrieve object types $object_types = $zbs->DAL->get_object_types_by_index(); $second_address_label = zeroBSCRM_getSetting( 'secondaddresslabel' ); if ( empty( $second_address_label ) ) { $second_address_label = __( 'Second Address', 'zero-bs-crm' ); } // cycle through them, adding where they have $include_in_templating foreach ( $object_types as $object_type_index => $object_type_key ){ $object_layer = $zbs->DAL->getObjectLayerByType( $object_type_index ); $object_label = $zbs->DAL->typeStr( $object_type_index ); // if there is an object layer available, and it's included in templating: if ( is_object( $object_layer ) && $object_layer->is_included_in_templating() ){ // (optionally) include custom field references if ( $include_custom_fields ){ $object_model = $object_layer->objModelIncCustomFields(); } else { $object_model = $object_layer->objModel(); } // cycle through object model & add fields foreach ( $object_model as $field_index => $field_info ) { // deal with exclusions if ( !in_array( $field_index, $excluded_slugs ) ) { // catching legacy secondary address contact field issues $secondary_address_array = array( 'secaddr1', 'secaddr2', 'seccity', 'seccounty', 'secpostcode', 'seccountry' ); if ( 'contact' === $object_type_key && in_array( $field_index, $secondary_address_array, true ) ) { $field_index = str_replace( 'sec', 'secaddr_', $field_index ); $new_key = $object_type_key . '-' . $field_index; } else { $new_key = str_replace( '_', '-', $object_type_key . '-' . $field_index ); } $expected_format = ''; // add if not present // e.g. $placeholders['contact']['ID'] if ( !isset( $placeholders[ $object_type_key ][ $new_key ] ) ) { // prettify these $description = $object_label . ' ' . $field_index; switch ( $field_index ) { case 'created': $description = sprintf( __( 'Date %s was created', 'zero-bs-crm' ), $object_label ); break; case 'lastupdated': $description = sprintf( __( 'Date %s was last updated', 'zero-bs-crm' ), $object_label ); break; case 'lastcontacted': $description = sprintf( __( 'Date %s was last contacted', 'zero-bs-crm' ), $object_label ); break; case 'tw': $description = sprintf( __( 'Twitter handle for %s', 'zero-bs-crm' ), $object_label ); break; case 'li': $description = sprintf( __( 'LinkedIn handle for %s', 'zero-bs-crm' ), $object_label ); break; case 'fb': $description = sprintf( __( 'Facebook page ID for %s', 'zero-bs-crm' ), $object_label ); break; case 'wpid': $description = sprintf( __( 'WordPress ID for %s', 'zero-bs-crm' ), $object_label ); break; } if ( isset( $field_info['label'] ) ) { $description = $object_label . ' ' . __( $field_info['label'], 'zero-bs-crm' ); } if ( !empty( $field_info['area'] ) && $field_info['area'] == 'Second Address' ) { $description .= ' (' . esc_html( $second_address_label ) . ')'; } // if it's a custom field we can infer format (and label): if ( isset( $field_info['custom-field'] ) && $field_info['custom-field'] == 1 ) { $field_info['format'] = $field_info[0]; if ( $field_info['format'] === 'date' ) { $field_info['format'] = 'uts'; } $description .= ' (' . __( 'Custom Field', 'zero-bs-crm' ) . ')'; } // add {placeholder_model} $placeholders[ $object_type_key ][ $new_key ] = array( 'description' => $description, 'origin' => sprintf( __( '%s object model', 'zero-bs-crm' ), $object_label ), 'available_in' => array(), 'associated_type' => $object_type_index, 'replace_str' => '##' . strtoupper( $object_type_key ) . '-' . strtoupper( $field_index ) . '##', 'expected_format' => $expected_format, ); // trying to future proof, added a few helper attributes: if ( isset( $field_info['format'] ) ) { $placeholders[ $object_type_key ][ $new_key ]['expected_format'] = $field_info['format']; if ( $field_info['format'] === 'uts' && empty( $field_info['autoconvert'] ) ) { $placeholders[ $object_type_key ][ $new_key . '_datetime_str' ] = array( 'description' => $description . ' (' . __( 'DateTime string', 'zero-bs-crm' ) . ')', 'origin' => sprintf( __( '%s object model', 'zero-bs-crm' ), $object_label ), 'available_in' => array(), 'associated_type' => $object_type_index, 'replace_str' => '##' . strtoupper( $object_type_key ) . '-' . strtoupper( $field_index ) . '_DATETIME_STR##', 'expected_format' => 'str', ); $placeholders[ $object_type_key ][ $new_key . '_date_str' ] = array( 'description' => $description . ' (' . __( 'Date string', 'zero-bs-crm' ) . ')', 'origin' => sprintf( __( '%s object model', 'zero-bs-crm' ), $object_label ), 'available_in' => array(), 'associated_type' => $object_type_index, 'replace_str' => '##' . strtoupper( $object_type_key ) . '-' . strtoupper( $field_index ) . '_DATE_STR##', 'expected_format' => 'str', ); } } } } } } } return $placeholders; } /** * Adds `available_in` links to allow tooling to get all applicable fields * e.g. Contact fields will be available in Quote builder * * @param array $placeholders placeholder array * * @return array $placeholders placeholder array */ private function add_available_in( $placeholders ){ // any to add? if ( is_array( $this->available_in_links ) ){ foreach ( $this->available_in_links as $object_type => $tooling_area_array ){ // $object_type = 'contact', $tooling_area = where to point to if ( isset( $placeholders[ $object_type ] ) ){ foreach ( $placeholders[ $object_type ] as $object_type_placeholder_key => $object_type_placeholder ){ // setup if not set if ( !is_array( $placeholders[ $object_type ][ $object_type_placeholder_key ]['available_in'] ) ){ $placeholders[ $object_type ][ $object_type_placeholder_key ]['available_in'] = array(); } // add if not present foreach ( $tooling_area_array as $tooling_area){ if ( !in_array( $tooling_area, $placeholders[ $object_type ][ $object_type_placeholder_key ]['available_in'] )){ $placeholders[ $object_type ][ $object_type_placeholder_key ]['available_in'][] = $tooling_area; } } } } } } return $placeholders; } /** * Returns full list of viable placeholders * * @param bool separate_categories - return in multi-dim array split out by categories * * @return array of all placeholders */ public function get_placeholders( $separate_categories = true ){ global $zbs; // if asked to return without categories, do that if ( !$separate_categories ){ $no_cat_list = array(); foreach ( $this->placeholders as $placeholder_group_key => $placeholder_group ){ foreach ( $placeholder_group as $placeholder_key => $placeholder ){ $no_cat_list[ $placeholder['replace_str'] ] = $placeholder; // any aliases too if ( isset( $placeholder['aliases'] ) && is_array( $placeholder['aliases'] ) ) { foreach ( $placeholder['aliases'] as $alias ){ $no_cat_list[ $alias ] = $placeholder; } } } } return $no_cat_list; } return $this->placeholders; } /** * Returns flattened list of viable placeholders * * @return array of all placeholders */ public function get_placeholders_shorthand(){ global $zbs; $shorthand_list = array(); foreach ( $this->placeholders as $placeholder_group_key => $placeholder_group ){ $placeholder_group_prefix = ''; // all objtypes basically if ( $zbs->DAL->isValidObjTypeID( $zbs->DAL->objTypeID( $placeholder_group_key ) ) ) { $placeholder_group_prefix = $placeholder_group_key . '-'; } foreach ( $placeholder_group as $placeholder_key => $placeholder ){ $shorthand_list[] = '##' . strtoupper( $placeholder_group_prefix . $placeholder_key ) . '##'; // any aliases too if ( isset( $placeholder['aliases'] ) && is_array( $placeholder['aliases'] ) ) { foreach ( $placeholder['aliases'] as $alias ){ $shorthand_list[] = $alias; } } } } return $shorthand_list; } /** * Returns list of viable placeholders for specific tooling/area, or group of areas, or object types, e.g. system emails or contact * * @param array|string tooling area, object type, or group of * @param bool hydrate_aliases - if true Aliases will be included as full records * @param bool split_by_category - if true return will be split by category as per get_placeholders * * @return array placeholders */ public function get_placeholders_for_tooling( $tooling = array('global'), $hydrate_aliases = false, $split_by_category = false ){ global $zbs; $applicable_placeholders = array(); // we allow array or string input here, so if a string, wrap for below if ( is_string( $tooling ) ) $tooling = array( $tooling ); // for MVP we let this get the whole lot then filter down, if this proves unperformant we could optimise here // .. or cache. $placeholders = $this->get_placeholders( ); // cycle through all looking at the `available_in` attribute. // alternatively if an object type is passed, it'll return all fields for that type if ( is_array( $placeholders ) ){ foreach ( $placeholders as $placeholder_group_key => $placeholder_group ){ $placeholder_group_prefix = ''; // all objtypes basically if ( $zbs->DAL->isValidObjTypeID( $zbs->DAL->objTypeID( $placeholder_group_key ) ) ) { $placeholder_group_prefix = $placeholder_group_key . '-'; } foreach ( $placeholder_group as $placeholder_key => $placeholder ){ // if in object type group: if ( in_array( $placeholder_group_key, $tooling ) || isset( $placeholder['available_in'] ) && count( array_intersect( $tooling, $placeholder['available_in']) ) > 0 ){ // here we've flattened the array to actual placeholders (no tooling group) // so use the placeholder str as key and add original id to array $key = '##' . strtoupper( $placeholder_group_prefix . $placeholder_key ) . '##'; if ( isset( $placeholder['replace_str'] ) ){ // this overrides if set (will always be the same?) $key = $placeholder['replace_str']; } // if return in categories if ( $split_by_category ){ if ( !isset( $applicable_placeholders[ $placeholder_group_key ] ) || !is_array( $applicable_placeholders[ $placeholder_group_key ] ) ){ $applicable_placeholders[ $placeholder_group_key ] = array(); } $applicable_placeholders[ $placeholder_group_key ][ $key ] = $placeholder; // add original key to arr $applicable_placeholders[ $placeholder_group_key ][ $key ]['key'] = $placeholder_key; } else { $applicable_placeholders[ $key ] = $placeholder; // add original key to arr $applicable_placeholders[ $key ]['key'] = $placeholder_key; } // aliases if ( $hydrate_aliases && isset( $placeholder['aliases'] ) && is_array( $placeholder['aliases'] ) ) { foreach ( $placeholder['aliases'] as $alias ){ // if return in categories if ( $split_by_category ){ $applicable_placeholders[ $placeholder_group_key ][ $alias ] = $placeholder; } else { $applicable_placeholders[ $alias ] = $placeholder; } } } } } } } return $applicable_placeholders; } /** * Returns a single placeholder info array based on a key * * @param string placeholder key * * @return array placeholder info */ public function get_single_placeholder_info( $placeholder = '' ){ // cycle through placeholders and return our match foreach ( $this->placeholders as $placeholder_area => $placeholders ){ foreach ( $placeholders as $key => $placeholder_info ){ if ( $key == $placeholder ){ return $placeholder_info; } } } return false; } /* * Returns a template-friendly placeholder array of generic replacements */ public function get_generic_replacements(){ global $zbs; // vars $login_url = admin_url( 'admin.php?page=' . $zbs->slugs['dash'] ); $portal_url = zeroBS_portal_link(); $biz_name = zeroBSCRM_getSetting( 'businessname' ); $biz_your_name = zeroBSCRM_getSetting( 'businessyourname' ); $biz_your_email = zeroBSCRM_getSetting( 'businessyouremail' ); $biz_your_url = zeroBSCRM_getSetting( 'businessyoururl' ); $biz_extra = zeroBSCRM_getSetting( 'businessextra' ); $biz_info = zeroBSCRM_invoicing_generateInvPart_bizTable( array( 'zbs_biz_name' => $biz_name, 'zbs_biz_yourname' => $biz_your_name, 'zbs_biz_extra' => $biz_extra, 'zbs_biz_youremail' => $biz_your_email, 'zbs_biz_yoururl' => $biz_your_url, 'template' => 'pdf', ) ); $social_links = show_social_links(); // return return array( // login 'login-link' => '<a href="' . $login_url . '">' . __( 'Go to CRM', 'zero-bs-crm' ) . '</a>', 'login-button' => '<div style="text-align:center;margin:1em;margin-top:2em">'.zeroBSCRM_mailTemplate_emailSafeButton( $login_url, __( 'Go to CRM', 'zero-bs-crm' ) ).'</div>', 'login-url' => $login_url, // portal 'portal-link' => '<a href="' . $portal_url . '">' . $portal_url . '</a>', 'portal-button' => '<div style="text-align:center;margin:1em;margin-top:2em">'.zeroBSCRM_mailTemplate_emailSafeButton( $portal_url, __( 'View Portal', 'zero-bs-crm' ) ).'</div>', 'portal-url' => $portal_url, // biz stuff 'biz-name' => $biz_name, 'biz-your-name' => $biz_your_name, 'biz-your-email' => $biz_your_email, 'biz-your-url' => $biz_your_url, 'biz-info' => $biz_info, 'biz-extra' => $biz_extra, 'biz-logo' => jpcrm_business_logo_img( '150px' ), // general 'powered-by' => zeroBSCRM_mailTemplate_poweredByHTML(), 'email-from-name' => zeroBSCRM_mailDelivery_defaultFromname(), 'password' => '<a href="' . wp_lostpassword_url() . '" title="' . __( 'Lost Password', 'zero-bs-crm' ) . '">'. __('Set Your Password', 'zero-bs-crm').'</a>', // social 'social-links' => $social_links, ); } /** * Enacts single string replacement on a passed string based on passed tooling/areas * Note: It's recommended to use this function even though str_replace would be approximate * - Using this accounts for multiple aliases, e.g. ###MSG-CONTENT### and ##MSG-CONTENT##, and keeps things centralised * * @param string string of placeholder to replace, e.g. 'msg-content' * @param string string to apply replacements to * @param string string to replace placeholder with * * @return string modified string */ public function replace_single_placeholder( $placeholder_key = '', $replace_with = '', $string = '' ){ // get info $placeholder_info = $this->get_single_placeholder_info( $placeholder_key ); // exists? if ( is_array( $placeholder_info ) ) { // auto-gen $main_placeholder_key = $this->make_placeholder_str( $placeholder_key ); // if replace_str is set, use that if ( isset( $placeholder_info['replace_str'] ) ){ $main_placeholder_key = $placeholder_info['replace_str']; } // replace any and all variants (e.g. aliases) // we do these first, as often in our case the variants are backward-compat // and so `###BIZ-INFO###` needs replacing before `##BIZ-INFO##` if ( isset( $placeholder_info['aliases'] ) && is_array( $placeholder_info['aliases'] ) ){ $string = str_replace( $placeholder_info['aliases'], $replace_with, $string ); } // replace $string = str_replace( $main_placeholder_key, $replace_with, $string ); } else { // not in index, replace requested placeholder: $string = str_replace( $this->make_placeholder_str( $placeholder_key ), $replace_with, $string ); } return $string; } /** * Enacts replacements on a string based on passed tooling/areas * Note: Using this method allows non-passed values to be emptied, * e.g. if 'global' tooling method, and no 'unsub-line' value passed, * any mentions of '##UNSUB-LINE##' will be taken out of $string * * @param array|string tooling - tooling area, object type, or group of * @param string string - to apply replacements to * @param array replacements - array of replacement values * @param array|false replacement_objects - an array of objects to replace fields from (e.g. contact) Should be keyed by object type, in the format array[ZBS_TYPE_CONTACT] = contact array * @param bool retain_unset_placeholders - bool whether or not to retain empty-valued placeholders (e.g. true = leaves ##BIZ-LOGO## in string if no value for 'biz-logo') * * @return string modified string */ public function replace_placeholders( $tooling = array( 'global' ), $string = '', $replacements = array(), $replacement_objects = false, $retain_unset_placeholders = false, $keys_staying_unrendered = array() ) { // retrieve replacements for this tooling $to_replace = $this->get_placeholders_for_tooling( $tooling ); // cycle through replacements and replace where possible if ( is_array( $to_replace ) ) { foreach ( $to_replace as $replace_string => $replacement_info ) { // ##BIZ-STATE## -> biz-state $key = str_replace( '#', '', strtolower( $replace_string ) ); if ( isset( $replacement_info['key'] ) && !empty( $replacement_info['key'] ) ) { $key = $replacement_info['key']; } // attempt to find value in $replacements $replace_with = ''; if ( isset( $replacements[ $key ] ) ) { $replace_with = $replacements[ $key ]; } // attempt to find value in $replacement_objects // ... if $replacements[value] not already set (that overrides) // here $key will be 'contact-prefix' // .. which would map to $replacement_objects[ZBS_TYPE_CONTACT]['prefix'] if ( empty( $replace_with ) ){ // attempt to pluck relative value $potential_value = $this->pick_from_replacement_objects( $key, $replacement_objects ); if ( !empty( $potential_value ) ) { $replace_with = $potential_value; } } // if $key is 'assigned-to-name', 'assigned-to-email', 'assigned-to-mob' - seek out an owner. // ... if $replacements[assigned-to-name] not already set (that overrides) if ( empty( $replace_with ) && in_array( $key, array( 'assigned-to-name', 'assigned-to-email', 'assigned-to-username', 'assigned-to-mob' ) ) && is_array( $replacement_objects ) ){ $owner_value = ''; $owner_info = $this->owner_from_replacement_objects( $replacement_objects ); if ( $owner_info ){ switch ( $key ){ case 'assigned-to-name': $owner_value = $owner_info->display_name; break; case 'assigned-to-username': $owner_value = $owner_info->user_login; break; case 'assigned-to-email': $owner_value = $owner_info->user_email; break; case 'assigned-to-mob': $owner_value = zeroBS_getWPUsersMobile($owner_info->ID); break; } // got value? if ( !empty( $owner_value ) ) { $replace_with = $owner_value; } } } // replace (if not empty + retain_unset_placeholders) if ( !$retain_unset_placeholders || ( $retain_unset_placeholders && !empty( $replace_with ) ) ){ // here we hit a problem, we've been wild with our ### use, so now we // have a mixture of ## and ### references. // ... wherever we have ### we must replace them first, // ... to avoid ###A### being pre-replaced by ##A## // for now, replacing aliases first solves this. // aliases if ( isset( $replacement_info['aliases'] ) && is_array( $replacement_info['aliases'] ) ){ $string = str_replace( $replacement_info['aliases'], $replace_with, $string ); } // If this is a Quote date key and is not set (Quote accepted or last viewed), let's print out a message saying the quote isn't accepted or viewed. if ( in_array( $key, array( 'quote-accepted', 'quote-lastviewed' ), true ) && ! in_array( $replacement_info['key'], $keys_staying_unrendered, true ) && ( empty( $replace_with ) || jpcrm_date_str_to_uts( $replace_with ) === 0 ) ) { if ( $key === 'quote-accepted' ) { $replace_with = __( 'Quote not yet accepted', 'zero-bs-crm' ); $string = str_replace( '##QUOTE-ACCEPTED_DATETIME_STR##', $replace_with, $string ); $string = str_replace( '##QUOTE-ACCEPTED_DATE_STR##', $replace_with, $string ); } else { $replace_with = __( 'Quote not yet viewed', 'zero-bs-crm' ); $string = str_replace( '##QUOTE-LASTVIEWED_DATETIME_STR##', $replace_with, $string ); $string = str_replace( '##QUOTE-LASTVIEWED_DATE_STR##', $replace_with, $string ); } } // Replace main key. if ( empty( $keys_staying_unrendered ) || ! in_array( $replacement_info['key'], $keys_staying_unrendered, true ) ) { $string = str_replace( $replace_string, $replace_with, $string ); } } } } return $string; } /** * Takes an array of replacement_objects and a target string * ... and returns a value if it can pick one from replacement_objects * ... e.g. target_string = 'contact-fname' * ... = * ... replacement_objects[ZBS_TYPE_CONTACT]['fname'] * * @param string target string e.g. `contact-fname` * @param array|bool replacement objects, keyed to object type - (e.g. contact) Should be in the format array[ZBS_TYPE_CONTACT] = contact array * * @return string valid placeholder string */ private function pick_from_replacement_objects( $target_string = '', $replacement_objects = array() ) { global $zbs; // got string and replacement objects? if ( !empty( $target_string ) && is_array( $replacement_objects ) && count( $replacement_objects ) > 0 ) { // retrieve object-type from $target_string (where possible) $target_exploded = explode( '-', $target_string, 2 ); if ( is_array( $target_exploded ) && count( $target_exploded ) > 1 ) { // convert `contact` to ZBS_TYPE_CONTACT (1) $object_type_id = $zbs->DAL->objTypeID( $target_exploded[0] ); // validate obj type id and check if it's passed in replacement_objects if ( $zbs->DAL->isValidObjTypeID( $object_type_id ) && isset( $replacement_objects[ $object_type_id ] ) ) { // at this point we turn `contact-fname` into `fname` and we pluck it from `$replacement_objects[ ZBS_TYPE_CONTACT ]['fname']` if it's set array_shift( $target_exploded ); $field_name = strtolower( $target_exploded[0] ); if ( isset( $replacement_objects[ $object_type_id ][ $field_name ] ) && !empty( $replacement_objects[ $object_type_id ][ $field_name ] ) ) { // successful find return $replacement_objects[ $object_type_id ][ $field_name ]; } // check for potential fallback fields if ( preg_match( '/_datetime_str$/', $field_name ) ) { $potential_uts_field = str_replace( '_datetime_str', '', $field_name ); if ( isset( $replacement_objects[ $object_type_id ][ $potential_uts_field ] ) ) { $potential_uts_value = $replacement_objects[ $object_type_id ][ $potential_uts_field ]; if ( jpcrm_is_int( $potential_uts_value ) ) { return jpcrm_uts_to_datetime_str( $potential_uts_value ); } else { // use original value as fallback return $potential_uts_value; } } } elseif ( preg_match( '/_date_str$/', $field_name ) ) { $potential_uts_field = str_replace( '_date_str', '', $field_name ); if ( isset( $replacement_objects[ $object_type_id ][ $potential_uts_field ] ) ) { $potential_uts_value = $replacement_objects[ $object_type_id ][ $potential_uts_field ]; if ( jpcrm_is_int( $potential_uts_value ) ) { return jpcrm_uts_to_date_str( $potential_uts_value ); } else { // use original value as fallback return $potential_uts_value; } } } } } } return false; } /** * Takes an array of replacement_objects and returns WordPress user info * for the first owner it finds in $replacement_objects * * @param array|bool replacement objects, keyed to object type - (e.g. contact) Should be in the format array[ZBS_TYPE_CONTACT] = contact array * * @return string WordPress user info (get_userdata) */ private function owner_from_replacement_objects( $replacement_objects = array() ){ // got string and replacement objects? if ( is_array( $replacement_objects ) && count( $replacement_objects ) > 0 ) { foreach ( $replacement_objects as $replacement_obj_type => $replacement_object){ // is `owner` set? if ( isset( $replacement_object['owner'] ) && !empty( $replacement_object['owner'] ) ){ // one of the passed replacement objects has an owner... first passed first served $user_info = get_userdata($replacement_object['owner']); if ( $user_info !== false){ return $user_info; } } } } return false; } /** * Takes a key (e.g. msg-content) and returns in valid placeholder * format. (e.g. ##MSG-CONTENT##) * * @param string placeholder key * * @return string valid placeholder string */ public function make_placeholder_str( $placeholder_key = '' ){ return '##' . str_replace( '_', '-', trim( strtoupper( $placeholder_key ) ) ) . '##'; } /** * Draws WYSIWYG Typeahead (Bloodhound JS) * * @param string select - HTML ID to give to the placeholder select * @param string insert_target_id - HTML ID which the placeholder should insert into when a placeholder is selected * @param array|string tooling - placeholder array of tooling areas to include, if 'all' string passed, all placeholders will be shown * @param array return - return or echo? * * @return string valid placeholder string */ public function placeholder_selector( $id = '', $insert_target_id = '', $tooling = array('global'), $return = false, $extra_classes = '' ){ $placeholder_list = array(); // Simpler <select> if ( is_array( $tooling ) ){ // retrieve placeholder list (divided by category) $placeholder_list = $this->get_placeholders_for_tooling( $tooling, false, true ); } else { // retrieve placeholder list (divided by category) $placeholder_list = $this->get_placeholders( true ); } $html = '<div class="jpcrm-placeholder-select-wrap '.$extra_classes.'">'; $html .= '<select id="' . $id .'" data-target="' . $insert_target_id . '" class="jpcrm-placeholder-select ui compact selection dropdown">'; // blank option $html .= '<option value="-1">' . __( 'Insert Placeholder', 'zero-bs-crm' ) . '</option>'; $html .= '<option value="-1" disabled="disabled">====================</option>'; // cycle through categories of placeholders: if ( is_array( $placeholder_list ) && count( $placeholder_list ) > 0 ){ foreach ( $placeholder_list as $placeholder_group_key => $placeholder_group ){ $html .= '<optgroup label="' . ucwords( $placeholder_group_key ) . '">'; foreach ( $placeholder_group as $placeholder_key => $placeholder_info ){ // value // if no replace_str attr... $placeholder_str = $this->make_placeholder_str( $placeholder_group_key . '-' . $placeholder_key ); if ( isset( $placeholder_info['replace_str'] ) ){ $placeholder_str = $placeholder_info['replace_str']; } // label $placeholder_label = ( isset( $placeholder_info['description'] ) && !empty( $placeholder_info['description'] ) ) ? $placeholder_info['description'] . ' (' . $placeholder_str .')' : $placeholder_str; $html .= '<option value="' . $placeholder_str . '">' . $placeholder_label . '</option>'; } $html .= '</optgroup>'; } } else { $html .= '<option value="-1">' . __( 'No Placeholders Available', 'zero-bs-crm' ) . '</option>'; } $html .= '</select><i class="code icon"></i></div>'; if ( !$return ){ echo $html; } return $html; } /** * Collates and tidies the full output of placeholders into a simpler array (for placeholder selector typeahead primarily) * * @param array placeholders - array of placeholders, probably from $this->get_placeholders or $this->get_placeholders_for_tooling (Note this requires non-categorised array) * * @return array placeholders - simplified array */ public function simplify_placeholders( $placeholders = array() ){ $return = array(); // cycle through and simplify foreach ( $placeholders as $key => $info ){ $placeholder = $info; // unset non-key unset( $placeholder['available_in'], $placeholder['associated_type'] ); // if return_str not set and key is, add it if ( !isset( $placeholder['replace_str'] ) ){ $placeholder['replace_str'] = $key; } $return[] = $placeholder; } return $return; } /** * Collates and tidies the full output of placeholders into a simpler array (designed for wysiwyg select insert - e.g. quotebuilder) * * @param array placeholders - array of placeholders, probably from $this->get_placeholders or $this->get_placeholders_for_tooling (Note this requires non-categorised array) * * @return array placeholders - simplified array (array[{text:desc,value:placeholder}]) */ public function simplify_placeholders_for_wysiwyg( $placeholders = array() ){ $return = array(); // cycle through and simplify foreach ( $placeholders as $placeholder_key => $placeholder_info ){ // label $placeholder_label = ( isset( $placeholder_info['description'] ) && !empty( $placeholder_info['description'] ) ) ? $placeholder_info['description'] . ' (' . $placeholder_key .')' : $placeholder_key; $return[] = array( 'text' => $placeholder_label, 'value' => $placeholder_key); } return $return; } }
projects/plugins/crm/includes/class-encryption.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * Encryption wrapper * */ namespace Automattic\JetpackCRM; // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; class Encryption { private $cipher = 'aes-256-gcm'; // AES-256-GCM Cipher we're going to use to encrypt - previously we used AES-256-CBC private $cipher_fallback = 'aes-256-cbc'; // AES-256-CBC is our fallback private $tag_length = 16; // AES GCM tag length (MAC) private $default_key = false; private $ready_to_encrypt = true; /** * Setup */ public function __construct() { // check if we have the algorhithm we want to use, and fall back if not $this->check_cipher_and_fallback(); } /* * check if we have the algorhithm we want to use, and fall back if not */ public function check_cipher_and_fallback(){ global $zbs; // check if has flipped fallback previously $fallback_blocked = zeroBSCRM_getSetting( 'enc_fallback_blocked' ); if ( !empty( $fallback_blocked ) ) { // doesn't even have fallback. Non encrypting!! $this->ready_to_encrypt = false; // error loading encryption echo zeroBSCRM_UI2_messageHTML( 'warning', __( 'Unable to load encryption method', 'zero-bs-crm' ), sprintf ( __( 'CRM was unable to load the required encryption method (%s). Until this is method is available to your PHP your sensitive data may not be encrypted properly.', 'zero-bs-crm' ), $this->cipher ) ); return; } // check if has flipped fallback previously $fallback_active = zeroBSCRM_getSetting( 'enc_fallback_active' ); if ( !empty( $fallback_active ) ) { // has fallback. Let's use that: $this->cipher = $this->cipher_fallback; return; } $available_cipher_methods = openssl_get_cipher_methods(); // check for our method if ( !in_array( $this->cipher, $available_cipher_methods ) ){ // try fallback if ( in_array( $this->cipher_fallback, $available_cipher_methods ) ){ // has fallback. Let's use that: $this->cipher = $this->cipher_fallback; // set option so we get 'stuck' in this mode $zbs->settings->update( 'enc_fallback_active', $this->cipher ); } else { // neither method. Present error $this->ready_to_encrypt = false; // set option so we get 'stuck' in this mode $zbs->settings->update( 'enc_fallback_blocked', 1 ); // error loading encryption echo zeroBSCRM_UI2_messageHTML( 'warning', __( 'Unable to load encryption method', 'zero-bs-crm' ), sprintf ( __( 'CRM was unable to load the required encryption method (%s). Until this is method is available to your PHP your sensitive data may not be encrypted properly.', 'zero-bs-crm' ), $this->cipher ) ); } } } /* * Ready to encrypt? */ public function ready_to_encrypt(){ return $this->ready_to_encrypt; } /* * Cipher method */ public function cipher_method(){ return $this->cipher; } /* * Encrypts a string */ public function encrypt( $data, $key = false ){ if ( $this->ready_to_encrypt ){ // retrieve encryption key (or default if false) $encryption_key = $this->encryption_key( $key ); // encrypt $iv_length = openssl_cipher_iv_length( $this->cipher ); $iv = openssl_random_pseudo_bytes( $iv_length ); $tag = ''; // will be filled by openssl_encrypt $encrypted = openssl_encrypt( $data, $this->cipher, $encryption_key, OPENSSL_RAW_DATA, $iv, $tag, '', $this->tag_length ); return base64_encode( $iv . $encrypted . $tag ); } else { // if we can't encrypt, store unencrypted, (having warned the user) return $data; } } /* * Decrypts a string */ public function decrypt( $encrypted_data, $key = false ){ if ( $this->ready_to_encrypt ){ // retrieve encryption key (or default if false) $encryption_key = $this->encryption_key( $key ); // break up encrypted string into parts $encrypted = base64_decode( $encrypted_data ); $iv_len = openssl_cipher_iv_length( $this->cipher ); $iv = substr( $encrypted, 0, $iv_len ); $ciphertext = substr( $encrypted, $iv_len, -$this->tag_length ); $tag = substr( $encrypted, -$this->tag_length ); return openssl_decrypt( $ciphertext, $this->cipher, $encryption_key, OPENSSL_RAW_DATA, $iv, $tag ); } else { // if we can't encrypt, store unencrypted, (having warned the user) return $encrypted_data; } } /* * Retrieves or generates an encryption key from data store * * @param string $key - a key to make an encryption key for */ public function get_encryption_key( $key ){ global $zbs; $encryption_key = zeroBSCRM_getSetting( 'enc_' . $key ); if ( empty( $encryption_key ) ) { // Creating a 256 bit key. This might need to change if the algorithm changes $encryption_key = openssl_random_pseudo_bytes( 32 ); $zbs->settings->update( 'enc_' . $key, bin2hex( $encryption_key ) ); } else { $encryption_key = hex2bin( $encryption_key ); } return $encryption_key; } /* * Retrieves default key */ public function get_default_encryption_key( ){ // cached? if ( !empty( $this->default_key ) ){ return $this->default_key; } // retrieve $default_key = $this->get_encryption_key( 'jpcrm_core' ); // cache $this->default_key = $default_key; return $default_key; } /* * Returns an encryption key, or default encryption key if no key passed */ public function encryption_key( $key ){ // retrieve encryption key if ( !empty( $key ) ){ // retrieve encryption key for $key return $this->get_encryption_key( $key ); } else { // use default key return $this->get_default_encryption_key(); } } /* * Returns random hex string. The returned string length will be 2x the input bytes. * * Inspired by WooCommerce: wc_rand_hash() * * @param int $bytes - number of bytes to generate a hash from * * @return str */ public function get_rand_hex( $bytes = 20 ) { return bin2hex( openssl_random_pseudo_bytes( (int)$bytes ) ); } /** * Returns hashed string. * * Inspired by WooCommerce: wc_api_hash() * * @param str $str - string to hash * * @return str **/ public function hash( $str ) { return hash_hmac( 'sha256', $str, 'jpcrm' ); } }
projects/plugins/crm/includes/ZeroBSCRM.AdminStyling.php
<?php /* ! * Jetpack CRM * https://jetpackcrm.com * V1.20 * * Copyright 2020 Automattic * * Date: 01/11/16 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) { exit; } /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== Jetpack CRM Closers - WH - these would be better as transients IMO These allow you to "x" things in ZBS and persist the state ====================================================== */ // } Returns a timestamp or false, depending on if a "closer" has been logged // } see zeroBSCRM_AJAX_logClose function zeroBSCRM_getCloseState( $key = '' ) { if ( ! empty( $key ) ) { return get_option( 'zbs_closers_' . $key, false ); } return false; } // } Removes close state function zeroBSCRM_clearCloseState( $key = '' ) { if ( ! empty( $key ) ) { return delete_option( 'zbs_closers_' . $key ); } return false; } /* ====================================================== / Jetpack CRM Closers ====================================================== */ /* ====================================================== WordPress Button/Text Overides (could end up in language inc?) ====================================================== */ // } WH10 http://wordpress.stackexchange.com/questions/15357/edit-the-post-updated-view-post-link // use: add_filter('post_updated_messages', 'zeroBSCRM_improvedPostMsgsBookings'); on init function zeroBSCRM_improvedPostMsgsCustomers( $messages ) { // print_r($messages); exit(); $messages['post'] = array( 0 => '', // Unused. Messages start at index 1. 1 => sprintf( /* Translators: %s: link to the main Contacts page */ __( 'Contact updated. <a href="%s">Back to Contacts</a>', 'zero-bs-crm' ), esc_url( 'edit.php?post_type=zerobs_customer&page=manage-customers' ) ), 2 => __( 'Contact updated.', 'zero-bs-crm' ), 3 => __( 'Contact field deleted.', 'zero-bs-crm' ), 4 => __( 'Contact updated.', 'zero-bs-crm' ), /* translators: %s: date and time of the revision */ 5 => isset( $_GET['revision'] ) ? sprintf( __( 'Contact restored to revision from %s', 'zero-bs-crm' ), wp_post_revision_title( (int) sanitize_text_field( $_GET['revision'] ), false ) ) : false, // phpcs:ignore WordPress.Security.NonceVerification.Recommended,WordPress.Security.ValidatedSanitizedInput.MissingUnslash 6 => sprintf( /* Translators: %s: link to the main Contacts page */ __( 'Contact added. <a href="%s">Back to Contacts</a>', 'zero-bs-crm' ), esc_url( 'edit.php?post_type=zerobs_customer&page=manage-customers' ) ), 7 => __( 'Contact saved.', 'zero-bs-crm' ), 8 => sprintf( /* Translators: %s: link to the main Contacts page */ __( 'Contact submitted. <a target="_blank" href="%s">Back to Contacts</a>', 'zero-bs-crm' ), esc_url( 'edit.php?post_type=zerobs_customer&page=manage-customers' ) ), 9 => '', 10 => sprintf( /* Translators: %s: link to the main Contacts page */ __( 'Contact draft updated. <a target="_blank" href="%s">Back to Contacts</a>', 'zero-bs-crm' ), esc_url( 'edit.php?post_type=zerobs_customer&page=manage-customers' ) ), ); return $messages; } function zeroBSCRM_improvedPostMsgsCompanies( $messages ) { // print_r($messages); exit(); $messages['post'] = array( 0 => '', // Unused. Messages start at index 1. 1 => sprintf( __( jpcrm_label_company() . ' updated. <a href="%s">Back to ' . jpcrm_label_company( true ) . '</a>', 'zero-bs-crm' ), esc_url( 'edit.php?post_type=zerobs_company&page=manage-companies' ) ), // get_permalink($post_ID) ) ), 2 => __( jpcrm_label_company() . ' updated.', 'zero-bs-crm' ), 3 => __( jpcrm_label_company() . ' field deleted.', 'zero-bs-crm' ), 4 => __( jpcrm_label_company() . ' updated.', 'zero-bs-crm' ), /* translators: %s: date and time of the revision */ 5 => isset( $_GET['revision'] ) ? sprintf( __( jpcrm_label_company() . ' restored to revision from %s', 'zero-bs-crm' ), wp_post_revision_title( (int) sanitize_text_field( $_GET['revision'] ), false ) ) : false, 6 => sprintf( __( jpcrm_label_company() . ' added. <a href="%s">Back to ' . jpcrm_label_company( true ) . '</a>', 'zero-bs-crm' ), esc_url( 'edit.php?post_type=zerobs_company&page=manage-companies' ) ), // get_permalink($post_ID) ) ),//esc_url( get_permalink($post_ID) ) ), 7 => __( jpcrm_label_company() . ' saved.', 'zero-bs-crm' ), 8 => sprintf( __( jpcrm_label_company() . ' submitted. <a target="_blank" href="%s">Back to ' . jpcrm_label_company( true ) . '</a>', 'zero-bs-crm' ), esc_url( 'edit.php?post_type=zerobs_company&page=manage-companies' ) ), // esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ), 9 => '', // sprintf( ), //get_permalink($post_ID) ) ),//esc_url( get_permalink($post_ID) ) ), 10 => sprintf( __( jpcrm_label_company() . ' draft updated. <a target="_blank" href="%s">Back to ' . jpcrm_label_company( true ) . '</a>', 'zero-bs-crm' ), esc_url( 'edit.php?post_type=zerobs_customer&page=manage-companies' ) ), // get_permalink($post_ID) ) ),//esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ), ); return $messages; } function zeroBSCRM_improvedPostMsgsInvoices( $messages ) { // print_r($messages); exit(); $messages['post'] = array( 0 => '', // Unused. Messages start at index 1. 1 => sprintf( __( 'Invoice updated. <a href="%s">Back to Invoices</a>', 'zero-bs-crm' ), esc_url( 'edit.php?post_type=zerobs_invoice&page=manage-invoices' ) ), // get_permalink($post_ID) ) ), 2 => __( 'Invoice updated.', 'zero-bs-crm' ), 3 => __( 'Invoice field deleted.', 'zero-bs-crm' ), 4 => __( 'Invoice updated.', 'zero-bs-crm' ), /* translators: %s: date and time of the revision */ 5 => isset( $_GET['revision'] ) ? sprintf( __( 'Invoice restored to revision from %s', 'zero-bs-crm' ), wp_post_revision_title( (int) sanitize_text_field( $_GET['revision'] ), false ) ) : false, 6 => sprintf( __( 'Invoice added. <a href="%s">Back to Invoices</a>', 'zero-bs-crm' ), esc_url( 'edit.php?post_type=zerobs_invoice&page=manage-invoices' ) ), // get_permalink($post_ID) ) ),//esc_url( get_permalink($post_ID) ) ), 7 => __( 'Invoice saved.', 'zero-bs-crm' ), 8 => sprintf( __( 'Invoice submitted. <a target="_blank" href="%s">Back to Invoices</a>', 'zero-bs-crm' ), esc_url( 'edit.php?post_type=zerobs_invoice&page=manage-invoices' ) ), // esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ), 9 => '', // sprintf( ), //get_permalink($post_ID) ) ),//esc_url( get_permalink($post_ID) ) ), 10 => sprintf( __( 'Invoice draft updated. <a target="_blank" href="%s">Back to Invoices</a>', 'zero-bs-crm' ), esc_url( 'edit.php?post_type=zerobs_invoice&page=manage-invoices' ) ), // get_permalink($post_ID) ) ),//esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ), ); return $messages; } function zeroBSCRM_improvedPostMsgsQuotes( $messages ) { // print_r($messages); exit(); $messages['post'] = array( 0 => '', // Unused. Messages start at index 1. 1 => sprintf( __( 'Quote updated. <a href="%s">Back to Quotes</a>', 'zero-bs-crm' ), esc_url( 'edit.php?post_type=zerobs_quote&page=manage-quotes' ) ), // get_permalink($post_ID) ) ), 2 => __( 'Quote updated.', 'zero-bs-crm' ), 3 => __( 'Quote field deleted.', 'zero-bs-crm' ), 4 => __( 'Quote updated.', 'zero-bs-crm' ), /* translators: %s: date and time of the revision */ 5 => isset( $_GET['revision'] ) ? sprintf( __( 'Quote restored to revision from %s', 'zero-bs-crm' ), wp_post_revision_title( (int) sanitize_text_field( $_GET['revision'] ), false ) ) : false, 6 => sprintf( __( 'Quote added. <a href="%s">Back to Quotes</a>', 'zero-bs-crm' ), esc_url( 'edit.php?post_type=zerobs_quote&page=manage-quotes' ) ), // get_permalink($post_ID) ) ),//esc_url( get_permalink($post_ID) ) ), 7 => __( 'Quote saved.', 'zero-bs-crm' ), 8 => sprintf( __( 'Quote submitted. <a target="_blank" href="%s">Back to Quotes</a>', 'zero-bs-crm' ), esc_url( 'edit.php?post_type=zerobs_quote&page=manage-quotes' ) ), // esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ), 9 => '', // sprintf( ), //get_permalink($post_ID) ) ),//esc_url( get_permalink($post_ID) ) ), 10 => sprintf( __( 'Quote draft updated. <a target="_blank" href="%s">Back to Quotes</a>', 'zero-bs-crm' ), esc_url( 'edit.php?post_type=zerobs_quote&page=manage-quotes' ) ), // get_permalink($post_ID) ) ),//esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ), ); return $messages; } function zeroBSCRM_improvedPostMsgsTransactions( $messages ) { // print_r($messages); exit(); global $zbs; $messages['post'] = array( 0 => '', // Unused. Messages start at index 1. 1 => sprintf( __( 'Transaction updated. <a href="%s">Back to Transactions</a>', 'zero-bs-crm' ), esc_url( 'admin.php?page=' . $zbs->slugs['managetransactions'] ) ), // get_permalink($post_ID) ) ), 2 => __( 'Transaction updated.', 'zero-bs-crm' ), 3 => __( 'Transaction field deleted.', 'zero-bs-crm' ), 4 => __( 'Transaction updated.', 'zero-bs-crm' ), /* translators: %s: date and time of the revision */ 5 => isset( $_GET['revision'] ) ? sprintf( __( 'Transaction restored to revision from %s', 'zero-bs-crm' ), wp_post_revision_title( (int) sanitize_text_field( $_GET['revision'] ), false ) ) : false, 6 => sprintf( __( 'Transaction added. <a href="%s">Back to Transactions</a>', 'zero-bs-crm' ), esc_url( 'admin.php?&page=' . $zbs->slugs['managetransactions'] ) ), // get_permalink($post_ID) ) ),//esc_url( get_permalink($post_ID) ) ), 7 => __( 'Transaction saved.', 'zero-bs-crm' ), 8 => sprintf( __( 'Transaction submitted. <a target="_blank" href="%s">Back to Transactions</a>', 'zero-bs-crm' ), esc_url( 'edit.php?post_type=zerobs_transaction' ) ), // esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ), 9 => '', // sprintf( ), //get_permalink($post_ID) ) ),//esc_url( get_permalink($post_ID) ) ), 10 => sprintf( __( 'Transaction draft updated. <a target="_blank" href="%s">Back to Transactions</a>', 'zero-bs-crm' ), esc_url( 'edit.php?post_type=zerobs_transaction' ) ), // get_permalink($post_ID) ) ),//esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ), ); return $messages; } /* ====================================================== / WordPress Button Overides ====================================================== */ /* ====================================================== WordPress Footer Msg ====================================================== */ // } Footer Text function jpcrm_footer_credit_thanks( $content ) { // return original text if not on a CRM page if ( ! zeroBSCRM_isAdminPage() ) { return $content; } ##WLREMOVE global $zbs; $showpoweredby_admin = $zbs->settings->get( 'showpoweredby_admin' ) === 1 ? true : false; if ( $showpoweredby_admin ) { return '<span id="footer-thankyou">' . sprintf( __( 'Thank you for using <a href="%s">Jetpack CRM</a>.', 'zero-bs-crm' ), $zbs->urls['home'] ) . '</span>'; } ##/WLREMOVE // return blank if disabled or white label return ''; } add_filter( 'admin_footer_text', 'jpcrm_footer_credit_thanks' ); function jpcrm_footer_credit_version( $content ) { // return original text if not on a CRM page if ( ! zeroBSCRM_isAdminPage() ) { return $content; } ##WLREMOVE global $zbs; $showpoweredby_admin = $zbs->settings->get( 'showpoweredby_admin' ) === 1 ? true : false; if ( $showpoweredby_admin ) { return sprintf( 'Jetpack CRM v%s', $zbs->version ); } ##/WLREMOVE // return blank if disabled or white label return ''; } add_filter( 'update_footer', 'jpcrm_footer_credit_version', 11 ); /* ====================================================== / WordPress Footer Msg ====================================================== */ /* ====================================================== Color Grabber Admin Colour Schemes ====================================================== */ // } Admin Colour Schemes add_action( 'admin_head', 'zbs_color_grabber' ); function zbs_color_grabber() { // } Information here to get the colors global $_wp_admin_css_colors, $zbsadmincolors; $current_color = get_user_option( 'admin_color' ); echo '<script type="text/javascript">var zbsJS_admcolours = ' . json_encode( $_wp_admin_css_colors[ $current_color ] ) . ';</script>'; echo '<script type="text/javascript">var zbsJS_unpaid = "' . esc_html__( 'unpaid', 'zero-bs-crm' ) . '";</script>'; $zbsadmincolors = $_wp_admin_css_colors[ $current_color ]->colors; ?> <style> .ranges li{ color: <?php echo esc_html( $zbsadmincolors[0] ); ?>; } .max_this{ color: <?php echo esc_html( $zbsadmincolors[0] ); ?> !important; } .ranges li:hover, .ranges li.active { background: <?php echo esc_html( $zbsadmincolors[0] ); ?> !important; border: 1px solid <?php echo esc_html( $zbsadmincolors[0] ); ?> !important; } .daterangepicker td.active{ background-color: <?php echo esc_html( $zbsadmincolors[0] ); ?> !important; } .zerobs_customer{ background-color: <?php echo esc_html( $zbsadmincolors[0] ); ?> !important; } .users-php .zerobs_customer { background: none !important; } .zerobs_transaction{ background-color: <?php echo esc_html( $zbsadmincolors[2] ); ?> !important; } .zerobs_invoice{ background-color: <?php echo esc_html( $zbsadmincolors[1] ); ?> !important; } .zerobs_quote{ background-color: <?php echo esc_html( $zbsadmincolors[3] ); ?> !important; } .graph-box .view-me, .rev{ color: <?php echo esc_html( $zbsadmincolors[0] ); ?> !important; } .toplevel_page_sales-dash .sales-graph-wrappers .area, .sales-dashboard_page_gross-revenue .sales-graph-wrappers .area, .sales-dashboard_page_net-revenue .sales-graph-wrappers .area, .sales-dashboard_page_discounts .sales-graph-wrappers .area, .sales-dashboard_page_fees .sales-graph-wrappers .area, .sales-dashboard_page_average-rev .sales-graph-wrappers .area, .sales-dashboard_page_new-customers .sales-graph-wrappers .area, .sales-dashboard_page_total-customers .sales-graph-wrappers .area{ fill: <?php echo esc_html( $zbsadmincolors[0] ); ?> !important; } .bar{ fill: <?php echo esc_html( $zbsadmincolors[0] ); ?> !important; } </style> <?php } /* ====================================================== / Color Grabber Admin Colour Schemes ====================================================== */ /* ====================================================== WP Override specifically ====================================================== */ function zeroBSCRM_stopFrontEnd() { // } Harsh redir! global $zbs; if ( ! zeroBSCRM_isAPIRequest() && ! zeroBSCRM_isClientPortalPage() ) { if ( is_user_logged_in() ) { // } No need here :) header( 'Location: ' . admin_url( 'admin.php?page=' . $zbs->slugs['managecontacts'] ) ); exit(); } else { // } No need here :) header( 'Location: ' . wp_login_url() ); exit(); } } } function zeroBSCRM_catchDashboard() { // debug echo 'api:'.zeroBSCRM_isAPIRequest().' portal:'.zeroBSCRM_isClientPortalPage().'!'; exit(); // } Only if not API / Client portal if ( ! zeroBSCRM_isAPIRequest() && ! zeroBSCRM_isClientPortalPage() ) { // } Admin side, zbs users // this is quick hack code and doesn't work! if ( is_admin() && zeroBSCRM_permsIsZBSUser() ) { // } Doesnt work: // require_once(ABSPATH . 'wp-admin/includes/screen.php'); // $screen = get_current_screen(); // } Does: global $pagenow,$zbs; if ( $pagenow == 'profile.php' || $pagenow == 'index.php' ) {// $screen->base == 'dashboard' ) { // } Customers quotes or invs? // this forwards non-wp users :) from dash/profile to their corresponding page if ( ! zeroBSCRM_permsWPEditPosts() ) { $sent = false; if ( zeroBSCRM_permsCustomers() ) { wp_redirect( jpcrm_esc_link( $zbs->slugs['managecontacts'] ) ); $sent = 1; } if ( ! $sent && zeroBSCRM_permsQuotes() ) { wp_redirect( jpcrm_esc_link( $zbs->slugs['managequotes'] ) ); $sent = 1; } if ( ! $sent && zeroBSCRM_permsInvoices() ) { wp_redirect( jpcrm_esc_link( $zbs->slugs['manageinvoices'] ) ); $sent = 1; } if ( ! $sent && zeroBSCRM_permsTransactions() ) { wp_redirect( jpcrm_esc_link( $zbs->slugs['managetransactions'] ) ); $sent = 1; } if ( ! $sent ) { // ? wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'zero-bs-crm' ) ); } } } } } // / if API request / portal } function zeroBSCRM_CustomisedLogin_Header() { $loginLogo = zeroBSCRM_getSetting( 'loginlogourl' ); if ( ! empty( $loginLogo ) ) { ?> <style type="text/css"> .login h1 a { background-image: url( <?php echo esc_html( $loginLogo ); ?> ); background-size: contain; width: auto; max-width: 90%; } </style> <?php } } add_action( 'login_head', 'zeroBSCRM_CustomisedLogin_Header' ); // changes wordpress.org to site.com :) function zeroBSCRM_CustomisedLogin_logo_url() { return site_url(); } add_filter( 'login_headerurl', 'zeroBSCRM_CustomisedLogin_logo_url' ); // changes the title :) (Powered by WordPress) to site title :) function zeroBSCRM_CustomisedLogin_logo_url_title() { return get_bloginfo( 'name' ); } add_filter( 'login_headertext', 'zeroBSCRM_CustomisedLogin_logo_url_title' ); ##WLREMOVE // add powered by Jetpack CRM to WP login footer if "override all" mode and public credits are enabled function jpcrm_wplogin_footer() { global $zbs; $wptakeovermodeforall = $zbs->settings->get( 'wptakeovermodeforall' ) === 1 ? true : false; $showpoweredby_public = $zbs->settings->get( 'showpoweredby_public' ) === 1 ? true : false; if ( $wptakeovermodeforall && $showpoweredby_public ) { echo '<div style="text-align:center;margin-top:1em;font-size:12px"><a href="' . esc_url( $zbs->urls['home'] ) . '" title="' . esc_attr__( 'Powered by Jetpack CRM', 'zero-bs-crm' ) . '" target="_blank">' . esc_html__( 'Powered by Jetpack CRM', 'zero-bs-crm' ) . '</a></div>'; } } add_action( 'login_footer', 'jpcrm_wplogin_footer' ); ##/WLREMOVE // } For (if shown mobile) - restrict things shown add_action( 'admin_bar_menu', 'remove_wp_items', 100 ); function remove_wp_items( $wp_admin_bar ) { global $zbs; // } Retrieve setting $customheadertext = $zbs->settings->get( 'customheadertext' ); // } Only for zbs custom user role users or all if flagged $takeoverModeAll = $zbs->settings->get( 'wptakeovermodeforall' ); $takeoverModeZBS = $zbs->settings->get( 'wptakeovermode' ); $takeoverMode = false; if ( $takeoverModeAll || ( zeroBSCRM_permsIsZBSUser() && $takeoverModeZBS ) ) { $takeoverMode = true; } if ( $takeoverMode ) { $wp_admin_bar->remove_menu( 'wp-logo' ); $wp_admin_bar->remove_menu( 'site-name' ); $wp_admin_bar->remove_menu( 'comments' ); $wp_admin_bar->remove_menu( 'new-content' ); $wp_admin_bar->remove_menu( 'my-account' ); // $wp_admin_bar->remove_menu('top-secondary'); if ( ! empty( $customheadertext ) ) { // https://codex.wordpress.org/Class_Reference/WP_Admin_Bar/add_menu // https://codex.wordpress.org/Function_Reference/add_node $wp_admin_bar->add_node( array( 'id' => 'zbshead', 'title' => '<div class="wp-menu-image dashicons-before dashicons-groups" style="display: inline-block;margin-right: 6px;"><br></div>' . $customheadertext, 'href' => zeroBSCRM_getAdminURL( $zbs->slugs['dash'] ), 'meta' => array( // 'class' => 'wp-menu-image dashicons-before dashicons-groups' ), ) ); } } } /* ====================================================== / WP Override specifically ====================================================== */ /* ====================================================== Thumbnails ====================================================== */ // } Can you even do this via plugin? function zeroBSCRM_addThemeThumbnails() { if ( function_exists( 'add_theme_support' ) ) { add_theme_support( 'post-thumbnails' ); } } /* ====================================================== / Thumbnails ====================================================== */
projects/plugins/crm/includes/ZeroBSCRM.FormatHelpers.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V1.20 * * Copyright 2020 Automattic * * Date: 01/11/16 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== Contact ====================================================== */ function zeroBSCRM_html_contactIntroSentence($contact){ // include 'contact since' when we have a valid date: if ( $contact['created'] > 0 ){ $c = '<i class="calendar alternate outline icon"></i>' . sprintf( __('Contact since %s',"zero-bs-crm"), $contact['created_date'] ); } // in co? + check if B2B mode active $b2bMode = zeroBSCRM_getSetting('companylevelcustomers'); if ( $b2bMode == 1 ){ $possibleCo = zeroBS_getCustomerCompanyID($contact['id']); if (!empty($possibleCo) && $possibleCo > 0){ $co = zeroBS_getCompany($possibleCo); if (is_array($co) && isset($co['name']) && !empty($co['name'])){ $c .= '<br/><i class="building outline icon"></i>' . __('Works for',"zero-bs-crm").' <a href="'.jpcrm_esc_link('view',$possibleCo,'zerobs_company').'" target="_blank">'.$co['name'].'</a>'; } } } #} New 2.98+ $contact_location = ""; if(!empty($contact['county']) && !empty($contact['country'])){ $contact_location = $contact['county'] . ", " . $contact['country']; }else if(!empty($contact['county']) && empty($contact['country'])){ $contact_location = $contact['county']; }else if(empty($contact['county']) && !empty($contact['country'])){ $contact_location = $contact['country']; } if($contact_location != ""){ $c .= '<br/><i class="map marker alternate icon"></i>' . $contact_location; } //tags for easier viewing UI wise (2.98+) $customerTags = zeroBSCRM_getCustomerTagsByID($contact['id']); if (!is_array($customerTags)) $customerTags = array(); if (count($customerTags) > 0){ $c .= '<br/>' . zeroBSCRM_html_linkedContactTags($contact['id'],$customerTags,'ui tag label zbs-mini-tag', false, true); } // assigned to? $usingOwnership = zeroBSCRM_getSetting('perusercustomers'); if ($usingOwnership){ $possibleOwner = zeroBS_getOwner($contact['id'],true,'zerobs_customer'); if (is_array($possibleOwner) && isset($possibleOwner['ID']) && !empty($possibleOwner['ID'])){ if (isset($possibleOwner['OBJ']) && isset($possibleOwner['OBJ']->user_nicename)){ $user_avatar = jpcrm_get_avatar( $possibleOwner['OBJ']->ID, 25 ); $c .= '<div class="zbs-contact-owner">' . __('Assigned to: ',"zero-bs-crm").' <span class="ui image label">'. $user_avatar . ' ' . $possibleOwner['OBJ']->display_name . '</span></div>'; } } } $c = apply_filters('zerobscrm_contactintro_filter', $c, $contact['id']); return $c; } function zeroBSCRM_html_contactSince($customer){ echo "<i class='fa fa-calendar'></i> "; esc_html_e("Contact since ", "zero-bs-crm"); $d = new DateTime($customer['created']); $formatted_date = $d->format(zeroBSCRM_getDateFormat()); return "<span class='zbs-action'><strong>" . $formatted_date . "</strong></span>"; } function zeroBSCRM_html_sendemailto($prefillID=-1,$emailAddress='',$withIco=true){ global $zbs; if ($prefillID > 0 && !empty($emailAddress)){ if ($withIco) echo "<i class='fa fa-envelope-o'></i> "; echo "<span class='zbs-action'><a href='". esc_url( zeroBSCRM_getAdminURL($zbs->slugs['emails']).'&zbsprefill='.$prefillID ) ."'>"; echo esc_html( $emailAddress ); echo "</a></span>"; } } //added echo = true (i.e by default echo this, but need to return it in some cases) function zeroBSCRM_html_linkedContactTags($contactID=-1,$tags=false,$classStr='',$echo = true, $trim = false, $limit = false){ global $zbs; $res = ''; //check if we have a way to pass a LIMIT to the below (cos tons of tags in the top box is bad) if ($contactID > 0 && $tags == false) $tags = zeroBSCRM_getCustomerTagsByID($contactID); if (count($tags) > 0) foreach ($tags as $tag){ // DAL1/2 switch $tagName = ''; $tagID = -1; if (is_array($tag)){ $tagName = $tag['name']; $tagID = $tag['id']; } else { $tagName = $tag->name; $tagID = $tag->term_id; } $short_tag_name = $trim && strlen($tagName) > 50 ? substr($tagName,0,10)."..." : $tagName; $link = admin_url('admin.php?page='.$zbs->slugs['managecontacts'].'&zbs_tag='.$tagID); $res .= '<a title="' . esc_attr( $tagName ) . '" class="' . $classStr . '" href="' . $link . '">' . esc_html( $short_tag_name ) . '</a>'; } if ($echo) echo $res; else return $res; } // builds the HTML for companies linked to a contact // note can pass $companiesArray parameter optionally to avoid the need to retrieve companies (DAL3+ these are got with the getContact) function zeroBSCRM_html_linkedContactCompanies($contactID=-1,$companiesArray=false){ global $zbs; #} Contacts' companies if (!is_array($companiesArray)) $companies = $zbs->DAL->contacts->getContactCompanies($contactID); else $companies = $companiesArray; $companiesStr = ''; foreach ($companies as $company){ if (is_array($company) && isset($company['name']) && !empty($company['name'])){ $companiesStr .= '<a href="'.jpcrm_esc_link('view',$company['id'],'zerobs_company').'" target="_blank">'.$company['name'].'</a>'; } } return $companiesStr; } function zeroBSCRM_html_contactTimeline($contactID=-1,$logs=false,$contactObj=false){ global $zeroBSCRM_logTypes, $zbs; if (isset($contactID) && $contactID > 0 && $logs === false){ // get logs $logs = zeroBSCRM_getContactLogs($contactID,true,100,0,'',false); } //echo 'zeroBSCRM_html_contactTimeline<pre>'.print_r($logs,1).'</pre>'; exit(); // Compile a list of actions to show // - if under 10, show them all // - if over 10, show creation, and 'higher level' logs, then latest // - 7/2/19 WH modified this to catch "creation" logs properly, and always put them at the end // ... (we were getting instances where transaction + contact created in same second, which caused the order to be off) $logsToShow = array(); $creationLog = false; if (count($logs) <= 10){ $logsToShow = $logs; $logsF = array(); $creationLog = false; // here we have to just do a re-order to make sure created is last :) foreach ($logsToShow as $l){ if ($l['type'] == 'created') $creationLog = $l; else $logsF[] = $l; } // add it if (is_array($creationLog)) $logsF[] = $creationLog; // tidy $logsToShow = $logsF; unset($logsF); unset($creationLog); } else { // cherry pick 9 logs // 1) latest $logsToShow[] = current($logs); // 2) cherry pick 8 middle events $logTypesToPrioritise = array( 'Quote: Accepted', 'Quote: Refused', 'Invoice: Sent', 'Invoice: Part Paid', 'Invoice: Paid', 'Invoice: Refunded', 'Transaction', 'Feedback', 'Status Change', 'Client Portal User Created', 'Call', 'Email', 'Note' ); // convert to type stored in db $x = array(); foreach ($logTypesToPrioritise as $lt) $x[] = zeroBSCRM_logTypeStrToDB($lt); $logTypesToPrioritise = $x; unset($x); // for now, abbreviated, just cycle through + pick any in prioritised group... could do this staggered by type/time later //skip first item, as we've already added it earlier foreach (array_slice($logs,1) as $l){ if ($l['type'] == 'created'){ // add to this var $creationLog = $l; } else { // normal pickery if (count($logsToShow) < 9){ if (in_array($l['type'], $logTypesToPrioritise)) $logsToShow[] = $l; } else { break; } } } // 3) created // for now, assume first log is created, if it's not, add one with date // ... this'll cover 100+ logs situ // WH changed 7/2/18 to remove issue mentioned above // $creationLog = end($logs); if ($creationLog == false){ // retrieve it if ($zbs->isDAL2()) $creationLog = zeroBSCRM_getObjCreationLog($contactID,1); } if ( is_array( $creationLog ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $logsToShow[] = $creationLog; } else { // if has creation date (contactObj) if ($contactObj != false){ // manufacture a created log $logsToShow[] = array( 'id' => -1, 'created' => $contactObj['created'], 'name' => '', // also add DAL2 support: 'type' => __('Created',"zero-bs-crm"), 'shortdesc' => __('Contact Created',"zero-bs-crm"), 'longdesc' => __('Contact was created',"zero-bs-crm"), 'meta' => array( 'type' => __('Created',"zero-bs-crm"), 'shortdesc' => __('Contact Created',"zero-bs-crm"), 'longdesc' => __('Contact was created',"zero-bs-crm") ), 'owner' => -1, //nicetime ); } } } if ( count($logsToShow) > 0 ) { ?> <ul class="zbs-timeline"> <?php $prevDate = ''; $i = 0; foreach ( $logsToShow as $log ) { if ( !is_array( $log ) || !isset( $log['created'] ) ) { continue; } // format date $d = new DateTime( $log['created'] ); $formatted_date = $d->format( zeroBSCRM_getDateFormat() ); // check if same day as prev log $sameDate = false; if ( $formatted_date == $prevDate ) { $sameDate = true; } $prevDate = $formatted_date; // ico? $ico = ''; $logKey = strtolower( str_replace( ' ', '_', str_replace( ':', '_', $log['type'] ) ) ); if ( isset( $zeroBSCRM_logTypes['zerobs_customer'][$logKey] ) ) { $ico = $zeroBSCRM_logTypes['zerobs_customer'][$logKey]['ico']; } // these are FA ico's at this point // fill in nicetime if using :) // use a setting to turn on off? if ( !empty( $log['createduts'] ) && $log['createduts'] > 0 ) { // get H:i in local timezone $log['nicetime'] = zeroBSCRM_date_i18n( 'H:i', $log['createduts'], true, false ); } // if it's last one, make sure it has class: $notLast = true; if ( count( $logsToShow ) == $i + 1 ) { $notLast = false; } // compile this first, so can catch default (empty types) $logTitle = ''; if ( !empty( $ico ) ) { $logTitle .= '<i class="fa ' . $ico . '"></i> '; } if ( isset( $zeroBSCRM_logTypes['zerobs_customer'][$logKey] ) ) { $logTitle .= __( $zeroBSCRM_logTypes['zerobs_customer'][$logKey]['label'], 'zero-bs-crm' ); } $timeline_item_classes = ''; if ( $sameDate && $notLast ) { $timeline_item_classes .= '-contd'; } if ( empty( $logTitle ) ) { $timeline_item_classes .= ' zbs-timeline-item-notitle'; } if ( !$notLast ) { $timeline_item_classes .= ' zbs-last-item'; // last item (stop rolling padding) } $timeline_item_id_attr = ''; if ( isset( $log['id'] ) && $log['id'] !== -1 ) { $timeline_item_id_attr = ' id="zbs-contact-log-' . $log['id'] . '"'; } ?> <li class="zbs-timeline-item<?php echo esc_attr( $timeline_item_classes ); ?> zbs-single-log"<?php $timeline_item_id_attr; ?>> <?php if ( !$sameDate ) { ?> <div class="zbs-timeline-info"> <span><?php echo esc_html( $formatted_date ); ?></span> </div> <?php } ?> <div class="zbs-timeline-marker"></div> <div class="zbs-timeline-content"> <h3 class="zbs-timeline-title"> <?php if ( !empty( $ico ) ) { echo '<i class="fa ' . esc_attr( $ico ) . '"></i> '; } if ( isset( $zeroBSCRM_logTypes['zerobs_customer'][$logKey] ) ) { echo esc_html__( $zeroBSCRM_logTypes['zerobs_customer'][$logKey]['label'], 'zero-bs-crm' ); } ?> </h3> <div> <?php if ( isset( $log['shortdesc'] ) ) { echo wp_kses( $log['shortdesc'], array( 'i' => array( 'class' => true ) ) ); } if ( !empty( $log['author'] ) ) { echo ' &mdash; ' . esc_html( $log['author'] ); } if ( isset( $log['nicetime'] ) ) { echo ' &mdash; <i class="clock icon"></i>' . esc_html( $log['nicetime'] ); } // if has long desc, show/hide if ( !empty( $log['longdesc'] ) ) { ?> <i class="angle down icon zbs-show-longdesc"></i><i class="angle up icon zbs-hide-longdesc"></i> <div class="zbs-long-desc"> <?php echo wp_kses( html_entity_decode( $log['longdesc'], ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 ), $zbs->acceptable_restricted_html ); ?> </div> <?php } ?> </div> </div> </li> <?php $i++; } // / per log ?> </ul> <?php } } // /** * Builds HTML table of custom tables & values for (any object type) * * @return string HTML table */ function zeroBSCRM_pages_admin_display_custom_fields_table($id = -1, $objectType=ZBS_TYPE_CONTACT){ global $zbs; // retrieve custom fields (including value) $custom_fields = $zbs->DAL->getObjectLayerByType($objectType)->getSingleCustomFields($id,false); // Build HTML if (is_array($custom_fields) && count($custom_fields) > 0){ $html = '<table class="ui fixed single line celled table zbs-view-vital-customfields"><tbody>'; foreach($custom_fields as $k => $v){ $html .= '<tr id="zbs-view-vital-customfield-'.esc_attr($v['id']). '" class="wraplines">'; $html .= '<td class="zbs-view-vital-customfields-label">' . esc_html($v['name']) . '</td>'; switch ($v['type']){ case 'text': $value = nl2br( esc_html( $v['value'] ) ); //if url, build link, prefixed with 'https://' if needed if ( jpcrm_is_url( $value ) ) { $value = '<a href="' . jpcrm_url_with_scheme($value) . '" target="_blank">' . $value . '</a>'; } $html .= '<td class="zbs-view-vital-customfields-'.esc_attr($v['type']).'">' . $value . '</td>'; break; case 'date': $html .= '<td class="zbs-view-vital-customfields-' . esc_attr( $v['type'] ) . '">' . ( $v['value'] !== '' ? jpcrm_uts_to_date_str( $v['value'], false, true ) : '' ) . '</td>'; break; case 'checkbox': // pad , out $html .= '<td class="zbs-view-vital-customfields-'.esc_attr($v['type']).'">' . str_replace(',',', ',esc_html( $v['value'] ) ) . '</td>'; break; default: $html .= '<td class="zbs-view-vital-customfields-'.esc_attr($v['type']).'">' . nl2br( esc_html( $v['value'] ) ) . '</td>'; break; } $html .= '</tr>'; } $html .= '</tbody></table>'; } else { $html = __("No custom fields have been set up yet.", "zero-bs-crm"); if (zeroBSCRM_isZBSAdminOrAdmin()){ $customFieldsUrl = esc_url(admin_url('admin.php?page='.$zbs->slugs['settings']).'&tab=customfields'); $html .= ' <a href="'.$customFieldsUrl.'" target="_blank">'.__('Click here to manage custom fields', 'zero-bs-crm').'</a>'; } } return $html; } /* ====================================================== / Contact ====================================================== */ /* ====================================================== Company ====================================================== */ /* * Returns company introduction sentence * e.g. Email: alessandra.koepp@example.com, Added 01/01/2022 */ function zeroBSCRM_html_companyIntroSentence( $company ){ $return = ""; if ( isset( $company['email'] ) && !empty( $company['email'] ) ){ $return .= __('Email:', 'zero-bs-crm'); $return .= '<a href="mailto:'.$company['email'].'" class="coemail"> ' . $company['email'] . "</a><br/>"; } if ( is_array( $company ) && $company['created'] > 0 && isset( $company['created_date'] ) ){ $formatted_date = $company['created_date']; $return .= __('Added',"zero-bs-crm") . ' ' . $formatted_date; } // filter $return = apply_filters( 'zerobscrm_companyintro_filter', $return, $company['id'] ); return $return; } function zeroBSCRM_html_linkedCompanyTags($contactID=-1,$tags=false,$classStr=''){ global $zbs; if ($contactID > 0 && $tags == false) $tags = zeroBSCRM_getCustomerTagsByID($contactID); if (count($tags) > 0) foreach ($tags as $tag){ // DAL1/2 switch $tagName = ''; $tagID = -1; if (is_array($tag)){ $tagName = $tag['name']; $tagID = $tag['id']; } else { $tagName = $tag->name; $tagID = $tag->term_id; } ?><a class="<?php echo esc_attr( $classStr ); ?>" href="<?php echo jpcrm_esc_link( $zbs->slugs['managecompanies'] ) . '&zbs_tag=' . $tagID; ?>"><?php echo esc_html( $tagName ); ?></a><?php } } // builds the HTML for contacts linked to a company // note can pass $contactsArray parameter optionally to avoid the need to retrieve contacts (DAL3+ these are got with the getCompany) function zeroBSCRM_html_linkedCompanyContacts( $companyID = -1, $contactsArray = false ) { // avatar mode $avatarMode = zeroBSCRM_getSetting( 'avatarmode' ); // Contacts at company if ( !is_array( $contactsArray ) ) { $contactsAtCo = zeroBS_getCustomers( true, 1000, 0, false, false, '', false, false, $companyID ); } else { $contactsAtCo = $contactsArray; } $contactStr = ''; foreach ( $contactsAtCo as $contact ) { if ( $avatarMode !== 3 ) { $contactStr .= zeroBS_getCustomerIcoLinkedLabel( $contact['id'] ); // or zeroBS_getCustomerIcoLinkedLabel? } else { // no avatars, use labels $contactStr .= zeroBS_getCustomerLinkedLabel( $contact['id'] ); } } return $contactStr; } function zeroBSCRM_html_companyTimeline($companyID=-1,$logs=false,$companyObj=false){ global $zeroBSCRM_logTypes, $zbs; if (isset($companyID) && $companyID > 0 && $logs === false){ // get logs $logs = zeroBSCRM_getCompanyLogs($companyID,true,100,0,'',false); } // Compile a list of actions to show // - if under 10, show them all // - if over 10, show creation, and 'higher level' logs, then latest // - 7/2/19 WH modified this to catch "creation" logs properly, and always put them at the end // ... (we were getting instances where transaction + contact created in same second, which caused the order to be off) $logsToShow = array(); $creationLog = false; if (count($logs) <= 10){ $logsToShow = $logs; $logsF = array(); $creationLog = false; // here we have to just do a re-order to make sure created is last :) foreach ($logsToShow as $l){ if ($l['type'] == 'created') $creationLog = $l; else $logsF[] = $l; } // add it if (is_array($creationLog)) $logsF[] = $creationLog; // tidy $logsToShow = $logsF; unset($logsF); unset($creationLog); } else { // cherry pick 9 logs // 1) latest $logsToShow[] = current($logs); // 2) cherry pick 8 middle events $logTypesToPrioritise = array( 'Call', 'Email', 'Note' ); // convert to type stored in db $x = array(); foreach ($logTypesToPrioritise as $lt) $x[] = zeroBSCRM_logTypeStrToDB($lt); $logTypesToPrioritise = $x; unset($x); // for now, abbreviated, just cycle through + pick any in prioritised group... could do this staggered by type/time later foreach ($logs as $l){ if ($l['type'] == 'created'){ // add to this var $creationLog = $l; } else { // normal pickery if (count($logsToShow) < 9){ if (in_array($l['type'], $logTypesToPrioritise)) $logsToShow[] = $l; } else { break; } } } // 3) created // for now, assume first log is created, if it's not, add one with date // ... this'll cover 100+ logs situ // WH changed 7/2/18 to remove issue mentioned above // $creationLog = end($logs); if ( $creationLog == false ) { // retrieve it if ( $zbs->isDAL2() ) { $creationLog = zeroBSCRM_getObjCreationLog( $companyID, 1 ); } } if ( is_array( $creationLog ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $logsToShow[] = $creationLog; } else { // if has creation date (companyObj) if ($companyObj != false){ // manufacture a created log $logsToShow[] = array( 'id' => -1, 'created' => $companyObj['created'], 'name' => '', // also add DAL2 support: 'type' => __('Created',"zero-bs-crm"), 'shortdesc' => __(jpcrm_label_company().'Created',"zero-bs-crm"), 'longdesc' => __(jpcrm_label_company().' was created',"zero-bs-crm"), 'meta' => array( 'type' => __('Created',"zero-bs-crm"), 'shortdesc' => __(jpcrm_label_company().' Created',"zero-bs-crm"), 'longdesc' => __(jpcrm_label_company().' was created',"zero-bs-crm") ), 'owner' => -1, //nicetime ); } } } if (count($logsToShow) > 0){ ?> <ul class="zbs-timeline"> <?php $prevDate = ''; $i = 0; foreach ($logsToShow as $log){ // format date $d = new DateTime($log['created']); $formatted_date = $d->format(zeroBSCRM_getDateFormat()); // check if same day as prev log $sameDate = false; if ($formatted_date == $prevDate) $sameDate = true; $prevDate = $formatted_date; // ico? $ico = ''; $logKey = strtolower(str_replace(' ','_',str_replace(':','_',$log['type']))); if (isset($zeroBSCRM_logTypes['zerobs_company'][$logKey])) $ico = $zeroBSCRM_logTypes['zerobs_company'][$logKey]['ico']; // these are FA ico's at this point // fill in nicetime if using :) // use a setting to turn on off? if (isset($log['createduts']) && !empty($log['createduts']) && $log['createduts'] > 0){ //$log['nicetime'] = date('H:i',$log['createduts']); $log['nicetime'] = zeroBSCRM_date_i18n('H:i', $log['createduts'], true, false); } // if it's last one, make sure it has class: $notLast = true; if (count($logsToShow) == $i+1) $notLast = false; ?> <li class="zbs-timeline-item<?php if ($sameDate && $notLast) echo '-contd'; if (empty($logTitle)) echo ' zbs-timeline-item-notitle'; if (!$notLast) echo ' zbs-last-item'; // last item (stop rolling padding) ?> zbs-single-log" <?php if (isset($log['id']) && $log['id'] !== -1) echo 'id="zbs-company-log-'. esc_attr( $log['id'] ).'"'; ?>> <?php if (!$sameDate){ ?><div class="zbs-timeline-info"> <span><?php echo esc_html( $formatted_date ); ?></span> </div><?php } ?> <div class="zbs-timeline-marker"></div> <div class="zbs-timeline-content"><?php // if multiple owners /* show "team member who enacted"? similar to https://semantic-ui.com/views/feed.html <div class="label"> <img src="/images/avatar/small/elliot.jpg"> </div> */ ?> <h3 class="zbs-timeline-title"><?php if (!empty($ico)) echo '<i class="fa '. esc_attr( $ico ) .'"></i> '; // DAL 2 saves type as permalinked if ($zbs->isDAL2()){ if (isset($zeroBSCRM_logTypes['zerobs_company'][$logKey])) echo esc_html( $zeroBSCRM_logTypes['zerobs_company'][$logKey]['label'] ); } else { if (isset($log['type'])) echo esc_html( $log['type'] ); } ?></h3> <p> <?php if ( isset( $log['shortdesc'] ) ) { echo wp_kses( $log['shortdesc'], array( 'i' => array( 'class' => true ) ) ); if ( isset( $log['author'] ) ) { echo ' &mdash; ' . esc_html( $log['author'] ); } if ( isset( $log['nicetime'] ) ) { echo ' &mdash; <i class="clock icon"></i>' . esc_html( $log['nicetime'] ); } } ?> </p> </div> </li> <?php $i++; } ?> </ul> <?php } } /* ====================================================== / Company ====================================================== */ /* ====================================================== Quotes ====================================================== */ function zeroBSCRM_html_quoteStatusLabel($quote=array()){ $statusInt = zeroBS_getQuoteStatus($quote,true); switch($statusInt){ case -2: // published not accepted return 'ui orange label'; break; case -1: // draft return 'ui grey label'; break; } // accepted return 'ui green label'; } /** * Return an updated HTML string, replacing date placeholders with correct date strings based on site settings. * @param string $value The value of the date variable to be replaced. * @param string $key The key of the date variable to be replaced. * @param string $working_html The HTML string to be updated. * @param string $placeholder_str_start The string to add to the beginning of the placeholder string (eg. ##QUOTE-). * * @return string The updated HTML string. */ function jpcrm_process_date_variables( $value, $key, $working_html, $placeholder_str_start = '##' ) { $base_date_key = $key; $date_to_uts = jpcrm_date_str_to_uts( $value ); $datetime_key = $key . '_datetime_str'; $date_uts_to_datetime = jpcrm_uts_to_datetime_str( $date_to_uts ); $date_key = $key . '_date_str'; $date_uts__to_date = jpcrm_uts_to_date_str( $date_to_uts ); $search_replace_pairs = array( $placeholder_str_start . strtoupper( $base_date_key ) . '##' => $date_to_uts, $placeholder_str_start . strtoupper( $datetime_key ) . '##' => $date_uts_to_datetime, $placeholder_str_start . strtoupper( $date_key ) . '##' => $date_uts__to_date, ); $working_html = str_replace( array_keys( $search_replace_pairs ), $search_replace_pairs, $working_html ); return $working_html; } /* ====================================================== / Quotes ====================================================== */ /* ====================================================== Invoices ====================================================== */ function zeroBSCRM_html_invoiceStatusLabel($inv=array()){ $status = ''; // <3.0 if (isset($inv['meta']) && isset($inv['meta']['status'])) $status = $inv['meta']['status']; // 3.0 if (isset($inv['status'])) $status = $inv['status']; switch($status){ case __("Draft",'zero-bs-crm'): return 'ui teal label'; break; case __("Unpaid",'zero-bs-crm'): return 'ui orange label'; break; case __("Paid",'zero-bs-crm'): return 'ui green label'; break; case __("Overdue",'zero-bs-crm'): return 'ui red label'; break; case __( "Deleted", 'zero-bs-crm' ): return 'ui red label'; break; } return 'ui grey label'; } /* ====================================================== / Invoices ====================================================== */ /* ====================================================== Transactions ====================================================== */ function zeroBSCRM_html_transactionStatusLabel($trans=array()){ $status = ''; // <3.0 if (isset($inv['meta']) && isset($inv['meta']['status'])) $status = $inv['meta']['status']; // 3.0 if (isset($inv['status'])) $status = $inv['status']; switch($status){ case __("failed",'zero-bs-crm'): return 'ui orange label'; break; case __("refunded",'zero-bs-crm'): return 'ui red label'; break; case __("succeeded",'zero-bs-crm'): return 'ui green label'; break; case __("completed",'zero-bs-crm'): return 'ui green label'; break; } return 'ui grey label'; } /* ====================================================== / Transactions ====================================================== */ /* ====================================================== Object Nav ====================================================== */ // Navigation block (usually wrapped in smt like:) // $filterStr = '<div class="ui items right floated" style="margin:0">'.zeroBSCRM_getObjNav($zbsid,'edit','CONTACT').'</div>'; function zeroBSCRM_getObjNav( $id = -1, $key = '', $type = ZBS_TYPE_CONTACT ) { global $zbs; $html = ''; $navigation_mode = $zbs->settings->get( 'objnav' ); // The first addition of a contact is actually 'edit' but gives the option to view. $id = ( empty( $_GET['zbsid'] ) ? -1 : (int) $_GET['zbsid'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended $html = ''; switch ($type) { case ZBS_TYPE_CONTACT: // contact nav $navigation = $zbs->DAL->contacts->getContactPrevNext( $id ); // PREV if ( $navigation_mode === 1 && ! empty( $navigation['prev'] ) ) { $html .= '<a href="' . jpcrm_esc_link( $key, $navigation['prev'], 'zerobs_customer', false ) . '" class="jpcrm-button transparent-bg font-14px"><i class="fa fa-chevron-left"></i>&nbsp;&nbsp;' . esc_html( __( 'Prev', 'zero-bs-crm' ) ) . '</a>'; } // If in edit mode, show view link if ( $key === 'edit' && $id > 0 ) { $html .= '<a class="jpcrm-button transparent-bg font-14px" href="' . jpcrm_esc_link( 'view', $id, 'zerobs_customer' ) . '">' . esc_html( __( 'View contact', 'zero-bs-crm' ) ) . '</a>'; } if ( $navigation_mode === 1 && ! empty( $navigation['next'] ) ) { $html .= '<a href="' . jpcrm_esc_link( $key, $navigation['next'], 'zerobs_customer', false ) . '" class="jpcrm-button transparent-bg font-14px">' . esc_html( __( 'Next', 'zero-bs-crm' ) ) . '&nbsp;&nbsp;<i class="fa fa-chevron-right"></i></a>'; } break; case ZBS_TYPE_COMPANY: // company nav $navigation = $zbs->DAL->companies->getCompanyPrevNext( $id ); // PREV if ( $navigation_mode === 1 && ! empty( $navigation['prev'] ) ) { $html .= '<a href="' . jpcrm_esc_link( $key, $navigation['prev'], 'zerobs_company', false ) . '" class="jpcrm-button transparent-bg font-14px"><i class="fa fa-chevron-left"></i>&nbsp;&nbsp;' . esc_html( __( 'Prev', 'zero-bs-crm' ) ) . '</a>'; } // If in edit mode, show view link if ( $key === 'edit' && $id > 0 ) { $html .= '<a style="margin: 0 5px;" class="jpcrm-button transparent-bg font-14px" href="' . jpcrm_esc_link( 'view', $id, ZBS_TYPE_COMPANY ) . '">' . esc_html( __( 'View company', 'zero-bs-crm' ) ) . '</a>'; } if ( $navigation_mode === 1 && ! empty( $navigation['next'] ) ) { $html .= '<a href="' . jpcrm_esc_link( $key, $navigation['next'], 'zerobs_company', false ) . '" class="jpcrm-button transparent-bg font-14px">' . esc_html( __( 'Next', 'zero-bs-crm' ) ) . '&nbsp;&nbsp;<i class="fa fa-chevron-right"></i></a>'; } break; case ZBS_TYPE_QUOTE: case ZBS_TYPE_INVOICE: case ZBS_TYPE_TRANSACTION: break; } return $html; } /* ====================================================== / Object Nav ====================================================== */ /** * Return table options button */ function get_jpcrm_table_options_button() { return '<button class="jpcrm-button transparent-bg font-14px" type="button" id="jpcrm_table_options">' . esc_html__( 'Table options', 'zero-bs-crm' ) . '&nbsp;<i class="fa fa-cog"></i></button>'; } /* ====================================================== Tasks ====================================================== */ function zeroBSCRM_html_taskStatusLabel($task=array()){ if (isset($task['complete']) && $task['complete'] === 1) return 'ui green label'; return 'ui grey label'; } /** * Returns a task datetime range string * * @param arr $task Task array. * * @return str datetime range string */ function zeroBSCRM_html_taskDate( $task = array() ) { if ( ! isset( $task['start'] ) ) { // task doesn't have start date...not sure why this would ever happen $task_start = jpcrm_uts_to_datetime_str( time() + 3600 ); $task_end = jpcrm_uts_to_datetime_str( $task_start + 3600 ); } else { $task_start = jpcrm_uts_to_datetime_str( $task['start'] ); $task_end = jpcrm_uts_to_datetime_str( $task['end'] ); } return $task_start . ' - ' . $task_end; } /* ====================================================== / Tasks ====================================================== */ /* ====================================================== Email History ====================================================== */ function zeroBSCRM_outputEmailHistory( $user_id = -1 ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid,Squiz.Commenting.FunctionComment.Missing,Squiz.Commenting.FunctionComment.WrongStyle global $zbs; // get the last 50 (can add pagination later...) $email_hist = zeroBSCRM_get_email_history( 0, 50, $user_id ); ?> <style> .zbs-email-sending-record { margin-bottom:0.8em; } .zbs-email-sending-record .avatar{ margin-left: 5px; border-radius: 50%; } .zbs-email-detail { width: 80%; display: inline-block; } </style> <?php if ( count( $email_hist ) === 0 ) { echo '<div class="ui message"><i class="icon envelope outline"></i>' . esc_html( __( 'No Recent Emails', 'zero-bs-crm' ) ) . '</div>'; } foreach ( $email_hist as $em_hist ) { $email_details_html = ''; $email_subject = zeroBSCRM_mailTemplate_getSubject( $em_hist->zbsmail_type ); $emoji = '🤖'; if ( $email_subject === '' ) { // then this is a custom email $email_subject = $em_hist->zbsmail_subject; $emoji = '😀'; } // if still empty if ( empty( $email_subject ) ) { $email_subject = esc_html__( 'Untitled', 'zero-bs-crm' ); } $email_details_html .= '<div class="zbs-email-sending-record">'; $email_details_html .= '<span class="label blue ui tiny hist-label" style="float:left"> ' . esc_html( __( 'sent', 'zero-bs-crm' ) ) . ' </span>'; $email_details_html .= '<div class="zbs-email-detail">' . esc_html( $emoji ); $email_details_html .= ' <strong>' . esc_html( $email_subject ) . '</strong><br />'; $email_details_html .= '<span class="sent-to">' . esc_html( __( ' sent to ', 'zero-bs-crm' ) ) . '</span>'; // -10 are the system emails sent to CUSTOMERS if ( $em_hist->zbsmail_sender_wpid === '-10' ) { $customer = zeroBS_getCustomerMeta( $em_hist->zbsmail_target_objid ); if ( ! $customer ) { continue; } $link = admin_url( 'admin.php?page=' . $zbs->slugs['addedit'] . '&action=view&zbsid=' . $em_hist->zbsmail_target_objid ); if ( $customer['fname'] === '' && $customer['lname'] === '' ) { $email_details_html .= '<a href="' . esc_url( $link ) . '">' . esc_html( $customer['email'] ) . '</a>'; } else { $email_details_html .= '<a href="' . esc_url( $link ) . '">' . esc_html( $customer['fname'] . ' ' . $customer['lname'] ) . '</a>'; } } elseif ( $em_hist->zbsmail_sender_wpid === '-11' ) { // quote proposal accepted (sent to admin...) $user_obj = get_user_by( 'ID', $em_hist->zbsmail_target_objid ); if ( ! $user_obj ) { continue; } $email_details_html .= esc_html( $user_obj->data->display_name ); $email_details_html .= jpcrm_get_avatar( $em_hist->zbsmail_target_objid, 20 ); } elseif ( $em_hist->zbsmail_sender_wpid === '-12' ) { // quote proposal accepted (sent to admin...) -12 is the you have a new quote... $customer = zeroBS_getCustomerMeta( $em_hist->zbsmail_target_objid ); if ( ! $customer ) { continue; } $link = admin_url( 'admin.php?page=' . $zbs->slugs['addedit'] . '&action=view&zbsid=' . $em_hist->zbsmail_target_objid ); if ( $customer['fname'] === '' && $customer['lname'] === '' ) { $email_details_html .= '<a href="' . esc_url( $link ) . '">' . esc_html( $customer['email'] ) . '</a>'; } else { $email_details_html .= '<a href="' . esc_url( $link ) . '">' . esc_html( $customer['fname'] . ' ' . $customer['lname'] ) . '</a>'; } } elseif ( $em_hist->zbsmail_sender_wpid === '-13' ) { // -13 is the task notification (sent to the OWNER of the task) so a WP user (not ZBS contact)... $user_obj = get_user_by( 'ID', $em_hist->zbsmail_target_objid ); if ( ! $user_obj ) { continue; } $email_details_html .= esc_html( $user_obj->data->display_name ); $email_details_html .= jpcrm_get_avatar( $em_hist->zbsmail_target_objid, 20 ); } else { $customer = zeroBS_getCustomerMeta( $em_hist->zbsmail_target_objid ); if ( ! $customer ) { continue; } // then it is a CRM team member [team member is quote accept].... $link = admin_url( 'admin.php?page=' . $zbs->slugs['addedit'] . '&action=view&zbsid=' . $em_hist->zbsmail_target_objid ); if ( $customer['fname'] === '' && $customer['lname'] === '' ) { $email_details_html .= '<a href="' . esc_url( $link ) . '">' . esc_html( $customer['email'] ) . '</a>'; } else { $email_details_html .= '<a href="' . esc_url( $link ) . '">' . esc_html( $customer['fname'] . ' ' . $customer['lname'] ) . '</a>'; } $user_obj = get_user_by( 'ID', $em_hist->zbsmail_sender_wpid ); if ( ! $user_obj ) { continue; } $email_details_html .= esc_html( __( ' by ', 'zero-bs-crm' ) . $user_obj->data->display_name ); $email_details_html .= jpcrm_get_avatar( $em_hist->zbsmail_sender_wpid, 20 ); } $unixts = gmdate( 'U', $em_hist->zbsmail_created ); $diff = human_time_diff( $unixts, time() ); $email_details_html .= '<time>' . esc_html( $diff . __( ' ago', 'zero-bs-crm' ) ) . '</time>'; if ( $em_hist->zbsmail_opened === '1' ) { $email_details_html .= '<span class="ui green basic label mini" style="margin-left:7px;"><i class="icon check"></i> ' . esc_html( __( 'opened', 'zero-bs-crm' ) ) . '</span>'; } $email_details_html .= '</div></div>'; echo $email_details_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped } } /* ====================================================== / Email History ====================================================== */ /* ====================================================== Edit Pages Field outputter ====================================================== */ // puts out edit fields for an object (e.g. quotes) // centralisd/genericified 20/7/18 wh 2.91+ function zeroBSCRM_html_editFields($objArr=false,$fields=false,$postPrefix='zbs_',$skipFields=array()){ if (is_array($fields)){ foreach ($fields as $fieldK => $fieldV){ // we skip some when we put them out specifically/manually in the metabox/ui if (!in_array($fieldK,$skipFields)) zeroBSCRM_html_editField($objArr,$fieldK,$fieldV,$postPrefix); } } } // puts out edit field for an object (e.g. quotes) // centralisd/genericified 20/7/18 wh 2.91+ function zeroBSCRM_html_editField($dataArr=array(), $fieldKey = false, $fieldVal = false, $postPrefix = 'zbs_'){ // phpcs:disable /* debug if ($fieldKey == 'house-type') { echo '<tr><td colspan="2">'.$fieldKey.'<pre>'.print_r(array($fieldVal,$dataArr),1).'</pre></td></tr>'; } */ if (!empty($fieldKey) && is_array($fieldVal)){ // infer a default (Added post objmodels v3.0 as a potential.) $default = ''; if (is_array($fieldVal) && isset($fieldVal['default'])) $default = $fieldVal['default']; // get a value (this allows field-irrelevant global tweaks, like the addr catch below...) // -99 = notset $value = -99; if (isset($dataArr[$fieldKey])) $value = $dataArr[$fieldKey]; // custom classes for inputs $inputClasses = isset($fieldVal['custom-field']) ? ' zbs-custom-field' : ''; // contacts got stuck in limbo as we upgraded db in 2 phases. // following catches old str and modernises to v3.0 // make addresses their own objs 3.0+ and do away with this. // ... hard typed to avoid custom field collisions, hacky at best. switch ($fieldKey){ case 'secaddr1': if (isset($dataArr['secaddr_addr1'])) $value = $dataArr['secaddr_addr1']; break; case 'secaddr2': if (isset($dataArr['secaddr_addr2'])) $value = $dataArr['secaddr_addr2']; break; case 'seccity': if (isset($dataArr['secaddr_city'])) $value = $dataArr['secaddr_city']; break; case 'seccounty': if (isset($dataArr['secaddr_county'])) $value = $dataArr['secaddr_county']; break; case 'seccountry': if (isset($dataArr['secaddr_country'])) $value = $dataArr['secaddr_country']; break; case 'secpostcode': if (isset($dataArr['secaddr_postcode'])) $value = $dataArr['secaddr_postcode']; break; } global $zbs; switch ( $fieldVal[0] ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase case 'text': ?> <div class="jpcrm-form-group jpcrm-form-group-span-2"> <label class="jpcrm-form-label" for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e( $fieldVal[1], 'zero-bs-crm' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, WordPress.WP.I18n.NonSingularStringLiteralText ?>:</label> <div class="zbs-text-input <?php echo esc_attr( $fieldKey ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?>"> <input type="text" name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?>" id="<?php echo esc_attr( $fieldKey ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?>" class="form-control widetext zbs-dc<?php echo esc_attr( $inputClasses ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?>" placeholder="<?php if ( isset( $fieldVal[2] ) ) echo esc_attr__( $fieldVal[2], 'zero-bs-crm' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, WordPress.WP.I18n.NonSingularStringLiteralText, Generic.ControlStructures.InlineControlStructure.NotAllowed ?>" value="<?php if ( $value !== -99 ) echo esc_attr( $value ); else echo esc_attr( $default ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, Generic.ControlStructures.InlineControlStructure.NotAllowed, Generic.Formatting.DisallowMultipleStatements.SameLine, Squiz.PHP.EmbeddedPhp.MultipleStatements ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>" /> </div> </div> <?php break; case 'price': ?> <div class="jpcrm-form-group jpcrm-form-group-span-2"> <label class="jpcrm-form-label" for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e( $fieldVal[1], 'zero-bs-crm' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, WordPress.WP.I18n.NonSingularStringLiteralText ?>:</label> <div class="jpcrm-form-input-group"> <?php echo esc_html( zeroBSCRM_getCurrencyChr() ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?> <input type="text" name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?>" id="<?php echo esc_attr( $fieldKey ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?>" class="form-control numbersOnly zbs-dc<?php echo esc_attr( $inputClasses ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?>" placeholder="<?php if ( isset( $fieldVal[2] ) ) echo esc_attr__( $fieldVal[2], 'zero-bs-crm' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, WordPress.WP.I18n.NonSingularStringLiteralText, Generic.ControlStructures.InlineControlStructure.NotAllowed ?>" value="<?php if ( $value !== -99 ) echo esc_attr( $value ); else echo esc_attr( $default ); // phpcs:ignore Generic.ControlStructures.InlineControlStructure.NotAllowed, Generic.Formatting.DisallowMultipleStatements.SameLine, Squiz.PHP.EmbeddedPhp.MultipleStatements ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>" /> </div> </div> <?php break; case 'numberfloat': ?> <div class="jpcrm-form-group jpcrm-form-group-span-2"> <label class="jpcrm-form-label" for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e( $fieldVal[1], 'zero-bs-crm' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, WordPress.WP.I18n.NonSingularStringLiteralText ?>:</label> <input type="text" name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?>" id="<?php echo esc_attr( $fieldKey ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?>" class="form-control numbersOnly zbs-dc<?php echo esc_attr( $inputClasses ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?>" placeholder="<?php if ( isset( $fieldVal[2] ) ) echo esc_attr__( $fieldVal[2], 'zero-bs-crm' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, WordPress.WP.I18n.NonSingularStringLiteralText, Generic.ControlStructures.InlineControlStructure.NotAllowed ?>" value="<?php if ( $value !== -99 ) echo esc_attr( $value ); else echo esc_attr( $default ); // phpcs:ignore Generic.ControlStructures.InlineControlStructure.NotAllowed, Generic.Formatting.DisallowMultipleStatements.SameLine, Squiz.PHP.EmbeddedPhp.MultipleStatements ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>" /> </div> <?php break; case 'numberint': ?> <div class="jpcrm-form-group jpcrm-form-group-span-2"> <label class="jpcrm-form-label" for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e( $fieldVal[1], 'zero-bs-crm' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, WordPress.WP.I18n.NonSingularStringLiteralText ?>:</label> <input type="text" name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?>" id="<?php echo esc_attr( $fieldKey ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?>" class="form-control intOnly zbs-dc<?php echo esc_attr( $inputClasses ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?>" placeholder="<?php if ( isset( $fieldVal[2] ) ) echo esc_attr__( $fieldVal[2], 'zero-bs-crm' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, WordPress.WP.I18n.NonSingularStringLiteralText, Generic.ControlStructures.InlineControlStructure.NotAllowed ?>" value="<?php if ($value !== -99) echo esc_attr( $value ); else echo esc_attr( $default ); // phpcs:ignore Generic.ControlStructures.InlineControlStructure.NotAllowed, Generic.Formatting.DisallowMultipleStatements.SameLine, Squiz.PHP.EmbeddedPhp.MultipleStatements ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>" /> </div> <?php break; case 'date': $datevalue = ''; if ( $value !== -99 ) { $datevalue = jpcrm_uts_to_date_str( $value, 'Y-m-d', true ); } // if this is a custom field, and is unset, we let it get passed as empty (gh-56) if ( isset( $fieldVal['custom-field'] ) && ( $value === -99 || $value === '' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $datevalue = ''; } ?> <div class="jpcrm-form-group jpcrm-form-group-span-2"> <label class="jpcrm-form-label" for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e( $fieldVal[1], 'zero-bs-crm' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, WordPress.WP.I18n.NonSingularStringLiteralText ?>:</label> <input type="date" name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>" id="<?php echo esc_attr( $fieldKey ); ?>" placeholder="yyyy-mm-dd" value="<?php echo esc_attr( $datevalue ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?>"/> </div> <?php break; case 'datetime': $datevalue = ''; if ($value !== -99) $datevalue = $value; // if DAL3 we need to use translated dates here :) if ($zbs->isDAL3()) $datevalue = zeroBSCRM_date_i18n_plusTime(-1,$datevalue,true); ?> <div class="jpcrm-form-group jpcrm-form-group-span-2"> <label class="jpcrm-form-label" for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e( $fieldVal[1], 'zero-bs-crm' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, WordPress.WP.I18n.NonSingularStringLiteralText ?>:</label> <input type="text" name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>" id="<?php echo esc_attr( $fieldKey ); ?>" class="form-control jpcrm-date-time zbs-dc<?php echo esc_attr( $inputClasses ); ?>" placeholder="<?php if (isset($fieldVal[2])) echo esc_attr__($fieldVal[2],'zero-bs-crm'); ?>" value="<?php echo esc_attr( $datevalue ); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>" /> </div> <?php break; case 'select': //don't load prefix select if prefix is hidden in settings if ($zbs->settings->get('showprefix') == 0 && $fieldKey == 'prefix') { break; } ?> <div class="jpcrm-form-group jpcrm-form-group-span-2"> <label class="jpcrm-form-label" for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e( $fieldVal[1], 'zero-bs-crm' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, WordPress.WP.I18n.NonSingularStringLiteralText ?>:</label> <select name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>" id="<?php echo esc_attr( $fieldKey ); ?>" class="form-control zbs-watch-input zbs-dc<?php echo esc_attr( $inputClasses ); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>"> <?php // pre DAL 2 = $fieldV[3], DAL2 = $fieldV[2] $options = false; if (isset($fieldVal[3]) && is_array($fieldVal[3])) { $options = $fieldVal[3]; } else { // DAL2 these don't seem to be auto-decompiled? // doing here for quick fix, maybe fix up the chain later. if (isset($fieldVal[2])) $options = explode(',', $fieldVal[2]); } //if (isset($fieldVal[3]) && count($fieldVal[3]) > 0){ if (isset($options) && is_array($options) && count($options) > 0 && $options[0] != ''){ // if $default, use that $selectVal = ''; if ($value !== -99 && !empty($value)){ $selectVal = $value; } elseif (!empty($default)) $selectVal = $default; //catcher echo '<option value=""' . ($fieldKey == 'prefix' ? '' :' disabled="disabled"'); if (empty($default) && ($value == -99 || ($value !== -99 && empty($value)))) echo ' selected="selected"'; echo '>'. esc_html__('Select','zero-bs-crm').'</option>'; foreach ($options as $opt){ echo '<option value="' . esc_attr( $opt ) . '"'; if ($selectVal == $opt) echo ' selected="selected"'; echo '>' . esc_html( $opt ) . '</option>'; } } else echo '<option value="">'. esc_html__('No Options','zero-bs-crm').'!</option>'; ?> </select> <input type="hidden" name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>_dirtyflag" id="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>_dirtyflag" value="0" /> </div> <?php break; case 'tel': // Click 2 call? $click2call = $zbs->settings->get('clicktocall'); ?> <div class="jpcrm-form-group jpcrm-form-group-span-2"> <label class="jpcrm-form-label" for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e( $fieldVal[1], 'zero-bs-crm' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, WordPress.WP.I18n.NonSingularStringLiteralText ?>:</label> <span class="zbs-tel-wrap"> <input type="text" name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>" id="<?php echo esc_attr( $fieldKey ); ?>" class="form-control zbs-tel zbs-dc<?php echo esc_attr( $inputClasses ); ?>" placeholder="<?php if (isset($fieldVal[2])) echo esc_attr__($fieldVal[2],'zero-bs-crm'); ?>" value="<?php if ($value !== -99) echo esc_attr( $value ); else echo esc_attr( $default ); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>" /> <?php if ($click2call == "1" && $value !== -99 && !empty($value)) echo '<a href="' . esc_attr( zeroBSCRM_clickToCallPrefix() . $value ) . '" class="button"><i class="fa fa-phone"></i> ' . esc_html( $value ) . '</a>'; ?> <?php if ($fieldKey == 'mobtel'){ $sms_class = 'send-sms-none'; $sms_class = apply_filters('zbs_twilio_sms', $sms_class); do_action('zbs_twilio_nonce'); $customerMob = ''; // wh genericified //if (is_array($dataArr) && isset($dataArr[$fieldKey]) && isset($dataArr['id'])) $customerMob = zeroBS_customerMobile($dataArr['id'],$dataArr); if ($value !== -99) $customerMob = $value; if (!empty($customerMob)) echo '<a class="' . esc_attr( $sms_class ) . ' button" data-smsnum="' . esc_attr( $customerMob ) .'"><i class="mobile alternate icon"></i> '. esc_html__('SMS','zero-bs-crm').': ' . esc_html( $customerMob ) . '</a>'; } ?> </span> </div> <?php break; case 'email': // added zbs-text-input class 5/1/18 - this allows "linkify" automatic linking // ... via js <div class="zbs-text-input"> // removed from email for now zbs-text-input ?> <div class="jpcrm-form-group jpcrm-form-group-span-2"> <label class="jpcrm-form-label" for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e( $fieldVal[1], 'zero-bs-crm' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, WordPress.WP.I18n.NonSingularStringLiteralText ?>:</label> <div class="<?php echo esc_attr( $fieldKey ); ?>"> <input type="text" name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>" id="<?php echo esc_attr( $fieldKey ); ?>" class="form-control zbs-email zbs-dc<?php echo esc_attr( $inputClasses ); ?>" placeholder="<?php if (isset($fieldVal[2])) echo esc_attr__($fieldVal[2],'zero-bs-crm'); ?>" value="<?php if ($value !== -99) echo esc_attr( $value ); else echo esc_attr( $default ); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>" /> </div> </div> <?php break; case 'textarea': ?> <div class="jpcrm-form-group jpcrm-form-group-span-2 jpcrm-form-group jpcrm-form-group-span-2-span-2"> <label class="jpcrm-form-label" for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e( $fieldVal[1], 'zero-bs-crm' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, WordPress.WP.I18n.NonSingularStringLiteralText ?>:</label> <textarea name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>" id="<?php echo esc_attr( $fieldKey ); ?>" class="form-control zbs-dc<?php echo esc_attr( $inputClasses ); ?>" placeholder="<?php if (isset($fieldVal[2])) echo esc_attr__($fieldVal[2],'zero-bs-crm'); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>"><?php if ($value !== -99) echo esc_textarea( $value ); else echo esc_textarea( $default ); ?></textarea> </div> <?php break; #} Added 1.1.19 case 'selectcountry': $countries = zeroBSCRM_loadCountryList(); ?> <div class="jpcrm-form-group jpcrm-form-group-span-2"> <label class="jpcrm-form-label" for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e( $fieldVal[1], 'zero-bs-crm' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, WordPress.WP.I18n.NonSingularStringLiteralText ?>:</label> <select name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>" id="<?php echo esc_attr( $fieldKey ); ?>" class="form-control zbs-dc<?php echo esc_attr( $inputClasses ); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>"> <?php #if (isset($fieldVal[3]) && count($fieldVal[3]) > 0){ if (isset($countries) && count($countries) > 0){ //catcher echo '<option value=""'; if (empty($default) && ($value == -99 || ($value !== -99 && empty($value)))) echo ' selected="selected"'; echo '>'. esc_html__('Select','zero-bs-crm').'</option>'; foreach ($countries as $countryKey => $country){ // temporary fix for people storing "United States" but also "US" // needs a migration to iso country code, for now, catch the latter (only 1 user via api) echo '<option value="' . esc_attr( $country ) . '"'; if ($value !== -99 && ( strtolower($value) == strtolower($country) || strtolower($value) == strtolower($countryKey) )) echo ' selected="selected"'; echo '>' . esc_html( $country ) . '</option>'; } } else echo '<option value="">'. esc_html__('No Countries Loaded','zero-bs-crm').'</option>'; ?> </select> </div> <?php break; // 2.98.5 added autonumber, checkbox, radio // auto number - can't actually edit autonumbers, so its just outputting :) case 'autonumber': ?> <div class="jpcrm-form-group jpcrm-form-group-span-2"> <label class="jpcrm-form-label" for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e( $fieldVal[1], 'zero-bs-crm' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, WordPress.WP.I18n.NonSingularStringLiteralText ?>:</label> <span class="zbs-field-id"> <?php // output any saved autonumber for this obj $str = ''; if ($value !== -99) $str = $value; // we strip the hashes saved in db for easy separation later $str = str_replace('#','',$str); // then output... if (empty($str)) echo '~'; else echo esc_html( $str ); // we also output as input, which stops any overwriting + makes new ones for new records echo '<input type="hidden" value="' . esc_attr( $str ) . '" name="'. esc_attr( $postPrefix.$fieldKey ) .'" />'; ?> </span> </div> <?php break; // radio case 'radio': ?> <div class="jpcrm-form-group jpcrm-form-group-span-2"> <label class="jpcrm-form-label" for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e( $fieldVal[1], 'zero-bs-crm' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, WordPress.WP.I18n.NonSingularStringLiteralText ?>:</label> <div class="zbs-field-radio-wrap"> <?php // pre DAL 2 = $fieldV[3], DAL2 = $fieldV[2] $options = false; if (isset($fieldVal[3]) && is_array($fieldVal[3])) { $options = $fieldVal[3]; } else { // DAL2 these don't seem to be auto-decompiled? // doing here for quick fix, maybe fix up the chain later. if (isset($fieldVal[2])) $options = explode(',', $fieldVal[2]); } //if (isset($fieldVal[3]) && count($fieldVal[3]) > 0){ if (isset($options) && is_array($options) && count($options) > 0 && $options[0] != ''){ $optIndex = 0; foreach ($options as $opt){ echo '<div class="zbs-radio"><input type="radio" name="'. esc_attr( $postPrefix.$fieldKey ) .'" id="'. esc_attr( $fieldKey.'-'.$optIndex ) .'" value="' . esc_attr( $opt ) . '"'; if ($value !== -99 && $value == $opt) echo ' checked="checked"'; echo ' /> <label class="jpcrm-form-label" for="' . esc_attr( $fieldKey . '-' . $optIndex ) . '">' . esc_html( $opt ) . '</label></div>'; //phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $optIndex++; } } else { echo '<label class="jpcrm-form-label" for="' . esc_attr( $fieldKey ) . '-0">' . esc_attr__( 'No Options', 'zero-bs-crm' ) . '!</label>'; //phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } ?> </div> <input type="hidden" name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>_dirtyflag" id="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>_dirtyflag" value="0" /> </div> <?php break; // checkbox case 'checkbox': ?> <div class="jpcrm-form-group jpcrm-form-group-span-2"> <label class="jpcrm-form-label" for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e( $fieldVal[1], 'zero-bs-crm' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, WordPress.WP.I18n.NonSingularStringLiteralText ?>:</label> <div class="zbs-field-checkbox-wrap"> <?php // pre DAL 2 = $fieldV[3], DAL2 = $fieldV[2] $options = false; if (isset($fieldVal[3]) && is_array($fieldVal[3])) { $options = $fieldVal[3]; } else { // DAL2 these don't seem to be auto-decompiled? // doing here for quick fix, maybe fix up the chain later. if (isset($fieldVal[2])) $options = explode(',', $fieldVal[2]); } // split fields (multi select) $dataOpts = array(); if ($value !== -99 && !empty($value)){ $dataOpts = explode(',', $value); } //if (isset($fieldVal[3]) && count($fieldVal[3]) > 0){ if (isset($options) && is_array($options) && count($options) > 0 && $options[0] != ''){ $optIndex = 0; foreach ($options as $opt){ echo '<div class="ui checkbox"><input type="checkbox" name="'. esc_attr( $postPrefix.$fieldKey.'-'.$optIndex ).'" id="'. esc_attr( $fieldKey.'-'.$optIndex ) .'" value="' . esc_attr( $opt ) . '"'; if (in_array($opt, $dataOpts)) echo ' checked="checked"'; echo ' /><label class="jpcrm-form-label" for="' . esc_attr( $fieldKey . '-' . $optIndex ) . '">' . esc_html( $opt ) . '</label></div>'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $optIndex++; } } else { echo '<label class="jpcrm-form-label" for="' . esc_attr( $fieldKey ) . '-0">' . esc_html__( 'No Options', 'zero-bs-crm' ) . '!</label>'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } ?> </div> <input type="hidden" name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>_dirtyflag" id="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>_dirtyflag" value="0" /> </div> <?php break; // tax case 'tax': ?> <div class="jpcrm-form-group jpcrm-form-group-span-2"> <label class="jpcrm-form-label" for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e( $fieldVal[1], 'zero-bs-crm' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, WordPress.WP.I18n.NonSingularStringLiteralText ?>:</label> <select name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>" id="<?php echo esc_attr( $fieldKey ); ?>" class="form-control zbs-watch-input zbs-dc<?php echo esc_attr( $inputClasses ); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>"> <?php // retrieve tax rates + cache global $zbsTaxRateTable; if (!isset($zbsTaxRateTable)) $zbsTaxRateTable = zeroBSCRM_taxRates_getTaxTableArr(); // if got em if (isset($zbsTaxRateTable) && is_array($zbsTaxRateTable) && count($zbsTaxRateTable) > 0){ // if $default, use that $selectVal = ''; if ($value !== -99 && !empty($value)){ $selectVal = $value; } elseif (!empty($default)) $selectVal = $default; //catcher echo '<option value=""'; if (empty($default) && ($value == -99 || ($value !== -99 && empty($value)))) echo ' selected="selected"'; echo '>' . esc_html( __( 'None', 'zero-bs-crm' ) ) . '</option>'; foreach ($zbsTaxRateTable as $taxRate){ echo '<option value="'. esc_attr( $taxRate['id'] ) .'"'; if ($selectVal == $taxRate['id']) echo ' selected="selected"'; echo '>' . esc_html( $taxRate['name'] . ' (' . $taxRate['rate'] . '%)' ) . '</option>'; } } else echo '<option value="">'. esc_html__('No Tax Rates Defined','zero-bs-crm').'!</option>'; ?> </select> <input type="hidden" name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>_dirtyflag" id="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>_dirtyflag" value="0" /> </div> <?php break; } // switch } // if is legit params // phpcs:enable } // TODO: Refactor invoice edit fields. // phpcs:disable function zeroBSCRM_html_editField_for_invoices($dataArr=array(), $fieldKey = false, $fieldVal = false, $postPrefix = 'zbs_') { /* debug if ($fieldKey == 'house-type') { echo '<tr><td colspan="2">'.$fieldKey.'<pre>'.print_r(array($fieldVal,$dataArr),1).'</pre></td></tr>'; } */ if (!empty($fieldKey) && is_array($fieldVal)){ // infer a default (Added post objmodels v3.0 as a potential.) $default = ''; if (is_array($fieldVal) && isset($fieldVal['default'])) $default = $fieldVal['default']; // get a value (this allows field-irrelevant global tweaks, like the addr catch below...) // -99 = notset $value = -99; if (isset($dataArr[$fieldKey])) $value = $dataArr[$fieldKey]; // custom classes for inputs $inputClasses = isset($fieldVal['custom-field']) ? ' zbs-custom-field' : ''; // contacts got stuck in limbo as we upgraded db in 2 phases. // following catches old str and modernises to v3.0 // make addresses their own objs 3.0+ and do away with this. // ... hard typed to avoid custom field collisions, hacky at best. switch ($fieldKey){ case 'secaddr1': if (isset($dataArr['secaddr_addr1'])) $value = $dataArr['secaddr_addr1']; break; case 'secaddr2': if (isset($dataArr['secaddr_addr2'])) $value = $dataArr['secaddr_addr2']; break; case 'seccity': if (isset($dataArr['secaddr_city'])) $value = $dataArr['secaddr_city']; break; case 'seccounty': if (isset($dataArr['secaddr_county'])) $value = $dataArr['secaddr_county']; break; case 'seccountry': if (isset($dataArr['secaddr_country'])) $value = $dataArr['secaddr_country']; break; case 'secpostcode': if (isset($dataArr['secaddr_postcode'])) $value = $dataArr['secaddr_postcode']; break; } global $zbs; switch ($fieldVal[0]){ case 'text': ?><tr class="wh-large"><th><label for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e($fieldVal[1],"zero-bs-crm"); ?>:</label></th> <td> <div class="zbs-text-input <?php echo esc_attr( $fieldKey ); ?>"> <input type="text" name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>" id="<?php echo esc_attr( $fieldKey ); ?>" class="form-control widetext zbs-dc<?php echo esc_attr( $inputClasses ); ?>" placeholder="<?php if (isset($fieldVal[2])) echo esc_attr__($fieldVal[2],'zero-bs-crm'); ?>" value="<?php if ($value !== -99) echo esc_attr( $value ); else echo esc_attr( $default ); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>" /> </div> </td></tr><?php break; case 'price': ?><tr class="wh-large"><th><label for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e($fieldVal[1],"zero-bs-crm"); ?>:</label></th> <td> <?php echo esc_html( zeroBSCRM_getCurrencyChr() ); ?> <input style="width: 130px;display: inline-block;" type="text" name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>" id="<?php echo esc_attr( $fieldKey ); ?>" class="form-control numbersOnly zbs-dc<?php echo esc_attr( $inputClasses ); ?>" placeholder="<?php if (isset($fieldVal[2])) echo esc_attr__($fieldVal[2],'zero-bs-crm'); ?>" value="<?php if ($value !== -99) echo esc_attr( $value ); else echo esc_attr( $default ); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>" /> </td></tr><?php break; case 'numberfloat': ?><tr class="wh-large"><th><label for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e($fieldVal[1],"zero-bs-crm"); ?>:</label></th> <td> <input style="width: 130px;display: inline-block;" type="text" name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>" id="<?php echo esc_attr( $fieldKey ); ?>" class="form-control numbersOnly zbs-dc<?php echo esc_attr( $inputClasses ); ?>" placeholder="<?php if (isset($fieldVal[2])) echo esc_attr__($fieldVal[2],'zero-bs-crm'); ?>" value="<?php if ($value !== -99) echo esc_attr( $value ); else echo esc_attr( $default ); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>" /> </td></tr><?php break; case 'numberint': ?><tr class="wh-large"><th><label for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e($fieldVal[1],"zero-bs-crm"); ?>:</label></th> <td> <input style="width: 130px;display: inline-block;" type="text" name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>" id="<?php echo esc_attr( $fieldKey ); ?>" class="form-control intOnly zbs-dc<?php echo esc_attr( $inputClasses ); ?>" placeholder="<?php if (isset($fieldVal[2])) echo esc_attr__($fieldVal[2],'zero-bs-crm'); ?>" value="<?php if ($value !== -99) echo esc_attr( $value ); else echo esc_attr( $default ); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>" /> </td></tr><?php break; case 'date': $datevalue = ''; if ( $value !== -99 ) { $datevalue = jpcrm_uts_to_date_str( $value, 'Y-m-d', true ); } // if this is a custom field, and is unset, we let it get passed as empty (gh-56) if ( isset( $fieldVal['custom-field'] ) && ( $value === -99 || $value === '' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $datevalue = ''; } ?> <tr class="wh-large"><th><label for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e( $fieldVal[1], 'zero-bs-crm' ); ?>:</label></th> <td> <input type="date" name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>" id="<?php echo esc_attr( $fieldKey ); ?>" placeholder="yyyy-mm-dd" value="<?php echo esc_attr( $datevalue ); ?>"/> </td></tr> <?php break; case 'datetime': $datevalue = ''; if ($value !== -99) $datevalue = $value; // if DAL3 we need to use translated dates here :) if ($zbs->isDAL3()) $datevalue = zeroBSCRM_date_i18n_plusTime(-1,$datevalue,true); ?><tr class="wh-large"><th><label for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e($fieldVal[1],"zero-bs-crm"); ?>:</label></th> <td> <input type="text" name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>" id="<?php echo esc_attr( $fieldKey ); ?>" class="form-control jpcrm-date-time zbs-dc<?php echo esc_attr( $inputClasses ); ?>" placeholder="<?php if (isset($fieldVal[2])) echo esc_attr__($fieldVal[2],'zero-bs-crm'); ?>" value="<?php echo esc_attr( $datevalue ); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>" /> </td></tr><?php break; case 'select': //don't load prefix select if prefix is hidden in settings if ($zbs->settings->get('showprefix') == 0 && $fieldKey == 'prefix') { break; } ?><tr class="wh-large"><th><label for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e($fieldVal[1],"zero-bs-crm"); ?>:</label></th> <td> <select name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>" id="<?php echo esc_attr( $fieldKey ); ?>" class="form-control zbs-watch-input zbs-dc<?php echo esc_attr( $inputClasses ); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>"> <?php // pre DAL 2 = $fieldV[3], DAL2 = $fieldV[2] $options = false; if (isset($fieldVal[3]) && is_array($fieldVal[3])) { $options = $fieldVal[3]; } else { // DAL2 these don't seem to be auto-decompiled? // doing here for quick fix, maybe fix up the chain later. if (isset($fieldVal[2])) $options = explode(',', $fieldVal[2]); } //if (isset($fieldVal[3]) && count($fieldVal[3]) > 0){ if (isset($options) && is_array($options) && count($options) > 0 && $options[0] != ''){ // if $default, use that $selectVal = ''; if ($value !== -99 && !empty($value)){ $selectVal = $value; } elseif (!empty($default)) $selectVal = $default; //catcher echo '<option value=""' . ($fieldKey == 'prefix' ? '' :' disabled="disabled"'); if (empty($default) && ($value == -99 || ($value !== -99 && empty($value)))) echo ' selected="selected"'; echo '>'. esc_html__('Select','zero-bs-crm').'</option>'; foreach ($options as $opt){ echo '<option value="' . esc_attr( $opt ) . '"'; if ($selectVal == $opt) echo ' selected="selected"'; echo '>' . esc_html( $opt ) . '</option>'; } } else echo '<option value="">'. esc_html__('No Options','zero-bs-crm').'!</option>'; ?> </select> <input type="hidden" name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>_dirtyflag" id="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>_dirtyflag" value="0" /> </td></tr><?php break; case 'tel': // Click 2 call? $click2call = $zbs->settings->get('clicktocall'); ?><tr class="wh-large"><th><label for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e($fieldVal[1],"zero-bs-crm"); ?>:</label></th> <td class="zbs-tel-wrap"> <input type="text" name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>" id="<?php echo esc_attr( $fieldKey ); ?>" class="form-control zbs-tel zbs-dc<?php echo esc_attr( $inputClasses ); ?>" placeholder="<?php if (isset($fieldVal[2])) echo esc_attr__($fieldVal[2],'zero-bs-crm'); ?>" value="<?php if ($value !== -99) echo esc_attr( $value ); else echo esc_attr( $default ); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>" /> <?php if ($click2call == "1" && $value !== -99 && !empty($value)) echo '<a href="' . esc_attr( zeroBSCRM_clickToCallPrefix() . $value ) . '" class="button"><i class="fa fa-phone"></i> ' . esc_html( $value ) . '</a>'; ?> <?php if ($fieldKey == 'mobtel'){ $sms_class = 'send-sms-none'; $sms_class = apply_filters('zbs_twilio_sms', $sms_class); do_action('zbs_twilio_nonce'); $customerMob = ''; // wh genericified //if (is_array($dataArr) && isset($dataArr[$fieldKey]) && isset($dataArr['id'])) $customerMob = zeroBS_customerMobile($dataArr['id'],$dataArr); if ($value !== -99) $customerMob = $value; if (!empty($customerMob)) echo '<a class="' . esc_attr( $sms_class ) . ' button" data-smsnum="' . esc_attr( $customerMob ) .'"><i class="mobile alternate icon"></i> '. esc_html__('SMS','zero-bs-crm').': ' . esc_html( $customerMob ) . '</a>'; } ?> </td></tr><?php break; case 'email': // added zbs-text-input class 5/1/18 - this allows "linkify" automatic linking // ... via js <div class="zbs-text-input"> // removed from email for now zbs-text-input ?><tr class="wh-large"><th><label for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e($fieldVal[1],"zero-bs-crm"); ?>:</label></th> <td> <div class="<?php echo esc_attr( $fieldKey ); ?>"> <input type="text" name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>" id="<?php echo esc_attr( $fieldKey ); ?>" class="form-control zbs-email zbs-dc<?php echo esc_attr( $inputClasses ); ?>" placeholder="<?php if (isset($fieldVal[2])) echo esc_attr__($fieldVal[2],'zero-bs-crm'); ?>" value="<?php if ($value !== -99) echo esc_attr( $value ); else echo esc_attr( $default ); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>" /> </div> </td></tr><?php break; case 'textarea': ?><tr class="wh-large"><th><label for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e($fieldVal[1],"zero-bs-crm"); ?>:</label></th> <td> <textarea name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>" id="<?php echo esc_attr( $fieldKey ); ?>" class="form-control zbs-dc<?php echo esc_attr( $inputClasses ); ?>" placeholder="<?php if (isset($fieldVal[2])) echo esc_attr__($fieldVal[2],'zero-bs-crm'); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>"><?php if ($value !== -99) echo esc_textarea( $value ); else echo esc_textarea( $default ); ?></textarea> </td></tr><?php break; #} Added 1.1.19 case 'selectcountry': $countries = zeroBSCRM_loadCountryList(); ?><tr class="wh-large"><th><label for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e($fieldVal[1],"zero-bs-crm"); ?>:</label></th> <td> <select name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>" id="<?php echo esc_attr( $fieldKey ); ?>" class="form-control zbs-dc<?php echo esc_attr( $inputClasses ); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>"> <?php #if (isset($fieldVal[3]) && count($fieldVal[3]) > 0){ if (isset($countries) && count($countries) > 0){ //catcher echo '<option value=""'; if (empty($default) && ($value == -99 || ($value !== -99 && empty($value)))) echo ' selected="selected"'; echo '>'. esc_html__('Select','zero-bs-crm').'</option>'; foreach ($countries as $countryKey => $country){ // temporary fix for people storing "United States" but also "US" // needs a migration to iso country code, for now, catch the latter (only 1 user via api) echo '<option value="' . esc_attr( $country ) . '"'; if ($value !== -99 && ( strtolower($value) == strtolower($country) || strtolower($value) == strtolower($countryKey) )) echo ' selected="selected"'; echo '>' . esc_html( $country ) . '</option>'; } } else echo '<option value="">'. esc_html__('No Countries Loaded','zero-bs-crm').'</option>'; ?> </select> </td></tr><?php break; // 2.98.5 added autonumber, checkbox, radio // auto number - can't actually edit autonumbers, so its just outputting :) case 'autonumber': ?><tr class="wh-large"><th><label for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e($fieldVal[1],"zero-bs-crm"); ?>:</label></th> <td class="zbs-field-id"> <?php // output any saved autonumber for this obj $str = ''; if ($value !== -99) $str = $value; // we strip the hashes saved in db for easy separation later $str = str_replace('#','',$str); // then output... if (empty($str)) echo '~'; else echo esc_html( $str ); // we also output as input, which stops any overwriting + makes new ones for new records echo '<input type="hidden" value="' . esc_attr( $str ) . '" name="'. esc_attr( $postPrefix.$fieldKey ) .'" />'; ?> </td></tr><?php break; // radio case 'radio': ?><tr class="wh-large"><th><label for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e($fieldVal[1],"zero-bs-crm"); ?>:</label></th> <td> <div class="zbs-field-radio-wrap"> <?php // pre DAL 2 = $fieldV[3], DAL2 = $fieldV[2] $options = false; if (isset($fieldVal[3]) && is_array($fieldVal[3])) { $options = $fieldVal[3]; } else { // DAL2 these don't seem to be auto-decompiled? // doing here for quick fix, maybe fix up the chain later. if (isset($fieldVal[2])) $options = explode(',', $fieldVal[2]); } //if (isset($fieldVal[3]) && count($fieldVal[3]) > 0){ if (isset($options) && is_array($options) && count($options) > 0 && $options[0] != ''){ $optIndex = 0; foreach ($options as $opt){ echo '<div class="zbs-radio"><input type="radio" name="'. esc_attr( $postPrefix.$fieldKey ) .'" id="'. esc_attr( $fieldKey.'-'.$optIndex ) .'" value="' . esc_attr( $opt ) . '"'; if ($value !== -99 && $value == $opt) echo ' checked="checked"'; echo ' /> <label for="'. esc_attr( $fieldKey.'-'.$optIndex ) .'">' . esc_html( $opt ) . '</label></div>'; $optIndex++; } } else echo '<label for="'. esc_attr( $fieldKey ) .'-0">'. esc_attr__('No Options','zero-bs-crm').'!</label>'; //<input type="radio" name="'.$postPrefix.$fieldKey.'" id="'.$fieldKey.'-0" value="" checked="checked" /> ?> </div> <input type="hidden" name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>_dirtyflag" id="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>_dirtyflag" value="0" /> </td></tr><?php break; // checkbox case 'checkbox': ?><tr class="wh-large"><th><label for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e($fieldVal[1],"zero-bs-crm"); ?>:</label></th> <td> <div class="zbs-field-checkbox-wrap"> <?php // pre DAL 2 = $fieldV[3], DAL2 = $fieldV[2] $options = false; if (isset($fieldVal[3]) && is_array($fieldVal[3])) { $options = $fieldVal[3]; } else { // DAL2 these don't seem to be auto-decompiled? // doing here for quick fix, maybe fix up the chain later. if (isset($fieldVal[2])) $options = explode(',', $fieldVal[2]); } // split fields (multi select) $dataOpts = array(); if ($value !== -99 && !empty($value)){ $dataOpts = explode(',', $value); } //if (isset($fieldVal[3]) && count($fieldVal[3]) > 0){ if (isset($options) && is_array($options) && count($options) > 0 && $options[0] != ''){ $optIndex = 0; foreach ($options as $opt){ echo '<div class="ui checkbox"><input type="checkbox" name="'. esc_attr( $postPrefix.$fieldKey.'-'.$optIndex ).'" id="'. esc_attr( $fieldKey.'-'.$optIndex ) .'" value="' . esc_attr( $opt ) . '"'; if (in_array($opt, $dataOpts)) echo ' checked="checked"'; echo ' /><label for="'. esc_attr( $fieldKey.'-'.$optIndex ) .'">' . esc_html( $opt ) . '</label></div>'; $optIndex++; } } else echo '<label for="'. esc_attr( $fieldKey ).'-0">'. esc_html__('No Options','zero-bs-crm').'!</label>'; ?> </div> <input type="hidden" name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>_dirtyflag" id="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>_dirtyflag" value="0" /> </td></tr><?php break; // tax case 'tax': ?><tr class="wh-large"><th><label for="<?php echo esc_attr( $fieldKey ); ?>"><?php esc_html_e($fieldVal[1],"zero-bs-crm"); ?>:</label></th> <td> <select name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>" id="<?php echo esc_attr( $fieldKey ); ?>" class="form-control zbs-watch-input zbs-dc<?php echo esc_attr( $inputClasses ); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>"> <?php // retrieve tax rates + cache global $zbsTaxRateTable; if (!isset($zbsTaxRateTable)) $zbsTaxRateTable = zeroBSCRM_taxRates_getTaxTableArr(); // if got em if (isset($zbsTaxRateTable) && is_array($zbsTaxRateTable) && count($zbsTaxRateTable) > 0){ // if $default, use that $selectVal = ''; if ($value !== -99 && !empty($value)){ $selectVal = $value; } elseif (!empty($default)) $selectVal = $default; //catcher echo '<option value=""'; if (empty($default) && ($value == -99 || ($value !== -99 && empty($value)))) echo ' selected="selected"'; echo '>' . esc_html( __( 'None', 'zero-bs-crm' ) ) . '</option>'; foreach ($zbsTaxRateTable as $taxRate){ echo '<option value="'. esc_attr( $taxRate['id'] ) .'"'; if ($selectVal == $taxRate['id']) echo ' selected="selected"'; echo '>' . esc_html( $taxRate['name'] . ' (' . $taxRate['rate'] . '%)' ) . '</option>'; } } else echo '<option value="">'. esc_html__('No Tax Rates Defined','zero-bs-crm').'!</option>'; ?> </select> <input type="hidden" name="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>_dirtyflag" id="<?php echo esc_attr( $postPrefix ); ?><?php echo esc_attr( $fieldKey ); ?>_dirtyflag" value="0" /> </td></tr><?php break; } // switch } // if is legit params } // phpcs:enable /* ====================================================== / Edit Pages Field outputter ====================================================== */ /* ====================================================== Table Views (temporary) (These need moving into JS globals - something like bringing the listview js into 1 model js/php obj outputter) ====================================================== */ // Temp here - takes a potential transaction column header // (can be a field key or a column key) and finds a str for title function zeroBS_objDraw_transactionColumnHeader($colKey=''){ global $zbsTransactionFields, $zeroBSCRM_columns_transaction; $ret = ucwords(str_replace('_',' ',$colKey)); // all fields (inc custom:) if (isset($zbsTransactionFields) && is_array($zbsTransactionFields) && isset($zbsTransactionFields[$colKey])){ // key => name $ret = $zbsTransactionFields[$colKey][1]; } // all columns (any with same key will override) if (isset($zeroBSCRM_columns_transaction['all']) && is_array($zeroBSCRM_columns_transaction['all']) && isset($zeroBSCRM_columns_transaction['all'][$colKey])){ // key => name $ret = $zeroBSCRM_columns_transaction['all'][$colKey][0]; } return $ret; } // Temp here - takes a potential transaction column + returns html // these are mimics of js draw funcs, move into globals (eventually) // hacky at best... (WH wrote to quickly satisfy Borge freelance) function zeroBS_objDraw_transactionColumnTD($colKey='',$obj=false){ $ret = ''; if (!empty($colKey) && is_array($obj)){ $linkOpen = jpcrm_esc_link('edit',$obj['id'],ZBS_TYPE_TRANSACTION); switch ($colKey){ case 'id': $idRef = zeroBS_objDraw_generic_id($obj); if (isset($obj['ref'])){ if (!empty($idRef)) $idRef .= ' - '; $idRef .= $obj['ref']; } $ret = '<a href="'.$linkOpen.'">'. $idRef .'</a>'; $ret .= !empty($obj['title']) ? '<br>'.$obj['title'] : ''; break; case 'editlink': $ret = '<a href="'.$linkOpen.'" class="ui button basic small">'. __('Edit','zero-bs-crm') . "</a>"; break; case 'date': if ( isset( $obj['date_date'] ) ) { $ret = $obj['date_date']; } break; case 'item': $itemStr = ''; if (isset($obj['meta'])) $itemStr = $obj['meta']['item']; // <3.0 if (isset($obj['title'])) $itemStr = $obj['title']; // 3.0 $ret = '<a href="'.$linkOpen.'">' . $itemStr . "</a>"; break; case 'total': $total = 0; if (isset($obj['meta'])) $total = $obj['meta']['total']; // <3.0 if (isset($obj['total'])) $total = $obj['total']; // 3.0 $ret = zeroBSCRM_formatCurrency($total); break; case 'status': $status = ''; if (isset($obj['meta'])) $status = $obj['meta']['status']; // <3.0 if (isset($obj['status'])) $status = $obj['status']; // 3.0 $ret = "<span class='".zeroBSCRM_html_transactionStatusLabel($obj)."'>" . ucfirst($status) . "</span>"; break; } // if still empty, let's try generic text if (empty($ret)) $ret = zeroBS_objDraw_generic_text($colKey,$obj); } return $ret; } // Temp here // these are mimics of js draw funcs, move into globals (eventually) function zeroBS_objDraw_generic_id($obj=false){ $ret = ''; if (is_array($obj)){ if (isset($obj['id'])) $ret = '#'.$obj['id']; if (isset($obj['zbsid'])) $ret = '#'.$obj['zbsid']; } return $ret; } function zeroBS_objDraw_generic_text($key='',$obj=false){ $ret = ''; if (!empty($key) && is_array($obj)){ if (isset($obj[$key])) $ret = $obj[$key]; if (isset($obj['meta']) && is_array($obj['meta']) && isset($obj['meta'][$key])) $ret = $obj['meta'][$key]; } return $ret; } /* ====================================================== / Table Views (temporary) ====================================================== */ // quick workaround to turn 29999 into 2.99.99 // noting that the real issue here is our non delimited migration numbers :facepalm: function zeroBSCRM_format_migrationVersion($ver=''){ // catch 3000 $ver = str_replace( '000', '0', $ver); switch ( strlen( $ver) ){ // catch x.x case 2: $migrationName = substr($ver,0,1).'.'.substr($ver,1,1); break; // catch x.x.x case 3: $migrationName = substr($ver,0,1).'.'.substr($ver,1,1).'.'.substr($ver,2); break; case 4: // if second char is 0 if ( substr( $ver, 1, 1 ) == 0 ){ // e.g. 3010 = 3.0.10 $migrationName = substr($ver,0,1).'.'.substr($ver,1,1).'.'.substr($ver,2); } else { // e.g. 3111 = 3.11.1 $migrationName = substr($ver,0,1).'.'.substr($ver,1,2).'.'.substr($ver,3); } break; // catch edge case 29999 case 5: // e.g. 29999 = 2.99 $migrationName = substr($ver,0,1).'.'.substr($ver,1,2); break; // default: $migrationName = $ver; break; } return $migrationName; }
projects/plugins/crm/includes/ZeroBSCRM.Core.php
<?php /** * Jetpack CRM Core * * @author Woody Hayday, Mike Stott * @package ZeroBSCRM * @since 2.27 */ if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } /** * Main ZeroBSCRM Class. * * @class ZeroBSCRM * @version 2.27 */ final class ZeroBSCRM { /** * ZeroBSCRM version. * * @var string */ public $version = '6.4.1'; /** * WordPress version tested with. * * @var string */ public $wp_tested = '6.5'; /** * WordPress update API version. * * @var string */ public $api_ver = '1.0'; /** * Jetpack CRM update API version. * * @var string */ public $update_api_version = '1.0'; /** * ZeroBSCRM DB version. * * @var string */ public $db_version = '3.0'; /** * Database details. * * @var array */ public $database_server_info = array(); /** * ZeroBSCRM DAL version. * * @var string */ public $dal_version = '3.0'; /** * ZeroBSCRM Extension Compatible versions * Stores which extensions are viable to use with newly-migrated v3.0 * * @var string */ public $compat_versions = array( // v3.0 Migration needed a 'minimum version' for any extensions which might not work with v3.0 but were active premigration // 15th Nov - as numbers it does not like the 1.4.1 type format so added as strings. 'v3extminimums' => array( 'advancedsegments' => '1.3', 'apiconnector' => '1.6', 'automations' => '1.4.1', 'aweber' => '1.2', 'awesomesupport' => '2.5', 'batchtag' => '2.3', 'passwordmanager' => '1.4.1', 'clientportalpro' => '1.7', 'contactform' => '2.5', 'convertkit' => '2.5', 'csvpro' => '2.0', 'envato' => '2.4.2', 'exitbee' => '1.1', 'funnels' => '1.2', 'googlecontact' => '2.6', 'gravity' => '2.6', 'groove' => '2.6', 'invpro' => '2.6', 'livestorm' => '1.1', 'mailcamp' => '2.0.4', 'mailchimp' => '2.6', 'membermouse' => '1.5', 'optinmonster' => '1.1', 'paypal' => '2.6.1', 'registrationmagic' => '1.1', 'salesdash' => '2.6', 'stripe' => '2.6.2', 'systememail' => '1.1', 'twilio' => '1.5', 'woosync' => '2.9', 'wordpressutilities' => '1.2', 'worldpay' => '2.4', ), ); /** * ZeroBSCRM DAL . * * @var object (DAL Class init) ;) */ public $DAL = false; /** * Dependency checker * * @var object JPCRM_DependencyChecker init */ public $dependency_checker = false; /** * Feature sniffer * * @var object JPCRM_FeatureSniffer init */ public $feature_sniffer = false; /** * WordPress User Integrations * * @var object Wordpress_User_Integration class */ public $wordpress_user_integration = false; /** * Zapier integration * * @var ? */ public $zapier = false; /** * Fonts * * @var object JPCRM_Fonts init */ public $fonts = false; /** * DB1 compatability support * * @var Bool - if true, basically $obj['meta'] is a clone of $obj itself (To be disabled once safely in DAL2 + updated extensions) */ public $db1CompatabilitySupport = false; /** * DB2 compatability support * * @var Bool - if true, basically $obj['meta'] is a clone of $obj itself (To be disabled once safely in DAL3 + updated extensions) * This variant accounts for stray objs in quotes, trans, invs, etc. */ public $db2CompatabilitySupport = false; /** * ZeroBSCRM DB Version Switch. * * @var string */ public $DBVER = 1; /** * The single instance of the class. * * @var ZeroBSCRM * @since 2.1 */ protected static $_instance = null; /** * JP CRM Page Loaded (KEY - used for screenoptions) (equivilent of pagenow) * * @var string */ public $pageKey = 'root'; /** * WordPress Admin notice stack * * @var array */ public $admin_notices = array(); /** * Hide admin_notices for specified pages * * @var array */ public $hide_admin_pages = array( // hidden due to #gh-1442 'manage-tasks', 'zerobscrm-csvimporterlite-app', ); /** * Template path, this is where we look in the theme directory for templates * * @var string */ public $template_path = 'jetpack-crm'; /** * Extensions instances * * @var Jetpack CRM Extensions */ public $extensions = null; /** * External Sources * * @var Jetpack CRM External Sources */ public $external_sources = null; /** * Listview filters * * @var array Jetpack CRM External Sources */ public $listview_filters = array(); /** * Settings Object * * @var Jetpack CRM Settings Object */ public $settings = null; /** * Internal Automator Block * * @var Bool - if true, IA will not fire anything :) */ public $internalAutomatorBlock = false; /** * Metaboxes Object * * @var Jetpack CRM Metaboxes Object */ public $metaboxes = null; /** * Menus Object * * @var Jetpack CRM Menus Array * This ultimately adds any WP menus that need injecting */ private $menu = null; /** * Learn Menu Object * * @var Jetpack CRM Learn menu class instance */ public $learn_menu = null; /** * URLS Array * * @var Jetpack CRM URLS list */ public $urls; /** * Slugs Array * * @var Jetpack CRM Slugs list */ public $slugs; /** * Transient Array * * @var Jetpack CRM Transients list */ public $transients; /** * Houses all module classes * e.g. $zbs->modules->woosync */ public $modules = null; /** * Package installer (Automattic\JetpackCRM\Package_Installer) */ public $package_installer = null; /** * OAuth handler */ public $oauth = null; /** * Endpoint Listener */ public $listener = null; /** * Encryption tooling */ public $encryption = null; /** * Included Array (means we can not 'reinclude' stripe etc.) */ public $included = array( 'stripe' => false, ); /** * Libraries included (3.0.12+) * Note: All paths need to be prepended by ZEROBSCRM_PATH before use */ private $libs = array(); /** * Usage Tracking * * @var object Usage tracking class */ public $tracking = false; /** * Page Messages Array * Experimental: stores msgs such as "Contact Updated" * * @var msg arr */ public $pageMessages; /** * Templating: placeholders * * @var object Placeholder Class */ public $templating_placeholders = false; /** * Acceptable mime types Array * * @var Jetpack CRM Acceptable mime types list */ public $acceptable_mime_types; /** * Acceptable fields to be included in the Total Value of contacts and companies * * @var Jetpack CRM Acceptable fields to be included in the Total Value */ public $acceptable_total_value_fields = array( 'transactions' => 'Transactions', 'invoices' => 'Invoices', ); /** * Acceptable html array * * @var Jetpack CRM Acceptable html types list * Was previously: $zeroBSCRM_allowedHTML */ public $acceptable_html = array( 'h1' => array( 'class' => array(), 'style' => array(), 'id' => array(), ), 'h2' => array( 'class' => array(), 'style' => array(), 'id' => array(), ), 'h3' => array( 'class' => array(), 'style' => array(), 'id' => array(), ), 'h4' => array( 'class' => array(), 'style' => array(), 'id' => array(), ), 'h5' => array( 'class' => array(), 'style' => array(), 'id' => array(), ), 'h6' => array( 'class' => array(), 'style' => array(), 'id' => array(), ), 'a' => array( 'href' => array(), 'title' => array(), 'target' => array(), 'class' => array(), ), 'b' => array(), 'br' => array(), 'em' => array(), 'strong' => array(), 'ul' => array(), 'ol' => array(), 'li' => array(), 'p' => array( 'style' => true, ), 'div' => array( 'class' => array(), 'style' => array(), 'id' => array(), ), 'span' => array( 'class' => array(), 'style' => array(), 'id' => array(), ), 'img' => array( 'class' => array(), 'style' => array(), 'src' => array(), ), 'i' => array( 'class' => array(), ), 'table' => array( 'tr' => array( 'th' => array( 'label' => array(), ), 'class' => array(), 'label' => array(), 'th' => array(), ), 'style' => array(), 'label' => array(), ), 'td' => array(), 'tr' => array(), 'blockquote' => array(), 'del' => array(), 'hr' => array(), ); /** * Acceptable (restricted) html array * * @var Jetpack CRM Acceptable (restricted) html types list * (e.g. for use in contact logs) */ public $acceptable_restricted_html = array( 'a' => array( 'href' => array(), 'title' => array(), 'id' => array(), ), 'br' => array(), 'em' => array(), 'strong' => array(), 'blockquote' => array(), ); /** * Error Codes Array * Experimental: loads + stores error codes, (only when needed/requested) * * @var error code arr */ private $errorCodes; /** * Main ZeroBSCRM Instance. * * Ensures only one instance of ZeroBSCRM is loaded or can be loaded. * * @since 2.27 * @static * @return ZeroBSCRM - Main instance. */ public static function instance() { if ( self::$_instance === null ) { self::$_instance = new self(); } return self::$_instance; } /** * Unserializing instances of this class is forbidden. * * @since 2.1 */ public function __wakeup() { zerobscrm_doing_it_wrong( __FUNCTION__, __( 'Cheatin&#8217; huh?', 'zero-bs-crm' ), '2.1' ); } /** * Auto-load in-accessible properties on demand - What is this wizadrey? * * @param mixed $key Key name. * @return mixed */ /* See: http://php.net/manual/en/language.oop5.overloading.php#object.get public function __get( $key ) { if ( in_array( $key, array( 'payment_gateways', 'shipping', 'mailer', 'checkout' ), true ) ) { return $this->$key(); } } */ /** * Jetpack CRM Constructor. */ public function __construct() { // Simple global definitions without loading any core files... // required for verify_minimum_requirements() // define constants & globals $this->define_constants(); // Verify we have minimum requirements (e.g. DAL3.0 and extension versions up to date) if ( $this->verify_minimum_requirements() ) { $this->debugMode(); // } Load includes $this->includes(); // urls, slugs, (post inc.) $this->setupUrlsSlugsEtc(); // } Initialisation $this->init_hooks(); /** * Feature flag to hide the new onboarding wizard page. * * @ignore * @since TBD * * @param bool Determine if we should initialize the new OBW logic. */ if ( apply_filters( 'jetpack_crm_feature_flag_onboarding_wizard_v2', false ) ) { Automattic\Jetpack_CRM\Onboarding_Wizard\Bootstrap::get_instance(); } // } Post Init hook do_action( 'zerobscrm_loaded' ); } else { // used by some extensions to determine if current page is an admin page require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.AdminPages.Checks.php'; // extensions use the dependency checker functions require_once ZEROBSCRM_INCLUDE_PATH . 'jpcrm-dependency-checker.php'; $this->dependency_checker = new JPCRM_DependencyChecker(); } // display any wp admin notices in the stack // needs to be outside of any above functionality as used for exposing failed verify_minimum_requirements() add_action( 'admin_notices', array( $this, 'wp_admin_notices' ) ); } /** * Verify we have minimum requirements (e.g. DAL3.0) */ private function verify_minimum_requirements() { // fresh installs get a pass so that migrations can run // ... as soon as DB is installed, this'll be skipped // gather database server info $this->get_database_server_info(); if ( ! $this->is_database_installed() ) { return true; } // v5.0+ JPCRM requires DAL3+ if ( ! $this->isDAL3() ) { // we need urls $this->setupUrlsSlugsEtc(); // build message $message_html = '<p>' . sprintf( esc_html__( 'This version of CRM (%1$s) requires an upgraded database (3.0). Your database is using an older version than this (%2$s). To use CRM you will need to install version 4 of CRM and run the database upgrade.', 'zero-bs-crm' ), $this->version, $this->dal_version ) . '</p>'; // phpcs:ignore WordPress.WP.I18n.MissingTranslatorsComment ##WLREMOVE $message_html = '<p>' . sprintf( esc_html__( 'This version of Jetpack CRM (%1$s) requires an upgraded database (3.0). Your database is using an older version than this (%2$s). To use Jetpack CRM you will need to install version 4 of Jetpack CRM and run the database upgrade.', 'zero-bs-crm' ), $this->version, $this->dal_version ) . '</p>'; // phpcs:ignore WordPress.WP.I18n.MissingTranslatorsComment $message_html .= '<p><a href="' . esc_url( $this->urls['kb-pre-v5-migration-todo'] ) . '" target="_blank" class="button">' . __( 'Read the guide on migrating', 'zero-bs-crm' ) . '</a></p>'; ##/WLREMOVE $this->add_wp_admin_notice( '', array( 'class' => 'warning', 'html' => $message_html, ) ); return false; } elseif ( ! function_exists( 'openssl_get_cipher_methods' ) ) { // build message $message_html = '<p>' . sprintf( __( 'Jetpack CRM uses the OpenSSL extension for PHP to properly protect sensitive data. Most PHP environments have this installed by default, but it seems yours does not; we recommend contacting your host for further help.', 'zero-bs-crm' ), $this->version, $this->dal_version ) . '</p>'; $message_html .= '<p><a href="' . esc_url( 'https://www.php.net/manual/en/book.openssl.php' ) . '" target="_blank" class="button">' . __( 'PHP docs on OpenSSL', 'zero-bs-crm' ) . '</a></p>'; $this->add_wp_admin_notice( '', array( 'class' => 'warning', 'html' => $message_html, ) ); return false; } return true; } /** * Verify our extensions meet minimum requirements (e.g. DAL3.0) * Where extensions are found which do not meet requirements, these are deactivated and notices posted * Note: This has to fire lower down the stack than `verify_minimum_requirements()` * because it relies on extension linkages */ private function verify_extension_minimum_requirements() { // v5.0+ JPCRM/DAL3 requires these extension versions $installed_extensions = zeroBSCRM_installedProExt(); if ( is_array( $installed_extensions ) ) { foreach ( $installed_extensions as $extension_name => $extension_info ) { // get minimum version okay with v3 $minimum_version = 99.99; if ( isset( $this->compat_versions['v3extminimums'][ $extension_info['key'] ] ) ) { $minimum_version = $this->compat_versions['v3extminimums'][ $extension_info['key'] ]; } // do we have an active outdated version? if ( $extension_info['active'] == 1 && $minimum_version > 0 && ! ( version_compare( $extension_info['ver'], $minimum_version ) >= 0 ) ) { // deactivate jpcrm_extensions_deactivate_by_key( $extension_info['key'] ); // show warning notice $message_html = '<p>' . sprintf( __( 'Your CRM extension %1$s (v%2$s) is not compatible with this version of CRM. You will need to run a database upgrade to use this extension. For now this extension has been deactivated.', 'zero-bs-crm' ), $extension_name, $extension_info['ver'] ) . '</p>'; ##WLREMOVE $message_html = '<p>' . sprintf( __( 'Your Jetpack CRM extension %1$s (v%2$s) is not compatible with this version of Jetpack CRM. You will need to run a database upgrade to be able to use this extension. For now this extension has been deactivated.', 'zero-bs-crm' ), $extension_name, $extension_info['ver'] ) . '</p>'; $message_html .= '<p><a href="' . esc_url( $this->urls['kb-pre-v5-migration-todo'] ) . '" target="_blank" class="button">' . __( 'Read the guide on migrating', 'zero-bs-crm' ) . '<a></p>'; ##/WLREMOVE $this->add_wp_admin_notice( '', array( 'class' => 'warning', 'html' => $message_html, ) ); } } } return false; } /** * Add admin notice to the stack */ private function add_wp_admin_notice( $page, $notice ) { // validate existing if ( ! is_array( $this->admin_notices ) ) { $this->admin_notices = array(); } // add to stack if new page if ( ! isset( $this->admin_notices[ $page ] ) ) { $this->admin_notices[ $page ] = array(); } // add notice to stack $this->admin_notices[ $page ][] = $notice; } /** * Output any admin notices in the stack */ public function wp_admin_notices() { global $pagenow; if ( is_array( $this->admin_notices ) ) { foreach ( $this->admin_notices as $page => $notices ) { // matching page or all pages (empty) if ( $pagenow == $page || empty( $page ) ) { foreach ( $notices as $notice ) { echo '<div class="notice notice-' . esc_attr( $notice['class'] ) . ' is-dismissible">' . $notice['html'] . '</div>'; } } } } } /** * Maintain a list of Jetpack CRM extension slugs here. * (This was an MS initiative for updates/licensing, WH removed 27/11/18, doing via Keys = rebrandr friendly) */ /* public $zeroBSCRM_extensionSlugs = array( 'ZeroBSCRM_BulkTagger.php', ); */ /** * Define ZeroBSCRM Constants. */ private function define_constants() { // Main paths etc. $this->define( 'ZBS_ABSPATH', dirname( ZBS_ROOTFILE ) . '/' ); $this->define( 'ZEROBSCRM_PATH', plugin_dir_path( ZBS_ROOTFILE ) ); $this->define( 'ZEROBSCRM_URL', plugin_dir_url( ZBS_ROOTFILE ) ); // Template paths $this->define( 'ZEROBSCRM_TEMPLATEPATH', ZEROBSCRM_PATH . 'templates/' ); $this->define( 'ZEROBSCRM_TEMPLATEURL', ZEROBSCRM_URL . 'templates/' ); // include/module paths $this->define( 'ZEROBSCRM_INCLUDE_PATH', ZEROBSCRM_PATH . 'includes/' ); $this->define( 'JPCRM_MODULES_PATH', ZEROBSCRM_PATH . 'modules/' ); // } define that the CORE has been loaded - for backwards compatibility with other extensions $this->define( 'ZBSCRMCORELOADED', true ); // } Menu types $this->define( 'ZBS_MENU_FULL', 1 ); $this->define( 'ZBS_MENU_SLIM', 2 ); $this->define( 'ZBS_MENU_CRMONLY', 3 ); // } Debug $this->define( 'ZBS_CRM_DEBUG', true ); } private function debugMode() { if ( defined( 'ZBS_CRM_DEBUG' ) ) { /* ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); */ } } // shorthand for lack of presence of any DB presence public function is_database_installed() { global $ZBSCRM_t, $wpdb; // we need db require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.Database.php'; // check $tables = $wpdb->get_results( "SHOW TABLES LIKE '" . $ZBSCRM_t['contacts'] . "'" ); return ( count( $tables ) > 0 ); } /** * Retrieves MySQL/MariaDB/Percona database server info */ public function get_database_server_info() { if ( empty( $this->database_server_info ) ) { // Adapted from proposed SQLite integration for core // https://github.com/WordPress/sqlite-database-integration/blob/4a687709bb16a569a7d1ecabfcce433c0e471de8/health-check.php if ( defined( 'DB_ENGINE' ) && DB_ENGINE === 'sqlite' ) { $db_engine = DB_ENGINE; $db_engine_label = 'SQLite'; $raw_version = class_exists( 'SQLite3' ) ? SQLite3::version()['versionString'] : null; $version = $raw_version; } else { global $wpdb; $raw_version = $wpdb->get_var( 'SELECT VERSION()' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.DirectQuery $version = preg_replace( '/[^0-9.].*/', '', $raw_version ); if ( stripos( $raw_version, 'mariadb' ) !== false ) { $db_engine = 'mariadb'; $db_engine_label = 'MariaDB'; } else { $db_engine = 'mysql'; $db_engine_label = 'MySQL'; } } $database_server_info = array( 'raw_version' => $raw_version, 'version' => $version, 'db_engine' => $db_engine, 'db_engine_label' => $db_engine_label, ); $this->database_server_info = $database_server_info; } return $this->database_server_info; } // } Use this for shorthand checking old DAL public function isDAL1() { // is DAL = 1.0 return ( version_compare( $this->dal_version, '2.53' ) < 0 ); } // } Use this for shorthand checking new DAL additions // this says "is At least DAL2" public function isDAL2() { // is DAL > 1.0 return ( version_compare( $this->dal_version, '1.0' ) > 0 ); } // } Use this for shorthand checking new DAL additions // this says "is At least DAL3" public function isDAL3() { // is DAL > 1.0 return ( version_compare( $this->dal_version, '2.53' ) > 0 ); } // } Use this to output the number of plugins with "Jetpack CRM" in the name public function extensionCount( $activatedOnly = false ) { /* Following func: zeroBSCRM_extensionsInstalledCount ... will get all active rebrandr extensions, ... and all active/inactive branded extensions ... and returns a count here */ return zeroBSCRM_extensionsInstalledCount( $activatedOnly ); } private function setupUrlsSlugsEtc() { // array check if ( ! is_array( $this->urls ) ) { $this->urls = array(); } if ( ! is_array( $this->slugs ) ) { $this->slugs = array(); } if ( ! is_array( $this->transients ) ) { $this->transients = array(); } if ( ! is_array( $this->acceptable_mime_types ) ) { $this->acceptable_mime_types = array(); } if ( ! is_array( $this->pageMessages ) ) { $this->pageMessages = array(); } // Urls $this->urls['home'] = 'https://jetpackcrm.com'; $this->urls['kb'] = 'https://kb.jetpackcrm.com'; $this->urls['support'] = 'https://kb.jetpackcrm.com/crm-support/'; $this->urls['feedback'] = 'https://kb.jetpackcrm.com/crm-support/'; $this->urls['pricing'] = 'https://jetpackcrm.com/pricing/'; $this->urls['usagetrackinginfo'] = 'https://jetpackcrm.com/usage-tracking/'; $this->urls['support-forum'] = 'https://wordpress.org/support/plugin/zero-bs-crm'; ##WLREMOVE $this->urls['betafeedbackemail'] = 'hello@jetpackcrm.com'; // SPECIFICALLY ONLY USED FOR FEEDBACK ON BETA RELEASES, DO NOT USE ELSEWHERE ##/WLREMOVE $this->urls['docs'] = 'https://kb.jetpackcrm.com/'; $this->urls['productsdatatools'] = 'https://jetpackcrm.com/data-tools/'; $this->urls['extimgrepo'] = 'https://jetpackcrm.com/_plugin_dependent_assets/_i/'; $this->urls['rateuswporg'] = 'https://wordpress.org/support/view/plugin-reviews/zero-bs-crm?filter=5#new-post'; $this->urls['extdlreporoot'] = 'https://jetpack-crm-cdn.s3.amazonaws.com/'; $this->urls['extdlrepo'] = $this->urls['extdlreporoot'] . 'ext/'; $this->urls['extdlfonts'] = $this->urls['extdlreporoot'] . 'fonts/'; $this->urls['extdlpackages'] = $this->urls['extdlreporoot'] . 'packages/'; $this->urls['apidocs'] = 'https://automattic.github.io/jetpack-crm-api-docs/'; $this->urls['oauthdocs'] = 'https://kb.jetpackcrm.com/knowledge-base/using-gmail-with-jetpack-crm-mail-delivery-system/#setting-up-gmail-oauth-connection-and-mail-delivery-method'; $this->urls['woosync'] = 'https://jetpackcrm.com/woocommerce/'; $this->urls['woomanagingorders'] = 'https://woocommerce.com/document/managing-orders/#order-statuses'; $this->urls['core-automations'] = 'https://jetpackcrm.com/features/automations'; // used for ext manager: $this->urls['checkoutapi'] = 'https://jetpackcrm.com/wp-json/zbsextensions/v1/extensions/0'; $this->urls['howtoinstall'] = 'https://kb.jetpackcrm.com/knowledge-base/how-do-i-install-a-zero-bs-extension/'; $this->urls['apiconnectorsales'] = 'https://jetpackcrm.com/product/api-connector/'; $this->urls['autonumberhelp'] = 'https://kb.jetpackcrm.com/knowledge-base/custom-field-type-autonumber/'; $this->urls['akamode'] = 'https://jetpackcrm.com/feature/aka-mode/'; $this->urls['licensinginfo'] = 'https://kb.jetpackcrm.com/knowledge-base/yearly-subscriptions-refunds/'; $this->urls['easyaccessguide'] = 'https://kb.jetpackcrm.com/knowledge-base/easy-access-links-for-client-portal/'; // API v3.0 - licensing - 5/12/18 $this->urls['api'] = 'https://app.jetpackcrm.com/api/updates/updates'; $this->urls['apilocalcheck'] = 'https://app.jetpackcrm.com/api/updates/localcheck'; $this->urls['smm'] = 'https://app.jetpackcrm.com/api/welcome-wizard'; $this->urls['api-support'] = 'https://app.jetpackcrm.com/api/support'; // account $this->urls['account'] = 'https://app.jetpackcrm.com/'; $this->urls['licensekeys'] = 'https://app.jetpackcrm.com/license-keys'; // } sales urls $this->urls['products'] = 'https://jetpackcrm.com/extensions/'; $this->urls['extcsvimporterpro'] = 'https://jetpackcrm.com/product/csv-importer-pro/'; $this->urls['invpro'] = 'https://jetpackcrm.com/product/invoicing-pro/'; $this->urls['upgrade'] = 'https://jetpackcrm.com/checkout/?plan=entrepreneur&utm_source=plugin&utm_medium=plugin&utm_campaign=welcome_upgrade'; $this->urls['extcpp'] = 'https://jetpackcrm.com/product/client-portal-pro/'; $this->urls['extcal'] = 'https://jetpackcrm.com/product/calendar-pro/'; $this->urls['roadtov3'] = 'https://jetpackcrm.com/road-to-v3/'; $this->urls['advancedsegments'] = 'https://jetpackcrm.com/product/advanced-segments/'; $this->urls['bulktagger'] = 'https://jetpackcrm.com/product/bulk-tagger/'; $this->urls['salesdash'] = 'https://jetpackcrm.com/product/sales-dashboard/'; $this->urls['connect-multi-woo'] = 'https://jetpackcrm.com/feature/multiple-woocommerce-stores/'; $this->urls['woosync'] = 'https://jetpackcrm.com/woocommerce/'; $this->urls['mailpoet'] = 'https://jetpackcrm.com/feature/mailpoet-crm-sync/'; $this->urls['feedbackform'] = 'https://forms.gle/k94AdShUHZ3LWPvx8'; // social $this->urls['twitter'] = 'https://twitter.com/jetpackcrm'; // assets $this->urls['crm-logo'] = plugins_url( 'i/jpcrm-logo-stacked-black.png', ZBS_ROOTFILE ); // temp/updates $this->urls['db3migrate'] = 'https://kb.jetpackcrm.com/knowledge-base/upgrading-database-v3-0-migration/'; $this->urls['migrationhelpemail'] = 'hello@jetpackcrm.com'; $this->urls['db3migrateexts'] = 'https://kb.jetpackcrm.com/knowledge-base/upgrading-database-v3-0-migration/#extension-compatibility'; // kb $this->urls['kbdevmode'] = 'https://kb.jetpackcrm.com/knowledge-base/developer-mode/'; $this->urls['kbquoteplaceholders'] = 'https://kb.jetpackcrm.com/knowledge-base/placeholders-in-emails-quote-templates-invoices-etc/#quote-template-placeholders'; $this->urls['kblicensefaq'] = 'https://kb.jetpackcrm.com/knowledge-base/license-keys-faq/'; $this->urls['kbcronlimitations'] = 'https://kb.jetpackcrm.com/knowledge-base/wordpress-cron-limitations/'; $this->urls['kbfirstcontact'] = 'https://kb.jetpackcrm.com/knowledge-base/adding-your-first-customer/'; $this->urls['kbactivatecoreext'] = 'https://kb.jetpackcrm.com/knowledge-base/how-to-activate-deactivate-core-modules/'; $this->urls['kbinvoicebuilder'] = 'https://kb.jetpackcrm.com/knowledge-base/how-to-use-the-invoice-builder/'; $this->urls['kbteam'] = 'https://kb.jetpackcrm.com/knowledge-base/setting-up-your-team/'; $this->urls['kbupdateext'] = 'https://kb.jetpackcrm.com/knowledge-base/how-do-i-update-an-extension/'; $this->urls['kbclientportal'] = 'https://kb.jetpackcrm.com/knowledge-base/how-does-the-client-portal-work/'; $this->urls['kbtemplatefiles'] = 'https://kb.jetpackcrm.com/knowledge-base/templating-how-to-change-templates-pdfs-portal-emails/'; $this->urls['kbeasyaccess'] = 'https://kb.jetpackcrm.com/knowledge-base/easy-access-links-for-client-portal/'; $this->urls['kbdisablewelcome'] = 'https://kb.jetpackcrm.com/knowledge-base/automatically-create-wordpress-users-but-not-send-them-a-welcome-email/'; $this->urls['kbapi'] = 'https://kb.jetpackcrm.com/knowledge-base/using-the-api-connector/'; $this->urls['kbshowwpmenus'] = 'https://kb.jetpackcrm.com/knowledge-base/how-to-get-wordpress-menu-items-back/'; $this->urls['kbsmtpsetup'] = 'https://kb.jetpackcrm.com/knowledge-base/mail-delivery-method-setup-smtp/'; $this->urls['kbcrmdashboard'] = 'https://kb.jetpackcrm.com/knowledge-base/zero-bs-crm-dashboard/'; $this->urls['kbrevoverview'] = 'https://kb.jetpackcrm.com/knowledge-base/revenue-overview-chart/'; $this->urls['kbcsvformat'] = 'https://kb.jetpackcrm.com/knowledge-base/what-should-my-csv-be-formatted-like/'; $this->urls['kbcat_cal'] = 'https://kb.jetpackcrm.com/article-categories/calendar/'; $this->urls['kbsegment_issues'] = 'https://kb.jetpackcrm.com/knowledge-base/segment-issues-and-errors/'; $this->urls['kb-woosync-home'] = 'https://kb.jetpackcrm.com/knowledge-base/using-the-woocommerce-sync-hub/'; $this->urls['kb-pre-v5-migration-todo'] = 'https://kb.jetpackcrm.com/knowledge-base/upgrading-to-jetpack-crm-v5-0/'; $this->urls['kb-mailpoet'] = 'https://kb.jetpackcrm.com/knowledge-base/mailpoet-crm-sync/'; $this->urls['kb-automations'] = 'https://kb.jetpackcrm.com/knowledge-base/automations/'; $this->urls['kb-contact-fields'] = 'https://kb.jetpackcrm.com/knowledge-base/contact-field-list/'; // coming soon $this->urls['soon'] = 'https://jetpackcrm.com/coming-soon/'; // v4 rebrand announcement $this->urls['v4announce'] = 'https://jetpackcrm.com/rebrand-announcement'; $this->urls['v5announce'] = 'https://jetpackcrm.com/announcing-jetpack-crm-v5-woocommerce-crm/'; // } Usage Tracking $this->urls['usage'] = 'https://app.jetpackcrm.com/api/usage'; $this->urls['usageinfo'] = 'https://jetpackcrm.com/usage-tracking'; // YouTubes! $this->urls['youtube_channel'] = 'https://www.youtube.com/channel/UCyT-wMU7Gp6r1wN6W5YMAiQ'; $this->urls['youtube_intro_playlist'] = 'https://www.youtube.com/watch?v=tCC25uTFDTs&list=PLO9bxAENhBHhnc53Eq3OGBKLMSj0leAel'; $this->urls['youtube_intro_to_crm'] = 'https://www.youtube.com/watch?v=tCC25uTFDTs'; $this->urls['youtube_intro_to_tags'] = 'https://www.youtube.com/watch?v=KwGh-Br_exc'; $this->urls['youtube_intro_to_forms'] = 'https://www.youtube.com/watch?v=mBPjV1KUb-w'; $this->urls['youtube_intro_to_modules'] = 'https://www.youtube.com/watch?v=j9RsXPcgeIo'; // $this->urls['youtube_intro_to_woosync'] = 'https://www.youtube.com/watch?v=4G-FtmMhy-s'; // Page slugs $this->slugs['home'] = 'zerobscrm-settings'; ##WLREMOVE $this->slugs['home'] = 'zerobscrm-plugin'; ##/WLREMOVE $this->slugs['dash'] = 'zerobscrm-dash'; $this->slugs['settings'] = 'zerobscrm-plugin-settings'; $this->slugs['logout'] = 'zerobscrm-logout'; $this->slugs['datatools'] = 'zerobscrm-datatools'; $this->slugs['welcome'] = 'zerobscrm-welcome'; $this->slugs['crmresources'] = 'jpcrm-resources'; $this->slugs['support'] = 'jpcrm-support'; $this->slugs['extensions'] = 'zerobscrm-extensions'; $this->slugs['modules'] = 'zerobscrm-modules'; $this->slugs['export'] = 'zerobscrm-export'; $this->slugs['systemstatus'] = 'zerobscrm-systemstatus'; $this->slugs['sync'] = 'zerobscrm-sync'; $this->slugs['core-automations'] = 'jpcrm-automations'; // CSV importer Lite $this->slugs['csvlite'] = 'zerobscrm-csvimporterlite-app'; // } FOR NOW wl needs these: $this->slugs['bulktagger'] = 'zerobscrm-batch-tagger'; $this->slugs['salesdash'] = 'sales-dash'; $this->slugs['stripesync'] = 'zerobscrm-stripesync-app'; $this->slugs['woosync'] = 'woo-sync-hub'; // previously 'woo-importer'; $this->slugs['paypalsync'] = 'zerobscrm-paypal-app'; $this->slugs['mailpoet'] = 'crm-mail-poet-hub'; // note can't use `*mailpoet*` as the plugin inteferes with styles // } 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'; $this->slugs['manage-tasks-list'] = 'manage-tasks-list'; $this->slugs['managecontactsprev'] = 'manage-customers-crm'; $this->slugs['managequotesprev'] = 'manage-quotes-crm'; $this->slugs['managetransactionsprev'] = 'manage-transactions-crm'; $this->slugs['manageinvoicesprev'] = 'manage-invoices-crm'; $this->slugs['managecompaniesprev'] = 'manage-companies-crm'; $this->slugs['manageformscrmprev'] = 'manage-forms-crm'; // } 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'; $this->slugs['zbs-edit-user'] = 'zbs-edit-user'; // WH Added this, not sure what you're using for // } Install helper $this->slugs['zerobscrm-install-helper'] = 'zerobscrm-install-helper'; // emails $this->slugs['email-templates'] = 'zbs-email-templates'; // tag manager $this->slugs['tagmanager'] = 'tag-manager'; // no access $this->slugs['zbs-noaccess'] = 'zbs-noaccess'; // } File Editor $this->slugs['editfile'] = 'zerobscrm-edit-file'; $this->slugs['addnewfile'] = 'zerobscrm-add-file'; // } Extensions Deactivated error $this->slugs['extensions-active'] = 'zbs-extensions-active'; // Activates a module and redirects to its 'hub' slug. $this->slugs['module-activate-redirect'] = 'jpcrm-module-activate-redirect'; // Transients // These are transients which CRM owns which can be set via jpcrm_set_jpcrm_transient() etc. // Licensing prompts $this->transients['jpcrm-license-modal'] = false; // Mime types just use this func () - needs rethinking - includes/ZeroBSCRM.FileUploads.php if ( function_exists( 'zeroBSCRM_returnMimeTypes' ) ) { $this->acceptable_mime_types = zeroBSCRM_returnMimeTypes(); } } /** * Include required core files used in admin and on the frontend. Note. In the main * file it was included everything on front end too. Can move the relevant ones * to if ( $this->is_request( 'admin' ) ) { } once initial tests complete. */ public function includes() { // Admin messages (for any promos etc) require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.PluginAdminNotices.php'; // ==================================================================== // ==================== General Perf Testing ========================== if ( defined( 'ZBSPERFTEST' ) ) { zeroBSCRM_performanceTest_startTimer( 'includes' ); } // =================== / General Perf Testing ========================= // ==================================================================== require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.GeneralFuncs.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.Core.DateTime.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.AdminPages.Checks.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.ScriptsStyles.php'; // } Settings require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.Config.Init.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'wh.config.lib.php'; // } WP REST API SUPPORT (better performant AJAX) require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.REST.php'; // } General store of Error Codes require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.ErrorCodes.php'; // Language modifiers (e.g. Company -> Organisation) require_once ZEROBSCRM_INCLUDE_PATH . 'jpcrm-language.php'; // Segment conditions require_once ZEROBSCRM_INCLUDE_PATH . 'class-segment-condition.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'jpcrm-segment-conditions.php'; // Generic CRM exceptions require_once ZEROBSCRM_INCLUDE_PATH . 'class-crm-exception.php'; // WordPress user integrations require_once ZEROBSCRM_INCLUDE_PATH . 'class-wordpress-user-integration.php'; // Endpoint Listener require_once ZEROBSCRM_INCLUDE_PATH . 'class-endpoint-listener.php'; // OAuth Handler require_once ZEROBSCRM_INCLUDE_PATH . 'class-oauth-handler.php'; // } DATA // DAL3 // Here we include: // - DAL 3 (base class) // - DAL 3 Objects // - DAL3.Helpers.php (our helper funcs) require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.DAL3.php'; // 3.0 DAL objs: require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.DAL3.ObjectLayer.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.DAL3.Obj.Contacts.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.DAL3.Obj.Companies.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.DAL3.Obj.Segments.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'class-segment-condition-exception.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'class-missing-settings-exception.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.DAL3.Obj.Quotes.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.DAL3.Obj.QuoteTemplates.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.DAL3.Obj.Invoices.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.DAL3.Obj.Transactions.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.DAL3.Obj.Forms.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.DAL3.Obj.Events.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.DAL3.Obj.EventReminders.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.DAL3.Obj.Logs.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.DAL3.Obj.LineItems.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.DAL3.Export.php'; // helper funcs require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.DAL3.Helpers.php'; // drop-in-replacement for previous global fields (uses models from objs now.) // NOTE: Rather than initially hard-typed, this now needs to WAIT until DAL3 initialised // ... so field Globals available LATER in build queue in DAL3+ require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.DAL3.Fields.php'; // } Metaboxes v3.0 // Root classes require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.MetaBox.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.MetaBoxes3.Logs.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.MetaBoxes3.Tags.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.MetaBoxes3.ExternalSources.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.MetaBoxes3.Contacts.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.MetaBoxes3.Companies.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.MetaBoxes3.TagManager.php'; // } 3.0 + ALL are in our metaboxes require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.MetaBoxes3.Quotes.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.MetaBoxes3.QuoteTemplates.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.MetaBoxes3.Invoices.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.MetaBoxes3.Ownership.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.MetaBoxes3.Tasks.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.MetaBoxes3.Transactions.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.MetaBoxes3.Forms.php'; // NO CPTs! YAY! require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.ExternalSources.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.DataIOValidation.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.Database.php'; // } Split out DAL2: require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.DAL2.Mail.php'; // } Admin Pages require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.AdminStyling.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.AdminPages.php'; require_once ZEROBSCRM_PATH . 'admin/tags/tag-manager.page.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.FormatHelpers.php'; // } Dashboard Boxes - WH Q why do we also need to define VARS for these, require once only requires once, right? require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.DashboardBoxes.php'; // } The kitchen sink require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.Migrations.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.Core.Localisation.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'jpcrm-localisation.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.Core.Extensions.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.Actions.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.Core.Menus.WP.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.Core.Menus.Top.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.Core.License.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'class-learn-menu.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.Permissions.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.ScreenOptions.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.Inventory.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'jpcrm-rewrite-rules.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'jpcrm-mail-templating.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'jpcrm-templating.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'jpcrm-templating-placeholders.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.MailTracking.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.InternalAutomator.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.CRON.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.Social.php'; // } Secondary require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.AJAX.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.WYSIWYGButtons.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.CustomerFilters.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.InternalAutomatorRecipes.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.FileUploads.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.Forms.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.InvoiceBuilder.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.QuoteBuilder.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.SystemChecks.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.IntegrationFuncs.php'; // Temporarily removed until MC2 catches up + finishes Mail Delivery: require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.Mail.php'; // } OBJ List Class (ZeroBSCRM.List.php) & List render funcs (ZeroBSCRM.List.Views.php) & List Column data require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.List.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.List.Views.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.List.Columns.php'; // } OBJ Edit & Delete Classes (ZeroBSCRM.Edit.php) require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.Edit.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.Delete.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.TagManager.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.Core.Page.Controller.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.Edit.Segment.php'; require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.List.Tasks.php'; // } Semantic UI Helper + columns list require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.SemanticUIHelpers.php'; // } Put Plugin update message (notifications into the transient /wp-admin/plugins.php) page.. that way the nag message is not needed at the top of pages (and will always show, not need to be dismissed) require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.PluginUpdates.php'; // v3.0 update coming, warning require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.PluginUpdates.ImminentRelease.php'; // } FROM PLUGIN HUNT THEME - LOT OF USEFUL CODE IN HERE. require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.NotifyMe.php'; // load dependency checker (since 4.5.0) require_once ZEROBSCRM_INCLUDE_PATH . 'jpcrm-dependency-checker.php'; // load feature sniffer (since 4.5.0) require_once ZEROBSCRM_INCLUDE_PATH . 'jpcrm-feature-sniffer.php'; if ( defined( 'WP_CLI' ) && WP_CLI ) { // if we need CLI stuff } // ==================================================================== // ==================== General Perf Testing ========================== if ( defined( 'ZBSPERFTEST' ) ) { zeroBSCRM_performanceTest_closeGlobalTest( 'includes' ); } // =================== / General Perf Testing ========================= // ==================================================================== } /** * Hook into actions and filters. * * @since 2.3 */ private function init_hooks() { // General activation hook: DB check, role creation register_activation_hook( ZBS_ROOTFILE, array( $this, 'install' ) ); add_action( 'activated_plugin', array( $this, 'activated_plugin' ) ); // Pre-init Hook do_action( 'before_zerobscrm_init' ); // After all the plugins have loaded (THESE FIRE BEFORE INIT) add_action( 'plugins_loaded', array( $this, 'load_textdomain' ) ); // } Translations // this moved to post_init_plugins_loaded below, needs to be post init: add_action('plugins_loaded', array($this, 'after_active_plugins_loaded') ); // Initialise // our 'pre-init', this is the last step before init // ... and loads settings :) // add_action('admin_init', array($this, 'preInit'), 1); add_action( 'init', array( $this, 'preInit' ), 1 ); // our formal init add_action( 'init', array( $this, 'init' ), 10 ); // post init (init 99) add_action( 'init', array( $this, 'postInit' ), 99 ); // Admin init - should condition this per page.. add_action( 'admin_init', array( $this, 'admin_init' ) ); // Add thumbnail support? add_action( 'after_setup_theme', array( $this, 'setup_environment' ) ); // Extension links add_filter( 'plugin_action_links_' . plugin_basename( ZBS_ROOTFILE ), array( $this, 'add_action_links' ) ); // Row meta add_filter( 'plugin_row_meta', array( __CLASS__, 'plugin_row_meta' ), 10, 2 ); // Install/uninstall - use uninstall.php here register_deactivation_hook( ZBS_ROOTFILE, array( $this, 'uninstall' ) ); // CRM top menu add_action( 'wp_after_admin_bar_render', 'zeroBSCRM_admin_top_menu', 10 ); // Learn menu // Note the priority here. This causes the "learn" block to present after the top menu add_action( 'wp_after_admin_bar_render', array( $this, 'initialise_learn_menu' ), 11 ); // Run late-stack events, e.g. post-loaded migrations, exports // note: this fires AFTER all advanced segments loaded, reliably add_action( 'wp_loaded', array( $this, 'post_wp_loaded' ) ); } public function filterExtensions( $extensions_array = false ) { $extensions_array = apply_filters( 'zbs_extensions_array', $extensions_array ); // remove dupes - even this doesn't seem to remove the dupes! return array_unique( $extensions_array ); } // load initial external sources private function loadBaseExternalSources() { // simply loads our initial set from array, for now. $this->external_sources = zeroBS_baseExternalSources(); } // load any extra hooked-in external sources private function loadExtraExternalSources() { // load initials if not loaded/borked if ( ! is_array( $this->external_sources ) || count( $this->external_sources ) < 1 ) { // reload initial $this->loadBaseExternalSources(); } // should be guaranteed that this->external_sources is an array now, but if for god-knows what reason, it's not, error. if ( ! is_array( $this->external_sources ) ) { // error out? (hard error not useful as err500's peeps) // ... rude text? (no translation, this way if someone EVER sees, they'll hopefully tell us) echo 'CRM ERROR #399: No external sources!<br>'; // should NEVER happen: $this->external_sources = array(); } // NOW we apply any filters to a blank array, then merge that with our HARD typed array to insure we never LOOSE originals $newExtSources = $this->filterExternalSources( array() ); // ^^ this is kind of miss-use of filters, but it'll work well here. // if anything to add, manually parse here (for complete control) if ( is_array( $newExtSources ) && count( $newExtSources ) > 0 ) { foreach ( $newExtSources as $extKey => $extDeets ) { // will look like this: // $external_sources['woo'] = array('WooCommerce', 'ico' => 'fa-shopping-cart'); // override/add to main (if checks out): if ( is_string( $extKey ) && ! empty( $extKey ) && is_array( $extDeets ) && count( $extDeets ) > 0 ) { // seems in right format $this->external_sources[ $extKey ] = $extDeets; } } // / if any new to add } // at this point $this->external_sources should be fully inline with apply_filter's added, // but will NEVER lack the original 'pack' // and 100% will be an array. } // simply applies filters to anny passed array // NOTE: From 2.97.7 this is only taken as a 'second' layer, as per loadExtraExternalSources() above. // ... so it can stay super simple. public function filterExternalSources( $approved_sources = false ) { return apply_filters( 'zbs_approved_sources', $approved_sources ); } // } Build-out Object Models public function buildOutObjectModels() { // ==================================================================== // ==================== General Perf Testing ========================== if ( defined( 'ZBSPERFTEST' ) ) { zeroBSCRM_performanceTest_startTimer( 'customfields' ); } // =================== / General Perf Testing ========================= // ==================================================================== // } Unpack Custom Fields + Apply sorts zeroBSCRM_unpackCustomFields(); zeroBSCRM_unpackCustomisationsToFields(); if ( 1 == 1 ) { // } switch off for perf? zeroBSCRM_applyFieldSorts(); } // } Unpacks any settings logged against listview setups zeroBSCRM_unpackListViewSettings(); // ==================================================================== // ==================== General Perf Testing ========================== if ( defined( 'ZBSPERFTEST' ) ) { zeroBSCRM_performanceTest_closeGlobalTest( 'customfields' ); } // =================== / General Perf Testing ========================= // ==================================================================== } public function setup_environment() { // Don't think we need this $this->add_thumbnail_support(); //add thumbnail support } public function add_action_links( $links ) { global $zbs; $mylinks = array( '<a href="' . zeroBSCRM_getAdminURL( $zbs->slugs['settings'] ) . '">' . __( 'Settings', 'zero-bs-crm' ) . '</a>', '<a href="' . zeroBSCRM_getAdminURL( $zbs->slugs['extensions'] ) . '">' . __( 'Extensions', 'zero-bs-crm' ) . '</a>', ); return array_merge( $mylinks, $links ); } /** * Show row meta on the plugin screen for Jetpack CRM plugin. * * @param mixed $links_array Plugin Row Meta. * @param mixed $plugin Plugin Base Name. * * @return array */ public static function plugin_row_meta( $links_array, $plugin ) { if ( ! str_contains( $plugin, plugin_basename( ZBS_ROOTFILE ) ) ) { return $links_array; } global $zbs; $row_meta = array( 'docs' => '<a href="' . esc_url( $zbs->urls['docs'] ) . '" aria-label="' . esc_attr__( 'Jetpack CRM knowledgebase', 'zero-bs-crm' ) . '" target="_blank">' . esc_html__( 'Docs', 'zero-bs-crm' ) . '</a>', ); ##WLREMOVE $license_key_array = zeroBSCRM_getSetting( 'license_key' ); if ( is_array( $license_key_array ) && ! empty( $license_key_array['key'] ) ) { $row_meta['account'] = '<a href="' . esc_url( $zbs->urls['account'] ) . '" aria-label="' . esc_attr__( 'Your account', 'zero-bs-crm' ) . '" target="_blank">' . esc_html__( 'Your account', 'zero-bs-crm' ) . '</a>'; } ##/WLREMOVE return array_merge( $links_array, $row_meta ); } public function post_init_plugins_loaded() { // } renamed to postSettingsIncludes and moved into that flow, (made more logical sense) // Veriy extension requirements $this->verify_extension_minimum_requirements(); // } Forms - only initiate if installed :) if ( zeroBSCRM_isExtensionInstalled( 'forms' ) ) { zeroBSCRM_forms_includeEndpoint(); } // ==================================================================== // ==================== General Perf Testing ========================== if ( defined( 'ZBSPERFTEST' ) ) { zeroBSCRM_performanceTest_closeGlobalTest( 'postsettingsincludes' ); } // =================== / General Perf Testing ========================= // ==================================================================== } public function preInit() { // ==================================================================== // ==================== General Perf Testing ========================== if ( defined( 'ZBSPERFTEST' ) ) { zeroBSCRM_performanceTest_startTimer( 'preinit' ); } // =================== / General Perf Testing ========================= // ==================================================================== global $zeroBSCRM_Conf_Setup, $zbscrmApprovedExternalSources; // } Init DAL (DAL2, now always enabled) $this->DAL = new zbsDAL(); // } ASAP after DAL is initialised, need to run this, which DEFINES all DAL3.Obj.Models into old-style $globalFieldVars // } #FIELDLOADING' zeroBSCRM_fields_initialise(); // } Setup Config (centralises version numbers temp) global $zeroBSCRM_Conf_Setup; $zeroBSCRM_Conf_Setup['conf_pluginver'] = $this->version; $zeroBSCRM_Conf_Setup['conf_plugindbver'] = $this->db_version; // Not needed yet :) do_action( 'before_zerobscrm_settings_init' ); // } Init settings + sources $this->settings = new WHWPConfigLib( $zeroBSCRM_Conf_Setup ); // register any modules with core $this->jpcrm_register_modules(); // external sources, load, then initially filter $this->loadBaseExternalSources(); $this->loadExtraExternalSources(); // This just sets up metaboxes (empty array for now) - see zeroBSCRM_add_meta_box in Edit.php if ( ! is_array( $this->metaboxes ) ) { $this->metaboxes = array(); } // } This houses includes which need to fire post settings model load // NOTE: BECAUSE this has some things which add_action to init // ... this MUST fire on init with a priority of 1, so that these still "have effect" $this->postSettingsIncludes(); // TEMP (ext update for 2.5 notice): if ( defined( 'ZBSTEMPLEGACYNOTICE' ) ) { zeroBS_temp_ext_legacy_notice(); } // Legacy support for pre v2.50 settings in extensions zeroBSCRM_legacySupport(); // load dependency checker for any modules/extensions $this->dependency_checker = new JPCRM_DependencyChecker(); // load feature sniffer to alert user to available integrations $this->feature_sniffer = new JPCRM_FeatureSniffer(); $this->jpcrm_sniff_features(); // load WordPress User integrations $this->wordpress_user_integration = new Automattic\JetpackCRM\Wordpress_User_Integration(); // fire an action do_action( 'after_zerobscrm_settings_preinit' ); // load included modules // this needs to be fired early so modules can hook into third-party plugin actions/filters do_action( 'jpcrm_load_modules' ); // Where on frontend, load our endpoint listener and OAuth handler if ( $this->is_request( 'frontend' ) && ! $this->is_request( 'ajax' ) ) { // load $this->load_oauth_handler(); $this->load_listener(); // catch listener requests (if any) $this->listener->catch_listener_request(); } // ==================================================================== // ==================== General Perf Testing ========================== if ( defined( 'ZBSPERFTEST' ) ) { zeroBSCRM_performanceTest_closeGlobalTest( 'preinit' ); } // =================== / General Perf Testing ========================= // ==================================================================== } public function postSettingsIncludes() { // ==================================================================== // ==================== General Perf Testing ========================== if ( defined( 'ZBSPERFTEST' ) ) { zeroBSCRM_performanceTest_startTimer( 'postsettingsincludes' ); } // =================== / General Perf Testing ========================= // ==================================================================== // } extensions :D - here are files that don't need including if they're switched off... // } ^^ can probably include this via free extension manager class (longer term tidier?) // WH addition: this was firing PRE init (you weren't seeing because no PHP warnings...needs to fire after) // Retrieve settings // $zbsCRMTempSettings = $zbs->settings->getAll(); use zeroBSCRM_isExtensionInstalled // } free extensions setup (needs to be post settings) zeroBSCRM_freeExtensionsInit(); // } CSV Importer LITE // } only run all this is no PRO installed :) if ( ! zeroBSCRM_isExtensionInstalled( 'csvpro' ) && zeroBSCRM_isExtensionInstalled( 'csvimporterlite' ) && ! defined( 'ZBSCRM_INC_CSVIMPORTERLITE' ) ) { require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.CSVImporter.php'; } // } API if ( zeroBSCRM_isExtensionInstalled( 'api' ) && ! defined( 'ZBSCRM_INC_API' ) ) { require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.API.php'; } // } If zbs admin: Tour if ( zeroBSCRM_isZBSAdminOrAdmin() && ! defined( 'ZBSCRM_INC_ONBOARD_ME' ) ) { require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.OnboardMe.php'; } // If usage tracking is active - include the tracking code. $this->load_usage_tracking(); if ( zeroBSCRM_isExtensionInstalled( 'jetpackforms' ) ) { // } Jetpack - can condition this include on detection of Jetpack - BUT the code in Jetpack.php only fires on actions so will be OK to just include require_once ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.Jetpack.php'; } } // } Initialisation - enqueueing scripts/styles public function init() { // ==================================================================== // ==================== General Perf Testing ========================== if ( defined( 'ZBSPERFTEST' ) ) { zeroBSCRM_performanceTest_startTimer( 'init' ); } // =================== / General Perf Testing ========================= // ==================================================================== // this catches zbs_customers who may be accessing backend (shouldn't) $this->checkBackendAccess(); global $zeroBSCRM_Conf_Setup, $zeroBSCRM_extensionsInstalledList, $zbscrmApprovedExternalSources; // unpack custom fieldsbuildOutObjectModels // #} #FIELDLOADING $this->buildOutObjectModels(); // } Unpacks any settings logged against listview setups zeroBSCRM_unpackListViewSettings(); // } Post settings hook - all meta views load in this hook :) // this has to fire for public + admin (things like mail campaigns rely on this for link tracking) do_action( 'after_zerobscrm_settings_init' ); // } this needs to be post settings $this->extensions = $this->filterExtensions( $zeroBSCRM_extensionsInstalledList ); // } Post extensions loaded hook do_action( 'after_zerobscrm_ext_init' ); // } Load the admin menu. Can consider in here the 'ORDER' of the menu // } As well where extensions put their settings too add_action( 'admin_menu', array( $this, 'admin_menu' ) ); // } WH MOVED these from being added on init_hooks, to just calling them here, was legacy mess. // no longer used (now notifyme) add_action('init', array($this,'admin_noticies') ); #} load the admin noticies etc.. // add_action('init', array($this,'include_updater') ); #} load the auto-updater class $this->include_updater(); // add_action('init', 'zeroBSCRM_wooCommerceRemoveBlock'); #} Admin unlock for ZBS users if WooCommerce installed zeroBSCRM_wooCommerceRemoveBlock(); // add_action('init', array($this, 'post_init_plugins_loaded')); #} Registers stuff that needs settings etc. $this->post_init_plugins_loaded(); // run migrations $this->run_migrations( 'init' ); // } Brutal override for feeding in json data to typeahead // WH: should these be removed now we're using REST? if ( isset( $_GET['zbscjson'] ) && is_user_logged_in() && zeroBSCRM_permsCustomers() ) { exit( zeroBSCRM_cjson() ); } if ( isset( $_GET['zbscojson'] ) && is_user_logged_in() && zeroBSCRM_permsCustomers() ) { exit( zeroBSCRM_cojson() ); } // } Brutal override for inv previews // No longer req. v3.0 + this is delivered via HASH URL // if (isset($_GET['zbs_invid']) && wp_verify_nonce($_GET['_wpnonce'], 'zbsinvpreview') && is_user_logged_in() && zeroBSCRM_permsInvoices()){ exit(zeroBSCRM_invoice_generateInvoiceHTML((int)sanitize_text_field($_GET['zbs_invid']),false)); } // } Catch Dashboard + redir (if override mode) // } but not for wp admin (wptakeovermodeforall) if ( $this->settings->get( 'wptakeovermode' ) == 1 ) { // Not if API or Client Portal... // ... moved them inside this func.. zeroBSCRM_catchDashboard(); } // } JUST before cpt, we do any install/uninstall of extensions, so that cpt's can adjust instantly: zeroBSCRM_extensions_init_install(); // } Here we do any 'default content' installs (quote templates) (In CPT <DAL3, In DAL3.Helpers DAL3+) zeroBSCRM_installDefaultContent(); // } Admin & Public req wp_enqueue_script( 'jquery' ); // } Post Init hook do_action( 'zerobscrm_post_init' ); // } Public & non wp-cli only if ( ! is_admin() && ! defined( 'WP_CLI' ) ) { // } Catch front end loads :) if ( $this->settings->get( 'killfrontend' ) == 1 ) { global $pagenow; if ( ! zeroBSCRM_isLoginPage() && ! zeroBSCRM_isWelcomeWizPage() && ! zeroBSCRM_isAPIRequest() && ! defined( 'XMLRPC_REQUEST' ) && ! defined( 'REST_REQUEST' ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended && ! ( 'index.php' === $pagenow && ! empty( $_GET['rest_route'] ) ) ) { zeroBSCRM_stopFrontEnd(); } } } // } Finally, if it's an edit page for a (obj) which is hard owned by another, redir away // if admin, ignore :) if ( $this->settings->get( 'perusercustomers' ) && ! zeroBSCRM_isZBSAdminOrAdmin() ) { // } Using ownership if ( ! $this->settings->get( 'usercangiveownership' ) ) { // DAL3/pre switch if ( $this->isDAL3() ) { // } is one of our dal3 edit pages if ( zeroBSCRM_is_zbs_edit_page() ) { // in this specific case we pre-call globalise_vars // ... which later gets recalled if on an admin page (but it's safe to do so here too) // this moves any _GET into $zbsPage $this->globalise_vars(); // this allows us to use these: $objID = $this->zbsvar( 'zbsid' ); // -1 or 123 ID $objTypeStr = $this->zbsvar( 'zbstype' ); // -1 or 'contact' // if objtypestr is -1, assume contact (default) if ( $objTypeStr == -1 ) { $objType = ZBS_TYPE_CONTACT; } else { $objType = $this->DAL->objTypeID( $objTypeStr ); } // if is edit page + has obj id, (e.g. is not "new") // then check ownership if ( isset( $objID ) && $objID > 0 && $objType > 0 ) { $ownershipValid = $this->DAL->checkObjectOwner( array( 'objID' => $objID, 'objTypeID' => $objType, 'potentialOwnerID' => get_current_user_id(), 'allowNoOwnerAccess' => true, // ? ) ); // } If user ! has rights, redir if ( ! $ownershipValid ) { // } Redirect to our "no rights" page // OLD WAY header("Location: edit.php?post_type=".$postType."&page=".$this->slugs['zbs-noaccess']."&id=".$postID); header( 'Location: admin.php?page=' . $this->slugs['zbs-noaccess'] . '&zbsid=' . $objID . '&zbstype=' . $objTypeStr ); exit(); } // / no rights. } // / obj ID } // / is edit page } } // / is setting usercangiveownership } // / !is admin // debug // print_r($GLOBALS['wp_post_types']['zerobs_quo_template']); exit(); // ==================================================================== // ==================== General Perf Testing ========================== if ( defined( 'ZBSPERFTEST' ) ) { zeroBSCRM_performanceTest_closeGlobalTest( 'init' ); } // =================== / General Perf Testing ========================= // ==================================================================== } public function postInit() { // pre 2.97.7: // WH note: filterExternalSources() above didn't seem to be adding them all (stripesync e.g. was being added on init:10) // ... so this gets called a second time (should be harmless) at init:99 (here) // $this->external_sources = $this->filterExternalSources($this->external_sources); // 2.97.7, switched to this, a more ROBUST check which only 'adds' and won't remove. $this->loadExtraExternalSources(); // this allows various extensions to add users AFTER external sources def loaded do_action( 'after_zerobscrm_extsources_init' ); // This action should replace after_zerobscrm_extsources_init when we refactor load order in this class. // initially used by advanced segments to add custom field segment condition classes after the class is declared in jpcrm-segment-conditions.php do_action( 'jpcrm_post_init' ); $default_listview_filters = array(); $this->listview_filters = apply_filters( 'jpcrm_listview_filters', $default_listview_filters ); // this allows us to do stuff (e.g. redirect based on a condition) prior to headers being sent $this->catch_preheader_interrupts(); } /** * Fires after CRM and WP fully loaded * (Late in stack) **/ public function post_wp_loaded() { // Run any migrations $this->run_migrations( 'wp_loaded' ); // do our late-fire actions do_action( 'jpcrm_post_wp_loaded' ); } /** * Fires on admin_init **/ public function admin_init() { // ==================================================================== // ==================== General Perf Testing ========================== if ( defined( 'ZBSPERFTEST' ) ) { zeroBSCRM_performanceTest_startTimer( 'admin_init' ); } // =================== / General Perf Testing ========================= // ==================================================================== // Autoload AJAX files for any admin pages $this->load_admin_ajax(); // only load if we are a ZBS admin page? Will this break the world?!? if ( zeroBSCRM_isAdminPage() ) { // catch wiz + redirect $this->wizardInitCheck(); // Let's ensure that our cronjobs are there if ( ! wp_next_scheduled( 'jpcrm_cron_watcher' ) ) { jpcrm_cron_watcher(); } // apply any filters req. to the exclude-from-settings arr global $zbsExtensionsExcludeFromSettings; $zbsExtensionsExcludeFromSettings = apply_filters( 'zbs_exclude_from_settings', $zbsExtensionsExcludeFromSettings ); // this moves any _GET into $zbsPage $this->globalise_vars(); // this sets page titles where it can ($this->setPageTitle();) add_filter( 'zbs_admin_title_modifier', array( $this, 'setPageTitle' ), 10, 2 ); // This is a pre-loader for edit page classes, allows us to save data before loading the page :) zeroBSCRM_prehtml_pages_admin_addedit(); // Again, necessary? do_action('before_zerobscrm_admin_init'); // All style registering moved into ZeroBSCRM.ScriptsStyles.php for v3.0, was getting messy zeroBSCRM_scriptStyles_initStyleRegister(); // JS Root obj (zbs_root) zeroBSCRM_scriptStyles_enqueueJSRoot(); // Check for stored messages in case we were redirected. $this->maybe_retrieve_page_messages(); // autohide admin_notices on pages we specify jpcrm_autohide_admin_notices_for_specific_pages(); } // ==================================================================== // ==================== General Perf Testing ========================== if ( defined( 'ZBSPERFTEST' ) ) { zeroBSCRM_performanceTest_closeGlobalTest( 'admin_init' ); } // =================== / General Perf Testing ========================= // ==================================================================== // ==================================================================== // ==================== General Perf Testing ========================== if ( defined( 'ZBSPERFTEST' ) ) { zeroBSCRM_performanceTest_startTimer( 'after-zerobscrm-admin-init' ); } // =================== / General Perf Testing ========================= // ==================================================================== // Action hook do_action( 'after-zerobscrm-admin-init' ); // ==================================================================== // ==================== General Perf Testing ========================== if ( defined( 'ZBSPERFTEST' ) ) { zeroBSCRM_performanceTest_closeGlobalTest( 'after-zerobscrm-admin-init' ); } // =================== / General Perf Testing ========================= // ==================================================================== } // this checks whether any extensions are active which might bring down an install to 500 error // backstop in case extensions used which don't deactivate for whatver reason (being doubly sure in core) // as part of UX work also make sure all extensions are classified and only load when core hook triggers // some users were still hitting 500 errors so worth having this in place to protect us / help retain / PICNIC // wh renamed: check_active_zbs_extensions -> pre_deactivation_check_exts_deactivated function pre_deactivation_check_exts_deactivated() { global $zbs; // } from telemetry however what if someone has extensions installed this should show up // } this is the full count (not whether they are active) $extensions_installed = zeroBSCRM_extensionsInstalledCount( true ); if ( $extensions_installed > 0 ) { // tried to add an error above the plugins.php list BUT it did not seem to show // instead re-direct to one of our pages which tells them about making sure extensions are // deactivated before deactivating core wp_safe_redirect( admin_url( 'admin.php?page=' . $zbs->slugs['extensions-active'] ) ); die(); // will killing it here stop deactivation? // failsafe? return false; } return true; } public function uninstall() { // Deactivate all the extensions zeroBSCRM_extensions_deactivateAll(); // Skip the deactivation feedback if it's a JSON/AJAX request or via WP-CLI if ( wp_is_json_request() || wp_doing_ajax() || ( defined( 'WP_CLI' ) && WP_CLI ) || wp_is_xml_request() ) { return; } // if($this->pre_deactivation_check_exts_deactivated()){ ##WLREMOVE // Remove roles :) zeroBSCRM_clearUserRoles(); // Debug delete_option('zbsfeedback');exit(); $feedbackAlready = get_option( 'zbsfeedback' ); // if php notice, (e.g. php ver to low, skip this) if ( ! defined( 'ZBSDEACTIVATINGINPROG' ) && $feedbackAlready == false && ! defined( 'ZBSPHPVERDEACTIVATE' ) ) { // } Show stuff + Deactivate // } Define is to stop an infinite loop :) // } (Won't get here the second time) define( 'ZBSDEACTIVATINGINPROG', true ); // } Before you go... if ( function_exists( 'file_get_contents' ) ) { // } telemetry // V3.0 No more telemetry if (!zeroBSCRM_isWL()) zeroBSCRM_teleLogAct(3); try { // } Also manually deactivate before exit deactivate_plugins( plugin_basename( ZBS_ROOTFILE ) ); // } require template require_once ZEROBSCRM_PATH . 'admin/activation/before-you-go.php'; exit(); } catch ( Exception $e ) { // } Nada } } } ##/WLREMOVE // } //end of check if there are extensions active } public function install() { // dir build zeroBSCRM_privatisedDirCheck(); zeroBSCRM_privatisedDirCheckWorks(); // the folder used to be '_wip', updated to 'tmp' // Additional DB tables hook on activation (such as api keys table) - requires ZeroBSCRM.Database.php zeroBSCRM_database_check(); // roles zeroBSCRM_clearUserRoles(); // roles + zeroBSCRM_addUserRoles(); } /** * Handle the redirection on JPCRM plugin activation * * @param $filename */ public function activated_plugin( $filename ) { // Skip the re-direction if it's a JSON/AJAX request or via WP-CLI if ( wp_is_json_request() || wp_doing_ajax() || ( defined( 'WP_CLI' ) && WP_CLI ) || wp_is_xml_request() ) { return; } if ( $filename == ZBS_ROOTPLUGIN ) { // Send the user to the Dash board global $zbs; if ( wp_redirect( zeroBSCRM_getAdminURL( $zbs->slugs['dash'] ) ) ) { exit; } } } // this func runs on admin_init and xxxx public function wizardInitCheck() { // not authorized to run the wizard if ( ! current_user_can( 'manage_options' ) ) { return; } $force_wizard = false; // reset any wizard overrides if URL param is present if ( ! empty( $_GET['jpcrm_force_wizard'] ) ) { delete_option( 'jpcrm_skip_wizard' ); delete_transient( 'jpcrm_defer_wizard' ); $force_wizard = true; } // set option if URL param if ( ! empty( $_GET['jpcrm_skip_wizard'] ) ) { update_option( 'jpcrm_skip_wizard', 1, false ); } // wizard was purposely skipped if ( get_option( 'jpcrm_skip_wizard' ) ) { return; } // set transient if URL param if ( ! empty( $_GET['jpcrm_defer_wizard'] ) ) { set_transient( 'jpcrm_defer_wizard', 1, 30 ); } // Skip wizard temporarily if transient is set // this can be used for Jetpack CTA installs, for example if ( get_transient( 'jpcrm_defer_wizard' ) ) { return; } // Bail if activating from network, or bulk if ( is_network_admin() ) { // WH removed this, if bulk, still do it :D || isset( $_GET['activate-multi'] ) ) { return; } ##WLREMOVE // Bail if already completed wizard // $run_count increments each time the wizard is loaded // always run if forced $run_count = get_option( 'zbs_wizard_run', 0 ); if ( $run_count <= 0 || $force_wizard ) { // require welcome wizard template require_once ZEROBSCRM_PATH . 'admin/activation/welcome-to-jpcrm.php'; exit(); } ##/WLREMOVE } /** * Loads the Plugin Updater Class * * @since 2.97.x */ public function include_updater() { // } Initialise ZBS Updater Class global $zeroBSCRM_Updater; if ( ! isset( $zeroBSCRM_Updater ) ) { $zeroBSCRM_Updater = new zeroBSCRM_Plugin_Updater( $this->urls['api'], $this->update_api_version, ZBS_ROOTFILE, array( 'version' => $this->version, 'license' => false, // license initiated to false.. ) ); } } /** * * Autoloads the modules (core extensions) included with core * * Ultimately we should probably include Jetpack Forms and maybe CSV Importer. * * Modularisation of this manner may allow easier drop-in integrations by third-party devs as well. */ public function jpcrm_register_modules() { // include modules class require_once ZEROBSCRM_INCLUDE_PATH . 'class-crm-modules.php'; // load it (which registers modules and creates $zbs->modules) $this->modules = new Automattic\JetpackCRM\CRM_Modules(); } /** * * Check to see if there's an integration our users could be using * At some point we should modularize this as well */ public function jpcrm_sniff_features() { $this->feature_sniffer->sniff_for_plugin( array( 'feature_slug' => 'jetpackforms', 'plugin_slug' => 'jetpack/jetpack.php', 'more_info_link' => 'https://kb.jetpackcrm.com/knowledge-base/jetpack-contact-forms/', ) ); do_action( 'jpcrm_sniff_features' ); $this->feature_sniffer->show_feature_alerts(); } /** * Ensures fatal errors are logged so they can be picked up in the status report. * * @since 3.2.0 */ public function log_errors() { $error = error_get_last(); if ( E_ERROR === $error['type'] ) { $this->write_log( $error['message'] . PHP_EOL ); // check this method.. should be OK } } public function write_log( $log ) { if ( is_array( $log ) || is_object( $log ) ) { error_log( print_r( $log, true ) ); } else { error_log( $log ); } } /** * Define constant if not already set. * * @param string $name Constant name. * @param string|bool $value Constant value. */ private function define( $name, $value ) { if ( ! defined( $name ) ) { define( $name, $value ); } } /** * What type of request is this? * Note: 'frontend' returns true for ajax calls too. * * @param string $type admin, ajax, cron or frontend. * @return bool */ private function is_request( $type ) { switch ( $type ) { case 'admin': return is_admin(); case 'ajax': return defined( 'DOING_AJAX' ); case 'cron': return defined( 'DOING_CRON' ); case 'frontend': return ( ! is_admin() || defined( 'DOING_AJAX' ) ) && ! defined( 'DOING_CRON' ); } } /** * Check the active theme. * * @since 2.6.9 * @param string $theme Theme slug to check. * @return bool */ private function is_active_theme( $theme ) { return get_template() === $theme; } /** * Include required frontend files. */ public function frontend_includes() { } /** * Load Localisation files. * * Note: the first-loaded translation file overrides any following ones if the same translation is present. * * Locales found in: * - WP_LANG_DIR/woocommerce/woocommerce-LOCALE.mo * - WP_LANG_DIR/plugins/woocommerce-LOCALE.mo */ public function load_textdomain() { // ==================================================================== // ==================== General Perf Testing ========================== if ( defined( 'ZBSPERFTEST' ) ) { zeroBSCRM_performanceTest_startTimer( 'loadtextdomain' ); } // =================== / General Perf Testing ========================= // ==================================================================== load_plugin_textdomain( 'zero-bs-crm', false, ZBS_LANG_DIR ); // basename( dirname( ZBS_ROOTFILE ) ) . '/languages' ); //plugin_dir_path( ZBS_ROOTFILE ) .'/languages' // ==================================================================== // ==================== General Perf Testing ========================== if ( defined( 'ZBSPERFTEST' ) ) { zeroBSCRM_performanceTest_closeGlobalTest( 'loadtextdomain' ); } // =================== / General Perf Testing ========================= // ==================================================================== } /** * Get the plugin url. * * @return string */ public function plugin_url() { return untrailingslashit( plugins_url( '/', ZBS_ROOTFILE ) ); } /** * Get the plugin path. * * @return string */ public function plugin_path() { return untrailingslashit( plugin_dir_path( ZBS_ROOTFILE ) ); } /** * Check if Settings exists, load default if not * * @return string */ public function checkSettingsSetup() { global $zeroBSCRM_Conf_Setup; if ( ! isset( $this->settings ) ) { $this->settings = null; // https://stackoverflow.com/questions/8900701/creating-default-object-from-empty-value-in-php $this->settings = new WHWPConfigLib( $zeroBSCRM_Conf_Setup ); } } /** * Check if user has capabilities to view backend :) * * @return string */ public function checkBackendAccess() { if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) { return; } // if zbs_customer in admin area, kick em out :) if ( zeroBSCRM_isRole( 'zerobs_customer' ) ) { if ( is_admin() ) { $redirect = isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : home_url( '/' ); if ( current_user_can( 'zerobs_customer' ) ) { wp_redirect( $redirect ); exit(); } } // and remove wp bar from front end add_filter( 'show_admin_bar', '__return_false' ); } } /** * Get Ajax URL. * * @return string */ public function ajax_url() { return admin_url( 'admin-ajax.php', 'relative' ); } /** * Get Site Domain * * @return string */ public function get_domain() { $urlparts = parse_url( home_url() ); if ( isset( $urlparts['host'] ) ) { return $urlparts['host']; } return false; } /** * Globalise ZBS Vars * * @return nout */ public function globalise_vars() { // here, where things are consistently used through a page // e.g. admin.php?page=zbs-add-edit&action=edit&zbsid=3 // we globally set them to save time later :) global $zbsPage; $zbsPage = array(); // zbsid if ( isset( $_GET['zbsid'] ) && ! empty( $_GET['zbsid'] ) ) { $zbsid = (int) sanitize_text_field( $_GET['zbsid'] ); // if $zbsid is set, make it a GLOBAL (save keep re-getting) // this is used by metaboxes, insights + hypothesis, titles below etc. DO NOT REMOVE if ( $zbsid > 0 ) { $zbsPage['zbsid'] = $zbsid; } } // page if ( isset( $_GET['page'] ) && ! empty( $_GET['page'] ) ) { $page = sanitize_text_field( $_GET['page'] ); // if $page is set, make it a GLOBAL (save keep re-getting) // this is used by metaboxes, insights + hypothesis, titles below etc. DO NOT REMOVE if ( ! empty( $page ) ) { $zbsPage['page'] = $page; } } // action if ( isset( $_GET['action'] ) && ! empty( $_GET['action'] ) ) { $action = sanitize_text_field( $_GET['action'] ); // if $action is set, make it a GLOBAL (save keep re-getting) // this is used by metaboxes, insights + hypothesis, titles below etc. DO NOT REMOVE if ( ! empty( $action ) ) { $zbsPage['action'] = $action; } } // type if ( isset( $_GET['type'] ) && ! empty( $_GET['type'] ) ) { $type = sanitize_text_field( $_GET['type'] ); // if $type is set, make it a GLOBAL (save keep re-getting) // this is used by metaboxes, insights + hypothesis, titles below etc. DO NOT REMOVE if ( ! empty( $type ) ) { $zbsPage['type'] = $type; } } // zbstype if ( isset( $_GET['zbstype'] ) && ! empty( $_GET['zbstype'] ) ) { $zbstype = sanitize_text_field( $_GET['zbstype'] ); // if $zbstype is set, make it a GLOBAL (save keep re-getting) // this is used by metaboxes, insights + hypothesis, titles below etc. DO NOT REMOVE if ( ! empty( $zbstype ) ) { $zbsPage['zbstype'] = $zbstype; } } // if action = 'edit' + no 'zbsid' = NEW EDIT (e.g. new contact) if ( isset( $zbsPage['action'] ) && $zbsPage['action'] == 'edit' && ( ! isset( $zbsPage['zbsid'] ) || $zbsPage['zbsid'] < 1 ) ) { $zbsPage['new_edit'] = true; } } /** * Get Globalised ZBS Vars * * @return str/int/bool */ public function zbsvar( $key = '' ) { // globalise_vars returned global $zbsPage; // zbsid if ( is_array( $zbsPage ) && ! empty( $key ) && isset( $zbsPage[ $key ] ) && ! empty( $zbsPage[ $key ] ) ) { return $zbsPage[ $key ]; } return -1; } /** * Tries to set page title (where it can) * * @return nout */ public function setPageTitle( $title = '', $adminTitle = '' ) { // default $pageTitle = ( ( $adminTitle == '' ) ? __( 'Jetpack CRM', 'zero-bs-crm' ) : $adminTitle ); // useful? global $post, $title, $action, $current_screen; // global $zbsPage; print_r($zbsPage); exit(); // we only need to do this for pages where we're using custom setups (not added via wp_add_menu whatever) if ( $this->zbsvar( 'page' ) != -1 ) { switch ( $this->zbsvar( 'page' ) ) { case 'zbs-add-edit': // default $pageTitle = __( 'View | Jetpack CRM' . $this->zbsvar( 'action' ), 'zero-bs-crm' ); // default/no type passed $objType = __( 'Contact', 'zero-bs-crm' ); switch ( $this->zbsvar( 'zbstype' ) ) { case 'contact': $objType = __( 'Contact', 'zero-bs-crm' ); break; case 'company': $objType = jpcrm_label_company(); break; case 'segment': $objType = __( 'Segment', 'zero-bs-crm' ); break; case 'quote': $objType = __( 'Quote', 'zero-bs-crm' ); break; case 'invoice': $objType = __( 'Invoice', 'zero-bs-crm' ); break; case 'transaction': $objType = __( 'Transaction', 'zero-bs-crm' ); break; case 'event': $objType = __( 'Task', 'zero-bs-crm' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase break; case 'form': $objType = __( 'Form', 'zero-bs-crm' ); break; case 'quotetemplate': $objType = __( 'Quote Template', 'zero-bs-crm' ); break; case 'log': $objType = __( 'Log', 'zero-bs-crm' ); break; } // just formatting: if ( ! empty( $objType ) ) { $objType = ' ' . $objType; } switch ( $this->zbsvar( 'action' ) ) { case 'edit': $pageTitle = __( 'Edit ' . $objType . ' | Jetpack CRM', 'zero-bs-crm' ); break; case 'delete': $pageTitle = __( 'Delete ' . $objType . ' | Jetpack CRM', 'zero-bs-crm' ); break; case 'view': $pageTitle = __( 'View ' . $objType . ' | Jetpack CRM', 'zero-bs-crm' ); break; } break; case 'zerobscrm-emails': // default $pageTitle = __( 'Email Manager | Jetpack CRM', 'zero-bs-crm' ); break; case 'tag-manager': $pageTitle = __( 'Tag Manager | Jetpack CRM', 'zero-bs-crm' ); break; case 'zerobscrm-notifications': $pageTitle = __( 'Notifications | Jetpack CRM', 'zero-bs-crm' ); break; case 'zbs-email-templates': $pageTitle = __( 'Email Templates | Jetpack CRM', 'zero-bs-crm' ); break; case 'zbs-export-tools': $pageTitle = __( 'Export Tools | Jetpack CRM', 'zero-bs-crm' ); break; case 'zerobscrm-csvimporterlite-app': $pageTitle = __( 'Import Tools | Jetpack CRM', 'zero-bs-crm' ); break; } } return $pageTitle; } /** * Get Current User's screen options for current page * This requires add_filter on page to work :) * // actually just use a global for now :) - so just set global $zbs->pageKey on page :) * // 2.94.2+ can pass pagekey to get opts for page other than current (used for list view perpage) * * @return array() screen options */ public function userScreenOptions( $pageKey = false ) { // TO ADD LATER: (optionally) allow admins to create a 'forced' screen options set (e.g. metabox layout etc.) // ... forced or default :) $currentUserID = get_current_user_id(); if ( ! $pageKey || empty( $pageKey ) ) { // actually just use a global for now :) - so just set global $zbs->pageKey on page :) $pageKeyCheck = apply_filters( 'zbs_pagekey', $this->pageKey ); } else { $pageKeyCheck = $pageKey; } if ( $currentUserID > 0 && ! empty( $pageKeyCheck ) ) { // retrieve via dal return $this->DAL->userSetting( $currentUserID, 'screenopts_' . $pageKeyCheck, false ); } return array(); } /** * Get global screen option settings * * @param string $page_key Page key. */ public function global_screen_options( $page_key = false ) { if ( empty( $page_key ) ) { $page_key = apply_filters( 'zbs_pagekey', $this->pageKey ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase } if ( empty( $page_key ) ) { return array(); } $screen_options = $this->DAL->getSetting( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase array( 'key' => 'screenopts_' . $page_key, ) ); return $screen_options; } /** * Shorthand for get_Current_user_id * * @return int user id */ public function user() { return get_current_user_id(); } /** * Shorthand for zeroBSCRM_getSetting('license_key') * * @return array() license settings (trimmed down) */ public function license() { // default $ret = array( 'validity' => false, 'access' => 'none', 'expires' => -1, ); // retrieve $licenseKeyArr = zeroBSCRM_getSetting( 'license_key' ); // return only these (not key, for simple semi-security? lol. not even) if ( is_array( $licenseKeyArr ) ) { if ( isset( $licenseKeyArr['validity'] ) ) { $ret['validity'] = $licenseKeyArr['validity']; } if ( isset( $licenseKeyArr['access'] ) ) { $ret['access'] = $licenseKeyArr['access']; } if ( isset( $licenseKeyArr['expires'] ) ) { $ret['expires'] = $licenseKeyArr['expires']; } } return $ret; } /* * Do we have a license key? */ public function has_license_key() { $settings = $this->settings->get( 'license_key' ); // checks if exists and it's not empty if ( ! empty( $settings['key'] ) ) { return true; } return false; } /** * Returns true/false if has AT LEAST entrepreneur Bundle * ... suspect this is an easy way to HACK out show promotional material. So rethink around that at some point. * * @return bool */ public function hasEntrepreneurBundleMin() { $license = $this->license(); $valid = array( 'entrepreneur', 'reseller' ); $license['validity'] = ( $license['validity'] === 'true' ? true : false ); if ( $license['validity'] && ( in_array( $license['access'], $valid ) ) ) { return true; } return false; } /** * Returns true/false if has AT LEAST entrepreneur Bundle * ... suspect this is an easy way to HACK out show promotional material. So rethink around that at some point. * * @return bool */ public function hasFreelancerBundleMin() { $license = $this->license(); $valid = array( 'freelancer', 'entrepreneur', 'reseller' ); $license['validity'] = ( $license['validity'] === 'true' ? true : false ); if ( $license['validity'] && ( in_array( $license['access'], $valid ) ) ) { return true; } return false; } /** * Returns pretty label for subscription * ... suspect this is an easy way to HACK out show promotional material. So rethink around that at some point. * * @return string */ public function getSubscriptionLabel( $str = '' ) { if ( empty( $str ) ) { // get from license $license = $this->license(); if ( isset( $license['validity'] ) ) { $license['validity'] = ( $license['validity'] === 'true' ? true : false ); if ( $license['validity'] && isset( $license['access'] ) && ! empty( $license['access'] ) ) { $str = $license['access']; } } } switch ( $str ) { case 'freelancer': return 'Freelancer Bundle'; break; case 'entrepreneur': return 'Entrepreneur Bundle'; break; case 'reseller': return 'Branded Bundle'; break; // for all others, use this: default: return 'Extension: ' . ucwords( $str ); break; } return false; } // ======= Menu Management ========= /** * Return private $menu * * @since 3.0 */ public function getMenu() { return $this->menu; } /** * Sets up admin menu * * @since 3.0 */ public function admin_menu() { $this->applyMenu(); // hook for extensions to add menus :) do_action( 'zerobs_admin_menu' ); } /** * Applys admin menu * (v3.0 + this replaces zeroBSCRM_admin_menu) * * @since 3.0 */ private function applyMenu() { // build init, if not there if ( ! isset( $this->menu ) && ! is_array( $this->menu ) ) { $this->menu = zeroBSCRM_menu_buildMenu(); } // ready? if ( isset( $this->menu ) && is_array( $this->menu ) ) { // Here we apply filters, this allows other ext etc. to modify menu items before we priotise + build $menu = apply_filters( 'zbs_menu_wpmenu', $this->menu ); // remove non-permissioned $menu = zeroBSCRM_menu_securityGuard( $menu ); // resort based on 'order' $menu = zeroBSCRM_menu_order( $menu ); // output (adds menus) zeroBSCRM_menu_applyWPMenu( $menu ); } } /** * Learn Menu * * @since 3.0 */ public function initialise_learn_menu() { $this->learn_menu = new Automattic\JetpackCRM\Learn_Menu(); // render the menu where possible $this->learn_menu->render_learn_menu(); } // ======= / Menu Management ========= // ========== Basic Library Management ========= /** * Retrieve array of details for a library * Returns: array() or false */ public function lib( $libKey = '' ) { if ( isset( $this->libs[ $libKey ] ) && is_array( $this->libs[ $libKey ] ) ) { // update path to use ZEROBSCRM_PATH $ret = $this->libs[ $libKey ]; $ret['path'] = ZEROBSCRM_PATH . $this->libs[ $libKey ]['path']; $ret['include'] = ZEROBSCRM_PATH . $this->libs[ $libKey ]['include']; return $ret; } return false; } /** * Retrieve root path for a library * Returns: str or false */ public function libPath( $libKey = '' ) { if ( isset( $this->libs[ $libKey ] ) && isset( $this->libs[ $libKey ]['path'] ) ) { return ZEROBSCRM_PATH . $this->libs[ $libKey ]['path']; } return false; } /** * Retrieve full include path for a library * Returns: str or false */ public function libInclude( $libKey = '' ) { if ( isset( $this->libs[ $libKey ] ) && isset( $this->libs[ $libKey ]['include'] ) ) { return ZEROBSCRM_PATH . $this->libs[ $libKey ]['include']; } return false; } /** * Returns the correct dompdf lib version depending on php compatibility * * @deprecated We no longer load Dompdf through this library system. * * @param string $lib_key The key/machine name. * @return string */ private function checkDompdfVersion( $lib_key ) { if ( $lib_key === 'dompdf' ) { $lib_key = 'dompdf-2'; } return $lib_key; } /* * Returns bool, are we running on a PHP version $operator (e.g. '>=') to $version */ public function has_min_php_version( $php_version ) { return version_compare( PHP_VERSION, $php_version, '>=' ); } /** * Retrieve version of a library * Returns: str or false */ public function libVer( $libKey = '' ) { if ( isset( $this->libs[ $libKey ] ) && isset( $this->libs[ $libKey ]['version'] ) ) { return $this->libs[ $libKey ]['version']; } return false; } /** * Check if library already loaded * Returns: bool */ public function libIsLoaded( $libKey = '' ) { if ( isset( $this->libs[ $libKey ] ) && isset( $this->libs[ $libKey ]['include'] ) && ! isset( $this->libs[ $libKey ]['loaded'] ) ) { return false; } return true; } /** * Load a library via include * Returns: str or false */ public function libLoad( $libKey = '' ) { if ( isset( $this->libs[ $libKey ] ) && isset( $this->libs[ $libKey ]['include'] ) && ! isset( $this->libs[ $libKey ]['loaded'] ) && file_exists( ZEROBSCRM_PATH . $this->libs[ $libKey ]['include'] ) ) { require_once ZEROBSCRM_PATH . $this->libs[ $libKey ]['include']; $this->libs[ $libKey ]['loaded'] = true; } return false; } /** * Autoload vendor libraries */ public function autoload_libraries() { require_once ZEROBSCRM_PATH . 'vendor/autoload.php'; } /** * Autoload files from a directory which match a regex filter */ public function autoload_from_directory( string $directory, string $regex_filter ) { $files = scandir( $directory ); if ( is_array( $files ) ) { foreach ( $files as $file ) { // find files `*.ajax.*` if ( preg_match( $regex_filter, $file ) ) { // load it require_once $directory . '/' . $file; } } } } /** * Autoload page AJAX * (This should be fired on admin_init and later should be rethought to be true autoloading, not loading all AJAX partials as this does) */ private function load_admin_ajax() { $admin_page_directories = jpcrm_get_directories( ZEROBSCRM_PATH . 'admin' ); if ( is_array( $admin_page_directories ) ) { foreach ( $admin_page_directories as $directory ) { $files = scandir( ZEROBSCRM_PATH . 'admin/' . $directory ); if ( is_array( $files ) ) { foreach ( $files as $file ) { // find files `*.ajax.*` if ( strrpos( $file, '.ajax.' ) > 0 ) { // load it require_once ZEROBSCRM_PATH . 'admin/' . $directory . '/' . $file; } } } } } } /** * Runs migrations routine */ public function run_migrations( $run_at = 'init' ) { // Run any migrations zeroBSCRM_migrations_run( $this->settings->get( 'migrations' ), $run_at ); } /** * Centralised method for detecting presence of WooCommerce */ public function woocommerce_is_active() { // check for Woo Presence if ( is_plugin_active( 'woocommerce/woocommerce.php' ) || ( isset( $GLOBALS['woocommerce'] ) && $GLOBALS['woocommerce'] ) ) { return true; } return false; } /** * Centralised method for detecting presence of MailPoet */ public function mailpoet_is_active() { // check for mailpoet Presence if ( is_plugin_active( 'mailpoet/mailpoet.php' ) ) { return true; } return false; } // ======= / Basic Library Management ========= // } If usage tracking is active - include the tracking code. // =========== Resource Loading =============== /** * Loads usage tracking where user has accepted via settings */ public function load_usage_tracking() { // load if not loaded, and permitted if ( $this->tracking === false ) { $tracking_active = zeroBSCRM_getSetting( 'shareessentials' ); if ( $tracking_active ) { require_once ZEROBSCRM_INCLUDE_PATH . 'jpcrm-usage-tracking.php'; $this->tracking = new jpcrm_usage_tracking(); } } return $this->tracking; } /** * Loads Endpoint Listener library */ public function load_listener() { if ( ! isset( $this->listener ) || $this->listener == null ) { $this->listener = new \Automattic\JetpackCRM\Endpoint_Listener(); } return $this->listener; } /** * Loads OAuth handler library */ public function load_oauth_handler() { if ( ! isset( $this->oauth ) || $this->oauth == null ) { $this->oauth = new \Automattic\JetpackCRM\Oauth_Handler(); } return $this->oauth; } /** * Loads Encryption library */ public function load_encryption() { require_once ZEROBSCRM_INCLUDE_PATH . 'class-encryption.php'; if ( ! isset( $this->encryption ) || $this->encryption == null ) { $this->encryption = new \Automattic\JetpackCRM\Encryption(); } return $this->encryption; } /** * Loads Package Installer library */ public function load_package_installer() { if ( ! isset( $this->package_installer ) || $this->package_installer == null ) { // Package installer require_once ZEROBSCRM_INCLUDE_PATH . 'class-package-installer.php'; $this->package_installer = new \Automattic\JetpackCRM\Package_Installer(); } return $this->package_installer; } /** * Package Installer pass through to simplify package dependency */ public function ensure_package_installed( $package_key, $min_version = 0 ) { $this->load_package_installer(); return $this->package_installer->ensure_package_is_installed( $package_key, $min_version ); } // ============ / Resource Loading ============ // ============= PDF engine ============ /** * Initialise Dompdf instance */ public function pdf_engine() { // PDF Install check: zeroBSCRM_extension_checkinstall_pdfinv(); // if we don't set options initially, weird issues happen (e.g. `installed-fonts.json` is overwritten at times): // https://github.com/dompdf/dompdf/issues/2990 $options = new Dompdf\Options(); // this batch of option setting ensures we allow remote images (http/s) // ... but they're only allowed from same-site urls $options->set( 'isRemoteEnabled', true ); $options->addAllowedProtocol( 'http://', 'jpcrm_dompdf_assist_validate_remote_uri' ); $options->addAllowedProtocol( 'https://', 'jpcrm_dompdf_assist_validate_remote_uri' ); // use JPCRM storage dir for extra fonts $options->set( 'fontDir', jpcrm_storage_fonts_dir_path() ); // build PDF $dompdf = new Dompdf\Dompdf( $options ); // set some generic defaults, (can be overriden later) $dompdf->set_paper( 'A4', 'portrait' ); $dompdf->setHttpContext( stream_context_create( array( 'ssl' => array( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true, ), ) ) ); return $dompdf; } // ============ / PDF engine ============ // =========== Templating Class =============== /** * Loads templating placeholder class into this->templating_placeholders * and returns it * (Can be loaded on-demand) */ public function get_templating() { // load if not loaded if ( $this->templating_placeholders === false ) { $this->templating_placeholders = new jpcrm_templating_placeholders(); } return $this->templating_placeholders; } /** * Loads fonts class into this->fonts * and returns it * (Can be loaded on-demand) */ public function get_fonts() { // load if not loaded require_once ZEROBSCRM_INCLUDE_PATH . 'jpcrm-fonts.php'; // load if not loaded if ( ! $this->fonts ) { $this->fonts = new JPCRM_Fonts(); } return $this->fonts; } // ============ / Templating Class ============ // =========== Error Coding =================== public function getErrorCode( $errorCodeKey = -1 ) { if ( $errorCodeKey ) { // load err codes if not loaded if ( ! isset( $this->errorCodes ) ) { $this->errorCodes = zeroBSCRM_errorCodes(); } // if set, return if ( isset( $this->errorCodes[ $errorCodeKey ] ) ) { return $this->errorCodes[ $errorCodeKey ]; } } return false; } // =========== / Error Coding =================== private function get_page_messages_transient_key( $obj_type, $inserted_id ) { return sprintf( 'pageMessages_%d_%d_%d', $this->DAL->objTypeID( $obj_type ), get_current_user_id(), $inserted_id ); } private function maybe_retrieve_page_messages() { if ( zeroBS_hasGETParamsWithValues( array( 'admin.php' ), array( 'page' => 'zbs-add-edit', 'action' => 'edit', ) ) && zeroBS_hasGETParams( array( 'admin.php' ), array( 'zbstype', 'zbsid' ) ) ) { $transient_key = $this->get_page_messages_transient_key( $_GET['zbstype'], $_GET['zbsid'] ); $page_messages = get_transient( $transient_key ); if ( ! empty( $page_messages ) ) { $this->pageMessages = $page_messages; delete_transient( $transient_key ); } } } public function new_record_edit_redirect( $obj_type, $inserted_id ) { if ( ! empty( $this->pageMessages ) ) { $transient_key = $this->get_page_messages_transient_key( $obj_type, $inserted_id ); set_transient( $transient_key, $this->pageMessages, MINUTE_IN_SECONDS ); } wp_redirect( jpcrm_esc_link( 'edit', $inserted_id, $obj_type ) ); exit; } public function catch_preheader_interrupts() { // This intercepts the request, looking for $_GET['page'] == $zbs->slugs['module-activate-redirect']. // If it sucessfully finds it, activates the module in $_GET['jpcrm-module-name'] and redirects to its 'hub' slug. if ( isset( $_GET['page'] ) && $_GET['page'] == $this->slugs['module-activate-redirect'] ) { $this->modules->activate_module_and_redirect(); } } }
projects/plugins/crm/includes/ZeroBSCRM.ExternalSources.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V2.97.4+ * * Copyright 2020 Automattic * * Date: 11/01/2019 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* External sources got a bit muddy in DAL1, This file is designed to centralise + simplify :) */ // Init set of external sources /* // Proper way to add to these is (in extension plugin class): // key is that filter has priority below 99 // .. can then be used anywhere POST init:99 public function register_external_source($external_sources = array()){ $external_sources['str'] = array('Stripe', 'ico' => 'fa-stripe'); return $external_sources; } #} adds this as an external source add_filter('zbs_approved_sources' , array($this, 'register_external_source'), 10); */ global $zbscrmApprovedExternalSources; $zbscrmApprovedExternalSources = zeroBS_baseExternalSources(); // 2.97.7 wrapped these in a func so they can be less affected than a global ? :/ // this is called directly now in core to load them, rather than using the global $zbscrmApprovedExternalSources; // ... global $zbscrmApprovedExternalSources is still set though, for backward compat, (not sure if some older ext using?) function zeroBS_baseExternalSources() { $external_sources = array( 'woo' => array( 'WooCommerce', 'ico' => 'fa-shopping-cart' ), // fa-shopping-cart is default :) no woo yet. 'pay' => array( 'PayPal', 'ico' => 'fa-paypal' ), 'env' => array( 'Envato', 'ico' => 'fa-envira' ), // fa-envira is a look-alike http://fontawesome.io/icon/envira/. 'csv' => array( 'CSV Import', 'ico' => 'fa-file-text' ), 'form' => array( 'Form Capture', 'ico' => 'fa-wpforms'), 'gra' => array( 'Gravity Forms', 'ico' => 'fa-wpforms'), 'api' => array( 'API', 'ico' => 'fa-random'), 'wpa' => array( 'WorldPay', 'ico' => 'fa-credit-card'), 'str' => array( 'Stripe', 'ico' => 'fa-credit-card'), 'wordpress' => array( 'WordPress', 'ico' => 'fa-wpforms'), 'cf7' => array( 'Contact Form 7', 'ico' => 'fa-wpforms'), 'jetpack_form' => array( 'Jetpack Contact Form', 'ico' => 'fa-wpforms' ), // Discontinued //'jvz' => array( 'JV Zoo', 'ico' => 'fa-paypal' ), ); $external_sources = apply_filters( 'jpcrm_register_external_sources', $external_sources ); return $external_sources; // phpcs:enable WordPress.Arrays.ArrayDeclarationSpacing.AssociativeArrayFound } /* * Simple external source info return based on key */ function jpcrm_get_external_source_info( $source_key ){ $external_sources = zeroBS_baseExternalSources(); if ( isset( $external_sources[ $source_key ] ) ){ return $external_sources[ $source_key ]; } return false; } // Returns a simplified 1 line explanation of an external source function zeroBS_getExternalSourceTitle($srcKey='',$srcUID=''){ // some old hard typed: switch ($srcKey){ case 'pay': #} paypal return '<i class="fa fa-paypal"></i> PayPal:<br /><span>'.$srcUID.'</span>'; break; #case 'woo': #} Woo case 'env': return '<i class="fa fa-envira"></i> Envato:<br /><span>'.$srcUID.'</span>'; break; case 'form': return '<i class="fa fa-wpforms"></i> Form Capture:<br /><span>'.$srcUID.'</span>'; break; case 'csv': return '<i class="fa fa-file-text"></i> CSV Import:<br /><span>'.$srcUID.'</span>'; break; case 'gra': return '<i class="fa fa-wpforms"></i> Gravity Forms:<br /><span>'.$srcUID.'</span>'; break; case 'api': return '<i class="fa fa-random"></i> API:<br /><span>'.$srcUID.'</span>'; break; default: // see if in $zbs->external_sources global $zbs; if (isset($zbs->external_sources[$srcKey])){ $ico = 'fa-users'; if (is_array($zbs->external_sources[$srcKey]) && isset($zbs->external_sources[$srcKey]['ico'])) $ico = $zbs->external_sources[$srcKey]['ico']; $name = ucwords(str_replace('_',' ',$srcKey)); if (is_array($zbs->external_sources[$srcKey]) && isset($zbs->external_sources[$srcKey][0])) $name = $zbs->external_sources[$srcKey][0]; return '<i class="fa '.$ico.'"></i> '.$name.':<br /><span>'.$srcUID.'</span>'; } else { #} Generic for now return '<i class="fa fa-users"></i> '.ucwords(str_replace('_',' ',$srcKey)).':<br /><span>'.$srcUID.'</span>'; } break; } } /* * Renders HTML describing external sources for an object * Primarily used in object 'external source' metaboxes * * @param int $object_id (crm contact, company, invoice, or transaction) * @param int $object_type_id */ function jpcrm_render_external_sources_by_id( $object_id, $object_type_id ){ global $zbs; // get sources, if any $external_sources = $zbs->DAL->getExternalSources( -1, array( 'objectID' => $object_id, 'objectType' => $object_type_id, 'grouped_by_source' => true, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT) )); // render jpcrm_render_external_sources_info( $external_sources, $object_id, $object_type_id ); } /* * Renders HTML describing external sources for an object * Primarily used in object 'external source' metaboxes * ... but also used on contact view etc. * * @param array $external_sources (requires these in 'grouped' format) */ function jpcrm_render_external_sources_info( $external_sources, $object_id, $object_type_id ){ global $zbs; // got any to render? if ( isset( $external_sources ) && is_array( $external_sources ) && count( $external_sources ) > 0 ){ if ( count( $external_sources ) > 0 ){ echo '<div id="jpcrm-external-sources-metabox">'; // first cycle through sources and stack by origin key (e.g. 'woo'), // so we can group if multiple. foreach ( $external_sources as $external_source_group_key => $external_source_group ){ // 'woo' => array( 'WooCommerce', 'ico' => 'fa-shopping-cart' ) $external_source_group_info = jpcrm_get_external_source_info( $external_source_group_key ); // got multiple of same source? (e.g. woo customer with multiple orders) $multiple_in_group = ( count( $external_source_group ) > 1 ); // show group header echo '<div class="jpcrm-external-source-group">'; echo '<div class="jpcrm-external-source-group-header ui header">' . ( is_array( $external_source_group_info ) ? '<i class="fa ' . esc_attr( $external_source_group_info['ico'] ) . '"></i>&nbsp;&nbsp;' . $external_source_group_info[0] : $external_source_group_key ) . '</div>'; foreach ( $external_source_group as $external_source ){ #} Display a "source" echo '<div class="jpcrm-external-source">'; $uid = $external_source['uid']; // company + CSV means uid will be a useless hash, so replace that with name if we have if ( $external_source['source'] == 'csv' && $object_type_id == ZBS_TYPE_COMPANY ){ $uid = __( 'Imported based on name', 'zero-bs-crm' ); } // build basic $external_source_html = zeroBS_getExternalSourceTitle( $external_source['source'], $uid ); // filter any given title - can be wired in to give links (e.g. wooc orders) $external_source_html = apply_filters( 'zbs_external_source_infobox_line', $external_source_html, array( 'objtype' => $object_type_id, 'objid' => $object_id, 'source' => $external_source['source'], 'origin' => $external_source['origin'], 'unique_id' => $uid ) ); // output echo $external_source_html; echo '</div>'; } echo '</div>'; } echo '</div>'; } } else { // manually added echo '<p><i class="address book icon"></i> ' . esc_html( sprintf( __( '%s added manually.', 'zero-bs-crm' ), ucwords( $zbs->DAL->objTypeKey( $object_type_id ) ) ) ) . '</p>'; } }
projects/plugins/crm/includes/ZeroBSCRM.DAL3.Obj.Addresses.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V3.0+ * * Copyright 2020 Automattic * * Date: 05/07/19 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /** * ZBS DAL >> Addresses * * @author Woody Hayday <hello@jetpackcrm.com> * @version 2.0 * @access public * @see https://jetpackcrm.com/kb */ class zbsDAL_addresses extends zbsDAL_ObjectLayer { protected $objectType = ZBS_TYPE_ADDRESS; //protected $objectDBPrefix = 'zbsadd_'; protected $include_in_templating = true; protected $objectModel = array( // ID 'ID' => array('fieldname' => 'ID', 'format' => 'int'), // site + team generics 'zbs_site' => array('fieldname' => 'zbs_site', 'format' => 'int'), 'zbs_team' => array('fieldname' => 'zbs_team', 'format' => 'int'), 'zbs_owner' => array('fieldname' => 'zbs_owner', 'format' => 'int'), // other fields 'addr1' => array( // db model: 'fieldname' => 'zbsa_addr1', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'Address Line 1', 'placeholder'=>'' ), 'addr2' => array( // db model: 'fieldname' => 'zbsa_addr2', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'Address Line 2', 'placeholder'=>'' ), 'city' => array( // db model: 'fieldname' => 'zbsa_city', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'City', 'placeholder'=> 'e.g. New York' ), 'county' => array( // db model: 'fieldname' => 'zbsa_county', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'County', 'placeholder'=> 'e.g. Kings County' ), 'postcode' => array( // db model: 'fieldname' => 'zbsa_postcode', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'Post Code', 'placeholder'=> 'e.g. 10019' ), 'country' => array( // db model: 'fieldname' => 'zbsa_country', 'format' => 'str', // output model 'input_type' => 'selectcountry', 'label' => 'Country', 'placeholder'=>'' ), 'created' => array('fieldname' => 'zbsa_created', 'format' => 'uts'), 'lastupdated' => array('fieldname' => 'zbsa_lastupdated', 'format' => 'uts'), ); function __construct($args=array()) { #} =========== LOAD ARGS ============== $defaultArgs = array( //'tag' => false, ); foreach ($defaultArgs as $argK => $argV){ $this->$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $this->$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$this->$argK = $newData;} else { $this->$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= } // =============================================================================== // =========== ADDRESS ======================================================== /* Addresses as distinct objects didn't make the v3.0 cut. They'd be a valid area for expansion post v3.0. This file is here as a precursor, and is used by the 3.0 migration routine to stop custom field keys colliding with field names (the obj model above) (function zeroBSCRM_AJAX_dbMigration300open()) */ // =========== / ADDRESS ===================================================== // =============================================================================== } // / class
projects/plugins/crm/includes/ZeroBSCRM.DAL3.Obj.Transactions.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V3.0+ * * Copyright 2020 Automattic * * Date: 14/01/19 */ // phpcs:disable Generic.WhiteSpace.DisallowSpaceIndent.SpacesUsed, WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ use Automattic\Jetpack\CRM\Event_Manager\Events_Manager; /** * ZBS DAL >> Transactions * * @author Woody Hayday <hello@jetpackcrm.com> * @version 2.0 * @access public * @see https://jetpackcrm.com/kb */ class zbsDAL_transactions extends zbsDAL_ObjectLayer { protected $objectType = ZBS_TYPE_TRANSACTION; protected $objectDBPrefix = 'zbst_'; protected $include_in_templating = true; protected $objectModel = array( // ID 'ID' => array('fieldname' => 'ID', 'format' => 'int'), // site + team generics 'zbs_site' => array('fieldname' => 'zbs_site', 'format' => 'int'), 'zbs_team' => array('fieldname' => 'zbs_team', 'format' => 'int'), 'zbs_owner'=> array('fieldname' => 'zbs_owner', 'format' => 'int'), // other fields 'status' => array( // db model: 'fieldname' => 'zbst_status', 'format' => 'str', // output model 'input_type' => 'select', 'label' => 'Status', 'placeholder'=>'', 'options'=>array('Succeeded','Completed','Failed','Refunded','Processing','Pending','Hold','Cancelled'), 'essential' => true, 'max_len' => 50 ), 'type' => array( // db model: 'fieldname' => 'zbst_type', 'format' => 'str', // output model 'input_type' => 'select', 'label' => 'Type', 'placeholder'=>'', 'options'=>array('Sale','Refund','Credit Note'), 'essential' => true, 'default' => 'Sale', 'max_len' => 50 ), 'ref' => array( // db model: 'fieldname' => 'zbst_ref', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'Transaction ID', 'placeholder'=>'', 'essential' => true, 'dal1key' => 'orderid', 'force_unique' => true, // must be unique. This is required and breaking if true, 'not_empty' => true, 'max_len' => 120 ), 'origin' => array( 'fieldname' => 'zbst_origin', 'format' => 'str', 'max_len' => 100 ), 'parent' => array('fieldname' => 'zbst_parent', 'format' => 'int'), 'hash' => array('fieldname' => 'zbst_hash', 'format' => 'str'), 'title' => array( // db model: 'fieldname' => 'zbst_title', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'Transaction Title', 'placeholder' => 'e.g. Product ABC', 'dal1key' => 'item', 'max_len' => 200 ), 'desc' => array( // db model: 'fieldname' => 'zbst_desc', 'format' => 'str', // output model 'input_type' => 'textarea', 'label' => 'Description', 'placeholder' => '', 'max_len' => 200 ), 'date' => array( // db model: 'fieldname' => 'zbst_date', 'format' => 'uts', 'autoconvert'=>'datetime', // NOTE autoconvert makes buildObjArr autoconvert from a 'date' using localisation rules, to a GMT timestamp (UTS) // output model 'input_type' => 'datetime', 'label' => 'Transaction Date', 'placeholder'=>'' ), // <-- this is a bit of a misnomer, it's basically timestamp for created 'customer_ip' => array( 'fieldname' => 'zbst_customer_ip', 'format' => 'str', 'max_len' => 45 ), 'currency' => array( 'fieldname' => 'zbst_currency', 'format' => 'curr', 'max_len' => 4 ), 'net' => array( // db model: 'fieldname' => 'zbst_net', 'format' => 'decimal', // output model 'input_type' => 'price', 'label' => 'Net', 'placeholder'=>'', 'default' => '0.00' ), 'fee' => array( // db model: 'fieldname' => 'zbst_fee', 'format' => 'decimal', // output model 'input_type' => 'price', 'label' => 'Fee', 'placeholder'=>'', 'default' => '0.00' ), 'discount' => array( // db model: 'fieldname' => 'zbst_discount', 'format' => 'decimal', // output model 'input_type' => 'price', 'label' => 'Discount', 'placeholder'=>'', 'default' => '0.00' ), 'shipping' => array( // db model: 'fieldname' => 'zbst_shipping', 'format' => 'decimal', // output model 'input_type' => 'price', 'label' => 'Shipping', 'placeholder'=>'', 'default' => '0.00' ), 'shipping_taxes' => array( // db model: 'fieldname' => 'zbst_shipping_taxes', 'format' => 'str', // output model 'input_type' => 'tax', 'label' => 'Shipping Taxes', 'placeholder'=>'' ), 'shipping_tax' => array('fieldname' => 'zbst_shipping_tax', 'format' => 'decimal', 'label' => 'Shipping Tax',), 'taxes' => array( // db model: 'fieldname' => 'zbst_taxes', 'format' => 'str', // output model 'input_type' => 'tax', 'label' => 'Taxes', 'placeholder'=>'' // replaces tax_rate, but tax_rate was a decimal, this is a string of applicable tax codes from tax table. ), 'tax' => array( 'fieldname' => 'zbst_tax', 'format' => 'decimal', 'label' => 'Tax', 'input_type' => 'price', 'placeholder'=>'', ), 'total' => array( // db model: 'fieldname' => 'zbst_total', 'format' => 'decimal', // output model 'input_type' => 'price', 'label' => 'Total', 'placeholder'=>'', 'default' => '0.00', 'essential' => true ), 'date_paid' => array( // db model: 'fieldname' => 'zbst_date_paid', 'format' => 'uts', 'autoconvert'=>'date', // NOTE autoconvert makes buildObjArr autoconvert from a 'date' using localisation rules, to a GMT timestamp (UTS) // output model 'input_type' => 'date', 'label' => 'Date Paid', ), 'date_completed' => array( // db model: 'fieldname' => 'zbst_date_completed', 'format' => 'uts', 'autoconvert'=>'date', // NOTE autoconvert makes buildObjArr autoconvert from a 'date' using localisation rules, to a GMT timestamp (UTS) // output model 'input_type' => 'date', 'label' => 'Date Completed' ), 'created' => array('fieldname' => 'zbst_created', 'format' => 'uts'), 'lastupdated' => array('fieldname' => 'zbst_lastupdated', 'format' => 'uts'), ); // hardtyped list of types this object type is commonly linked to protected $linkedToObjectTypes = array( ZBS_TYPE_CONTACT, ZBS_TYPE_COMPANY ); /** * Events_Manager instance. Manages CRM events. * * @since 6.2.0 * * @var Events_Manager */ private $events_manager; function __construct($args=array()) { #} =========== LOAD ARGS ============== $defaultArgs = array( //'tag' => false, ); foreach ($defaultArgs as $argK => $argV){ $this->$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $this->$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$this->$argK = $newData;} else { $this->$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= $this->events_manager = new Events_Manager(); add_filter( 'jpcrm_listview_filters', array( $this, 'add_listview_filters' ) ); } /** * Adds items to listview filter using `jpcrm_listview_filters` hook. * * @param array $listview_filters Listview filters. */ public function add_listview_filters( $listview_filters ) { global $zbs; // Add statuses if enabled. if ( $zbs->settings->get( 'filtersfromstatus' ) === 1 ) { $statuses = zeroBSCRM_getTransactionsStatuses( true ); foreach ( $statuses as $status ) { $listview_filters[ ZBS_TYPE_TRANSACTION ]['status'][ 'status_' . $status ] = $status; } } return $listview_filters; } // =============================================================================== // =========== TRANSACTION ======================================================= // generic get Company (by ID) // Super simplistic wrapper used by edit page etc. (generically called via dal->contacts->getSingle etc.) public function getSingle($ID=-1){ return $this->getTransaction($ID); } // generic get (by ID list) // Super simplistic wrapper used by MVP Export v3.0 public function getIDList($IDs=false){ return $this->getTransactions(array( 'inArr' => $IDs, 'withOwner' => true, 'withAssigned' => true, 'page' => -1, 'perPage' => -1 )); } // generic get (EVERYTHING) // expect heavy load! public function getAll($IDs=false){ return $this->getTransactions(array( 'withOwner' => true, 'withAssigned' => true, 'sortByField' => 'ID', 'sortOrder' => 'ASC', 'page' => -1, 'perPage' => -1, )); } // generic get count of (EVERYTHING) public function getFullCount(){ return $this->getTransactions(array( 'count' => true, 'page' => -1, 'perPage' => -1, )); } /** * Verifies there is a transaction with this ID accessible to current logged in user * * @param int transaction_id * * @return bool */ public function transaction_exists( $transaction_id ){ // has to be a legit int if ( empty( $transaction_id ) ){ return false; } // note this ignores ownership for now $potential_transaction = $this->getTransaction( $transaction_id, array( 'onlyID' => true ) ); if ( $potential_transaction > 0 ){ return true; } return false; } /** * returns full transaction line +- details * * @param int id transaction id * @param array $args Associative array of arguments * * @return array transaction object */ public function getTransaction($id=-1,$args=array()){ global $zbs; #} =========== LOAD ARGS ============== $defaultArgs = array( // if these two passed, will search based on these 'externalSource' => false, 'externalSourceUID' => false, // with what? 'withLineItems' => true, 'withCustomFields' => true, 'withAssigned' => true, // return ['contact'] & ['company'] arrays, & invoice_id field, if has link 'withTags' => false, 'withOwner' => false, // permissions 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_TRANSACTION), // this'll let you not-check the owner of obj // returns scalar ID of line 'onlyID' => false, 'fields' => false // false = *, array = fieldnames ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} Check ID $id = (int)$id; if ( (!empty($id) && $id > 0) || (!empty($email)) || (!empty($externalSource) && !empty($externalSourceUID)) ){ global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); $extraSelect = ''; #} ============= PRE-QUERY ============ #} Custom Fields if ($withCustomFields && !$onlyID){ #} Retrieve any cf $custFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_TRANSACTION)); #} Cycle through + build into query if (is_array($custFields)) foreach ($custFields as $cK => $cF){ // add as subquery $extraSelect .= ',(SELECT zbscf_objval FROM ' . $ZBSCRM_t['customfields'] . " WHERE zbscf_objid = transactions.ID AND zbscf_objkey = %s AND zbscf_objtype = %d LIMIT 1) '" . $cK . "'"; // add params $params[] = $cK; $params[] = ZBS_TYPE_TRANSACTION; } } $selector = 'transactions.*'; if (isset($fields) && is_array($fields)) { $selector = ''; // always needs id, so add if not present if ( ! in_array( 'ID', $fields, true ) ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable $selector = 'transactions.ID'; } foreach ( $fields as $f ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable if ( ! empty( $selector ) ) { $selector .= ','; } $selector .= 'transactions.' . $f; } } elseif ( $onlyID ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable $selector = 'transactions.ID'; } #} ============ / PRE-QUERY =========== #} Build query $query = 'SELECT ' . $selector . $extraSelect . ' FROM ' . $ZBSCRM_t['transactions'] . ' AS transactions'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase #} ============= WHERE ================ if (!empty($id) && $id > 0){ #} Add ID $wheres['ID'] = array('ID','=','%d',$id); } if (!empty($externalSource) && !empty($externalSourceUID)){ $wheres['extsourcecheck'] = array('ID','IN','(SELECT DISTINCT zbss_objid FROM '.$ZBSCRM_t['externalsources']." WHERE zbss_objtype = ".ZBS_TYPE_TRANSACTION." AND zbss_source = %s AND zbss_uid = %s)",array($externalSource,$externalSourceUID)); } #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort('ID','DESC') . $this->buildPaging(0,1); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_row($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret Results (ROW) if (isset($potentialRes) && isset($potentialRes->ID)) { #} Has results, tidy + return #} Only ID? return it directly if ($onlyID) return $potentialRes->ID; // tidy if (is_array($fields)){ // guesses fields based on table col names $res = $this->lazyTidyGeneric($potentialRes); } else { // proper tidy $res = $this->tidy_transaction($potentialRes,$withCustomFields); } if ($withLineItems){ // add all line item lines $res['lineitems'] = $this->DAL()->lineitems->getLineitems(array('associatedObjType'=>ZBS_TYPE_TRANSACTION,'associatedObjID'=>$potentialRes->ID,'perPage'=>1000,'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_LINEITEM))); } if ($withAssigned){ /* This is for MULTIPLE (e.g. multi contact/companies assigned to an inv) // add all assigned contacts/companies $res['contacts'] = $this->DAL()->contacts->getContacts(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_TRANSACTION, 'hasObjIDLinkedTo'=>$resDataLine->ID, 'perPage'=>-1, 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); $res['companies'] = $this->DAL()->companies->getCompanies(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_TRANSACTION, 'hasObjIDLinkedTo'=>$resDataLine->ID, 'perPage'=>-1, 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_COMPANY))); .. but we use 1:1, at least now: */ // add all assigned contacts/companies $res['contact'] = $this->DAL()->contacts->getContacts(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_TRANSACTION, 'hasObjIDLinkedTo'=>$potentialRes->ID, 'page' => 0, 'perPage'=>1, // FORCES 1 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); $res['company'] = $this->DAL()->companies->getCompanies(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_TRANSACTION, 'hasObjIDLinkedTo'=>$potentialRes->ID, 'page' => 0, 'perPage'=>1, // FORCES 1 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_COMPANY))); // invoice id always singular. $res['invoice_id'] = $this->DAL()->getFirstIDLinkedToObj(array( 'objtypefrom' => ZBS_TYPE_TRANSACTION, 'objtypeto' => ZBS_TYPE_INVOICE, 'objfromid' => $potentialRes->ID, )); } if ($withTags){ // add all tags lines $res['tags'] = $this->DAL()->getTagsForObjID(array('objtypeid'=>ZBS_TYPE_TRANSACTION,'objid'=>$potentialRes->ID)); } return $res; } } // / if ID return false; } /** * Returns transaction summed by field between passed timestamps */ public function getTransactionTotalByMonth( $args=array() ) { global $ZBSCRM_t, $wpdb, $zbs; // ============ LOAD ARGS ============= $defaultArgs = array( 'paidAfter' => strtotime( '12 month ago' ), 'paidBefore' => time(), ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } // =========== / LOAD ARGS ============= $column_prefix = 'zbst_'; // only include transactions with statuses which should be included in total value: $transStatusQueryAdd = $this->getTransactionStatusesToIncludeQuery(); $sql = $wpdb->prepare( 'SELECT SUM(' . $column_prefix . 'total) as total, MONTH(FROM_UNIXTIME(' . $column_prefix . 'date)) as month, YEAR(FROM_UNIXTIME(' . $column_prefix . 'date)) as year FROM ' . $ZBSCRM_t['transactions'] . ' WHERE ' . $column_prefix . 'date > %d AND ' . $column_prefix . 'date < %d' . $transStatusQueryAdd . ' GROUP BY month, year ORDER BY year, month', $paidAfter, $paidBefore ); $res = $wpdb->get_results( $sql, ARRAY_A ); return $res; } /** * returns transaction detail lines * * @param array $args Associative array of arguments * * @return array of transaction lines */ public function getTransactions($args=array()){ global $ZBSCRM_t,$wpdb,$zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( // Search/Filtering (leave as false to ignore) 'searchPhrase' => '', // searches zbst_title and zbst_desc 'inArr' => false, 'isTagged' => false, // 1x INT OR array(1,2,3) 'isNotTagged' => false, // 1x INT OR array(1,2,3) 'ownedBy' => false, 'externalSource' => false, // e.g. paypal 'hasStatus' => false, // Lead (this takes over from the quick filter post 19/6/18) 'otherStatus' => false, // status other than 'Lead' 'assignedContact' => false, // assigned to contact id (int) 'assignedCompany' => false, // assigned to company id (int) 'assignedInvoice' => false, // assigned to invoice id (int) 'quickFilters' => false, 'external_source_uid' => false, // e.g. woo-order_10 // date ranges 'olderThan' => false, // uts - checks 'date' 'newerThan' => false, // uts - checks 'date' 'paidBefore' => false, // uts - checks 'date_paid' 'paidAfter' => false, // uts - checks 'date_paid' 'createdBefore' => false, // uts - checks 'created' 'createdAfter' => false, // uts - checks 'created' // returns 'count' => false, 'total' => false, // returns a summed total value of transactions (scalar) 'withLineItems' => true, 'withCustomFields' => true, 'withTags' => false, 'withOwner' => false, 'withAssigned' => true, // return ['contact'] & ['company'] objs, & invoice_id field, if has link 'onlyColumns' => false, // if passed (array('fname','lname')) will return only those columns (overwrites some other 'return' options). NOTE: only works for base fields (not custom fields) // order by 'sortByField' => 'ID', 'sortOrder' => 'ASC', 'page' => 0, // this is what page it is (gets * by for limit) 'perPage' => 100, 'whereCase' => 'AND', // DEFAULT = AND // permissions 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_TRANSACTION), // this'll let you not-check the owner of obj ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); $joinQ = ''; $extraSelect = ''; #} ============= PRE-QUERY ============ // Capitalise this $sortOrder = strtoupper($sortOrder); // If just count or total, turn off any meta detail if ( $count || $total ) { $withCustomFields = false; $withTags = false; $withOwner = false; $withAssigned = false; $withLineItems = false; } #} If onlyColumns, validate if ($onlyColumns){ #} onlyColumns build out a field arr if (is_array($onlyColumns) && count($onlyColumns) > 0){ $onlyColumnsFieldArr = array(); foreach ($onlyColumns as $col){ // find db col key from field key (e.g. fname => zbsc_fname) $dbCol = ''; if (isset($this->objectModel[$col]) && isset($this->objectModel[$col]['fieldname'])) $dbCol = $this->objectModel[$col]['fieldname']; if (!empty($dbCol)){ $onlyColumnsFieldArr[$dbCol] = $col; } } } // if legit cols: if (isset($onlyColumnsFieldArr) && is_array($onlyColumnsFieldArr) && count($onlyColumnsFieldArr) > 0){ $onlyColumns = true; // If onlyColumns, turn off extras $withCustomFields = false; $withTags = false; $withOwner = false; $withAssigned = false; $withLineItems = false; } else { // deny $onlyColumns = false; } } #} Custom Fields if ($withCustomFields){ #} Retrieve any cf $custFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_TRANSACTION)); #} Cycle through + build into query if (is_array($custFields)) foreach ($custFields as $cK => $cF){ // custom field (e.g. 'third name') it'll be passed here as 'third-name' // ... problem is mysql does not like that :) so we have to chage here: // in this case we prepend cf's with cf_ and we switch - for _ $cKey = 'cf_'.str_replace('-','_',$cK); // we also check the $sortByField in case that's the same cf if ($cK == $sortByField){ // sort by $sortByField = $cKey; // check if sort needs any CAST (e.g. numeric): $sortByField = $this->DAL()->build_custom_field_order_by_str( $sortByField, $cF ); } // add as subquery $extraSelect .= ',(SELECT zbscf_objval FROM ' . $ZBSCRM_t['customfields'] . ' WHERE zbscf_objid = transactions.ID AND zbscf_objkey = %s AND zbscf_objtype = %d LIMIT 1) ' . $cKey; // add params $params[] = $cK; $params[] = ZBS_TYPE_TRANSACTION; } } if ( $external_source_uid ) { $extraSelect .= ', external_source.external_source_uids, external_source.external_source_sources'; $joinQ .= ' LEFT JOIN ( SELECT extsrcs.zbss_objid external_source_objid, ' . $this->DAL()->build_group_concat( 'extsrcs.zbss_uid', '\n' ) . ' AS external_source_uids, ' . $this->DAL()->build_group_concat( 'extsrcs.zbss_source', '\n' ) . ' AS external_source_sources FROM ' . $ZBSCRM_t['externalsources'] . ' extsrcs WHERE extsrcs.zbss_objtype = %s GROUP BY extsrcs.zbss_objid ) external_source ON transactions.ID = external_source.external_source_objid'; $params[] = ZBS_TYPE_TRANSACTION; } #} ============ / PRE-QUERY =========== #} Build query $query = 'SELECT transactions.*' . $extraSelect . ' FROM ' . $ZBSCRM_t['transactions'] . ' AS transactions' . $joinQ; #} Count override if ( $count ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable $query = 'SELECT COUNT(transactions.ID) FROM ' . $ZBSCRM_t['transactions'] . ' AS transactions' . $joinQ; } #} onlyColumns override if ($onlyColumns && is_array($onlyColumnsFieldArr) && count($onlyColumnsFieldArr) > 0){ $columnStr = ''; foreach ($onlyColumnsFieldArr as $colDBKey => $colStr){ if (!empty($columnStr)) $columnStr .= ','; // this presumes str is db-safe? could do with sanitation? $columnStr .= $colDBKey; } $query = 'SELECT ' . $columnStr . ' FROM ' . $ZBSCRM_t['transactions'] . ' AS transactions' . $joinQ; } // $total only override if ( $total ){ $query = 'SELECT SUM(transactions.zbst_total) total FROM ' . $ZBSCRM_t['transactions'] . ' AS transactions' . $joinQ; } #} ============= WHERE ================ #} Add Search phrase if (!empty($searchPhrase)){ // search? - ALL THESE COLS should probs have index of FULLTEXT in db? $searchWheres = array(); $searchWheres['search_ID'] = array('ID','=','%d',$searchPhrase); $searchWheres['search_ref'] = array('zbst_ref','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_title'] = array('zbst_title','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_desc'] = array('zbst_desc','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_total'] = array('zbst_total','LIKE','%s', $searchPhrase.'%'); if ( $external_source_uid ) { $searchWheres['search_external_source_uid'] = array( 'external_source.external_source_uids', 'LIKE', '%s', '%' . $searchPhrase . '%' ); } // 3.0.13 - Added ability to search custom fields (optionally) $customFieldSearch = zeroBSCRM_getSetting('customfieldsearch'); if ($customFieldSearch == 1){ // simplistic add // NOTE: This IGNORES ownership of custom field lines. $searchWheres['search_customfields'] = array('ID','IN',"(SELECT zbscf_objid FROM ".$ZBSCRM_t['customfields']." WHERE zbscf_objval LIKE %s AND zbscf_objtype = ".ZBS_TYPE_TRANSACTION.")",'%'.$searchPhrase.'%'); } // This generates a query like 'zbst_fname LIKE %s OR zbst_lname LIKE %s', // which we then need to include as direct subquery (below) in main query :) $searchQueryArr = $this->buildWheres($searchWheres,'',array(),'OR',false); if (is_array($searchQueryArr) && isset($searchQueryArr['where']) && !empty($searchQueryArr['where'])){ // add it $wheres['direct'][] = array('('.$searchQueryArr['where'].')',$searchQueryArr['params']); } } #} In array (if inCompany passed, this'll currently overwrite that?! (todo2.5)) if (is_array($inArr) && count($inArr) > 0){ // clean for ints $inArrChecked = array(); foreach ($inArr as $x){ $inArrChecked[] = (int)$x; } // add where $wheres['inarray'] = array('ID','IN','('.implode(',',$inArrChecked).')'); } #} Owned by if (!empty($ownedBy) && $ownedBy > 0){ // would never hard-type this in (would make generic as in buildWPMetaQueryWhere) // but this is only here until MIGRATED to db2 globally //$wheres['incompany'] = array('ID','IN','(SELECT DISTINCT post_id FROM '.$wpdb->prefix."postmeta WHERE meta_key = 'zbs_company' AND meta_value = %d)",$inCompany); // Use obj links now $wheres['ownedBy'] = array('zbs_owner','=','%s',$ownedBy); } // External sources if ( !empty( $externalSource ) ){ // NO owernship built into this, check when roll out multi-layered ownsership $wheres['externalsource'] = array('ID','IN','(SELECT DISTINCT zbss_objid FROM '.$ZBSCRM_t['externalsources']." WHERE zbss_objtype = ".ZBS_TYPE_TRANSACTION." AND zbss_source = %s)",$externalSource); } // Timestamp checks: #} olderThan if (!empty($olderThan) && $olderThan > 0 && $olderThan !== false) $wheres['olderThan'] = array('zbst_date','<=','%d',$olderThan); #} newerThan if (!empty($newerThan) && $newerThan > 0 && $newerThan !== false) $wheres['newerThan'] = array('zbst_date','>=','%d',$newerThan); #} createdBefore if (!empty($createdBefore) && $createdBefore > 0 && $createdBefore !== false) $wheres['createdBefore'] = array('zbst_created','<=','%d',$createdBefore); #} createdAfter if (!empty($createdAfter) && $createdAfter > 0 && $createdAfter !== false) $wheres['createdAfter'] = array('zbst_created','>=','%d',$createdAfter); #} paidBefore if (!empty($paidBefore) && $paidBefore > 0 && $paidBefore !== false) $wheres['paidBefore'] = array('zbst_date_paid','<=','%d',$paidBefore); #} paidAfter if (!empty($paidAfter) && $paidAfter > 0 && $paidAfter !== false) $wheres['paidAfter'] = array('zbst_date_paid','>=','%d',$paidAfter); // status if (!empty($hasStatus) && $hasStatus !== false) $wheres['hasStatus'] = array('zbst_status','=','%s',$hasStatus); if (!empty($otherStatus) && $otherStatus !== false) $wheres['otherStatus'] = array('zbst_status','<>','%s',$otherStatus); // assignedContact + assignedCompany + assignedInvoice if (!empty($assignedContact) && $assignedContact !== false && $assignedContact > 0) $wheres['assignedContact'] = array('ID','IN','(SELECT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = ".ZBS_TYPE_TRANSACTION." AND zbsol_objtype_to = ".ZBS_TYPE_CONTACT." AND zbsol_objid_to = %d)",$assignedContact); if (!empty($assignedCompany) && $assignedCompany !== false && $assignedCompany > 0) $wheres['assignedCompany'] = array('ID','IN','(SELECT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = ".ZBS_TYPE_TRANSACTION." AND zbsol_objtype_to = ".ZBS_TYPE_COMPANY." AND zbsol_objid_to = %d)",$assignedCompany); if (!empty($assignedInvoice) && $assignedInvoice !== false && $assignedInvoice > 0) $wheres['assignedInvoice'] = array('ID','IN','(SELECT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = ".ZBS_TYPE_TRANSACTION." AND zbsol_objtype_to = ".ZBS_TYPE_INVOICE." AND zbsol_objid_to = %d)",$assignedInvoice); #} Quick filters - adapted from DAL1 (probs can be slicker) if (is_array($quickFilters) && count($quickFilters) > 0){ // cycle through foreach ($quickFilters as $qFilter){ // where status = x // USE hasStatus above now... if ( str_starts_with( $qFilter, 'status_' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $quick_filter_status = substr( $qFilter, 7 ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $wheres['quickfilterstatus'] = array( 'zbst_status', '=', 'convert(%s using utf8mb4) collate utf8mb4_bin', $quick_filter_status ); } else { // if we've hit no filter query, let external logic hook in to provide alternatives // First used in WooSync module $wheres = apply_filters( 'jpcrm_transaction_query_quickfilter', $wheres, $qFilter ); } } }// / quickfilters #} Any additionalWhereArr? if (isset($additionalWhereArr) && is_array($additionalWhereArr) && count($additionalWhereArr) > 0){ // add em onto wheres (note these will OVERRIDE if using a key used above) // Needs to be multi-dimensional $wheres = array_merge($wheres,$additionalWhereArr); $wheres = array_merge_recursive($wheres,$additionalWhereArr); } #} Is Tagged (expects 1 tag ID OR array) // catch 1 item arr if (is_array($isTagged) && count($isTagged) == 1) $isTagged = $isTagged[0]; if (!is_array($isTagged) && !empty($isTagged) && $isTagged > 0){ // add where tagged // 1 int: $wheres['direct'][] = array( '((SELECT COUNT(ID) FROM ' . $ZBSCRM_t['taglinks'] . ' WHERE zbstl_objtype = %d AND zbstl_objid = transactions.ID AND zbstl_tagid = %d) > 0)', array( ZBS_TYPE_TRANSACTION, $isTagged ), ); } else if (is_array($isTagged) && count($isTagged) > 0){ // foreach in array :) $tagStr = ''; foreach ($isTagged as $iTag){ $i = (int)$iTag; if ($i > 0){ if ($tagStr !== '') $tagStr .','; $tagStr .= $i; } } if (!empty($tagStr)){ $wheres['direct'][] = array( '((SELECT COUNT(ID) FROM ' . $ZBSCRM_t['taglinks'] . ' WHERE zbstl_objtype = %d AND zbstl_objid = transactions.ID AND zbstl_tagid IN (%s)) > 0)', array( ZBS_TYPE_TRANSACTION, $tagStr ), ); } } #} Is NOT Tagged (expects 1 tag ID OR array) // catch 1 item arr if (is_array($isNotTagged) && count($isNotTagged) == 1) $isNotTagged = $isNotTagged[0]; if (!is_array($isNotTagged) && !empty($isNotTagged) && $isNotTagged > 0){ // add where tagged // 1 int: $wheres['direct'][] = array( '((SELECT COUNT(ID) FROM ' . $ZBSCRM_t['taglinks'] . ' WHERE zbstl_objtype = %d AND zbstl_objid = transactions.ID AND zbstl_tagid = %d) = 0)', array( ZBS_TYPE_TRANSACTION, $isNotTagged ), ); } else if (is_array($isNotTagged) && count($isNotTagged) > 0){ // foreach in array :) $tagStr = ''; foreach ($isNotTagged as $iTag){ $i = (int)$iTag; if ($i > 0){ if ($tagStr !== '') $tagStr .','; $tagStr .= $i; } } if (!empty($tagStr)){ $wheres['direct'][] = array( '((SELECT COUNT(ID) FROM ' . $ZBSCRM_t['taglinks'] . ' WHERE zbstl_objtype = %d AND zbstl_objid = transactions.ID AND zbstl_tagid IN (%s)) = 0)', array( ZBS_TYPE_TRANSACTION, $tagStr ), ); } } #} ============ / WHERE =============== #} ============ SORT ============== // Obj Model based sort conversion // converts 'addr1' => 'zbsco_addr1' generically if (isset($this->objectModel[$sortByField]) && isset($this->objectModel[$sortByField]['fieldname'])) $sortByField = $this->objectModel[$sortByField]['fieldname']; // Mapped sorts // This catches listview and other exception sort cases $sort_map = array( // Note: "customer" here could be company or contact, so it's not a true sort (as no great way of doing this beyond some sort of prefix comparing) 'customer' => '(SELECT ID FROM ' . $ZBSCRM_t['contacts'] . ' WHERE ID IN (SELECT zbsol_objid_to FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_TRANSACTION . ' AND zbsol_objtype_to = ' . ZBS_TYPE_CONTACT . ' AND zbsol_objid_from = transactions.ID))', ); if ( array_key_exists( $sortByField, $sort_map ) ) { $sortByField = $sort_map[ $sortByField ]; } if ( $external_source_uid && $sortByField === "external_source" ){ $sortByField = ["external_source_uids" => $sortOrder]; } #} ============ / SORT ============== #} CHECK this + reset to default if faulty if (!in_array($whereCase,array('AND','OR'))) $whereCase = 'AND'; #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params,$whereCase); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner,'contact'); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort($sortByField,$sortOrder) . $this->buildPaging($page,$perPage); try { #} Prep & run query $queryObj = $this->prepare($query,$params); // Catch count/total + return if requested if ( $count || $total ) return $wpdb->get_var($queryObj); #} else continue.. $potentialRes = $wpdb->get_results($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret results (Result Set - multi-row) if (isset($potentialRes) && is_array($potentialRes) && count($potentialRes) > 0) { #} Has results, tidy + return foreach ($potentialRes as $resDataLine) { // only columns? if ($onlyColumns && is_array($onlyColumnsFieldArr) && count($onlyColumnsFieldArr) > 0){ // only coumns return. $resArr = array(); foreach ($onlyColumnsFieldArr as $colDBKey => $colStr){ if (isset($resDataLine->$colDBKey)) $resArr[$colStr] = $resDataLine->$colDBKey; } } else { // tidy $resArr = $this->tidy_transaction($resDataLine,$withCustomFields); } if ($withLineItems){ // add all line item lines $resArr['lineitems'] = $this->DAL()->lineitems->getLineitems(array('associatedObjType'=>ZBS_TYPE_TRANSACTION,'associatedObjID'=>$resDataLine->ID,'perPage'=>1000,'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_LINEITEM))); } if ($withTags){ // add all tags lines $resArr['tags'] = $this->DAL()->getTagsForObjID(array('objtypeid'=>ZBS_TYPE_TRANSACTION,'objid'=>$resDataLine->ID)); } if ($withAssigned){ /* This is for MULTIPLE (e.g. multi contact/companies assigned to an inv) // add all assigned contacts/companies $res['contacts'] = $this->DAL()->contacts->getContacts(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_TRANSACTION, 'hasObjIDLinkedTo'=>$resDataLine->ID, 'perPage'=>-1, 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); $res['companies'] = $this->DAL()->companies->getCompanies(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_TRANSACTION, 'hasObjIDLinkedTo'=>$resDataLine->ID, 'perPage'=>-1, 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_COMPANY))); .. but we use 1:1, at least now: */ // add all assigned contacts/companies $resArr['contact'] = $this->DAL()->contacts->getContacts(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_TRANSACTION, 'hasObjIDLinkedTo'=>$resDataLine->ID, 'page' => 0, 'perPage'=>1, // FORCES 1 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); $resArr['company'] = $this->DAL()->companies->getCompanies(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_TRANSACTION, 'hasObjIDLinkedTo'=>$resDataLine->ID, 'page' => 0, 'perPage'=>1, // FORCES 1 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_COMPANY))); } if ( $external_source_uid ) { $resArr['external_source_uid'] = $this->tidy_external_sources( $resDataLine ); } $res[] = $resArr; } } return $res; } /** * Returns a count of transactions (owned) * .. inc by status * * @return int count */ public function getTransactionCount($args=array()){ #} ============ LOAD ARGS ============= $defaultArgs = array( // Search/Filtering (leave as false to ignore) 'withStatus' => false, // will be str if used // permissions 'ignoreowner' => true, // this'll let you not-check the owner of obj ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= $whereArr = array(); if ($withStatus !== false && !empty($withStatus)) $whereArr['status'] = array('zbst_status','=','%s',$withStatus); return $this->DAL()->getFieldByWHERE(array( 'objtype' => ZBS_TYPE_TRANSACTION, 'colname' => 'COUNT(ID)', 'where' => $whereArr, 'ignoreowner' => $ignoreowner)); } /** * adds or updates a transaction object * * @param array $args Associative array of arguments * id (if update), owner, data (array of field data) * * @return int line ID */ public function addUpdateTransaction($args=array()){ global $ZBSCRM_t,$wpdb,$zbs; #} Retrieve any cf $customFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_TRANSACTION)); // not req. $addrCustomFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_ADDRESS)); #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'owner' => -1, // fields (directly) 'data' => array( 'status' => '', 'type' => '', 'ref' => '', 'origin' => '', 'parent' => '', 'hash' => '', 'title' => '', 'desc' => '', 'date' => '', 'customer_ip' => '', 'currency' => '', 'net' => '', 'fee' => '', 'discount' => '', 'shipping' => '', 'shipping_taxes' => '', 'shipping_tax' => '', 'taxes' => '', 'tax' => '', 'total' => '', 'date_paid' => null, 'date_completed' => null, // lineitems: 'lineitems' => false, // will be an array of lineitem lines (as per matching lineitem database model) // note: if no change desired, pass "false" // if removal of all/change, pass empty array // Note Custom fields may be passed here, but will not have defaults so check isset() // obj links: 'contacts' => false, // array of id's 'companies' => false, // array of id's 'invoice_id' => false, // ID if assigned to an invoice // tags 'tags' => -1, // pass an array of tag ids or tag strings 'tag_mode' => 'replace', // replace|append|remove 'externalSources' => -1, // if this is an array(array('source'=>src,'uid'=>uid),multiple()) it'll add :) // allow this to be set for MS sync etc. 'created' => -1, 'lastupdated' => '', ), 'limitedFields' => -1, // if this is set it OVERRIDES data (allowing you to set specific fields + leave rest in tact) // ^^ will look like: array(array('key'=>x,'val'=>y,'type'=>'%s')) // this function as DAL1 func did. 'extraMeta' => -1, 'automatorPassthrough' => -1, 'silentInsert' => false, // this was for init Migration - it KILLS all IA for newTransaction (because is migrating, not creating new :) this was -1 before 'do_not_update_blanks' => false, // this allows you to not update fields if blank (same as fieldoverride for extsource -> in) 'do_not_mark_invoices' => false // by default all trans associated with an INV will fire a check "should this inv be marked paid" on add/update of trans. If this is true, check will not run ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } // Needs this to grab custom fields (if passed) too :) if (is_array($customFields)) foreach ($customFields as $cK => $cF){ // only for data, limited fields below if (is_array($data)) { if (isset($args['data'][$cK])) $data[$cK] = $args['data'][$cK]; } } // this takes limited fields + checks through for custom fields present // (either as key zbst_source or source, for example) // then switches them into the $data array, for separate update // where this'll fall over is if NO normal contact data is sent to update, just custom fields if (is_array($limitedFields) && is_array($customFields)){ //$customFieldKeys = array_keys($customFields); $newLimitedFields = array(); // cycle through foreach ($limitedFields as $field){ // some weird case where getting empties, so added check if (isset($field['key']) && !empty($field['key'])){ $dePrefixed = ''; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase if ( str_starts_with( $field['key'], 'zbst_' ) ) { $dePrefixed = substr( $field['key'], strlen( 'zbst_' ) ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } if (isset($customFields[$field['key']])){ // is custom, move to data $data[$field['key']] = $field['val']; } else if (!empty($dePrefixed) && isset($customFields[$dePrefixed])){ // is custom, move to data $data[$dePrefixed] = $field['val']; } else { // add it to limitedFields (it's not dealt with post-update) $newLimitedFields[] = $field; } } } // move this back in $limitedFields = $newLimitedFields; unset($newLimitedFields); } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ $id = (int)$id; // here we check that the potential owner CAN even own if ($owner > 0 && !user_can($owner,'admin_zerobs_usr')) $owner = -1; // if owner = -1, add current if (!isset($owner) || $owner === -1) { $owner = zeroBSCRM_user(); } if (is_array($limitedFields)){ // LIMITED UPDATE (only a few fields.) if (!is_array($limitedFields) || count ($limitedFields) <= 0) return false; // REQ. ID too (can only update) if (empty($id) || $id <= 0) return false; } else { // NORMAL, FULL UPDATE } #} If no status, and default is specified in settings, add that in :) // for now, I copied this from addUpdateTransaction: 'Unknown'; if (is_null($data['status']) || !isset($data['status']) || empty($data['status'])){ // Default status for obj? -> this one gets for contacts -> $data['status'] = __('Unknown','zero-bs-crm'); //zeroBSCRM_getSetting('defaultstatus'); } #} ========= / CHECK FIELDS =========== #} ========= OVERRIDE SETTING (Deny blank overrides) =========== // this only functions if externalsource is set (e.g. api/form, etc.) if (isset($data['externalSources']) && is_array($data['externalSources']) && count($data['externalSources']) > 0) { if (zeroBSCRM_getSetting('fieldoverride') == "1"){ $do_not_update_blanks = true; } } // either ext source + setting, or set by the func call if ($do_not_update_blanks){ // this setting says 'don't override filled-out data with blanks' // so here we check through any passed blanks + convert to limitedFields // only matters if $id is set (there is somt to update not add if (isset($id) && !empty($id) && $id > 0){ // get data to copy over (for now, this is required to remove 'fullname' etc.) $dbData = $this->db_ready_transaction($data); //unset($dbData['id']); // this is unset because we use $id, and is update, so not req. legacy issue //unset($dbData['created']); // this is unset because this uses an obj which has been 'updated' against original details, where created is output in the WRONG format :) $origData = $data; //$data = array(); $limitedData = array(); // array(array('key'=>'zbst_x','val'=>y,'type'=>'%s')) // cycle through + translate into limitedFields (removing any blanks, or arrays (e.g. externalSources)) // we also have to remake a 'faux' data (removing blanks for tags etc.) for the post-update updates foreach ($dbData as $k => $v){ $intV = (int)$v; // only add if valuenot empty if (!is_array($v) && !empty($v) && $v != '' && $v !== 0 && $v !== -1 && $intV !== -1){ // add to update arr $limitedData[] = array( 'key' => 'zbst_'.$k, // we have to add zbst_ here because translating from data -> limited fields 'val' => $v, 'type' => $this->getTypeStr('zbst_'.$k) ); // add to remade $data for post-update updates $data[$k] = $v; } } // copy over $limitedFields = $limitedData; } // / if ID } // / if do_not_update_blanks #} ========= / OVERRIDE SETTING (Deny blank overrides) =========== #} ========= BUILD DATA =========== $update = false; $dataArr = array(); $typeArr = array(); if (is_array($limitedFields)){ // LIMITED FIELDS $update = true; // cycle through foreach ($limitedFields as $field){ // some weird case where getting empties, so added check if (!empty($field['key'])){ $dataArr[$field['key']] = $field['val']; $typeArr[] = $field['type']; } } // add update time if (!isset($dataArr['zbst_lastupdated'])){ $dataArr['zbst_lastupdated'] = time(); $typeArr[] = '%d'; } } else { // FULL UPDATE/INSERT // contacts - avoid dupes if (isset($data['contacts']) && is_array($data['contacts'])){ $coArr = array(); foreach ($data['contacts'] as $c){ $cI = (int)$c; if ($cI > 0 && !in_array($cI, $coArr)) $coArr[] = $cI; } // reset the main if (count($coArr) > 0) $data['contacts'] = $coArr; else $data['contacts'] = 'unset'; unset($coArr); } // companies - avoid dupes if (isset($data['companies']) && is_array($data['companies'])){ $coArr = array(); foreach ($data['companies'] as $c){ $cI = (int)$c; if ($cI > 0 && !in_array($cI, $coArr)) $coArr[] = $cI; } // reset the main if (count($coArr) > 0) $data['companies'] = $coArr; else $data['companies'] = 'unset'; unset($coArr); } // UPDATE $dataArr = array( // ownership // no need to update these (as of yet) - can't move teams etc. //'zbs_site' => zeroBSCRM_installSite(), //'zbs_team' => zeroBSCRM_installTeam(), //'zbs_owner' => $owner, 'zbst_status' => $data['status'], 'zbst_type' => $data['type'], 'zbst_ref' => $data['ref'], 'zbst_origin' => $data['origin'], 'zbst_parent' => $data['parent'], 'zbst_hash' => $data['hash'], 'zbst_title' => $data['title'], 'zbst_desc' => $data['desc'], 'zbst_date' => $data['date'], 'zbst_customer_ip' => $data['customer_ip'], 'zbst_currency' => $data['currency'], 'zbst_net' => $data['net'], 'zbst_fee' => $data['fee'], 'zbst_discount' => $data['discount'], 'zbst_shipping' => $data['shipping'], 'zbst_shipping_taxes' => $data['shipping_taxes'], 'zbst_shipping_tax' => $data['shipping_tax'], 'zbst_taxes' => $data['taxes'], 'zbst_tax' => $data['tax'], 'zbst_total' => $data['total'], 'zbst_date_paid' => $data['date_paid'], 'zbst_date_completed' => $data['date_completed'], 'zbst_lastupdated' => time(), ); $typeArr = array( // field data types //'%d', // site //'%d', // team //'%d', // owner '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%d', '%d', ); if (!empty($id) && $id > 0){ // is update $update = true; } else { // INSERT (get's few extra :D) $update = false; $dataArr['zbs_site'] = zeroBSCRM_site(); $typeArr[] = '%d'; $dataArr['zbs_team'] = zeroBSCRM_team(); $typeArr[] = '%d'; $dataArr['zbs_owner'] = $owner; $typeArr[] = '%d'; if (isset($data['created']) && !empty($data['created']) && $data['created'] !== -1){ $dataArr['zbst_created'] = $data['created'];$typeArr[] = '%d'; } else { $dataArr['zbst_created'] = time(); $typeArr[] = '%d'; } // if no transaction date is passed on creation, use time() // allow for 0 value (valid epoch time) if ( empty($dataArr['zbst_date']) && $dataArr['zbst_date'] !== 0 ) { $dataArr['zbst_date'] = time(); } } } #} ========= / BUILD DATA =========== #} ============================================================ #} ========= CHECK force_uniques & not_empty & max_len ======== // if we're passing limitedFields we skip these, for now // #v3.1 - would make sense to unique/nonempty check just the limited fields. #gh-145 if (!is_array($limitedFields)){ // verify uniques if (!$this->verifyUniqueValues($data,$id)) return false; // / fails unique field verify // verify not_empty if (!$this->verifyNonEmptyValues($data)) return false; // / fails empty field verify } // whatever we do we check for max_len breaches and abbreviate to avoid wpdb rejections $dataArr = $this->wpdbChecks($dataArr); #} ========= / CHECK force_uniques & not_empty ================ #} ============================================================ #} Check if ID present if ($update){ #} Check if obj exists (here) - for now just brutal update (will error when doesn't exist) $originalStatus = $this->getTransactionStatus($id); // log any change of status if (isset($dataArr['zbst_status']) && !empty($dataArr['zbst_status']) && !empty($originalStatus) && $dataArr['zbst_status'] != $originalStatus){ // status change $statusChange = array( 'from' => $originalStatus, 'to' => $dataArr['zbst_status'] ); } #} Attempt update if ($wpdb->update( $ZBSCRM_t['transactions'], $dataArr, array( // where 'ID' => $id ), $typeArr, array( // where data types '%d' )) !== false){ // if passing limitedFields instead of data, we ignore the following // this doesn't work, because data is in args default as arr //if (isset($data) && is_array($data)){ // so... if (!isset($limitedFields) || !is_array($limitedFields) || $limitedFields == -1){ // Line Items ==== // line item work if (isset($data['lineitems']) && is_array($data['lineitems'])){ // if array passed, update, even if removing if (count($data['lineitems']) > 0){ // passed, for now this is BRUTAL and just clears old ones + readds // once live, discuss how to refactor to be less brutal. // delete all lineitems $this->DAL()->lineitems->deleteLineItemsForObject(array('objID'=>$id,'objType'=>ZBS_TYPE_TRANSACTION)); // addupdate each foreach ($data['lineitems'] as $lineitem) { // slight rejig of passed so works cleanly with data array style $lineItemID = false; if (isset($lineitem['ID'])) $lineItemID = $lineitem['ID']; $this->DAL()->lineitems->addUpdateLineitem(array( 'id'=>$lineItemID, 'linkedObjType' => ZBS_TYPE_TRANSACTION, 'linkedObjID' => $id, 'data'=>$lineitem )); } } else { // delete all lineitems $this->DAL()->lineitems->deleteLineItemsForObject(array('objID'=>$id,'objType'=>ZBS_TYPE_TRANSACTION)); } } // / Line Items ==== // OBJ LINKS - to contacts/companies $this->addUpdateObjectLinks($id,$data['contacts'],ZBS_TYPE_CONTACT); $this->addUpdateObjectLinks($id,$data['companies'],ZBS_TYPE_COMPANY); // IA also gets 'againstid' historically, but we'll pass as 'against id's' $againstIDs = array('contacts'=>$data['contacts'],'companies'=>$data['companies']); // OBJ Links - to invoices $this->addUpdateObjectLinks($id,array($data['invoice_id']),ZBS_TYPE_INVOICE); // if not-empty inv id, check if needs to be mark paid! if (!$do_not_mark_invoices && !empty($data['invoice_id']) && $data['invoice_id'] > 0){ //function to check ammount due and mark invoice as paid if amount due <= 0. zeroBSCRM_check_amount_due_mark_paid($data['invoice_id']); } // tags if (isset($data['tags']) && is_array($data['tags'])) { $this->addUpdateTransactionTags( array( 'id' => $id, 'tag_input' => $data['tags'], 'mode' => $data['tag_mode'] ) ); } // externalSources $approvedExternalSource = $this->DAL()->addUpdateExternalSources( array( 'obj_id' => $id, 'obj_type_id' => ZBS_TYPE_TRANSACTION, 'external_sources' => isset($data['externalSources']) ? $data['externalSources'] : array(), ) ); // for IA below // Custom fields? #} Cycle through + add/update if set if (is_array($customFields)) foreach ($customFields as $cK => $cF){ // any? if (isset($data[$cK])){ // add update $cfID = $this->DAL()->addUpdateCustomField(array( 'data' => array( 'objtype' => ZBS_TYPE_TRANSACTION, 'objid' => $id, 'objkey' => $cK, 'objval' => $data[$cK] ))); } } // / Custom Fields } else { // limited fields // here we set what will not have been passed as blanks, for the IA to use below. $againstIDs = false; $approvedExternalSource = ''; } // Any extra meta keyval pairs // BRUTALLY updates (no checking) $confirmedExtraMeta = false; if (isset($extraMeta) && is_array($extraMeta)) { $confirmedExtraMeta = array(); foreach ($extraMeta as $k => $v){ #} This won't fix stupid keys, just catch basic fails... $cleanKey = strtolower(str_replace(' ','_',$k)); #} Brutal update //update_post_meta($postID, 'zbs_customer_extra_'.$cleanKey, $v); $this->DAL()->updateMeta(ZBS_TYPE_TRANSACTION,$id,'extra_'.$cleanKey,$v); #} Add it to this, which passes to IA $confirmedExtraMeta[$cleanKey] = $v; } } #} INTERNAL AUTOMATOR #} & #} FALLBACKS // UPDATING CONTACT if (!$silentInsert){ // catch dirty flag (update of status) (note, after update_post_meta - as separate) //if (isset($_POST['zbst_status_dirtyflag']) && $_POST['zbst_status_dirtyflag'] == "1"){ // actually here, it's set above if (isset($statusChange) && is_array($statusChange)){ // status has changed // IA zeroBSCRM_FireInternalAutomator('transaction.status.update',array( 'id' => $id, 'againstids' => $againstIDs, 'data' => $data, 'from' => $statusChange['from'], 'to' => $statusChange['to'] )); } // IA General transaction update (2.87+) zeroBSCRM_FireInternalAutomator('transaction.update',array( 'id' => $id, 'data' => $data, 'againstids' => $againstIDs, 'extsource' => $approvedExternalSource, 'automatorpassthrough' => $automatorPassthrough, #} This passes through any custom log titles or whatever into the Internal automator recipe. 'extraMeta' => $confirmedExtraMeta #} This is the "extraMeta" passed (as saved) )); $data['id'] = $id; // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable $this->events_manager->transaction()->updated( $data ); // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable } // Successfully updated - Return id return $id; } else { $msg = __('DB Update Failed','zero-bs-crm'); $zbs->DAL->addError(302,$this->objectType,$msg,$dataArr); // FAILED update return false; } } else { #} No ID - must be an INSERT if ($wpdb->insert( $ZBSCRM_t['transactions'], $dataArr, $typeArr ) > 0){ #} Successfully inserted, lets return new ID $newID = $wpdb->insert_id; // Line Items ==== // line item work if (isset($data['lineitems']) && is_array($data['lineitems'])){ // if array passed, update, even if removing if (count($data['lineitems']) > 0){ // passed, for now this is BRUTAL and just clears old ones + readds // once live, discuss how to refactor to be less brutal. // delete all lineitems $this->DAL()->lineitems->deleteLineItemsForObject(array('objID'=>$newID,'objType'=>ZBS_TYPE_TRANSACTION)); // addupdate each foreach ($data['lineitems'] as $lineitem) { // slight rejig of passed so works cleanly with data array style $lineItemID = false; if (isset($lineitem['ID'])) $lineItemID = $lineitem['ID']; $this->DAL()->lineitems->addUpdateLineitem(array( 'id'=>$lineItemID, 'linkedObjType' => ZBS_TYPE_TRANSACTION, 'linkedObjID' => $newID, 'data'=>$lineitem )); } } else { // delete all lineitems $this->DAL()->lineitems->deleteLineItemsForObject(array('objID'=>$newID,'objType'=>ZBS_TYPE_TRANSACTION)); } } // / Line Items ==== // OBJ LINKS - to contacts/companies $this->addUpdateObjectLinks($newID,$data['contacts'],ZBS_TYPE_CONTACT); $this->addUpdateObjectLinks($newID,$data['companies'],ZBS_TYPE_COMPANY); // IA also gets 'againstid' historically, but we'll pass as 'against id's' $againstIDs = array('contacts'=>$data['contacts'],'companies'=>$data['companies']); // OBJ Links - to invoices $this->addUpdateObjectLinks($newID,array($data['invoice_id']),ZBS_TYPE_INVOICE); // if not-empty inv id, check if needs to be mark paid! if (!$do_not_mark_invoices && !empty($data['invoice_id']) && $data['invoice_id'] > 0){ //function to check ammount due and mark invoice as paid if amount due <= 0. zeroBSCRM_check_amount_due_mark_paid($data['invoice_id']); } // tags if (isset($data['tags']) && is_array($data['tags'])) { $this->addUpdateTransactionTags( array( 'id' => $newID, 'tag_input' => $data['tags'], 'mode' => $data['tag_mode'] ) ); } // externalSources $approvedExternalSource = $this->DAL()->addUpdateExternalSources( array( 'obj_id' => $newID, 'obj_type_id' => ZBS_TYPE_TRANSACTION, 'external_sources' => isset($data['externalSources']) ? $data['externalSources'] : array(), ) ); // for IA below // Custom fields? #} Cycle through + add/update if set if (is_array($customFields)) foreach ($customFields as $cK => $cF){ // any? if (isset($data[$cK])){ // add update $cfID = $this->DAL()->addUpdateCustomField(array( 'data' => array( 'objtype' => ZBS_TYPE_TRANSACTION, 'objid' => $newID, 'objkey' => $cK, 'objval' => $data[$cK] ))); } } // / Custom Fields #} Any extra meta keyval pairs? // BRUTALLY updates (no checking) $confirmedExtraMeta = false; if (isset($extraMeta) && is_array($extraMeta)) { $confirmedExtraMeta = array(); foreach ($extraMeta as $k => $v){ #} This won't fix stupid keys, just catch basic fails... $cleanKey = strtolower(str_replace(' ','_',$k)); #} Brutal update //update_post_meta($postID, 'zbs_customer_extra_'.$cleanKey, $v); $this->DAL()->updateMeta(ZBS_TYPE_TRANSACTION,$newID,'extra_'.$cleanKey,$v); #} Add it to this, which passes to IA $confirmedExtraMeta[$cleanKey] = $v; } } #} INTERNAL AUTOMATOR #} & #} FALLBACKS // NEW CONTACT if (!$silentInsert){ #} Add to automator zeroBSCRM_FireInternalAutomator('transaction.new',array( 'id'=>$newID, 'data'=>$data, 'againstids'=>$againstIDs, 'extsource'=>$approvedExternalSource, 'automatorpassthrough'=>$automatorPassthrough, #} This passes through any custom log titles or whatever into the Internal automator recipe. 'extraMeta'=>$confirmedExtraMeta #} This is the "extraMeta" passed (as saved) )); $data['id'] = $newID; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable $this->events_manager->transaction()->created( $data ); // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable } return $newID; } else { $msg = __('DB Insert Failed','zero-bs-crm'); $zbs->DAL->addError(303,$this->objectType,$msg,$dataArr); #} Failed to Insert return false; } } return false; } /** * adds or updates a transaction's tags * ... this is really just a wrapper for addUpdateObjectTags * * @param array $args Associative array of arguments * id (if update), owner, data (array of field data) * * @return int line ID */ public function addUpdateTransactionTags($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, // generic pass-through (array of tag strings or tag IDs): 'tag_input' => -1, // or either specific: 'tagIDs' => -1, 'tags' => -1, 'mode' => 'append' ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ // check id $id = (int)$id; if (empty($id) || $id <= 0) return false; #} ========= / CHECK FIELDS =========== return $this->DAL()->addUpdateObjectTags( array( 'objtype' => ZBS_TYPE_TRANSACTION, 'objid' => $id, 'tag_input' => $tag_input, 'tags' => $tags, 'tagIDs' => $tagIDs, 'mode' => $mode ) ); } /** * updates status for a transaction (no blanks allowed) * * @param int id transaction ID * @param string transaction Status * * @return bool */ public function setTransactionStatus($id=-1,$status=-1){ global $zbs; $id = (int)$id; if ($id > 0 && !empty($status) && $status !== -1){ return $this->addUpdateTransaction(array( 'id'=>$id, 'limitedFields'=>array( array('key'=>'zbst_status','val' => $status,'type' => '%s') ))); } return false; } /** * deletes a transaction object * * @param array $args Associative array of arguments * id * * @return int success; */ public function deleteTransaction($args=array()){ global $ZBSCRM_t,$wpdb,$zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'saveOrphans' => false ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} Check ID & Delete :) $id = (int)$id; if (!empty($id) && $id > 0) { // delete orphans? if ($saveOrphans === false){ // delete any tag links $this->DAL()->deleteTagObjLinks(array( 'objtype' => ZBS_TYPE_TRANSACTION, 'objid' => $id, )); // delete any external source information $this->DAL()->delete_external_sources( array( 'obj_type' => ZBS_TYPE_TRANSACTION, 'obj_id' => $id, 'obj_source' => 'all', )); } $del = zeroBSCRM_db2_deleteGeneric($id,'transactions'); #} Add to automator zeroBSCRM_FireInternalAutomator('transaction.delete',array( 'id'=>$id, 'saveOrphans'=>$saveOrphans )); $this->events_manager->transaction()->deleted( $id ); return $del; } return false; } /** * tidy's the object from wp db into clean array * * @param array $obj (DB obj) * * @return array transaction (clean obj) */ private function tidy_transaction($obj=false,$withCustomFields=false){ $res = false; if (isset($obj->ID)){ $res = array(); $res['id'] = $obj->ID; /* `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, */ $res['owner'] = $obj->zbs_owner; $res['status'] = $this->stripSlashes($obj->zbst_status); $res['type'] = $this->stripSlashes($obj->zbst_type); // status categorisation (basically did it succeed?) // this is dictated by Transaction Status settings: /wp-admin/admin.php?page=zerobscrm-plugin-settings&tab=transactions $res['status_bool'] = ( 'all' === $this->getTransactionStatusesToInclude() || in_array( $res['status'], $this->getTransactionStatusesToInclude() ) ? 1 : -1 ); // type further categorised here, because JS etc. needs it in non-lingual $res['type_accounting'] = $this->transactionAccountingType($res['type']); $res['ref'] = $this->stripSlashes($obj->zbst_ref); $res['origin'] = $this->stripSlashes($obj->zbst_origin); $res['parent'] = (int)$obj->zbst_parent; $res['hash'] = $this->stripSlashes($obj->zbst_hash); $res['title'] = is_null($obj->zbst_title)?'':$this->stripSlashes($obj->zbst_title); $res['desc'] = $this->stripSlashes($obj->zbst_desc); $res['date'] = (int)$obj->zbst_date; // well this naming convention makes this confusing... lol: // $res['date_date'] = (isset($obj->zbst_date) && $obj->zbst_date > 0) ? zeroBSCRM_locale_utsToDatetime($obj->zbst_date) : false; $res['customer_ip'] = $this->stripSlashes($obj->zbst_customer_ip); $res['currency'] = $this->stripSlashes($obj->zbst_currency); $res['net'] = $this->stripSlashes($obj->zbst_net); $res['fee'] = $this->stripSlashes($obj->zbst_fee); $res['discount'] = $this->stripSlashes($obj->zbst_discount); $res['shipping'] = $this->stripSlashes($obj->zbst_shipping); $res['shipping_taxes'] = $this->stripSlashes($obj->zbst_shipping_taxes); $res['shipping_tax'] = $this->stripSlashes($obj->zbst_shipping_tax); $res['taxes'] = $this->stripSlashes($obj->zbst_taxes); $res['tax'] = $this->stripSlashes($obj->zbst_tax); $res['total'] = $this->stripSlashes($obj->zbst_total); $res['date_paid'] = is_null( $obj->zbst_date_paid ) ? null : (int)$obj->zbst_date_paid; $res['date_paid_date'] = (isset($obj->zbst_date_paid) && $obj->zbst_date_paid > 0) ? zeroBSCRM_locale_utsToDatetime($obj->zbst_date_paid) : false; $res['date_completed'] = is_null( $obj->zbst_date_completed ) ? null : (int)$obj->zbst_date_completed; $res['date_completed_date'] = (isset($obj->zbst_date_completed) && $obj->zbst_date_completed > 0) ? zeroBSCRM_locale_utsToDatetime($obj->zbst_date_completed) : false; $res['created'] = (int)$obj->zbst_created; $res['created_date'] = (isset($obj->zbst_created) && $obj->zbst_created > 0) ? zeroBSCRM_date_i18n(-1,$obj->zbst_created,false,true) : false; $res['lastupdated'] = (int)$obj->zbst_lastupdated; $res['lastupdated_date'] = (isset($obj->zbst_lastupdated) && $obj->zbst_lastupdated > 0) ? zeroBSCRM_locale_utsToDatetime($obj->zbst_lastupdated) : false; // custom fields - tidy any that are present: if ($withCustomFields) $res = $this->tidyAddCustomFields(ZBS_TYPE_TRANSACTION,$obj,$res,false); } return $res; } /** * Tidies a row from a database result containing the columns external_source_uids and external_source_sources. * The result is a formatted HTML string. * * @param object $row (DB row containing the columns external_source_uids and external_source_sources) * * @return string Formatted HTML string for the external sources. */ private function tidy_external_sources( $row ) { if ($row->external_source_uids == null && $row->external_source_sources == null) { return ""; } $external_source_uids = explode("\n", $row->external_source_uids); $external_source_sources = explode("\n", $row->external_source_sources); $external_source_strings = array_map( function($source, $uid) { $source_title = zeroBS_getExternalSourceTitle( $source, $uid ); // Formats the default zeroBS_getExternalSourceTitle string to look better in the table. $source_title_explode = explode( "<br />", $source_title, 2 ); if ( count($source_title_explode) === 2 ) { // Removes the trailing ':' from the source. E.g. 'WooCommerce:' becomes 'WooCommerce'. $source_title_source = rtrim($source_title_explode[0], ":"); return "{$source_title_explode[1]} ({$source_title_source})"; } else { return $source_title; } }, $external_source_sources, $external_source_uids ); return implode( '<br />', $external_source_strings ); } /** * Takes a transaction status (e.g. Sale or Credit Note), and returns debit/credit :) * wrapper that should be used throughout for inferring accounting direction for a transaction * * @param int objtype * @param int objid * @param string key * * @return array transaction meta result */ public function transactionAccountingType( $transaction_type='Sale' ){ if ( !empty( $transaction_type ) ){ if ( in_array( $transaction_type, array( __( 'Refund', 'zero-bs-crm' ), __( 'Credit Note', 'zero-bs-crm' ) ) ) ){ return 'credit'; } } return 'debit'; } /** * Wrapper, use $this->getTransactionMeta($contactID,$key) for easy retrieval of singular transaction * Simplifies $this->getMeta * * @param int objtype * @param int objid * @param string key * * @return array transaction meta result */ public function getTransactionMeta($id=-1,$key='',$default=false){ global $zbs; if (!empty($key)){ return $this->DAL()->getMeta(array( 'objtype' => ZBS_TYPE_TRANSACTION, 'objid' => $id, 'key' => $key, 'fullDetails' => false, 'default' => $default, 'ignoreowner' => true // for now !! )); } return $default; } /** * Returns a Transaction's tag array * * @param int id Transaction ID * * @return mixed */ public function getTransactionTags($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getTagsForObjID(array('objtypeid'=>ZBS_TYPE_TRANSACTION,'objid'=>$id)); } return false; } /** * Returns a reference against a transaction * * @param int id transaction ID * * @return string transaction ref */ public function get_transaction_ref( $transaction_id = -1 ){ global $zbs; return $this->DAL()->getFieldByID( array( 'id' => $transaction_id, 'objtype' => ZBS_TYPE_TRANSACTION, 'colname' => 'zbst_ref', 'ignoreowner' => true )); } /** * Returns an ownerid against a transaction * * @param int id transaction ID * * @return int transaction owner id */ public function getTransactionOwner($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_TRANSACTION, 'colname' => 'zbs_owner', 'ignoreowner'=>true)); } return false; } /** * Returns an array of contacts associtaed with a transaction * * @param int id transaction ID * * @return array contacts assocatied with transaction */ public function get_transaction_contacts( $transaction_id ){ return $this->DAL()->contacts->getContacts(array( 'hasObjTypeLinkedTo'=>ZBS_TYPE_TRANSACTION, 'hasObjIDLinkedTo'=>$transaction_id )); } /** * Returns an invoice associtaed with a transaction * * @param int id transaction ID * * @return array $invoice */ public function get_transaction_invoice_id( $transaction_id ){ return $this->DAL()->getFirstIDLinkedToObj(array( 'objtypefrom' => ZBS_TYPE_TRANSACTION, 'objtypeto' => ZBS_TYPE_INVOICE, 'objfromid' => $transaction_id, )); } /** * Returns an status against a transaction * * @param int id transaction ID * * @return str transaction status string */ public function getTransactionStatus($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_TRANSACTION, 'colname' => 'zbst_status', 'ignoreowner'=>true)); } return false; } /** * returns the transaction statuses to include in "total value" as per the setting on * admin.php?page=zerobscrm-plugin-settings&tab=transactions * * @return array */ function getTransactionStatusesToInclude(){ // load (accept from cache) $setting = $this->DAL()->setting( 'transinclude_status', 'all', true ); if (is_string($setting) && strpos($setting, ',') > 0){ return explode(',', $setting); } elseif (is_array($setting)){ return $setting; } return 'all'; } /** * returns an SQL query addition which will allow filtering of transactions * that should be included in "total value" fields * admin.php?page=zerobscrm-plugin-settings&tab=transactions * * @param str $table_alias_sql - if using a table alias pass that here, e.g. `transactions.` * @return array */ function getTransactionStatusesToIncludeQuery( $table_alias_sql = '' ){ // first we get the setting $transaction_statuses = $this->getTransactionStatusesToInclude(); // next we build the SQL // note that (in a legacy way) getTransactionStatusesToInclude() returns a string 'all' // .. if all transactions are selected // .. in that case there's no SQL to return as all statuses count. $query_addition = ''; if ( is_array( $transaction_statuses ) && count( $transaction_statuses ) > 0 ){ // create escaped csv $transaction_statuses_str = $this->build_csv( $transaction_statuses ); // build return sql $query_addition = ' AND ' . $table_alias_sql . 'zbst_status IN ('.$transaction_statuses_str.')'; } return $query_addition; } /** * remove any non-db fields from the object * basically takes array like array('owner'=>1,'fname'=>'x','fullname'=>'x') * and returns array like array('owner'=>1,'fname'=>'x') * This does so based on the objectModel! * * @param array $obj (clean obj) * * @return array (db ready arr) */ private function db_ready_transaction($obj=false){ // use the generic? (override here if necessary) return $this->db_ready_obj($obj); } /** * Takes full object and makes a "list view" boiled down version * Used to generate listview objs * * @param array $obj (clean obj) * * @return array (listview ready obj) */ public function listViewObj($transaction=false,$columnsRequired=array()){ if (is_array($transaction) && isset($transaction['id'])){ $resArr = $transaction; // a lot of this is legacy <DAL3 stuff just mapped. def could do with an improvement for efficacy's sake. $resArr['total'] = zeroBSCRM_formatCurrency($resArr['total']); //$resArr['orderid'] = strlen($transaction['orderid']) > 7 ? substr($transaction['orderid'],0,7)."..." : $transaction['orderid']; // order id now = ref (use proper field) //$resArr['id'] = $transaction['id']; $resArr['status'] = ucfirst($transaction['status']); // This wasn't working: $d = new DateTime($transaction['meta']['date']); // ... so I added the correct field (post_date) to getTransactions and piped in here //$d = new DateTime($transaction['date']); //$formatted_date = $d->format(zeroBSCRM_getDateFormat()); // USE proper field $resArr['added'] = $formatted_date; #} Convert $contact arr into list-view-digestable 'customer'// & unset contact for leaner data transfer $resArr['customer'] = zeroBSCRM_getSimplyFormattedContact($transaction['contact'],(in_array('assignedobj', $columnsRequired))); #} Convert $contact arr into list-view-digestable 'customer'// & unset contact for leaner data transfer $resArr['company'] = zeroBSCRM_getSimplyFormattedCompany($transaction['company'],(in_array('assignedobj', $columnsRequired))); #} Tags //if (in_array('tagged', $columnsRequired)){ // $resArr['tags'] = $transaction['tags']; //} return $resArr; } return false; } // =========== / TRANSACTION ======================================================= // =============================================================================== } // / class
projects/plugins/crm/includes/ZeroBSCRM.List.Columns.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V2.2 * * Copyright 2017 ZeroBSCRM.com * * Date: 30/07/2017 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ #{ Wh NOTE: this should all be in 1 global, messy to ahve them all separate! } /* ====================================================== Hard Coded Columns for each list view (UI2.0) (Defaults which can be overriden by custom views) ====================================================== */ /* // LABEL, column ??, grouping (in column manager) array('LABEL','zbsDefault_column_customerid','basefield') */ /* ====================================================================================================== ======================== Customers ===================================================================================================== */ global $zeroBSCRM_columns_customer; $zeroBSCRM_columns_customer = array(); $zeroBSCRM_columns_customer['default'] = array( 'id' => array('ID',false,'basefield'), 'nameavatar' => array(__('Name and Avatar',"zero-bs-crm")), //'email' => array('Email','zbsDefault_column_customeremail'), 'status' => array(__('Status',"zero-bs-crm"),false,'basefield','editinline'=>1), 'totalvalue' => array(__('Total Value',"zero-bs-crm")), 'added' => array(__('Added',"zero-bs-crm"),false,'basefield') ); $zeroBSCRM_columns_customer['all'] = array( 'id' => array('ID',false,'basefield'), 'name' => array(__('Name',"zero-bs-crm"),false,'basefield'), 'nameavatar' => array(__('Name and Avatar',"zero-bs-crm")), 'email' => array(__('Email',"zero-bs-crm"),false,'basefield'), 'status' => array(__('Status',"zero-bs-crm"),false,'basefield','editinline'=>1), 'hasquote' => array(__('Has Quote',"zero-bs-crm")), 'hasinvoice' => array(__('Has Invoice',"zero-bs-crm")), 'hastransaction' => array(__('Has Transaction',"zero-bs-crm")), 'quotecount' => array(__('Quote Count',"zero-bs-crm")), 'invoicecount' => array(__('Invoice Count',"zero-bs-crm")), 'transactioncount' => array(__('Transaction Count',"zero-bs-crm")), 'quotetotal' => array(__('Quotes Total',"zero-bs-crm")), 'invoicetotal' => array(__('Invoices Total',"zero-bs-crm")), 'transactiontotal' => array(__('Transactions Total',"zero-bs-crm")), 'totalvalue' => array(__('Total Value',"zero-bs-crm")), 'added' => array(__('Added',"zero-bs-crm"),false,'basefield'), 'lastupdated' => array(__('Last Updated',"zero-bs-crm"),false,'basefield'), 'assigned' => array(__('Assigned To',"zero-bs-crm"),false,'basefield','editinline'=>1), 'latestlog' => array(__('Latest Log',"zero-bs-crm")), 'tagged' => array(__('Tagged',"zero-bs-crm")), 'editlink' => array(__('View',"zero-bs-crm")), 'editdirectlink' => array(__('Edit',"zero-bs-crm")), 'phonelink' => array(__('Phone Link',"zero-bs-crm")), 'lastcontacted' => array(__('Last Contacted',"zero-bs-crm")), 'company' => array(__('Company','zero-bs-crm')), ); /** * Corrects label for 'Company' (could be Organisation) after the settings have loaded. * Clunky workaround for now */ add_action( 'after_zerobscrm_settings_preinit', 'jpcrm_list_columns_correct_labels', 10); function jpcrm_list_columns_correct_labels(){ global $zeroBSCRM_columns_customer; $zeroBSCRM_columns_customer['all']['company'] = array(jpcrm_label_company()); } /* ====================================================================================================== ======================== / Customers ===================================================================================================== */ /* ====================================================================================================== ======================== Companies ===================================================================================================== */ global $zeroBSCRM_columns_company; $zeroBSCRM_columns_company = array(); $zeroBSCRM_columns_company['default'] = array( 'id' => array('ID',false,'basefield'), 'name' => array(__('Name',"zero-bs-crm"),false,'basefield'), 'status' => array(__('Status',"zero-bs-crm"),false,'basefield'), 'contacts' => array(__('Contacts',"zero-bs-crm")), 'added' => array(__('Added',"zero-bs-crm"),false,'basefield'), 'viewlink' => array(__('View',"zero-bs-crm")) ); $zeroBSCRM_columns_company['all'] = array( 'id' => array('ID',false,'basefield'), 'name' => array(__('Name',"zero-bs-crm"),false,'basefield'), 'email' => array(__('Email',"zero-bs-crm"),false,'basefield'), 'status' => array(__('Status',"zero-bs-crm"),false,'basefield'), 'hasinvoice' => array(__('Has Invoice',"zero-bs-crm")), 'hastransaction' => array(__('Has Transaction',"zero-bs-crm")), 'invoicecount' => array(__('Invoice Count',"zero-bs-crm")), 'transactioncount' => array(__('Transaction Count',"zero-bs-crm")), 'invoicetotal' => array(__('Invoices Total',"zero-bs-crm")), 'transactiontotal' => array(__('Transactions Total',"zero-bs-crm")), // When Company<->Quotes: //'hasquote' => array(__('Has Quote',"zero-bs-crm")), //'quotecount' => array(__('Quote Count',"zero-bs-crm")), //'quotetotal' => array(__('Quotes Total',"zero-bs-crm")), 'totalvalue' => array(__('Total Value',"zero-bs-crm")), 'contacts' => array(__('Contacts',"zero-bs-crm")), 'added' => array(__('Added',"zero-bs-crm"),false,'basefield'), 'lastupdated' => array(__('Last Updated',"zero-bs-crm"),false,'basefield'), 'viewlink' => array(__('View',"zero-bs-crm")), 'editlink' => array(__('Edit',"zero-bs-crm")), 'assigned' => array(__('Assigned To',"zero-bs-crm"),false,'basefield'), 'tagged' => array(__(__('Tagged',"zero-bs-crm"),"zero-bs-crm")), 'phonelink' => array(__('Phone Link',"zero-bs-crm")), // Should this be in company? (removed 04/9/18, don't think wired up) ''latestlog' => array(__('Latest Log',"zero-bs-crm")), // Should this be in company? (removed 04/9/18, don't think wired up) 'lastcontacted' => array(__('Last Contacted',"zero-bs-crm")), ); /* ====================================================================================================== ======================== / Companies ===================================================================================================== */ /* ====================================================================================================== ======================== Quotes ===================================================================================================== */ global $zeroBSCRM_columns_quote; $zeroBSCRM_columns_quote = array(); $zeroBSCRM_columns_quote['default'] = array( 'id' => array('ID',false,'basefield'), 'title' => array(__('Quote Title','zero-bs-crm'),false,'basefield'), 'customer' => array( __( 'Contact', 'zero-bs-crm' ) ), // phpcs:ignore WordPress.Arrays.ArrayIndentation.ItemNotAligned -- impossible to fix without fixing everything else. 'status' => array(__('Status','zero-bs-crm'),false,'basefield'), 'value' => array(__('Quote Value',"zero-bs-crm"),false,'basefield'), 'editlink' => array(__('Edit',"zero-bs-crm")) ); $zeroBSCRM_columns_quote['all'] = array( 'id' => array('ID',false,'basefield'), 'title' => array(__('Quote Title','zero-bs-crm'),false,'basefield'), 'customer' => array( __( 'Contact', 'zero-bs-crm' ) ), // phpcs:ignore WordPress.Arrays.ArrayIndentation.ItemNotAligned -- impossible to fix without fixing everything else. 'status' => array(__('Status','zero-bs-crm'),false,'basefield'), 'value' => array(__('Quote Value',"zero-bs-crm"),false,'basefield'), 'editlink' => array(__('Edit',"zero-bs-crm")), // not user-configurable, so disabling for now //'assignedobj' => array(__('Assigned To',"zero-bs-crm"),false,'basefield'), ); /* ====================================================================================================== ======================== / Quotes ===================================================================================================== */ /* ====================================================================================================== ======================== Invoices ===================================================================================================== */ global $zeroBSCRM_columns_invoice; $zeroBSCRM_columns_invoice = array(); $zeroBSCRM_columns_invoice['default'] = array( 'id' => array('ID',false,'basefield'), 'ref' => array(__('Reference','zero-bs-crm'),false,'basefield'), 'customer' => array( __( 'Contact', 'zero-bs-crm' ) ), // phpcs:ignore WordPress.Arrays.ArrayIndentation.ItemNotAligned -- impossible to fix without fixing everything else. 'status' => array(__('Status','zero-bs-crm'),false,'basefield'), 'value' => array(__('Value',"zero-bs-crm"),false,'basefield'), 'date' => array(__('Date',"zero-bs-crm"),false,'basefield'), 'editlink' => array(__('Edit',"zero-bs-crm")) ); $zeroBSCRM_columns_invoice['all'] = array( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase,Generic.WhiteSpace.ScopeIndent.Incorrect 'id' => array('ID',false,'basefield'), 'ref' => array(__('Reference','zero-bs-crm'),false,'basefield'), 'customer' => array( __( 'Contact', 'zero-bs-crm' ) ), // phpcs:ignore WordPress.Arrays.ArrayIndentation.ItemNotAligned -- impossible to fix without fixing everything else. 'status' => array(__('Status','zero-bs-crm'),false,'basefield'), 'value' => array(__('Value',"zero-bs-crm"),false,'basefield'), 'date' => array(__('Date',"zero-bs-crm"),false,'basefield'), 'due' => array(__('Due date',"zero-bs-crm"),false,'basefield'), 'editlink' => array(__('Edit',"zero-bs-crm")), // not user-configurable, so disabling for now //'assignedobj' => array(__('Assigned To',"zero-bs-crm"),false,'basefield'), ); /* ====================================================================================================== ======================== / Invoices ===================================================================================================== */ /* ====================================================================================================== ======================== Transactions ===================================================================================================== */ global $zeroBSCRM_columns_transaction; $zeroBSCRM_columns_transaction = array(); $zeroBSCRM_columns_transaction['default'] = array( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase 'id' => array('ID','zbsDefault_column_customerid','basefield'), 'customer' => array( __( 'Contact', 'zero-bs-crm' ) ), // phpcs:ignore WordPress.Arrays.ArrayIndentation.ItemNotAligned -- impossible to fix without fixing everything else. 'status' => array(__('Status',"zero-bs-crm"),false,'basefield'), 'total' => array(__('Value',"zero-bs-crm"),false,'basefield'), 'item' => array(__('Item',"zero-bs-crm"),false,'basefield'), 'added' => array(__('Added',"zero-bs-crm"),false,'basefield'), 'editlink' => array(__('Edit Link',"zero-bs-crm")) ); $zeroBSCRM_columns_transaction['all'] = array( 'id' => array('ID','zbsDefault_column_customerid','basefield'), 'customer' => array( __( 'Contact', 'zero-bs-crm' ) ), // phpcs:ignore WordPress.Arrays.ArrayIndentation.ItemNotAligned -- impossible to fix without fixing everything else. 'customeremail' => array(__('Email',"zero-bs-crm")), 'tagged' => array(__(__('Tagged',"zero-bs-crm"),"zero-bs-crm")), 'status' => array(__('Status',"zero-bs-crm"),false,'basefield'), 'total' => array(__('Value',"zero-bs-crm"),false,'basefield'), 'item' => array(__('Item',"zero-bs-crm"),false,'basefield'), 'added' => array(__('Added',"zero-bs-crm"),false,'basefield'), 'editlink' => array(__('Edit Link',"zero-bs-crm")), 'external_source' => array(__('External Source',"zero-bs-crm")), // not user-configurable, so disabling for now //'assignedobj' => array(__('Assigned To',"zero-bs-crm"),false,'basefield'), ); /* ====================================================================================================== ======================== / Transactions ===================================================================================================== */ /* ====================================================================================================== ======================== Forms ===================================================================================================== */ global $zeroBSCRM_columns_form; $zeroBSCRM_columns_form = array(); $zeroBSCRM_columns_form['default'] = array( 'id' => array('ID',false,'basefield'), 'title' => array(__('Title','zero-bs-crm'),false,'basefield'), 'style' => array(__('Style',"zero-bs-crm"),false,'basefield'), 'views' => array(__('Views',"zero-bs-crm")), 'conversions' => array(__('Conversions',"zero-bs-crm")), 'added' => array(__('Added',"zero-bs-crm"),false,'basefield'), 'editlink' => array(__('Edit',"zero-bs-crm")) ); $zeroBSCRM_columns_form['all'] = array( 'id' => array('ID',false,'basefield'), 'title' => array(__('Title','zero-bs-crm'),false,'basefield'), 'style' => array(__('Style',"zero-bs-crm"),false,'basefield'), 'views' => array(__('Views',"zero-bs-crm")), 'conversions' => array(__('Conversions',"zero-bs-crm")), 'added' => array(__('Added',"zero-bs-crm"),false,'basefield'), 'editlink' => array(__('Edit',"zero-bs-crm")) ); /* ====================================================================================================== ======================== / Forms ===================================================================================================== */ /* ====================================================================================================== ======================== Segments ===================================================================================================== */ global $zeroBSCRM_columns_segment; $zeroBSCRM_columns_segment = array(); $zeroBSCRM_columns_segment['default'] = array( 'id' => array('ID',false,'basefield'), 'name' => array(__('Name','zero-bs-crm'),false,'basefield'), 'audiencecount' => array(__('Contact Count','zero-bs-crm')), 'action' => array(__('Action','zero-bs-crm')) ); $zeroBSCRM_columns_segment['all'] = array( 'id' => array('ID',false,'basefield'), 'name' => array(__('Name','zero-bs-crm'),false,'basefield'), 'audiencecount' => array(__('Contact Count','zero-bs-crm')), 'action' => array(__('Action','zero-bs-crm')), 'added' => array(__('Added','zero-bs-crm')) ); /* ====================================================================================================== ======================== / Segments ===================================================================================================== */ /* ====================================================================================================== ======================== Quote Templates ===================================================================================================== */ global $zeroBSCRM_columns_quotetemplate; $zeroBSCRM_columns_quotetemplate = array(); $zeroBSCRM_columns_quotetemplate['default'] = array( 'id' => array('ID',false,'basefield'), 'title' => array(__('Title','zero-bs-crm'),false,'basefield'), 'action' => array(__('Action','zero-bs-crm')) ); $zeroBSCRM_columns_quotetemplate['all'] = array( 'id' => array('ID',false,'basefield'), 'title' => array(__('Title','zero-bs-crm'),false,'basefield'), 'action' => array(__('Action','zero-bs-crm')) ); /* ====================================================================================================== ======================== / Quote Templates ===================================================================================================== */ /* ====================================================================================================== ======================== Tasks ===================================================================================================== */ global $zeroBSCRM_columns_event; $zeroBSCRM_columns_event = array(); $zeroBSCRM_columns_event['default'] = array( 'id' => array('ID',false,'basefield'), 'title' => array( __('Name','zero-bs-crm'), false, 'basefield' ), 'start' => array( __('Starting', 'zero-bs-crm' ) ), 'end' => array( __('Finishing', 'zero-bs-crm' ) ), 'status' => array( __('Status', 'zero-bs-crm' ) ), 'assigned' => array(__('Assigned To',"zero-bs-crm"), false, 'basefield' ), 'action' => array( __('Action', 'zero-bs-crm') ) ); $zeroBSCRM_columns_event['all'] = array( 'id' => array('ID',false,'basefield'), 'title' => array( __('Name','zero-bs-crm'), false, 'basefield' ), 'desc' => array( __('Description', 'zero-bs-crm' ) ), 'start' => array( __('Starting', 'zero-bs-crm' ) ), 'end' => array( __('Finishing', 'zero-bs-crm' ) ), 'status' => array( __('Status', 'zero-bs-crm' ) ), 'remind' => array( __('Reminder', 'zero-bs-crm' ) ), 'showcal' => array( __('Show on Cal', 'zero-bs-crm' ) ), //'showportal' => array( __('Show on Portal', 'zero-bs-crm' ) ), 'contact' => array( __('Contact', 'zero-bs-crm' ) ), 'company' => array( __('Company', 'zero-bs-crm' ) ), 'assigned' => array(__('Assigned To',"zero-bs-crm"), false, 'basefield' ), 'action' => array( __('Action', 'zero-bs-crm') ) ); /* ====================================================================================================== ======================== / Tasks ===================================================================================================== */ // phpcs:disable Generic.WhiteSpace.ScopeIndent.Incorrect, Generic.WhiteSpace.ScopeIndent.IncorrectExact /** * Unpacks listview settings */ function zeroBSCRM_unpackListViewSettings() { // ALL FIELD TYPES global $zeroBSCRM_columns_customer, $zbsCustomerFields; global $zeroBSCRM_columns_company, $zbsCompanyFields; global $zeroBSCRM_columns_quote, $zbsCustomerQuoteFields; global $zeroBSCRM_columns_invoice, $zbsCustomerInvoiceFields; global $zeroBSCRM_columns_transaction, $zbsTransactionFields; global $zeroBSCRM_columns_form, $zbsFormFields; $useSecondAddress = zeroBSCRM_getSetting('secondaddress'); $second_address_label = zeroBSCRM_getSetting( 'secondaddresslabel' ); if ( empty( $second_address_label ) ) { $second_address_label = __( 'Second Address', 'zero-bs-crm' ); } // Cycle through each + add $mappings = array( 'zeroBSCRM_columns_customer' => 'zbsCustomerFields', 'zeroBSCRM_columns_company' => 'zbsCompanyFields', 'zeroBSCRM_columns_quote' => 'zbsCustomerQuoteFields', // not sure why naming convention lost here 'zeroBSCRM_columns_invoice' => 'zbsCustomerInvoiceFields', // not sure why naming convention lost here 'zeroBSCRM_columns_transaction' => 'zbsTransactionFields', 'zeroBSCRM_columns_form' => 'zbsFormFields', ); foreach ($mappings as $columnsObjName => $fieldsObjName){ // add all normal fields to columns (DAL2) from 2.95 if (is_array(${$fieldsObjName}) && count(${$fieldsObjName}) > 0){ foreach (${$fieldsObjName} as $fKey => $fDetail){ if (!isset(${$columnsObjName}['all'][$fKey])){ // some need hiding (just for api/behind scenes:) $hideCol = false; if (is_array($fDetail) && isset($fDetail['nocolumn']) && $fDetail['nocolumn']) $hideCol = true; if (!$hideCol){ $skip = false; // skip addr 2 if off // add it $cfTitle = $fKey; if (is_array($fDetail) && isset($fDetail[1])) $cfTitle = $fDetail[1]; // secaddr get's dealt with: if ( str_starts_with( $fKey, 'secaddr_' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $cfTitle .= ' (' . esc_html( $second_address_label ) . ')'; if ($useSecondAddress !== 1) $skip = true; } if (!$skip) ${$columnsObjName}['all'][$fKey] = array($cfTitle,false,'basefield'); // note adding as basefield :) } } } } } // Auto-add 'edit link' to quotes invs (somehow it wasn't always adding) $customviews2 = zeroBSCRM_getSetting('customviews2'); $cv2Changed = false; if (isset($customviews2['quote']) && !array_key_exists('editlink', $customviews2['quote'])){ // add it $customviews2['quote']['editlink'] = array(__('Edit',"zero-bs-crm")); $cv2Changed = true; } if (isset($customviews2['invoice']) && !array_key_exists('editlink', $customviews2['invoice'])){ // add it $customviews2['invoice']['editlink'] = array(__('Edit',"zero-bs-crm")); $cv2Changed = true; } if ($cv2Changed && is_array($customviews2)){ // Save setting global $zbs; return $zbs->settings->update('customviews2',$customviews2); } } // phpcs:enable Generic.WhiteSpace.ScopeIndent.Incorrect, Generic.WhiteSpace.ScopeIndent.IncorrectExact
projects/plugins/crm/includes/jpcrm-usage-tracking.php
<?php /** * * Usage Tracking for CRM insights * is only included if the setting * is enabled * * @since 4.3.0 * */ class jpcrm_usage_tracking{ protected $setting_key = 'teammember_usage'; public function __construct() { $this->init_hooks(); } public function init_hooks(){ #} Usage tracking (pageviews) sent via AJAX add_action('admin_footer', array($this, 'tracking_footer')); add_action('wp_ajax_jpcrm_send_page_view', array($this, 'send_page_view')); } /** * AJAX function to send the pageview */ public function send_page_view(){ global $zbs; $res = array(); // check nonce check_ajax_referer( 'jpcrm_usage_tracking_nonce', 'security' ); // retrieve page_name $page_name = sanitize_text_field($_POST['page_name']); // pool data $data = array( 'action' => 'jpcrm_track_usage', 'event_name' => $page_name, 'event_type' => 'page_view', 'site_url' => home_url() ); // call $response = wp_remote_post( $zbs->urls['usage'], array( 'method' => 'POST', 'timeout' => 45, 'redirection' => 5, 'httpversion' => '1.0', 'blocking' => true, 'headers' => array(), 'body' => $data, 'cookies' => array() ) ); $res['pageview'] = 'sent'; // send summary snapshot based on a transient if(!get_transient('jpcrm_crm_snapshot')){ $this->send_snapshot(); $res['snapshot'] = 'sent'; set_transient( 'jpcrm_crm_snapshot', true, DAY_IN_SECONDS ); } wp_send_json($res); } /** * send summary snapshot */ public function send_snapshot(){ global $zbs, $wp_version; // build data $contacts_count = $zbs->DAL->contacts->getFullCount(); $contacts_woo_count = $zbs->DAL->contacts->getContacts( array( 'externalSource' => 'woo', 'count' => true )); $contacts_with_extsource = $zbs->DAL->contacts->getTotalExtSourceCount(); $companies_count = $zbs->DAL->companies->getFullCount(); $transactions_count = $zbs->DAL->transactions->getFullCount(); $quotes_count = $zbs->DAL->quotes->getFullCount(); $invoices_count = $zbs->DAL->invoices->getFullCount(); $forms_count = $zbs->DAL->forms->getFullCount(); $tasks_count = $zbs->DAL->events->getFullCount(); $crm_users = $this->get_teammates_count( true ); $extensions_count = zeroBSCRM_extensionsInstalledCount(); $modules_count = jpcrm_core_modules_installed_count(); $wp_version = $wp_version; $crm_version = $zbs->version; $dal_version = $zbs->dal_version; $php_version = PHP_VERSION; $mysql_version = zeroBSCRM_database_getVersion(); $data = array( 'action' => 'jpcrm_track_stats', 'site_url' => home_url(), 'contacts_count' => $contacts_count, 'contacts_woo_count' => $contacts_woo_count, 'contacts_with_extsource' => $contacts_with_extsource, 'companies_count' => $companies_count, 'transactions_count' => $transactions_count, 'quotes_count' => $quotes_count, 'invoices_count' => $invoices_count, 'forms_count' => $forms_count, 'events_count' => $tasks_count, 'users_count' => $crm_users, 'extensions_count' => $extensions_count, 'modules_count' => $modules_count, 'wp_version' => $wp_version, 'crm_version' => $crm_version, 'dal_version' => $dal_version, 'php_version' => $php_version, 'mysql_version' => $mysql_version, ); // call return wp_remote_post( $zbs->urls['usage'], array( 'method' => 'POST', 'timeout' => 45, 'redirection' => 5, 'httpversion' => '1.0', 'blocking' => true, 'headers' => array(), 'body' => $data, 'cookies' => array() ) ); } /** * Package admin page as string which can be passed to usage tracking API */ public function get_jpcrm_admin_page(){ // retrieve uri $uri = isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : ''; $uri = preg_replace( '|^.*/wp-admin/|i', '', $uri ); // if somehow failed, return if ( ! $uri ) { return ''; } // hard remove any unwanted get parameters here $uri = remove_query_arg( array( '_wpnonce' ), admin_url( $uri ) ); // get _GET Parameters $parameters = jpcrm_url_get_params( $uri ); // cycle through some key parameters and tokenise for anonymity / cleanliness if ( is_array( $parameters ) ) { $return_string = ''; // required: page if ( isset( $parameters['page'] ) && !empty ( $parameters['page'] ) ){ $return_string = $parameters['page']; } else { // missing $page, skip return ''; } // Overrides: // action: by default it's add, unless zbsid is set, then it's edit, make so: if ( isset( $parameters['action'] ) && !empty( $parameters['action'] ) ){ // if action is set and no zbsid is present, it's an add if ( $parameters['action'] == 'edit' && ( !isset( $parameters['zbsid'] ) || empty( $parameters['zbsid'] ) ) ){ $parameters['action'] = 'add'; } // note if there's an action present and zbsid, we can go ahead and remove zbsid from the return :) if ( isset( $parameters['zbsid'] ) ){ unset( $parameters['zbsid'] ); } } // generic out any non-helpful data $parameters_to_blank = array( 'zbsid', 'zbsprefillcust', 'zbsprefill', 'zbs_tag', 'quickfilters', 'sort', 'zbsowner', 'zbs_template_id' ); foreach ( $parameters_to_blank as $parameter_key ){ if ( isset( $parameters[ $parameter_key ] ) ){ // set generic value $parameters[ $parameter_key ] = 'present'; } } // finally rebuild into a useful string foreach ( $parameters as $parameter_key => $parameter_value){ // skip page as is always added above if ( $parameter_key == 'page' ){ continue; } if ( !empty( $return_string ) ){ $return_string .= '|'; } // here we check if $parameter_value might be an email // ... designed as future-proofing and to catch any potential leaks of user data to our system if ( zeroBSCRM_validateEmail( $parameter_value ) ) $parameter_value = '{email}'; // append return string $return_string .= $parameter_key . ':' . $parameter_value; } return $return_string; } // fallback: retrieve page via explode $split = explode("?page=",$uri); $page = $split[0]; if(count($split) == 2){ $page = $split[1]; } // returns everything after the ?page= part of the URL return $page; } /** * JS to track usage */ public function tracking_footer(){ global $zbs; if ( zeroBSCRM_isAdminPage() ){ // retrieve page info $page = $this->get_jpcrm_admin_page(); if ( !empty( $page ) ){ $this->track_specific_pageview( $page ); } } } /** * JS to track usage for a specific key * is used by `tracking_footer()` and can be used inline throughout * core to track extra view events */ public function track_specific_pageview( $page_key = '' ){ global $zbs; if ( zeroBSCRM_isAdminPage() ){ // Where usage tracking enabled, clock that this user is a CRM team member // noting that this never sends team-member data out of the install, only the count $this->track_crm_teammember_usage(); if ( !empty( $page_key ) ){ ?> <script> data = { action: 'jpcrm_send_page_view', page_name: '<?php echo esc_html( $page_key ); ?>', security: '<?php echo esc_html( wp_create_nonce('jpcrm_usage_tracking_nonce') ); ?>' }; jQuery.post(ajaxurl, data, function (response) { //nothing to see here. }); </script> <?php } } } /** * Adds user id to an option of "WP users who use the CRM" which is totalled for usage statistics * (No specific user usage data is ever sent) */ private function track_crm_teammember_usage(){ global $zbs; // retrieve existing array $existing_teammembers = $zbs->settings->get( $this->setting_key ); // catch first call if ( !is_array( $existing_teammembers ) ){ $existing_teammembers = array(); } $current_user_id = get_current_user_id(); // append if ( isset( $existing_teammembers[ $current_user_id ] ) ){ // increment $existing_teammembers[ $current_user_id ]['count']++; // update $existing_teammembers[ $current_user_id ]['last_seen'] = time(); } else { // add $existing_teammembers[ $current_user_id ] = array( 'count' => 1, 'last_seen' => time() ); } // update setting $zbs->settings->update( $this->setting_key, $existing_teammembers ); } /** * Retrieves a count of teammates who have accessed a crm page (optionally checking wp user status) * * @param $check_is_current_wp_user - bool; if true check that the user_id is a current wp user */ public function get_teammates_count( $check_is_current_wp_crm_user = false ){ global $zbs; // retrieve teammembers $seen_teammembers = $zbs->settings->get( $this->setting_key ); // catch first call if ( !is_array( $seen_teammembers ) ){ return 0; } // if validating current status, do that, else return count if ( $check_is_current_wp_crm_user ){ // filter user_ids who are current wp_users $current_wp_teammembers = array_filter( array_keys( $seen_teammembers ), 'get_userdata' ); // filter user_ids who do not have a CRM backend role (and are not admins) // e.g. CRM admins who are now Subscribers $current_wp_teammembers = array_filter( $current_wp_teammembers, 'zeroBSCRM_permsIsZBSUserOrAdmin' ); return count( $current_wp_teammembers ); } else { return count( $seen_teammembers ); } } }
projects/plugins/crm/includes/ZeroBSCRM.Migrations.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V1.1.18 * * Copyright 2020 Automattic * * Date: 30/08/16 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== MIGRATION FUNCS ====================================================== */ global $zeroBSCRM_migrations; $zeroBSCRM_migrations = array( '288', // build client portal page (moved to shortcodes) if using '2963', // 2.96.3 - installs page templates '29999', // Flush permalinks '411', // 4.11.0 - Ensure upload folders are secure '50', // 5.0 - Alter external sources table for existing users (added origin) '53', // 5.3 - Migrate all encrypted data to new encryption endpoints '54', // 5.4 - Support pinned logs, migrate all log meta stored in old dehydrated fashion '543', // 5.4.3 - Deletes unwanted .htaccess files '544', // 5.4.2 Forces re-install of default fonts '55', // 5.5 Deletes orphaned rows linked to invoices in the objlinks table '55a', // 5.5a Recompiles segments after wp_loaded '551', // 5.5.1 Deletes orphaned aka rows linked to contacts since deleted '560', // 5.6.0 Moves old folder structure (zbscrm-store) to new (jpcrm-storage) 'task_offset_fix', // removes task timezone offsets from database 'refresh_user_roles', // Refresh user roles 'regenerate_tag_slugs', // Regenerate tag slugs 'create_workflows_table', // Create "workflows" table. 'invoice_language_fixes', // Store invoice statuses and mappings consistently ); global $zeroBSCRM_migrations_requirements; $zeroBSCRM_migrations_requirements = array( '288' => array('isDAL2','postsettings'), '53' => array('isDAL3','postsettings'), '5402' => array('isDAL3','postsettings'), '55a' => array( 'wp_loaded' ), ); // mark's a migration complete function zeroBSCRM_migrations_markComplete($migrationKey=-1,$logObj=false){ global $zeroBSCRM_migrations; if (!empty($migrationKey) && in_array($migrationKey, $zeroBSCRM_migrations)) { $completedMigrations = zeroBSCRM_migrations_getCompleted(); $completedMigrations[] = $migrationKey; // we're using wp options because they're reliable OUTSIDE of the scope of our settings model // ... which has changed through versions // the separation here is key, at 2.88 WH discovered much re-running + pain due to this. // stick to a separate migration system (away from zbssettings) update_option('zbsmigrations',$completedMigrations, false); // log opt? update_option('zbsmigration'.$migrationKey,array('completed'=>time(),'meta'=>$logObj), false); } } // gets the list of completed migrations function zeroBSCRM_migrations_getCompleted(){ // we're using wp options because they're reliable OUTSIDE of the scope of our settings model // ... which has changed through versions // the separation here is key, at 2.88 WH discovered much re-running + pain due to this. // stick to a separate migration system (away from zbssettings) // BUT WAIT! hilariously, for those who already have finished migrations, this'll re-run them // ... so here we 'MIGRATE' the migrations :o ffs global $zbs; $migrations = $zbs->settings->get('migrations'); if (isset($migrations) && is_array($migrations) && count($migrations) > 0) { $existingMigrationsMigration = get_option( 'zbsmigrationsdal', -1); if ($existingMigrationsMigration == -1){ // copy over + // to stop this ever rerunning + confusing things, we set an option to say migrated the migrations, LOL update_option('zbsmigrations',$migrations, false); update_option('zbsmigrationsdal',2, false); } } // normal return return get_option( 'zbsmigrations', array() ); } // gets details on a migration function jpcrm_migrations_get_migration($migrationKey=''){ // we're using wp options because they're reliable OUTSIDE of the scope of our settings model // ... which has changed through versions // the separation here is key, at 2.88 WH discovered much re-running + pain due to this. // stick to a separate migration system (away from zbssettings) $finished = false; $migrations = zeroBSCRM_migrations_getCompleted(); if (in_array($migrationKey,$migrations)) $finished = true; return array($finished,get_option('zbsmigration'.$migrationKey,false)); } function zeroBSCRM_migrations_run( $settingsArr = false, $run_at = 'init' ){ global $zeroBSCRM_migrations,$zeroBSCRM_migrations_requirements; // catch migration block removal (can be run from system status): if (current_user_can('admin_zerobs_manage_options') && isset($_GET['resetmigrationblock']) && wp_verify_nonce( $_GET['_wpnonce'], 'resetmigrationblock' ) ){ // unblock migration blocks delete_option('zbsmigrationpreloadcatch'); delete_option('zbsmigrationblockerrors'); // flag $migrationBlocksRemoved = true; } #} Check if we've been stumped by blocking errs, and STOP migrating if so $blockingErrs = get_option( 'zbsmigrationblockerrors', false); if ($blockingErrs !== false && !empty($blockingErrs)) return false; #} load migrated list if not loaded $migratedAlreadyArr = zeroBSCRM_migrations_getCompleted(); #} Run count $migrationRunCount = 0; #} cycle through any migrations + fire if not fired. if (count($zeroBSCRM_migrations) > 0) foreach ($zeroBSCRM_migrations as $migration){ if (!in_array($migration,$migratedAlreadyArr) && function_exists('zeroBSCRM_migration_'.$migration)) { $run = true; // check reached state if ( isset( $zeroBSCRM_migrations_requirements[$migration] ) ){ // 'preload' requirement means this migration needs to run AFTER a reload AFTER the previous migration // ... so if preload here, we kill this loop, if prev migrations have run if ( in_array( 'preload', $zeroBSCRM_migrations_requirements[$migration]) && $migrationRunCount > 0 ){ // ... as a catch to stop infinite reloads, we check whether more than 3 of these have run in a row, and we stop that. $previousAttempts = get_option( 'zbsmigrationpreloadcatch', array()); if (!is_array($previousAttempts)) $previousAttempts = array(); if (!isset($previousAttempts[$migration])) $previousAttempts[$migration] = 1; if ($previousAttempts[$migration] < 5){ // update count $previousAttempts[$migration]++; update_option('zbsmigrationpreloadcatch', $previousAttempts, false); // stop running migrations, reload the page header("Refresh:0"); exit(); } else { // set a global which'll show up on systemstatus if this state occurs. update_option('zbsmigrationblockerrors', $migration, false); // expose an error that the world's about to rupture add_action('after-zerobscrm-admin-init','zeroBSCRM_adminNotices_majorMigrationError'); add_action( 'admin_notices', 'zeroBSCRM_adminNotices_majorMigrationError' ); } } // assume func foreach ($zeroBSCRM_migrations_requirements[$migration] as $check){ // skip 'preload', dealt with above // skip 'wp_loaded', dealt with in second run if ( $check !== 'preload' && $check !== 'wp_loaded' ){ $checkFuncName = 'zeroBSCRM_migrations_checks_'.$check; if (!call_user_func($checkFuncName)) $run = false; } } // wp_loaded if ( in_array( 'wp_loaded', $zeroBSCRM_migrations_requirements[$migration] ) ){ $run = false; if ( $run_at == 'wp_loaded' ){ $run = true; } } } // go if ($run) { // run migration call_user_func('zeroBSCRM_migration_'.$migration); // update count $migrationRunCount++; } } } } // Migration dependency check for DAL2 function zeroBSCRM_migrations_checks_isDAL2(){ global $zbs; return $zbs->isDAL2(); } // Migration dependency check for DAL3 function zeroBSCRM_migrations_checks_isDAL3(){ global $zbs; return $zbs->isDAL3(); } function zeroBSCRM_migrations_checks_postsettings(){ global $zbs; /* didn't work: if (isset($zbs->settings) && method_exists($zbs->settings,'get')){ $possiblyInstalled = $zbs->settings->get('settingsinstalled',true); if (isset($possiblyInstalled) && $possiblyInstalled > 0) return true; } */ // HARD DB settings check try { $potentialDBSetting = $zbs->DAL->getSetting(array('key' => 'settingsinstalled','fullDetails' => false)); if (isset($potentialDBSetting) && $potentialDBSetting > 0) { return true; } } catch (Exception $e){ } return false; } // general migration mechanism error function zeroBSCRM_adminNotices_majorMigrationError(){ //pop in a Notify Me Notification here instead....? if (get_current_user_id() > 0){ // already sent? $msgSent = get_transient('zbs-migration-general-errors'); if (!$msgSent){ zeroBSCRM_notifyme_insert_notification(get_current_user_id(), -999, -1, 'migration.blocked.errors','migration.blocked.errors'); set_transient( 'zbs-migration-general-errors', 20, 24 * 7 * HOUR_IN_SECONDS ); } } } /* ====================================================== / MIGRATION FUNCS ====================================================== */ /* ====================================================== MIGRATIONS ====================================================== */ /* * Migration 2.88 - build client portal page (moved to shortcodes) if using */ function zeroBSCRM_migration_288(){ global $zbs; zeroBSCRM_portal_checkCreatePage(); zeroBSCRM_migrations_markComplete('288',array('updated'=>'1')); } /* * Migration 2.4 - Refresh user roles * Previously this was a number of template related migrations * for v5 we combined these, though in time the need for this method of install should be done away with * Previously, migrations: 2.96.3, 2.96.4, 2.96.6, 2.97.4, 4.0.7, 4.0.8 */ function zeroBSCRM_migration_2963(){ global $zbs, $wpdb, $ZBSCRM_t; #} Check + create zeroBSCRM_checkTablesExist(); #} Make the DB emails... zeroBSCRM_populateEmailTemplateList(); // ===== Previously: Migration 2.96.3 - adds new template for 'client portal pw reset' #} default is admin email and CRM name //now all done via zeroBSCRM_mailDelivery_defaultFromname $from_name = zeroBSCRM_mailDelivery_defaultFromname(); /* This wasn't used in end, switched to default mail delivery opt $from_address = zeroBSCRM_mailDelivery_defaultEmail();; //default WordPress admin email ? $reply_to = ''; $cc = ''; */ $deliveryMethod = zeroBSCRM_getMailDeliveryDefault(); $ID = 6; $reply_to = ''; $cc = ''; $bcc = ''; #} The email stuff... $subject = __("Your Client Portal Password", 'zero-bs-crm'); $content = zeroBSCRM_mail_retrieveDefaultBodyTemplate('clientportalpwreset'); $active = 1; //1 = true.. if(zeroBSCRM_mailTemplate_exists($ID) == 0){ $content = zeroBSCRM_mailTemplate_processEmailHTML($content); //zeroBSCRM_insertEmailTemplate($ID,$from_name,$from_address,$reply_to,$cc,$bcc,$subject,$content,$active); zeroBSCRM_insertEmailTemplate($ID,$deliveryMethod,$bcc,$subject,$content,$active); } // ===== / Previously: Migration 2.96.3 // ===== Previously: last one hadn't got the html file, this ADDS file proper :) #} default is admin email and CRM name //now all done via zeroBSCRM_mailDelivery_defaultFromname $from_name = zeroBSCRM_mailDelivery_defaultFromname(); /* This wasn't used in end, switched to default mail delivery opt $from_address = zeroBSCRM_mailDelivery_defaultEmail();; //default WordPress admin email ? $reply_to = ''; $cc = ''; */ $deliveryMethod = zeroBSCRM_getMailDeliveryDefault(); $ID = 6; $reply_to = ''; $cc = ''; $bcc = ''; // BRUTAL DELETE old one $wpdb->delete( $ZBSCRM_t['system_mail_templates'], array( 'zbsmail_id' => $ID ) ); #} The email stuff... $subject = __("Your Client Portal Password", 'zero-bs-crm'); $content = zeroBSCRM_mail_retrieveDefaultBodyTemplate('clientportalpwreset'); $active = 1; //1 = true.. if(zeroBSCRM_mailTemplate_exists($ID) == 0){ $content = zeroBSCRM_mailTemplate_processEmailHTML($content); //zeroBSCRM_insertEmailTemplate($ID,$from_name,$from_address,$reply_to,$cc,$bcc,$subject,$content,$active); zeroBSCRM_insertEmailTemplate($ID,$deliveryMethod,$bcc,$subject,$content,$active); } // ===== / Previously: last one hadn't got the html file, this ADDS file proper :) // ===== Previously: adds template for 'invoice summary statement sent' #} default is admin email and CRM name //now all done via zeroBSCRM_mailDelivery_defaultFromname $from_name = zeroBSCRM_mailDelivery_defaultFromname(); /* This wasn't used in end, switched to default mail delivery opt $from_address = zeroBSCRM_mailDelivery_defaultEmail();; //default WordPress admin email ? $reply_to = ''; $cc = ''; */ $deliveryMethod = zeroBSCRM_getMailDeliveryDefault(); $ID = 7; $reply_to = ''; $cc = ''; $bcc = ''; #} The email stuff... $subject = __("Your Statement", 'zero-bs-crm'); $content = zeroBSCRM_mail_retrieveDefaultBodyTemplate('invoicestatementsent'); // BRUTAL DELETE old one $wpdb->delete( $ZBSCRM_t['system_mail_templates'], array( 'zbsmail_id' => $ID ) ); $active = 1; //1 = true.. if(zeroBSCRM_mailTemplate_exists($ID) == 0){ $content = zeroBSCRM_mailTemplate_processEmailHTML($content); //zeroBSCRM_insertEmailTemplate($ID,$from_name,$from_address,$reply_to,$cc,$bcc,$subject,$content,$active); zeroBSCRM_insertEmailTemplate($ID,$deliveryMethod,$bcc,$subject,$content,$active); } // ===== / Previously: adds template for 'invoice summary statement sent' // ===== Previously: 2.97.4 - fixes duplicated email templates (found on 2 installs so far) // 7 template emails up to here :) for ($i = 0; $i <= 7; $i++){ // count em $sql = $wpdb->prepare("SELECT ID FROM " . $ZBSCRM_t['system_mail_templates'] . " WHERE zbsmail_id = %d GROUP BY ID ORDER BY zbsmail_id DESC, zbsmail_lastupdated DESC", $i); $r = $wpdb->get_results($sql, ARRAY_A); // if too many, delete oldest (few?) if (is_array($r) && count($r) > 1){ $count = 0; // first stays, as the above selects in order by last updated foreach ($r as $x){ // if already got one, delete this (extra) if ($count > 0){ // BRUTAL DELETE old one $wpdb->delete( $ZBSCRM_t['system_mail_templates'], array( 'ID' => $x['ID'] ) ); } $count++; } } } // ===== / Previously: 2.97.4 - fixes duplicated email templates (found on 2 installs so far) // ===== Previously: 4.0.7 - corrects outdated task notification template // retrieve existing template - hardtyped $existingTemplate = $wpdb->get_var('SELECT zbsmail_body FROM '.$ZBSCRM_t['system_mail_templates'].' WHERE ID = 6'); // load new $newTemplate = zeroBSCRM_mail_retrieveDefaultBodyTemplate( 'tasknotification' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // back it up into a WP option if was different if ( $existingTemplate !== $newTemplate ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase update_option( 'jpcrm_tasknotificationtemplate', $existingTemplate, false ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } // overwrite $sql = "UPDATE " . $ZBSCRM_t['system_mail_templates'] . " SET zbsmail_body = %s WHERE ID = 6"; $q = $wpdb->prepare($sql,array($newTemplate)); $wpdb->query($q); // ===== / Previously: 4.0.7 - corrects outdated task notification template // ===== Previously: 4.0.8 - Set the default reference type for invoices & Update the existing template for email notifications (had old label) if ( $zbs->DAL->invoices->getFullCount() > 0 ) { // The user has used the invoice module. Default reference type = manual $zbs->settings->update( 'reftype', 'manual' ); } // Update the existing template for email notifications (had old label) global $ZBSCRM_t,$wpdb; // retrieve existing template - hardtyped $existingTemplate = $wpdb->get_var('SELECT zbsmail_body FROM '.$ZBSCRM_t['system_mail_templates'].' WHERE ID = 4'); // load new $newTemplate = zeroBSCRM_mail_retrieveDefaultBodyTemplate('invoicesent'); // back it up into a WP option if was different if ($existingTemplate !== $newTemplate) update_option('jpcrm_invnotificationtemplate',$existingTemplate, false); // overwrite $sql = "UPDATE " . $ZBSCRM_t['system_mail_templates'] . " SET zbsmail_body = %s WHERE ID = 4"; $q = $wpdb->prepare($sql,array($newTemplate)); $wpdb->query($q); // ===== / Previously: 4.0.8 - Set the default reference type for invoices & Update the existing template for email notifications (had old label) zeroBSCRM_migrations_markComplete('2963',array('updated'=>'1')); } /* * Migration 2.99.99 - set permalinks to flush (was used with v3.0 migration, left in tact as portal may be dependent) */ function zeroBSCRM_migration_29999(){ // set permalinks to flush, this'll cause them to be refreshed on 3000 migration // ... as that has preload setting jpcrm_flag_for_flush_rewrite(); // fini zeroBSCRM_migrations_markComplete('29999',array('updated'=>1)); } /* * Migration 4.11.0 - secure upload folders * previously: * 4.5.0 - Adds indexing protection to directories with potentially sensitive .html files * 4.11.0 - secure upload folders */ function zeroBSCRM_migration_411(){ $wp_uploads_dir = wp_upload_dir(); // directories to secure // if these ever expand beyond this we should move the list to core & manage periodic checks $directories = array( ZEROBSCRM_PATH . 'templates/', ZEROBSCRM_PATH . 'templates/emails/', ZEROBSCRM_PATH . 'templates/invoices/', ZEROBSCRM_PATH . 'templates/quotes/', $wp_uploads_dir['basedir'] . '/' . 'zbscrm-store/_wip/', ); // secure them! foreach ( $directories as $directory ){ jpcrm_create_and_secure_dir_from_external_access( $directory, true ); } jpcrm_create_and_secure_dir_from_external_access( $wp_uploads_dir['basedir'] . '/' . 'zbscrm-store/', false ); // mark complete zeroBSCRM_migrations_markComplete('411',array('updated'=>1)); } /* * Migration 5.0 - Alter external sources table for existing users (added origin) */ function zeroBSCRM_migration_50(){ global $zbs, $wpdb, $ZBSCRM_t; // external source tweak if ( !zeroBSCRM_migration_tableHasColumn( $ZBSCRM_t['externalsources'], 'zbss_origin' ) ){ $sql = "ALTER TABLE " . $ZBSCRM_t['externalsources'] . " ADD COLUMN `zbss_origin` VARCHAR(400) NULL DEFAULT NULL AFTER `zbss_uid`, ADD INDEX (zbss_origin);"; $wpdb->query( $sql ); } // add transaction status // build string $transaction_statuses = zeroBSCRM_getTransactionsStatuses(true); $deleted_string = __( 'Deleted', 'zero-bs-crm' ); if ( !in_array( $deleted_string, $transaction_statuses ) ){ $transaction_statuses[] = $deleted_string; } $transaction_statuses_str = implode( ',', $transaction_statuses ); // update $customisedFields = $zbs->settings->get('customisedfields'); $customisedFields['transactions']['status'][1] = $transaction_statuses_str; $zbs->settings->update('customisedfields',$customisedFields); // mark complete zeroBSCRM_migrations_markComplete( '50', array( 'updated' => 1 ) ); } /* * 5.3 - Migrate all encrypted data to new encryption endpoints */ function zeroBSCRM_migration_53(){ global $zbs; // load libs // ~5.3 if ( ! function_exists( 'zeroBSCRM_encrypt' ) ) { require( ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.Encryption.php' ); } // 5.3~ $zbs->load_encryption(); // count $successful_recryptions = 0; // Mail Delivery methods (if any): // previous decrypt key $decryption_key = hex2bin( zeroBSCRM_getSetting('smtpkey') ); // retrieve existing $existing_mail_delivery_methods = zeroBSCRM_getSetting( 'smtpaccs' ); if (!is_array($existing_mail_delivery_methods)) $existing_mail_delivery_methods = array(); // cycle through them and re-encrypt $replacement_delivery_methods = array(); foreach ( $existing_mail_delivery_methods as $method_key => $method_array ){ $updated_method_array = $method_array; if ( isset( $method_array['pass'] ) ){ // decrypt (hiding deprecation notices via param) $password = zeroBSCRM_encryption_unsafe_process( 'decrypt', $method_array['pass'], $decryption_key, zeroBSCRM_get_iv( true ), true ); // This is used as a fallback because some users can still have passwords // that were encrypted using the wrong IV. if ( !$password ) { $password = zeroBSCRM_encryption_unsafe_process( 'decrypt', $method_array['pass'], $decryption_key, $decryption_key, true ); } if ( $password ) { // encrypt password: $updated_method_array['pass'] = $zbs->encryption->encrypt( $password, 'smtp' ); } else { // keep existing ciphertext; likely already updated but otherwise corrupt $updated_method_array['pass'] = $method_array['pass']; } $successful_recryptions++; } $replacement_delivery_methods[ $method_key ] = $updated_method_array; } // update em $zbs->settings->update( 'smtpaccs', $replacement_delivery_methods ); // There was some old usage of pwmanager on companys with CPTs, for now we're skipping support. // $pws = get_post_meta($id,$zbsPasswordManager['dbkey'],true); // hash secret if not already hashed $api_secret = $zbs->DAL->setting( 'api_secret' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase if ( str_starts_with( $api_secret, 'zbscrm_' ) ) { $hashed_api_secret = $zbs->encryption->hash( $api_secret ); $zbs->DAL->updateSetting( 'api_secret', $hashed_api_secret ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase } global $wpdb, $ZBSCRM_t; // add indexes for performance if ( jpcrm_database_server_has_ability('fulltext_index') && !jpcrm_migration_table_has_index( $ZBSCRM_t['customfields'], 'search' ) ) { $sql = 'ALTER TABLE ' . $ZBSCRM_t['customfields'] . ' ADD FULLTEXT INDEX `search` (`zbscf_objval`);'; $wpdb->query( $sql ); } if ( !jpcrm_migration_table_has_index( $ZBSCRM_t['taglinks'], 'zbstl_tagid+zbstl_objtype' ) ) { $sql = 'ALTER TABLE ' . $ZBSCRM_t['taglinks'] . ' ADD INDEX `zbstl_tagid+zbstl_objtype` (`zbstl_tagid`,`zbstl_objtype`) USING BTREE;'; $wpdb->query( $sql ); } if ( !jpcrm_migration_table_has_index( $ZBSCRM_t['externalsources'], 'zbss_uid+zbss_source+zbss_objtype' ) ) { $sql = 'ALTER TABLE ' . $ZBSCRM_t['externalsources'] . ' ADD INDEX `zbss_uid+zbss_source+zbss_objtype` (`zbss_uid`,`zbss_source`,`zbss_objtype`) USING BTREE;'; $wpdb->query( $sql ); } if ( !jpcrm_migration_table_has_index( $ZBSCRM_t['meta'], 'zbsm_objid+zbsm_key+zbsm_objtype' ) ) { $sql = 'ALTER TABLE ' . $ZBSCRM_t['meta'] . ' ADD INDEX `zbsm_objid+zbsm_key+zbsm_objtype` (`zbsm_objid`,`zbsm_key`,`zbsm_objtype`) USING BTREE;'; $wpdb->query( $sql ); } if ( !jpcrm_migration_table_has_index( $ZBSCRM_t['logs'], 'zbsl_created' ) ) { $sql = 'ALTER TABLE ' . $ZBSCRM_t['logs'] . ' ADD INDEX `zbsl_created` (`zbsl_created`) USING BTREE;'; $wpdb->query( $sql ); } if ( !jpcrm_migration_table_has_index( $ZBSCRM_t['contacts'], 'zbsc_status' ) ) { $sql = 'ALTER TABLE ' . $ZBSCRM_t['contacts'] . ' ADD INDEX `zbsc_status` (`zbsc_status`) USING BTREE;'; $wpdb->query( $sql ); } // remove errant .htaccess file $wp_uploads_dir = wp_upload_dir(); $errant_htaccess = $wp_uploads_dir['basedir'] . '/' . 'zbscrm-store/.htaccess'; if ( file_exists( $errant_htaccess ) ) { unlink( $errant_htaccess ); } // mark complete zeroBSCRM_migrations_markComplete( '53', array( 'updated' => $successful_recryptions ) ); } /* * Migration 5.4 * - Support pinned logs. * - Migrate all log meta stored in old dehydrated fashion. (Will do in 1k chunks until finished.) */ function zeroBSCRM_migration_54(){ global $zbs, $wpdb, $ZBSCRM_t; // add zbsl_pinned to log table if not existing if ( !zeroBSCRM_migration_tableHasColumn( $ZBSCRM_t['logs'], 'zbsl_pinned' ) ) { $sql = 'ALTER TABLE ' . $ZBSCRM_t['logs'] . ' ADD `zbsl_pinned` int(1) NULL AFTER `zbsl_longdesc`;'; $wpdb->query( $sql ); } // get outdated log meta count $outdated_log_meta_count = (int)$wpdb->get_var( 'SELECT COUNT(ID) FROM ' . $ZBSCRM_t['meta'] . ' WHERE zbsm_objtype = 8 AND zbsm_key = "logmeta"' ); if ( $outdated_log_meta_count > 0 ) { // get outdated meta records $outdated_log_meta_records = $wpdb->get_results( 'SELECT * FROM ' . $ZBSCRM_t['meta'] . ' WHERE zbsm_objtype = 8 AND zbsm_key = "logmeta" ORDER BY ID DESC LIMIT 5000' ); foreach ( $outdated_log_meta_records as $log_record ){ // hydrate - Note that `[]` doesn't hydrate into array with this $log_meta = $zbs->DAL->decodeIfJSON( $zbs->DAL->stripSlashes( $log_record->zbsm_val ) ); // insert new line foreach meta if ( is_array( $log_meta ) ){ foreach ( $log_meta as $key => $value ){ $zbs->DAL->updateMeta( ZBS_TYPE_LOG, $log_record->zbsm_objid, $zbs->DAL->makeSlug( $key ), $value ); } } // delete old 'dehydrated whole' line zeroBSCRM_db2_deleteGeneric( $log_record->ID, 'meta' ); } // any left? $outdated_log_meta_count = (int)$wpdb->get_var( 'SELECT COUNT(ID) FROM ' . $ZBSCRM_t['meta'] . ' WHERE zbsm_objtype = 8 AND zbsm_key = "logmeta"' ); } if ( $outdated_log_meta_count == 0 ){ // mark complete zeroBSCRM_migrations_markComplete( '54', array( 'updated' => 1 ) ); } } /* * Migration 5.4.3 * - Removes unwanted .htaccess files */ function zeroBSCRM_migration_543() { // recursively deletes all .htaccess files starting from the root storage folder $root_storage = zeroBSCRM_privatisedDirCheck(); if ( $root_storage !== false ) { $recursive_file_iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $root_storage['path'] ) ); $htaccess_files = array(); foreach ( $recursive_file_iterator as $file ) { if ( $file->isDir() || $file->getBasename() != '.htaccess' ) { continue; } $htaccess_files[] = $file->getPathname(); } foreach ( $htaccess_files as $errant_htaccess ) { if ( is_file( $errant_htaccess ) ){ unlink( $errant_htaccess ); } } } // mark this migration as complete zeroBSCRM_migrations_markComplete( '543', array( 'updated' => 1 ) ); } /* * Migration 5.4.4 * - Forces re-install of default fonts (moved to new JPCRM storage folder) */ function zeroBSCRM_migration_544(){ global $zbs; // font reinstall $shouldBeInstalled = zeroBSCRM_getSetting( 'feat_pdfinv' ); if ( $shouldBeInstalled == "1" ){ // force reinstall of fonts $fonts = $zbs->get_fonts(); if ( !$fonts->extract_and_install_default_fonts() ) { return false; } } // mark complete zeroBSCRM_migrations_markComplete( '544', array( 'updated' => 1 ) ); } /* * Migration 5.5 * - Deletes orphaned rows linked to invoices in the objlinks table */ function zeroBSCRM_migration_55() { global $zbs, $wpdb, $ZBSCRM_t; // Deletes links when missing invoices are the 'to' object $wpdb->query( ' DELETE FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE ' . ' zbsol_objtype_to = ' . ZBS_TYPE_INVOICE . ' AND zbsol_objid_to NOT IN ( SELECT ID from ' . $ZBSCRM_t['invoices'] . ' ) ' ); // Deletes links when missing invoices are the 'from' object $wpdb->query( ' DELETE FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE ' . ' zbsol_objtype_from = ' . ZBS_TYPE_INVOICE . ' AND zbsol_objid_from NOT IN ( SELECT ID from ' . $ZBSCRM_t['invoices'] . ' ) ' ); // Deletes orphaned line items $wpdb->query( ' DELETE FROM ' . $ZBSCRM_t['lineitems'] . ' WHERE ID NOT IN' . ' (' . ' SELECT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE ' . ' zbsol_objtype_from = ' . ZBS_TYPE_LINEITEM . ' )' ); // mark complete zeroBSCRM_migrations_markComplete( '55', array( 'updated' => 1 ) ); } /* * Migration 5.5a * Recompiles segments, runs on later schedule (wp_loaded) */ function zeroBSCRM_migration_55a(){ global $zbs; // recompile segments with new condition names $zbs->DAL->segments->compile_all_segments(); // mark complete zeroBSCRM_migrations_markComplete( '55a', array( 'updated' => 1 ) ); } /* * Migration 5.5.1 * - Deletes orphaned aka rows linked to contacts since deleted */ function zeroBSCRM_migration_551() { global $zbs, $wpdb, $ZBSCRM_t; // Deletes orphaned aka rows $wpdb->query( 'DELETE FROM ' . $ZBSCRM_t['aka'] . ' WHERE aka_type = ' . ZBS_TYPE_CONTACT . ' AND aka_id NOT IN' . ' (SELECT id FROM ' . $ZBSCRM_t['contacts'] . ')' ); // mark complete zeroBSCRM_migrations_markComplete( '551', array( 'updated' => 1 ) ); } /** * Migration 5.6.0 * Moves files from the old file structure (zbscrm-store) to the new * one (jpcrm-storage) for rows from the meta table that have their object type * equals to ZBS_TYPE_CONTACT and a file in the zbsm_val column. * * @param object $meta_row Row from the meta table that needs to be updated. * * @return void */ function zeroBSCRM_migration_560_move_custom_file_upload_box( $meta_row ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid global $wpdb, $ZBSCRM_t; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase jpcrm_migration_load_wp_filesystem_direct(); // Skip if this is not a custom file for a contact // (the only type that should exist, but we are being extra careful here). if ( $meta_row->zbsm_objtype !== ZBS_TYPE_CONTACT ) { return; } $file_path = $meta_row->zbsm_val; // Skip if this file doesn't exist (user may have deleted using the filesystem). if ( ! file_exists( $file_path ) ) { error_log( sprintf( 'JPCRM migration error while searching for upload box file %s', $file_path ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log return; } $new_dir = jpcrm_storage_dir_info_for_contact( $meta_row->zbsm_objid ); // Skip if there is no information for the files subfolder. if ( $new_dir === false || ! isset( $new_dir['files'] ) ) { error_log( sprintf( 'JPCRM migration error missing subfolder files for contact ID %s', $meta_row->zbsm_objid ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log return; } $new_dir_info = $new_dir['files']; $upload_folder_exists = jpcrm_create_and_secure_dir_from_external_access( $new_dir_info['path'], false ); if ( $upload_folder_exists === false ) { // We shouldn't have any errors here, but if we do we log it and skip this one. error_log( sprintf( 'JPCRM migration error while creating upload box folder %s ', $new_dir_info['path'] ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log return; } $file_name = basename( $file_path ); $new_file_path = $new_dir_info['path'] . '/' . $file_name; $wp_filesystem_direct = new WP_Filesystem_Direct( false ); // Moving the file. if ( ! $wp_filesystem_direct->move( $file_path, $new_file_path, true ) ) { // We shouldn't have any errors here, but if we do we log it and skip this one. error_log( sprintf( 'JPCRM migration error while moving upload box %s to %s', $file_path, $new_file_path ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log return; } // Updates the database. $update_result = $wpdb->update( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching $ZBSCRM_t['meta'], // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase array( 'zbsm_val' => $new_file_path, 'zbsm_lastupdated' => time(), ), array( 'ID' => $meta_row->ID ), array( // Field data types. '%s', '%d', ), array( // Where data types. '%d', ) ); if ( $update_result === false ) { error_log( sprintf( 'JPCRM migration error while updating upload box meta %s to %s', $meta_row->ID ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log } } /** * Migration 5.6.0 * Moves files from the old file structure (zbscrm-store) to the new * one (jpcrm-storage) for rows from the meta table that have the key 'files'. * * @param object $meta_row Row from the meta table that needs to be updated. * * @return void */ function zeroBSCRM_migration_560_move_file_array( $meta_row ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid global $wpdb, $ZBSCRM_t; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase jpcrm_migration_load_wp_filesystem_direct(); // Before we move the files from the array we must discover its type and // update its dir_info information (contains information for several // subfolders, we will use the 'files' subfolder). $new_dir = false; switch ( $meta_row->zbsm_objtype ) { case ZBS_TYPE_CONTACT: $new_dir = jpcrm_storage_dir_info_for_contact( $meta_row->zbsm_objid ); break; case ZBS_TYPE_COMPANY: $new_dir = jpcrm_storage_dir_info_for_company( $meta_row->zbsm_objid ); break; case ZBS_TYPE_QUOTE: $new_dir = jpcrm_storage_dir_info_for_quotes( $meta_row->zbsm_objid ); break; case ZBS_TYPE_INVOICE: $new_dir = jpcrm_storage_dir_info_for_invoices( $meta_row->zbsm_objid ); break; } // Skip if any other type (we are only moving these four types). if ( $new_dir === false || ! isset( $new_dir['files'] ) ) { return; } $new_dir_info = $new_dir['files']; $outdated_file_array = json_decode( $meta_row->zbsm_val, true ); // If we can't decode it neither the CRM can when it shows files, so // we can skip it. if ( $outdated_file_array === null ) { return; } // This was the hard-coded value in JPCRM < 5.4.x. $previous_folder = 'zbscrm-store'; $new_file_array = array(); foreach ( $outdated_file_array as $outdated_file_meta ) { // Skip if this has an unknown format. // Skip if this isn't an outdate file. // Skip if this file doesn`t exist (user may have deleted using the filesystem). if ( ! isset( $outdated_file_meta['file'] ) || ! str_contains( $outdated_file_meta['file'], "/$previous_folder/" ) || ! file_exists( $outdated_file_meta['file'] ) ) { $new_file_array[] = $outdated_file_meta; continue; } $upload_folder_exists = jpcrm_create_and_secure_dir_from_external_access( $new_dir_info['path'], false ); if ( $upload_folder_exists === false ) { // We shouldn't have any errors here, but if we do we log it and skip this one. error_log( sprintf( 'JPCRM migration error while creating folder %s ', $new_dir_info['path'] ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log $new_file_array[] = $outdated_file_meta; return; } $file_name = basename( $outdated_file_meta['file'] ); $new_file_path = $new_dir_info['path'] . '/' . $file_name; $wp_filesystem_direct = new WP_Filesystem_Direct( false ); // Moving the file. if ( ! $wp_filesystem_direct->move( $outdated_file_meta['file'], $new_file_path, true ) ) { // We shouldn't have any errors here, but if we do we log it and skip this one. error_log( sprintf( 'JPCRM migration error while moving %s to %s', $outdated_file_meta['file'], $new_file_path ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log $new_file_array[] = $outdated_file_meta; continue; } // Updating references to save in the database. $outdated_file_meta['file'] = $new_file_path; $outdated_file_meta['url'] = $new_dir_info['url'] . '/' . $file_name; $new_file_array[] = $outdated_file_meta; } // Updates the database. $update_result = $wpdb->update( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching $ZBSCRM_t['meta'], // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase array( 'zbsm_val' => wp_json_encode( $new_file_array ), 'zbsm_lastupdated' => time(), ), array( 'ID' => $meta_row->ID ), array( // Field data types. '%s', '%d', ), array( // Where data types. '%d', ) ); if ( $update_result === false ) { error_log( sprintf( 'JPCRM migration error while updating file array meta %s to %s', $meta_row->ID ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log } } /** * Migration 5.6.0 * Moves the old folder structure (zbscrm-store) to the new one (jpcrm-storage). * * @return void */ function zeroBSCRM_migration_560() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid global $wpdb, $ZBSCRM_t; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // This was the hard-coded value in JPCRM < 5.4.x. $previous_folder = 'zbscrm-store'; // We only store files in the meta table. $query = sprintf( "SELECT * FROM `%s` WHERE `zbsm_val` LIKE '%s'", $ZBSCRM_t['meta'], '%%%s%%' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $outdated_rows = $wpdb->get_results( $wpdb->prepare( $query, $previous_folder ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching if ( is_array( $outdated_rows ) ) { foreach ( $outdated_rows as $outdated_row ) { // The first type of row we have to migrate has they key 'files' and // has an array of files attached to an object of type `zbsm_objtype`. if ( $outdated_row->zbsm_key === 'files' ) { zeroBSCRM_migration_560_move_file_array( $outdated_row ); } else { zeroBSCRM_migration_560_move_custom_file_upload_box( $outdated_row ); } } } // Mark as complete. zeroBSCRM_migrations_markComplete( '560', array( 'updated' => 1 ) ); } /** * Migration create_workflows_table * * This migration will: * - Make sure all tables are up-to-date. Practically speaking, then we're creating a new "workflows" table. * * @return void */ function zeroBSCRM_migration_create_workflows_table() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid // Check tables if exist and create if not. zeroBSCRM_checkTablesExist(); // Mark migration as complete. zeroBSCRM_migrations_markComplete( 'create_workflows_table', array( 'updated' => 1 ) ); } /** * Removes errant task timezone offsets from database */ function zeroBSCRM_migration_task_offset_fix() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid global $wpdb, $ZBSCRM_t; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $timezone_offset_in_secs = jpcrm_get_wp_timezone_offset_in_seconds(); if ( ! empty( $timezone_offset_in_secs ) ) { // remove offset from stored task dates $sql = sprintf( 'UPDATE %s SET zbse_start = zbse_start - %d;', $ZBSCRM_t['events'], $timezone_offset_in_secs ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $wpdb->query( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching $sql = sprintf( 'UPDATE %s SET zbse_end = zbse_end - %d;', $ZBSCRM_t['events'], $timezone_offset_in_secs ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $wpdb->query( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching } zeroBSCRM_migrations_markComplete( 'task_offset_fix', array( 'updated' => 1 ) ); } /** * Refresh user roles after tightening restrictions */ function zeroBSCRM_migration_refresh_user_roles() { // remove roles zeroBSCRM_clearUserRoles(); // add roles anew zeroBSCRM_addUserRoles(); zeroBSCRM_migrations_markComplete( 'refresh_user_roles', array( 'updated' => 1 ) ); } /** * Regenerate tag slugs */ function zeroBSCRM_migration_regenerate_tag_slugs() { $obj_ids = array( ZBS_TYPE_CONTACT, ZBS_TYPE_COMPANY, ZBS_TYPE_QUOTE, ZBS_TYPE_INVOICE, ZBS_TYPE_TRANSACTION, ZBS_TYPE_TASK, ZBS_TYPE_FORM ); foreach ( $obj_ids as $obj_id ) { jpcrm_migration_regenerate_tag_slugs_for_obj_type( $obj_id ); } zeroBSCRM_migrations_markComplete( 'regenerate_tag_slugs', array( 'updated' => 1 ) ); } /** * Convert invoice statuses and mappings to English */ function zeroBSCRM_migration_invoice_language_fixes() { // if already English, can't auto-migrate and probably no need $cur_locale = get_locale(); if ( $cur_locale === 'en_US' ) { zeroBSCRM_migrations_markComplete( 'invoice_language_fixes', array( 'updated' => 1 ) ); return; } global $zbs, $wpdb, $ZBSCRM_t; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $invoice_statuses = array( 'Draft' => __( 'Draft', 'zero-bs-crm' ), 'Unpaid' => __( 'Unpaid', 'zero-bs-crm' ), 'Paid' => __( 'Paid', 'zero-bs-crm' ), 'Overdue' => __( 'Overdue', 'zero-bs-crm' ), 'Deleted' => __( 'Deleted', 'zero-bs-crm' ), ); // get WooSync settings $woosync_settings = $zbs->settings->get( 'zbscrm_dmz_ext_woosync' ); $settings_to_update = array(); foreach ( $invoice_statuses as $invoice_status => $translated_status ) { // if the "translation" is the same as English, continue if ( $translated_status === $invoice_status ) { continue; } // if there are settings, we may need to update mappings too if ( $woosync_settings ) { foreach ( $woosync_settings as $setting => $value ) { // if not a setting we care about, continue if ( ! str_starts_with( $setting, 'order_invoice_map_' ) ) { continue; } // if no translated status matches, continue if ( $value !== $translated_status ) { continue; } // flag setting for update $settings_to_update[ $setting ] = $invoice_status; } } // see if there are any matches on translated status $query = $wpdb->prepare( 'SELECT COUNT(ID) FROM ' . $ZBSCRM_t['invoices'] . ' WHERE zbsi_status=%s', $translated_status ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $count = $wpdb->get_var( $query ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared // if no matches, nothing to update if ( $count === 0 ) { continue; } // update status to English $query = $wpdb->prepare( 'UPDATE ' . $ZBSCRM_t['invoices'] . ' SET zbsi_status=%s WHERE zbsi_status=%s', $invoice_status, $translated_status ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $wpdb->query( $query ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared } // if there are mapping settings to update, do it if ( $woosync_settings && ! empty( $settings_to_update ) ) { // make a backup of settings $zbs->settings->update( 'zbscrm_dmz_ext_woosync.bak', $woosync_settings ); // update WooSync settings $updated_woosync_settings = array_merge( $woosync_settings, $settings_to_update ); $zbs->settings->update( 'zbscrm_dmz_ext_woosync', $updated_woosync_settings ); } zeroBSCRM_migrations_markComplete( 'invoice_language_fixes', array( 'updated' => 1 ) ); } /* ====================================================== / MIGRATIONS ====================================================== */ /* ====================================================== MIGRATION Helpers ====================================================== */ // simplistic arr manager function zeroBSCRM_migration_addErrToStack($err=array(),$errKey=''){ if ($errKey !== ''){ $existing = get_option($errKey, array()); // catch err in err stack. if (!is_array($existing)) $existing = array(); // add + update $existing[] = $err; update_option( $errKey, $existing, false); return true; } return false; } // checks if a column already exists // note $tableName is used unchecked function zeroBSCRM_migration_tableHasColumn( $table_name, $column_name ){ global $wpdb; if ( !empty( $table_name ) && !empty( $column_name ) ){ $query = $wpdb->prepare( "SHOW COLUMNS FROM " . $table_name . " LIKE %s", $column_name ); $row = $wpdb->get_results( $query ); if ( is_array( $row ) && count( $row ) > 0 ){ return true; } } return false; } /* * Verifies if a mysql table has an index named X */ function jpcrm_migration_table_has_index( $table_name, $index_name ){ global $wpdb; $query = $wpdb->prepare( "SHOW INDEX FROM " . $table_name . " WHERE Key_name = %s", $index_name ); $row = $wpdb->get_results( $query ); if ( is_array( $row ) && count( $row ) > 0){ return true; } return false; } /** * Retrieves the data typo of the given colemn name in the given table name. * It's worth noting that it will have the size of the field too, so `int(10)` * rather than just `int`. * * @param $table_name string The table name to query. * @param $column_name string The column name to query. * * @return string|false The column type as a string, or `false` on failure. */ function zeraBSCRM_migration_get_column_data_type( $table_name, $column_name ) { global $wpdb; $column = $wpdb->get_row( $wpdb->prepare( "SHOW COLUMNS FROM $table_name LIKE %s", $column_name ) ); return empty( $column ) ? false : $column->Type; } /** * Loads everything needed to use the WP_Filesystem_Direct class. * * @return void */ function jpcrm_migration_load_wp_filesystem_direct() { require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php'; require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php'; } /** * Regenerates tag slugs for a given object type. * * @param int $obj_type_id Object type ID. */ function jpcrm_migration_regenerate_tag_slugs_for_obj_type( int $obj_type_id ) { global $zbs; // get tags for object type $tags = $zbs->DAL->getTagsForObjType( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase array( 'objtypeid' => $obj_type_id, 'excludeEmpty' => false, ) ); // store slugs we've used so we prevent duplicates $used_slugs = array(); foreach ( $tags as $tag ) { // generate a potential slug $potential_slug = sanitize_key( $tag['name'] ); // this will be empty if Chinese or Cyrillic or symbols, so use `tag` fallback if ( empty( $potential_slug ) ) { if ( preg_match( '/^tag-\d+$/', $tag['slug'] ) && ! in_array( $tag['slug'], $used_slugs, true ) ) { // if we had a fallback slug before and it hasn't been claimed by another tag, use it $potential_slug = $tag['slug']; } else { // get a new fallback slug $potential_slug = $zbs->DAL->get_new_tag_slug( $obj_type_id, 'tag', true ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase } } elseif ( in_array( $potential_slug, $used_slugs, true ) ) { // this needs an iteration if ( preg_match( '/^' . $potential_slug . '-\d+$/', $tag['slug'] ) && ! in_array( $tag['slug'], $used_slugs, true ) ) { // use old slug iteration $potential_slug = $tag['slug']; } else { // generate a new slug iteration $potential_slug = $zbs->DAL->get_new_tag_slug( $obj_type_id, $potential_slug ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase } } // if the new slug is different than the old one, update the database if ( $potential_slug !== $tag['slug'] ) { $zbs->DAL->addUpdateTag( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase array( 'id' => $tag['id'], 'data' => array( 'objtype' => $obj_type_id, 'name' => $tag['name'], 'slug' => $potential_slug, ), ) ); } // store in index of used slugs $used_slugs[] = $potential_slug; } } /* ====================================================== / MIGRATION Helpers ====================================================== */
projects/plugins/crm/includes/ZeroBSCRM.FileUploads.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V1.20 * * Copyright 2020 Automattic * * Date: 01/11/16 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== Acceptible Mime Types ====================================================== */ #} A list of applicable Mimetypes for file uploads function zeroBSCRM_returnMimeTypes(){ return array( 'pdf' => array('application/pdf'), 'doc' => array('application/msword'), 'docx' => array('application/vnd.openxmlformats-officedocument.wordprocessingml.document'), 'ppt' => array('application/vnd.ms-powerpointtd>'), 'pptx' => array('application/vnd.openxmlformats-officedocument.presentationml.presentation'), 'xls' => array('application/vnd.ms-excel'), 'xlsx' => array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'), 'csv' => array('text/csv'), 'png' => array('image/png'), 'jpg' => array('image/jpeg'), 'jpeg' => array('image/jpeg'), 'gif' => array('image/gif'), 'mp3' => array('audio/mpeg'), 'txt' => array('text/plain'), 'zip' => array('application/zip', 'application/x-compressed-zip'), 'mp4' => array('video/mp4') # plus 'any' ); } /* * Returns the extension for the provided mimetype, false otherwise. */ function jpcrm_return_ext_for_mimetype( $mimetype ) { global $zbs; $all_types = $zbs->acceptable_mime_types; foreach( $all_types as $extension => $ext_mimetypes ) { foreach( $ext_mimetypes as $this_mimetype ) { if ( $this_mimetype === $mimetype ) { return $extension; } } } return false; } /* ====================================================== / Acceptible Mime Types ====================================================== */ /* ====================================================== File Upload Related Funcs ====================================================== */ // str e.g. .pdf, .xls function zeroBS_acceptableFileTypeListStr(){ $ret = ''; global $zbs; #} Retrieve settings $settings = $zbs->settings->getAll(); if (isset($settings['filetypesupload'])) { if (isset($settings['filetypesupload']['all']) && $settings['filetypesupload']['all'] == 1){ $ret = __( 'All File Types', 'zero-bs-crm' ); } else { foreach ($settings['filetypesupload'] as $filetype => $enabled){ if (isset($settings['filetypesupload'][$filetype]) && $enabled == 1) { if (!empty($ret)) $ret .= ', '; $ret .= '.'.$filetype; } } } } if (empty($ret)) $ret = 'No Uploads Allowed'; return $ret; } function zeroBS_acceptableFileTypeListArr(){ $ret = array(); global $zbs; #} Retrieve settings $settings = $zbs->settings->getAll(); if (isset($settings['filetypesupload'])) foreach ($settings['filetypesupload'] as $filetype => $enabled){ if (isset($settings['filetypesupload'][$filetype]) && $enabled == 1) $ret[] = '.'.$filetype; } return $ret; } function zeroBS_acceptableFileTypeMIMEArr(){ $ret = array(); global $zbs; #} Retrieve settings $settings = $zbs->settings->getAll(); // if all, pass that if ( isset( $settings['filetypesupload'] ) && isset($settings['filetypesupload']['all']) && $settings['filetypesupload']['all'] == 1){ return array('all'=>1); } if (isset($settings['filetypesupload'])) { if (isset($settings['filetypesupload']['all']) && $settings['filetypesupload']['all'] == 1) { // add all foreach ($settings['filetypesupload'] as $filetype => $enabled){ $ret = array_merge( $ret, $zbs->acceptable_mime_types[$filetype] ); } } else { // individual foreach ($settings['filetypesupload'] as $filetype => $enabled) { if ( isset( $settings['filetypesupload'][$filetype] ) && $enabled == 1 ) { $ret = array_merge( $ret, $zbs->acceptable_mime_types[$filetype] ); } } } } return $ret; } /** * Returns an array with all the mime types accepted for uploads from * contacts. */ function jpcrm_acceptable_filetype_mime_array_from_contacts() { global $zbs; $ret = array(); $settings = $zbs->settings->getAll(); if ( isset( $settings['filetypesupload'] ) ) { foreach ( $settings['filetypesupload'] as $filetype => $enabled ) { if ( $enabled == 1 && isset( $settings['filetypesupload'][$filetype] ) && isset( $zbs->acceptable_mime_types[$filetype] ) ) { $ret = array_merge( $ret, $zbs->acceptable_mime_types[$filetype] ); } } } return $ret; } function jpcrm_acceptable_file_type_list_str_for_contact() { $ret = ''; global $zbs; $settings = $zbs->settings->getAll(); if ( isset( $settings['filetypesupload'] ) && is_array( $settings['filetypesupload'] ) ) { foreach ($settings['filetypesupload'] as $filetype => $enabled){ if (isset($settings['filetypesupload'][$filetype]) && $enabled == 1 && $filetype !== 'all') { if (!empty($ret)) $ret .= ', '; $ret .= '.'.$filetype; } } } if (empty($ret)) $ret = 'No Uploads Allowed'; return $ret; } #} removes a link to file (quote, invoice, other) // not always customer id... sometimes inv/co etc. function zeroBS_removeFile($objectID=-1,$fileType='',$fileURL=''){ if ( current_user_can( 'admin_zerobs_customers' ) ) { //only admin can do this too (extra security layer) global $zbs; if ($objectID !== -1 && !empty($fileURL)){ /* centralised into zeroBSCRM_files_getFiles switch ($fileType){ case 'customer': $filesArrayKey = 'zbs_customer_files'; break; case 'quotes': $filesArrayKey = 'zbs_customer_quotes'; break; case 'invoices': $filesArrayKey = 'zbs_customer_invoices'; break; } */ #} good? // zeroBSCRM_files_getFiles if (isset($filesArrayKey)){ if (in_array($fileType, array('customer','quotes','invoices','company'))){ #} First remove list reference: #} any change? $changeFlag = false; $fileObjToDelete = false; #} Load files arr /* centralised into zeroBSCRM_files_getFiles // for DAL1 contacts + quotes/invs: if (!$zbs->isDAL2() || $filesArrayKey == 'zbs_customer_quotes' || $filesArrayKey == 'zbs_customer_invoices') // DAL1 $filesList = get_post_meta($objectID, $filesArrayKey, true); else // DAL2 $filesList = $zbs->DAL->contacts->getContactMeta($objectID,'files'); */ $filesList = zeroBSCRM_files_getFiles($fileType,$objectID); if (is_array($filesList) && count($filesList) > 0){ #} defs $ret = array(); #} Cycle through and remove any with this url - lame, but works for now foreach ($filesList as $fileObj){ if ($fileObj['url'] != $fileURL) $ret[] = $fileObj; else { $fileObjToDelete = $fileObj; $changeFlag = true; // also, if the removed file(s) are logged in any slots, clear the slot :) $slot = zeroBSCRM_fileslots_fileSlot($fileObj['file'],$objectID,ZBS_TYPE_CONTACT); if ($slot !== false && !empty($slot)){ zeroBSCRM_fileslots_clearFileSlot($slot,$objectID,ZBS_TYPE_CONTACT); } } } if ($changeFlag) { /* zeroBSCRM_files_updateFiles // for DAL1 contacts + quotes/invs: if (!$zbs->isDAL2() || $filesArrayKey == 'zbs_customer_quotes' || $filesArrayKey == 'zbs_customer_invoices') // DAL1 update_post_meta($objectID,$filesArrayKey,$ret); else // DAL2 $zbs->DAL->updateMeta(ZBS_TYPE_CONTACT,$objectID,'files',$ret); */ zeroBSCRM_files_updateFiles($fileType,$objectID,$ret); } } #} else w/e #} Then delete actual file ... if ($changeFlag && isset($fileObjToDelete) && isset($fileObjToDelete['file'])){ #} Brutal #} #recyclingbin if (file_exists($fileObjToDelete['file'])) { #} Delete unlink($fileObjToDelete['file']); #} Check if deleted: if (file_exists($fileObjToDelete['file'])){ // try and be more forceful: chmod($fileObjToDelete['file'], 0777); unlink(realpath($fileObjToDelete['file'])); if (file_exists($fileObjToDelete['file'])){ // tone down perms, at least chmod($fileObjToDelete['file'], 0644); // add message return __('Could not delete file from server:','zero-bs-crm').' '.$fileObjToDelete['file']; } } } } return true; } } } #} / can manage options return false; } /* ====================================================== File Upload related funcs ====================================================== */ function zeroBSCRM_privatiseUploadedFile($fromPath='',$filename=''){ #} Check dir created $currentUploadDirObj = zeroBSCRM_privatisedDirCheck(); if (is_array($currentUploadDirObj) && isset($currentUploadDirObj['path'])){ $currentUploadDir = $currentUploadDirObj['path']; $currentUploadURL = $currentUploadDirObj['url']; } else { $currentUploadDir = false; $currentUploadURL = false; } if (!empty($currentUploadDir)){ // generate a safe name + check no file existing // this is TEMP code to be rewritten on formally secure file sys WH $filePreHash = md5($filename.time()); // actually limit to first 16 chars is plenty $filePreHash = substr($filePreHash,0,16); $finalFileName = $filePreHash.'-'.$filename; $finalFilePath = $currentUploadDir.'/'.$finalFileName; // check exists, deal with (unlikely) dupe names $c = 1; while (file_exists($finalFilePath) && $c < 50){ // remake $finalFileName = $filePreHash.'-'.$c.'-'.$filename; $finalFilePath = $currentUploadDir.'/'.$finalFileName; // let it roll + retest $c++; } if (rename($fromPath.'/'.$filename,$finalFilePath)){ // moved :) // check perms? /* https://developer.wordpress.org/reference/functions/wp_upload_bits/ // Set correct file permissions $stat = @ stat( dirname( $new_file ) ); $perms = $stat['mode'] & 0007777; $perms = $perms & 0000666; @ chmod( $new_file, $perms ); */ $endPath = $finalFilePath; // this url is temp, it should be fed via php later. $endURL = $currentUploadURL.'/'.$finalFileName; // the caller-func needs to remove/change data/meta :) return array('file'=>$endPath,'url'=>$endURL); } else { // failed to move return false; } } return false; // couldn't - no dir to move to :) } function zeroBSCRM_privatisedDirCheck( $echo = false ) { $storage_dir_info = jpcrm_storage_dir_info(); if ( $storage_dir_info === false ) { return false; } $is_dir_created = jpcrm_create_and_secure_dir_from_external_access( $storage_dir_info['path'], false ); if ( $is_dir_created === false ) { return false; } return $storage_dir_info; } function jpcrm_get_hash_for_object( $object_id, $object_hash_string ) { global $zbs; $zbs->load_encryption(); return $zbs->encryption->hash( $object_id . $zbs->encryption->get_encryption_key( $object_hash_string ) ); } /* * Returns the 'dir info' for the storage folder. * dir info = * [ * 'path' => 'path for the physical file', * 'url' => 'public facing url' * ] * */ function jpcrm_storage_dir_info() { $uploads_dir = WP_CONTENT_DIR; $uploads_url = content_url(); $private_dir_name = 'jpcrm-storage'; if ( ! empty( $uploads_dir ) && ! empty( $uploads_url ) ) { $full_dir_path = $uploads_dir . '/' . $private_dir_name; $full_url = $uploads_url . '/' . $private_dir_name; return array( 'path' => $full_dir_path, 'url' => $full_url ); } return false; } /* * Returns the 'dir info' for the fonts folder. */ function jpcrm_storage_fonts_dir_path() { $root_storage_info = jpcrm_storage_dir_info(); if ( !$root_storage_info ) { return false; } $fonts_dir = $root_storage_info['path'] . '/fonts/'; // Create and secure fonts dir as needed if ( !jpcrm_create_and_secure_dir_from_external_access( $fonts_dir ) || !is_dir( $fonts_dir ) ) { return false; } return $fonts_dir; } /* * Returns the 'dir info' for the provided generic object. This directory should * be used to store all files associated to this object (e.g. contact files, * company files, invoices...). * * dir info = * [ * 'subfolder_1' => * [ * 'path' => 'path for the physical file', * 'url' => 'public facing url' * ], * 'subfolder_2' => * [ * 'path' => 'path for the physical file', * 'url' => 'public facing url' * ], * . * . * . * ] * */ function jpcrm_storage_dir_info_for_object( $object_id, $object_hash_string, $object_parent_folder, $subfolder_list ) { global $zbs; $root_storage_info = jpcrm_storage_dir_info(); if ( $root_storage_info === false ) { return false; } $parent_storage_info = array( 'path' => $root_storage_info['path'] . '/' . $object_parent_folder, 'url' => $root_storage_info['url'] . '/' . $object_parent_folder ); if ( ! jpcrm_create_and_secure_dir_from_external_access( $parent_storage_info['path'], false ) ) { return false; } $object_unique_hash = jpcrm_get_hash_for_object( $object_id, $object_hash_string ); $parent_relative_path = sprintf( '/%s-%s/', $object_id, $object_unique_hash ); $parent_full_path = $parent_storage_info['path'] . $parent_relative_path; if ( ! jpcrm_create_and_secure_dir_from_external_access( $parent_full_path, false ) ) { return false; } $object_dir_info = array(); foreach ( $subfolder_list as $subfolder ) { $object_dir_info[ $subfolder ] = array( 'path' => $parent_full_path . $subfolder, 'url' => $parent_storage_info['url'] . $parent_relative_path . $subfolder, ); } return $object_dir_info; } /* * Returns the 'dir info' for the provided contact with the subfolders 'avatar', * and 'files'. The definition of 'dir info' can be found in the function * 'jpcrm_storage_dir_info_for_object'. * */ function jpcrm_storage_dir_info_for_contact( $contact_id ) { return jpcrm_storage_dir_info_for_object( $contact_id, 'contact_hash', 'contacts', array( 'avatar', 'files' ) ); } /* * Returns the 'dir info' for the provided company with the subfolder 'files'. * The definition of 'dir info' can be found in the function 'jpcrm_storage_dir_info_for_object'. * */ function jpcrm_storage_dir_info_for_company( $company_id ) { return jpcrm_storage_dir_info_for_object( $company_id, 'company_hash', 'companies', array( 'files' ) ); } /* * Returns the 'dir info' for the provided invoice with the subfolder 'files'. * The definition of 'dir info' can be found in the function 'jpcrm_storage_dir_info_for_object'. * */ function jpcrm_storage_dir_info_for_invoices( $invoice_id ) { return jpcrm_storage_dir_info_for_object( $invoice_id, 'invoice_hash', 'invoices', array( 'files' ) ); } /* * Returns the 'dir info' for the provided quote with the subfolder 'files'. * The definition of 'dir info' can be found in the function 'jpcrm_storage_dir_info_for_object'. * */ function jpcrm_storage_dir_info_for_quotes( $quote_id ) { return jpcrm_storage_dir_info_for_object( $quote_id, 'quote_hash', 'quotes', array( 'files' ) ); } /* * Saves a file uploaded by an admin from $_FILES[ $param_name ] to the folder * $target_dir_info['path'] and returns an array( 'error' => something ) in the * case of errors and an * array( 'file' => file_path, 'url' => file_url, 'priv' => boolean) in the case * of success. */ function jpcrm_save_admin_upload_to_folder( $param_name, $target_dir_info ) { $upload = wp_upload_bits( $_FILES[ $param_name ]['name'], null, file_get_contents( $_FILES[ $param_name ]['tmp_name'] ) ); if( isset( $upload['error'] ) && $upload['error'] != 0 ) { return $upload; } // change this to return a custom error in the future if needed if ( $target_dir_info === false ) { return $upload; } global $zbs; $zbs->load_encryption(); $upload_path = $target_dir_info['path']; $upload_folder_exists = jpcrm_create_and_secure_dir_from_external_access( $upload_path, false ); if ( $upload_folder_exists ) { $upload_filename = sanitize_file_name( sprintf( '%s-%s', $zbs->encryption->get_rand_hex( 16 ), $_FILES[ $param_name ]['name'] // for admins we are accepting "filename.ext" as provided by $_FILES ) ); if ( move_uploaded_file( $_FILES[ $param_name ]['tmp_name'], $upload_path . '/' . $upload_filename ) ) { $upload['file'] = $upload_path . '/' . $upload_filename; $upload['url'] = $target_dir_info['url'] . '/' . $upload_filename; // add this extra identifier if in privatised sys $upload['priv'] = true; } } return $upload; } // 2.95.5+ we also add a subdir for 'work' (this is used by CPP when making thumbs, for example) function zeroBSCRM_privatisedDirCheckWorks( $echo = false ) { $uploads_dir = WP_CONTENT_DIR; $uploads_url = content_url(); $private_dir_name = 'jpcrm-storage/tmp'; if ( ! empty( $uploads_dir ) && ! empty( $uploads_url ) ) { $full_dir_path = $uploads_dir . '/' . $private_dir_name; $full_url = $uploads_url . '/' . $private_dir_name; // check existence if ( !file_exists( $full_dir_path ) ) { // doesn't exist, attempt to create mkdir( $full_dir_path, 0755, true ); // force perms? chmod( $full_dir_path, 0755 ); } if ( is_dir( $full_dir_path ) ) { jpcrm_create_and_secure_dir_from_external_access( $full_dir_path ); return array( 'path' => $full_dir_path, 'url' => $full_url ); } } return false; } /* ====================================================== / File Upload related funcs ====================================================== */ /* ====================================================== File Slots helpers ====================================================== */ function zeroBSCRM_fileSlots_getFileSlots($objType=1){ global $zbs; $fileSlots = array(); $settings = zeroBSCRM_getSetting('customfields'); $cfbInd = 1; switch ($objType){ case 1: if (isset($settings['customersfiles']) && is_array($settings['customersfiles']) && count($settings['customersfiles']) > 0){ foreach ($settings['customersfiles'] as $cfb){ $cfbName = ''; if (isset($cfb[0])) $cfbName = $cfb[0]; $key = $zbs->DAL->makeSlug($cfbName); // $cfbInd if (!empty($key)){ $fileSlots[] = array('key'=>$key,'name'=>$cfbName); $cfbInd++; } } } break; } return $fileSlots; } // returns the slot (if assigned) of a given file function zeroBSCRM_fileslots_fileSlot($file='',$objID=-1,$objType=1){ // get all slotted files for contact/obj if ($objID > 0 && !empty($file)){ global $zbs; $fileSlots = zeroBSCRM_fileslots_allSlots($objID,$objType); // cycle through if (count($fileSlots) > 0){ foreach ($fileSlots as $fsKey => $fsFile){ if ($fsFile == $file) return $fsKey; } } } return false; } // returns all slots (if assigned) of a given obj(contact) function zeroBSCRM_fileslots_allSlots($objID=-1,$objType=1){ if ($objID > 0){ global $zbs; $fileSlots = zeroBSCRM_fileSlots_getFileSlots(ZBS_TYPE_CONTACT); $ret = array(); if (count($fileSlots) > 0){ foreach ($fileSlots as $fs){ $ret[$fs['key']] = zeroBSCRM_fileslots_fileInSlot($fs['key'],$objID,$objType); } } return $ret; } return false; } // returns a file for a slot function zeroBSCRM_fileslots_fileInSlot($fileSlot='',$objID=-1,$objType=1){ if ($objID > 0){ global $zbs; return $zbs->DAL->meta($objType,$objID,'cfile_'.$fileSlot); } return false; } // adds a file to a slot function zeroBSCRM_fileslots_addToSlot($fileSlot='',$file='',$objID=-1,$objType=1,$overrite=false){ if ($objID > 0){ //echo '<br>zeroBSCRM_fileslots_addToSlot '.$fileSlot.' '.$file.' '.$objID.' ext:'.zeroBSCRM_fileslots_fileInSlot($fileSlot,$objID).'!'; global $zbs; // check existing? if (!$overrite){ $existingFile = zeroBSCRM_fileslots_fileInSlot($fileSlot,$objID); if (!empty($existingFile)) return false; } else { // overrite... so remove any if present before.. zeroBSCRM_fileslots_clearFileSlot($fileSlot,$objID,$objType); } // DAL2 add via meta (for now) $zbs->DAL->updateMeta($objType,$objID,'cfile_'.$fileSlot,$file); return true; } return false; } function zeroBSCRM_fileslots_clearFileSlot($fileSlot='',$objID=-1,$objType=1){ if ($objID > 0){ global $zbs; return $zbs->DAL->deleteMeta(array( 'objtype' => $objType, 'objid' => $objID, 'key' => 'cfile_'.$fileSlot )); } return false; } function zeroBSCRM_files_baseName($filePath='',$privateRepo=false){ $file = ''; if (!empty($filePath)){ $file = basename($filePath); if ($privateRepo) $file = substr($file,strpos($file, '-')+1); } return $file; } /* ====================================================== / File Slots helpers ====================================================== */ // gives an hashed filename+salt that is generally suitable for filesystems function jpcrm_get_hashed_filename( $filename, $suffix='' ) { global $zbs; $zbs->load_encryption(); $salt = $zbs->encryption->get_encryption_key( 'filename' ); $hashed_filename = $zbs->encryption->hash( $filename . $salt ) . $suffix; return $hashed_filename; } /** * Checks legitimacy (in so far as practicable) of an uploaded file * With default 'setting' params, checks against the core functions: * `zeroBS_acceptableFileTypeMIMEArr()` and `zeroBS_acceptableFileTypeListArr()` * (Which reflect the core setting) * * @param $FILE * @param $check_file_extension string|array - if string, can be single, e.g. `.pdf`, if array, can be multiple strings * @param $check_mime_type string|array - if string, can be single, e.g. `application/pdf`, if array, can be multiple strings */ function jpcrm_file_check_mime_extension( $FILE, $check_file_extension = 'setting', $check_mime_type = 'setting' ){ // expects $_FILES type array (e.g. pass $_FILES['zbsc_file_attachment']) if ( !is_array( $FILE ) || !isset( $FILE['name'] ) || !isset( $FILE['type'] ) || !isset( $FILE['tmp_name'] ) ){ return false; } // check file extension // retrieve settings, or prepare an array of acceptable file extensions from passed string/array if ( $check_file_extension == 'setting' ){ $check_file_extension = zeroBS_acceptableFileTypeListArr(); } elseif ( $check_file_extension != 'setting' && !is_array( $check_file_extension ) ){ $check_file_extension = array( $check_file_extension ); } // check actual extension if ( !in_array( '.' . pathinfo( $FILE['name'], PATHINFO_EXTENSION ), $check_file_extension ) ){ return false; } // check mime // retrieve settings, or prepare an array of acceptable file extensions from passed string/array if ( $check_mime_type == 'setting' ){ $check_mime_type = zeroBS_acceptableFileTypeMIMEArr(); } elseif ( $check_mime_type != 'setting' && !is_array( $check_mime_type ) ){ $check_mime_type = array( $check_mime_type ); } // catch 'all' legacy solution which (perhaps dangerously) sidesteps this check // will do mime check if legacy 'all' is empty, which includes false, 0, and !isset() if ( empty( $check_mime_type['all'] ) ) { // check actual mime type if ( ! in_array( $FILE['type'], $check_mime_type ) ) { return false; } // also check the mime type directly inferred from the uploaded file // note: we don't check this type against $FILE['type'] because it // doesn't really matter if they are different but both accepted types $tmp_file_type = jpcrm_get_mimetype( $FILE['tmp_name'] ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase if ( ! in_array( $tmp_file_type, $check_mime_type ) ) { return false; } } return true; }
projects/plugins/crm/includes/class-crm-exception.php
<?php /** * Jetpack CRM Exception Class * Extends Exception to provide additional data. * */ namespace Automattic\JetpackCRM; defined( 'ZEROBSCRM_PATH' ) || exit; /** * CRM exception class. */ class CRM_Exception extends \Exception { /** * Sanitized error code. * * @var string */ protected $error_code; /** * Error extra data. * * @var array */ protected $error_data; /** * Setup exception. * * @param string $code Machine-readable error code, e.g `segment_condition_produces_no_args`. * @param string $message User-friendly translated error message, e.g. 'Segment Condition produces no filtering arguments'. * @param array $data Extra error data. */ public function __construct( $code, $message, $data = array() ) { $this->error_code = $code; $this->error_data = $data; parent::__construct( $message . ' (' . $code . ')', 0, null ); } /** * Returns the error code. * * @return string */ public function get_error_code() { return $this->error_code; } /** * Returns error data. * * @return array */ public function get_error_data() { return $this->error_data; } }
projects/plugins/crm/includes/ZeroBSCRM.MetaBoxes3.Locked.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V3.0 * * Copyright 2020 Automattic * * Date: 14/06/2019 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== DB MIGRATION Helper - Lock Metaboxes Locks metaboxes so no edits can be enacted while migration in process (DAL2, not yet v3.0) ====================================================== */ /* ====================================================== Init Func ====================================================== */ function zeroBSCRM_LockMetaboxSetup(){ // Lock all CPT Metabox edit pages: $zeroBS__Metabox_Lock = new zeroBS__Metabox_Lock( __FILE__, array('zerobs_customer','zerobs_company','zerobs_invoice','zerobs_quote','zerobs_transaction','zerobs_form','zerobs_mailcampaign','zerobs_quotetemplate','zerobs_event') ); // Lock DAL2 Contacts edit page: $zeroBS__Metabox_ContactLock = new zeroBS__Metabox_ContactLock(__FILE__); // lock the DAL2 Contact view page: $zeroBS__Metabox_ContactViewLock = new zeroBS__Metabox_ContactViewLock(__FILE__); // add global to learn menu: add_action( 'zerobscrm-subtop-menu', 'zeroBSCRM_lockToLearnMenu' ); } add_action( 'admin_init','zeroBSCRM_LockMetaboxSetup'); /* ====================================================== / Init Func ====================================================== */ function zeroBSCRM_lockToLearnMenu(){ global $zbs; // if not the migration page if (zeroBSCRM_isAdminPage() && !zeroBS_isPage(array('admin.php'),false,array($zbs->slugs['migratedal3']))){ // Migration / IMPERITIVE notifications ?><div id="zbs-lockout-top-menu-notification" style="margin: 1em;margin-right:2em;margin-top: 3em;"><?php echo zeroBSCRM_UI2_messageHTML('small warning',__('CRM Database Update Needed',"zero-bs-crm"),__('Your CRM data needs to be migrated, you will not be able to edit CRM information until your database has been migrated.',"zero-bs-crm"),'disabled warning sign','zbsNope'); if (current_user_can( 'manage_options' )){ ?><a href="<?php echo esc_url( admin_url('admin.php?page='.$zbs->slugs['migratedal3']) ); ?>" class="ui button small blue"><?php esc_html_e('Go to Migration',"zero-bs-crm"); ?></a><?php } ?><hr /> </div><?php } } /* ====================================================== LOCKED (v2) Metabox ====================================================== */ class zeroBS__Metabox_Lock { static $instance; private $postTypes; public function __construct( $plugin_file, $typesToLock=array('zerobs_customer') ) { self::$instance = $this; $this->postTypes = $typesToLock; add_action( 'add_meta_boxes', array( $this, 'initMetaBox' ) ); } public function initMetaBox(){ if (count($this->postTypes) > 0) foreach ($this->postTypes as $pt){ #} pass an arr $callBackArr = array($this,$pt); add_meta_box( 'wpzbsc_lockdetails_'.$pt, __('Locked',"zero-bs-crm"), array( $this, 'print_meta_box' ), $pt, 'normal', 'high', $callBackArr ); } } public function print_meta_box( $post, $metabox ) { #} Display locked msg + hide EVERYTHING else :) global $zbs; ?><div id="zbs-lockout" class="ui modal"> <div class="content"> <?php echo zeroBSCRM_UI2_messageHTML('large info',__('CRM Database Update Needed',"zero-bs-crm"),__('Your CRM data needs to be migrated, you will not be able to edit CRM information until your database has been migrated.',"zero-bs-crm"),'disabled warning sign','zbsNope'); ?></div><div class="actions"><?php if (current_user_can( 'manage_options' )){ ?><a href="<?php echo esc_url( admin_url('admin.php?page='.$zbs->slugs['migratedal3']) ); ?>" class="ui button large blue"><?php esc_html_e('Go to Migration',"zero-bs-crm"); ?></a><?php } ?></div> </div> <style> #postbox-container-1, #postbox-container-2, #titlewrap { display:none !important;} </style> <script type="text/javascript"> jQuery(function(){ jQuery('#zbs-lockout').modal({closable:false}).modal('show').modal('refresh'); }); </script><?php } } /* ====================================================== / Lock v2 Metabox ====================================================== */ /* ====================================================== Lock (our non-cpt) Contact edit screen ====================================================== */ class zeroBS__Metabox_ContactLock extends zeroBS__Metabox{ public function __construct( $plugin_file ) { // DAL3 switched for objType $this->postType = 'zerobs_customer'; $this->objType = 'contact'; $this->metaboxID = 'zerobs-lockdown'; $this->metaboxTitle = 'Locked'; $this->metaboxScreen = 'zbs-add-edit-contact-edit'; //'zerobs_edit_contact'; // we can use anything here as is now using our func $this->metaboxArea = 'normal'; $this->metaboxLocation = 'high'; $this->capabilities = array( 'can_hide' => true, // can be hidden 'areas' => array('side'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => false, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true // can be minimised ); // call this $this->initMetabox(); } public function html( $contact, $metabox ) { #} Display locked msg + hide EVERYTHING else :) global $zbs; ?><div id="zbs-lockout" class="ui modal"> <div class="content"> <?php echo zeroBSCRM_UI2_messageHTML('large info',__('CRM Database Update Needed',"zero-bs-crm"),__('Your CRM data needs to be migrated, you will not be able to edit CRM information until your database has been migrated.',"zero-bs-crm"),'disabled warning sign','zbsNope'); ?></div><div class="actions"><?php if (current_user_can( 'manage_options' )){ ?><a href="<?php echo esc_url( admin_url('admin.php?page='.$zbs->slugs['migratedal3']) ); ?>" class="ui button large blue"><?php esc_html_e('Go to Migration',"zero-bs-crm"); ?></a><?php } ?></div> </div> <style> #zbs-edit-wrap { display:none !important;} </style> <script type="text/javascript"> jQuery(function(){ jQuery('#zbs-lockout').modal({closable:false}).modal('show').modal('refresh'); }); </script><?php } public function save_data( $contact_id, $contact ) { return $contact; } } /* ====================================================== / Lock (our non-cpt) Contact edit screen ====================================================== */ /* ====================================================== Lock Contact view screen ====================================================== */ class zeroBS__Metabox_ContactViewLock extends zeroBS__Metabox{ public function __construct( $plugin_file ) { // DAL3 switched for objType $this->postType = 'zerobs_customer'; $this->objType = 'contact'; $this->metaboxID = 'zerobs-lockdown'; $this->metaboxTitle = 'Locked'; $this->metaboxScreen = 'zbs-view-contact'; //'zerobs_edit_contact'; // we can use anything here as is now using our func $this->metaboxArea = 'side'; $this->metaboxLocation = 'high'; $this->capabilities = array( 'can_hide' => true, // can be hidden 'areas' => array('side'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => false, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true // can be minimised ); // call this $this->initMetabox(); } public function html( $contact, $metabox ) { #} Display locked msg + hide EVERYTHING else :) global $zbs; ?><div id="zbs-lockout" class="ui modal"> <div class="content"> <?php echo zeroBSCRM_UI2_messageHTML('large info',__('CRM Database Update Needed',"zero-bs-crm"),__('Your CRM data needs to be migrated, you will not be able to edit CRM information until your database has been migrated.',"zero-bs-crm"),'disabled warning sign','zbsNope'); ?></div><div class="actions"><?php if (current_user_can( 'manage_options' )){ ?><a href="<?php echo esc_url( admin_url('admin.php?page='.$zbs->slugs['migratedal3']) ); ?>" class="ui button large blue"><?php esc_html_e('Go to Migration',"zero-bs-crm"); ?></a><?php } ?></div> </div> <style> .ui.divided.grid { display:none !important;} </style> <script type="text/javascript"> jQuery(function(){ jQuery('#zbs-lockout').modal({closable:false}).modal('show').modal('refresh'); }); </script><?php } public function save_data( $contact_id, $contact ) { return $contact; } } /* ====================================================== / Lock Contact view screen ====================================================== */ #} Mark as included :) define('ZBSCRM_INC_LOCKMB',true);
projects/plugins/crm/includes/ZeroBSCRM.SemanticUIHelpers.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V2.2 * * Copyright 2017 ZeroBSCRM.com * * Date: 30/07/2017 */ #} Outputs html label /* $labelClass = yellow image etc. https://semantic-ui.com/elements/label.html */ function zeroBSCRM_UI2_label($labelClass='',$imgHTML='',$html='',$detailHTML='',$id=''){ $ret = '<div class="ui '.$labelClass.' label"'; if (!empty($id)) $ret .= ' id="'.$id.'"'; $ret .= '>'; if (!empty($imgHTML)) $ret .= $imgHTML; $ret .= $html; if (!empty($detailHTML)) $ret .= '<div class="detail">'.$detailHTML.'</div>'; $ret .= '</div>'; return $ret; } function zeroBSCRM_faSocialToSemantic($faClass=''){ switch ($faClass){ case 'fa-twitter': return 'twitter icon'; break; case 'fa-facebook': return 'facebook icon'; break; case 'fa-linkedin': return 'linkedin icon'; break; default: return $faClass; break; } } #} To match the key to the flag (for button class) the above one pops "icon" on the end function zeroBSCRM_getSocialIcon($key = ''){ if($key != ''){ $socials = array( 'fb' => 'facebook', 'tw' => 'twitter', 'li' => 'linkedin', 'vk' => 'vk', 'gp' => 'google plus', 'in' => 'instagram', 'yt' => 'youtube' ); if(array_key_exists($key, $socials)){ return $socials[$key]; } } return false; } /** * Generates HTML markup for a message box. * * @param string $msg_class CSS class for the message box. * @param string $msg_header Optional. Header text for the message box. * @param string $msg Main content of the message box. * @param string $icon_class Optional. CSS class for an icon to be displayed in the message box. * @param string $id Optional. ID attribute for the message box element. * * @return string HTML markup for the message box. * @link https://semantic-ui.com/collections/message.html Semantic UI Message Documentation. */ function zeroBSCRM_UI2_messageHTML( $msg_class = '', $msg_header = '', $msg = '', $icon_class = '', $id = '' ) { if ( ! empty( $icon_class ) ) { $msg_class .= ' icon'; } $ret = '<div style="box-shadow:unset; color:black;" class="ui ' . $msg_class . ' icon message jpcrm-div-message-box"'; if ( ! empty( $id ) ) { $ret .= ' id="' . $id . '"'; } $ret .= '>'; if ( ! empty( $icon_class ) ) { $ret .= '<i class="' . $icon_class . ' icon"></i>'; } $ret .= '<div class="content">'; if ( ! empty( $msg_header ) ) { $ret .= '<div style="color:black;" class="header">' . $msg_header . '</div>'; } $ret .= '<p>' . $msg . '</p></div></div>'; return $ret; } /** * Return HTML for a spinner centered in a container */ function jpcrm_loading_container() { return '<div class="empty-container-with-spinner"><div class="ui active centered inline loader"></div></div>'; } function zeroBSCRM_UI2_squareFeedbackUpsell($title='',$desc='',$linkStr='',$linkTarget='',$extraClasses=''){ $html = ''; $html .= '<div class="zbs-upgrade-banner '.$extraClasses.'">'; if (!empty($title)) $html .= '<h4>'.$title.'</h4>'; if (!empty($desc)) $html .= '<p>'.$desc.'</p>'; if (!empty($linkTarget) && !empty($linkStr)) $html .= '<a class="btn" href="'.$linkTarget.'" target="_blank">'.$linkStr.'</a>'; $html .= '</div>'; return $html; }
projects/plugins/crm/includes/ZeroBSCRM.DAL3.Obj.Companies.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V3.0+ * * Copyright 2020 Automattic * * Date: 14/01/19 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /** * ZBS DAL >> Companies * * @author Woody Hayday <hello@jetpackcrm.com> * @version 2.0 * @access public * @see https://jetpackcrm.com/kb */ class zbsDAL_companies extends zbsDAL_ObjectLayer { protected $objectType = ZBS_TYPE_COMPANY; protected $objectDBPrefix = 'zbsco_'; protected $objectIncludesAddresses = true; protected $include_in_templating = true; protected $objectModel = array( // ID 'ID' => array('fieldname' => 'ID', 'format' => 'int'), // site + team generics 'zbs_site' => array('fieldname' => 'zbs_site', 'format' => 'int'), 'zbs_team' => array('fieldname' => 'zbs_team', 'format' => 'int'), 'zbs_owner' => array('fieldname' => 'zbs_owner', 'format' => 'int'), // other fields 'status' => array( // db model: 'fieldname' => 'zbsco_status', 'format' => 'str', // output model 'input_type' => 'select', 'label' => 'Status', 'placeholder'=>'', 'options' => array( 'Lead', 'Customer', 'Refused' ), 'essential' => true, 'max_len' => 50, 'do_not_show_on_portal' => true ), 'name' => array( // db model: 'fieldname' => 'zbsco_name', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'Name', 'placeholder'=> 'e.g. NewCo', 'dal1key' => 'coname', 'essential' => true, 'force_unique' => true, // must be unique. This is required and breaking if true, 'not_empty' => true, 'max_len' => 100 ), 'addr1' => array( // db model: 'fieldname' => 'zbsco_addr1', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'Address Line 1', 'placeholder'=>'', 'area'=> 'Main Address', 'migrate'=>'addresses', 'max_len' => 200 ), 'addr2' => array( // db model: 'fieldname' => 'zbsco_addr2', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'Address Line 2', 'placeholder'=>'', 'area'=> 'Main Address', 'migrate'=>'addresses', 'max_len' => 200 ), 'city' => array( // db model: 'fieldname' => 'zbsc_city', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'City', 'placeholder'=> 'e.g. New York', 'area'=> 'Main Address', 'migrate'=>'addresses', 'max_len' => 100 ), 'county' => array( // db model: 'fieldname' => 'zbsco_county', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'County', 'placeholder'=> 'e.g. Kings County', 'area'=> 'Main Address', 'migrate'=>'addresses', 'max_len' => 200 ), 'postcode' => array( // db model: 'fieldname' => 'zbsco_postcode', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'Post Code', 'placeholder'=> 'e.g. 10019', 'area'=> 'Main Address', 'migrate'=>'addresses', 'max_len' => 50 ), 'country' => array( // db model: 'fieldname' => 'zbsco_country', 'format' => 'str', // output model 'input_type' => 'selectcountry', 'label' => 'Country', 'placeholder'=>'', 'area'=> 'Main Address', 'migrate'=>'addresses', 'max_len' => 200 ), 'secaddr1' => array( // db model: 'fieldname' => 'zbsco_secaddr1', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'Address Line 1', 'placeholder'=>'', 'area'=> 'Second Address', 'migrate'=>'addresses', 'opt'=>'secondaddress', 'max_len' => 200, 'dal1key' => 'secaddr_addr1' // previous field name ), 'secaddr2' => array( // db model: 'fieldname' => 'zbsco_secaddr2', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'Address Line 2', 'placeholder'=>'', 'area'=> 'Second Address', 'migrate'=>'addresses', 'opt'=>'secondaddress', 'max_len' => 200, 'dal1key' => 'secaddr_addr2' // previous field name ), 'seccity' => array( // db model: 'fieldname' => 'zbsco_seccity', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'City', 'placeholder'=> 'e.g. Los Angeles', 'area'=> 'Second Address', 'migrate'=>'addresses', 'opt'=>'secondaddress', 'max_len' => 100, 'dal1key' => 'secaddr_city' // previous field name ), 'seccounty' => array( // db model: 'fieldname' => 'zbsco_seccounty', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'County', 'placeholder'=> 'e.g. Los Angeles', 'area'=> 'Second Address', 'migrate'=>'addresses', 'opt'=>'secondaddress', 'max_len' => 200, 'dal1key' => 'secaddr_county' // previous field name ), 'secpostcode' => array( // db model: 'fieldname' => 'zbsco_secpostcode', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'Post Code', 'placeholder'=> 'e.g. 90001', 'area'=> 'Second Address', 'migrate'=>'addresses', 'opt'=>'secondaddress', 'max_len' => 50, 'dal1key' => 'secaddr_postcode' // previous field name ), 'seccountry' => array( // db model: 'fieldname' => 'zbsco_seccountry', 'format' => 'str', // output model 'input_type' => 'selectcountry', 'label' => 'Country', 'placeholder'=>'', 'area'=> 'Second Address', 'migrate'=>'addresses', 'opt'=>'secondaddress', 'max_len' => 200, 'dal1key' => 'secaddr_country' // previous field name ), 'maintel' => array( // db model: 'fieldname' => 'zbsco_maintel', 'format' => 'str', // output model 'input_type' => 'tel', 'label' => 'Main Telephone', 'placeholder'=> 'e.g. 877 2733049', 'max_len' => 40 ), 'sectel' => array( // db model: 'fieldname' => 'zbsco_sectel', 'format' => 'str', // output model 'input_type' => 'tel', 'label' => 'Secondary Telephone', 'placeholder'=> 'e.g. 877 2733049', 'max_len' => 40 ), 'email' => array( // db model: 'fieldname' => 'zbsco_email', 'format' => 'str', // output model 'input_type' => 'email', 'label' => 'Main Email Address', 'placeholder'=> 'e.g. hello@company.com', 'max_len' => 200, 'force_unique' => true, // must be unique. This is required and breaking if true 'can_be_blank' => true, 'do_not_show_on_portal' => true ), // ... just removed for DAL3 :) should be custom field anyway by this point 'wpid' => array('fieldname' => 'zbsco_wpid', 'format' => 'int'), 'avatar' => array('fieldname' => 'zbsco_avatar', 'format' => 'str'), 'tw' => array( 'fieldname' => 'zbsco_tw', 'format' => 'str', 'max_len' => 100 ), 'li' => array( 'fieldname' => 'zbsco_li', 'format' => 'str', 'max_len' => 300 ), 'fb' => array( 'fieldname' => 'zbsco_fb', 'format' => 'str', 'max_len' => 200 ), 'created' => array('fieldname' => 'zbsco_created', 'format' => 'uts'), 'lastupdated' => array('fieldname' => 'zbsco_lastupdated', 'format' => 'uts'), 'lastcontacted' => array('fieldname' => 'zbsco_lastcontacted', 'format' => 'uts'), ); function __construct($args=array()) { #} =========== LOAD ARGS ============== $defaultArgs = array( //'tag' => false, ); foreach ($defaultArgs as $argK => $argV){ $this->$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $this->$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$this->$argK = $newData;} else { $this->$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= add_filter( 'jpcrm_listview_filters', array( $this, 'add_listview_filters' ) ); } /** * Adds items to listview filter using `jpcrm_listview_filters` hook. * * @param array $listview_filters Listview filters. */ public function add_listview_filters( $listview_filters ) { global $zbs; $quick_filter_settings = $zbs->settings->get( 'quickfiltersettings' ); // Add 'not-contacted-in-x-days'. if ( ! empty( $quick_filter_settings['notcontactedinx'] ) && $quick_filter_settings['notcontactedinx'] > 0 ) { $days = (int) $quick_filter_settings['notcontactedinx']; $listview_filters[ ZBS_TYPE_COMPANY ]['general'][ 'notcontactedin' . $days ] = sprintf( // translators: %s is the number of days __( 'Not Contacted in %s days', 'zero-bs-crm' ), $days ); } // Add 'olderthan-x-days'. if ( ! empty( $quick_filter_settings['olderthanx'] ) && $quick_filter_settings['olderthanx'] > 0 ) { $days = (int) $quick_filter_settings['olderthanx']; $listview_filters[ ZBS_TYPE_COMPANY ]['general'][ 'olderthan' . $days ] = sprintf( // translators: %s is the number of days __( 'Older than %s days', 'zero-bs-crm' ), $days ); } // Add statuses if enabled. if ( $zbs->settings->get( 'filtersfromstatus' ) === 1 ) { $statuses = zeroBSCRM_getCompanyStatuses(); foreach ( $statuses as $status ) { $listview_filters[ ZBS_TYPE_COMPANY ]['status'][ 'status_' . $status ] = $status; } } return $listview_filters; } // generic get Company (by ID) // Super simplistic wrapper used by edit page etc. (generically called via dal->contacts->getSingle etc.) public function getSingle($ID=-1){ return $this->getCompany($ID); } // generic get contact (by ID list) // Super simplistic wrapper used by MVP Export v3.0 public function getIDList($IDs=false){ return $this->getCompanies(array( 'inArr' => $IDs, 'withCustomFields' => true, 'page' => -1, 'perPage' => -1 )); } // generic get (EVERYTHING) // expect heavy load! public function getAll($IDs=false){ return $this->getCompanies(array( 'withCustomFields' => true, 'sortByField' => 'ID', 'sortOrder' => 'ASC', 'page' => -1, 'perPage' => -1, )); } // generic get count of (EVERYTHING) public function getFullCount(){ return $this->getCompanies(array( 'count' => true, 'page' => -1, 'perPage' => -1, )); } /** * Retrieves the company ID by its name. * * @param string $name The name of the company whose ID is to be retrieved. * @return int|bool Returns the ID of the company if found, false otherwise. * * @throws Exception Catches and handles exceptions, logging SQL errors. * * @since 6.2.0 */ public function get_company_id_by_name( $name ) { global $ZBSCRM_t; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase global $wpdb; try { $query = $this->prepare( 'SELECT ID FROM ' . $ZBSCRM_t['companies'] . ' WHERE zbsco_name LIKE %s', $name ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $result = $wpdb->get_row( $query, OBJECT ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.NotPrepared if ( isset( $result ) && ( $result->ID ) ) { return $result->ID; } } catch ( Exception $e ) { $this->catchSQLError( $e ); } return false; } /** * returns full company line +- details * * @param int id company id * @param array $args Associative array of arguments * * @return array company object */ public function getCompany($id=-1,$args=array()){ global $zbs; #} =========== LOAD ARGS ============== $defaultArgs = array( 'email' => false, // if id -1 and email given, will return based on email 'name' => false, // if id -1 and name given, will return based on name // if theset wo passed, will search based on these 'externalSource' => false, 'externalSourceUID' => false, // with what? 'withCustomFields' => true, 'withQuotes' => false, 'withInvoices' => false, 'withTransactions' => false, 'withTasks' => false, //'withLogs' => false, 'withLastLog' => false, 'withTags' => false, 'withOwner' => false, 'withValues' => false, // if passed, returns with 'total' 'invoices_total' 'transactions_total' etc. (requires getting all obj, use sparingly) 'withContacts' => true, // return ['contact'] objs 'withExternalSources' => false, 'withExternalSourcesGrouped' => false, // permissions 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_COMPANY), // this'll let you not-check the owner of obj // returns scalar ID of line 'onlyID' => false, 'fields' => false // false = *, array = fieldnames ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} Check ID $id = (int)$id; if ( (!empty($id) && $id > 0) || (!empty($email)) || ( ! empty( $name ) ) || (!empty($externalSource) && !empty($externalSourceUID)) ){ global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); $extraSelect = ''; #} ============= PRE-QUERY ============ #} Custom Fields if ($withCustomFields && !$onlyID){ #} Retrieve any cf $custFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_COMPANY)); #} Cycle through + build into query if (is_array($custFields)) foreach ($custFields as $cK => $cF){ // add as subquery $extraSelect .= ',(SELECT zbscf_objval FROM '.$ZBSCRM_t['customfields']." WHERE zbscf_objid = company.ID AND zbscf_objkey = %s AND zbscf_objtype = %d LIMIT 1) '".$cK."'"; // add params $params[] = $cK; $params[] = ZBS_TYPE_COMPANY; } } // Add any addr custom fields for addr1+addr2 $addrCustomFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_ADDRESS)); if ($withCustomFields && !$onlyID && is_array($addrCustomFields) && count($addrCustomFields) > 0){ foreach ($addrCustomFields as $cK => $cF){ // custom field key $cfKey = 'addr_'.$cK; $cfKey2 = 'secaddr_'.$cK; // address custom field (e.g. 'house name') it'll be passed here as 'house-name' // ... problem is mysql does not like that :) so we have to chage here: // in this case we prepend address cf's with addr_ and we switch - for _ $cKey = 'addrcf_'.str_replace('-','_',$cK); $cKey2 = 'secaddrcf_'.str_replace('-','_',$cK); // addr1 // add as subquery $extraSelect .= ',(SELECT zbscf_objval FROM '.$ZBSCRM_t['customfields']." WHERE zbscf_objid = company.ID AND zbscf_objkey = %s AND zbscf_objtype = %d) ".$cKey; // add params $params[] = $cfKey; $params[] = ZBS_TYPE_COMPANY; // addr2 // add as subquery $extraSelect .= ',(SELECT zbscf_objval FROM '.$ZBSCRM_t['customfields']." WHERE zbscf_objid = company.ID AND zbscf_objkey = %s AND zbscf_objtype = %d) ".$cKey2; // add params $params[] = $cfKey2; $params[] = ZBS_TYPE_COMPANY; } } // ==== TOTAL VALUES // Calculate total vals etc. with SQL if (!$onlyID && $withValues){ // arguably, if getting $withInvoices etc. may be more performant to calc this in php in AFTER loop, // ... for now as a fair guess, this'll be most performant: // ... we calc total by adding invs + trans below :) // only include transactions with statuses which should be included in total value: $transStatusQueryAdd = $this->DAL()->transactions->getTransactionStatusesToIncludeQuery(); // include invoices without deleted status in the total value for invoices_total_inc_deleted: $inv_status_query_add = $this->DAL()->invoices->get_invoice_status_except_deleted_for_query(); // quotes: $extraSelect .= ',(SELECT SUM(quotestotal.zbsq_value) FROM '.$ZBSCRM_t['quotes'].' as quotestotal WHERE quotestotal.ID IN (SELECT DISTINCT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = ".ZBS_TYPE_QUOTE." AND zbsol_objtype_to = ".ZBS_TYPE_COMPANY." AND zbsol_objid_to = company.ID)) as quotes_total"; // invs: $extraSelect .= ',(SELECT IFNULL(SUM(invstotal.zbsi_total),0) FROM ' . $ZBSCRM_t['invoices'] . ' as invstotal WHERE invstotal.ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_INVOICE . ' AND zbsol_objtype_to = ' . ZBS_TYPE_COMPANY . ' AND zbsol_objid_to = company.ID)' . $inv_status_query_add . ') as invoices_total'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // invs including deleted: $extraSelect .= ',(SELECT SUM(invstotalincdeleted.zbsi_total) FROM ' . $ZBSCRM_t['invoices'] . ' as invstotalincdeleted WHERE invstotalincdeleted.ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_INVOICE . ' AND zbsol_objtype_to = ' . ZBS_TYPE_COMPANY . ' AND zbsol_objid_to = company.ID)) as invoices_total_inc_deleted'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // invs count: $extraSelect .= ',(SELECT COUNT(ID) FROM ' . $ZBSCRM_t['invoices'] . ' WHERE ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_INVOICE . ' AND zbsol_objtype_to = ' . ZBS_TYPE_COMPANY . ' AND zbsol_objid_to = company.ID)' . $inv_status_query_add . ') as invoices_count'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // invs count including deleted: $extraSelect .= ',(SELECT COUNT(ID) FROM ' . $ZBSCRM_t['invoices'] . ' WHERE ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_INVOICE . ' AND zbsol_objtype_to = ' . ZBS_TYPE_COMPANY . ' AND zbsol_objid_to = company.ID)) as invoices_count_inc_deleted'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // trans (with status): $extraSelect .= ',(SELECT SUM(transtotal.zbst_total) FROM '.$ZBSCRM_t['transactions'].' as transtotal WHERE transtotal.ID IN (SELECT DISTINCT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = ".ZBS_TYPE_TRANSACTION." AND zbsol_objtype_to = ".ZBS_TYPE_COMPANY." AND zbsol_objid_to = company.ID)".$transStatusQueryAdd.") as transactions_total"; // paid balance against invs (also in getCompany) // (this allows us to subtract from totals to get a true figure where transactions are part/whole payments for invs) /* This selects transactions where there is a link to an invoice where that invoice has a link to this contact: ========== SELECT * FROM wp_zbs_transactions trans WHERE trans.ID IN ( SELECT DISTINCT zbsol_objid_from FROM `wp_zbs_object_links` WHERE zbsol_objtype_from = 5 AND zbsol_objtype_to = 4 AND zbsol_objid_to IN ( SELECT DISTINCT zbsol_objid_from FROM `wp_zbs_object_links` WHERE zbsol_objtype_from = 4 AND zbsol_objtype_to = 1 AND zbsol_objid_to = 1 ) ) */ $extraSelect .= ',(SELECT SUM(assignedtranstotal.zbst_total) FROM '.$ZBSCRM_t['transactions'].' assignedtranstotal WHERE assignedtranstotal.ID IN '; $extraSelect .= '(SELECT DISTINCT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks'].' WHERE zbsol_objtype_from = '.ZBS_TYPE_TRANSACTION.' AND zbsol_objtype_to = '.ZBS_TYPE_INVOICE.' AND zbsol_objid_to IN '; $extraSelect .= '(SELECT DISTINCT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks'].' WHERE zbsol_objtype_from = '.ZBS_TYPE_INVOICE.' AND zbsol_objtype_to = '.ZBS_TYPE_COMPANY.' AND zbsol_objid_to = company.ID)'; $extraSelect .= ')'.$transStatusQueryAdd.') as transactions_paid_total'; } // ==== / TOTAL VALUES $selector = 'company.*'; if (isset($fields) && is_array($fields)) { $selector = ''; // always needs id, so add if not present if (!in_array('ID',$fields)) $selector = 'company.ID'; foreach ($fields as $f) { if (!empty($selector)) $selector .= ','; $selector .= 'company.'.$f; } } else if ($onlyID){ $selector = 'company.ID'; } #} ============ / PRE-QUERY =========== #} Build query $query = "SELECT ".$selector.$extraSelect." FROM ".$ZBSCRM_t['companies'].' as company'; #} ============= WHERE ================ if (!empty($id) && $id > 0){ #} Add ID $wheres['ID'] = array('ID','=','%d',$id); } if (!empty($email)){ $emailWheres = array(); // simple, inc AKA (even tho not in UI yet :)) //nope$wheres['emailcheck'] = array('zbsco_email','=','%s',$email); #} Add ID $emailWheres['emailcheck'] = array('zbsco_email','=','%s',$email); #} Check AKA $emailWheres['email_alias'] = array('ID','IN',"(SELECT aka_id FROM ".$ZBSCRM_t['aka']." WHERE aka_type = ".ZBS_TYPE_COMPANY." AND aka_alias = %s)",$email); // This generates a query like 'zbsc_email = %s OR zbsc_email2 = %s', // which we then need to include as direct subquery (below) in main query :) $emailSearchQueryArr = $this->buildWheres($emailWheres,'',array(),'OR',false); if (is_array($emailSearchQueryArr) && isset($emailSearchQueryArr['where']) && !empty($emailSearchQueryArr['where'])){ // add it $wheres['direct'][] = array('('.$emailSearchQueryArr['where'].')',$emailSearchQueryArr['params']); } } if (!empty($name)){ // simple $wheres['name'] = array('zbsco_name','=','%s',$name); } if (!empty($externalSource) && !empty($externalSourceUID)){ $wheres['extsourcecheck'] = array('ID','IN','(SELECT DISTINCT zbss_objid FROM '.$ZBSCRM_t['externalsources']." WHERE zbss_objtype = ".ZBS_TYPE_COMPANY." AND zbss_source = %s AND zbss_uid = %s)",array($externalSource,$externalSourceUID)); } #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort('ID','DESC') . $this->buildPaging(0,1); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_row($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret Results (ROW) if (isset($potentialRes) && isset($potentialRes->ID)) { #} Has results, tidy + return #} Only ID? return it directly if ($onlyID) return $potentialRes->ID; // tidy if (is_array($fields)){ // guesses fields based on table col names $res = $this->lazyTidyGeneric($potentialRes); } else { // proper tidy $res = $this->tidy_company($potentialRes,$withCustomFields); } // TWO methods here, this feels more "common sense" (other commented out below.) if ($withInvoices){ #} only gets first 100? //DAL3 ver, more perf, gets all $res['invoices'] = $zbs->DAL->invoices->getInvoices(array( 'assignedCompany' => $potentialRes->ID, // assigned to company id (int) 'page' => -1, 'perPage' => -1, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_INVOICE) )); } if ($withQuotes){ //DAL3 ver, more perf, gets all $res['quotes'] = $zbs->DAL->quotes->getQuotes(array( 'assignedCompany' => $potentialRes->ID, // assigned to company id (int) 'page' => -1, 'perPage' => -1, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_QUOTE) )); } #} ... brutal for mvp #DB1LEGACY (TOMOVE) if ($withTransactions){ //DAL3 ver, more perf, gets all $res['transactions'] = $zbs->DAL->transactions->getTransactions(array( 'assignedCompany' => $potentialRes->ID, // assigned to company id (int) 'page' => -1, 'perPage' => -1, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_TRANSACTION) )); } /* #} With quotes? if ($withQuotes){ // add all quotes lines $res['quotes'] = $this->DAL()->getObjsLinkedToObj(array( 'objtypefrom' => ZBS_TYPE_QUOTE, // quote 'objtypeto' => ZBS_TYPE_COMPANY, // company 'objfromid' => $potentialRes->ID)); } #} With invoices? if ($withQuotes){ // add all invoices lines $res['invoices'] = $this->DAL()->getObjsLinkedToObj(array( 'objtypefrom' => ZBS_TYPE_INVOICE, // invoice 'objtypeto' => ZBS_TYPE_COMPANY, // company 'objfromid' => $potentialRes->ID)); } #} With transactions? if ($withTransactions){ // add all transactions lines $res['transactions'] = $this->DAL()->getObjsLinkedToObj(array( 'objtypefrom' => ZBS_TYPE_TRANSACTION, // transaction 'objtypeto' => ZBS_TYPE_COMPANY, // company 'objfromid' => $potentialRes->ID)); } */ #} With most recent log? #DB1LEGACY (TOMOVE) if ($withLastLog){ $res['lastlog'] = $this->DAL()->logs->getLogsForObj(array( 'objtype' => ZBS_TYPE_COMPANY, 'objid' => $potentialRes->ID, 'incMeta' => true, 'sortByField' => 'zbsl_created', 'sortOrder' => 'DESC', 'page' => 0, 'perPage' => 1 )); } if ($withContacts){ // add all assigned contacts/companies $res['contacts'] = $this->DAL()->contacts->getContacts(array( 'isLinkedToObjType'=>ZBS_TYPE_COMPANY, 'isLinkedToObjID'=>$potentialRes->ID, 'page'=>-1, 'perPage'=>100, // commonsense cap 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); } if ($withTags){ // add all tags lines $res['tags'] = $this->DAL()->getTagsForObjID(array('objtypeid'=>ZBS_TYPE_COMPANY,'objid'=>$potentialRes->ID)); } #} With Assigned? if ($withOwner){ $res['owner'] = zeroBS_getOwner($potentialRes->ID,true,'zerobs_company',$potentialRes->zbs_owner); } #} With Tasks? if ($withTasks){ //DAL3 ver, more perf, gets all $res['tasks'] = $zbs->DAL->events->getEvents(array( 'assignedCompany' => $potentialRes->ID, // assigned to company id (int) 'page' => -1, 'perPage' => -1, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_TASK), 'sortByField' => 'zbse_start', 'sortOrder' => 'DESC', 'withAssigned' => false // no need, it's assigned to this obj already )); } // simplistic, could be optimised (though low use means later.) if ( $withExternalSources ){ $res['external_sources'] = $zbs->DAL->getExternalSources( array( 'objectID' => $potentialRes->ID, 'objectType' => ZBS_TYPE_COMPANY, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership( ZBS_TYPE_COMPANY ) )); } if ( $withExternalSourcesGrouped ){ $res['external_sources'] = $zbs->DAL->getExternalSources( -1, array( 'objectID' => $potentialRes->ID, 'objectType' => ZBS_TYPE_COMPANY, 'grouped_by_source' => true, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership( ZBS_TYPE_COMPANY ) )); } return $res; } } // / if ID return false; } /** * returns company detail lines * * @param array $args Associative array of arguments * * @return array of company lines */ public function getCompanies($args=array()){ global $zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( // Search/Filtering (leave as false to ignore) 'searchPhrase' => '', // searches which fields? 'inArr' => false, 'isTagged' => false, // 1x INT OR array(1,2,3) 'isNotTagged' => false, // 1x INT OR array(1,2,3) 'ownedBy' => false, 'externalSource' => false, // e.g. paypal 'olderThan' => false, // uts 'newerThan' => false, // uts 'hasStatus' => false, // Lead (this takes over from the quick filter post 19/6/18) 'otherStatus' => false, // status other than 'Lead' 'hasContact' => false, // has a contact of this ID associated with it 'quickFilters' => false, // booo // addr 'inCounty' => false, // Hertfordshire 'inPostCode' => false, // AL1 1AA 'inCountry' => false, // United Kingdom 'notInCounty' => false, // Hertfordshire 'notInPostCode' => false, // AL1 1AA 'notInCountry' => false, // United Kingdom // generic assignments - requires both // Where the link relationship is OBJECT -> CONTACT 'hasObjIDLinkedTo' => false, // e.g. quoteid 123 'hasObjTypeLinkedTo' => false, // e.g. ZBS_TYPE_QUOTE // generic assignments - requires both // Where the link relationship is CONTACT -> OBJECT 'isLinkedToObjID' => false, // e.g. quoteid 123 'isLinkedToObjType' => false, // e.g. ZBS_TYPE_QUOTE // returns 'count' => false, 'withCustomFields' => true, 'withQuotes' => false, // Will only be operable when Company<->Quotes established 'withInvoices' => false, 'withTransactions' => false, 'withTasks' => false, 'withTags' => false, 'withOwner' => false, 'withLogs' => false, 'withLastLog' => false, 'withValues' => false, // if passed, returns with 'total' 'invoices_total' 'transactions_total' etc. (requires getting all obj, use sparingly) 'withContacts' => true, // return ['contact'] objs 'withExternalSources' => false, 'withExternalSourcesGrouped' => false, 'simplified' => false, // returns just id,name,created (for typeaheads) 'onlyColumns' => false, // if passed (array('fname','lname')) will return only those columns (overwrites some other 'return' options). NOTE: only works for base fields (not custom fields) 'sortByField' => 'ID', 'sortOrder' => 'ASC', 'page' => 0, // this is what page it is (gets * by for limit) 'perPage' => 100, // permissions 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_COMPANY), // this'll let you not-check the owner of obj ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= global $ZBSCRM_t,$wpdb,$zbs; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); $joinQ = ''; $extraSelect = ''; $whereCase = 'AND'; #} ============= PRE-QUERY ============ #} Capitalise this $sortOrder = strtoupper($sortOrder); #} If just count, or simplified, turn off any extra gumpf if ( $count || $simplified ) { $withCustomFields = false; $withTags = false; $withOwner = false; $withLogs = false; $withLastLog = false; $withContacts = false; $withTasks = false; $withExternalSources = false; $withExternalSourcesGrouped = false; } #} If onlyColumns, validate if ($onlyColumns){ #} onlyColumns build out a field arr if (is_array($onlyColumns) && count($onlyColumns) > 0){ $onlyColumnsFieldArr = array(); foreach ($onlyColumns as $col){ // find db col key from field key (e.g. fname => zbsc_fname) $dbCol = ''; if (isset($this->objectModel[$col]) && isset($this->objectModel[$col]['fieldname'])) $dbCol = $this->objectModel[$col]['fieldname']; if (!empty($dbCol)){ $onlyColumnsFieldArr[$dbCol] = $col; } } } // if legit cols: if (isset($onlyColumnsFieldArr) && is_array($onlyColumnsFieldArr) && count($onlyColumnsFieldArr) > 0){ $onlyColumns = true; // If onlyColumns, turn off extras $withCustomFields = false; $withTags = false; $withOwner = false; $withLogs = false; $withLastLog = false; $withContacts = false; $withTasks = false; $withExternalSources = false; $withExternalSourcesGrouped = false; } else { // deny $onlyColumns = false; } } #} Custom Fields if ($withCustomFields){ #} Retrieve any cf $custFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_COMPANY)); #} Cycle through + build into query if (is_array($custFields)) foreach ($custFields as $cK => $cF){ // custom field (e.g. 'third name') it'll be passed here as 'third-name' // ... problem is mysql does not like that :) so we have to chage here: // in this case we prepend cf's with cf_ and we switch - for _ $cKey = 'cf_'.str_replace('-','_',$cK); // we also check the $sortByField in case that's the same cf if ($cK == $sortByField){ // sort by $sortByField = $cKey; // check if sort needs any CAST (e.g. numeric): $sortByField = $this->DAL()->build_custom_field_order_by_str( $sortByField, $cF ); } // add as subquery $extraSelect .= ',(SELECT zbscf_objval FROM '.$ZBSCRM_t['customfields']." WHERE zbscf_objid = company.ID AND zbscf_objkey = %s AND zbscf_objtype = %d LIMIT 1) ".$cKey; // add params $params[] = $cK; $params[] = ZBS_TYPE_COMPANY; } } // Add any addr custom fields for addr1+addr2 // no need if simpliefied or count parameters passed if (!$simplified && !$count && !$onlyColumns){ $addrCustomFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_ADDRESS)); if (is_array($addrCustomFields) && count($addrCustomFields) > 0){ foreach ($addrCustomFields as $cK => $cF){ // custom field key $cfKey = 'addr_'.$cK; $cfKey2 = 'secaddr_'.$cK; // address custom field (e.g. 'house name') it'll be passed here as 'house-name' // ... problem is mysql does not like that :) so we have to chage here: // in this case we prepend address cf's with addr_ and we switch - for _ $cKey = 'addrcf_'.str_replace('-','_',$cK); $cKey2 = 'secaddrcf_'.str_replace('-','_',$cK); // we also check the $sortByField in case that's the same cf if ($cfKey == $sortByField) $sortByField = $cKey; if ($cfKey2 == $sortByField) $sortByField = $cKey2; // addr 1 // add as subquery $extraSelect .= ',(SELECT zbscf_objval FROM '.$ZBSCRM_t['customfields']." WHERE zbscf_objid = company.ID AND zbscf_objkey = %s AND zbscf_objtype = %d) ".$cKey; // add params $params[] = $cfKey; $params[] = ZBS_TYPE_COMPANY; // addr 2 // add as subquery $extraSelect .= ',(SELECT zbscf_objval FROM '.$ZBSCRM_t['customfields']." WHERE zbscf_objid = company.ID AND zbscf_objkey = %s AND zbscf_objtype = %d) ".$cKey2; // add params $params[] = $cfKey2; $params[] = ZBS_TYPE_COMPANY; } } } // ==== TOTAL VALUES // Calculate total vals etc. with SQL if (!$simplified && !$count && $withValues && !$onlyColumns){ // arguably, if getting $withInvoices etc. may be more performant to calc this in php in AFTER loop, // ... for now as a fair guess, this'll be most performant: // ... we calc total by adding invs + trans below :) // only include transactions with statuses which should be included in total value: $transStatusQueryAdd = $this->DAL()->transactions->getTransactionStatusesToIncludeQuery(); // include invoices without deleted status in the total value for invoices_total_inc_deleted: $inv_status_query_add = $this->DAL()->invoices->get_invoice_status_except_deleted_for_query(); // When Company<->Quotes: // $extraSelect .= ',(SELECT SUM(quotestotal.zbsq_value) FROM '.$ZBSCRM_t['quotes'].' as quotestotal WHERE quotestotal.ID IN (SELECT DISTINCT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = ".ZBS_TYPE_QUOTE." AND zbsol_objtype_to = ".ZBS_TYPE_COMPANY." AND zbsol_objid_to = company.ID)) as quotes_total"; // invs: $extraSelect .= ',(SELECT IFNULL(SUM(invstotal.zbsi_total),0) FROM ' . $ZBSCRM_t['invoices'] . ' as invstotal WHERE invstotal.ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_INVOICE . ' AND zbsol_objtype_to = ' . ZBS_TYPE_COMPANY . ' AND zbsol_objid_to = company.ID)' . $inv_status_query_add . ') as invoices_total'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // invs including deleted: $extraSelect .= ',(SELECT SUM(invstotalincdeleted.zbsi_total) FROM ' . $ZBSCRM_t['invoices'] . ' as invstotalincdeleted WHERE invstotalincdeleted.ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_INVOICE . ' AND zbsol_objtype_to = ' . ZBS_TYPE_COMPANY . ' AND zbsol_objid_to = company.ID)) as invoices_total_inc_deleted'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // invs count: $extraSelect .= ',(SELECT COUNT(ID) FROM ' . $ZBSCRM_t['invoices'] . ' WHERE ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_INVOICE . ' AND zbsol_objtype_to = ' . ZBS_TYPE_COMPANY . ' AND zbsol_objid_to = company.ID)' . $inv_status_query_add . ') as invoices_count'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // invs count including deleted: $extraSelect .= ',(SELECT COUNT(ID) FROM ' . $ZBSCRM_t['invoices'] . ' WHERE ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_INVOICE . ' AND zbsol_objtype_to = ' . ZBS_TYPE_COMPANY . ' AND zbsol_objid_to = company.ID)) as invoices_count_inc_deleted'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // trans (with status): $extraSelect .= ',(SELECT SUM(transtotal.zbst_total) FROM '.$ZBSCRM_t['transactions'].' as transtotal WHERE transtotal.ID IN (SELECT DISTINCT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = ".ZBS_TYPE_TRANSACTION." AND zbsol_objtype_to = ".ZBS_TYPE_COMPANY." AND zbsol_objid_to = company.ID)".$transStatusQueryAdd.") as transactions_total"; // paid balance against invs (also in getCompany) // (this allows us to subtract from totals to get a true figure where transactions are part/whole payments for invs) /* This selects transactions where there is a link to an invoice where that invoice has a link to this contact: ========== SELECT * FROM wp_zbs_transactions trans WHERE trans.ID IN ( SELECT DISTINCT zbsol_objid_from FROM `wp_zbs_object_links` WHERE zbsol_objtype_from = 5 AND zbsol_objtype_to = 4 AND zbsol_objid_to IN ( SELECT DISTINCT zbsol_objid_from FROM `wp_zbs_object_links` WHERE zbsol_objtype_from = 4 AND zbsol_objtype_to = 1 AND zbsol_objid_to = 1 ) ) */ $extraSelect .= ',(SELECT SUM(assignedtranstotal.zbst_total) FROM '.$ZBSCRM_t['transactions'].' assignedtranstotal WHERE assignedtranstotal.ID IN '; $extraSelect .= '(SELECT DISTINCT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks'].' WHERE zbsol_objtype_from = '.ZBS_TYPE_TRANSACTION.' AND zbsol_objtype_to = '.ZBS_TYPE_INVOICE.' AND zbsol_objid_to IN '; $extraSelect .= '(SELECT DISTINCT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks'].' WHERE zbsol_objtype_from = '.ZBS_TYPE_INVOICE.' AND zbsol_objtype_to = '.ZBS_TYPE_COMPANY.' AND zbsol_objid_to = company.ID)'; $extraSelect .= ')'.$transStatusQueryAdd.') as transactions_paid_total'; } // ==== / TOTAL VALUES #} ============ / PRE-QUERY =========== #} Build query $query = "SELECT company.*".$extraSelect." FROM ".$ZBSCRM_t['companies'].' as company'.$joinQ; #} Count override if ($count) $query = "SELECT COUNT(company.ID) FROM ".$ZBSCRM_t['companies'].' as company'.$joinQ; #} simplified override if ($simplified) $query = "SELECT company.ID as id,company.zbsco_name as name,company.zbsco_created as created,company.zbsco_email as email FROM ".$ZBSCRM_t['companies'].' as company'.$joinQ; #} onlyColumns override if ($onlyColumns && is_array($onlyColumnsFieldArr) && count($onlyColumnsFieldArr) > 0){ $columnStr = ''; foreach ($onlyColumnsFieldArr as $colDBKey => $colStr){ if (!empty($columnStr)) $columnStr .= ','; // this presumes str is db-safe? could do with sanitation? $columnStr .= $colDBKey; } $query = "SELECT ".$columnStr." FROM ".$ZBSCRM_t['companies'].' as company'.$joinQ; } #} ============= WHERE ================ #} Add Search phrase if (!empty($searchPhrase)){ // search? - ALL THESE COLS should probs have index of FULLTEXT in db? $searchWheres = array(); $searchWheres['search_ID'] = array('ID','=','%d',$searchPhrase); $searchWheres['search_name'] = array('zbsco_name','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_email'] = array('zbsco_email','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_maintel'] = array('zbsco_maintel','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_sectel'] = array('zbsco_sectel','LIKE','%s','%'.$searchPhrase.'%'); // address elements $searchWheres['search_addr1'] = array('zbsco_addr1','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_addr2'] = array('zbsco_addr2','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_city'] = array('zbsco_city','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_county'] = array('zbsco_county','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_country'] = array('zbsco_country','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_postcode'] = array('zbsco_postcode','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_secaddr1'] = array('zbsco_secaddr1','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_secaddr2'] = array('zbsco_secaddr2','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_seccity'] = array('zbsco_seccity','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_seccounty'] = array('zbsco_seccounty','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_seccountry'] = array('zbsco_seccountry','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_secpostcode'] = array('zbsco_secpostcode','LIKE','%s','%'.$searchPhrase.'%'); // social $searchWheres['search_tw'] = array('zbsco_tw','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_li'] = array('zbsco_li','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_fb'] = array('zbsco_fb','LIKE','%s','%'.$searchPhrase.'%'); // 3.0.13 - Added ability to search custom fields (optionally) $customFieldSearch = zeroBSCRM_getSetting('customfieldsearch'); if ($customFieldSearch == 1){ // simplistic add // NOTE: This IGNORES ownership of custom field lines. $searchWheres['search_customfields'] = array('ID','IN',"(SELECT zbscf_objid FROM ".$ZBSCRM_t['customfields']." WHERE zbscf_objval LIKE %s AND zbscf_objtype = ".ZBS_TYPE_COMPANY.")",'%'.$searchPhrase.'%'); } // This generates a query like 'zbsco_fname LIKE %s OR zbsco_lname LIKE %s', // which we then need to include as direct subquery (below) in main query :) $searchQueryArr = $this->buildWheres($searchWheres,'',array(),'OR',false); if (is_array($searchQueryArr) && isset($searchQueryArr['where']) && !empty($searchQueryArr['where'])){ // add it $wheres['direct'][] = array('('.$searchQueryArr['where'].')',$searchQueryArr['params']); } } #} In array (if inCompany passed, this'll currently overwrite that?! (todo2.5)) if (is_array($inArr) && count($inArr) > 0){ // clean for ints $inArrChecked = array(); foreach ($inArr as $x){ $inArrChecked[] = (int)$x; } // add where $wheres['inarray'] = array('ID','IN','('.implode(',',$inArrChecked).')'); } #} Owned by if (is_int($ownedBy) && !empty($ownedBy) && $ownedBy > 0){ // would never hard-type this in (would make generic as in buildWPMetaQueryWhere) // but this is only here until MIGRATED to db2 globally //$wheres['incompany'] = array('ID','IN','(SELECT DISTINCT post_id FROM '.$wpdb->prefix."postmeta WHERE meta_key = 'zbs_company' AND meta_value = %d)",$inCompany); // Use obj links now $wheres['ownedBy'] = array('zbs_owner','=','%s',$ownedBy); } // External sources if ( !empty( $externalSource ) ){ // NO owernship built into this, check when roll out multi-layered ownsership $wheres['externalsource'] = array('ID','IN','(SELECT DISTINCT zbss_objid FROM '.$ZBSCRM_t['externalsources']." WHERE zbss_objtype = ".ZBS_TYPE_COMPANY." AND zbss_source = %s)",$externalSource); } // quick addition for mike #} olderThan if (!empty($olderThan) && $olderThan > 0 && $olderThan !== false) $wheres['olderThan'] = array('zbsco_created','<=','%d',$olderThan); #} newerThan if (!empty($newerThan) && $newerThan > 0 && $newerThan !== false) $wheres['newerThan'] = array('zbsco_created','>=','%d',$newerThan); // status if (!empty($hasStatus) && $hasStatus !== false) $wheres['hasStatus'] = array('zbsco_status','=','%s',$hasStatus); if (!empty($otherStatus) && $otherStatus !== false) $wheres['otherStatus'] = array('zbsco_status','<>','%s',$otherStatus); #} inCounty if (!empty($inCounty) && !empty($inCounty) && $inCounty !== false) { $wheres['inCounty'] = array('zbsco_county','=','%s',$inCounty); $wheres['inCountyAddr2'] = array('zbsco_secaddrcounty','=','%s',$inCounty); } #} inPostCode if (!empty($inPostCode) && !empty($inPostCode) && $inPostCode !== false) { $wheres['inPostCode'] = array('zbsco_postcode','=','%s',$inPostCode); $wheres['inPostCodeAddr2'] = array('zbsco_secaddrpostcode','=','%s',$inPostCode); } #} inCountry if (!empty($inCountry) && !empty($inCountry) && $inCountry !== false) { $wheres['inCountry'] = array('zbsco_country','=','%s',$inCountry); $wheres['inCountryAddr2'] = array('zbsco_secaddrcountry','=','%s',$inCountry); } #} notInCounty if (!empty($notInCounty) && !empty($notInCounty) && $notInCounty !== false) { $wheres['notInCounty'] = array('zbsco_county','<>','%s',$notInCounty); $wheres['notInCountyAddr2'] = array('zbsco_secaddrcounty','<>','%s',$notInCounty); } #} notInPostCode if (!empty($notInPostCode) && !empty($notInPostCode) && $notInPostCode !== false) { $wheres['notInPostCode'] = array('zbsco_postcode','<>','%s',$notInPostCode); $wheres['notInPostCodeAddr2'] = array('zbsco_secaddrpostcode','<>','%s',$notInPostCode); } #} notInCountry if (!empty($notInCountry) && !empty($notInCountry) && $notInCountry !== false) { $wheres['notInCountry'] = array('zbsco_country','<>','%s',$notInCountry); $wheres['notInCountryAddr2'] = array('zbsco_secaddrcountry','<>','%s',$notInCountry); } // has contact associated with it if (!empty($hasContact) && $hasContact !== false && $hasContact > 0) $wheres['hasContact'] = array('ID','IN','(SELECT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = ".ZBS_TYPE_CONTACT." AND zbsol_objtype_to = ".ZBS_TYPE_COMPANY." AND zbsol_objid_to = company.ID)"); // generic obj links, e.g. quotes, invs, trans // e.g. contact(s) assigned to inv 123 // Where the link relationship is OBJECT -> CONTACT if (!empty($hasObjIDLinkedTo) && $hasObjIDLinkedTo !== false && $hasObjIDLinkedTo > 0 && !empty($hasObjTypeLinkedTo) && $hasObjTypeLinkedTo !== false && $hasObjTypeLinkedTo > 0) { $wheres['hasObjIDLinkedTo'] = array('ID','IN','(SELECT zbsol_objid_to FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = %d AND zbsol_objtype_to = ".ZBS_TYPE_COMPANY." AND zbsol_objid_from = %d AND zbsol_objid_to = company.ID)",array($hasObjTypeLinkedTo,$hasObjIDLinkedTo)); } // generic obj links, e.g. companies // Where the link relationship is CONTACT -> OBJECT if (!empty($isLinkedToObjID) && $isLinkedToObjID !== false && $isLinkedToObjID > 0 && !empty($isLinkedToObjType) && $isLinkedToObjType !== false && $isLinkedToObjType > 0) { $wheres['isLinkedToObjID'] = array('ID','IN','(SELECT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = ".ZBS_TYPE_COMPANY." AND zbsol_objtype_to = %d AND zbsol_objid_from = company.ID AND zbsol_objid_to = %d)",array($isLinkedToObjType,$isLinkedToObjID)); } #} Any additionalWhereArr? if (isset($additionalWhereArr) && is_array($additionalWhereArr) && count($additionalWhereArr) > 0){ // add em onto wheres (note these will OVERRIDE if using a key used above) // Needs to be multi-dimensional $wheres = array_merge($wheres,$additionalWhereArr); $wheres = array_merge_recursive($wheres,$additionalWhereArr); } #} Quick filters - adapted from DAL1 (probs can be slicker) if (is_array($quickFilters) && count($quickFilters) > 0){ // cycle through foreach ($quickFilters as $qFilter){ // where status = x // USE hasStatus above now... if ( str_starts_with( $qFilter, 'status_' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $quick_filter_status = substr( $qFilter, 7 ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $wheres['quickfilterstatus'] = array( 'zbsco_status', '=', 'convert(%s using utf8mb4) collate utf8mb4_bin', $quick_filter_status ); } elseif ( str_starts_with( $qFilter, 'notcontactedin' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // check $notcontactedinDays = (int)substr($qFilter,14); $notcontactedinDaysSeconds = $notcontactedinDays*86400; $wheres['notcontactedinx'] = array('zbsco_lastcontacted','<','%d',time()-$notcontactedinDaysSeconds); } elseif ( str_starts_with( $qFilter, 'olderthan' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // check $olderThanDays = (int)substr($qFilter,9); $olderThanDaysSeconds = $olderThanDays*86400; $wheres['olderthanx'] = array('zbsco_created','<','%d',time()-$olderThanDaysSeconds); } else { // normal/hardtyped switch ($qFilter){ case 'lead': // hack "leads only" - adapted from DAL1 (probs can be slicker) $wheres['quickfilterlead'] = array('zbsco_status','LIKE','%s','Lead'); break; case 'customer': // hack - adapted from DAL1 (probs can be slicker) $wheres['quickfiltercustomer'] = array( 'zbsco_status', 'LIKE', '%s', 'Customer' ); break; } // / switch } // / hardtyped } } // / quickfilters #} Is Tagged (expects 1 tag ID OR array) // catch 1 item arr if (is_array($isTagged) && count($isTagged) == 1) $isTagged = $isTagged[0]; if (!is_array($isTagged) && !empty($isTagged) && $isTagged > 0){ // add where tagged // 1 int: $wheres['direct'][] = array('((SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = company.ID AND zbstl_tagid = %d) > 0)',array(ZBS_TYPE_COMPANY,$isTagged)); } else if (is_array($isTagged) && count($isTagged) > 0){ // foreach in array :) $tagStr = ''; foreach ($isTagged as $iTag){ $i = (int)$iTag; if ($i > 0){ if ($tagStr !== '') $tagStr .','; $tagStr .= $i; } } if (!empty($tagStr)){ $wheres['direct'][] = array('((SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = company.ID AND zbstl_tagid IN (%s)) > 0)',array(ZBS_TYPE_COMPANY,$tagStr)); } } #} Is NOT Tagged (expects 1 tag ID OR array) // catch 1 item arr if (is_array($isNotTagged) && count($isNotTagged) == 1) $isNotTagged = $isNotTagged[0]; if (!is_array($isNotTagged) && !empty($isNotTagged) && $isNotTagged > 0){ // add where tagged // 1 int: $wheres['direct'][] = array('((SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = company.ID AND zbstl_tagid = %d) = 0)',array(ZBS_TYPE_COMPANY,$isNotTagged)); } else if (is_array($isNotTagged) && count($isNotTagged) > 0){ // foreach in array :) $tagStr = ''; foreach ($isNotTagged as $iTag){ $i = (int)$iTag; if ($i > 0){ if ($tagStr !== '') $tagStr .','; $tagStr .= $i; } } if (!empty($tagStr)){ $wheres['direct'][] = array('((SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = company.ID AND zbstl_tagid IN (%s)) = 0)',array(ZBS_TYPE_COMPANY,$tagStr)); } } #} ============ / WHERE =============== #} ============ SORT ============== // Obj Model based sort conversion // converts 'addr1' => 'zbsco_addr1' generically if (isset($this->objectModel[$sortByField]) && isset($this->objectModel[$sortByField]['fieldname'])) $sortByField = $this->objectModel[$sortByField]['fieldname']; // include invoices without deleted status in the total value for invoices_total_inc_deleted: $inv_status_query_add = $this->DAL()->invoices->get_invoice_status_except_deleted_for_query(); // Mapped sorts // This catches listview and other exception sort cases $sort_map = array( 'id' => 'ID', 'assigned' => 'zbsco_owner', 'fullname' => 'zbsco_name', 'status' => 'zbsco_status', 'email' => 'zbsco_email', // contacts (count) 'contacts' => '(SELECT COUNT(ID) FROM '.$ZBSCRM_t['contacts'].' WHERE ID IN (SELECT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks'].' WHERE zbsol_objtype_from = '.ZBS_TYPE_CONTACT.' AND zbsol_objtype_to = '.ZBS_TYPE_COMPANY.' AND zbsol_objid_to = company.ID))', // has & counts (same queries) // phpcs:disable WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase 'hasinvoice' => '(SELECT COUNT(ID) FROM ' . $ZBSCRM_t['invoices'] . ' WHERE ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_INVOICE . ' AND zbsol_objtype_to = ' . ZBS_TYPE_COMPANY . ' AND zbsol_objid_to = company.ID))', 'hastransaction' => '(SELECT COUNT(ID) FROM ' . $ZBSCRM_t['transactions'] . ' WHERE ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_TRANSACTION . ' AND zbsol_objtype_to = ' . ZBS_TYPE_COMPANY . ' AND zbsol_objid_to = company.ID))', 'invoicecount_inc_deleted' => '(SELECT COUNT(ID) FROM ' . $ZBSCRM_t['invoices'] . ' WHERE ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_INVOICE . ' AND zbsol_objtype_to = ' . ZBS_TYPE_COMPANY . ' AND zbsol_objid_to = company.ID))', 'invoicecount' => '(SELECT COUNT(ID) FROM ' . $ZBSCRM_t['invoices'] . ' WHERE ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_INVOICE . ' AND zbsol_objtype_to = ' . ZBS_TYPE_COMPANY . ' AND zbsol_objid_to = company.ID)' . $inv_status_query_add . ')', 'transactioncount' => '(SELECT COUNT(ID) FROM ' . $ZBSCRM_t['transactions'] . ' WHERE ID IN (SELECT DISTINCT zbsol_objid_from FROM ' . $ZBSCRM_t['objlinks'] . ' WHERE zbsol_objtype_from = ' . ZBS_TYPE_TRANSACTION . ' AND zbsol_objtype_to = ' . ZBS_TYPE_COMPANY . ' AND zbsol_objid_to = company.ID))', // phpcs:enable WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // following will only work if obj total value subqueries triggered above ^ 'totalvalue' => '((IFNULL(invoices_total,0) + IFNULL(transactions_total,0)) - IFNULL(transactions_paid_total,0))', // custom sort by total invoice value + transaction value - paid transactions (as mimicking tidy_contact php logic into SQL) 'transactiontotal' => 'transactions_total', 'invoicetotal' => 'invoices_total', // When Company<->Quotes: /* 'hasquote' => '(SELECT COUNT(ID) FROM '.$ZBSCRM_t['quotes'].' WHERE ID IN (SELECT DISTINCT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks'].' WHERE zbsol_objtype_from = '.ZBS_TYPE_QUOTE.' AND zbsol_objtype_to = '.ZBS_TYPE_COMPANY.' AND zbsol_objid_to = company.ID))', 'quotetotal' => 'quotes_total', 'quotecount' => '(SELECT COUNT(ID) FROM '.$ZBSCRM_t['quotes'].' WHERE ID IN (SELECT DISTINCT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks'].' WHERE zbsol_objtype_from = '.ZBS_TYPE_QUOTE.' AND zbsol_objtype_to = '.ZBS_TYPE_COMPANY.' AND zbsol_objid_to = company.ID))', */ ); if ( array_key_exists( $sortByField, $sort_map ) ) { $sortByField = $sort_map[ $sortByField ]; } #} ============ / SORT ============== #} CHECK this + reset to default if faulty if (!in_array($whereCase,array('AND','OR'))) $whereCase = 'AND'; #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params,$whereCase); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner,'contact'); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort($sortByField,$sortOrder) . $this->buildPaging($page,$perPage); try { #} Prep & run query $queryObj = $this->prepare($query,$params); #} Catch count + return if requested if ($count) return $wpdb->get_var($queryObj); #} else continue.. $potentialRes = $wpdb->get_results($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret results (Result Set - multi-row) if (isset($potentialRes) && is_array($potentialRes) && count($potentialRes) > 0) { #} Has results, tidy + return foreach ($potentialRes as $resDataLine) { #} simplified override if ($simplified){ $resArr = array( 'id' => $resDataLine->id, 'name' => $resDataLine->name, 'created' => $resDataLine->created, 'email' => $resDataLine->email ); } else if ($onlyColumns && is_array($onlyColumnsFieldArr) && count($onlyColumnsFieldArr) > 0){ // only coumns return. $resArr = array(); foreach ($onlyColumnsFieldArr as $colDBKey => $colStr){ if (isset($resDataLine->$colDBKey)) $resArr[$colStr] = $resDataLine->$colDBKey; } } else { // tidy $resArr = $this->tidy_company($resDataLine,$withCustomFields); } if ($withTags){ // add all tags lines $resArr['tags'] = $this->DAL()->getTagsForObjID(array('objtypeid'=>ZBS_TYPE_COMPANY,'objid'=>$resDataLine->ID)); } #} With most recent log? #DB1LEGACY (TOMOVE) if ($withLastLog){ // doesn't return singular, for now using arr $potentialLogs = $this->DAL()->logs->getLogsForObj(array( 'objtype' => ZBS_TYPE_COMPANY, 'objid' => $resDataLine->ID, 'incMeta' => true, 'sortByField' => 'zbsl_created', 'sortOrder' => 'DESC', 'page' => 0, 'perPage' => 1 )); if (is_array($potentialLogs) && count($potentialLogs) > 0) $resArr['lastlog'] = $potentialLogs[0]; // COMPANY logs specifically // doesn't return singular, for now using arr $potentialLogs = $this->DAL()->logs->getLogsForObj( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase array( 'objtype' => ZBS_TYPE_COMPANY, 'objid' => $resDataLine->ID, // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase 'notetypes' => $zbs->DAL->logs->contact_log_types, // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase 'incMeta' => true, 'sortByField' => 'zbsl_created', 'sortOrder' => 'DESC', 'page' => 0, 'perPage' => 1, ) ); if (is_array($potentialLogs) && count($potentialLogs) > 0) $resArr['lastcontactlog'] = $potentialLogs[0]; } #} With Assigned? if ($withOwner){ $resArr['owner'] = zeroBS_getOwner($resDataLine->ID,true,'zerobs_company',$resDataLine->zbs_owner); } if ($withContacts){ // add all assigned contacts/companies $resArr['contacts'] = $this->DAL()->contacts->getContacts(array( 'isLinkedToObjType'=>ZBS_TYPE_COMPANY, 'isLinkedToObjID'=>$resDataLine->ID, 'page'=>-1, 'perPage'=>-1, 'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); } if ($withInvoices){ #} only gets first 100? #} CURRENTLY inc meta..? (isn't huge... but isn't efficient) //$resArr['invoices'] = zeroBS_getInvoicesForCompany($resDataLine->ID,true,100); //DAL3 ver, more perf, gets all $resArr['invoices'] = $zbs->DAL->invoices->getInvoices(array( 'assignedCompany' => $resDataLine->ID, // assigned to company id (int) 'page' => -1, 'perPage' => -1, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_INVOICE) )); } if ( $withQuotes ) { //DAL3 ver, more perf, gets all $resArr['quotes'] = $zbs->DAL->quotes->getQuotes(array( 'assignedCompany' => $resDataLine->ID, // assigned to company id (int) 'page' => -1, 'perPage' => -1, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_QUOTE) )); } #} ... brutal for mvp #DB1LEGACY (TOMOVE) if ($withTransactions){ //DAL3 ver, more perf, gets all $resArr['transactions'] = $zbs->DAL->transactions->getTransactions(array( 'assignedCompany' => $resDataLine->ID, // assigned to company id (int) 'page' => -1, 'perPage' => -1, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_TRANSACTION) )); } #} ... brutal for mvp #DB1LEGACY (TOMOVE) if ($withTasks){ $res['tasks'] = $zbs->DAL->events->getEvents(array( 'assignedCompany' => $resDataLine->ID, // assigned to company id (int) 'page' => -1, 'perPage' => -1, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_TASK), 'sortByField' => 'zbse_start', 'sortOrder' => 'DESC', 'withAssigned' => false // no need, it's assigned to this obj already )); } // simplistic, could be optimised (though low use means later.) if ( $withExternalSources ){ $res['external_sources'] = $zbs->DAL->getExternalSources( array( 'objectID' => $resDataLine->ID, 'objectType' => ZBS_TYPE_COMPANY, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT) )); } if ( $withExternalSourcesGrouped ){ $res['external_sources'] = $zbs->DAL->getExternalSources( -1, array( 'objectID' => $resDataLine->ID, 'objectType' => ZBS_TYPE_COMPANY, 'grouped_by_source' => true, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership( ZBS_TYPE_COMPANY ) )); } //} // =================================================== // ========== / #DB1LEGACY (TOMOVE) // =================================================== $res[] = $resArr; } } return $res; } /** * Returns a count of companies (owned) * .. inc by status * * @return int count */ public function getCompanyCount($args=array()){ #} ============ LOAD ARGS ============= $defaultArgs = array( // Search/Filtering (leave as false to ignore) 'withStatus' => false, // will be str if used // permissions 'ignoreowner' => true, // this'll let you not-check the owner of obj ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= $whereArr = array(); if ($withStatus !== false && !empty($withStatus)) $whereArr['status'] = array('zbsco_status','=','%s',$withStatus); return $this->DAL()->getFieldByWHERE(array( 'objtype' => ZBS_TYPE_COMPANY, 'colname' => 'COUNT(ID)', 'where' => $whereArr, 'ignoreowner' => $ignoreowner)); } /** * adds or updates a company object * * @param array $args Associative array of arguments * id (if update), owner, data (array of field data) * * @return int line ID */ public function addUpdateCompany($args=array()){ global $ZBSCRM_t,$wpdb,$zbs; #} Retrieve any cf $customFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_COMPANY)); $addrCustomFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_ADDRESS)); #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'owner' => -1, // fields (directly) 'data' => array( 'status' => '', 'name' => '', 'email' => '', 'addr1' => '', 'addr2' => '', 'city' => '', 'county' => '', 'country' => '', 'postcode' => '', 'secaddr1' => '', 'secaddr2' => '', 'seccity' => '', 'seccounty' => '', 'seccountry' => '', 'secpostcode' => '', 'maintel' => '', 'sectel' => '', 'wpid' => '', 'avatar' => '', 'tw' => '', 'li' => '', 'fb' => '', 'lastcontacted' => '', // Note Custom fields may be passed here, but will not have defaults so check isset() // tags 'tags' => -1, // pass an array of tag ids or tag strings 'tag_mode' => 'replace', // replace|append|remove 'externalSources' => -1, // if this is an array(array('source'=>src,'uid'=>uid),multiple()) it'll add :) // allow this to be set for MS sync etc. 'created' => -1, 'lastupdated' => '', // obj links: 'contacts' => false, // array of id's ), 'limitedFields' => -1, // if this is set it OVERRIDES data (allowing you to set specific fields + leave rest in tact) // ^^ will look like: array(array('key'=>x,'val'=>y,'type'=>'%s')) // this function as DAL1 func did. 'extraMeta' => -1, 'automatorPassthrough' => -1, 'fallBackLog' => -1, 'silentInsert' => false, // this was for init Migration - it KILLS all IA for newCompany (because is migrating, not creating new :) this was -1 before 'do_not_update_blanks' => false // this allows you to not update fields if blank (same as fieldoverride for extsource -> in) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } // Needs this to grab custom fields (if passed) too :) if (is_array($customFields)) foreach ($customFields as $cK => $cF){ // only for data, limited fields below if (is_array($data)) { if (isset($args['data'][$cK])) $data[$cK] = $args['data'][$cK]; } } // this takes limited fields + checks through for custom fields present // (either as key zbsco_source or source, for example) // then switches them into the $data array, for separate update // where this'll fall over is if NO normal contact data is sent to update, just custom fields if (is_array($limitedFields) && is_array($customFields)){ //$customFieldKeys = array_keys($customFields); $newLimitedFields = array(); // cycle through foreach ($limitedFields as $field){ // some weird case where getting empties, so added check if (isset($field['key']) && !empty($field['key'])){ $dePrefixed = ''; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase if ( str_starts_with( $field['key'], 'zbsco_' ) ) { $dePrefixed = substr( $field['key'], strlen( 'zbsco_' ) ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } if (isset($customFields[$field['key']])){ // is custom, move to data $data[$field['key']] = $field['val']; } else if (!empty($dePrefixed) && isset($customFields[$dePrefixed])){ // is custom, move to data $data[$dePrefixed] = $field['val']; } else { // add it to limitedFields (it's not dealt with post-update) $newLimitedFields[] = $field; } } } // move this back in $limitedFields = $newLimitedFields; unset($newLimitedFields); } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ $id = (int)$id; // here we check that the potential owner CAN even own if ($owner > 0 && !user_can($owner,'admin_zerobs_usr')) $owner = -1; // if owner = -1, add current if (!isset($owner) || $owner === -1) { $owner = zeroBSCRM_user(); } if (is_array($limitedFields)){ // LIMITED UPDATE (only a few fields.) if (!is_array($limitedFields) || count ($limitedFields) <= 0) return false; // REQ. ID too (can only update) if (empty($id) || $id <= 0) return false; } else { // NORMAL, FULL UPDATE // check email + load that user if present if (!isset($data['email']) || empty($data['email'])){ // no email // Allow users without emails? WH removed this for db1->2 migration // leaving this in breaks MIGRATIONS from DAL 1 // in that those companies without emails will not be copied in // return false; } else { // email present, check if it matches ID? if (!empty($id) && $id > 0){ // if ID + email, check if existing contact with email, (e.g. in use) // ... allow it if the ID of that email contact matches the ID given here // (else e.g. add email x to ID y without checking) $potentialUSERID = (int)$this->getCompany(-1,array('email'=>$data['email'],'ignoreOwner'=>1,'onlyID'=>1)); if (!empty($potentialUSERID) && $potentialUSERID > 0 && $id > 0 && $potentialUSERID != $id){ // email doesn't match ID return false; } // also check if has rights?!? Could be just email passed here + therefor got around owner check? hmm. } else { // no ID, check if email present, and then update that co if so $potentialUSERID = (int)$this->getCompany(-1,array('email'=>$data['email'],'ignoreOwner'=>1,'onlyID'=>1)); if (isset($potentialUSERID) && !empty($potentialUSERID) && $potentialUSERID > 0) { $id = $potentialUSERID; } } } } #} If no status, and default is specified in settings, add that in :) if (is_null($data['status']) || !isset($data['status']) || empty($data['status'])){ // Default status for obj? -> this one gets for contacts -> $zbsCustomerMeta['status'] = zeroBSCRM_getSetting('defaultstatus'); } #} ========= / CHECK FIELDS =========== #} ========= OVERRIDE SETTING (Deny blank overrides) =========== // this only functions if externalsource is set (e.g. api/form, etc.) if (isset($data['externalSources']) && is_array($data['externalSources']) && count($data['externalSources']) > 0) { if (zeroBSCRM_getSetting('fieldoverride') == "1"){ $do_not_update_blanks = true; } } // either ext source + setting, or set by the func call if ($do_not_update_blanks){ // this setting says 'don't override filled-out data with blanks' // so here we check through any passed blanks + convert to limitedFields // only matters if $id is set (there is somt to update not add if (isset($id) && !empty($id) && $id > 0){ // get data to copy over (for now, this is required to remove 'fullname' etc.) $dbData = $this->db_ready_company($data); //unset($dbData['id']); // this is unset because we use $id, and is update, so not req. legacy issue //unset($dbData['created']); // this is unset because this uses an obj which has been 'updated' against original details, where created is output in the WRONG format :) $origData = $data; //$data = array(); $limitedData = array(); // array(array('key'=>'zbsco_x','val'=>y,'type'=>'%s')) // cycle through + translate into limitedFields (removing any blanks, or arrays (e.g. externalSources)) // we also have to remake a 'faux' data (removing blanks for tags etc.) for the post-update updates foreach ($dbData as $k => $v){ $intV = (int)$v; // only add if valuenot empty if (!is_array($v) && !empty($v) && $v != '' && $v !== 0 && $v !== -1 && $intV !== -1){ // add to update arr $limitedData[] = array( 'key' => 'zbsco_'.$k, // we have to add zbsco_ here because translating from data -> limited fields 'val' => $v, 'type' => $this->getTypeStr('zbsco_'.$k) ); // add to remade $data for post-update updates $data[$k] = $v; } } // copy over $limitedFields = $limitedData; } // / if ID } // / if do_not_update_blanks #} ========= / OVERRIDE SETTING (Deny blank overrides) =========== #} ========= BUILD DATA =========== $update = false; $dataArr = array(); $typeArr = array(); if (is_array($limitedFields)){ // LIMITED FIELDS $update = true; // cycle through foreach ($limitedFields as $field){ // some weird case where getting empties, so added check if (!empty($field['key'])){ $dataArr[$field['key']] = $field['val']; $typeArr[] = $field['type']; } } // add update time if (!isset($dataArr['zbsco_lastupdated'])){ $dataArr['zbsco_lastupdated'] = time(); $typeArr[] = '%d'; } } else { // FULL UPDATE/INSERT // contacts - avoid dupes if (isset($data['contacts']) && is_array($data['contacts'])){ $coArr = array(); foreach ($data['contacts'] as $c){ $cI = (int)$c; if ($cI > 0 && !in_array($cI, $coArr)) $coArr[] = $cI; } // reset the main if (count($coArr) > 0) $data['contacts'] = $coArr; else $data['contacts'] = 'unset'; unset($coArr); } // UPDATE $dataArr = array( // ownership // no need to update these (as of yet) - can't move teams etc. //'zbs_site' => zeroBSCRM_installSite(), //'zbs_team' => zeroBSCRM_installTeam(), //'zbs_owner' => $owner, 'zbsco_status' => $data['status'], 'zbsco_name' => $data['name'], 'zbsco_email' => $data['email'], 'zbsco_addr1' => $data['addr1'], 'zbsco_addr2' => $data['addr2'], 'zbsco_city' => $data['city'], 'zbsco_county' => $data['county'], 'zbsco_country' => $data['country'], 'zbsco_postcode' => $data['postcode'], 'zbsco_secaddr1' => $data['secaddr1'], 'zbsco_secaddr2' => $data['secaddr2'], 'zbsco_seccity' => $data['seccity'], 'zbsco_seccounty' => $data['seccounty'], 'zbsco_seccountry' => $data['seccountry'], 'zbsco_secpostcode' => $data['secpostcode'], 'zbsco_maintel' => $data['maintel'], 'zbsco_sectel' => $data['sectel'], 'zbsco_wpid' => $data['wpid'], 'zbsco_avatar' => $data['avatar'], 'zbsco_tw' => $data['tw'], 'zbsco_li' => $data['li'], 'zbsco_fb' => $data['fb'], 'zbsco_lastupdated' => time(), 'zbsco_lastcontacted' =>$data['lastcontacted'], ); $typeArr = array( // field data types //'%d', // site //'%d', // team //'%d', // owner '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%d', '%d', ); if (!empty($id) && $id > 0){ // is update $update = true; // got owner change? - allow all basically? if (isset($owner) && $owner > 0){ $dataArr['zbs_owner'] = $owner; $typeArr[] = '%d'; } } else { // INSERT (get's few extra :D) $update = false; $dataArr['zbs_site'] = zeroBSCRM_site(); $typeArr[] = '%d'; $dataArr['zbs_team'] = zeroBSCRM_team(); $typeArr[] = '%d'; $dataArr['zbs_owner'] = $owner; $typeArr[] = '%d'; if (isset($data['created']) && !empty($data['created']) && $data['created'] !== -1){ $dataArr['zbsco_created'] = $data['created'];$typeArr[] = '%d'; } else { $dataArr['zbsco_created'] = time(); $typeArr[] = '%d'; } } } #} ========= / BUILD DATA =========== #} ============================================================ #} ========= CHECK force_uniques & not_empty & max_len ======== // if we're passing limitedFields we skip these, for now // #v3.1 - would make sense to unique/nonempty check just the limited fields. #gh-145 if (!is_array($limitedFields)){ // verify uniques if (!$this->verifyUniqueValues($data,$id)) return false; // / fails unique field verify // verify not_empty if (!$this->verifyNonEmptyValues($data)) return false; // / fails empty field verify } // whatever we do we check for max_len breaches and abbreviate to avoid wpdb rejections $dataArr = $this->wpdbChecks($dataArr); #} ========= / CHECK force_uniques & not_empty ================ #} ============================================================ #} Check if ID present if ($update){ #} Check if obj exists (here) - for now just brutal update (will error when doesn't exist) $originalStatus = $this->getCompanyStatus($id); $previous_company_obj = $this->getCompany( $id ); // log any change of status if (isset($dataArr['zbsco_status']) && !empty($dataArr['zbsco_status']) && !empty($originalStatus) && $dataArr['zbsco_status'] != $originalStatus){ // status change $statusChange = array( 'from' => $originalStatus, 'to' => $dataArr['zbsco_status'] ); } #} Attempt update if ($wpdb->update( $ZBSCRM_t['companies'], $dataArr, array( // where 'ID' => $id ), $typeArr, array( // where data types '%d' )) !== false){ // if passing limitedFields instead of data, we ignore the following // this doesn't work, because data is in args default as arr //if (isset($data) && is_array($data)){ // so... if (!isset($limitedFields) || !is_array($limitedFields) || $limitedFields == -1){ // OBJ LINKS - contacts -> companies // This would link Company -> Contacts, $this->addUpdateObjectLinks($id,$data['contacts'],ZBS_TYPE_CONTACT); // ... but we need it Contacts -> Company, so use a direct call in this case: if (is_array($data['contacts'])) foreach ($data['contacts'] as $contactID){ // if is ID if ($contactID > 0){ // append to it's links (in case it has other companies too) $this->DAL()->addUpdateObjLinks(array( 'objtypefrom' => ZBS_TYPE_CONTACT, 'objtypeto' => ZBS_TYPE_COMPANY, 'objfromid' => $contactID, 'objtoids' => array($id), 'mode' => 'append')); } } // tags if (isset($data['tags']) && is_array($data['tags'])) { $this->addUpdateCompanyTags( array( 'id' => $id, 'tag_input' => $data['tags'], 'mode' => $data['tag_mode'] ) ); } // externalSources $approvedExternalSource = $this->DAL()->addUpdateExternalSources( array( 'obj_id' => $id, 'obj_type_id' => ZBS_TYPE_COMPANY, 'external_sources' => isset($data['externalSources']) ? $data['externalSources'] : array(), ) ); // for IA below // Custom fields? #} Cycle through + add/update if set if (is_array($customFields)) foreach ($customFields as $cK => $cF){ // any? if (isset($data[$cK])){ // add update $cfID = $this->DAL()->addUpdateCustomField(array( 'data' => array( 'objtype' => ZBS_TYPE_COMPANY, 'objid' => $id, 'objkey' => $cK, 'objval' => $data[$cK] ))); } } // Also got to catch any 'addr' custom fields :) if (is_array($addrCustomFields) && count($addrCustomFields) > 0){ // cycle through addr custom fields + save // see #ZBS-518, not easy until addr's get DAL2 // WH deferring here // WH later added via the addUpdateContactField method - should work fine if we catch properly in get foreach ($addrCustomFields as $cK => $cF){ // v2: //$cKN = (int)$cK+1; //$cKey = 'addr_cf'.$cKN; //$cKey2 = 'secaddr_cf'.$cKN; // v3: $cKey = 'addr_'.$cK; $cKey2 = 'secaddr_'.$cK; // any? if (isset($data[$cKey])){ // add update $cfID = $this->DAL()->addUpdateCustomField(array( 'data' => array( 'objtype' => ZBS_TYPE_COMPANY, 'objid' => $id, 'objkey' => $cKey, 'objval' => $data[$cKey] ))); } // any? if (isset($data[$cKey2])){ // add update $cfID = $this->DAL()->addUpdateCustomField(array( 'data' => array( 'objtype' => ZBS_TYPE_COMPANY, 'objid' => $id, 'objkey' => $cKey2, 'objval' => $data[$cKey2] ))); } } } // / Custom Fields } // / if $data #} Any extra meta keyval pairs? // BRUTALLY updates (no checking) $confirmedExtraMeta = false; if (isset($extraMeta) && is_array($extraMeta)) { $confirmedExtraMeta = array(); foreach ($extraMeta as $k => $v){ #} This won't fix stupid keys, just catch basic fails... $cleanKey = strtolower(str_replace(' ','_',$k)); #} Brutal update //update_post_meta($postID, 'zbs_customer_extra_'.$cleanKey, $v); $this->DAL()->updateMeta(ZBS_TYPE_COMPANY,$id,'extra_'.$cleanKey,$v); #} Add it to this, which passes to IA $confirmedExtraMeta[$cleanKey] = $v; } } #} INTERNAL AUTOMATOR #} & #} FALLBACKS // UPDATING CONTACT if (!$silentInsert){ #} FALLBACK #} (This fires for customers that weren't added because they already exist.) #} e.g. x@g.com exists, so add log "x@g.com filled out form" #} Requires a type and a shortdesc if ( isset($fallBackLog) && is_array($fallBackLog) && isset($fallBackLog['type']) && !empty($fallBackLog['type']) && isset($fallBackLog['shortdesc']) && !empty($fallBackLog['shortdesc']) ){ #} Brutal add, maybe validate more?! #} Long desc if present: $zbsNoteLongDesc = ''; if (isset($fallBackLog['longdesc']) && !empty($fallBackLog['longdesc'])) $zbsNoteLongDesc = $fallBackLog['longdesc']; #} Only raw checked... but proceed. $newOrUpdatedLogID = zeroBS_addUpdateCompanyLog($id,-1,-1,array( #} Anything here will get wrapped into an array and added as the meta vals 'type' => $fallBackLog['type'], 'shortdesc' => $fallBackLog['shortdesc'], 'longdesc' => $zbsNoteLongDesc )); } // catch dirty flag (update of status) (note, after update_post_meta - as separate) //if (isset($_POST['zbsco_status_dirtyflag']) && $_POST['zbsco_status_dirtyflag'] == "1"){ // actually here, it's set above if (isset($statusChange) && is_array($statusChange)){ // status has changed // IA zeroBSCRM_FireInternalAutomator('company.status.update',array( 'id'=>$id, 'againstid' => $id, 'data'=> $dataArr, 'from' => $statusChange['from'], 'to' => $statusChange['to'] )); } // IA General company update (2.87+) zeroBSCRM_FireInternalAutomator('company.update',array( 'id'=>$id, 'againstid' => $id, 'data' => $dataArr, // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase 'prev_company' => $previous_company_obj, )); } // Successfully updated - Return id return $id; } else { $msg = __('DB Update Failed','zero-bs-crm'); $zbs->DAL->addError(302,$this->objectType,$msg,$dataArr); // FAILED update return false; } } else { #} No ID - must be an INSERT if ($wpdb->insert( $ZBSCRM_t['companies'], $dataArr, $typeArr ) > 0){ #} Successfully inserted, lets return new ID $newID = $wpdb->insert_id; // OBJ LINKS - contacts -> companies // This would link Company -> Contacts, $this->addUpdateObjectLinks($newID,$data['contacts'],ZBS_TYPE_CONTACT); // ... but we need it Contacts -> Company, so use a direct call in this case: if (is_array($data['contacts'])) foreach ($data['contacts'] as $contactID){ // if is ID if ($contactID > 0){ // append to it's links (in case it has other companies too) $this->DAL()->addUpdateObjLinks(array( 'objtypefrom' => ZBS_TYPE_CONTACT, 'objtypeto' => ZBS_TYPE_COMPANY, 'objfromid' => $contactID, 'objtoids' => array($newID), 'mode' => 'append')); } } // tags if (isset($data['tags']) && is_array($data['tags'])) { $this->addUpdateCompanyTags( array( 'id' => $newID, 'tag_input' => $data['tags'], 'mode' => $data['tag_mode'] ) ); } // externalSources $approvedExternalSource = $this->DAL()->addUpdateExternalSources( array( 'obj_id' => $newID, 'obj_type_id' => ZBS_TYPE_COMPANY, 'external_sources' => isset($data['externalSources']) ? $data['externalSources'] : array(), ) ); // for IA below // Custom fields? #} Cycle through + add/update if set if (is_array($customFields)) foreach ($customFields as $cK => $cF){ // any? if (isset($data[$cK])){ // add update $cfID = $this->DAL()->addUpdateCustomField(array( 'data' => array( 'objtype' => ZBS_TYPE_COMPANY, 'objid' => $newID, 'objkey' => $cK, 'objval' => $data[$cK] ))); } } // / Custom Fields // Also got to catch any 'addr' custom fields :) if (is_array($addrCustomFields) && count($addrCustomFields) > 0){ foreach ($addrCustomFields as $cK => $cF){ $cKey = 'addr_'.$cK; $cKey2 = 'secaddr_'.$cK; if (isset($data[$cKey])){ // add update $cfID = $this->DAL()->addUpdateCustomField(array( 'data' => array( 'objtype' => ZBS_TYPE_COMPANY, 'objid' => $newID, 'objkey' => $cKey, 'objval' => $data[$cKey] ))); } // any? if (isset($data[$cKey2])){ // add update $cfID = $this->DAL()->addUpdateCustomField(array( 'data' => array( 'objtype' => ZBS_TYPE_COMPANY, 'objid' => $newID, 'objkey' => $cKey2, 'objval' => $data[$cKey2] ))); } } } #} Any extra meta keyval pairs? // BRUTALLY updates (no checking) $confirmedExtraMeta = false; if (isset($extraMeta) && is_array($extraMeta)) { $confirmedExtraMeta = array(); foreach ($extraMeta as $k => $v){ #} This won't fix stupid keys, just catch basic fails... $cleanKey = strtolower(str_replace(' ','_',$k)); #} Brutal update //update_post_meta($postID, 'zbs_customer_extra_'.$cleanKey, $v); $this->DAL()->updateMeta(ZBS_TYPE_COMPANY,$newID,'extra_'.$cleanKey,$v); #} Add it to this, which passes to IA $confirmedExtraMeta[$cleanKey] = $v; } } #} INTERNAL AUTOMATOR #} & #} FALLBACKS // NEW CONTACT if (!$silentInsert){ #} Add to automator zeroBSCRM_FireInternalAutomator('company.new',array( 'id'=>$newID, 'data'=>$dataArr, 'extsource'=>$approvedExternalSource, 'automatorpassthrough'=>$automatorPassthrough, #} This passes through any custom log titles or whatever into the Internal automator recipe. 'extraMeta'=>$confirmedExtraMeta #} This is the "extraMeta" passed (as saved) )); } return $newID; } else { $msg = __('DB Insert Failed','zero-bs-crm'); $zbs->DAL->addError(303,$this->objectType,$msg,$dataArr); #} Failed to Insert return false; } } return false; } /** * adds or updates a company's tags * ... this is really just a wrapper for addUpdateObjectTags * * @param array $args Associative array of arguments * id (if update), owner, data (array of field data) * * @return int line ID */ public function addUpdateCompanyTags($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, // co id // generic pass-through (array of tag strings or tag IDs): 'tag_input' => -1, // or either specific: 'tagIDs' => -1, 'tags' => -1, 'mode' => 'append' ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ // check id $id = (int)$id; if (empty($id) || $id <= 0) return false; #} ========= / CHECK FIELDS =========== return $this->DAL()->addUpdateObjectTags( array( 'objtype' => ZBS_TYPE_COMPANY, 'objid' => $id, 'tag_input' => $tag_input, 'tags' => $tags, 'tagIDs' => $tagIDs, 'mode' => $mode ) ); } /** * deletes a company object * * @param array $args Associative array of arguments * id * * @return int success; */ public function deleteCompany($args=array()){ global $ZBSCRM_t,$wpdb,$zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'saveOrphans' => true ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} Check ID & Delete :) $id = (int)$id; if (!empty($id) && $id > 0) { // delete orphans? if ($saveOrphans === false){ // delete any tag links $this->DAL()->deleteTagObjLinks(array( 'objtype' => ZBS_TYPE_COMPANY, 'objid' => $id )); // delete any external source information $this->DAL()->delete_external_sources( array( 'obj_type' => ZBS_TYPE_COMPANY, 'obj_id' => $id, 'obj_source' => 'all', )); } $del = zeroBSCRM_db2_deleteGeneric($id,'companies'); #} Add to automator zeroBSCRM_FireInternalAutomator('company.delete',array( 'id'=>$id, 'saveOrphans'=>$saveOrphans )); return $del; } return false; } /** * tidy's the object from wp db into clean array * * @param array $obj (DB obj) * * @return array company (clean obj) */ private function tidy_company($obj=false,$withCustomFields=false){ $res = false; if (isset($obj->ID)){ $res = array(); $res['id'] = $obj->ID; /* `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, */ $res['owner'] = $obj->zbs_owner; $res['status'] = $this->stripSlashes($obj->zbsco_status); $res['name'] = $this->stripSlashes($obj->zbsco_name); $res['email'] = $this->stripSlashes($obj->zbsco_email); $res['addr1'] = $this->stripSlashes($obj->zbsco_addr1); $res['addr2'] = $this->stripSlashes($obj->zbsco_addr2); $res['city'] = $this->stripSlashes($obj->zbsco_city); $res['county'] = $this->stripSlashes($obj->zbsco_county); $res['country'] = $this->stripSlashes($obj->zbsco_country); $res['postcode'] = $this->stripSlashes($obj->zbsco_postcode); $res['secaddr1'] = $this->stripSlashes($obj->zbsco_secaddr1); $res['secaddr2'] = $this->stripSlashes($obj->zbsco_secaddr2); $res['seccity'] = $this->stripSlashes($obj->zbsco_seccity); $res['seccounty'] = $this->stripSlashes($obj->zbsco_seccounty); $res['seccountry'] = $this->stripSlashes($obj->zbsco_seccountry); $res['secpostcode'] = $this->stripSlashes($obj->zbsco_secpostcode); $res['maintel'] = $this->stripSlashes($obj->zbsco_maintel); $res['sectel'] = $this->stripSlashes($obj->zbsco_sectel); $res['wpid'] = (int)$obj->zbsco_wpid; $res['avatar'] = $this->stripSlashes($obj->zbsco_avatar); $res['tw'] = $this->stripSlashes($obj->zbsco_tw); $res['li'] = $this->stripSlashes($obj->zbsco_li); $res['fb'] = $this->stripSlashes($obj->zbsco_fb); $res['created'] = (int)$obj->zbsco_created; $res['created_date'] = (isset($obj->zbsco_created) && $obj->zbsco_created > 0) ? zeroBSCRM_date_i18n(-1,$obj->zbsco_created,false,true) : false; $res['lastupdated'] = (int)$obj->zbsco_lastupdated; $res['lastupdated_date'] = (isset($obj->zbsco_lastupdated) && $obj->zbsco_lastupdated > 0) ? zeroBSCRM_date_i18n(-1,$obj->zbsco_lastupdated,false,true) : false; $res['lastcontacted'] = (int)$obj->zbsco_lastcontacted; $res['lastcontacted_date'] = (isset($obj->zbsco_lastcontacted) && $obj->zbsco_lastcontacted > 0) ? zeroBSCRM_date_i18n(-1,$obj->zbsco_lastcontacted,false,true) : false; // if have totals, pass them :) if (isset($obj->quotes_total)) $res['quotes_total'] = $obj->quotes_total; if ( isset( $obj->invoices_total ) ) { $res['invoices_total'] = $obj->invoices_total; $res['invoices_total_inc_deleted'] = $obj->invoices_total_inc_deleted; $res['invoices_count'] = $obj->invoices_count; $res['invoices_count_inc_deleted'] = $obj->invoices_count_inc_deleted; } if ( isset( $obj->transactions_total ) ) { $res['transactions_total'] = $obj->transactions_total; } if (isset($obj->transactions_paid_total)) $res['transactions_paid_total'] = $obj->transactions_paid_total; // and if have invs + trans totals, add to make total val // This now accounts for "part payments" where trans are part/whole payments against invs if (isset($res['invoices_total']) || isset($res['transactions_total'])){ $res['total_value'] = jpcrm_get_total_value_from_contact_or_company( $res ); } // custom fields - tidy any that are present: if ($withCustomFields) $res = $this->tidyAddCustomFields(ZBS_TYPE_COMPANY,$obj,$res,true); } return $res; } /** * Wrapper, use $this->getCompanyMeta($contactID,$key) for easy retrieval of singular company * Simplifies $this->getMeta * * @param int objtype * @param int objid * @param string key * * @return array company meta result */ public function getCompanyMeta($id=-1,$key='',$default=false){ global $zbs; if (!empty($key)){ return $this->DAL()->getMeta(array( 'objtype' => ZBS_TYPE_COMPANY, 'objid' => $id, 'key' => $key, 'fullDetails' => false, 'default' => $default, 'ignoreowner' => true // for now !! )); } return $default; } /** * Returns an email addr against a Company * * @param int id Company ID * * @return string Company email */ public function getCompanyEmail($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_COMPANY, 'colname' => 'zbsco_email', 'ignoreowner' => true)); } return false; } /** * Returns an ownerid against a company * * @param int id company ID * * @return int company owner id */ public function getCompanyOwner($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_COMPANY, 'colname' => 'zbs_owner', 'ignoreowner'=>true)); } return false; } /** * Returns an status against a company * * @param int id company ID * * @return str company status string */ public function getCompanyStatus($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_COMPANY, 'colname' => 'zbsco_status', 'ignoreowner'=>true)); } return false; } /** * Returns a formatted fullname (optionally including ID + first line of addr) * Replaces zeroBS_companyName * * @param int id Company ID * @param array Company array (if already loaded can pass) * @param array args (see format_fullname func) * * @return string Company full name */ public function getCompanyNameEtc($id=-1,$companyArr=false,$args=array()){ global $zbs; $id = (int)$id; // this makes sure it uses name not 'fname' $args['company'] = true; if ($id > 0){ // get a limited-fields contact obj $company = $zbs->DAL->companies->getCompany($id,array('withCustomFields' => false,'fields'=>array('zbsco_addr1','zbsco_name'),'ignoreowner' => true)); if (isset($company) && is_array($company) && isset($company['name'])) return $this->format_name_etc($company,$args); } elseif (is_array($companyArr)){ // pass through return $this->format_name_etc($companyArr,$args); } return false; } /** * Returns a formatted address of a contact * Replaces zeroBS_companyAddr * * @param int id Company ID * @param array Company array (if already loaded can pass) * @param array args (see format_address func) * * @return string Company addr html */ public function getCompanyAddress($id=-1,$companyArr=false,$args=array()){ global $zbs; $id = (int)$id; if ($id > 0){ // get a limited-fields company obj // this is hacky, but basically get whole basic company record for this for now, because // this doesn't properly get addr custom fields: // $company = $this->getContact($id,array('withCustomFields' => false,'fields'=>$this->field_list_address2,'ignoreowner'=>true)); $company = $this->getCompany($id,array('withCustomFields' => true,'ignoreowner'=>true)); if (isset($company) && is_array($company) && isset($company['addr1'])) return $this->format_address($company,$args); } elseif (is_array($companyArr)){ // pass through return $this->format_address($companyArr,$args); } return false; } /** * Returns a formatted address of a Company (2nd addr) * Replaces zeroBS_companySecondAddr * * @param int id Company ID * @param array Company array (if already loaded can pass) * @param array args (see format_address func) * * @return string Company addr html */ public function getCompany2ndAddress($id=-1,$companyArr=false,$args=array()){ global $zbs; $id = (int)$id; $args['secondaddr'] = true; if ($id > 0){ // get a limited-fields company obj // this is hacky, but basically get whole basic company record for this for now, because // this doesn't properly get addr custom fields: // $company = $this->getContact($id,array('withCustomFields' => false,'fields'=>$this->field_list_address2,'ignoreowner'=>true)); $company = $this->getCompany($id,array('withCustomFields' => true,'ignoreowner'=>true)); if (isset($company) && is_array($company) && isset($company['addr1'])) return $this->format_address($company,$args); } elseif (is_array($companyArr)){ // pass through return $this->format_address($companyArr,$args); } return false; } /** * Returns a Company's tag array * * @param int id Company ID * * @return mixed */ public function getCompanyTags($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getTagsForObjID(array('objtypeid'=>ZBS_TYPE_COMPANY,'objid'=>$id)); } return false; } /** * Returns last contacted uts against a Company * * @param int id Company ID * * @return int Contact last contacted date as uts (or -1) */ public function getCompanyLastContactUTS($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_COMPANY, 'colname' => 'zbsco_lastcontacted', 'ignoreowner' => true)); } return false; } /** * updates lastcontacted date for a Company * * @param int id Company ID * @param int uts last contacted * * @return bool */ public function setCompanyLastContactUTS($id=-1,$lastContactedUTS=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->addUpdateCompany(array( 'id'=>$id, 'limitedFields'=>array( array('key'=>'zbsco_lastcontacted','val' => $lastContactedUTS,'type' => '%d') ))); } return false; } /** * Returns a set of social accounts for a Company (tw,li,fb) * * @param int id Company ID * * @return array social acc's */ // this is not used yet, ahead of time :) - will work tho ;) public function getCompanySocials($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ // lazy 3 queries, optimise later $tw = $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_COMPANY, 'colname' => 'zbsco_tw', 'ignoreowner' => true)); $li = $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_COMPANY, 'colname' => 'zbsco_li', 'ignoreowner' => true)); $fb = $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_COMPANY, 'colname' => 'zbsco_fb', 'ignoreowner' => true)); return array('tw'=>$tw,'li' => $li, 'fb' => $fb); } return false; } /** * Returns the next company ID and the previous company ID * Used for the navigation between companies. * * @param int id * * @return array int id */ public function getCompanyPrevNext($id=-1){ global $ZBSCRM_t, $wpdb; if($id > 0){ //then run the queries.. $nextSQL = $this->prepare("SELECT MIN(ID) FROM ".$ZBSCRM_t['companies']." WHERE ID > %d", $id); $res['next'] = $wpdb->get_var($nextSQL); $prevSQL = $this->prepare("SELECT MAX(ID) FROM ".$ZBSCRM_t['companies']." WHERE ID < %d", $id); $res['prev'] = $wpdb->get_var($prevSQL); return $res; } return false; } /** * Takes full object and makes a "list view" boiled down version * Used to generate listview objs * * @param array $obj (clean obj) * * @return array (listview ready obj) */ public function listViewObj($company=false,$columnsRequired=array()){ if (is_array($company) && isset($company['id'])){ // copy whole obj $resArr = $company; // here I've translated from DAL2 version (from AJAX) so commented out is no longer req. // ... or they'll naturally be in DAL3 model already //$resArr['id'] = $company['id']; //$resArr['name'] = $company['coname']; $resArr['avatar'] = false; //zeroBS_customerAvatar($resArr['id']); #} Format the date in the list view.. //$formatted_date = zeroBSCRM_date_i18n(-1, strtotime($obj['created'])); // let it use proper obj. //$resArr['added'] = $company['created_date']; #} Custom columns #} Tags if (in_array('tagged', $columnsRequired)){ $resArr['tags'] = $company['tags']; } // Total value if (in_array('totalvalue', $columnsRequired)){ #} Calc total value + add to return array $resArr['totalvalue'] = zeroBSCRM_formatCurrency(0); if (isset($company['total_value'])) $resArr['totalvalue'] = zeroBSCRM_formatCurrency($company['total_value']); } // When Company<->Quotes: // Quotes /*if ( in_array( 'quotetotal', $columnsRequired ) ) { if ( isset( $company['quotes_total'] ) ) { $resArr['quotestotal'] = zeroBSCRM_formatCurrency( $company['quotes_total'] ); } else { $resArr['quotestotal'] = zeroBSCRM_formatCurrency( 0 ); } }*/ // Invoices if ( in_array('invoicetotal', $columnsRequired ) ) { if ( isset( $company['invoices_total'] ) ) { $resArr['invoicestotal'] = zeroBSCRM_formatCurrency( $company['invoices_total'] ); // also pass total without formatting (used for hasinvoices check) $resArr['invoices_total_value'] = $company['invoices_total']; } else { $resArr['invoicestotal'] = zeroBSCRM_formatCurrency( 0 ); } } // Transactions if (in_array('transactiontotal', $columnsRequired)){ $resArr['transactionstotal'] = zeroBSCRM_formatCurrency(0); if (isset($company['transactions_value'])) $resArr['transactionstotal'] = zeroBSCRM_formatCurrency($company['transactions_value']); } // v3.0 if (isset($company['transactions_total'])){ // DAL2 way, brutal effort. $resArr['transactions_total'] = zeroBSCRM_formatCurrency($company['transactions_total']); // also pass total without formatting (used for hastransactions check) $resArr['transactions_total_value'] = $company['transactions_total']; } // avatar mode $avatarMode = zeroBSCRM_getSetting( 'avatarmode' ); #} Contacts at company $contactsAtCo = zeroBS_getCustomers(true,1000,0,false,false,'',false,false,$company['id']); // build as str $resArr['contacts'] = ''; // when a company had many contacts the UI was breached, here we max out at 4... $contactCount = 0; foreach ( $contactsAtCo as $contact ){ // stop at 4 if ($contactCount >= 4){ $resArr['contacts'] .= '<a href="' . jpcrm_esc_link( 'view', $company['id'], ZBS_TYPE_COMPANY ) . '" title="'.__('View all contacts at company','zero-bs-crm').'">...</a>'; break; } // add avatar/label if ( $avatarMode !== 3 ) { $resArr['contacts'] .= zeroBS_getCustomerIcoLinked($contact['id']); // or zeroBS_getCustomerIcoLinkedLabel? } else { // no avatars, use labels $resArr['contacts'] .= zeroBS_getCustomerLinkedLabel($contact['id']); } $contactCount++; } return $resArr; } return false; } /** * remove any non-db fields from the object * basically takes array like array('owner'=>1,'fname'=>'x','fullname'=>'x') * and returns array like array('owner'=>1,'fname'=>'x') * This does so based on the objectModel! * * @param array $obj (clean obj) * * @return array (db ready arr) */ private function db_ready_company($obj=false){ // use the generic? (override here if necessary) return $this->db_ready_obj($obj); } // =============================================================================== // ============ Formatting =================================================== /** * Returns a formatted company name +- id, address (e.g. Automattic Ltd. 12 London Street #23) * * @param array $obj (tidied db obj) * * @return string name */ public function format_name_etc( $companyArr=array(), $args=array() ){ #} =========== LOAD ARGS ============== $defaultArgs = array( 'incFirstLineAddr' => false, 'incID' => false ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= $str = ''; if (isset($companyArr['name'])) $str = $companyArr['name']; // First line of addr? if ($incFirstLineAddr) if (isset($companyArr['addr1']) && !empty($companyArr['addr1'])) $str .= ' ('.$companyArr['addr1'].')'; // ID? if ($incID) $str .= ' #'.$companyArr['id']; return $str; } // =========== / Formatting =================================================== // =============================================================================== } // / class
projects/plugins/crm/includes/ZeroBSCRM.CRON.php
<?php /* ! * Jetpack CRM * https://jetpackcrm.com * V1.2.3 * * Copyright 2020 Automattic * * Date: 15/12/16 */ /* To add to cron: 1) Add to list (#1) 2) Add func x 2 (#2) To see what cron is enabled: http://wordpress.stackexchange.com/questions/98032/is-there-a-quick-way-to-view-the-wp-cron-schedule <?php $cron_jobs = get_option( 'cron' ); print_r($cron_jobs); ?> */ /* ====================================================== Wrapper Arr (lists of cron to add) ====================================================== */ global $zbscrm_CRONList; $zbscrm_CRONList = array( ##WLREMOVE 'zbstele' => 'daily', 'zbsext' => 'daily', ##/WLREMOVE 'zbsnotifyevents' => 'hourly', // 'clearTempHashes' => 'hourly' 'zbsclearseclogs' => 'daily', 'jpcrm_cron_watcher' => 'twicedaily', ); /* ====================================================== /Wrapper Arr (lists of cron to add) ====================================================== */ /* ====================================================== Add Jetpack CRM Custom schedule (5m) // https://wordpress.stackexchange.com/questions/208135/how-to-run-a-function-every-5-minutes ====================================================== */ function zeroBSCRM_cronSchedules( $schedules ) { if ( ! isset( $schedules['5min'] ) ) { $schedules['5min'] = array( 'interval' => 5 * 60, 'display' => __( 'Once every 5 minutes', 'zero-bs-crm' ), ); } return $schedules; } add_filter( 'cron_schedules', 'zeroBSCRM_cronSchedules' ); /* ====================================================== /Add Jetpack CRM Custom schedule (5m) ====================================================== */ function zeroBSCRM_deactivateCrons() { global $zbscrm_CRONList; foreach ( $zbscrm_CRONList as $cronName => $timingStr ) { wp_clear_scheduled_hook( $cronName ); } } register_deactivation_hook( ZBS_ROOTFILE, 'zeroBSCRM_deactivateCrons' ); /* ====================================================== Actual Action Funcs #2 ====================================================== */ function jpcrm_cron_notify_tasks() { // } Simple jpcrm_notify_tasks(); } add_action( 'zbsnotifyevents', 'jpcrm_cron_notify_tasks' ); function jpcrm_cron_watcher() { global $zbscrm_CRONList; // Get all the cronjobs from extensions to be watched $cronjobs_to_monitor = apply_filters( 'jpcrm_cron_to_monitor', $zbscrm_CRONList ); if ( is_array( $cronjobs_to_monitor ) ) { foreach ( $cronjobs_to_monitor as $cron_name => $recurrence ) { // Check if the cronjob is working/scheduled if ( ! wp_next_scheduled( $cron_name ) ) { wp_schedule_event( time(), $recurrence, $cron_name ); } } } } add_action( 'jpcrm_cron_watcher', 'jpcrm_cron_watcher' ); register_activation_hook( ZBS_ROOTFILE, 'jpcrm_cron_watcher' ); // ======= Clear temporary hashes /* function zeroBSCRM_cron_clearTempHashes() { #} Simple zeroBSCRM_clearTemporaryHashes(); } add_action('zbscleartemphashes', 'zeroBSCRM_cron_clearTempHashes'); */ // ======= Clear security logs (from easy-pay hash requests) *after 72h function zeroBSCRM_cron_clearSecLogs() { // } Simple zeroBSCRM_clearSecurityLogs(); } add_action( 'zbsclearseclogs', 'zeroBSCRM_cron_clearSecLogs' ); /* ====================================================== / Actual Action Funcs ====================================================== */ /* ====================================================== CRONNABLE FUNCTION (should house these somewhere) ====================================================== */ // Notify user of upcoming task (task) function jpcrm_notify_tasks() { // is the email notification active? (if not, nothing to do) if ( ! zeroBSCRM_get_email_status( ZBSEMAIL_TASK_NOTIFICATION ) ) { return; } global $zbs; // retrieve upcoming task reminders $due_task_reminders = $zbs->DAL->eventreminders->getEventreminders( array( 'dueBefore' => time() + 3600, // anytime within next hour 'dueAfter' => time() - 3600, // anytime from -1h 'sent' => false, // reminders which hasn't been sent ) ); // cycle through them, if any foreach ( $due_task_reminders as $task_reminder ) { $task = $zbs->DAL->events->getEvent( $task_reminder['event'] ); // check if task // check task not complete (if so, no need to send) // check if task has owner if ( is_array( $task ) && $task['complete'] !== 1 && $task['owner'] > 0 ) { // retrieve target (task owner) $owner_info = get_userdata( $task['owner'] ); if ( $owner_info > 0 ) { // email $owner_email = $owner_info->user_email; // send notification email (tracking dealt with by zeroBSCRM_mailDelivery_sendMessage) // ========================================================================================== // =================================== MAIL SENDING ========================================= // generate html $emailHTML = jpcrm_task_generate_notification_html( true, $owner_email, $task['id'], $task ); // build send array $mailArray = array( 'toEmail' => $owner_email, 'toName' => '', 'subject' => zeroBSCRM_mailTemplate_getSubject( ZBSEMAIL_TASK_NOTIFICATION ), 'headers' => zeroBSCRM_mailTemplate_getHeaders( ZBSEMAIL_TASK_NOTIFICATION ), 'body' => $emailHTML, 'textbody' => '', 'options' => array( 'html' => 1, ), 'tracking' => array( // tracking :D (auto-inserted pixel + saved in history db) 'emailTypeID' => ZBSEMAIL_TASK_NOTIFICATION, 'targetObjID' => $task['owner'], 'senderWPID' => -13, 'associatedObjID' => $task['id'], ), ); // Sends email, including tracking, via setting stored route out, (or default if none) // and logs tracking :) // discern delivery method $mailDeliveryMethod = zeroBSCRM_mailTemplate_getMailDelMethod( ZBSEMAIL_TASK_NOTIFICATION ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase if ( ! isset( $mailDeliveryMethod ) || empty( $mailDeliveryMethod ) ) { $mailDeliveryMethod = -1; } // send $sent = zeroBSCRM_mailDelivery_sendMessage( $mailDeliveryMethod, $mailArray ); // mark as sent $zbs->DAL->eventreminders->setSentStatus( $task_reminder['id'], 1 ); // =================================== / MAIL SENDING ======================================= // ========================================================================================== } // / if owner exists as wp user } // / if task, if task not complete, if task has owner } }
projects/plugins/crm/includes/ZeroBSCRM.DAL3.Obj.LineItems.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V3.0+ * * Copyright 2020 Automattic * * Date: 14/01/19 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* Note on these getting separate DAL OBJ LAYER (excerpt from WH DAL3.0 notes) - There are a few tables which are nested (no separate DAL2.Obj file), for these reasons: - Meta, Custom Fields, ObjLinks are used so universally that they have been left in main DAL2.php - Event Reminders sit within Events.php obj layer file - LineItems get their own file, while they could sit in DAL2, they're new, and using the object layer will speed up the code write (easy get funcs etc. using obj model). Arguably these + meta, custom fields, etc. could sit somewhere else (these are used for Quotes, Invs, Trans) */ /** * ZBS DAL >> LineItems * * @author Woody Hayday <hello@jetpackcrm.com> * @version 2.0 * @access public * @see https://jetpackcrm.com/kb */ class zbsDAL_lineitems extends zbsDAL_ObjectLayer { protected $objectType = ZBS_TYPE_LINEITEM; protected $objectDBPrefix = 'zbsli_'; protected $objectModel = array( // ID 'ID' => array('fieldname' => 'ID', 'format' => 'int'), // site + team generics 'zbs_site' => array('fieldname' => 'zbs_site', 'format' => 'int'), 'zbs_team' => array('fieldname' => 'zbs_team', 'format' => 'int'), 'zbs_owner' => array('fieldname' => 'zbs_owner', 'format' => 'int'), // other fields 'order' => array('fieldname' => 'zbsli_order', 'format' => 'int'), 'title' => array( 'fieldname' => 'zbsli_title', 'format' => 'str', 'max_len' => 300 ), 'desc' => array( 'fieldname' => 'zbsli_desc', 'format' => 'str', 'max_len' => 300 ), 'quantity' => array('fieldname' => 'zbsli_quantity', 'format' => 'decimal'), 'price' => array('fieldname' => 'zbsli_price', 'format' => 'decimal'), 'currency' => array('fieldname' => 'zbsli_currency', 'format' => 'curr'), 'net' => array('fieldname' => 'zbsli_net', 'format' => 'decimal'), 'discount' => array('fieldname' => 'zbsli_discount', 'format' => 'decimal'), 'fee' => array('fieldname' => 'zbsli_fee', 'format' => 'decimal'), 'shipping' => array('fieldname' => 'zbsli_shipping', 'format' => 'decimal'), 'shipping_taxes' => array('fieldname' => 'zbsli_shipping_taxes', 'format' => 'str'), 'shipping_tax' => array('fieldname' => 'zbsli_shipping_tax', 'format' => 'decimal'), 'taxes' => array('fieldname' => 'zbsli_taxes', 'format' => 'str'), 'tax' => array('fieldname' => 'zbsli_tax', 'format' => 'decimal'), 'total' => array('fieldname' => 'zbsli_total', 'format' => 'decimal'), 'created' => array('fieldname' => 'zbsli_created', 'format' => 'uts'), 'lastupdated' => array('fieldname' => 'zbsli_lastupdated', 'format' => 'uts'), ); function __construct($args=array()) { #} =========== LOAD ARGS ============== $defaultArgs = array( //'tag' => false, ); foreach ($defaultArgs as $argK => $argV){ $this->$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $this->$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$this->$argK = $newData;} else { $this->$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= } // =============================================================================== // =========== LINEITEM ======================================================= /** * returns full lineitem line +- details * * @param int id lineitem id * @param array $args Associative array of arguments * * @return array lineitem object */ public function getLineitem($id=-1,$args=array()){ global $zbs; #} =========== LOAD ARGS ============== $defaultArgs = array( // permissions 'ignoreowner' => false, // this'll let you not-check the owner of obj // returns scalar ID of line 'onlyID' => false, 'fields' => false // false = *, array = fieldnames ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} Check ID $id = (int)$id; if ( (!empty($id) && $id > 0) || (!empty($email)) || (!empty($externalSource) && !empty($externalSourceUID)) ){ global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); $extraSelect = ''; #} ============= PRE-QUERY ============ $selector = 'lineitem.*'; if (isset($fields) && is_array($fields)) { $selector = ''; // always needs id, so add if not present if (!in_array('ID',$fields)) $selector = 'lineitem.ID'; foreach ($fields as $f) { if (!empty($selector)) $selector .= ','; $selector .= 'lineitem.'.$f; } } else if ($onlyID){ $selector = 'lineitem.ID'; } #} ============ / PRE-QUERY =========== #} Build query $query = "SELECT ".$selector.$extraSelect." FROM ".$ZBSCRM_t['lineitems'].' as lineitem'; #} ============= WHERE ================ if (!empty($id) && $id > 0){ #} Add ID $wheres['ID'] = array('ID','=','%d',$id); } #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort('ID','DESC') . $this->buildPaging(0,1); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_row($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret Results (ROW) if (isset($potentialRes) && isset($potentialRes->ID)) { #} Has results, tidy + return #} Only ID? return it directly if ($onlyID) return $potentialRes->ID; // tidy if (is_array($fields)){ // guesses fields based on table col names $res = $this->lazyTidyGeneric($potentialRes); } else { // proper tidy $res = $this->tidy_lineitem($potentialRes,$withCustomFields); } return $res; } } // / if ID return false; } /** * returns lineitem detail lines * * @param array $args Associative array of arguments * * @return array of lineitem lines */ public function getLineitems($args=array()){ global $zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( // Search/Filtering (leave as false to ignore) 'searchPhrase' => '', // searches zbsli_title, zbsli_desc 'associatedObjType' => false, // e.g. ZBS_TYPE_QUOTE 'associatedObjID' => false, // e.g. 123 // Note on associated types: They can be used: // associatedObjType // associatedObjType + associatedObjID // BUT NOT JUST associatedObjID (would bring collisions) 'withCustomFields' => false, // none yet anyhow // returns 'count' => false, 'sortByField' => 'ID', 'sortOrder' => 'ASC', 'page' => 0, // this is what page it is (gets * by for limit) 'perPage' => 100, 'whereCase' => 'AND', // DEFAULT = AND // permissions 'ignoreowner' => false, // this'll let you not-check the owner of obj ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= global $ZBSCRM_t,$wpdb,$zbs; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); $joinQ = ''; $extraSelect = ''; #} ============= PRE-QUERY ============ #} Capitalise this $sortOrder = strtoupper($sortOrder); #} If just count, turn off any extra gumpf //if ($count) { } #} ============ / PRE-QUERY =========== #} Build query $query = "SELECT lineitem.*".$extraSelect." FROM ".$ZBSCRM_t['lineitems'].' as lineitem'.$joinQ; #} Count override if ($count) $query = "SELECT COUNT(lineitem.ID) FROM ".$ZBSCRM_t['lineitems'].' as lineitem'.$joinQ; #} ============= WHERE ================ #} Add Search phrase if (!empty($searchPhrase)){ // search? - ALL THESE COLS should probs have index of FULLTEXT in db? $searchWheres = array(); $searchWheres['search_title'] = array('zbsli_title','LIKE','%s','%'.$searchPhrase.'%'); $searchWheres['search_desc'] = array('zbsli_desc','LIKE','%s','%'.$searchPhrase.'%'); // This generates a query like 'zbsli_fname LIKE %s OR zbsli_lname LIKE %s', // which we then need to include as direct subquery (below) in main query :) $searchQueryArr = $this->buildWheres($searchWheres,'',array(),'OR',false); if (is_array($searchQueryArr) && isset($searchQueryArr['where']) && !empty($searchQueryArr['where'])){ // add it $wheres['direct'][] = array('('.$searchQueryArr['where'].')',$searchQueryArr['params']); } } // associated object search // simplifiers $hasObjType = false; $hasObjID = false; if (!empty($associatedObjType) && $associatedObjType > 0) $hasObjType = true; if (!empty($associatedObjID) && $associatedObjID > 0) $hasObjID = true; // switch depending on setup if ($hasObjType && $hasObjID){ // has id + type to match to (e.g. quote 123) $wheres['associatedObjType'] = array('ID','IN','(SELECT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = ".ZBS_TYPE_LINEITEM." AND zbsol_objtype_to = %d AND zbsol_objid_to = %d)",array($associatedObjType,$associatedObjID)); } else if ($hasObjType && !$hasObjID){ // has type but no id // e.g. line items attached to invoices $wheres['associatedObjType'] = array('ID','IN','(SELECT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = ".ZBS_TYPE_LINEITEM." AND zbsol_objtype_to = %d)",$associatedObjType); } else if ($hasObjID && !$hasObjType){ // has id but no type // DO NOTHING, this is dodgy to ever call :) as collision of objs } #} Any additionalWhereArr? if (isset($additionalWhereArr) && is_array($additionalWhereArr) && count($additionalWhereArr) > 0){ // add em onto wheres (note these will OVERRIDE if using a key used above) // Needs to be multi-dimensional $wheres = array_merge($wheres,$additionalWhereArr); $wheres = array_merge_recursive($wheres,$additionalWhereArr); } #} ============ / WHERE =============== #} CHECK this + reset to default if faulty if (!in_array($whereCase,array('AND','OR'))) $whereCase = 'AND'; #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params,$whereCase); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner,'contact'); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort($sortByField,$sortOrder) . $this->buildPaging($page,$perPage); try { #} Prep & run query $queryObj = $this->prepare($query,$params); #} Catch count + return if requested if ($count) return $wpdb->get_var($queryObj); #} else continue.. $potentialRes = $wpdb->get_results($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret results (Result Set - multi-row) if (isset($potentialRes) && is_array($potentialRes) && count($potentialRes) > 0) { #} Has results, tidy + return foreach ($potentialRes as $resDataLine) { // tidy $resArr = $this->tidy_lineitem($resDataLine,$withCustomFields); $res[] = $resArr; } } return $res; } /** * Returns a count of lineitems (owned) * .. inc by status * * @return int count */ public function getLineItemCount($args=array()){ #} ============ LOAD ARGS ============= $defaultArgs = array( // Search/Filtering (leave as false to ignore) // permissions 'ignoreowner' => true, // this'll let you not-check the owner of obj ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= $whereArr = array(); return $this->DAL()->getFieldByWHERE(array( 'objtype' => ZBS_TYPE_LINEITEM, 'colname' => 'COUNT(ID)', 'where' => $whereArr, 'ignoreowner' => $ignoreowner)); } /** * returns tax summary array, of taxes applicable to given lineitems * * @param array $args Associative array of arguments * * @return array summary of taxes (e.g. array(array('name' => 'VAT','rate' => 20, 'value' => 123.44))) */ public function getLineitemsTaxSummary($args=array()){ global $zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( // pass lineitems objs in array 'lineItems' => array() ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= $summaryData = array(); // calc if (isset($lineItems) && is_array($lineItems) && count($lineItems) > 0){ $lineItemTaxes = array(); $taxRateTable = zeroBSCRM_taxRates_getTaxTableArr(true); foreach ($lineItems as $lineItem){ // got any taxes on ? if (isset($lineItem['net']) && isset($lineItem['taxes'])){ $taxRatesToApply = array(); // get any taxes... if (strpos($lineItem['taxes'],',')){ $taxRateIDs = explode(',', $lineItem['taxes']); if (is_array($taxRateIDs)) $taxRatesToApply = $taxRateIDs; } else $taxRatesToApply[] = (int)$lineItem['taxes']; // calc these ones + add to summary if (is_array($taxRatesToApply)) foreach ($taxRatesToApply as $taxRateID){ $rateID = (int)$taxRateID; if (isset($taxRateTable[$rateID])){ // get rate $rate = 0.0; if (isset($taxRateTable[$rateID]['rate'])) $rate = (float)$taxRateTable[$rateID]['rate']; // calc + add $itemNet = $lineItem['net']; if (isset($lineItem['discount'])) $itemNet -= $lineItem['discount']; $taxValue = round($itemNet*($rate/100),2); // add to summary if (!isset($summaryData[$rateID])){ // new, add $summaryData[$rateID] = array( 'name' => $taxRateTable[$rateID]['name'], 'rate' => $rate, 'value' => $taxValue ); } else { // += $summaryData[$rateID]['value'] += $taxValue; } } // else not set? } // / foreach tax rate to apply } // / if has net and taxes } // / foreach line item } // / if has items return $summaryData; } /** * adds or updates a lineitem object * * @param array $args Associative array of arguments * id (if update), owner, data (array of field data) * * @return int line ID */ public function addUpdateLineitem($args=array()){ global $ZBSCRM_t,$wpdb,$zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'owner' => -1, // assign to 'linkedObjType' => -1, 'linkedObjID' => -1, // fields (directly) 'data' => array( 'order' => '', 'title' => '', 'desc' => '', 'quantity' => '', 'price' => '', 'currency' => '', 'net' => '', 'discount' => '', 'fee' => '', 'shipping' => '', 'shipping_taxes' => '', 'shipping_tax' => '', 'taxes' => '', 'tax' => '', 'total' => '', 'lastupdated' => '', // allow this to be set for sync etc. 'created' => -1, ), 'limitedFields' => -1, // if this is set it OVERRIDES data (allowing you to set specific fields + leave rest in tact) // ^^ will look like: array(array('key'=>x,'val'=>y,'type'=>'%s')) 'silentInsert' => false, // this was for init Migration - it KILLS all IA for newLineitem (because is migrating, not creating new :) this was -1 before 'do_not_update_blanks' => false, // this allows you to not update fields if blank (same as fieldoverride for extsource -> in) 'calculate_totals' => false // This allows us to recalculate tax, subtotal, total via php (e.g. if added via api). Only works if not using limitedFields ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ $id = (int)$id; // here we check that the potential owner CAN even own if ($owner > 0 && !user_can($owner,'admin_zerobs_usr')) $owner = -1; // if owner = -1, add current if (!isset($owner) || $owner === -1) { $owner = zeroBSCRM_user(); } if (is_array($limitedFields)){ // LIMITED UPDATE (only a few fields.) if (!is_array($limitedFields) || count ($limitedFields) <= 0) return false; // REQ. ID too (can only update) if (empty($id) || $id <= 0) return false; } else { // NORMAL, FULL UPDATE // (re)calculate the totals etc? if (isset($calculate_totals) && $calculate_totals){ $data = $this->recalculate($data); } } #} ========= / CHECK FIELDS =========== #} ========= OVERRIDE SETTING (Deny blank overrides) =========== // either ext source + setting, or set by the func call if ($do_not_update_blanks){ // this setting says 'don't override filled-out data with blanks' // so here we check through any passed blanks + convert to limitedFields // only matters if $id is set (there is somt to update not add if (isset($id) && !empty($id) && $id > 0){ // get data to copy over (for now, this is required to remove 'fullname' etc.) $dbData = $this->db_ready_lineitem($data); //unset($dbData['id']); // this is unset because we use $id, and is update, so not req. legacy issue //unset($dbData['created']); // this is unset because this uses an obj which has been 'updated' against original details, where created is output in the WRONG format :) $origData = $data; //$data = array(); $limitedData = array(); // array(array('key'=>'zbsli_x','val'=>y,'type'=>'%s')) // cycle through + translate into limitedFields (removing any blanks, or arrays (e.g. externalSources)) // we also have to remake a 'faux' data (removing blanks for tags etc.) for the post-update updates foreach ($dbData as $k => $v){ $intV = (int)$v; // only add if valuenot empty if (!is_array($v) && !empty($v) && $v != '' && $v !== 0 && $v !== -1 && $intV !== -1){ // add to update arr $limitedData[] = array( 'key' => 'zbsli_'.$k, // we have to add zbsli_ here because translating from data -> limited fields 'val' => $v, 'type' => $this->getTypeStr('zbsli_'.$k) ); // add to remade $data for post-update updates $data[$k] = $v; } } // copy over $limitedFields = $limitedData; } // / if ID } // / if do_not_update_blanks #} ========= / OVERRIDE SETTING (Deny blank overrides) =========== #} ========= BUILD DATA =========== $update = false; $dataArr = array(); $typeArr = array(); if (is_array($limitedFields)){ // LIMITED FIELDS $update = true; // cycle through foreach ($limitedFields as $field){ // some weird case where getting empties, so added check if (!empty($field['key'])){ $dataArr[$field['key']] = $field['val']; $typeArr[] = $field['type']; } } // add update time if (!isset($dataArr['zbsli_lastupdated'])){ $dataArr['zbsli_lastupdated'] = time(); $typeArr[] = '%d'; } } else { // FULL UPDATE/INSERT // UPDATE $dataArr = array( // ownership // no need to update these (as of yet) - can't move teams etc. //'zbs_site' => zeroBSCRM_installSite(), //'zbs_team' => zeroBSCRM_installTeam(), //'zbs_owner' => $owner, 'zbsli_order' => $data['order'], 'zbsli_title' => $data['title'], 'zbsli_desc' => $data['desc'], 'zbsli_quantity' => $data['quantity'], 'zbsli_price' => $data['price'], 'zbsli_currency' => $data['currency'], 'zbsli_net' => $data['net'], 'zbsli_discount' => $data['discount'], 'zbsli_fee' => $data['fee'], 'zbsli_shipping' => $data['shipping'], 'zbsli_shipping_taxes' => $data['shipping_taxes'], 'zbsli_shipping_tax' => $data['shipping_tax'], 'zbsli_taxes' => $data['taxes'], 'zbsli_tax' => $data['tax'], 'zbsli_total' => $data['total'], 'zbsli_lastupdated' => time(), ); $typeArr = array( // field data types //'%d', // site //'%d', // team //'%d', // owner '%d', '%s', '%s', '%f', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', ); if (!empty($id) && $id > 0){ // is update $update = true; } else { // INSERT (get's few extra :D) $update = false; $dataArr['zbs_site'] = zeroBSCRM_site(); $typeArr[] = '%d'; $dataArr['zbs_team'] = zeroBSCRM_team(); $typeArr[] = '%d'; $dataArr['zbs_owner'] = $owner; $typeArr[] = '%d'; if (isset($data['created']) && !empty($data['created']) && $data['created'] !== -1){ $dataArr['zbsli_created'] = $data['created'];$typeArr[] = '%d'; } else { $dataArr['zbsli_created'] = time(); $typeArr[] = '%d'; } } } #} ========= / BUILD DATA =========== #} ============================================================ #} ========= CHECK force_uniques & not_empty & max_len ======== // if we're passing limitedFields we skip these, for now // #v3.1 - would make sense to unique/nonempty check just the limited fields. #gh-145 if (!is_array($limitedFields)){ // verify uniques if (!$this->verifyUniqueValues($data,$id)) return false; // / fails unique field verify // verify not_empty if (!$this->verifyNonEmptyValues($data)) return false; // / fails empty field verify } // whatever we do we check for max_len breaches and abbreviate to avoid wpdb rejections $dataArr = $this->wpdbChecks($dataArr); #} ========= / CHECK force_uniques & not_empty ================ #} ============================================================ #} Check if ID present if ($update){ #} Attempt update if ($wpdb->update( $ZBSCRM_t['lineitems'], $dataArr, array( // where 'ID' => $id ), $typeArr, array( // where data types '%d' )) !== false){ // if passing limitedFields instead of data, we ignore the following // this doesn't work, because data is in args default as arr //if (isset($data) && is_array($data)){ // so... if (!isset($limitedFields) || !is_array($limitedFields) || $limitedFields == -1){ } // / if $data // linked to anything? if ($linkedObjType > 0 && $linkedObjID > 0){ // if not already got obj link, add it $c = $this->DAL()->getObjsLinksLinkedToObj(array( 'objtypefrom' => ZBS_TYPE_LINEITEM, // line item type (10) 'objtypeto' => $linkedObjType, // obj type (e.g. inv) 'objfromid' => $id, 'objtoid' => $linkedObjID, 'direction' => 'both', 'count' => true, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_LINEITEM))); // add link (via append) if not present if ($c <= 0) $this->DAL()->addUpdateObjLink(array( 'data'=>array( 'objtypefrom' => ZBS_TYPE_LINEITEM, 'objtypeto' => $linkedObjType, 'objfromid' => $id, 'objtoid' => $linkedObjID, // not req. 'owner' => $owner ) )); } /* Not necessary #} INTERNAL AUTOMATOR #} & #} FALLBACKS // UPDATING CONTACT if (!$silentInsert){ // IA General lineitem update (2.87+) zeroBSCRM_FireInternalAutomator('lineitem.update',array( 'id'=>$id, 'againstid' => $id, 'data'=> $dataArr )); } */ // Successfully updated - Return id return $id; } else { $msg = __('DB Update Failed','zero-bs-crm'); $zbs->DAL->addError(302,$this->objectType,$msg,$dataArr); // FAILED update return false; } } else { #} No ID - must be an INSERT if ($wpdb->insert( $ZBSCRM_t['lineitems'], $dataArr, $typeArr ) > 0){ #} Successfully inserted, lets return new ID $newID = $wpdb->insert_id; // linked to anything? if ($linkedObjType > 0 && $linkedObjID > 0){ // if not already got obj link, add it $c = $this->DAL()->getObjsLinksLinkedToObj(array( 'objtypefrom' => ZBS_TYPE_LINEITEM, // line item type (10) 'objtypeto' => $linkedObjType, // obj type (e.g. inv) 'objfromid' => $newID, 'objtoid' => $linkedObjID, 'direction' => 'both', 'count' => true, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_LINEITEM))); // add link (via append) if not present if ($c <= 0) $this->DAL()->addUpdateObjLink(array( 'data'=>array( 'objtypefrom' => ZBS_TYPE_LINEITEM, 'objtypeto' => $linkedObjType, 'objfromid' => $newID, 'objtoid' => $linkedObjID, // not req. 'owner' => $owner ) )); } /* Not necessary #} INTERNAL AUTOMATOR #} & #} FALLBACKS // NEW CONTACT if (!$silentInsert){ #} Add to automator zeroBSCRM_FireInternalAutomator('lineitem.new',array( 'id'=>$newID, 'data'=>$dataArr, 'extsource'=>$approvedExternalSource, 'automatorpassthrough'=>$automatorPassthrough, #} This passes through any custom log titles or whatever into the Internal automator recipe. 'extraMeta'=>$confirmedExtraMeta #} This is the "extraMeta" passed (as saved) )); } */ return $newID; } else { $msg = __('DB Insert Failed','zero-bs-crm'); $zbs->DAL->addError(303,$this->objectType,$msg,$dataArr); #} Failed to Insert return false; } } return false; } /** * deletes a lineitem object * * NOTE! Not to be used directly, or if so, manually delete the objlinks for this item<->obj (e.g. inv) else garbage kept in objlinks table * Use: deleteLineItemsForObject * * @param array $args Associative array of arguments * id * * @return int success; */ public function deleteLineitem($args=array()){ global $ZBSCRM_t,$wpdb,$zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'saveOrphans' => true, ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} Check ID & Delete :) $id = (int)$id; if (!empty($id) && $id > 0) { // delete orphans? if ($saveOrphans === false){ } return zeroBSCRM_db2_deleteGeneric($id,'lineitems'); } return false; } /** * deletes all lineitem objects assigned to another obj (quote,inv,trans) * * @param array $args Associative array of arguments * id * * @return int success; */ public function deleteLineItemsForObject($args=array()){ global $ZBSCRM_t,$wpdb,$zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( 'objID' => -1, 'objType' => -1 ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} Check ID & Delete :) $objID = (int)$objID; if (!empty($objID) && $objID > 0 && !empty($objType) && $objType > 0) { $lineItems = $this->getLineitems(array('associatedObjType'=>$objType,'associatedObjID'=>$objID,'perPage'=>1000,'ignoreowner'=>true)); $delcount = 0; if (is_array($lineItems)) foreach ($lineItems as $li){ $delcount += $this->deleteLineitem(array('id'=>$li['id'])); // also delete the objlink for this $this->DAL()->deleteObjLinks(array( 'objtypefrom' => ZBS_TYPE_LINEITEM, 'objtypeto' => $objType, 'objfromid' => $li['id'], 'objtoid' => $objID )); } return $delcount; } return false; } /** * tidy's the object from wp db into clean array * * @param array $obj (DB obj) * * @return array lineitem (clean obj) */ private function tidy_lineitem($obj=false,$withCustomFields=false){ $res = false; if (isset($obj->ID)){ $res = array(); $res['id'] = $obj->ID; /* `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, */ $res['owner'] = $obj->zbs_owner; $res['order'] = (int)$obj->zbsli_order; $res['title'] = $this->stripSlashes($obj->zbsli_title); $res['desc'] = $this->stripSlashes($obj->zbsli_desc); $res['quantity'] = zeroBSCRM_format_quantity( $this->stripSlashes( $obj->zbsli_quantity ) ); $res['price'] = $this->stripSlashes($obj->zbsli_price); $res['currency'] = $this->stripSlashes($obj->zbsli_currency); $res['net'] = $this->stripSlashes($obj->zbsli_net); $res['discount'] = $this->stripSlashes($obj->zbsli_discount); $res['fee'] = $this->stripSlashes($obj->zbsli_fee); $res['shipping'] = $this->stripSlashes($obj->zbsli_shipping); $res['shipping_taxes'] = $this->stripSlashes($obj->zbsli_shipping_taxes); $res['shipping_tax'] = $this->stripSlashes($obj->zbsli_shipping_tax); $res['taxes'] = $this->stripSlashes($obj->zbsli_taxes); $res['tax'] = $this->stripSlashes($obj->zbsli_tax); $res['total'] = $this->stripSlashes($obj->zbsli_total); $res['created'] = (int)$obj->zbsli_created; $res['created_date'] = (isset($obj->zbsli_created) && $obj->zbsli_created > 0) ? zeroBSCRM_locale_utsToDatetime($obj->zbsli_created) : false; $res['lastupdated'] = (int)$obj->zbsli_lastupdated; $res['lastupdated_date'] = (isset($obj->zbsli_lastupdated) && $obj->zbsli_lastupdated > 0) ? zeroBSCRM_locale_utsToDatetime($obj->zbsli_lastupdated) : false; } return $res; } /** * Takes whatever lineitem data available and re-calculates net, total, tax etc. * .. returning same obj with updated vals * * @param array $line_item The line item. * * @return array $lineItem */ public function recalculate( $line_item = false ) { if ( is_array( $line_item ) ) { // subtotal (zbsi_net) // == line item Quantity * rate * tax% $total = 0.0; if ( isset( $line_item ) && is_array( $line_item ) ) { // Subtotal if ( isset( $line_item['quantity'] ) && isset( $line_item['price'] ) ) { $quantity = (float) $line_item['quantity']; $price = (float) $line_item['price']; // Discount? (applied to gross) // ALWAYS gross 0.00 value for lineitems (Where as at invoice level can be %) $discount = 0; if ( isset( $line_item['discount'] ) ) { $discount = (float) $line_item['discount']; } // gross $sub_total_pre_discount = $quantity * $price; $sub_total = $sub_total_pre_discount - $discount; // tax - this should be logged against line item, but lets recalc if ( isset( $line_item['taxes'] ) && $line_item['taxes'] !== -1 ) { $line_item['tax'] = zeroBSCRM_taxRates_getTaxValue( $sub_total, $line_item['taxes'] ); } // total would have discount, shipping, but as above, not using per line item as at v3.0 mvp $total = $sub_total + $line_item['tax']; } } $line_item['net'] = $sub_total_pre_discount; $line_item['total'] = $total; return $line_item; } return false; } /** * remove any non-db fields from the object * basically takes array like array('owner'=>1,'fname'=>'x','fullname'=>'x') * and returns array like array('owner'=>1,'fname'=>'x') * This does so based on the objectModel! * * @param array $obj (clean obj) * * @return array (db ready arr) */ private function db_ready_lineitem($obj=false){ // use the generic? (override here if necessary) return $this->db_ready_obj($obj); } // =========== / LINEITEM ======================================================= // =============================================================================== } // / class
projects/plugins/crm/includes/ZeroBSCRM.Core.Extensions.php
<?php /* ! * Jetpack CRM * https://jetpackcrm.com * V1.1.18 * * Copyright 2020 Automattic * * Date: 30/08/16 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) { exit; } /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== EXTENSION Globals ====================================================== */ // this is filtered in core, so if you want to remove/add to this // hook into zbs_exclude_from_settings filter global $zbsExtensionsExcludeFromSettings; $zbsExtensionsExcludeFromSettings = array( 'pdfinv', 'csvimporterlite', 'portal', 'cf7', 'cal', 'batchtagger', 'salesdash', 'envato', 'bulktag', 'clientportalpro', 'mailcampaigns', 'apiconnector', 'contactform7', 'awesomesupport', 'membermouse', 'bulktagger', 'systememailspro', 'woo', 'wpa', 'advancedsegments', 'contactform', 'pay' ); /* ====================================================== EXTENSION Globals ====================================================== */ /* ====================================================== EXTENSION FUNCS ====================================================== */ // } function to detect what extensions are installed // } ONLY WORKS after plugins_loaded // } see https://codex.wordpress.org/Plugin_API/Action_Reference function zeroBSCRM_extensionsInstalled() { // } This list var will be populated via do_action at top of every extension global $zeroBSCRM_extensionsInstalledList; return $zeroBSCRM_extensionsInstalledList; } // } function to return all extensions inc what extensions are installed // } ONLY WORKS after plugins_loaded // } see https://codex.wordpress.org/Plugin_API/Action_Reference function zeroBSCRM_extensionsList() { global $zbs; // } This list is all extensions + which are free global $zeroBSCRM_extensionsCompleteList; // get free $freeExts = zeroBSCRM_extensions_free( true ); // } Process full list inc what's on/off $ret = array(); foreach ( $zeroBSCRM_extensionsCompleteList as $extKey => $extObj ) { // } Get name $extName = $extKey; if ( function_exists( 'zeroBSCRM_extension_name_' . $extKey ) == 'function' ) { $extName = call_user_func( 'zeroBSCRM_extension_name_' . $extKey ); } // } if not, usefallback if ( $extName == $extKey && isset( $extObj['fallbackname'] ) ) { $extName = $extObj['fallbackname']; } $ret[ $extKey ] = array( 'name' => $extName, 'installed' => zeroBSCRM_isExtensionInstalled( $extKey ), 'free' => in_array( $extKey, $freeExts ), 'meta' => $extObj, ); } return $ret; } // } Returns a list split into FREE / PAID function zeroBSCRM_extensionsListSegmented() { $exts = zeroBSCRM_extensionsList(); // } Sort em $ret = array( 'free' => array(), 'paid' => array(), ); foreach ( $exts as $extKey => $ext ) { if ( $ext['free'] ) { $ret['free'][ $extKey ] = $ext; } else { $ret['paid'][ $extKey ] = $ext; } } return $ret; } // } Returns a list of possible PAID exts function zeroBSCRM_extensionsListPaid( $onlyInstalledAndActive = false ) { $exts = zeroBSCRM_extensionsList(); // } Sort em $ret = array(); foreach ( $exts as $extKey => $ext ) { if ( ! $ext['free'] ) { if ( $onlyInstalledAndActive ) { if ( isset( $ext['installed'] ) && $ext['installed'] ) { $ret[ $extKey ] = $ext; } } else { $ret[ $extKey ] = $ext; } } } return $ret; } // } Returns a list of installed PAID exts function zeroBSCRM_activeInstalledProExt() { return zeroBSCRM_extensionsListPaid( true ); } // This is a meshing of Mikes method + our existing ext system // it catches: // Installed, branded extensions // Installed, rebranded extensions // Installed, unactive, branded extensions // DOES NOT FIND: // Installed, unactive, rebranded extensions // ... does this by checking actives for NAMES // ... and checking our installed ext func // REturns array of arrays(name=>,key=>,slug=>) (where possible) /* e.g. ( [Automations] => Array ( [name] => Automations [key] => automations [slug] => [active] => 1 ) [Mail Campaigns] => Array ( [name] => Jetpack CRM Extension: Mail Campaigns [key] => mailcampaigns [slug] => zero-bs-extension-mailcamps/ZeroBSCRM_MailCampaigns.php [active] => -1 ) ) // note keepAllVars allows stripping of unnecessary vars (pre send to update.) */ function zeroBSCRM_installedProExt( $ignoreIfCantFindSlug = false, $keepAllVars = false, $ignoreIfCantFindKey = true ) { $ret = array(); // first go through our 'installedExt' $zbsExtInstalled = zeroBSCRM_activeInstalledProExt(); if ( is_array( $zbsExtInstalled ) ) { foreach ( $zbsExtInstalled as $k => $deets ) { // will have all but only slug where ext's have this: $slug = ''; $file = ''; if ( function_exists( 'zeroBSCRM_extension_file_' . $k ) ) { $file = call_user_func( 'zeroBSCRM_extension_file_' . $k ); $slug = plugin_basename( $file ); } // if here, MUST be active :) $ret[ $deets['name'] ] = array( 'name' => $deets['name'], 'key' => $k, 'slug' => $slug, 'active' => 1, 'ver' => '', 'file' => $file, ); } } // from: https://codex.wordpress.org/Function_Reference/get_plugins // Check if get_plugins() function exists. This is required on the front end of the // site, since it is in a file that is normally only loaded in the admin. if ( ! function_exists( 'get_plugins' ) ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; } // then go through installed plugins and try and grab any deactivated via name $zbs_all = get_plugins(); if ( is_array( $zbs_all ) ) { foreach ( $zbs_all as $slug => $v ) { // } JetpackRebrandRelook if ( $v['Name'] !== 'Jetpack CRM' && stripos( '#' . $v['Name'], 'Jetpack CRM' ) > 0 ) { // is a branded one of ours (probably) // cleaned name $cleanName = str_replace( 'Jetpack CRM Extension: ', '', $v['Name'] ); if ( ! isset( $ret[ $cleanName ] ) ) { // attempt to find deets $key = ''; $potentialItem = zeroBSCRM_returnExtensionDetailsFromName( $cleanName ); if ( is_array( $potentialItem ) ) { $key = $potentialItem['key']; } $active = -1; if ( is_plugin_active( $slug ) ) { $active = 1; } $ret[ $cleanName ] = array( 'name' => $v['Name'], 'key' => $key, 'slug' => $slug, 'active' => $active, 'ver' => $v['Version'], 'file' => '', ); } else { // was set by zeroBSCRM_activeInstalledProExt() above, so fill in any missing details :) if ( empty( $ret[ $cleanName ]['ver'] ) ) { $ret[ $cleanName ]['ver'] = $v['Version']; } } } else { // either CORE crm, or other plugin, or REBRANDED ver of ext // try to catch deactivated rebranded vers? // LICENSING3.0 TODO } } // / foreach plugin } // go through RET + get versions where needed :) + weed out $ignoreIfCantFindSlug $finalReturn = array(); foreach ( $ret as $extName => $ext ) { $extA = $ext; if ( empty( $ext['ver'] ) && ! empty( $ext['file'] ) ) { $pluginFullDeets = get_plugin_data( $ext['file'] ); if ( is_array( $pluginFullDeets ) && isset( $pluginFullDeets['Version'] ) ) { $extA['ver'] = $pluginFullDeets['Version']; } // might as well copy over name if here too :) if ( is_array( $pluginFullDeets ) && isset( $pluginFullDeets['Name'] ) ) { $extA['name'] = $pluginFullDeets['Name']; } } // strip these (unnecessary vars) if ( ! $keepAllVars ) { unset( $extA['file'] ); } // finally, clean any slugs which are coming through as zero-bs-extension-csv-importer/ZeroBSCRM_CSVImporter.php instaed of ZeroBSCRM_CSVImporter.php // (but keep full in 'path') if ( strpos( $extA['slug'], '/' ) > 0 ) { $extA['path'] = $extA['slug']; $extA['slug'] = substr( $extA['slug'], strrpos( $extA['slug'], '/' ) + 1 ); } if ( ( ! $ignoreIfCantFindSlug || ( $ignoreIfCantFindSlug && isset( $extA['slug'] ) && ! empty( $extA['slug'] ) ) ) && ( ! $ignoreIfCantFindKey || ( $ignoreIfCantFindKey && isset( $extA['key'] ) && ! empty( $extA['key'] ) ) ) ) { $finalReturn[ $extName ] = $extA; } } return $finalReturn; } // as above (zeroBSCRM_installedProExt) but returns a single arr for WL Core, if installed function zeroBSCRM_installedWLCore( $ignoreIfCantFindSlug = false, $keepAllVars = false, $ignoreIfCantFindKey = true ) { if ( ! zeroBSCRM_isWL() ) { return false; } $ret = false; // then go through installed plugins and try and grab any deactivated via name $zbs_all = get_plugins(); if ( is_array( $zbs_all ) ) { foreach ( $zbs_all as $slug => $v ) { // if is core :) + WL if ( $slug == plugin_basename( ZBS_ROOTFILE ) ) { // is rebranded core :) // cleaned name $cleanName = $v['Name']; // attempt to find deets $key = 'core'; $active = -1; if ( is_plugin_active( $slug ) ) { $active = 1; } $ret = array( 'name' => $v['Name'], 'key' => $key, 'slug' => $slug, 'active' => $active, 'ver' => $v['Version'], 'file' => '', ); } } // / foreach plugin } // go through RET + get versions where needed :) + weed out $ignoreIfCantFindSlug $finalReturn = array(); $extA = $ret; if ( empty( $ret['ver'] ) && ! empty( $ret['file'] ) ) { $pluginFullDeets = get_plugin_data( $ret['file'] ); if ( is_array( $pluginFullDeets ) && isset( $pluginFullDeets['Version'] ) ) { $extA['ver'] = $pluginFullDeets['Version']; } // might as well copy over name if here too :) if ( is_array( $pluginFullDeets ) && isset( $pluginFullDeets['Name'] ) ) { $extA['name'] = $pluginFullDeets['Name']; } } // strip these (unnecessary vars) if ( ! $keepAllVars ) { unset( $extA['file'] ); } // finally, clean any slugs which are coming through as zero-bs-extension-csv-importer/ZeroBSCRM_CSVImporter.php instaed of ZeroBSCRM_CSVImporter.php // (but keep full in 'path') if ( strpos( $extA['slug'], '/' ) > 0 ) { $extA['path'] = $extA['slug']; $extA['slug'] = substr( $extA['slug'], strrpos( $extA['slug'], '/' ) + 1 ); } if ( ( ! $ignoreIfCantFindSlug || ( $ignoreIfCantFindSlug && isset( $extA['slug'] ) && ! empty( $extA['slug'] ) ) ) && ( ! $ignoreIfCantFindKey || ( $ignoreIfCantFindKey && isset( $extA['key'] ) && ! empty( $extA['key'] ) ) ) ) { $finalReturn = $extA; } return $finalReturn; } function zeroBSCRM_extensionsInstalledCount( $activatedOnly = false ) { // grabs all extensions (rebrander only grabs active, rest grabs active + deactive) $exts = zeroBSCRM_installedProExt(); if ( ! $activatedOnly ) { return count( $exts ); } $c = 0; // typo - should have been $exts not $ext. foreach ( $exts as $e ) { if ( $e['active'] == '1' ) { ++$c; } } return $c; } /* * Returns array of installed (active) core module keys */ function jpcrm_core_modules_installed() { $modules = zeroBSCRM_extensions_free(); $modules_installed = array(); foreach ( $modules as $module_key => $module ) { if ( is_array( $module ) && zeroBSCRM_isExtensionInstalled( $module_key ) ) { $modules_installed[] = $module_key; } } return $modules_installed; } /* * Returns count of installed (active) core modules */ function jpcrm_core_modules_installed_count() { $modules = zeroBSCRM_extensions_free(); $module_count = 0; foreach ( $modules as $module_key => $module ) { if ( is_array( $module ) && zeroBSCRM_isExtensionInstalled( $module_key ) ) { ++$module_count; } } return $module_count; } // } MS - 27th Feb 2019. This is bugged. // } function to detect if a specific extension is installed // } ONLY WORKS after plugins_loaded // } see https://codex.wordpress.org/Plugin_API/Action_Reference function zeroBSCRM_isExtensionInstalled( $extKey = '' ) { // } This list var will be populated via do_action at top of every extension global $zeroBSCRM_extensionsInstalledList, $zbs; if ( count( $zeroBSCRM_extensionsInstalledList ) > 0 ) { foreach ( $zeroBSCRM_extensionsInstalledList as $ext ) { if ( ! empty( $ext ) && $ext == $extKey ) { return true; } } } // } Otherwise it's not! return false; } // } function to return a specific extension details // } ONLY WORKS after plugins_loaded // } see https://codex.wordpress.org/Plugin_API/Action_Reference function zeroBSCRM_returnExtensionDetails( $extKey = '' ) { // } list global $zeroBSCRM_extensionsCompleteList; // get free $freeExts = zeroBSCRM_extensions_free( true ); if ( array_key_exists( $extKey, $zeroBSCRM_extensionsCompleteList ) ) { $extObj = $zeroBSCRM_extensionsCompleteList[ $extKey ]; // } Get name $extName = $extKey; if ( function_exists( 'zeroBSCRM_extension_name_' . $extKey ) == 'function' ) { $extName = call_user_func( 'zeroBSCRM_extension_name_' . $extKey ); } // } if not, usefallback if ( $extName == $extKey && isset( $extObj['fallbackname'] ) ) { $extName = $extObj['fallbackname']; } return array( 'key' => $extKey, 'name' => $extName, 'installed' => zeroBSCRM_isExtensionInstalled( $extKey ), 'free' => in_array( $extKey, $freeExts ), 'meta' => $extObj, ); } // } Otherwise it's not! return false; } // brutal check through list for 'Automations' etc. function zeroBSCRM_returnExtensionDetailsFromName( $extName = '' ) { // } list global $zeroBSCRM_extensionsCompleteList; // get free $freeExts = zeroBSCRM_extensions_free( true ); if ( is_array( $zeroBSCRM_extensionsCompleteList ) ) { foreach ( $zeroBSCRM_extensionsCompleteList as $key => $deets ) { // check against names $thisIsIt = false; if ( $deets['fallbackname'] == $extName ) { $thisIsIt = true; } if ( isset( $deets['name'] ) && $deets['name'] == $extName ) { $thisIsIt = true; } // aliases (where we've changed names, e.g. PayPal Sync -> PayPal Connect) if ( isset( $deets['aliases'] ) && is_array( $deets['aliases'] ) ) { foreach ( $deets['aliases'] as $alias ) { if ( $alias == $extName ) { $thisIsIt = true; } } } if ( $thisIsIt ) { return array( 'key' => $key, 'name' => $extName, 'installed' => zeroBSCRM_isExtensionInstalled( $key ), 'free' => in_array( $key, $freeExts ), ); } } } // } Otherwise it's not! return false; } function zeroBSCRM_hasSyncExtensionActivated() { // tries several plugins to see if installed $hasExtension = false; $syncExtensions = array( 'pay', 'woosync', 'stripesync', 'worldpay', 'groovesync', 'googlesync', 'envato' ); foreach ( $syncExtensions as $ext ) { if ( zeroBSCRM_isExtensionInstalled( $ext ) ) { $hasExtension = true; break; } } return $hasExtension; } function zeroBSCRM_hasPaidExtensionActivated() { $list = zeroBSCRM_extensionsListSegmented(); if ( is_array( $list['paid'] ) && count( $list['paid'] ) > 0 ) { foreach ( $list['paid'] as $extKey => $extDeet ) { // test if ( zeroBSCRM_isExtensionInstalled( $extKey ) ) { return true; } } } return false; } // } Check update - DEFUNCT - moved to transient checks function zeroBSCRM_extensions_checkForUpdates() { } /* ====================================================== / EXTENSION FUNCS ====================================================== */ /* ====================================================== EXTENSION DETAILS / FREE/included EXTENSIONS ====================================================== */ // } JSON short description only // REFRESH this is ever update woo/products: From: https://jetpackcrm.com/wp-json/zbsextensions/v1/extensions/0 function zeroBSCRM_serve_cached_extension_block() { // a localhosted version of the extensions array. Loading images from local. $plugin_url = plugins_url( '', ZBS_ROOTFILE ) . '/'; $imgs = array( 'ph' => $plugin_url . 'i/ext/1px.png', 'rm' => $plugin_url . 'i/ext/registration-magic.png', 'live' => $plugin_url . 'i/ext/livestorm.png', 'exit' => $plugin_url . 'i/ext/exit-bee.png', 'wp' => $plugin_url . 'i/ext/wordpress-utilities.png', 'as' => $plugin_url . 'i/ext/advanced-segments.png', 'aweb' => $plugin_url . 'i/ext/aweber.png', 'mm' => $plugin_url . 'i/ext/member-mouse.png', 'auto' => $plugin_url . 'i/ext/automations.png', 'api' => $plugin_url . 'i/ext/api.png', 'cpp' => $plugin_url . 'i/ext/client-portal-pro.png', 'passw' => $plugin_url . 'i/ext/client-password-manager.png', 'twilio' => $plugin_url . 'i/ext/twillo.png', 'mailchimp' => $plugin_url . 'i/ext/mailchip.png', 'awesomesupport' => $plugin_url . 'i/ext/awesome-support.png', 'convertkit' => $plugin_url . 'i/ext/convertkit.png', 'batchtag' => $plugin_url . 'i/ext/bulk-tagger.png', 'googlecontact' => $plugin_url . 'i/ext/google-contacts.png', 'groove' => $plugin_url . 'i/ext/groove.png', 'contactform' => $plugin_url . 'i/ext/contact-form-7.png', 'stripe' => $plugin_url . 'i/ext/stripe.png', 'worldpay' => $plugin_url . 'i/ext/world-pay.png', 'invpro' => $plugin_url . 'i/ext/invoicing-pro.png', 'gravity' => $plugin_url . 'i/ext/gravity-forms.png', 'csvpro' => $plugin_url . 'i/ext/csv-importer-pro.png', 'mailcamp' => $plugin_url . 'i/ext/mail-campaigns.png', 'paypal' => $plugin_url . 'i/ext/paypal.png', 'salesdash' => $plugin_url . 'i/ext/sales-dashboard.png', ); $json = '{"data":{},"count":29,"paid":[{"id":26172,"name":"Registration Magic Connect","short_desc":"Capture your Registration Magic sign ups into Jetpack CRM. Including First Name and Last Name.","date":{"date":"2019-01-08 12:57:32.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"59","regular_price":"59","image":"' . $imgs['rm'] . '","extkey":"registrationmagic"},{"id":25432,"name":"Livestorm","short_desc":"The Jetpack CRM livestorm connector automatically adds your Livestorm webinar sign ups into Jetpack CRM.","date":{"date":"2018-12-02 22:03:07.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"79","regular_price":"79","image":"' . $imgs['live'] . '","extkey":"livestorm"},{"id":25431,"name":"ExitBee Connect","short_desc":"Exit Bee Connect automatically adds your Exit Bee form completions into Jetpack CRM.","date":{"date":"2018-12-02 21:59:18.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"79","regular_price":"79","image":"' . $imgs['exit'] . '","extkey":"exitbee"},{"id":25336,"name":"WordPress Utilities","short_desc":"The Jetpack CRM WordPress utilities extension adds your website registrations to your Jetpack CRM.","date":{"date":"2018-11-19 22:50:37.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"59","regular_price":"59","image":"' . $imgs['wp'] . '","extkey":"wordpressutilities"},{"id":25174,"name":"Advanced Segments","short_desc":"Easily divide your contacts into dynamic subgroups and manage your contacts effectively","date":{"date":"2018-09-21 10:44:24.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"49","regular_price":"49","image":"' . $imgs['as'] . '","extkey":"advancedsegments"},{"id":24955,"name":"AWeber Connect","short_desc":"Connect your aWeber to your Jetpack CRM and add new Jetpack CRM contacts to your aWeber list.","date":{"date":"2018-07-26 05:02:28.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"39","regular_price":"39","image":"' . $imgs['aweb'] . '","extkey":"aweber"},{"id":24763,"name":"Membermouse Connect","short_desc":"Enhance your MemberMouse subscription website by integrating your data with Jetpack CRM","date":{"date":"2018-07-24 17:29:28.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"79","regular_price":"79","image":"' . $imgs['mm'] . '","extkey":"membermouse"},{"id":24696,"name":"Automations","short_desc":"Let Automations handle the mundane tasks within your CRM and save yourself time.","date":{"date":"2018-07-22 15:24:14.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"79","regular_price":"79","image":"' . $imgs['auto'] . '","extkey":"automations"},{"id":24692,"name":"API Connector","short_desc":"Connects your website to Jetpack CRM via the API. Supports Forms, Website Registrations. Use on as many external sites as you like.","date":{"date":"2018-07-09 00:46:59.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"59","regular_price":"59","image":"' . $imgs['api'] . '","extkey":"apiconnector"},{"id":24676,"name":"Client Portal Pro","short_desc":"Customise your Client Portal, Allow File Downloads, Display Tasks and Tickets plus much more","date":{"date":"2018-07-06 17:40:11.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"79","regular_price":"79","image":"' . $imgs['cpp'] . '","extkey":"clientportalpro"},{"id":24569,"name":"Client Password Manager","short_desc":"Securely manage usernames and passwords for your clients websites, servers, and other logins.","date":{"date":"2018-05-28 14:09:12.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"39","regular_price":"39","image":"' . $imgs['passw'] . '","extkey":"passwordmanager"},{"id":20570,"name":"Twilio Connect","short_desc":"Send SMS messages to your contacts, leads, and customers","date":{"date":"2017-11-24 11:53:18.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"49","regular_price":"49","image":"' . $imgs['twilio'] . '","extkey":"twilio"},{"id":18274,"name":"MailChimp","short_desc":"Subscribe your Jetpack CRM contacts to your MailChimp email marketing list automatically.","date":{"date":"2017-07-27 09:35:08.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"39","regular_price":"39","image":"' . $imgs['mailchimp'] . '","extkey":"mailchimp"},{"id":18221,"name":"Awesome Support","short_desc":"Integrate Jetpack CRM with Awesome Support Plugin and see your Contacts support ticket information within your CRM.","date":{"date":"2017-07-24 19:49:23.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"29","regular_price":"29","image":"' . $imgs['awesomesupport'] . '","extkey":"awesomesupport"},{"id":17921,"name":"ConvertKit","short_desc":"Subscribe your contacts to your ConvertKit list automatically. Subscribe to a form, add a tag or subscribe to a sequence","date":{"date":"2017-07-10 10:25:41.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"39","regular_price":"39","image":"' . $imgs['convertkit'] . '","extkey":"convertkit"},{"id":17692,"name":"Bulk Tagger","short_desc":"Bulk tag your contacts based on transaction keywords. Target contacts based on their transaction tags.","date":{"date":"2017-07-02 10:09:47.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"29.00","regular_price":"29.00","image":"' . $imgs['batchtag'] . '","extkey":"batchtag"},{"id":17425,"name":"Google Contacts Sync","short_desc":"Retrieve all contact data from Google Contacts. Keep all Leads in your CRM and start managing your contacts effectively.","date":{"date":"2017-06-05 12:32:02.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"39.00","regular_price":"39.00","image":"' . $imgs['googlecontact'] . '","extkey":"googlecontact"},{"id":17413,"name":"Groove Sync","short_desc":"Retrieve all contact data from Groove\u00a0automatically. Keep all Leads in your CRM.","date":{"date":"2017-06-02 16:25:18.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"39.00","regular_price":"39.00","image":"' . $imgs['groove'] . '","extkey":"groove"},{"id":17409,"name":"Contact Form 7","short_desc":"Use Contact Form 7 to collect leads and contact info. Save time by automating your lead generation process.","date":{"date":"2017-06-01 13:05:12.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"49","regular_price":"49","image":"' . $imgs['contactform'] . '","extkey":"contactform"},{"id":17378,"name":"Stripe Sync","short_desc":"Retrieve all customer data from Stripe automatically.","date":{"date":"2017-05-30 18:30:29.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"49.00","regular_price":"49.00","image":"' . $imgs['stripe'] . '","extkey":"stripe"},{"id":17356,"name":"WorldPay Sync","short_desc":"Retrieve all customer data from WorldPay\u00a0automatically. Works great with Sales Dashboard.","date":{"date":"2017-05-24 12:25:12.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"49.00","regular_price":"49.00","image":"' . $imgs['worldpay'] . '","extkey":"worldpay"},{"id":17067,"name":"Invoicing PRO","short_desc":"Invoicing PRO lets your\u00a0customers pay their invoices right from your Client Portal using either PayPal or Stripe.","date":{"date":"2017-02-21 11:06:47.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"49","regular_price":"49","image":"' . $imgs['invpro'] . '","extkey":"invpro"},{"id":17030,"name":"Gravity Forms Connect","short_desc":"Use Gravity Forms to collect leads and contact info. Save time by automating your lead generation process.","date":{"date":"2017-01-25 03:31:56.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"49","regular_price":"49","image":"' . $imgs['gravity'] . '","extkey":"gravity"},{"id":16690,"name":"CSV Importer PRO","short_desc":"Import your existing contact data into the Jetpack CRM system with our super simple CSV importer extension.","date":{"date":"2016-06-20 23:02:27.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"29","regular_price":"29","image":"' . $imgs['csvpro'] . '","extkey":"csvpro"},{"id":16688,"name":"Mail Campaigns","short_desc":"Send emails to targeted segments of contacts with this easy to use, powerful mail extension. Contact your contacts easily.","date":{"date":"2016-06-20 22:53:09.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"79","regular_price":"79","image":"' . $imgs['mailcamp'] . '","extkey":"mailcamp"},{"id":16685,"name":"PayPal Sync","short_desc":"Retrieve all customer data from PayPal automatically. Works great with Sales Dashboard.","date":{"date":"2016-06-16 23:00:34.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"49","regular_price":"49","image":"' . $imgs['paypal'] . '","extkey":"paypal"},{"id":16609,"name":"Sales Dashboard","short_desc":"<p class=\"p1\"><span class=\"s1\">The ultimate sales dashboard. Track Gross Revenue, Net Revenue, Customer growth right from your CRM.<\/span><\/p>","date":{"date":"2016-06-05 14:04:16.000000","timezone_type":3,"timezone":"Europe\/London"},"price":"129","regular_price":"129","image":"' . $imgs['salesdash'] . '","extkey":"salesdash"}]}'; return $json; } // } Vars global $zeroBSCRM_extensionsInstalledList, $zeroBSCRM_extensionsCompleteList, $jpcrm_core_extension_setting_map; $jpcrm_core_extension_setting_map = array( 'forms' => 'feat_forms', 'pdfinv' => 'feat_pdfinv', 'quotebuilder' => 'feat_quotes', 'invbuilder' => 'feat_invs', 'csvimporterlite' => 'feat_csvimporterlite', 'api' => 'feat_api', 'cal' => 'feat_calendar', 'transactions' => 'feat_transactions', 'jetpackforms' => 'feat_jetpackforms', 'b2bmode' => 'companylevelcustomers', ); // } Fill out full list - NOTE: this is currently only used for extra info for extensions page // } Sould still use the functions like "zeroBSCRM_extension_name_mailcampaigns" for names etc. $zeroBSCRM_extensionsCompleteList = array( // MS 15th Oct. This list needs to be maintained as it drives the update check // Probably need a more central (i.e. on jetpackcrm.com) list of these // As per the above comments, we should consolidate this whole system, with // one central location holding extension meta (along with a fallback cache) // Paid extensions; last updated 21 March 1922 'advancedsegments' => array( 'fallbackname' => 'Advanced Segments', 'desc' => __( 'Easily divide your contacts into dynamic subgroups and manage your contacts effectively.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/product/advanced-segments/', 'colour' => '#aa73ac', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/advanced-segments/', ), 'apiconnector' => array( 'fallbackname' => 'API Connector', 'desc' => __( 'Connects your website to Jetpack CRM via the API. Supports Forms & Registrations.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/product/api-connector/', 'colour' => '#11ABCC', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/api-connector/', ), 'automations' => array( 'fallbackname' => 'Automations', 'desc' => __( 'Let our Automations do the mundane tasks for you.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/extensions/automations/', 'colour' => '#009cde', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/automations/', ), 'aweber' => array( 'fallbackname' => 'AWeber Connect', 'desc' => __( 'Send Jetpack CRM contacts to your AWeber list.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/product/aweber-connect/', 'colour' => '#aa73ac', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/aweber-connect/', ), 'awesomesupport' => array( 'fallbackname' => 'Awesome Support Connector', 'desc' => __( 'See your contacts support ticket overview.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/product/awesome-support/', 'colour' => '#11ABCC', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/awesome-support/', ), 'batchtag' => array( 'fallbackname' => 'Bulk Tagger', 'desc' => __( 'Bulk Tag your contacts based on their transaction strings', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/product/bulk-tagger/', 'colour' => '#11ABCC', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/bulk-tagger/', ), 'passwordmanager' => array( 'fallbackname' => 'Client Password Manager', 'desc' => __( 'Securely manage usernames and passwords for your clients websites, servers, and other logins.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/product/client-password-manager/', 'colour' => '#11ABCC', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/client-password-manager/', ), 'clientportalpro' => array( 'fallbackname' => 'Client Portal Pro', 'desc' => __( 'Customise your Client Portal, Allow File Downloads, Display Tasks and more', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/product/client-portal-pro/', 'colour' => '#11ABCC', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/client-portal-pro/', ), 'contactform' => array( 'fallbackname' => 'Contact Form 7 Connector', 'desc' => __( 'Use Contact Form 7 to collect leads and contact info.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/product/contact-form-7/', 'colour' => '#e2ca00', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/contact-form-7/', ), 'convertkit' => array( 'fallbackname' => 'ConvertKit Connector', 'desc' => __( 'Add your Jetpack CRM Contacts to your ConvertKit list.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/product/convertkit/', 'colour' => '#11ABCC', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/convertkit/', ), 'csvpro' => array( 'fallbackname' => 'CSV Importer PRO', 'desc' => __( 'Import existing contact data from CSV (Pro Version)', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/extensions/simple-csv-importer/', 'colour' => 'green', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/csv-importer-pro/', 'shortname' => 'CSV Imp. PRO', // used where long name won't fit ), 'exitbee' => array( 'fallbackname' => 'Exit Bee Connect', 'desc' => __( 'Convert abandoning visitors into contacts.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/product/exitbee-connect/', 'colour' => '#aa73ac', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/exit-bee/', ), 'funnels' => array( 'fallbackname' => 'Funnels', ), 'googlecontact' => array( 'fallbackname' => 'Google Contacts', 'desc' => __( 'Retrieve all contact data from Google Contacts.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/product/google-contacts-sync/', 'colour' => '#91a8ad', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/google-contacts-sync/', 'aliases' => array( 'Google Contact Sync', 'Google Contact Connect' ), ), 'gravity' => array( 'fallbackname' => 'Gravity Connect', 'desc' => __( 'Create Contacts from Gravity Forms (Integration).', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/extensions/gravity-forms/', 'colour' => '#91a8ad', // grav forms :) #91a8ad 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/gravity-forms/', 'aliases' => array( 'Gravity Forms' ), ), 'groove' => array( 'fallbackname' => 'Groove Connect', 'desc' => __( 'Retrieve all contact data from Groove automatically.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/product/groove-sync/', 'colour' => '#11ABCC', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/groove-sync/', 'aliases' => array( 'Groove Sync' ), ), 'invpro' => array( 'fallbackname' => 'Invoicing Pro', 'desc' => __( 'Collect invoice payments directly from your CRM with PayPal or Stripe.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/extensions/invoicing-pro/', 'colour' => '#1e0435', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/invoicing-pro/', ), 'livestorm' => array( 'fallbackname' => 'Livestorm Connect', 'desc' => __( 'Capture webinar sign ups to your CRM.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/product/livestorm-connect/', 'colour' => '#aa73ac', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/livestorm/', 'aliases' => array( 'Live Storm Connect' ), ), 'mailcamp' => array( 'fallbackname' => 'Mail Campaigns', 'desc' => __( 'Send emails to targeted segments of contacts.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/extensions/mail-campaigns/', 'colour' => 'rgb(173, 210, 152)', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/mail-campaigns-v2/', 'aliases' => array( '[BETA] v2.0 Mail Campaigns' ), ), 'mailchimp' => array( 'fallbackname' => 'MailChimp Connector', 'desc' => __( 'Add your Jetpack CRM Contacts to your Mailchimp email list.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/product/mailchimp/', 'colour' => '#11ABCC', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/mailchimp/', ), 'membermouse' => array( 'fallbackname' => 'Member Mouse', 'desc' => __( 'Imports your Membermouse user data to your CRM.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/product/membermouse/', 'colour' => '#f01e14', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/member-mouse/', ), 'optinmonster' => array( 'fallbackname' => 'OptinMonster', 'aliases' => array( 'Optin Monster' ), ), 'paypal' => array( 'fallbackname' => 'PayPal Connect', 'desc' => __( 'Retrieve all contact data from PayPal automatically.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/extensions/paypal-sync/', 'colour' => '#009cde', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/paypal-sync/', 'aliases' => array( 'PayPal Sync' ), ), 'registrationmagic' => array( 'fallbackname' => 'Registration Magic', ), 'salesdash' => array( 'fallbackname' => 'Sales Dashboard', 'desc' => __( 'The ultimate sales dashboard. See sales trends and more', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/extensions/sales-dashboard/', 'colour' => 'black', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/sales-dashboard/', ), 'stripe' => array( 'fallbackname' => 'Stripe Connect', 'desc' => __( 'Retrieve all customer data from Stripe automatically.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/product/stripe-sync/', 'colour' => '#5533ff', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/stripe-sync/', 'aliases' => array( 'Stripe Sync' ), ), 'systememail' => array( 'fallbackname' => 'System Emails Pro', 'aliases' => array( 'System Email Pro' ), ), 'twilio' => array( 'fallbackname' => 'Twilio Connect', 'desc' => __( 'Send SMS from your Twilio Account.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/product/twilio/', 'colour' => '#11ABCC', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/twilio-connector/', ), 'wordpressutilities' => array( 'fallbackname' => 'WordPress Utilities', 'desc' => __( 'Capture website sign ups into Jetpack CRM.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/product/wordpress-utilities/', 'colour' => '#aa73ac', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/wordpress-utilities/', ), 'worldpay' => array( 'fallbackname' => 'WorldPay Sync', 'desc' => __( 'Create Contacts from World Pay Sync.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/product/worldpay-sync/', 'colour' => '#f01e14', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/worldpay-sync/', ), // } ============= Free ===== 'api' => array( 'fallbackname' => 'API', // This is if no name func is found... 'imgstr' => '<i class="fa fa-random" aria-hidden="true"></i>', 'desc' => __( 'Enable the API area of your CRM.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/feature/api/', 'colour' => '#000000', 'helpurl' => 'https://automattic.github.io/jetpack-crm-api-docs/', 'shortName' => 'API', ), 'cal' => array( 'fallbackname' => __( 'Task Scheduler', 'zero-bs-crm' ), // This is if no name func is found... 'imgstr' => '<i class="fa fa-calendar" aria-hidden="true"></i>', 'desc' => __( 'Enable Jetpack CRM Task Scheduler.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/feature/tasks/', 'colour' => '#ad6d0d', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/calendar/', 'shortName' => 'Calendar', ), 'quotebuilder' => array( 'fallbackname' => 'Quote Builder', // This is if no name func is found... 'imgstr' => '<i class="fa fa-file-text-o" aria-hidden="true"></i>', 'desc' => __( 'Write and send professional proposals from your CRM.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/feature/quotes/', 'colour' => '#1fa67a', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/quotes/', ), 'invbuilder' => array( 'fallbackname' => 'Invoice Builder', // This is if no name func is found... 'imgstr' => '<i class="fa fa-file-text-o" aria-hidden="true"></i>', 'desc' => __( 'Write and send professional invoices from your CRM.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/feature/invoices/', 'colour' => '#2a044a', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/invoices/', ), 'pdfinv' => array( 'fallbackname' => 'PDF Invoicing', // This is if no name func is found... 'imgstr' => '<i class="fa fa-file-pdf-o" aria-hidden="true"></i>', 'desc' => __( 'Want PDF Invoices? Get this installed.', 'zero-bs-crm' ), // 'url' => 'https://jetpackcrm.com/feature/', 'colour' => 'green', // 'helpurl' => 'https://kb.jetpackcrm.com/' ), 'transactions' => array( 'fallbackname' => 'Transactions', // This is if no name func is found... 'imgstr' => '<i class="fa fa-file-shopping-cart" aria-hidden="true"></i>', 'desc' => __( 'Log transactions in your CRM.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/feature/transactions/', 'colour' => 'green', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/transactions/', ), 'forms' => array( 'fallbackname' => 'Front-end Forms', // This is if no name func is found... 'imgstr' => '<i class="fa fa-keyboard-o" aria-hidden="true"></i>', 'desc' => __( 'Useful front-end forms to capture leads.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/feature/forms/', 'colour' => 'rgb(126, 88, 232)', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/forms/', 'shortname' => 'Forms', // used where long name won't fit ), // } Free ver 'csvimporterlite' => array( 'fallbackname' => 'CSV Importer LITE', // This is if no name func is found... 'imgstr' => '<i class="fa fa-upload" aria-hidden="true"></i>', 'desc' => __( 'Lite Version of CSV Customer Importer', 'zero-bs-crm' ), // 'url' => 'https://jetpackcrm.com/extensions/simple-csv-importer/', 'colour' => 'green', // 'helpurl' => 'https://kb.jetpackcrm.com/', 'shortname' => 'CSV Imp. LITE', // used where long name won't fit 'prover' => 'csvpro', // } if this is set, and 'csvimporter' ext exists, it'll default to "PRO installed" ), 'b2bmode' => array( 'fallbackname' => 'B2B Mode', // This is if no name func is found... 'imgstr' => '<i class="building outline icon"></i>', 'desc' => __( 'Manage Contacts at Companies or Organisations', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/feature/b2b-mode/', 'colour' => 'rgb(117 184 231)', 'helpurl' => 'https://kb.jetpackcrm.com/knowledge-base/how-to-assign-a-contact-to-a-company/', 'shortname' => 'B2B Mode', // used where long name won't fit ), 'jetpackforms' => array( 'fallbackname' => 'Jetpack Forms', // This is if no name func is found... 'imgstr' => '<i class="fa fa-keyboard-o" aria-hidden="true"></i>', 'desc' => __( 'Capture leads from Jetpack Forms', 'zero-bs-crm' ), // 'url' => 'https://jetpackcrm.com/feature/', 'colour' => 'rgb(126, 88, 232)', 'helpurl' => 'https://kb.jetpackcrm.com/knowledge-base/jetpack-contact-forms/', 'shortname' => 'Jetpack Forms', // used where long name won't fit ), 'woo-sync' => array( 'fallbackname' => 'WooSync', 'desc' => __( 'Retrieve all customer data from WooCommerce.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/woocommerce/', 'colour' => 'rgb(216, 187, 73)', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/woocommerce-sync/', 'aliases' => array( 'WooSync', 'Woo Sync' ), ), // Legacy keys used to identify obsolete extensions 'woosync' => array( 'fallbackname' => 'WooSync', ), ); // } #coreintegration // This deactivates all active ZBS extensions (used by migration routine for v3.0 - be careful if alter as back-compat may be comprimised) function zeroBSCRM_extensions_deactivateAll() { // count $c = 0; // retrieve extensions $extensions = zeroBSCRM_installedProExt(); // Disable extensions if ( is_array( $extensions ) ) { foreach ( $extensions as $shortName => $e ) { if ( isset( $e['path'] ) ) { deactivate_plugins( plugin_basename( $e['path'] ) ); } ++$c; } } return $c; } /* * Deactivates specific extension based on its key * * @param string $key - e.g. 'woosync' * * @return bool - (approximate) success */ function jpcrm_extensions_deactivate_by_key( $key ) { // Most reliable way I found to do this is using our internal extension register $installed_extensions = zeroBSCRM_installedProExt(); foreach ( $installed_extensions as $name => $extension ) { if ( $extension['key'] == $key && $extension['active'] == 1 ) { // deactivate the extension if ( isset( $extension['path'] ) ) { deactivate_plugins( plugin_basename( $extension['path'] ) ); return ! is_plugin_active( plugin_basename( $extension['path'] ) ); } } } return false; } // } This activates a given extension // No point, just use activate_plugin vanilla. function zeroBSCRM_extensions_activate($path=false){} // } Free Array // this is a simpler version, with better icons (from the welcome to ZBS page and a description) // have also added "transactions" to here. CSVimporterLite I would not see as a "module" to disable. Think should be the areas function zeroBSCRM_extensions_free( $justKeys = false ) { $exts = array( 'csvimporterlite' => false, // false = doesn't show on ext manager page 'api' => array( 'name' => __( 'API', 'zero-bs-crm' ), 'i' => 'api.png', 'short_desc' => __( 'The CRM API lets you interact with Jetpack CRM via the application program interface.', 'zero-bs-crm' ), ), 'cal' => array( 'name' => __( 'Tasks', 'zero-bs-crm' ), 'i' => 'task-cal.png', 'short_desc' => __( 'Manage tasks for your contacts and what you need to do for them.', 'zero-bs-crm' ), ), 'quotebuilder' => array( 'name' => __( 'Quotes', 'zero-bs-crm' ), 'i' => 'quotes.png', 'short_desc' => __( 'Offer Quotes for your contacts to help you win more business.', 'zero-bs-crm' ), ), 'invbuilder' => array( 'name' => __( 'Invoices', 'zero-bs-crm' ), 'i' => 'invoices.png', 'short_desc' => __( 'Send invoices to your clients and allow them to pay online.', 'zero-bs-crm' ), ), 'pdfinv' => array( 'name' => __( 'PDF Engine', 'zero-bs-crm' ), 'i' => 'pdf.png', 'short_desc' => __( 'Supports PDF invoicing and PDF quotes (plus more).', 'zero-bs-crm' ), ), 'forms' => array( 'name' => __( 'Forms', 'zero-bs-crm' ), 'i' => 'form.png', 'short_desc' => __( 'Capture contacts into your CRM using our simple form solutions.', 'zero-bs-crm' ), ), 'transactions' => array( 'name' => __( 'Transactions', 'zero-bs-crm' ), 'i' => 'transactions.png', 'short_desc' => __( 'Log transactions against contacts and see their total value in the CRM.', 'zero-bs-crm' ), ), 'b2bmode' => array( 'name' => __( 'B2B Mode', 'zero-bs-crm' ), 'i' => 'customers.png', 'short_desc' => __( 'Manage Contacts at Companies or Organisations', 'zero-bs-crm' ), ), 'jetpackforms' => array( 'name' => __( 'Jetpack Forms', 'zero-bs-crm' ), 'i' => 'form.png', 'short_desc' => __( 'Capture contacts from Jetpack forms into your CRM.', 'zero-bs-crm' ), ), 'woo-sync' => array( 'name' => 'WooSync', 'i' => 'auto.png', 'short_desc' => __( 'Retrieve all customer data from WooCommerce into your CRM.', 'zero-bs-crm' ), ), ); $exts = apply_filters( 'jpcrm_register_free_extensions', $exts ); if ( $justKeys ) { return array_keys( $exts ); } return $exts; } // } Free extensions name funcs function zeroBSCRM_extension_name_pdfinv() { return __( 'PDF Engine', 'zero-bs-crm' ); } function zeroBSCRM_extension_name_forms() { return __( 'Front-end Forms', 'zero-bs-crm' ); } function zeroBSCRM_extension_name_quotebuilder() { return __( 'Quotes', 'zero-bs-crm' ); } function zeroBSCRM_extension_name_invbuilder() { return __( 'Invoicing', 'zero-bs-crm' ); } function zeroBSCRM_extension_name_csvimporterlite() { return __( 'CSV Importer LITE', 'zero-bs-crm' ); } function zeroBSCRM_extension_name_api() { return __( 'API', 'zero-bs-crm' ); } function zeroBSCRM_extension_name_cal() { return __( 'Tasks', 'zero-bs-crm' ); } function zeroBSCRM_extension_name_transactions() { return __( 'Transactions', 'zero-bs-crm' ); } function zeroBSCRM_extension_name_jetpackforms() { return __( 'Jetpack Forms', 'zero-bs-crm' ); } function zeroBSCRM_extension_name_b2bmode() { return __( 'B2B Mode', 'zero-bs-crm' ); } // } Settings page for PDF Invoicing (needs writing) // } function zeroBSCRM_html_settings_pdfinv // hard deletes any extracted repo (e.g. dompdf) function zeroBSCRM_extension_remove_dl_repo( $repoName = '' ) { if ( in_array( $repoName, array( 'dompdf' ) ) ) { // this is here to stop us ever accidentally using zeroBSCRM_del define( 'ZBS_OKAY_TO_PROCEED', time() ); zeroBSCRM_del( ZEROBSCRM_INCLUDE_PATH . $repoName ); } } // } WH 2.0.6 - added to check installed pre-use, auto-installs if not present (or marks uninstalled + returns false) // } $checkInstallFonts allows you to just check dompdf, not the piggy-backed pdf fonts installer too (as PDFBuilder needs this) function zeroBSCRM_extension_checkinstall_pdfinv( $checkInstallFonts = true ) { global $zbs; // retrieve lib path $includeFile = $zbs->libInclude( 'dompdf' ); $shouldBeInstalled = zeroBSCRM_getSetting( 'feat_pdfinv' ); if ( $shouldBeInstalled == '1' && ! empty( $includeFile ) && ! file_exists( $includeFile ) ) { // } Brutal really, just set the setting global $zbs; $zbs->settings->update( 'feat_pdfinv', 0 ); // } Returns true/false zeroBSCRM_extension_install_pdfinv(); } $fontsInstalled = zeroBSCRM_getSetting( 'pdf_fonts_installed' ); if ( $checkInstallFonts && $shouldBeInstalled == '1' && $fontsInstalled !== 1 ) { // check fonts $fonts = $zbs->get_fonts(); $fonts->extract_and_install_default_fonts(); } } // } Install funcs for free exts function zeroBSCRM_extension_install_pdfinv() { global $zbs; if ( ! zeroBSCRM_checkSystemFeat_mb_internal_encoding() ) { global $zbsExtensionInstallError; $zbsExtensionInstallError = __( 'Please ensure the mbstring PHP module is enabled on your server prior to installing the PDF Engine.', 'zero-bs-crm' ); return false; } // retrieve lib path $includeFilePath = $zbs->libPath( 'dompdf' ); $includeFile = $zbs->libInclude( 'dompdf' ); // } Check if already downloaded libs: if ( ! empty( $includeFile ) && ! file_exists( $includeFile ) ) { global $zbs; // } Libs appear to need downloading.. // } dirs $workingDir = ZEROBSCRM_PATH . 'temp' . time(); if ( ! file_exists( $workingDir ) ) { wp_mkdir_p( $workingDir ); } $endingDir = $includeFilePath; if ( ! file_exists( $endingDir ) ) { wp_mkdir_p( $endingDir ); } if ( file_exists( $endingDir ) && file_exists( $workingDir ) ) { // } Retrieve zip $libs = zeroBSCRM_retrieveFile( $zbs->urls['extdlrepo'] . 'pdfinv.zip', $workingDir . '/pdfinv.zip' ); // } Expand if ( file_exists( $workingDir . '/pdfinv.zip' ) ) { // } Should checksum? // } For now, expand zip $expanded = zeroBSCRM_expandArchive( $workingDir . '/pdfinv.zip', $endingDir . '/' ); // } Check success? if ( file_exists( $includeFile ) ) { // } All appears good, clean up if ( file_exists( $workingDir . '/pdfinv.zip' ) ) { unlink( $workingDir . '/pdfinv.zip' ); } if ( file_exists( $workingDir ) ) { rmdir( $workingDir ); } jpcrm_install_core_extension( 'pdfinv' ); // Also install pdf fonts $fonts = $zbs->get_fonts(); $fonts->extract_and_install_default_fonts(); return true; } else { // } Add error msg global $zbsExtensionInstallError; $zbsExtensionInstallError = __( 'Jetpack CRM was not able to extract the libraries it needs to in order to install PDF Engine.', 'zero-bs-crm' ); } } else { // } Add error msg global $zbsExtensionInstallError; $zbsExtensionInstallError = __( 'Jetpack CRM was not able to download the libraries it needs to in order to install PDF Engine.', 'zero-bs-crm' ); } } else { // } Add error msg global $zbsExtensionInstallError; $zbsExtensionInstallError = __( 'Jetpack CRM was not able to create the directories it needs to in order to install PDF Engine.', 'zero-bs-crm' ); } } else { // } Already exists... // } Brutal really, just set the setting global $zbs; $zbs->settings->update( 'feat_pdfinv', 1 ); // } Make it show up in the array again global $zeroBSCRM_extensionsInstalledList; if ( ! is_array( $zeroBSCRM_extensionsInstalledList ) ) { $zeroBSCRM_extensionsInstalledList = array(); } $zeroBSCRM_extensionsInstalledList[] = 'pdfinv'; // Also install pdf fonts $fonts = $zbs->get_fonts(); $fonts->extract_and_install_default_fonts(); return true; } // } Return fail return false; } // } Uninstall funcs for free exts function zeroBSCRM_extension_uninstall_pdfinv() { return jpcrm_uninstall_core_extension( 'pdfinv' ); } // } Transactions: New 2.98.2 function zeroBSCRM_extension_install_transactions() { return jpcrm_install_core_extension( 'transactions' ); } function zeroBSCRM_extension_uninstall_transactions() { return jpcrm_uninstall_core_extension( 'transactions' ); } function zeroBSCRM_extension_install_forms() { return jpcrm_install_core_extension( 'forms' ); } function zeroBSCRM_extension_uninstall_forms() { return jpcrm_uninstall_core_extension( 'forms' ); } function zeroBSCRM_extension_install_jetpackforms() { return jpcrm_install_core_extension( 'jetpackforms' ); } function zeroBSCRM_extension_uninstall_jetpackforms() { return jpcrm_uninstall_core_extension( 'jetpackforms' ); } function zeroBSCRM_extension_install_b2bmode() { return jpcrm_install_core_extension( 'b2bmode' ); } function zeroBSCRM_extension_uninstall_b2bmode() { return jpcrm_uninstall_core_extension( 'b2bmode' ); } function zeroBSCRM_extension_install_cal() { return jpcrm_install_core_extension( 'cal' ); } function zeroBSCRM_extension_uninstall_cal() { return jpcrm_uninstall_core_extension( 'cal' ); } function zeroBSCRM_extension_install_quotebuilder() { $result = jpcrm_install_core_extension( 'quotebuilder', true ); return $result; } function zeroBSCRM_extension_uninstall_quotebuilder() { $result = jpcrm_uninstall_core_extension( 'quotebuilder', true ); return $result; } function zeroBSCRM_extension_install_invbuilder() { return jpcrm_install_core_extension( 'invbuilder', true ); } function zeroBSCRM_extension_uninstall_invbuilder() { return jpcrm_uninstall_core_extension( 'invbuilder', true ); } function zeroBSCRM_extension_install_csvimporterlite() { return jpcrm_install_core_extension( 'csvimporterlite' ); } function zeroBSCRM_extension_uninstall_csvimporterlite() { return jpcrm_uninstall_core_extension( 'csvimporterlite' ); } function zeroBSCRM_extension_install_api() { return jpcrm_install_core_extension( 'api', true ); } function zeroBSCRM_extension_uninstall_api() { return jpcrm_uninstall_core_extension( 'api', true ); } // } Free extensions init function zeroBSCRM_freeExtensionsInit() { global $zeroBSCRM_extensionsInstalledList, $jpcrm_core_extension_setting_map; $zeroBSCRM_extensionsInstalledList = array(); foreach ( $jpcrm_core_extension_setting_map as $ext_name => $setting_name ) { if ( zeroBSCRM_getSetting( $setting_name ) == 1 ) { $zeroBSCRM_extensionsInstalledList[] = $ext_name; } } } /** * @param $ext_name Extension name * @return bool */ function jpcrm_install_core_extension( $ext_name, $flag_for_flush_rewrite = false ) { global $zbs, $zeroBSCRM_extensionsInstalledList, $jpcrm_core_extension_setting_map; $ext_setting = $jpcrm_core_extension_setting_map[ $ext_name ]; $zbs->settings->update( $ext_setting, 1 ); // Add to the installed extension list $is_installed = array_search( $ext_name, $zeroBSCRM_extensionsInstalledList ); if ( ! $is_installed ) { $zeroBSCRM_extensionsInstalledList[] = $ext_name; // flush rewrite rules as needed if ( $flag_for_flush_rewrite ) { jpcrm_flag_for_flush_rewrite(); } return true; } return false; } /** * @param $ext_name Extension name * @return bool */ function jpcrm_uninstall_core_extension( $ext_name, $flag_for_flush_rewrite = false ) { global $zbs, $zeroBSCRM_extensionsInstalledList, $jpcrm_core_extension_setting_map; $ext_setting = $jpcrm_core_extension_setting_map[ $ext_name ]; $zbs->settings->update( $ext_setting, -1 ); // Remove from the installed extension list $idx = array_search( $ext_name, $zeroBSCRM_extensionsInstalledList ); if ( $idx !== false ) { array_splice( $zeroBSCRM_extensionsInstalledList, $idx, 1 ); // flush rewrite rules as needed if ( $flag_for_flush_rewrite ) { jpcrm_flag_for_flush_rewrite(); } return true; } return false; } /** * Registers an external extension, (adds to our global list, for now) * * @param $ext_name Extension name * @return bool */ function jpcrm_register_external_extension( $ext_name ) { if ( ! empty( $ext_name ) ) { global $zeroBSCRM_extensionsInstalledList; if ( ! is_array( $zeroBSCRM_extensionsInstalledList ) ) { $zeroBSCRM_extensionsInstalledList = array(); } $zeroBSCRM_extensionsInstalledList[] = $ext_name; return true; } return false; } /* ====================================================== EXTENSION DETAILS / FREE/included EXTENSIONS ====================================================== */
projects/plugins/crm/includes/ZeroBSCRM.MetaBoxes3.Quotes.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V3.0 * * Copyright 2020 Automattic * * Date: 20/02/2019 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== Init Func ====================================================== */ function zeroBSCRM_QuotesMetaboxSetup(){ // main detail $zeroBS__Metabox_Quote = new zeroBS__Metabox_Quote( __FILE__ ); // quote content box $zeroBS__Metabox_QuoteContent = new zeroBS__Metabox_QuoteContent( __FILE__ ); // quote next step box (publish etc.) $zeroBS__Metabox_QuoteNextStep = new zeroBS__Metabox_QuoteNextStep( __FILE__ ); // quote actions box $zeroBS__Metabox_QuoteActions = new zeroBS__Metabox_QuoteActions( __FILE__ ); // quote tags box $zeroBS__Metabox_QuoteTags = new zeroBS__Metabox_QuoteTags( __FILE__ ); // quote accepted details $zeroBS__Metabox_QuoteAcceptedDetails = new zeroBS__Metabox_QuoteAcceptedDetails( __FILE__ ); // files $zeroBS__Metabox_QuoteFiles = new zeroBS__Metabox_QuoteFiles( __FILE__ ); } add_action( 'admin_init','zeroBSCRM_QuotesMetaboxSetup'); /* $zeroBS__MetaboxQuote = new zeroBS__MetaboxQuote( __FILE__ ); $zeroBS__QuoteContentMetabox = new zeroBS__QuoteContentMetabox( __FILE__ ); $zeroBS__QuoteActionsMetabox = new zeroBS__QuoteActionsMetabox( __FILE__ ); $zeroBS__QuoteStatusMetabox = new zeroBS__QuoteStatusMetabox( __FILE__ ); */ /* ====================================================== / Init Func ====================================================== */ /* ====================================================== Quote Metabox ====================================================== */ class zeroBS__Metabox_Quote extends zeroBS__Metabox{ // this is for catching 'new' quotes private $newRecordNeedsRedir = false; public function __construct( $plugin_file ) { // set these $this->objType = 'quote'; $this->metaboxID = 'zerobs-quote-edit'; $this->metaboxTitle = __('Step 1: Quote Details','zero-bs-crm'); // will be headless anyhow $this->headless = true; $this->metaboxScreen = 'zbs-add-edit-quote-edit'; $this->metaboxArea = 'normal'; $this->metaboxLocation = 'high'; $this->saveOrder = 1; $this->capabilities = array( 'can_hide' => false, // can be hidden 'areas' => array('normal'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => true, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true, // can be minimised 'can_move' => true // can be moved ); // call this $this->initMetabox(); } public function html( $quote, $metabox ) { // localise ID $quoteID = -1; if (is_array($quote) && isset($quote['id'])) $quoteID = (int)$quote['id']; // if new + $zbsObjDataPrefill passed, use that instead of loaded trans. if ($quoteID == -1){ global $zbsObjDataPrefill; $quote = $zbsObjDataPrefill; } global $zbs; // Define Quote statuses. $acceptable_quote_statuses = jpcrm_get_quote_statuses(); // status $status = $acceptable_quote_statuses['draft']; if ( is_array( $quote ) && isset( $quote['status'] ) ) { if ( $quote['status'] === -2 ) { $status = $acceptable_quote_statuses['published']; } if ( $quote['status'] === 1 ) { $status = $acceptable_quote_statuses['accepted']; } } // Debug echo 'Quote:<pre>'.print_r($quote,1).'</pre>'; ?> <script type="text/javascript">var zbscrmjs_secToken = '<?php echo esc_js( wp_create_nonce( 'zbscrmjs-ajax-nonce' ) ); ?>';</script> <?php #} retrieve // some legacy bits from CPT days: $quoteContactID = -1; if (is_array($quote) && isset($quote['contact']) && is_array($quote['contact']) && count($quote['contact']) > 0) $quoteContactID = $quote['contact'][0]['id']; //get_post_meta($post->ID, 'zbs_customer_quote_customer', true); $templateUsed = -1; if (is_array($quote) && isset($quote['template'])) $templateUsed = $quote['template']; //get_post_meta($post->ID, 'zbs_quote_template_id', true); #} this is a temp weird one, just passing onto meta for now (long day): // ? Not used DAL3? //$zbsTemplated = get_post_meta($post->ID, 'templated', true); //if (!empty($zbsTemplated)) $quote['templated'] = true; // quick WH predictive hack, not sure if viable - to test DAL3 $quote['templated'] = false; if ($templateUsed !== -1 && !empty($templateUsed)) $quote['templated'] = true; #} if customer id is empty, but prefill isn't, use prefill if ($quoteContactID == -1 && isset($_GET['zbsprefillcust'])) $quoteContactID = (int)$_GET['zbsprefillcust']; #} pass to other metaboxes (cache?) global $zbsCurrentEditQuote; $zbsCurrentEditQuote = $quote; #} Retrieve fields from global global $zbsCustomerQuoteFields; $fields = $zbsCustomerQuoteFields; // Debug echo 'Fields:<pre>'.print_r($fields,1).'</pre>'; #} Using "Quote Builder" or not? $useQuoteBuilder = zeroBSCRM_getSetting('usequotebuilder'); // Inputs out: #} New quote? if (!isset($quote['id'])) echo '<input type="hidden" name="zbscrm_newquote" value="1" />'; #} pass this if already templated: if ($useQuoteBuilder == 1 && isset($quote['template'])) echo '<input type="hidden" name="zbscrm_templated" id="zbscrm_templated" value="1" />'; #} Nonce used for loading quote template, left in for now, could be centralised to normal sec nonce echo '<input type="hidden" name="quo-ajax-nonce" id="quo-ajax-nonce" value="' . esc_attr( wp_create_nonce( 'quo-ajax-nonce' ) ) . '" />'; // we pass the hash along the chain here too :) echo '<input type="hidden" name="zbscq_hash" id="zbscq_hash" value="' . (isset($quote['hash']) ? esc_attr( $quote['hash'] ) : '') . '" />'; ?> <div> <div class="jpcrm-form-grid" id="wptbpMetaBoxMainItem"> <?php // DAL3 only show after saved, easier if (!empty($quoteID) && $quoteID > 0){ ?> <div class="jpcrm-form-group jpcrm-form-group-span-2"> <label class="jpcrm-form-label"><?php esc_html_e( 'Quote (ID)', 'zero-bs-crm' ); ?>:</label> <?php echo '<b>' . esc_html( $quoteID ) . '</b>'; //phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?> <input type="hidden" name="zbsquoteid" value="<?php echo esc_attr( $quoteID ); //phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?>" /> </div> <?php } // Quote status. if ( $quoteID > 0 ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?> <div class="jpcrm-form-group jpcrm-form-group-span-2"> <label class="jpcrm-form-label" for="quote_status"><?php esc_html_e( 'Status', 'zero-bs-crm' ); ?>:</label> <select class="form-control" id="quote_status" name="quote_status"> <?php foreach ( $acceptable_quote_statuses as $status_opt => $status_str ) { $sel = ''; if ( $status_str === $status ) { $sel = ' selected="selected"'; } /* Translators: %s is the Quote status. */ echo '<option value="' . esc_attr( $status_opt ) . '"' . esc_attr( $sel ) . '>' . esc_html( sprintf( __( '%s', 'zero-bs-crm' ), $status_str ) ) . '</option>'; // phpcs:ignore WordPress.WP.I18n.NoEmptyStrings } ?> </select> </div> <?php } // end if ?> <div class="jpcrm-form-group jpcrm-form-group-span-2 jpcrm-override-typeahead-padding"> <label class="jpcrm-form-label"><?php esc_html_e( 'Contact', 'zero-bs-crm' ); ?>:</label> <?php #} 27/09/16 - switched select for typeahead #} Any customer? $prefillStr = ''; if (isset($quoteContactID) && !empty($quoteContactID)){ $prefillStr = $zbs->DAL->contacts->getContactNameWithFallback( $quoteContactID ); } #} Output select box echo zeroBSCRM_CustomerTypeList('zbscrmjs_quoteCustomerSelect',$prefillStr,true,'zbscrmjs_quote_unsetCustomer'); #} Output input which will pass the value via post ?><input type="hidden" name="zbscq_customer" id="zbscq_customer" value="<?php echo esc_attr( $quoteContactID ); ?>" /><?php #} Output function which will copy over value - maybe later move to js ?><script type="text/javascript"> jQuery(function(){ // bind setTimeout(function(){ zeroBSCRMJS_showContactLinkIf(jQuery("#zbscq_customer").val()); },0); }); function zbscrmjs_quoteCustomerSelect(cust){ // pass id to hidden input jQuery('#zbscq_customer').val(cust.id); // enable/disable button if present (here is def present) jQuery('#zbsQuoteBuilderStep2').prop( 'disabled', false ); jQuery('#zbsQuoteBuilderStep2info').hide(); setTimeout(function(){ var lID = cust.id; // when inv select drop down changed, show/hide quick nav zeroBSCRMJS_showContactLinkIf(lID); },0); } function zbscrmjs_quote_unsetCustomer(o){ if (typeof o == "undefined" || o == ''){ jQuery("#zbscq_customer").val(''); //jQuery("#bill").val(''); //jQuery("#cusbill").val(''); setTimeout(function(){ // when inv select drop down changed, show/hide quick nav zeroBSCRMJS_showContactLinkIf(''); },0); } } // if an contact is selected (against a trans) can 'quick nav' to contact function zeroBSCRMJS_showContactLinkIf(contactID){ // remove old //jQuery('#zbs-customer-title .zbs-view-contact').remove(); jQuery('#zbs-quote-learn-nav .zbs-quote-quicknav-contact').remove(); if (typeof contactID != "undefined" && contactID !== null && contactID !== ''){ contactID = parseInt(contactID); if (contactID > 0){ // seems like a legit inv, add /* this was from trans meta, here just add to top var html = '<div class="ui right floated mini animated button zbs-view-contact">'; html += '<div class="visible content"><?php zeroBSCRM_slashOut(__('View','zero-bs-crm')); ?></div>'; html += '<div class="hidden content">'; html += '<i class="user icon"></i>'; html += '</div>'; html += '</div>'; jQuery('#zbs-customer-title').prepend(html); */ // ALSO show in header bar, if so var navButton = '<a target="_blank" style="margin-left:6px;" class="zbs-quote-quicknav-contact ui icon button black mini labeled" href="<?php echo jpcrm_esc_link( 'edit', -1, 'zerobs_customer', true ); ?>' + contactID + '"><i class="user icon"></i> <?php zeroBSCRM_slashOut( __( 'Contact', 'zero-bs-crm' ) ); ?></a>'; jQuery('#zbs-quote-learn-nav').append(navButton); // bind //zeroBSCRMJS_bindContactLinkIf(); } } } </script> </div> <?php // wh centralised 20/7/18 - 2.91+ skipFields zeroBSCRM_html_editFields($quote,$fields,'zbscq_'); #} if enabled, and new quote, or one which hasn't had the 'templated' meta key added. if ($useQuoteBuilder == 1 && !isset($quote['template'])){ ?> <div class="jpcrm-form-group jpcrm-form-group-span-2"> <div class="zbs-move-on-wrap"> <!-- infoz --> <h3><?php esc_html_e('Publish this Quote',"zero-bs-crm");?></h3> <p><?php esc_html_e('Do you want to use the Quote Builder to publish this quote? (This lets you email it to a client directly, for approval)',"zero-bs-crm");?></p> <input type="hidden" name="zbs_quote_template_id_used" id="zbs_quote_template_id_used" value="<?php if (isset($templateUsed) && !empty($templateUsed)) echo esc_attr( $templateUsed ); ?>" /> <select class="form-control" name="zbs_quote_template_id" id="zbs_quote_template_id"> <option value="" disabled="disabled"><?php esc_html_e('Select a template',"zero-bs-crm");?>:</option> <?php $templates = zeroBS_getQuoteTemplates(true,100,0); #} If this quote has already selected a template it'll be stored in the meta under 'templateid' #} But if it's not the first, we never need to show this anyway... if (count($templates) > 0) foreach ($templates as $template){ $templateName = __('Template','zero-bs-crm').' '.$template['id']; if (isset($template['title']) && !empty($template['title'])) $templateName = $template['title'].' ('.$template['id'].')'; echo '<option value="' . esc_attr( $template['id'] ) . '"'; #if (isset()) echo '>' . esc_html( $templateName ) . '</option>'; } ?> <option value=""><?php esc_html_e("Blank Template","zero-bs-crm");?></option> </select> <br /> <p><?php esc_html_e('Create additional quote templates',"zero-bs-crm"); ?> <a href="<?php echo jpcrm_esc_link( $zbs->slugs['quote-templates'] ); ?>"><?php esc_html_e('here',"zero-bs-crm");?></a></p> <button type="button" id="zbsQuoteBuilderStep2" class="ui button button-primary black button-large xl"<?php if ( ! isset( $quoteContactID ) || empty( $quoteContactID ) ) { echo ' disabled="disabled"'; } ?>><?php esc_html_e( 'Use Quote Builder', 'zero-bs-crm' ); // phpcs:ignore Squiz.ControlStructures.ControlSignature.NewlineAfterOpenBrace, WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?></button> <?php if (!isset($quoteContactID) || empty($quoteContactID)){ ?> <p id="zbsQuoteBuilderStep2info">(<?php esc_html_e( "You'll need to assign this Quote to a contact to use this", 'zero-bs-crm' ); ?>);</p> <?php } ?> </div> </div> <?php } ?> </div></div> <?php } public function save_data( $quoteID, $quote ) { if (!defined('ZBS_OBJ_SAVED')){ define('ZBS_OBJ_SAVED',1); // DAL3.0+ global $zbs; // check this if (empty($quoteID) || $quoteID < 1) $quoteID = -1; // defaults, pulled from DAL obj 25/2/19 /* $quote = array( 'title' => '', 'currency' => '', 'value' => '', 'date' => '', 'template' => '', 'content' => '', 'notes' => '', 'send_attachments' => -1, (removed 4.0.9) 'hash' => '', 'lastviewed' => '', 'viewed_count' => '', 'accepted' => '', //'created' => '', //'lastupdated' => '', ); */ $extraMeta = array(); // can pass any additional meta here // retrieve _POST into arr //global $zbsCustomerQuoteFields; //$zbsCustomerQuoteMeta = zeroBSCRM_save_fields($zbsCustomerQuoteFields,'zbscq_'); $autoGenAutonumbers = true; // generate if not set :) $removeEmpties = false; // req for autoGenAutonumbers $quote = zeroBS_buildObjArr($_POST,array(),'zbscq_','',$removeEmpties,ZBS_TYPE_QUOTE,$autoGenAutonumbers); // Use the tag-class function to retrieve any tags so we can add inline. // Save tags against objid $quote['tags'] = zeroBSCRM_tags_retrieveFromPostBag(true,ZBS_TYPE_QUOTE); /*// debug echo 'POST:<pre>'.print_r($_POST,1).'</pre>'; echo 'Quote:<pre>'.print_r($quote,1).'</pre>'; exit();*/ // we always get this, because it's used below, but not part of buildObjArr (currently at 3.0) if ($quoteID > 0) $quote['template'] = (int)$zbs->DAL->quotes->getQuoteTemplateID($quoteID); // content (from other metabox actually) if (isset($_POST['zbs_quote_content'])) { #} Save content //$data=htmlspecialchars($_POST['zbs_quote_content'], ENT_COMPAT); $quote['content'] = wp_kses( $_POST['zbs_quote_content'], $zbs->acceptable_html ); // phpcs:ignore WordPress.Security.NonceVerification.Missing,WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- to follow up with. #} update templated vars if (isset($_POST['zbs_quote_template_id'])) $quote['template'] = (int)sanitize_text_field($_POST['zbs_quote_template_id']); } #} First up, save quote id! #TRANSITIONTOMETANO // DAL 3 will probs move away from this, for now leaving for refactoring round 2 // for now store as meta (though perhaps needs a new field zbsid) $quoteOffset = zeroBSCRM_getQuoteOffset(); $quoteZBSID = (int)$quoteID+$quoteOffset; if (isset($_POST['zbsquoteid']) && !empty($_POST['zbsquoteid'])) $quoteZBSID = (int)$_POST['zbsquoteid']; //update_post_meta($post_id,"zbsid",$quoteID); $extraMeta['zbsid'] = $quoteZBSID; #} and increment this if (!empty($quoteZBSID)) zeroBSCRM_setMaxQuoteID($quoteZBSID); // assignments $zbsQuoteContact = -1; if (isset($_POST['zbscq_customer'])) $zbsQuoteContact = (int)sanitize_text_field($_POST['zbscq_customer']); $quote['contacts'] = ($zbsQuoteContact > 0) ? array($zbsQuoteContact) : array(); $zbsQuoteCompany = -1; if (isset($_POST['zbscq_company'])) $zbsQuoteCompany = (int)sanitize_text_field($_POST['zbscq_company']); $quote['companies'] = ($zbsQuoteCompany > 0) ? array($zbsQuoteCompany) : array(); /* line item (temp here from Inv metabox, not yet implemented in ui) //new way.. now not limited to 30 lines as now they are stored in [] type array in JS draw $zbsInvoiceLines = array(); foreach($_POST['zbsli_itemname'] as $k => $v){ $ks = sanitize_text_field( $k ); // at least this $zbsInvoiceLines[$ks]['title'] = sanitize_text_field($_POST['zbsli_itemname'][$k]); $zbsInvoiceLines[$ks]['desc'] = sanitize_text_field($_POST['zbsli_itemdes'][$k]); $zbsInvoiceLines[$ks]['quantity'] = sanitize_text_field($_POST['zbsli_quan'][$k]); $zbsInvoiceLines[$ks]['price'] = sanitize_text_field($_POST['zbsli_price'][$k]); $zbsInvoiceLines[$ks]['tax'] = sanitize_text_field($_POST['zbsli_tax'][$k]); } if (count($zbsInvoiceLines) > 0) $invoice['lineitems'] = $zbsInvoiceLines; */ // Status Overwrites (manual changes, only after initial save) if ($quoteID > 0 && isset($_POST['quote_status'])){ switch ($_POST['quote_status']){ case 'draft': // if changing to draft, remove any accepted date + template ID $quote['accepted'] = 0; $quote['template'] = -1; break; case 'published': // if changing to published, just needs accepted unsetting, and if no template, populate $quote['accepted'] = 0; // got template? // if not already set, set, otherwise leave existing set time in. if (!isset($quote['template']) || $quote['template'] <= 0) { // hacky setting of it to unlikely cieling $quote['template'] = 99999; } break; case 'accepted': // if not already accepted, mark accepted. // existing $accepted = (int)$zbs->DAL->quotes->getQuoteAcceptedTime($quoteID); // if not already set, set, otherwise leave existing set time in. if ($accepted <= 0) { // set it (first time, manual) $quote['accepted'] = time(); $quote['acceptedsigned'] = 'manual'; $quote['acceptedip'] = ''; } break; } } // add/update $addUpdateReturn = $zbs->DAL->quotes->addUpdateQuote(array( 'id' => $quoteID, 'data' => $quote, 'extraMeta' => $extraMeta, 'limitedFields' => -1 )); //echo 'adding:'.$quoteID.':<pre>'.print_r($quote,1).'</pre>'; exit(); // Note: For NEW objs, we make sure a global is set here, that other update funcs can catch // ... so it's essential this one runs first! // this is managed in the metabox Class :) if ($quoteID == -1 && !empty($addUpdateReturn) && $addUpdateReturn != -1) { $quoteID = $addUpdateReturn; global $zbsJustInsertedMetaboxID; $zbsJustInsertedMetaboxID = $quoteID; // set this so it redirs $this->newRecordNeedsRedir = true; } // success? if ($addUpdateReturn != -1 && $addUpdateReturn > 0){ // Update Msg // this adds an update message which'll go out ahead of any content // This adds to metabox: $this->updateMessages['update'] = zeroBSCRM_UI2_messageHTML('info olive mini zbs-not-urgent',__('Contact Updated',"zero-bs-crm"),'','address book outline','contactUpdated'); // This adds to edit page $this->updateMessage(); // catch any non-critical messages $nonCriticalMessages = $zbs->DAL->getErrors(ZBS_TYPE_QUOTE); if (is_array($nonCriticalMessages) && count($nonCriticalMessages) > 0) $this->dalNoticeMessage($nonCriticalMessages); } else { // fail somehow $failMessages = $zbs->DAL->getErrors(ZBS_TYPE_QUOTE); // show msg (retrieved from DAL err stack) if (is_array($failMessages) && count($failMessages) > 0) $this->dalErrorMessage($failMessages); else $this->dalErrorMessage(array(__('Insert/Update Failed with general error','zero-bs-crm'))); // pass the pre-fill: global $zbsObjDataPrefill; $zbsObjDataPrefill = $quote; } } return $quote; } // This catches 'new' contacts + redirs to right url public function post_save_data($objID,$obj){ if ($this->newRecordNeedsRedir){ global $zbsJustInsertedMetaboxID; if (!empty($zbsJustInsertedMetaboxID) && $zbsJustInsertedMetaboxID > 0){ // redir wp_redirect( jpcrm_esc_link('edit',$zbsJustInsertedMetaboxID,$this->objType) ); exit; } } } public function updateMessage(){ global $zbs; // zbs-not-urgent means it'll auto hide after 1.5s // genericified from DAL3.0 $msg = zeroBSCRM_UI2_messageHTML('info olive mini zbs-not-urgent',$zbs->DAL->typeStr($zbs->DAL->objTypeKey($this->objType)).' '.__('Updated',"zero-bs-crm"),'','address book outline','contactUpdated'); $zbs->pageMessages[] = $msg; } } /* ====================================================== / Quote Metabox ====================================================== */ /* ====================================================== Quote Content Metabox ====================================================== */ class zeroBS__Metabox_QuoteContent extends zeroBS__Metabox{ public function __construct( $plugin_file ) { // set these $this->objType = 'quote'; $this->metaboxID = 'zerobs-quote-content-edit'; $this->metaboxTitle = __('Step 2: Quote Content','zero-bs-crm'); // will be headless anyhow $this->headless = true; $this->metaboxScreen = 'zbs-add-edit-quote-edit'; $this->metaboxArea = 'normal'; $this->metaboxLocation = 'low'; $this->saveOrder = 1; $this->capabilities = array( 'can_hide' => false, // can be hidden 'areas' => array('normal'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => true, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true, // can be minimised 'can_move' => true // can be moved ); // call this $this->initMetabox(); } public function html( $quote, $metabox ) { global $zbs; // localise ID & content $quoteID = -1; if (is_array($quote) && isset($quote['id'])) $quoteID = (int)$quote['id']; $quote_content = ''; if ( is_array( $quote ) && isset( $quote['content'] ) ) { $quote_content = wp_kses( $quote['content'], $zbs->acceptable_html ); } // remove "Add contact form" button from Jetpack remove_action( 'media_buttons', 'grunion_media_button', 999 ); wp_editor( $quote_content, 'zbs_quote_content', array( 'editor_height' => 580, 'wpautop' => false, ) ); } // saved via main metabox } /* ====================================================== / Quote Content Metabox ====================================================== */ /* ====================================================== Quote Next Step Metabox ====================================================== */ class zeroBS__Metabox_QuoteNextStep extends zeroBS__Metabox{ public function __construct( $plugin_file ) { // set these $this->objType = 'quote'; $this->metaboxID = 'zerobs-quote-nextstep'; $this->metaboxTitle = __('Step 3: Publish and Send','zero-bs-crm'); // will be headless anyhow $this->headless = true; $this->metaboxScreen = 'zbs-add-edit-quote-edit'; $this->metaboxArea = 'normal'; $this->metaboxLocation = 'low'; $this->saveOrder = 1; $this->capabilities = array( 'can_hide' => false, // can be hidden 'areas' => array('normal'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => true, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true, // can be minimised 'can_move' => true // can be moved ); // call this $this->initMetabox(); } public function html( $quote, $metabox ) { if ( $quote === false ) { $quote = array(); } global $zbs; // localise ID & content $quoteID = -1; if (is_array($quote) && isset($quote['id'])) $quoteID = (int)$quote['id']; #} retrieve // some legacy bits from CPT days: $quoteContactID = -1; if (is_array($quote) && isset($quote['contact']) && is_array($quote['contact']) && count($quote['contact']) > 0) $quoteContactID = $quote['contact'][0]['id']; //get_post_meta($post->ID, 'zbs_customer_quote_customer', true); $templateUsed = -1; if (is_array($quote) && isset($quote['template'])) $templateUsed = $quote['template']; //get_post_meta($post->ID, 'zbs_quote_template_id', true); #} Using "Quote Builder" or not? $useQuoteBuilder = zeroBSCRM_getSetting('usequotebuilder'); $useHash = zeroBSCRM_getSetting('easyaccesslinks'); #} if enabled, and new quote, or one which hasn't had the 'templated' meta key added. if ($useQuoteBuilder == "1") { // retrieve email $contactEmail = ''; $contactEmail = $zbs->DAL->contacts->getContactEmail($quoteContactID);//zeroBS_contactEmail($quoteContactID); // quick WH predictive hack, not sure if viable - to test DAL3 $quote['templated'] = false; if ($templateUsed !== -1 && !empty($templateUsed)) $quote['templated'] = true; #} first load? if (gettype($quote) != "array" || !isset($quote['templated'])){ ?> <div class="zbs-move-on-wrap" style="padding-top:30px;"> <!-- infoz --> <h3><?php esc_html_e("Publish this Quote","zero-bs-crm");?></h3> <p><?php esc_html_e( "When you've finished writing your Quote, save it here before sending on to your contact", 'zero-bs-crm' ); ?>:</p> <button type="button" id="zbsQuoteBuilderStep3" class="button button-primary button-large xl"><?php esc_html_e("Save Quote","zero-bs-crm");?></button> </div> <?php } else { # already has a saved quote #} If Portal is uninstalled it will break Quotes. So show a message warning them that this should be on if (!zeroBSCRM_isExtensionInstalled('portal')){ ?> <div class="ui message red" style="font-size:18px;"> <b><i class="ui icon warning"></i><?php esc_html_e("Client Portal Deactivated","zero-bs-crm");?></b> <p><?php esc_html_e('You have uninstalled the Client Portal. The only way you will be able to send your Quote to your contact is by downloading a PDF (needs PDF invoicing installed) and then emailing it to them manually.','zero-bs-crm'); ?></p> <a class="ui button blue" href="<?php echo esc_url( admin_url('admin.php?page=zerobscrm-extensions') );?>"><?php esc_html_e("Enable Client Portal","zero-bs-crm"); ?></a> </div> <?php }else{ // v3.0+ we use hash urls, so check exists $dal3HashCheck = true; if ($zbs->isDAL3() && (!isset($quote['hash']) || empty($quote['hash']))) $dal3HashCheck = false; if (isset($contactEmail) && !empty($contactEmail) && zeroBSCRM_validateEmail($contactEmail) && (!$useHash || ($useHash && $dal3HashCheck))){ // has email, and portal, all good ?> <div class="zbs-move-on-wrap" style="padding-top:30px;"> <?php #} Add nonce echo '<script type="text/javascript">var zbscrmjs_secToken = \'' . esc_js( wp_create_nonce( 'zbscrmjs-ajax-nonce' ) ) . '\';</script>'; ?> <!-- infoz --> <h3><?php esc_html_e("Email or Share","zero-bs-crm");?></h3> <p><?php esc_html_e( 'Great! Your Quote has been published. You can now email it to your contact, or share the link directly', 'zero-bs-crm' ); ?>:</p> <?php do_action('zbs_quote_actions'); ?> <div class="zbsEmailOrShare"> <h4><?php esc_html_e( 'Email to Contact', 'zero-bs-crm' ); ?>:</h4> <!-- todo --> <p><input type="text" class="form-control" id="zbsQuoteBuilderEmailTo" value="<?php echo esc_attr( $contactEmail ); ?>" placeholder="<?php esc_attr_e('e.g. customer@yahoo.com','zero-bs-crm'); ?>" data-quoteid="<?php echo esc_attr( $quoteID ); ?>" /></p> <p><button type="button" id="zbsQuoteBuilderSendNotification" class="ui button black"><?php esc_html_e( 'Send Quote', 'zero-bs-crm' ); ?></button></p> <p class="small" id="zbsQuoteBuilderEmailToErr" style="display:none"><?php esc_html_e("An Email Address to send to is required","zero-bs-crm");?>!</p> </div> <?php if ( property_exists( $zbs->modules, 'portal' ) ) : $quote_id_or_hash = $useHash ? $quote['hash'] : $quoteID; $single_quote_slug = $zbs->modules->portal->get_endpoint( ZBS_TYPE_QUOTE ); $preview_url = zeroBS_portal_link( $single_quote_slug, $quote_id_or_hash ); ?> <div class="zbsEmailOrShare"> <h4><?php esc_html_e("Share the Link or","zero-bs-crm"); ?> <a href="<?php echo esc_url($preview_url); ?>" target="_blank"><?php esc_html_e("preview","zero-bs-crm");?></a>:</h4> <p><input type="text" class="form-control" id="zbsQuoteBuilderURL" value="<?php echo esc_url($preview_url); ?>" /></p> </div> <?php endif; ?> <?php #} WH second change, only showed if dompdf extension installed if (zeroBSCRM_isExtensionInstalled('pdfinv')){ #} PDF Invoicing is installed ?> <div class="zbsEmailOrShare"> <h4><?php esc_html_e("Download PDF","zero-bs-crm");?></h4> <p><i class="file pdf outline icon red" style="font-size:30px;margin-top:10px;"></i></p> <input type="button" name="jpcrm_quote_download_pdf" id="jpcrm_quote_download_pdf" class="ui button black" value="<?php esc_attr_e( 'Download PDF', 'zero-bs-crm' ); ?>" /> </div> <script type="text/javascript"> jQuery(function(){ // add your form to the end of body (outside <form>) var formHTML = '<form target="_blank" method="post" id="jpcrm_quote_download_pdf_form" action="">'; formHTML += '<input type="hidden" name="jpcrm_quote_download_pdf" value="1" />'; formHTML += '<input type="hidden" name="jpcrm_quote_id" value="<?php echo esc_attr( $quoteID ); ?>" />'; formHTML += '<input type="hidden" name="jpcrm_quote_pdf_gen_nonce" value="<?php echo esc_attr( wp_create_nonce( 'jpcrm-quote-pdf-gen' ) ); ?>" />'; formHTML += '</form>'; jQuery('#wpbody').append(formHTML); // on click jQuery('#jpcrm_quote_download_pdf').on( 'click', function(){ // submit form jQuery('#jpcrm_quote_download_pdf_form').submit(); }); }); </script> <?php } ?> </div> <?php } else { if (isset($quoteContactID) && $quoteContactID > 0){ // Contact, but they don't have an email addr on file: ?> <div class="zbs-move-on-wrap" style="padding-top:30px;"> <h3><?php esc_html_e("Email or Share","zero-bs-crm");?></h3> <div class="zbsEmailOrShare"> <h4><?php esc_html_e("Add Contact's Email","zero-bs-crm");?>:</h4> <p><?php esc_html_e('To proceed, edit the contact and add their email address, that way we can then send them this quote online.','zero-bs-crm'); ?></p> <p><a href="<?php echo jpcrm_esc_link( 'edit', $quoteContactID, 'zerobs_customer', true ); ?>" class="button button-primary button-large"><?php esc_html_e("Edit Contact","zero-bs-crm");?></a></p> </div> </div> <?php } else { // not yet assigned to anyone. ?> <div class="zbs-move-on-wrap" style="padding-top:30px;"> <h3><?php esc_html_e("Email or Share","zero-bs-crm");?></h3> <div class="zbsEmailOrShare"> <h4><?php esc_html_e("Assign to Contact","zero-bs-crm");?>:</h4> <p><?php esc_html_e('To proceed, assign this quote to a contact and save it.','zero-bs-crm'); ?></p> </div> </div> <?php } } } } } # if quotebuilder } // nothing to save. } /* ====================================================== / Quote Actions Metabox ====================================================== */ /* ====================================================== Quote files Metabox ====================================================== */ class zeroBS__Metabox_QuoteFiles extends zeroBS__Metabox{ public function __construct( $plugin_file ) { // DAL3 switched for objType $this->postType = 'zerobs_customer'; $this->objType = 'quote'; $this->metaboxID = 'zerobs-quote-files'; $this->metaboxTitle = __('Associated Files',"zero-bs-crm"); $this->metaboxScreen = 'zbs-add-edit-quote-edit'; //'zerobs_edit_contact'; // we can use anything here as is now using our func $this->metaboxArea = 'normal'; $this->metaboxLocation = 'low'; $this->capabilities = array( 'can_hide' => true, // can be hidden 'areas' => array('normal'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => true, // can/can't accept tabs onto it 'can_become_tab' => true, // can be added as tab 'can_minimise' => true // can be minimised ); // call this $this->initMetabox(); } public function html( $quote, $metabox ) { global $zbs; $html = ''; // localise ID $quoteID = -1; if (is_array($quote) && isset($quote['id'])) $quoteID = (int)$quote['id']; #} retrieve $zbsFiles = array(); if ($quoteID > 0) $zbsFiles = zeroBSCRM_files_getFiles('quote',$quoteID); ?><table class="form-table wh-metatab wptbp" id="wptbpMetaBoxMainItemFiles"> <?php // WH only slightly updated this for DAL3 - could do with a cleanup run (contact file edit has more functionality) #} Any existing if (is_array($zbsFiles) && count($zbsFiles) > 0){ ?><tr class="wh-large"><th><label><?php printf( esc_html( _n( '%s associated file', '%s associated files', count($zbsFiles), 'text-domain' ) ), esc_html( number_format_i18n( count($zbsFiles) ) ) ); ?></label></th> <td id="zbsFileWrapInvoices"> <?php $fileLineIndx = 1; foreach($zbsFiles as $zbsFile){ $file = zeroBSCRM_files_baseName($zbsFile['file'],isset($zbsFile['priv'])); echo '<div class="zbsFileLine" id="zbsFileLineQuote' . esc_attr( $fileLineIndx ) . '"><a href="' . esc_url( $zbsFile['url'] ) . '" target="_blank">' . esc_html( $file ) . '</a> (<span class="zbsDelFile" data-delurl="' . esc_attr( $zbsFile['url'] ) . '"><i class="fa fa-trash"></i></span>)</div>'; $fileLineIndx++; } ?> </td></tr><?php } ?> <?php #adapted from http://code.tutsplus.com/articles/attaching-files-to-your-posts-using-wordpress-custom-meta-boxes-part-1--wp-22291 $html .= '<input type="file" id="zbsobj_file_attachment" name="zbsobj_file_attachment" size="25" class="zbs-dc">'; ?><tr class="wh-large"><th><label><?php esc_html_e('Add File',"zero-bs-crm");?>:</label><br />(<?php esc_html_e('Optional',"zero-bs-crm");?>)<br /><?php esc_html_e('Accepted File Types',"zero-bs-crm");?>:<br /><?php echo esc_html( zeroBS_acceptableFileTypeListStr() ); ?></th> <td><?php wp_nonce_field(plugin_basename(__FILE__), 'zbsobj_file_attachment_nonce'); echo $html; ?></td></tr> </table> <script type="text/javascript"> var zbsQuotesCurrentlyDeleting = false; var zbsMetaboxFilesLang = { 'err': '<?php echo esc_html( zeroBSCRM_slashOut(__('Error',"zero-bs-crm")) ); ?>', 'unabletodel' : '<?php echo esc_html( zeroBSCRM_slashOut(__('Unable to delete this file',"zero-bs-crm")) ); ?>', } jQuery(function(){ jQuery('.zbsDelFile').on( 'click', function(){ if (!window.zbsQuotesCurrentlyDeleting){ // blocking window.zbsQuotesCurrentlyDeleting = true; var delUrl = jQuery(this).attr('data-delurl'); var lineIDtoRemove = jQuery(this).closest('.zbsFileLine').attr('id'); if (typeof delUrl != "undefined" && delUrl != ''){ // postbag! var data = { 'action': 'delFile', 'zbsfType': 'quotes', 'zbsDel': delUrl, // could be csv, never used though 'zbsCID': <?php echo esc_html( $quoteID ); ?>, 'sec': window.zbscrmjs_secToken }; // Send it Pat :D jQuery.ajax({ type: "POST", url: ajaxurl, // admin side is just ajaxurl not wptbpAJAX.ajaxurl, "data": data, dataType: 'json', timeout: 20000, success: function(response) { // visually remove jQuery('#' + lineIDtoRemove).remove(); // file deletion errors, show msg: if (typeof response.errors != "undefined" && response.errors.length > 0){ jQuery.each(response.errors,function(ind,ele){ jQuery('#zerobs-quotes-files-box').append('<div class="ui warning message" style="margin-top:10px;">' + ele + '</div>'); }); } }, error: function(response){ jQuery('#zerobs-quotes-files-box').append('<div class="ui warning message" style="margin-top:10px;"><strong>' + window.zbsMetaboxFilesLang.err + ':</strong> ' + window.zbsMetaboxFilesLang.unabletodel + '</div>'); } }); } window.zbsQuotesCurrentlyDeleting = false; } // / blocking }); }); </script><?php } public function save_data( $quoteID, $quote ) { global $zbsobj_justUploadedObjFile; $id = $quoteID; if(!empty($_FILES['zbsobj_file_attachment']['name']) && (!isset($zbsobj_justUploadedObjFile) || (isset($zbsobj_justUploadedObjFile) && $zbsobj_justUploadedObjFile != $_FILES['zbsobj_file_attachment']['name']) ) ) { /* --- security verification --- */ if(!wp_verify_nonce($_POST['zbsobj_file_attachment_nonce'], plugin_basename(__FILE__))) { return $id; } // end if if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $id; } // end if if (!zeroBSCRM_permsQuotes()){ return $id; } /* - end security verification - */ // Blocking repeat-upload bug $zbsobj_justUploadedObjFile = $_FILES['zbsobj_file_attachment']['name']; // verify file extension and mime type if ( jpcrm_file_check_mime_extension( $_FILES['zbsobj_file_attachment'] ) ){ $quote_dir_info = jpcrm_storage_dir_info_for_quotes( $quoteID ); $upload = jpcrm_save_admin_upload_to_folder( 'zbsobj_file_attachment', $quote_dir_info['files'] ); if ( isset( $upload['error'] ) && $upload['error'] != 0 ) { wp_die( 'There was an error uploading your file. The error is: ' . esc_html( $upload['error'] ) ); } else { // w mod - adds to array :) $zbsFiles = zeroBSCRM_files_getFiles('quote',$quoteID); if (is_array($zbsFiles)){ //add it $zbsFiles[] = $upload; } else { // first $zbsFiles = array($upload); } // update zeroBSCRM_files_updateFiles('quote',$quoteID, $zbsFiles); // Fire any 'post-upload-processing' (e.g. CPP makes thumbnails of pdf, jpg, etc.) // not req invoicing: do_action('zbs_post_upload_contact',$upload); } } else { wp_die("The file type that you've uploaded is not an accepted file format."); } } return $quote; } } /* ====================================================== / Attach files to quote metabox ====================================================== */ /* ====================================================== Quote Accepted Details Metabox ====================================================== */ class zeroBS__Metabox_QuoteAcceptedDetails extends zeroBS__Metabox{ // this is for catching 'new' contacts private $newRecordNeedsRedir = false; public function __construct( $plugin_file ) { // set these $this->objType = 'quote'; $this->metaboxID = 'zerobs-quote-status-edit'; $this->metaboxTitle = __('Quote Public Status','zero-bs-crm'); // will be headless anyhow $this->headless = true; $this->metaboxScreen = 'zbs-add-edit-quote-edit'; $this->metaboxArea = 'side'; $this->metaboxLocation = 'low'; $this->saveOrder = 1; $this->capabilities = array( 'can_hide' => false, // can be hidden 'areas' => array('side'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => true, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true, // can be minimised 'can_move' => true // can be moved ); global $useQuoteBuilder; // call this if ($useQuoteBuilder == "1") $this->initMetabox(); } public function html( $quote, $metabox ) { // localise ID & template $quoteID = -1; if (is_array($quote) && isset($quote['id'])) $quoteID = (int)$quote['id']; $templateUsed = -1; if (is_array($quote) && isset($quote['template'])) $templateUsed = $quote['template']; // quick WH predictive hack, not sure if viable - to test DAL3 $quote['templated'] = false; if ($templateUsed !== -1 && !empty($templateUsed)) $quote['templated'] = true; global $useQuoteBuilder; #} if enabled, and new quote, or one which hasn't had the 'templated' meta key added. #} ... also hide unless it's been "published" if ($useQuoteBuilder == "1" && (is_array($quote) && isset($quote['templated']) && $quote['templated'])) { if (isset($quote) && is_array($quote) && isset($quote['accepted']) && $quote['accepted'] > 0){ #} Deets $acceptedDate = date(zeroBSCRM_getTimeFormat().' '.zeroBSCRM_getDateFormat(),$quote['accepted']); $acceptedBy = $quote['acceptedsigned']; $acceptedIP = $quote['acceptedip']; ?> <table class="wh-metatab-side wptbp" id="wptbpMetaBoxQuoteStatus"> <tr><td style="text-align:center;color:green"><strong><?php esc_html_e('Accepted',"zero-bs-crm"); ?> <?php echo esc_html( $acceptedDate ); ?></strong></td></tr> <?php if (!empty($acceptedBy)) { ?><tr><td style="text-align:center"><?php esc_html_e('By: ',"zero-bs-crm"); ?> <a href="mailto:<?php echo esc_attr( $acceptedBy ); ?>" target="_blank"<?php if (!empty($acceptedIP)) { echo ' title="IP address:' . esc_attr( $acceptedIP ) . '"'; } ?>><?php echo esc_html( $acceptedBy ); ?></a></td></tr><?php } ?> </table> <?php } else { ?> <table class="wh-metatab-side wptbp" id="wptbpMetaBoxQuoteStatus"> <tr> <td style="text-align:center"><strong><?php esc_html_e('Not Yet Accepted',"zero-bs-crm"); ?></td></tr> </table> <?php } } else { // / only load if post type #} Gross hide :/ ?><style type="text/css">#wpzbscquote_status {display:none;}</style><?php } } // nothing to save } /* ====================================================== / Quote Accepted Details Metabox ====================================================== */ /* ====================================================== Create Tags Box ====================================================== */ class zeroBS__Metabox_QuoteTags extends zeroBS__Metabox_Tags{ public function __construct( $plugin_file ) { $this->objTypeID = ZBS_TYPE_QUOTE; // DAL3 switched for objType $this->postType = 'zerobs_customer'; $this->objType = 'quote'; $this->metaboxID = 'zerobs-quote-tags'; $this->metaboxTitle = __('Quote Tags',"zero-bs-crm"); $this->metaboxScreen = 'zbs-add-edit-quote-edit'; //'zerobs_edit_contact'; // we can use anything here as is now using our func $this->metaboxArea = 'side'; $this->metaboxLocation = 'high'; $this->showSuggestions = true; $this->capabilities = array( 'can_hide' => true, // can be hidden 'areas' => array('side'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => false, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true // can be minimised ); // call this $this->initMetabox(); } // html + save dealt with by parent class :) } /* ====================================================== / Create Tags Box ====================================================== */ /* ====================================================== Quote Actions Metabox ====================================================== */ class zeroBS__Metabox_QuoteActions extends zeroBS__Metabox{ public function __construct( $plugin_file ) { // set these $this->objType = 'quote'; $this->metaboxID = 'zerobs-quote-actions'; $this->metaboxTitle = __('Quote Actions','zero-bs-crm'); // will be headless anyhow $this->headless = true; $this->metaboxScreen = 'zbs-add-edit-quote-edit'; $this->metaboxArea = 'side'; $this->metaboxLocation = 'high'; $this->saveOrder = 1; $this->capabilities = array( 'can_hide' => false, // can be hidden 'areas' => array('high'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => true, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true, // can be minimised 'can_move' => true // can be moved ); // call this $this->initMetabox(); } public function html( $quote, $metabox ) { ?><div class="zbs-generic-save-wrap"> <div class="ui medium dividing header"><i class="save icon"></i> <?php esc_html_e('Quote Actions','zero-bs-crm'); ?></div> <?php // localise ID & content $quoteID = -1; if (is_array($quote) && isset($quote['id'])) $quoteID = (int)$quote['id']; #} if a saved post... //if (isset($post->post_status) && $post->post_status != "auto-draft"){ if ( $quoteID > 0 ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?> <div class="zbs-quote-actions-bottom zbs-objedit-actions-bottom"> <button class="ui button black" type="button" id="zbs-edit-save"><?php esc_html_e( 'Update', 'zero-bs-crm' ); ?> <?php esc_html_e( 'Quote', 'zero-bs-crm' ); ?></button> <?php // delete? // for now just check if can modify, later better, granular perms. if ( zeroBSCRM_permsQuotes() ) { ?><div id="zbs-quote-actions-delete" class="zbs-objedit-actions-delete"> <a class="submitdelete deletion" href="<?php echo jpcrm_esc_link( 'delete', $quoteID, 'quote' ); ?>"><?php esc_html_e('Delete Permanently', "zero-bs-crm"); ?></a> </div> <?php } // can delete ?> <div class='clear'></div> </div> <?php } else { // NEW quote ?> <button class="ui button black" type="button" id="zbs-edit-save"><?php esc_html_e( 'Save', 'zero-bs-crm' ); ?> <?php esc_html_e( 'Quote', 'zero-bs-crm' ); ?></button> <?php } ?></div><?php // / .zbs-generic-save-wrap } // html // saved via main metabox } /* ====================================================== / Quotes Actions Metabox ====================================================== */
projects/plugins/crm/includes/ZeroBSCRM.InvoiceBuilder.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V1.20 * * Copyright 2020 Automattic * * Date: 01/11/16 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ // takes inv meta and works out if due // now v3.0 friendly! function zeroBSCRM_invoiceBuilder_isInvoiceDue($zbsInvoice=array()){ global $zbs; if (is_array($zbsInvoice)){ // first get due $due = 0; if (isset($zbsInvoice['due_date']) && $zbsInvoice['due_date'] > 0) $due = (int)$zbsInvoice['due_date']; // compare (could give days difference here, but not req yet.) if ($due > time()){ // not due return false; } else { // due return true; } } return false; } /* ====================================================== ZBS Invoicing - REMOVE previous submit meta box + replace with custom ====================================================== */ #} This adds our own save box function zeroBSCRM_replace_invoice_submit_meta_box() { #} remove typical submit box: remove_meta_box('submitdiv', 'zerobs_invoice', 'core'); // $item represents post_type #} Include/initialise custom submitbox require_once( ZEROBSCRM_INCLUDE_PATH . 'ZeroBSCRM.MetaBoxes.SubmitBoxes.php'); } add_action( 'admin_init', 'zeroBSCRM_replace_invoice_submit_meta_box' ); #} This specifies 1 column pre-save, 2 columns post-save :) function zeroBSCRM_invoiceBuilderColumnCount(){ global $post; if (isset($post->post_status) && $post->post_status != "auto-draft") return 2; return 2; } add_filter('get_user_option_screen_layout_zerobs_invoice', 'zeroBSCRM_invoiceBuilderColumnCount' ); /* ====================================================== ZBS Invoicing - HTML GENERATOR ====================================================== */ #} Generates the HTML of an invoice based on the template in templates/invoices/invoice-pdf.html #} if $return, it'll return, otherwise it'll echo + exit #} --------- Notes: #} ... there's several ways we COULD do this, #} ... suggest we explore this way first, then re-discuss, #} ... Benefits of this inc. easy to theme ;) just create variations of invoice.html // Note: This is primarily used to generate PDF invoice html. (dig down and see use if "zeroBSCRM_invoicing_generateInvoiceHTML($invoiceID,'pdf'") function zeroBSCRM_invoice_generateInvoiceHTML($invoicePostID=-1,$return=true){ if (!empty($invoicePostID)){ global $zbs; return zeroBSCRM_invoice_generateInvoiceHTML_v3( $invoicePostID, $return ); } #} Empty inv id return false; } // invoice html generation 3.0+ function zeroBSCRM_invoice_generateInvoiceHTML_v3( $invoiceID=-1, $return=true ){ global $zbs; if (!empty($invoiceID)){ // Discern template and retrieve $global_invoice_pdf_template = zeroBSCRM_getSetting('inv_pdf_template'); if ( !empty( $global_invoice_pdf_template ) ){ $templatedHTML = jpcrm_retrieve_template( $global_invoice_pdf_template, false ); } // fallback to default template if ( !isset( $templatedHTML ) || empty( $templatedHTML ) ){ // template failed as setting potentially holds out of date (removed) template // so use the default $templatedHTML = jpcrm_retrieve_template( 'invoices/invoice-pdf.html', false ); } #} Act if (!empty($templatedHTML)){ // Over-ride the #MSGCONTENT# part $placeholder_templating = $zbs->get_templating(); // replace the content with our new ID ... (gets our content template info and replaces ###MSG CONTENT) $message_content = zeroBSCRM_mailTemplate_get(ZBSEMAIL_EMAILINVOICE); $message_content = $message_content->zbsmail_body; $templatedHTML = $placeholder_templating->replace_single_placeholder( 'msg-content', $message_content, $templatedHTML ); // for v3.0 WH split out the data-retrieval from scattering amongst this func, unified here: // translated the below cpt way into dal / v3.0: // this was refactored as was duplicate code. // now all wired through zeroBSCRM_invoicing_generateInvoiceHTML $html = zeroBSCRM_invoicing_generateInvoiceHTML($invoiceID,'pdf',$templatedHTML); // return if ( !$return ){ echo $html; exit(); } } return $html; } #} Empty inv id return false; } // this was clunky, so split into 3.0 and <3.0 versions. // ultimately this is much like zeroBSCRM_invoice_generateInvoiceHTML // ... should refactor the bits that are the same function zeroBSCRM_invoice_generatePortalInvoiceHTML($invoicePostID=-1,$return=true){ global $zbs; if (!empty($invoicePostID)){ return zeroBSCRM_invoice_generatePortalInvoiceHTML_v3( $invoicePostID, $return ); } #} Empty inv id return false; } // 3.0+ function zeroBSCRM_invoice_generatePortalInvoiceHTML_v3($invoiceID=-1,$return=true){ global $zbs; if (!empty($invoiceID)){ // Discern template and retrieve $global_invoice_portal_template = zeroBSCRM_getSetting('inv_portal_template'); if ( !empty( $global_invoice_portal_template ) ){ $html = jpcrm_retrieve_template( $global_invoice_portal_template, false ); } // fallback to default template if ( !isset( $html ) || empty( $html ) ){ // template failed as setting potentially holds out of date (removed) template // so use the default $html = jpcrm_retrieve_template( 'invoices/portal-invoice.html', false ); } #} Act if (!empty($html)){ // load templating $placeholder_templating = $zbs->get_templating(); // replace the content with our new ID ... (gets our content template info and replaces ###MSG CONTENT) $message_content = zeroBSCRM_mailTemplate_get(ZBSEMAIL_EMAILINVOICE); $message_content = $message_content->zbsmail_body; $html = $placeholder_templating->replace_single_placeholder( 'msg-content', $message_content, $html ); // this was refactored as was duplicate code. // now all wired through zeroBSCRM_invoicing_generateInvoiceHTML $html = zeroBSCRM_invoicing_generateInvoiceHTML($invoiceID,'portal',$html); // return if ( !$return ){ echo $html; exit(); } } return $html; } #} Empty inv id return false; } function zbs_invoice_generate_pdf(){ // download flag if ( isset( $_POST['zbs_invoicing_download_pdf'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing // THIS REALLLY needs nonces! For now (1.1.19) added this for you... if ( ! zeroBSCRM_permsInvoices() ) { exit(); } // Check ID $invoice_id = -1; if ( ! empty( $_POST['zbs_invoice_id'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing $invoice_id = (int) $_POST['zbs_invoice_id']; // phpcs:ignore WordPress.Security.NonceVerification.Missing } if ( $invoice_id <= 0 ) { exit(); } // generate the PDF $pdf_path = jpcrm_invoice_generate_pdf( $invoice_id ); if ( $pdf_path !== false ) { $pdf_filename = basename( $pdf_path ); // print the pdf file to the screen for saving header( 'Content-type: application/pdf' ); header( 'Content-Disposition: attachment; filename="' . $pdf_filename . '"' ); header( 'Content-Transfer-Encoding: binary' ); header( 'Content-Length: ' . filesize( $pdf_path ) ); header( 'Accept-Ranges: bytes' ); readfile( $pdf_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_readfile // delete the PDF file once it's been read (i.e. downloaded) wp_delete_file( $pdf_path ); } exit(); } } // This fires post ZBS init add_action( 'zerobscrm_post_init', 'zbs_invoice_generate_pdf' ); /** * Generate PDF file for an invoice * * @param int $invoice_id Invoice ID. * @return str path to PDF file */ function jpcrm_invoice_generate_pdf( $invoice_id = -1 ) { // brutal. if ( ! zeroBSCRM_permsInvoices() ) { return false; } // If user has no perms, or id not present, die if ( $invoice_id <= 0 ) { return false; } // Generate html $html = zeroBSCRM_invoice_generateInvoiceHTML( $invoice_id ); global $zbs; $invoice = $zbs->DAL->invoices->getInvoice( $invoice_id ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase // if invoice has reference number, use instead of ID if ( ! empty( $invoice['id_override'] ) ) { $invoice_id = $invoice['id_override']; } // normalise translated text to alphanumeric, resulting in a filename like `invoice-321.pdf` $pdf_filename = sanitize_title( __( 'Invoice', 'zero-bs-crm' ) . '-' . $invoice_id ) . '.pdf'; // return PDF filename if successful, false if not return jpcrm_generate_pdf( $html, $pdf_filename ); } // LEGACY, should now be using zeroBSCRM_invoice_generateInvoiceHTML // still used in Client Portal Pro function zbs_invoice_html($invoicePostID){ $html = zeroBSCRM_invoice_generateInvoiceHTML($invoicePostID); return $html; } #} this generates a PDF statement for a contact, either returning the filepath or a PDF download prompt function zeroBSCRM_invoicing_generateStatementPDF( $contactID = -1, $returnPDF = false ){ if (!zeroBSCRM_permsInvoices()) exit(); global $zbs; #} Check ID $contactID = (int)$contactID; #} If user has no perms, or id not present, die if (!zeroBSCRM_permsInvoices() || empty($contactID) || $contactID <= 0){ die(); } $html = zeroBSCRM_invoicing_generateStatementHTML($contactID); // build PDF $dompdf = $zbs->pdf_engine(); $dompdf->loadHtml($html,'UTF-8'); $dompdf->render(); // target dir $upload_dir = wp_upload_dir(); $zbsInvoicingDir = $upload_dir['basedir'].'/invoices/'; if ( ! file_exists( $zbsInvoicingDir ) ) { wp_mkdir_p( $zbsInvoicingDir ); } // got it? if ( ! file_exists( $zbsInvoicingDir ) ) { return false; } // make a hash // here we've tried to protect against someone overriding the security, // but if they're inside... it's too late anyhow. $hash = wp_generate_password(14, false); if (empty($hash) || strlen($hash) < 14) $hash = md5(time().'xcsac'); // backup $statementFilename = $zbsInvoicingDir.$hash.'-'.__('statement','zero-bs-crm').'-'.$contactID.'.pdf'; //save the pdf file on the server file_put_contents($statementFilename, $dompdf->output()); if (file_exists( $statementFilename )) { // if return pdf, return, otherwise return filepath if ($returnPDF){ //print the pdf file to the screen for saving header('Content-type: application/pdf'); header('Content-Disposition: attachment; filename="invoice-'.$invoiceID.'.pdf"'); header('Content-Transfer-Encoding: binary'); header('Content-Length: ' . filesize($statementFilename)); header('Accept-Ranges: bytes'); readfile($statementFilename); //delete the PDF file once it's been read (i.e. downloaded) unlink($statementFilename); } else { return $statementFilename; } } // if file return false; } /* ====================================================== ZBS Invoicing - STATEMENT HTML GENERATOR ====================================================== */ // phpcs:ignore Squiz.Commenting.FunctionComment.MissingParamTag /** * Generates the HTML of an invoice based on the template in templates/invoices/statement-pdf.html * if $return, it'll return, otherwise it'll echo + exit **/ function zeroBSCRM_invoicing_generateStatementHTML( $contact_id = -1, $return = true ) { if ( ! empty( $contact_id ) && $contact_id > 0 ) { // Discern template and retrieve $global_statement_pdf_template = zeroBSCRM_getSetting( 'statement_pdf_template' ); if ( ! empty( $global_statement_pdf_template ) ) { $templated_html = jpcrm_retrieve_template( $global_statement_pdf_template, false ); } // fallback to default template if ( ! isset( $templated_html ) || empty( $templated_html ) ) { // template failed as setting potentially holds out of date (removed) template // so use the default $templated_html = jpcrm_retrieve_template( 'invoices/statement-pdf.html', false ); } // Act if ( ! empty( $templated_html ) ) { return zeroBSCRM_invoicing_generateStatementHTML_v3( $contact_id, $return, $templated_html ); } } // Empty inv id return false; } // 3.0+ (could now run off contact or company, but that's not written in yet) // phpcs:ignore Squiz.Commenting.FunctionComment.Missing function zeroBSCRM_invoicing_generateStatementHTML_v3( $contact_id = -1, $return = true, $templated_html = '' ) { if ( $contact_id > 0 && $templated_html !== '' ) { global $zbs; // Globals $biz_name = zeroBSCRM_getSetting( 'businessname' ); $biz_contact_name = zeroBSCRM_getSetting( 'businessyourname' ); $biz_contact_email = zeroBSCRM_getSetting( 'businessyouremail' ); $biz_url = zeroBSCRM_getSetting( 'businessyoururl' ); $biz_extra = zeroBSCRM_getSetting( 'businessextra' ); $biz_tel = zeroBSCRM_getSetting( 'businesstel' ); $statement_extra = zeroBSCRM_getSetting( 'statementextra' ); $logo_url = zeroBSCRM_getSetting( 'invoicelogourl' ); // invoices $invoices = $zbs->DAL->invoices->getInvoices( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase array( 'assignedContact' => $contact_id, // assigned to contact id (int) 'assignedCompany' => false, // assigned to company id (int) // returns 'withLineItems' => true, 'withCustomFields' => true, 'withTransactions' => true, // partials 'withTags' => false, // sort 'sortByField' => 'ID', 'sortOrder' => 'ASC', ) ); // statement table wrapper $statement_table = '<table id="zbs-statement-table" border="0" cellpadding="0" cellspacing="0" class="body" style="border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt;background-color:#FFF;width:100%;">'; // logo header if ( ! empty( $logo_url ) ) { $statement_table .= '<tr><td colspan="3" style="text-align:right"><img src="' . esc_url( $logo_url ) . '" alt="' . esc_attr( $biz_name ) . '" style="max-width:200px;max-height:140px" /></td></tr>'; } // title $statement_table .= '<tr><td colspan="3"><h2 class="zbs-statement">' . esc_html__( 'STATEMENT', 'zero-bs-crm' ) . '</h2></td></tr>'; // address | dates | biz deets line $statement_table .= '<tr>'; // contact address // v3.0 $contact_details = $zbs->DAL->contacts->getContact( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase $contact_id, array( 'withCustomFields' => true, 'withQuotes' => false, 'withInvoices' => false, 'withTransactions' => false, 'withLogs' => false, 'withLastLog' => false, 'withTags' => false, 'withCompanies' => false, 'withOwner' => false, 'withValues' => false, ) ); if ( is_array( $contact_details ) && isset( $contact_details['fname'] ) ) { $invoice_customer_info_table_html = '<div class="zbs-line-info zbs-line-info-title">' . esc_html( $contact_details['fname'] ) . ' ' . esc_html( $contact_details['lname'] ) . '</div>'; if ( isset( $contact_details['addr1'] ) && ! empty( $contact_details['addr1'] ) ) { $invoice_customer_info_table_html .= '<div class="zbs-line-info">' . esc_html( $contact_details['addr1'] ) . '</div>'; } if ( isset( $contact_details['addr2'] ) && ! empty( $contact_details['addr2'] ) ) { $invoice_customer_info_table_html .= '<div class="zbs-line-info">' . esc_html( $contact_details['addr2'] ) . '</div>'; } if ( isset( $contact_details['city'] ) && ! empty( $contact_details['city'] ) ) { $invoice_customer_info_table_html .= '<div class="zbs-line-info">' . esc_html( $contact_details['city'] ) . '</div>'; } if ( isset( $contact_details['county'] ) && ! empty( $contact_details['county'] ) ) { $invoice_customer_info_table_html .= '<div class="zbs-line-info">' . esc_html( $contact_details['county'] ) . '</div>'; } if ( isset( $contact_details['postcode'] ) && ! empty( $contact_details['postcode'] ) ) { $invoice_customer_info_table_html .= '<div class="zbs-line-info">' . esc_html( $contact_details['postcode'] ) . '</div>'; } } // add $statement_table .= '<td><div style="text-align:left">' . $invoice_customer_info_table_html . '</div></td>'; // Dates $statement_table .= '<td>'; $statement_table .= '<div class="zbs-statement-date"><strong>' . esc_html__( 'Statement Date', 'zero-bs-crm' ) . '</strong><br />' . esc_html( zeroBSCRM_locale_utsToDate( time() ) ) . '</div>'; $statement_table .= '</td>'; // Biz deets // get biz deets $biz_info_table = '<div class="zbs-line-info zbs-line-info-title">' . esc_html( $biz_name ) . '</div>'; if ( ! empty( $biz_contact_name ) ) { $biz_info_table .= '<div class="zbs-line-info">' . esc_html( $biz_contact_name ) . '</div>'; } if ( ! empty( $biz_extra ) ) { $biz_info_table .= '<div class="zbs-line-info">' . nl2br( esc_html( $biz_extra ) ) . '</div>'; } if ( ! empty( $biz_contact_email ) ) { $biz_info_table .= '<div class="zbs-line-info">' . esc_html( $biz_contact_email ) . '</div>'; } if ( ! empty( $biz_url ) ) { $biz_info_table .= '<div class="zbs-line-info">' . esc_html( $biz_url ) . '</div>'; } if ( ! empty( $biz_tel ) ) { $biz_info_table .= '<div class="zbs-line-info">' . esc_html( $biz_tel ) . '</div>'; } // add $statement_table .= '<td><div class="zbs-biz-info">' . $biz_info_table . '</div></td>'; $statement_table .= '</tr>'; // STATEMENT table // start $s_table = '<table border="0" cellpadding="0" cellspacing="0" class="body" style="border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt;background-color:#FFF;width:100%">'; // header $s_table .= '<tr><th cellpadding="0" cellspacing="0" >' . esc_html__( 'Date', 'zero-bs-crm' ) . '</th>'; $s_table .= '<th cellpadding="0" cellspacing="0" >' . esc_html( $zbs->settings->get( 'reflabel' ) ) . '</th>'; $s_table .= '<th cellpadding="0" cellspacing="0" >' . esc_html__( 'Due date', 'zero-bs-crm' ) . '</th>'; $s_table .= '<th class="zbs-accountant-td" style="text-align:right">' . esc_html__( 'Amount', 'zero-bs-crm' ) . '</th>'; $s_table .= '<th class="zbs-accountant-td" style="text-align:right">' . esc_html__( 'Payments', 'zero-bs-crm' ) . '</th>'; $s_table .= '<th class="zbs-accountant-td" style="text-align:right">' . esc_html__( 'Balance', 'zero-bs-crm' ) . '</th></tr>'; // should be all of em so can do 'outstanding balance' from this $balance_due = 0.00; // rows. (all invs for this contact) if ( is_array( $invoices ) && count( $invoices ) > 0 ) { foreach ( $invoices as $invoice ) { // number $invoice_reference = $invoice['id']; if ( isset( $invoice['id_override'] ) && ! empty( $invoice['id_override'] ) ) { $invoice_reference = $invoice['id_override']; } // date $invoice_date = $invoice['date_date']; // due if ( $invoice['due_date'] <= 0 ) { //no due date; $due_date_str = __( 'No due date', 'zero-bs-crm' ); } else { $due_date_str = $invoice['due_date_date']; // is it due? if ( zeroBSCRM_invoiceBuilder_isInvoiceDue( $invoice ) ) { $due_date_str .= ' [' . esc_html__( 'Due', 'zero-bs-crm' ) . ']'; } } // partials = transactions associated in v3.0 model $partials = $invoice['transactions']; // ================= / DATA RETRIEVAL =================================== // total etc. $total = 0.00; $payments = 0.00; $balance = 0.00; if ( isset( $invoice['total'] ) && $invoice['total'] > 0 ) { $total = $invoice['total']; $balance = $total; } // 2 ways here - if marked 'paid', then assume balance // ... if not, then trans allocation check if ( isset( $invoice['status'] ) && $invoice['status'] === 'Paid' ) { // assume fully paid $balance = 0.00; $payments = $total; } elseif ( is_array( $partials ) ) { foreach ( $partials as $partial ) { // ignore if status_bool (non-completed status) $partial['status_bool'] = (int) $partial['status_bool']; if ( isset( $partial ) && $partial['status_bool'] == 1 && isset( $partial['total'] ) && $partial['total'] > 0 ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual // v3.0+ has + or - partials. Account for that: if ( $partial['type_accounting'] === 'credit' ) { // credit note, or refund $balance = $balance + $partial['total']; // add to payments $payments += $partial['total']; } else { // assume debit $balance = $balance - $partial['total']; // add to payments $payments += $partial['total']; } } } // /foreach } // if is array // now we add any outstanding bal to the total bal for table if ( $balance > 0 ) { $balance_due += $balance; } // output $s_table .= '<tr><td>' . esc_html( $invoice_date ) . '</td>'; $s_table .= '<td>' . esc_html( $invoice_reference ) . '</td>'; $s_table .= '<td>' . esc_html( $due_date_str ) . '</td>'; $s_table .= '<td class="zbs-accountant-td">' . esc_html( zeroBSCRM_formatCurrency( $total ) ) . '</td>'; $s_table .= '<td class="zbs-accountant-td">' . esc_html( zeroBSCRM_formatCurrency( $payments ) ) . '</td>'; $s_table .= '<td class="zbs-accountant-td">' . esc_html( zeroBSCRM_formatCurrency( $balance ) ) . '</td></tr>'; } } else { // No invoices? $s_table .= '<tr><td colspan="6" style="text-align:center;font-size:14px;font-weight:bold;padding:2em">' . esc_html__( 'No Activity', 'zero-bs-crm' ) . '</td></tr>'; } // footer $s_table .= '<tr class="zbs-statement-footer"><td colspan="6">' . esc_html__( 'BALANCE DUE', 'zero-bs-crm' ) . ' ' . esc_html( zeroBSCRM_formatCurrency( $balance_due ) ) . '</td></tr>'; // close table $s_table .= '</table>'; // add $statement_table .= '<tr><td colspan="3">' . $s_table . '</td></tr>'; // Extra Info $statement_table .= '<tr><td colspan="3" style="text-align:left;padding: 30px;">' . nl2br( esc_html( $statement_extra ) ) . '</td></tr>'; // close table $statement_table .= '</table>'; // load templating $placeholder_templating = $zbs->get_templating(); // main content build $html = $placeholder_templating->replace_single_placeholder( 'invoice-statement-html', $statement_table, $templated_html ); // return if ( ! $return ) { echo $html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped exit(); } return $html; } // /if anything return false; } // phpcs:ignore Squiz.Commenting.FunctionComment.MissingParamTag,Generic.Commenting.DocComment.MissingShort /** * * Generate an invoice as html (where the actual holder-html is passed) * ... this is a refactor of what was being replicated 3 places * ... 1) Invoice PDF Gen (zeroBSCRM_invoice_generateInvoiceHTML) * ... 2) Invoice Portal Gen (zeroBSCRM_invoice_generatePortalInvoiceHTML) * ... 3) Invoice email notification Gen (zeroBSCRM_invoice_generateNotificationHTML in mail-templating.php) * ... now the generic element of the above are all wired through here :) * Note: * $template is crucial. pdf | portal | notification *currently v3.0 **/ function zeroBSCRM_invoicing_generateInvoiceHTML( $invoice_id = -1, $template = 'pdf', $html = '' ) { global $zbs; // load templating $placeholder_templating = $zbs->get_templating(); // need this. if ( $invoice_id <= 0 || $html == '' ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual return ''; } // for v3.0 WH split out the data-retrieval from scattering amongst this func, unified here: // translated the below cpt way into dal / v3.0: // ================== DATA RETRIEVAL =================================== $invoice = $zbs->DAL->invoices->getInvoice( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase $invoice_id, array( // we want all this: 'withLineItems' => true, 'withCustomFields' => true, 'withTransactions' => true, // gets trans associated with inv as well 'withAssigned' => true, // return arrays of assigned contact and companies objects 'withTags' => true, 'withOwner' => true, 'withTotals' => true, ) ); // retrieve $zbs_customer_id = -1; if ( is_array( $invoice ) && isset( $invoice['contact'] ) && is_array( $invoice['contact'] ) && count( $invoice['contact'] ) > 0 ) { $zbs_customer_id = $invoice['contact'][0]['id']; } $zbs_company_id = -1; if ( is_array( $invoice ) && isset( $invoice['company'] ) && is_array( $invoice['company'] ) && count( $invoice['company'] ) > 0 ) { $zbs_company_id = $invoice['company'][0]['id']; } // date $inv_date_str = jpcrm_uts_to_date_str( $invoice['date'] ); // due if ( $invoice['due_date'] <= 0 ) { //no due date $due_date_str = __( 'No due date', 'zero-bs-crm' ); } else { $due_date_str = jpcrm_uts_to_date_str( $invoice['due_date'] ); } // Custom fields $invoice_custom_fields_html = jpcrm_invoicing_generate_invoice_custom_fields_lines( $invoice, $template ); // default status and status label if ( ! isset( $invoice['status'] ) ) { $invoice['status'] = 'Draft'; } if ( ! isset( $invoice['status_label'] ) ) { $invoice['status_label'] = __( 'Draft', 'zero-bs-crm' ); } // status html: if ( $template === 'portal' ) { // portal version: Includes status label and amount (shown at top of portal invoice) $top_status = '<div class="zbs-portal-label">'; $top_status .= esc_html( $invoice['status_label'] ); $top_status .= '</div>'; // WH added quickly to get around fact this is sometimes empty, please tidy when you address currency formatting :) $inv_g_total = ''; if ( isset( $invoice['total'] ) ) { $inv_g_total = zeroBSCRM_formatCurrency( $invoice['total'] ); } $top_status .= '<h1 class="zbs-portal-value">' . esc_html( $inv_g_total ) . '</h1>'; if ( $invoice['status'] === 'Paid' ) { $top_status .= '<div class="zbs-invoice-paid"><i class="fa fa-check"></i>' . esc_html( $invoice['status_label'] ) . '</div>'; } } elseif ( $template === 'pdf' ) { // pdf status if ( $invoice['status'] === 'Paid' ) { $top_status = '<div class="jpcrm-invoice-status jpcrm-invoice-paid">' . esc_html( $invoice['status_label'] ) . '</div>'; } else { $top_status = '<div class="jpcrm-invoice-status">' . esc_html( $invoice['status_label'] ) . '</div>'; } } elseif ( $template === 'notification' ) { // sent to contact via email $top_status = esc_html( $invoice['status_label'] ); } // inv lines $invlines = $invoice['lineitems']; // switch for Company if set... if ( $zbs_company_id > 0 ) { $inv_to = zeroBS_getCompany( $zbs_company_id ); if ( is_array( $inv_to ) && ( isset( $inv_to['name'] ) || isset( $inv_to['coname'] ) ) ) { if ( isset( $inv_to['name'] ) ) { $inv_to['fname'] = $inv_to['name']; // DAL3 } if ( isset( $inv_to['coname'] ) ) { $inv_to['fname'] = $inv_to['coname']; // DAL2 } $inv_to['lname'] = ''; } else { $inv_to = array( 'fname' => '', 'lname' => '', ); } // object type flag used downstream, I wonder if we should put these in at the DAL level.. $inv_to['objtype'] = ZBS_TYPE_COMPANY; } else { $inv_to = $zbs->DAL->contacts->getContact( $zbs_customer_id ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase if ( ! $inv_to ) { $inv_to = array(); } // object type flag used downstream, I wonder if we should put these in at the DAL level.. $inv_to['objtype'] = ZBS_TYPE_CONTACT; } // is this stored same format? $zbs_invoice_hours_or_quantity = $invoice['hours_or_quantity']; // partials = transactions associated in v3.0 model $partials = $invoice['transactions']; // ================= / DATA RETRIEVAL =================================== // ================= CONTENT BUILDING =================================== // Globals $invsettings = $zbs->settings->getAll(); $css_url = ZEROBSCRM_URL . 'css/ZeroBSCRM.admin.invoicepreview' . wp_scripts_get_suffix() . '.css'; $ref_label = $zbs->settings->get( 'reflabel' ); $logo_url = ''; if ( isset( $invoice['logo_url'] ) ) { if ( isset( $invoice['logo_url'] ) ) { $logo_url = $invoice['logo_url']; } } elseif ( isset( $invsettings['invoicelogourl'] ) && $invsettings['invoicelogourl'] != '' ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseNotEqual $logo_url = $invsettings['invoicelogourl']; } if ( $logo_url != '' && isset( $invoice['logo_url'] ) ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseNotEqual $logo_class = 'show'; $logo_url = $invoice['logo_url']; $biz_info_class = ''; } else { $logo_class = ''; $logo_url = ''; $biz_info_class = 'biz-up'; } // Invoice Number or Reference // Reference, falling back to ID $inv_id_styles = ''; $inv_ref_styles = 'display:none;'; // none initially // ID $this_inv_reference = $invoice['id']; // ID - Portal if ( $template === 'portal' ) { $this_inv_reference = __( 'Invoice #', 'zero-bs-crm' ) . ' ' . $this_inv_reference; } // Reference if ( isset( $invoice['id_override'] ) && ! empty( $invoice['id_override'] ) ) { // Ref $this_inv_reference = $invoice['id_override']; // Ref - Portal if ( $template === 'portal' ) { $this_inv_reference = $ref_label . ' ' . $this_inv_reference; } // and we don't show ID, do show ref label: $inv_id_styles = 'display:none;'; $inv_ref_styles = ''; } // replacement str $inv_no_str = $this_inv_reference; // Portal if ( $template === 'portal' ) { $inv_no_str = '<div class="zbs-normal">' . esc_html( $this_inv_reference ) . '</div>'; } // == Build biz info table. //the business info from the settings $zbs_biz_name = zeroBSCRM_getSetting( 'businessname' ); $zbs_biz_yourname = zeroBSCRM_getSetting( 'businessyourname' ); $zbs_biz_extra = zeroBSCRM_getSetting( 'businessextra' ); $zbs_biz_youremail = zeroBSCRM_getSetting( 'businessyouremail' ); $zbs_biz_yoururl = zeroBSCRM_getSetting( 'businessyoururl' ); // generate a templated biz info table $biz_info_table = zeroBSCRM_invoicing_generateInvPart_bizTable( array( 'zbs_biz_name' => $zbs_biz_name, 'zbs_biz_yourname' => $zbs_biz_yourname, 'zbs_biz_extra' => $zbs_biz_extra, 'zbs_biz_youremail' => $zbs_biz_youremail, 'zbs_biz_yoururl' => $zbs_biz_yoururl, 'template' => $template, ) ); // generate a templated customer info table $invoice_customer_info_table_html = zeroBSCRM_invoicing_generateInvPart_custTable( $inv_to, $template ); // == Lineitem table > Column headers // generate a templated customer info table $table_headers = zeroBSCRM_invoicing_generateInvPart_tableHeaders( $zbs_invoice_hours_or_quantity ); // == Lineitem table > Line items // generate a templated lineitems $line_items = zeroBSCRM_invoicing_generateInvPart_lineitems( $invlines ); // == Lineitem table > Totals // due to withTotals parameter on get above, we now don't need ot calc anything here, just expose $totals_table = ''; $totals_table .= '<table id="invoice_totals" class="table-totals zebra" style="width: 100%;"><tbody>'; if ( $invsettings['invtax'] != 0 || $invsettings['invpandp'] != 0 || $invsettings['invdis'] != 0 ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseNotEqual $totals_table .= '<tr class="total-top">'; $totals_table .= '<td class="bord bord-l" style="text-align:right; width: 80%; text-transform: uppercase;">' . esc_html__( 'Subtotal', 'zero-bs-crm' ) . '</td>'; $totals_table .= '<td class="bord row-amount" style="text-align:right; "><span class="zbs-totals">'; if ( isset( $invoice['net'] ) && ! empty( $invoice['net'] ) ) { $totals_table .= esc_html( zeroBSCRM_formatCurrency( $invoice['net'] ) ); } else { $totals_table .= esc_html( zeroBSCRM_formatCurrency( 0 ) ); } $totals_table .= '</span></td>'; $totals_table .= '</tr>'; } // discount if ( isset( $invoice['discount'] ) && ! empty( $invoice['discount'] ) ) { if ( $invsettings['invdis'] == 1 && isset( $invoice['totals'] ) && is_array( $invoice['totals'] ) && isset( $invoice['totals']['discount'] ) ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual $invoice_percent = ''; if ( $invoice['discount_type'] == '%' && $invoice['discount'] != 0 ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual,Universal.Operators.StrictComparisons.LooseNotEqual $invoice_percent = (float) $invoice['discount'] . '% '; } $totals_table .= '<tr class="discount"> <td class="bord bord-l" style="text-align:right; text-transform: uppercase;">' . esc_html( $invoice_percent . __( 'Discount', 'zero-bs-crm' ) ) . '</td> <td class="bord row-amount" id="zbs_discount_combi" style="text-align:right"><span class="zbs-totals">'; $totals_table .= '-' . esc_html( zeroBSCRM_formatCurrency( $invoice['totals']['discount'] ) ); $totals_table .= '</span></td>'; $totals_table .= '</tr>'; } } // shipping if ( $invsettings['invpandp'] == 1 ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual $totals_table .= '<tr class="postage_and_pack"> <td class="bord bord-l" style="text-align:right; text-transform: uppercase;">' . esc_html__( 'Postage and packaging', 'zero-bs-crm' ) . '</td> <td class="bord row-amount" id="pandptotal" style="text-align:right;"><span class="zbs-totals">'; if ( isset( $invoice['shipping'] ) && ! empty( $invoice['shipping'] ) ) { $totals_table .= esc_html( zeroBSCRM_formatCurrency( $invoice['shipping'] ) ); } else { $totals_table .= esc_html( zeroBSCRM_formatCurrency( 0 ) ); } $totals_table .= '</span></td>'; $totals_table .= '</tr>'; } // tax if ( $invsettings['invtax'] == 1 ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual $tax_lines = false; if ( isset( $invoice['totals'] ) && is_array( $invoice['totals'] ) && isset( $invoice['totals']['taxes'] ) ) { // now calc'd in DAL $tax_lines = $invoice['totals']['taxes']; } if ( isset( $tax_lines ) && is_array( $tax_lines ) && count( $tax_lines ) > 0 ) { foreach ( $tax_lines as $tax ) { $tax_name = __( 'Tax', 'zero-bs-crm' ); if ( isset( $tax['name'] ) ) { $tax_name = $tax['name']; } $totals_table .= '<tr class="ttclass"> <td class="bord bord-l" style="text-align:right">' . esc_html( $tax_name ) . '</td> <td class="bord bord-l row-amount zbs-tax-total-span" style="text-align:right"><span class="zbs-totals">'; if ( isset( $tax['value'] ) && ! empty( $tax['value'] ) ) { $totals_table .= esc_html( zeroBSCRM_formatCurrency( $tax['value'] ) ); } else { $totals_table .= esc_html( zeroBSCRM_formatCurrency( 0 ) ); } $totals_table .= '</span></td>'; $totals_table .= '</tr>'; } } else { // simple fallback $totals_table .= '<tr class="ttclass"> <td class="bord bord-l" style="text-align:right">' . esc_html__( 'Tax', 'zero-bs-crm' ) . '</td> <td class="bord bord-l row-amount zbs-tax-total-span" style="text-align:right"><span class="zbs-totals">'; if ( isset( $invoice['tax'] ) && ! empty( $invoice['tax'] ) ) { $totals_table .= esc_html( zeroBSCRM_formatCurrency( $invoice['tax'] ) ); } else { $totals_table .= esc_html( zeroBSCRM_formatCurrency( 0 ) ); } $totals_table .= '</span></td>'; $totals_table .= '</tr>'; } } $totals_table .= '<tr class="zbs_grand_total" style="line-height:30px;"> <td class="bord-l" style="text-align:right; font-weight:bold; border-radius: 0px;"><span class="zbs-total">' . __( 'Total', 'zero-bs-crm' ) . '</span></td> <td class="row-amount" style="text-align:right; font-weight:bold; border: 3px double #111!important; "><span class="zbs-total">'; if ( isset( $invoice['total'] ) && ! empty( $invoice['total'] ) ) { $totals_table .= esc_html( zeroBSCRM_formatCurrency( $invoice['total'] ) ); } else { $totals_table .= esc_html( zeroBSCRM_formatCurrency( 0 ) ); } $totals_table .= '</span></td>'; $totals_table .= '</tr>'; $totals_table .= '</table>'; // == Partials (Transactions against Invs) $partials_table = ''; if ( $invoice['total'] == 0 ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual $partials_table .= '<table id="partials" class="hide table-totals zebra">'; } else { $partials_table .= '<table id="partials" class="table-totals zebra">'; } $balance = $invoice['total']; if ( is_array( $partials ) && count( $partials ) > 0 ) { // header $partials_table .= '<tr><td colspan="2" style="text-align:center;font-weight:bold; border-radius: 0px;"><span class="zbs-total">' . esc_html__( 'Payments', 'zero-bs-crm' ) . '</span></td></tr>'; foreach ( $partials as $partial ) { // ignore if status_bool (non-completed status) $partial['status_bool'] = (int) $partial['status_bool']; if ( isset( $partial ) && $partial['status_bool'] == 1 ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual // v3.0+ has + or - partials. Account for that: if ( $partial['type_accounting'] === 'credit' ) { // credit note, or refund $balance = $balance + $partial['total']; } else { // assume debit $balance = $balance - $partial['total']; } $partials_table .= '<tr class="total-top">'; $partials_table .= '<td class="bord bord-l" style="text-align:right">' . esc_html__( 'Payment', 'zero-bs-crm' ) . '<br/>(' . esc_html( $partial['ref'] ) . ')</td>'; $partials_table .= '<td class="bord row-amount"><span class="zbs-partial-value">'; if ( ! empty( $partial['total'] ) ) { $partials_table .= esc_html( zeroBSCRM_formatCurrency( $partial['total'] ) ); } else { $partials_table .= esc_html( zeroBSCRM_formatCurrency( 0 ) ); } $partials_table .= '</span></td>'; $partials_table .= '</tr>'; } } } if ( $balance == $invoice['total'] ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual $balance_hide = 'hide'; } else { $balance_hide = ''; } $partials_table .= '<tr class="zbs_grand_total' . $balance_hide . '">'; $partials_table .= '<td class="bord bord-l" style="text-align:right; font-weight:bold; border-radius: 0px;"><span class="zbs-minitotal">' . esc_html__( 'Amount due', 'zero-bs-crm' ) . '</span></td>'; $partials_table .= '<td class="bord row-amount"><span class="zbs-subtotal-value">' . esc_html( zeroBSCRM_formatCurrency( $balance ) ) . '</span></td>'; $partials_table .= '</tr>'; $partials_table .= '</table>'; // generate a templated paybutton (depends on template :)) $potential_pay_button = zeroBSCRM_invoicing_generateInvPart_payButton( $invoice_id, $invoice['status'], $template ); // == Payment terms, thanks etc. will only replace when present in template, so safe to generically check $pay_thanks = ''; if ( $invoice['status'] === 'Paid' ) { $pay_thanks = '<div class="deets"><h3>' . esc_html__( 'Thank You', 'zero-bs-crm' ) . '</h3>'; $pay_thanks .= '<div>' . nl2br( esc_html( zeroBSCRM_getSetting( 'paythanks' ) ) ) . '</div>'; $pay_thanks .= '</div>'; } $payment_info_text = zeroBSCRM_getSetting( 'paymentinfo' ); $pay_details = '<div class="deets"><h2>' . esc_html__( 'Payment Details', 'zero-bs-crm' ) . '</h2>'; $pay_details .= '<div class="deets-line"><span class="deets-content">' . nl2br( esc_html( $payment_info_text ) ) . '</span></div>'; $pay_details .= '<div class="deets-line"><span class="deets-title">' . esc_html__( 'Payment Reference:', 'zero-bs-crm' ) . '</span> <span>' . $inv_no_str . '</span></div>'; $pay_details .= '</div>'; // == Template -> HTML build // powered by $powered_by = zeroBSCRM_mailTemplate_poweredByHTML(); $view_in_portal_link = ''; $view_in_portal_button = ''; // got portal? if ( zeroBSCRM_isExtensionInstalled( 'portal' ) ) { $view_in_portal_link = zeroBSCRM_portal_linkObj( $invoice_id, ZBS_TYPE_INVOICE ); $view_in_portal_button = '<div style="text-align:center;margin:1em;margin-top:2em">' . zeroBSCRM_mailTemplate_emailSafeButton( $view_in_portal_link, esc_html__( 'View Invoice', 'zero-bs-crm' ) ) . '</div>'; } // build replacements array $replacements = array( // invoice specific 'invoice-title' => __( 'Invoice', 'zero-bs-crm' ), 'css' => $css_url, 'logo-class' => $logo_class, 'logo-url' => esc_url( $logo_url ), 'invoice-number' => $inv_no_str, 'invoice-date' => $inv_date_str, 'invoice-id-styles' => $inv_id_styles, 'invoice-ref' => $inv_no_str, 'invoice-ref-styles' => $inv_ref_styles, 'invoice-due-date' => $due_date_str, 'invoice-custom-fields' => $invoice_custom_fields_html, 'invoice-biz-class' => $biz_info_class, 'invoice-customer-info' => $invoice_customer_info_table_html, 'invoice-html-status' => $top_status, 'invoice-table-headers' => $table_headers, 'invoice-line-items' => $line_items, 'invoice-totals-table' => $totals_table, 'invoice-partials-table' => $partials_table, 'invoice-pay-button' => $potential_pay_button, 'pre-invoice-payment-details' => '', 'invoice-payment-details' => $pay_details, 'invoice-pay-thanks' => $pay_thanks, // client portal 'portal-view-button' => $view_in_portal_button, 'portal-link' => $view_in_portal_link, // language 'invoice-label-inv-number' => __( 'Invoice number', 'zero-bs-crm' ) . ':', 'invoice-label-inv-date' => __( 'Invoice date', 'zero-bs-crm' ) . ':', 'invoice-label-inv-ref' => $zbs->settings->get( 'reflabel' ), 'invoice-label-status' => __( 'Status:', 'zero-bs-crm' ), 'invoice-label-from' => __( 'From', 'zero-bs-crm' ) . ':', 'invoice-label-to' => __( 'To', 'zero-bs-crm' ) . ':', 'invoice-label-due-date' => __( 'Due date', 'zero-bs-crm' ) . ':', 'invoice-pay-terms' => __( 'Payment terms', 'zero-bs-crm' ) . ': ' . __( 'Due', 'zero-bs-crm' ) . ' ', // global 'biz-info' => $biz_info_table, 'powered-by' => $powered_by, ); // Switch. If partials, put the payment deets on the left next to the partials, // rather than in it's own line: if ( ! empty( $partials_table ) ) { // partials, split to two columns $replacements['pre-invoice-payment-details'] = $pay_details; $replacements['invoice-payment-details'] = ''; } // replace vars $html = $placeholder_templating->replace_placeholders( array( 'invoice', 'global', 'contact', 'company' ), $html, $replacements, array( ZBS_TYPE_INVOICE => $invoice, $inv_to['objtype'] => $inv_to, ) ); // ================= / CONTENT BUILDING ================================= return $html; } // Used to generate specific part of invoice pdf: Biz table (Pay To) function zeroBSCRM_invoicing_generateInvPart_bizTable($args=array()){ #} =========== LOAD ARGS ============== $defaultArgs = array( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase 'zbs_biz_name' => '', 'zbs_biz_yourname' => '', 'zbs_biz_extra' => '', 'zbs_biz_youremail' => '', 'zbs_biz_yoururl' => '', 'template' => 'pdf', // this'll choose between the html output variants below, e.g. pdf, portal, notification ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= $biz_info_table = ''; switch ( $template ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable case 'pdf': case 'notification': $biz_info_table = '<div class="zbs-line-info zbs-line-info-title">' . esc_html( $zbs_biz_name ) . '</div>'; // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable $biz_info_table .= '<div class="zbs-line-info">' . esc_html( $zbs_biz_yourname ) . '</div>'; // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable $biz_info_table .= '<div class="zbs-line-info">' . nl2br( esc_html( $zbs_biz_extra ) ) . '</div>'; // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable $biz_info_table .= '<div class="zbs-line-info">' . esc_html( $zbs_biz_youremail ) . '</div>'; // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable $biz_info_table .= '<div class="zbs-line-info">' . esc_html( $zbs_biz_yoururl ) . '</div>'; // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable break; case 'portal': $biz_info_table = '<div class="pay-to">'; $biz_info_table .= '<div class="zbs-portal-label">' . esc_html__( 'Pay To', 'zero-bs-crm' ) . '</div>'; $biz_info_table .= '<div class="zbs-portal-biz">'; $biz_info_table .= '<div class="pay-to-name">' . esc_html( $zbs_biz_name ) . '</div>'; // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable $biz_info_table .= '<div>' . esc_html( $zbs_biz_yourname ) . '</div>'; // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable $biz_info_table .= '<div>' . nl2br( esc_html( $zbs_biz_extra ) ) . '</div>'; // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable $biz_info_table .= '<div>' . esc_html( $zbs_biz_youremail ) . '</div>'; // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable $biz_info_table .= '<div>' . esc_html( $zbs_biz_yoururl ) . '</div>'; // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable $biz_info_table .= '</div>'; $biz_info_table .= '</div>'; break; } return $biz_info_table; } /** // phpcs:ignore Squiz.Commenting.FunctionComment.MissingParamTag,Generic.Commenting.DocComment.MissingShort * Used to generate specific part of invoice pdf: (Customer table) **/ function zeroBSCRM_invoicing_generateInvPart_custTable( $inv_to = array(), $template = 'pdf' ) { $invoice_customer_info_table_html = '<div class="customer-info-wrapped">'; switch ( $template ) { case 'pdf': case 'notification': if ( isset( $inv_to['fname'] ) && isset( $inv_to['fname'] ) ) { $invoice_customer_info_table_html .= '<div class="zbs-line-info zbs-line-info-title">' . esc_html( $inv_to['fname'] ) . ' ' . esc_html( $inv_to['lname'] ) . '</div>'; } if ( isset( $inv_to['addr1'] ) ) { $invoice_customer_info_table_html .= '<div class="zbs-line-info">' . esc_html( $inv_to['addr1'] ) . '</div>'; } if ( isset( $inv_to['addr2'] ) ) { $invoice_customer_info_table_html .= '<div class="zbs-line-info">' . esc_html( $inv_to['addr2'] ) . '</div>'; } if ( isset( $inv_to['city'] ) ) { $invoice_customer_info_table_html .= '<div class="zbs-line-info">' . esc_html( $inv_to['city'] ) . '</div>'; } if ( isset( $inv_to['county'] ) ) { $invoice_customer_info_table_html .= '<div class="zbs-line-info">' . esc_html( $inv_to['county'] ) . '</div>'; } if ( isset( $inv_to['postcode'] ) ) { $invoice_customer_info_table_html .= '<div class="zbs-line-info">' . esc_html( $inv_to['postcode'] ) . '</div>'; } if ( isset( $inv_to['country'] ) ) { $invoice_customer_info_table_html .= '<div class="zbs-line-info">' . esc_html( $inv_to['country'] ) . '</div>'; } // Append custom fields if specified in settings $invoice_customer_info_table_html .= jpcrm_invoicing_generate_customer_custom_fields_lines( $inv_to, $template ); // the abilty to add in extra info to the customer info area. $extra_cust_info = ''; $extra_cust_info = apply_filters( 'zbs_invoice_customer_info_line', $extra_cust_info ); $invoice_customer_info_table_html .= $extra_cust_info; break; case 'portal': $invoice_customer_info_table_html .= '<div class="pay-to">'; $invoice_customer_info_table_html .= '<div class="zbs-portal-label">' . esc_html__( 'Invoice To', 'zero-bs-crm' ) . '</div><div style="margin-top:18px;">&nbsp;</div>'; $invoice_customer_info_table_html .= '<div class="zbs-portal-biz">'; if ( isset( $inv_to['fname'] ) && isset( $inv_to['fname'] ) ) { $invoice_customer_info_table_html .= '<div class="pay-to-name">' . esc_html( $inv_to['fname'] ) . ' ' . esc_html( $inv_to['lname'] ) . '</div>'; } if ( isset( $inv_to['addr1'] ) ) { $invoice_customer_info_table_html .= '<div>' . esc_html( $inv_to['addr1'] ) . '</div>'; } if ( isset( $inv_to['addr2'] ) ) { $invoice_customer_info_table_html .= '<div>' . esc_html( $inv_to['addr2'] ) . '</div>'; } if ( isset( $inv_to['city'] ) ) { $invoice_customer_info_table_html .= '<div>' . esc_html( $inv_to['city'] ) . '</div>'; } if ( isset( $inv_to['postcode'] ) ) { $invoice_customer_info_table_html .= '<div>' . esc_html( $inv_to['postcode'] ) . '</div>'; } // Append custom fields if specified in settings $invoice_customer_info_table_html .= jpcrm_invoicing_generate_customer_custom_fields_lines( $inv_to, $template ); // the abilty to add in extra info to the customer info area. $extra_cust_info = apply_filters( 'zbs_invoice_customer_info_line', '' ); $invoice_customer_info_table_html .= $extra_cust_info; $invoice_customer_info_table_html .= '</div>'; $invoice_customer_info_table_html .= '</div>'; break; } $invoice_customer_info_table_html .= '</div>'; //filter the whole thing if you really want to modify it $invoice_customer_info_table_html = apply_filters( 'zbs_invoice_customer_info_table', $invoice_customer_info_table_html ); return $invoice_customer_info_table_html; } /* * Generates html string to output customer (contact or company) custom field lines for templating * * @param array $customer - a contact|company object * @param string $template - 'pdf', 'notification', or 'portal' * * @return string HTML */ function jpcrm_invoicing_generate_customer_custom_fields_lines( $customer, $template ){ global $zbs; $customer_custom_fields_html = ''; // retrieve custom fields to pass through // contact or company? if ( $customer['objtype'] == ZBS_TYPE_CONTACT ){ $custom_fields_to_include = zeroBSCRM_getSetting( 'contactcustomfields' ); } elseif ( $customer['objtype'] == ZBS_TYPE_COMPANY ){ $custom_fields_to_include = zeroBSCRM_getSetting( 'companycustomfields' ); } else { // no type? ¯\_(ツ)_/¯ return ''; } if ( !empty( $custom_fields_to_include ) ){ // split the csv $custom_fields_to_include = array_map( 'trim', explode( ',', $custom_fields_to_include ) ); // retrieve fields $invoice_custom_fields = $zbs->DAL->getActiveCustomFields( array( 'objtypeid' => $customer['objtype'] ) ); // build custom fields string. // here we immitate what we expect the HTML to be, which will be errorsome if people modify heavily. // for now it's better than no custom fields, let's see if people have issue with this approach. foreach ( $invoice_custom_fields as $field_key => $field_info){ // where user has set the field in settings if ( in_array( $field_key, $custom_fields_to_include ) ){ $custom_field_str = ''; if ( isset( $customer[ $field_key ] ) && $customer[ $field_key ] ){ $custom_field_str = $customer[ $field_key ]; // catch formatted dates if ( isset( $customer[ $field_key . '_cfdate' ] ) ){ $custom_field_str = $customer[ $field_key . '_cfdate' ]; } } // skip empties if ( empty( $custom_field_str ) ) { continue; } switch ( $template ) { case 'pdf': case 'notification': $customer_custom_fields_html .= '<div class="zbs-line-info">' . esc_html( $field_info[1] ) . ': ' . esc_html( $custom_field_str ) . '</div>'; break; case 'portal': $customer_custom_fields_html .= '<div><strong>' . esc_html( $field_info[1] ) . ':</strong> ' . esc_html( $custom_field_str ) . '</div>'; break; } } } } return $customer_custom_fields_html; } /* * Generates html string to output invoice custom field lines for templating * * @param array $invoice - an invoice object * @param string $template - 'pdf', 'notification', or 'portal' * * @return string HTML */ function jpcrm_invoicing_generate_invoice_custom_fields_lines( $invoice, $template ){ global $zbs; $invoice_custom_fields_html = ''; // retrieve custom fields to pass through $custom_fields_to_include = zeroBSCRM_getSetting( 'invcustomfields' ); if ( !empty( $custom_fields_to_include ) ){ // split the csv $custom_fields_to_include = array_map( 'trim', explode( ',', $custom_fields_to_include ) ); // retrieve fields $invoice_custom_fields = $zbs->DAL->getActiveCustomFields( array( 'objtypeid' => ZBS_TYPE_INVOICE ) ); // build custom fields string. // here we immitate what we expect the HTML to be, which will be errorsome if people modify heavily. // for now it's better than no custom fields, let's see if people have issue with this approach. foreach ( $invoice_custom_fields as $field_key => $field_info){ // where user has set the field in settings if ( in_array( $field_key, $custom_fields_to_include ) ){ $custom_field_str = ''; if ( $invoice[ $field_key ] ){ $custom_field_str = $invoice[ $field_key ]; // catch formatted dates if ( isset( $invoice[ $field_key . '_cfdate' ] ) ){ $custom_field_str = $invoice[ $field_key . '_cfdate' ]; } } // skip empties if ( empty( $custom_field_str ) ) { continue; } switch ( $template ) { case 'pdf': case 'notification': $invoice_custom_fields_html .= '<tr class="zbs-top-right-box-line">'; $invoice_custom_fields_html .= ' <td><label for="' . esc_attr( $field_key ) . '">' . esc_html( $field_info[1] ) . ':</label></td>'; $invoice_custom_fields_html .= ' <td style="text-align:right;">' . esc_html( $custom_field_str ) . '</td>'; $invoice_custom_fields_html .= '</tr>'; break; case 'portal': $invoice_custom_fields_html .= '<div><strong>' . esc_html( $field_info[1] ) . ':</strong> ' . esc_html( $custom_field_str ) . '</div>'; break; } } } } return $invoice_custom_fields_html; } // Used to generate specific part of invoice pdf: (Lineitem row in inv table) // phpcs:ignore Squiz.Commenting.FunctionComment.Missing function zeroBSCRM_invoicing_generateInvPart_lineitems( $invlines = array() ) { if ( empty( $invlines ) ) { return ''; } $line_item_html = ''; foreach ( $invlines as $invline ) { $line_item_html .= ' <tr class="jpcrm-invoice-lineitem"> <td class="jpcrm-invoice-lineitem-description"><span class="title">' . esc_html( $invline['title'] ) . '</span><br/><span class="subtitle">' . nl2br( esc_html( $invline['desc'] ) ) . '</span></td> <td class="jpcrm-invoice-lineitem-quantity">' . esc_html( zeroBSCRM_format_quantity( $invline['quantity'] ) ) . '</td> <td class="jpcrm-invoice-lineitem-price">' . esc_html( zeroBSCRM_formatCurrency( $invline['price'] ) ) . '</td> <td class="jpcrm-invoice-lineitem-amount">' . esc_html( zeroBSCRM_formatCurrency( $invline['net'] ) ) . '</td> </tr>'; } return $line_item_html; } // Used to generate specific part of invoice pdf: (pay button) function zeroBSCRM_invoicing_generateInvPart_payButton( $invoice_id = -1, $status = '', $template = 'pdf' ) { // phpcs:ignore Squiz.Commenting.FunctionComment.WrongStyle $potential_pay_button = ''; switch ( $template ) { case 'pdf': $potential_pay_button = ''; break; case 'portal': if ( $status !== 'Paid' ) { // need to add somethere here which stops the below if WooCommerce meta set // so the action below will fire in WooSync, and remove the three filters below // https://codex.wordpress.org/Function_Reference/remove_filter // and then filter itself in. EDIT the remove filter does not seem to remove them below // think they already need to be applied (i.e. this below). The below works but should // think how best to do this for further extension later? // WH: This'll be the ID if woo doesn't return a button (e.g. it's a woo inv so don't show pay buttons) $potential_woo_pay_button_or_inv_id = apply_filters( 'zbs_woo_pay_invoice', $invoice_id ); if ( $potential_woo_pay_button_or_inv_id == $invoice_id ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual $potential_pay_button = apply_filters( 'invpro_pay_online', $invoice_id ); } else { $potential_pay_button = $potential_woo_pay_button_or_inv_id; } if ( $potential_pay_button == $invoice_id ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual $potential_pay_button = ''; } } break; case 'notification': $potential_pay_button = ''; break; } return $potential_pay_button; } // Used to generate specific part of invoice pdf: (table headers) // phpcs:ignore Squiz.Commenting.FunctionComment.Missing function zeroBSCRM_invoicing_generateInvPart_tableHeaders( $zbs_invoice_hours_or_quantity = 1 ) { $table_headers = '<tr>'; $table_headers .= '<th class="jpcrm-invoice-lineitem-description">' . esc_html__( 'Description', 'zero-bs-crm' ) . '</th>'; if ( $zbs_invoice_hours_or_quantity == 1 ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual $table_headers .= '<th class="jpcrm-invoice-lineitem-quantity">' . esc_html__( 'Quantity', 'zero-bs-crm' ) . '</th>'; $table_headers .= '<th class="jpcrm-invoice-lineitem-price">' . esc_html__( 'Price', 'zero-bs-crm' ) . '</th>'; } else { $table_headers .= '<th class="jpcrm-invoice-lineitem-quantity">' . esc_html__( 'Hours', 'zero-bs-crm' ) . '</th>'; $table_headers .= '<th class="jpcrm-invoice-lineitem-price">' . esc_html__( 'Rate', 'zero-bs-crm' ) . '</th>'; } $table_headers .= '<th class="jpcrm-invoice-lineitem-amount">' . esc_html__( 'Amount', 'zero-bs-crm' ) . '</th>'; $table_headers .= '</tr>'; return $table_headers; }
projects/plugins/crm/includes/ZeroBSCRM.MetaBoxes3.Tasks.php
<?php /* ! * Jetpack CRM * https://jetpackcrm.com * V3.0 * * Copyright 2020 Automattic * * Date: 20/02/2019 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) { exit; } /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== Init Func ====================================================== */ function zeroBSCRM_TasksMetaboxSetup() { $zeroBS__Metabox_Task = new zeroBS__Metabox_Task( __FILE__ ); // actions box $zeroBS__Metabox_TaskActions = new zeroBS__Metabox_TaskActions( __FILE__ ); // tags $zeroBS__Metabox_TaskTags = new zeroBS__Metabox_TaskTags( __FILE__ ); } add_action( 'admin_init', 'zeroBSCRM_TasksMetaboxSetup' ); /* ====================================================== / Init Func ====================================================== */ /* ====================================================== Task Metabox ====================================================== */ class zeroBS__Metabox_Task extends zeroBS__Metabox { // this is for catching 'new' task private $newRecordNeedsRedir = false; public function __construct( $plugin_file ) { // set these // DAL3 switched for objType $this->postType = 'zerobs_customer'; $this->objType = 'event'; $this->metaboxID = 'jpcrm-task-edit'; $this->metaboxTitle = __( 'Task Information', 'zero-bs-crm' ); $this->metaboxScreen = 'zbs-add-edit-event-edit'; $this->metaboxArea = 'normal'; $this->metaboxLocation = 'high'; $this->saveOrder = 1; $this->capabilities = array( 'can_hide' => false, // can be hidden 'areas' => array( 'normal' ), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => true, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true, // can be minimised 'can_move' => true, // can be moved ); // call this $this->initMetabox(); } public function html( $task, $metabox ) { // localise ID $task_id = -1; if ( is_array( $task ) && isset( $task['id'] ) ) { $task_id = (int) $task['id']; } // debug echo 'task:<pre>'; print_r(array($task,$metabox)); echo '</pre>'; // PerfTest: zeroBSCRM_performanceTest_startTimer('custmetabox-dataget'); #} Rather than reload all the time :) global $zbsTaskEditing; // PerfTest: zeroBSCRM_performanceTest_finishTimer('custmetabox-dataget'); // PerfTest: zeroBSCRM_performanceTest_startTimer('custmetabox-draw'); ?> <script type="text/javascript">var zbscrmjs_secToken = '<?php echo esc_js( wp_create_nonce( 'zbscrmjs-ajax-nonce' ) ); ?>';</script> <?php #} Pass this if it's a new customer (for internal automator) - note added this above with DEFINE for simpler. if ( gettype( $task ) != 'array' ) { echo '<input type="hidden" name="zbscrm_newevent" value="1" />'; } // MS HTML out.. // from the function lower down in this file. echo zeroBSCRM_task_addEdit( $task_id ); // PerfTest: zeroBSCRM_performanceTest_finishTimer('custmetabox-draw'); } public function save_data( $task_id, $task ) { if ( ! defined( 'ZBS_OBJ_SAVED' ) ) { // debug if (get_current_user_id() == 12) echo 'FIRING<br>'; define( 'ZBS_OBJ_SAVED', 1 ); // DAL3.0+ global $zbs; // check this if ( empty( $task_id ) || $task_id < 1 ) { $task_id = -1; } // DAL3 way: $autoGenAutonumbers = true; // generate if not set :) $task = zeroBS_buildObjArr( $_POST, array(), 'zbse_', '', false, ZBS_TYPE_TASK, $autoGenAutonumbers ); // catch calendar and portal options (show_on_portal not needed) $task['show_on_cal'] = -1; if ( isset( $_POST['zbse_show_on_cal'] ) ) { $task['show_on_cal'] = 1; } // Use the tag-class function to retrieve any tags so we can add inline. // Save tags against objid $task['tags'] = zeroBSCRM_tags_retrieveFromPostBag( true, ZBS_TYPE_TASK ); // because we deal with non-model datetime stamps here, we have to process separate to buildObjArr: // jpcrm_datetime_post_keys_to_uts() sanitises POST data $task_start = jpcrm_datetime_post_keys_to_uts( 'jpcrm_start' ); $task_end = jpcrm_datetime_post_keys_to_uts( 'jpcrm_end' ); // if unable to use task start input, set to current time if ( ! $task_start ) { // start +1 hour from now $task_start = time() + 3600; // round to 15 minutes $task_start -= $task_start % 900; } if ( ! $task_end || $task_end < $task_start ) { // set to task start time + 1 hour if end is not set or is before start $task_end = $task_start + 3600; } $task['start'] = $task_start; $task['end'] = $task_end; // obj links: $task['contacts'] = array(); if ( isset( $_POST['zbse_customer'] ) ) { $task['contacts'][] = (int) sanitize_text_field( $_POST['zbse_customer'] ); } $task['companies'] = array(); if ( isset( $_POST['zbse_company'] ) ) { $task['companies'][] = (int) sanitize_text_field( $_POST['zbse_company'] ); } // completeness: $task['complete'] = -1; if ( isset( $_POST['zbs-task-complete'] ) ) { $task['complete'] = (int) sanitize_text_field( $_POST['zbs-task-complete'] ); } $zbs->DAL->events->setEventCompleteness( $task_id, $task['complete'] ); // ownership also passed via post here. $owner = -1; if ( isset( $_POST['zbse_owner'] ) ) { // this could do with some CHECK to say "can this user assign to this (potentially other) user" $owner = (int) sanitize_text_field( $_POST['zbse_owner'] ); } // get old-style notify -> reminders $task_reminders = array(); $jpcrm_task_notify = false; if ( isset( $_POST['zbs_remind_task_24'] ) ) { $jpcrm_task_notify = (int) sanitize_text_field( $_POST['zbs_remind_task_24'] ); } if ( $jpcrm_task_notify > 0 ) { // this was only ever 0 or 24 if ( $jpcrm_task_notify == 24 ) { $task_reminders[] = array( 'remind_at' => -86400, 'sent' => -1, ); } } $task['reminders'] = $task_reminders; // echo 'Task owned by '.$owner.':<pre>'.print_r($task,1).'</pre>'; exit(); // add/update $addUpdateReturn = $zbs->DAL->events->addUpdateEvent( array( 'id' => $task_id, 'owner' => $owner, 'data' => $task, 'limitedFields' => -1, ) ); // Note: For NEW objs, we make sure a global is set here, that other update funcs can catch // ... so it's essential this one runs first! // this is managed in the metabox Class :) if ( $task_id == -1 && ! empty( $addUpdateReturn ) && $addUpdateReturn != -1 ) { $task_id = $addUpdateReturn; global $zbsJustInsertedMetaboxID; $zbsJustInsertedMetaboxID = $task_id; // set this so it redirs $this->newRecordNeedsRedir = true; } // success? if ( $addUpdateReturn != -1 && $addUpdateReturn > 0 ) { // Update Msg // this adds an update message which'll go out ahead of any content // This adds to metabox: $this->updateMessages['update'] = zeroBSCRM_UI2_messageHTML('info olive mini zbs-not-urgent',__('Contact Updated',"zero-bs-crm"),'','address book outline','contactUpdated'); // This adds to edit page $this->updateMessage(); // catch any non-critical messages $nonCriticalMessages = $zbs->DAL->getErrors( ZBS_TYPE_TASK ); if ( is_array( $nonCriticalMessages ) && count( $nonCriticalMessages ) > 0 ) { $this->dalNoticeMessage( $nonCriticalMessages ); } } else { // fail somehow $failMessages = $zbs->DAL->getErrors( ZBS_TYPE_TASK ); // show msg (retrieved from DAL err stack) if ( is_array( $failMessages ) && count( $failMessages ) > 0 ) { $this->dalErrorMessage( $failMessages ); } else { $this->dalErrorMessage( array( __( 'Insert/Update Failed with general error', 'zero-bs-crm' ) ) ); } // pass the pre-fill: global $zbsObjDataPrefill; $zbsObjDataPrefill = $task; } } return $task; } // This catches 'new' contacts + redirs to right url public function post_save_data( $objID, $obj ) { if ( $this->newRecordNeedsRedir ) { global $zbsJustInsertedMetaboxID; if ( ! empty( $zbsJustInsertedMetaboxID ) && $zbsJustInsertedMetaboxID > 0 ) { // redir wp_redirect( jpcrm_esc_link( 'edit', $zbsJustInsertedMetaboxID, $this->objType ) ); exit; } } } public function updateMessage() { global $zbs; // zbs-not-urgent means it'll auto hide after 1.5s // genericified from DAL3.0 $msg = zeroBSCRM_UI2_messageHTML( 'info olive mini zbs-not-urgent', $zbs->DAL->typeStr( $zbs->DAL->objTypeKey( $this->objType ) ) . ' ' . __( 'Updated', 'zero-bs-crm' ), '', 'address book outline', 'contactUpdated' ); $zbs->pageMessages[] = $msg; } } /* ====================================================== / Task Metabox ====================================================== */ /* ====================================================== Task Actions Metabox ====================================================== */ class zeroBS__Metabox_TaskActions extends zeroBS__Metabox { public function __construct( $plugin_file ) { // set these $this->objType = 'event'; $this->metaboxID = 'zerobs-event-actions'; $this->metaboxTitle = __( 'Task Actions', 'zero-bs-crm' ); // will be headless anyhow $this->headless = true; $this->metaboxScreen = 'zbs-add-edit-event-edit'; $this->metaboxArea = 'side'; $this->metaboxLocation = 'high'; $this->saveOrder = 1; $this->capabilities = array( 'can_hide' => false, // can be hidden 'areas' => array( 'high' ), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => true, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true, // can be minimised 'can_move' => true, // can be moved ); // call this $this->initMetabox(); } public function html( $task, $metabox ) { ?> <div class="zbs-generic-save-wrap"> <div class="ui medium dividing header"><i class="save icon"></i> <?php esc_html_e( 'Task Actions', 'zero-bs-crm' ); ?></div> <?php // localise ID & content $task_id = -1; if ( is_array( $task ) && isset( $task['id'] ) ) { $task_id = (int) $task['id']; } if ( $task_id > 0 ) { ?> <div class="zbs-task-actions-bottom zbs-objedit-actions-bottom"> <button class="ui button black" type="button" id="zbs-edit-save"><?php esc_html_e( 'Update', 'zero-bs-crm' ); ?> <?php esc_html_e( 'Task', 'zero-bs-crm' ); ?></button> <?php // delete? // for now just check if can modify, later better, granular perms. if ( zeroBSCRM_perms_tasks() ) { ?> <div id="zbs-task-actions-delete" class="zbs-objedit-actions-delete"> <a class="submitdelete deletion" href="<?php echo jpcrm_esc_link( 'delete', $task_id, 'event' ); ?>"><?php esc_html_e( 'Delete Permanently', 'zero-bs-crm' ); ?></a> </div> <?php } // can delete ?> <div class='clear'></div> </div> <?php } else { // NEW Task ?> <button class="ui button black" type="button" id="zbs-edit-save"><?php esc_html_e( 'Save', 'zero-bs-crm' ); ?> <?php esc_html_e( 'Task', 'zero-bs-crm' ); ?></button> <?php } ?> </div> <?php // / .zbs-generic-save-wrap } // html // saved via main metabox } /* ====================================================== / Tasks Actions Metabox ====================================================== */ /* ====================================================== Create Tags Box ====================================================== */ class zeroBS__Metabox_TaskTags extends zeroBS__Metabox_Tags { public function __construct( $plugin_file ) { $this->objTypeID = ZBS_TYPE_TASK; // DAL3 switched for objType $this->postType = 'zerobs_customer'; $this->objType = 'event'; $this->metaboxID = 'zerobs-event-tags'; $this->metaboxTitle = __( 'Task Tags', 'zero-bs-crm' ); $this->metaboxScreen = 'zbs-add-edit-event-edit'; //'zerobs_edit_contact'; // we can use anything here as is now using our func $this->metaboxArea = 'side'; $this->metaboxLocation = 'low'; $this->showSuggestions = true; $this->capabilities = array( 'can_hide' => true, // can be hidden 'areas' => array( 'side' ), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => false, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true, // can be minimised ); // call this $this->initMetabox(); } // html + save dealt with by parent class :) } /* ====================================================== / Create Tags Box ====================================================== */ /* ====================================================== Task UI code - outputting the HTML for the task ====================================================== */ function zeroBSCRM_task_addEdit( $taskID = -1 ) { global $zbs; $taskObject = $zbs->DAL->events->getEvent( $taskID, array( 'withReminders' => true, 'withCustomFields' => true, 'withTags' => false, 'withOwner' => false, ) ); // catch fresh/new? if ( ! is_array( $taskObject ) ) { $taskObject = array(); } /* $uid = get_current_user_id(); $zbsThisOwner = zeroBS_getOwner($taskID,true,'zerobs_event'); ... this'd just be $taskObject['owner'] 3.0 + :) if($uid != $zbsThisOwner['ID']){ $html = "<div class='ui segment'>"; $html .= __("You cannot edit this task. It is not your task. Ask the task owner to modify.", 'zero-bs-crm'); }else{ */ if ( $taskID > 0 ) { $html = "<div id='task-" . $taskID . "' class='jpcrm-task-editor-wrap'>"; } else { $html = "<div id='task-0' class='jpcrm-task-editor-wrap'>"; } $html .= zeroBSCRM_task_ui_clear(); $title = ''; if ( is_array( $taskObject ) && isset( $taskObject['title'] ) ) { $title = $taskObject['title']; } $placeholder = __( 'Task Name...', 'zero-bs-crm' ); if ( is_array( $taskObject ) && isset( $taskObject['placeholder'] ) ) { $placeholder = $taskObject['placeholder']; } // WH: Not sure placeholder is really req 3.0? What was that even? (It's not a field we've added to the data model) $html .= "<input id='zbs-task-title' name='zbse_title' type='text' value='" . esc_attr( $title ) . "' placeholder='" . $placeholder . "' />"; $html .= zeroBSCRM_task_ui_mark_complete( $taskObject, $taskID ); $html .= zeroBSCRM_task_ui_clear(); $html .= jpcrm_task_ui_daterange( $taskObject ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $html .= zeroBSCRM_task_ui_clear(); $html .= zeroBSCRM_task_ui_assignment( $taskObject, $taskID ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $html .= zeroBSCRM_task_ui_clear(); $html .= zeroBSCRM_task_ui_description( $taskObject ); $html .= zeroBSCRM_task_ui_clear(); $html .= zeroBSCRM_task_ui_reminders( $taskObject, $taskID ); $html .= zeroBSCRM_task_ui_clear(); // NOTE show_on_portal is available and could clone this v3.0+ $html .= zeroBSCRM_task_ui_showOnCalendar( $taskObject, $taskID ); $html .= zeroBSCRM_task_ui_clear(); if ( class_exists( 'ZeroBSCRM_ClientPortalPro' ) ) { $html .= zeroBSCRM_task_ui_showOnPortal( $taskObject ); } $html .= zeroBSCRM_task_ui_clear(); $html .= zeroBSCRM_task_ui_for( $taskObject, $taskID ); $html .= zeroBSCRM_task_ui_clear(); $html .= zeroBSCRM_task_ui_for_co( $taskObject ); $html .= '</div>'; return $html; } function zeroBSCRM_task_ui_clear() { return '<div class="clear zbs-task-clear"></div>'; } #} Assign to CRM user UI function zeroBSCRM_task_ui_assignment( $taskObject = array(), $taskID = -1 ) { global $zbs; $current_task_user_id = -1; if ( array_key_exists( 'owner', $taskObject ) ) { $current_task_user_id = $taskObject['owner']; } $html = ''; if ( $current_task_user_id === '' || $current_task_user_id <= 0 ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $html .= "<div class='no-owner'><i class='ui icon user circle zbs-unassigned'></i>"; } else { $owner_info = get_userdata( $current_task_user_id ); $display_name = $owner_info->data->display_name; $ava_args = array( 'class' => 'rounded-circle', ); $avatar = jpcrm_get_avatar( $current_task_user_id, 30, '', $display_name, $ava_args ); $html .= "<div class='no-owner'>" . $avatar . "<div class='dn'></div>"; } $uid = get_current_user_id(); $linked_cal = $zbs->DAL->meta( ZBS_TYPE_TASK, $taskID, $key = 'zbs_outlook_id', false ); // false = default here if ( $uid != $current_task_user_id ) { //then it is LOCKED and cannot be changed to another owner? } // get potential owners $jpcrm_tasks_users = zeroBS_getPossibleTaskOwners(); $html .= '<div class="owner-select" style="margin-left:30px;"><select class="form-controlx" id="zerobscrm-owner" name="zbse_owner" style="width:80%">'; $html .= '<option value="-1">' . __( 'None', 'zero-bs-crm' ) . '</option>'; if ( count( $jpcrm_tasks_users ) > 0 ) { foreach ( $jpcrm_tasks_users as $possOwner ) { $html .= '<option value="' . $possOwner->ID . '"'; if ( $possOwner->ID == $current_task_user_id ) { $html .= ' selected="selected"'; } $html .= '>' . esc_html( $possOwner->display_name ) . '</option>'; } } $html .= '</select></div></div>'; return $html; } function zeroBSCRM_task_ui_mark_complete( $taskObject = array(), $taskID = -1 ) { $html = "<div class='mark-complete-task'>"; if ( ! array_key_exists( 'complete', $taskObject ) ) { $taskObject['complete'] = 0; } if ( $taskObject['complete'] == 1 ) { $html .= "<div id='task-mark-incomplete' class='task-comp incomplete'><button class='ui button black' data-taskid='" . $taskID . "'><i class='ui icon check white'></i>" . __( 'Completed', 'zero-bs-crm' ) . '</button></div>'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $complete = "<input type='hidden' id='zbs-task-complete' value = '1' name = 'zbs-task-complete'/>"; } else { $html .= sprintf( '<div id="task-mark-complete" class="task-comp complete"><button class="ui button black button-primary button-large" data-taskid="%s"><i class="ui icon check"></i>%s</button></div>', $taskID, // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase __( 'Mark Complete', 'zero-bs-crm' ) ); $complete = "<input type='hidden' id='zbs-task-complete' value = '-1' name = 'zbs-task-complete'/>"; } $html .= '</div>'; $html .= $complete; return $html; } #} CRM company / contact assignment #} assign to CRM user UI function zeroBSCRM_task_ui_for( $taskObject = array() ) { global $zbs; $html = "<div class='no-contact zbs-task-for-who'><div class='zbs-task-for-help'><i class='ui icon users'></i> " . __( 'Contact', 'zero-bs-crm' ) . '</div>'; //need UI for selecting who the task is for (company, then contaxt) $custName = ''; $custID = ''; if ( isset( $taskObject['contact'] ) && is_array( $taskObject['contact'] ) ) { $taskContact = $taskObject['contact']; // for now this needs a 0 offset as has potential for multi-contact if ( isset( $taskContact[0] ) && is_array( $taskContact[0] ) ) { $taskContact = $taskContact[0]; } if ( isset( $taskContact['id'] ) ) { $custID = $taskContact['id']; } $custName = $zbs->DAL->contacts->getContactNameWithFallback( $custID ); } elseif ( isset( $_GET['zbsprefillcust'] ) && ! empty( $_GET['zbsprefillcust'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended $custID = (int) $_GET['zbsprefillcust']; $custName = $zbs->DAL->contacts->getContactNameWithFallback( $custID ); } #} Output $html .= '<div class="zbs-task-for">' . zeroBSCRM_CustomerTypeList( 'jpcrm_tasks_setContact', $custName, true, 'jpcrm_tasks_changeContact' ) . '</div>'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $html .= '<input type="hidden" name="zbse_customer" id="zbse_customer" value="' . ( $custName ? $custID : '' ) . '" />'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $html .= '<div class="clear"></div></div>'; return $html; } function zeroBSCRM_task_ui_for_co( $taskObject = array() ) { global $zbs; $html = ''; if ( zeroBSCRM_getSetting( 'companylevelcustomers' ) == '1' ) { $html .= "<div class='no-contact zbs-task-for-who'><div class='zbs-task-for-help'><i class='ui icon building outline'></i> " . jpcrm_label_company() . '</div>'; //need UI for selecting who the task is for (company, then contact) $co_name = ''; $co_id = ''; if ( isset( $taskObject['company'] ) && is_array( $taskObject['company'] ) ) { $task_company = $taskObject['company']; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // for now this needs a 0 offset as has potential for multi-contact if ( isset( $task_company[0] ) && is_array( $task_company[0] ) ) { $task_company = $task_company[0]; } if ( isset( $task_company['id'] ) ) { $co_id = $task_company['id']; } if ( isset( $task_company['name'] ) ) { $co_name = $task_company['name']; } } elseif ( isset( $_GET['zbsprefillco'] ) && ! empty( $_GET['zbsprefillco'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended $co_id = (int) $_GET['zbsprefillco']; // phpcs:ignore WordPress.Security.NonceVerification.Recommended $co_name = $zbs->DAL->companies->getCompanyNameEtc( $co_id ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase } #} Output $html .= '<div class="zbs-task-for-company">' . zeroBSCRM_CompanyTypeList( 'jpcrm_tasks_setCompany', $co_name, true, 'jpcrm_tasks_changeCompany' ) . '</div>'; $html .= '<input type="hidden" name="zbse_company" id="zbse_company" value="' . ( $co_name ? $co_id : '' ) . '" />'; $html .= '<div class="clear"></div></div>'; } return $html; } /** * Returns a string for disabling browser autocomplete * Ideally we'd just use "off", but support is not complete: https://caniuse.com/input-autocomplete-onoff * * @param obj $task_object Object containing task details. * * @return string $html Contains the start/end date and time inputs. */ function jpcrm_task_ui_daterange( $task_object = array() ) { if ( ! isset( $task_object['start'] ) ) { // no task start defined yet, so use some defaults // start +1 hour from now $task_start = time() + 3600; // round to 15 minutes $task_start -= $task_start % 900; // end +1 hour from start $task_end = $task_start + 3600; } else { $task_start = $task_object['start']; $task_end = $task_object['end']; } // For now, hack together a table so the date and time inputs line up nicely. Eventually we'll want to rework the entire UI of this page. $html = ' <table style="margin-left:20px;"> <tr class="wh-large"> <td><label>' . esc_html__( 'Start time', 'zero-bs-crm' ) . ':</label>&nbsp;</td> <td> <input type="date" name="jpcrm_start_datepart" value="' . esc_attr( jpcrm_uts_to_date_str( $task_start, 'Y-m-d' ) ) . '" autocomplete="' . esc_attr( jpcrm_disable_browser_autocomplete() ) . '" /> @ <input type="time" name="jpcrm_start_timepart" value="' . esc_attr( jpcrm_uts_to_date_str( $task_start, 'H:i' ) ) . '" autocomplete="' . esc_attr( jpcrm_disable_browser_autocomplete() ) . '" /> </td> </tr> <tr class="wh-large"> <td><label>' . esc_html__( 'End time', 'zero-bs-crm' ) . ':</label>&nbsp;</td> <td> <input type="date" name="jpcrm_end_datepart" value="' . esc_attr( jpcrm_uts_to_date_str( $task_end, 'Y-m-d' ) ) . '" autocomplete="' . esc_attr( jpcrm_disable_browser_autocomplete() ) . '" /> @ <input type="time" name="jpcrm_end_timepart" value="' . esc_attr( jpcrm_uts_to_date_str( $task_end, 'H:i' ) ) . '" autocomplete="' . esc_attr( jpcrm_disable_browser_autocomplete() ) . '" /> </td> </tr> </table>'; return $html; } #} UI Reminders function zeroBSCRM_task_ui_reminders( $taskObject = array(), $taskID = -1 ) { $show = false; // v3.0 + this is differently stored: //if (isset($taskObject['notify_crm'])) $show = $taskObject['notify_crm']; if ( isset( $taskObject['reminders'] ) && is_array( $taskObject['reminders'] ) ) { // eventually diff time reminders will be in this array, for v3.0 we only have 24h reminders foreach ( $taskObject['reminders'] as $reminder ) { if ( is_array( $reminder ) && isset( $reminder['remind_at'] ) ) { // catch 24 if ( $reminder['remind_at'] == -86400 ) { $show = true; } } } } else { // new, set default: $show = true; } $html = "<div class='remind_task'>"; $html .= '<div>'; // add admin cog (settings) for task notification template if ( zeroBSCRM_isZBSAdminOrAdmin() ) { $html .= sprintf( '<a href="%s" class="button button-primary button-large" style="background-color:black;border-color:black;" title="%s" target="_blank"><i class="cogs icon"></i></a>', esc_url_raw( jpcrm_esc_link( 'zbs-email-templates' ) . '&zbs_template_id=' . ZBSEMAIL_TASK_NOTIFICATION ), __( 'Admin: Notification Settings', 'zero-bs-crm' ) ); } $html .= '<input name="zbs_remind_task_24" id="zbs_remind_task_24" type="checkbox" value="24"'; if ( $show ) { $html .= ' checked="checked"'; } $html .= "/><label for='zbs_remind_task_24'>" . __( 'Remind CRM member 24 hours before', 'zero-bs-crm' ) . '</label></div>'; // $html .= "<a class='ui label blue' href='". admin_url('admin.php?page=zbs-reminders') ."' target='_blank' style='margin-top: 0.2em;margin-right: 0.3em;'>" .__('Add more reminders', 'zero-bs-crm') . "</a>"; $html .= '</div>'; #} Better reminders in Calendar Pro :-) $html = apply_filters( 'zbs_task_reminders', $html ); return $html; } // NOTE show_on_portal is available and could clone this v3.0+ function zeroBSCRM_task_ui_showOnCalendar( $taskObject = array(), $taskID = -1 ) { global $zbs; // show? $show = false; if ( isset( $taskObject['show_on_cal'] ) ) { if ( $taskObject['show_on_cal'] == 1 ) { $show = true; } } else { // new, set default: $show = true; } $linked_cal = $zbs->DAL->meta( ZBS_TYPE_TASK, $taskID, $key = 'zbs_outlook_id', false ); // false = default here $html = "<div class='show-on-calendar'>"; if ( $linked_cal != '' ) { $html .= '<div class="zbs-hide"><input name="zbse_show_on_cal" id="zbse_show_on_cal" type="checkbox" value="1"'; if ( $show ) { $html .= ' checked="checked"'; } $html .= "/></div><div class='outlook-event'>" . __( 'Linked to Online Calendar (will always show on CRM Calendar)', 'zero-bs-crm' ) . '</div>'; } else { $html .= '<div><input name="zbse_show_on_cal" id="zbse_show_on_cal" type="checkbox" value="1"'; if ( $show ) { $html .= ' checked="checked"'; } $html .= "/><label for='zbse_show_on_cal'>" . __( 'Show on Calendar', 'zero-bs-crm' ) . '</label></div></div>'; } #} anything else we may want to filter with. $html = apply_filters( 'zbs_calendar_add_to_calendar', $html ); return $html; } function zeroBSCRM_task_ui_showOnPortal( $taskObject = array() ) { $show = true; if ( isset( $taskObject['show_on_portal'] ) ) { $show = $taskObject['show_on_portal']; } $html = "<div class='show-on-calendar'>"; $html .= '<div><input name="zbse_show_on_portal" id="zbse_show_on_portal" type="checkbox" value="1"'; if ( $show ) { $html .= ' checked="checked"'; } $html .= "/><label for='zbse_show_on_portal'>" . __( 'Show on Client Portal (if assigned to contact)', 'zero-bs-crm' ) . '</label></div>'; $html .= '</div>'; return $html; } function zeroBSCRM_task_ui_comments( $pID = -1 ) { $args = array(); $html = comment_form( $args, $pID ); return $html; } function zeroBSCRM_task_ui_description( $taskObject = array() ) { $html = "<div class='clear'></div><div class='zbs-task-desc'><textarea id='zbse_desc' name='zbse_desc' placeholder='" . __( 'Task Description...', 'zero-bs-crm' ) . "'>"; if ( isset( $taskObject ) && isset( $taskObject['desc'] ) ) { $html .= $taskObject['desc']; } $html .= '</textarea></div>'; return $html; } /* ====================================================== / Task UI code ====================================================== */
projects/plugins/crm/includes/ZeroBSCRM.DAL3.Helpers.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V1.20 * * Copyright 2020 Automattic * * Date: 01/11/16 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* This file contains functions from DAL1 & DAL2 which have been translated into DAL2.5 This, along with DAL2, provide backward compatability with all other extensions etc. - Note: First half of this file (customer funcs etc.) is the same as DAL2.LegacySupport.php first half, but going forwards, we only maintain this file. Leaving peeps in a few states (until migrated): 1) Still on DAL1, using DAL.LegacySuport.php -> Requires Migration -> 2) Still on DAL2, using DAL2.PHP, DAL.LegacySupport.php & DAL2.LegacySupport.php, & loading DAL objs but not using (except for contacts, logs, segments) -> Requires Migration -> 3) Up to date fully, using DAL2.Helpers.php & fully using DAL objs. .. fresh installs will silently migrate up to 3), older ones will manually have to run the wizs */ // ==================================================================================================================================== // ==================================================================================================================================== // ==================== DAL 2.0 FUNCS ================================================================================================= // ==================================================================================================================================== // ==================================================================================================================================== /* ====================================================== Unchanged DAL2->3 (Mostly customer/contact + log relatead) ====================================================== */ function zeroBS_getCustomer($cID=-1,$withInvoices=false,$withQuotes=false,$withTransactions=false){ global $zbs; return $zbs->DAL->contacts->getContact($cID,array( // with what? 'withCustomFields' => true, 'withQuotes' => $withQuotes, 'withInvoices' => $withInvoices, 'withTransactions' => $withTransactions, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT) )); } function zeroBS_getCustomerName($contactID=-1){ global $zbs; return $zbs->DAL->contacts->getContactFullNameEtc($contactID,array(),array( 'incFirstLineAddr' => true, 'incID' => true )); } function zeroBS_customerName($contactID='',$contactArr=false,$incFirstLineAddr=true,$incID=true){ global $zbs; return $zbs->DAL->contacts->getContactFullNameEtc($contactID,$contactArr,array( 'incFirstLineAddr' => $incFirstLineAddr, 'incID' => $incID )); } function zeroBS_getCustomerNameShort($contactID=-1){ global $zbs; return $zbs->DAL->contacts->getContactFullNameEtc($contactID,array(),array( 'incFirstLineAddr' => false, 'incID' => false )); } function zeroBS_customerAddr($contactID='',$contactArr=array(),$addrFormat = 'short',$delimiter= ', '){ global $zbs; return $zbs->DAL->contacts->getContactAddress($contactID,array(),array( 'addrFormat' => $addrFormat, 'delimiter' => $delimiter )); } #} Returns a str of address, ($third param = 'short','full') #} Pass an ID OR a customerMeta array (saves loading ;) - in fact doesn't even work with ID yet... lol) function zeroBS_customerSecondAddr($contactID='',$contactArr=array(),$addrFormat = 'short',$delimiter= ', '){ global $zbs; return $zbs->DAL->contacts->getContact2ndAddress($contactID,array(),array( 'addrFormat' => $addrFormat, 'delimiter' => $delimiter )); } function zeroBS_customerEmail($contactID='',$contactArr=false){ global $zbs; return $zbs->DAL->contacts->getContactEmail($contactID); } /** * Retrieves all emails againast a contact * * @var int contactID */ function zeroBS_customerEmails($contactID=''){ global $zbs; return $zbs->DAL->contacts->getContactEmails($contactID); } function zeroBS_customerMobile($contactID='',$contactArr=false){ global $zbs; return $zbs->DAL->contacts->getContactMobile($contactID); } function zeroBS_customerAvatar($contactID='',$contactArr=false){ global $zbs; return $zbs->DAL->contacts->getContactAvatar($contactID); } function zeroBS_customerAvatarHTML($contactID='',$contactArr=false,$size=100,$extraClasses=''){ global $zbs; return $zbs->DAL->contacts->getContactAvatarHTML($contactID,$size,$extraClasses); } function zeroBS_customerCountByStatus($status=''){ global $zbs; return $zbs->DAL->contacts->getContactCount(array( 'withStatus' => $status, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); } function zeroBS_customerCount(){ global $zbs; return $zbs->DAL->contacts->getContactCount(array('ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); } #} Retrieves company post id if associated with customer // note 2.5+ can have multiple co's, but this'll only return first ID, need to move away from this function zeroBS_getCustomerCompanyID($cID=-1){ global $zbs; $coArr = $zbs->DAL->contacts->getContactCompanies($cID); if (is_array($coArr) && count($coArr) > 0) return $coArr[0]['id']; return false; } #} sets company id associated with customer (note this'll override any existing val) // note 2.5+ can have multiple co's, but this'll only add first ID, need to move away from this function zeroBS_setCustomerCompanyID($cID=-1,$coID=-1){ global $zbs; if (!empty($cID) && !empty($coID)) { return $zbs->DAL->contacts->addUpdateContactCompanies(array( 'id' => $cID, 'companyIDs' => array($coID))); } return false; } function zbsCRM_addUpdateCustomerCompany($customerID=-1,$companyID=-1){ global $zbs; if (!empty($customerID) && !empty($companyID)) { return $zbs->DAL->contacts->addUpdateContactCompanies(array( 'id' => $customerID, 'companyIDs' => array($companyID))); } return false; } function zeroBS_getCustomerCount($companyID=false){ global $zbs; if (!empty($companyID)){ return $zbs->DAL->contacts->getContactCount(array('inCompany' => $companyID,'ignoreowner'=>true)); } else { return $zbs->DAL->contacts->getContactCount(array('ignoreowner'=>true)); } return 0; } #} Retrieves wp id for a customer function zeroBS_getCustomerWPID($cID=-1){ global $zbs; return $zbs->DAL->contacts->getContactWPID($cID); } #} Retrieves wp id for a customer function zeroBS_getCustomerIDFromWPID($wpID=-1){ global $zbs; return $zbs->DAL->contacts->getContact(-1,array( 'WPID'=>$wpID, 'onlyID'=>1, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); } #} Sets a WP id against a customer function zeroBS_setCustomerWPID($cID=-1,$wpID=-1){ global $zbs; return $zbs->DAL->contacts->addUpdateContactWPID(array('id'=>$cID,'WPID'=>$wpID)); } function zeroBSCRM_getCustomerTags($hide_empty=false){ global $zbs; return $zbs->DAL->getTagsForObjType(array( 'objtypeid'=>ZBS_TYPE_CONTACT, 'excludeEmpty'=>$hide_empty, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); } // either or function zeroBSCRM_setContactTags($cID=-1,$tags=array(),$tagIDs=array(),$mode='replace'){ if ($cID > 0){ $args = array( 'id' => $cID, 'mode' => $mode ); // got tags? if ( is_array( $tags ) && ! empty( $tags ) ) { $args['tags'] = $tags; } elseif ( is_array( $tagIDs ) && ! empty( $tagIDs ) ) { $args['tagIDs'] = $tagIDs; } else { return false; } global $zbs; return $zbs->DAL->contacts->addUpdateContactTags($args); } return false; } function zeroBSCRM_getContactTagsArr($hide_empty=true){ global $zbs; return $zbs->DAL->getTagsForObjType(array( 'objtypeid'=>ZBS_TYPE_CONTACT, 'excludeEmpty'=>$hide_empty, 'withCount' => true, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); } function zeroBS_getCustomerIcoHTML($cID=-1,$additionalClasses=''){ $thumbHTML = '<i class="fa fa-user" aria-hidden="true"></i>'; global $zbs; $thumbURL = $zbs->DAL->contacts->getContactAvatarURL($cID); if (!empty($thumbURL)) { $thumbHTML = '<img src="'.$thumb_url.'" alt="" />'; } return '<div class="zbs-co-img '.$additionalClasses.'">'.$thumbHTML.'</div>'; } function zeroBS_getCustomerIDWithEmail($custEmail=''){ /** * @var $custEmail the customer email you want to check if a contact exists for * * @return returns return $potentialRes->ID from $zbs->DAL->contacts->getContact().. * */ global $zbs; return $zbs->DAL->contacts->getContact(-1,array( 'email'=>$custEmail, 'onlyID'=>true, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); } function zeroBS_searchCustomers($args=array(),$withMoneyData=false){ // here I've shoehorned old into new, // NOTE: // this WONT return same exact fields $args['ignoreowner'] = zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT); if ($withMoneyData){ $args['withInvoices'] = true; $args['withTransactions'] = true; } global $zbs; return $zbs->DAL->contacts->getContacts($args); } /** * Enables or disables the client portal access for a contact, by ID. * * @param int $contact_id The id of the CRM Contact to be enabled or disabled. * @param string $enable_or_disable String indicating if the selected contact should be enabled or disabled. Use 'disable' to disable, otherwise the contact will be enabled. * * @return bool True in case of success, false otherwise. */ function zeroBSCRM_customerPortalDisableEnable( $contact_id = -1, $enable_or_disable = 'disable' ) { global $zbs; if ( zeroBSCRM_permsCustomers() && ! empty( $contact_id ) ) { // Verify this user can be changed. // Has to have singular role of `zerobs_customer`. This helps to avoid users changing each others accounts via crm. $wp_user_id = zeroBSCRM_getClientPortalUserID( $contact_id ); $user_object = get_userdata( $wp_user_id ); if ( jpcrm_role_check( $user_object, array(), array(), array( 'zerobs_customer' ) ) ) { if ( $enable_or_disable === 'disable' ) { return $zbs->DAL->updateMeta( ZBS_TYPE_CONTACT, $contact_id, 'portal_disabled', true ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase } else { return $zbs->DAL->updateMeta( ZBS_TYPE_CONTACT, $contact_id, 'portal_disabled', false ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase } } } return false; } /* * Resets the password for client portal access for a contact, by ID */ function zeroBSCRM_customerPortalPWReset( $contact_id=-1 ) { global $zbs; if ( zeroBSCRM_permsCustomers() && !empty( $contact_id ) ) { $wp_user_id = zeroBS_getCustomerWPID( $contact_id ); $contact = $zbs->DAL->contacts->getContact( $contact_id ); $contact_email = $contact['email']; $user_object = get_userdata( $contact_email ); if ( $wp_user_id > 0 && !empty( $contact_email ) ) { // Verify this user can be changed // (Has to have singular role of `zerobs_customer`. This helps to avoid users resetting each others passwords via crm) if ( jpcrm_role_check( $user_object, array(), array(), array( 'zerobs_customer' ) ) ) { return false; } // generate new pw $new_password = wp_generate_password( 12, false ); // update wp_set_password( $new_password, $wp_user_id ); // email? // check if the email is active.. $active = zeroBSCRM_get_email_status( ZBSEMAIL_CLIENTPORTALPWREST ); if ( $active ) { // send welcome email (tracking will now be dealt with by zeroBSCRM_mailDelivery_sendMessage) // ========================================================================================== // =================================== MAIL SENDING ========================================= // generate html $emailHTML = zeroBSCRM_Portal_generatePWresetNotificationHTML( $new_password, true, $contact ); // build send array $mailArray = array( 'toEmail' => $contact_email, 'toName' => '', 'subject' => zeroBSCRM_mailTemplate_getSubject(ZBSEMAIL_CLIENTPORTALPWREST), 'headers' => zeroBSCRM_mailTemplate_getHeaders(ZBSEMAIL_CLIENTPORTALPWREST), 'body' => $emailHTML, 'textbody' => '', 'options' => array( 'html' => 1 ), 'tracking' => array( // tracking :D (auto-inserted pixel + saved in history db) 'emailTypeID' => ZBSEMAIL_CLIENTPORTALPWREST, 'targetObjID' => $contact_id, 'senderWPID' => -10, 'associatedObjID' => -1, // none ), ); // Sends email, including tracking, via setting stored route out, (or default if none) // and logs trcking :) // discern del method $mailDeliveryMethod = zeroBSCRM_mailTemplate_getMailDelMethod(ZBSEMAIL_CLIENTPORTALPWREST); if (!isset($mailDeliveryMethod) || empty($mailDeliveryMethod)) $mailDeliveryMethod = -1; // send $sent = zeroBSCRM_mailDelivery_sendMessage($mailDeliveryMethod,$mailArray); // =================================== / MAIL SENDING ======================================= // ========================================================================================== } return $new_password; } // if wpid } return false; } // Returns bool of whether or not a specific customer can access client portal function zeroBSCRM_isCustomerPortalDisabled( $contact_id=-1 ) { // No Contact ID, no entry, unless Admin or Jetpack CRM Admin we can let those in. $contact_id = (int)$contact_id; if ( $contact_id < 1 ) { if ( zeroBSCRM_isZBSAdminOrAdmin() ) { return false; } return true; } else { // return check global $zbs; return $zbs->DAL->contacts->getContactMeta( $contact_id, 'portal_disabled' ); } // default = closed door return true; } // loads customer record + creates a portal user for record // replaces zeroBSCRM_genPortalUser function zeroBSCRM_createClientPortalUserFromRecord($cID=-1){ if (!empty($cID)){ global $zbs; // existing? $existing = zeroBSCRM_getClientPortalUserID($cID); if (!empty($existing) || $existing > 0) return false; $email = $zbs->DAL->contacts->getContactEmail($cID); $contact = $zbs->DAL->contacts->getContact($cID,array('fields'=>array('zbsc_fname','zbsc_lname'))); $fname = ''; if (isset($contact['fname']) && !empty($contact['fname'])) $fname = $contact['fname']; $lname = ''; if (isset($contact['lname']) && !empty($contact['lname'])) $lname = $contact['lname']; // fire return zeroBSCRM_createClientPortalUser($cID,$email,12,$fname,$lname); } return false; } function zeroBSCRM_getClientPortalUserID($cID=-1){ if (!empty($cID)){ global $zbs; //first lets check if a user already exists with that email.. $email = $zbs->DAL->contacts->getContactEmail($cID); if (!empty($email)){ $userID = email_exists($email); if($userID != null){ //update_post_meta($cID, 'zbs_portal_wpid', $userID); $zbs->DAL->contacts->addUpdateContactWPID(array('id'=>$cID,'WPID'=>$userID)); } }else{ //no email in meta, but might be linked? //$userID = get_post_meta($cID, 'zbs_portal_wpid', true); $userID = $zbs->DAL->contacts->getContactWPID($cID); } return $userID; } return false; } function zeroBSCRM_getClientPortalUserWPObj($cID=-1){ if (!empty($cID)){ global $zbs; //$user_id = zeroBSCRM_getClientPortalUserID($cID); $user_id = $zbs->DAL->contacts->getContactWPID($cID); return new WP_User( $user_id ); } return false; } // Function to update the zbs<->wp user link function zeroBSCRM_setClientPortalUser($cID=-1,$wpUserID=-1){ if ($cID > 0 && $wpUserID > 0){ global $zbs; $zbs->DAL->contacts->addUpdateContactWPID(array('id'=>$cID,'WPID'=>$wpUserID)); return true; } return false; } function zeroBSCRM_createClientPortalUser( $cID=-1, $email='', $passwordLength=12, $first_name='', $last_name='' ) { // fail if bad params if ( empty( $cID ) || empty( $email ) || !zeroBSCRM_validateEmail( $email ) ) { return false; } // fail if email already exists as a WP user if ( email_exists( $email ) ) { return false; } global $zbs; $password = wp_generate_password( $passwordLength, false ); // organise WP user details $wpUserDeets = array( 'user_email' => $email, 'user_login' => $email, 'user_pass' => $password, 'nickname' => $email, 'first_name' => empty( $first_name ) ? '' : $first_name, 'last_name' => empty( $last_name ) ? '' : $last_name, ); // create WP user $user_id = wp_insert_user( $wpUserDeets ); // retrieve created user $user = new WP_User( $user_id ); // fail if the user doesn't exist if ( !$user->exists() ) { return false; } // link WP user ID to contact $zbs->DAL->contacts->addUpdateContactWPID( array( 'id' => $cID, 'WPID' => $user_id ) ); // any extra assigned role? (from settings) $extraRole = zeroBSCRM_getSetting( 'portalusers_extrarole' ); // add role(s) if ( ! empty( $extraRole ) ) { // Set the WP role first, then the JPCRM role $user->set_role( $extraRole ); $user->add_role( 'zerobs_customer' ); } else { $user->set_role( 'zerobs_customer' ); } // check if the email template is active, and if it is, send... $active = zeroBSCRM_get_email_status(ZBSEMAIL_CLIENTPORTALWELCOME); if ( $active ){ // generate html $emailHTML = zeroBSCRM_Portal_generateNotificationHTML( $password, true, $email, $cID ); // build send array $mailArray = array( 'toEmail' => $email, 'toName' => '', 'subject' => zeroBSCRM_mailTemplate_getSubject( ZBSEMAIL_CLIENTPORTALWELCOME ), 'headers' => zeroBSCRM_mailTemplate_getHeaders( ZBSEMAIL_CLIENTPORTALWELCOME ), 'body' => $emailHTML, 'textbody' => '', 'options' => array( 'html' => 1 ), 'tracking' => array( // tracking :D (auto-inserted pixel + saved in history db) 'emailTypeID' => ZBSEMAIL_CLIENTPORTALWELCOME, 'targetObjID' => $cID, 'senderWPID' => -10, 'associatedObjID' => -1 // none ) ); // Sends email, including tracking, via setting stored route out, (or default if none) // and logs tracking :) // discern del method $mailDeliveryMethod = zeroBSCRM_mailTemplate_getMailDelMethod( ZBSEMAIL_CLIENTPORTALWELCOME ); if ( !isset( $mailDeliveryMethod ) || empty( $mailDeliveryMethod ) ) { $mailDeliveryMethod = -1; } // send $sent = zeroBSCRM_mailDelivery_sendMessage( $mailDeliveryMethod, $mailArray ); } // IA zeroBSCRM_FireInternalAutomator( 'clientwpuser.new', array( 'id' => $user_id, 'againstid' => $cID, 'userEmail' => $email, ) ); } // THIS IS NOW DEPRECATED db2+ // (META used to be all deets, it's now normal deets - as table) #} Quick wrapper to future-proof. #} Should later replace all get_post_meta's with this function zeroBS_getCustomerMeta($cID=-1){ // zeroBSCRM_DEPRECATEDMSG('Use of function: zeroBS_getCustomerMeta'); global $zbs; //if (!empty($cID)) return get_post_meta($cID, 'zbs_customer_meta', true); // Return contact directly DB2+ if (!empty($cID)) return $zbs->DAL->contacts->getContact($cID,array('ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); return false; } // generates a 'demo' customer object (excluding custom fields) function zeroBS_getDemoCustomer(){ global $zbs, $zbsCustomerFields; $ret = array(); $demoData = array( 'status' => array( 'Lead', 'Customer' ), 'prefix' => array('Mr', 'Mrs', 'Miss'), 'fname' => array('John','Jim','Mike','Melvin','Janet','Jennifer','Judy','Julie'), 'lname' => array('Smith','Jones','Scott','Filbert'), 'fullname' => array('John Smith','Jim Ellison','Mike Myers','Melvin Malcolms'), 'addr1' => array('101 Red Street','26 Somerset Street','1 London Road'), 'addr2' => array('Winchester','Leeds Village','Webleck'), 'city' => array('London','Los Angeles','Leeds','Exeter'), 'county' => array('London','Hertfordshire','California','Montana'), 'postcode' => array('A1 1XU','AO12 3RR','E1 3XG','M1 3LF'), 'secaddr_addr1' => array('101 Red Street','26 Somerset Street','1 London Road'), 'secaddr_addr2' => array('Winchester','Leeds Village','Webleck'), 'secaddr_city' => array('London','Los Angeles','Leeds','Exeter'), 'secaddr_county' => array('London','Hertfordshire','California','Buckinghamshire'), 'secaddr_postcode' => array('A1 1XU','AO12 3RR','E1 3XG','M1 3LF'), // dirty repetition... 'secaddr1' => array('101 Red Street','26 Somerset Street','1 London Road'), 'secaddr2' => array('Winchester','Leeds Village','Webleck'), 'seccity' => array('London','Los Angeles','Leeds','Exeter'), 'seccounty' => array('London','Hertfordshire','California','Buckinghamshire'), 'secpostcode' => array('A1 1XU','AO12 3RR','E1 3XG','M1 3LF'), 'hometel' => array('01010 123 345', '01234 546 789'), 'worktel' => array('01010 123 345', '01234 546 789'), 'mobtel' => array('07812 345 678'), 'email' => array('random@email.com','not.real@gmail.com','nonsense@email.com') ); foreach ($zbsCustomerFields as $fK => $fV){ $ret[$fK] = ''; if (isset($demoData[$fK])) $ret[$fK] = $demoData[$fK][mt_rand(0, count($demoData[$fK]) - 1)]; } // add fullname $ret['fullname'] = $demoData['fullname'][mt_rand(0, count($demoData['fullname']) - 1)]; // fill in some randoms $ret['status'] = $demoData['status'][mt_rand(0, count($demoData['status']) - 1)]; return $ret; } function zeroBS_getCustomerExtraMetaVal($cID=-1,$extraMetaKey=false){ if (!empty($cID) && !empty($extraMetaKey)) { global $zbs; // quick $cleanKey = strtolower(str_replace(' ','_',$extraMetaKey)); //return get_post_meta($cID, 'zbs_customer_extra_'.$cleanKey, true); return $zbs->DAL->contacts->getContactMeta($cID,'extra_'.$cleanKey); } return false; } #} sets an extra meta val function zeroBS_setCustomerExtraMetaVal($cID=-1,$extraMetaKey=false,$extraMetaVal=false){ if (!empty($cID) && !empty($extraMetaKey)) { // quick $cleanKey = strtolower(str_replace(' ','_',$extraMetaKey)); global $zbs; //return update_post_meta($cID, 'zbs_customer_extra_'.$cleanKey, $extraMetaVal); return $zbs->DAL->updateMeta(ZBS_TYPE_CONTACT,$cID,'extra_'.$extraMetaKey,$extraMetaVal); } return false; } function zeroBS_getCustomerSocialAccounts($cID=-1){ global $zbs; //if (!empty($cID)) return get_post_meta($cID, 'zbs_customer_socials', true); if (!empty($cID)) return $zbs->DAL->contacts->getContactSocials($cID); return false; } function zeroBS_updateCustomerSocialAccounts($cID=-1,$accArray=array()){ if (!empty($cID) && is_array($accArray)){ //return update_post_meta($cID, 'zbs_customer_socials', $accArray); global $zbs; #} Enact return $zbs->DAL->contacts->addUpdateContact(array( 'id' => $cID, 'limitedFields' =>array( array('key'=>'zbsc_tw','val'=>$accArray['tw'],'type'=>'%s'), array('key'=>'zbsc_li','val'=>$accArray['li'],'type'=>'%s'), array('key'=>'zbsc_fb','val'=>$accArray['fb'],'type'=>'%s') ))); } return false; } function zeroBSCRM_getCustomerFiles($cID=-1){ if (!empty($cID)){ global $zbs; //return get_post_meta($cID, 'zbs_customer_files', true); //return $zbs->DAL->contacts->getContactMeta($cID,'files'); return zeroBSCRM_files_getFiles('customer',$cID); } return false; } // maintainIndexs keeps the files original index .e.g. 1,2 so that can match when doing portal stuff (as we're using legacy indx) function zeroBSCRM_getCustomerPortalFiles($cID=-1){ if (!empty($cID)){ global $zbs; //return get_post_meta($cID, 'zbs_customer_files', true); //return $zbs->DAL->contacts->getContactMeta($cID,'files'); $ret = array(); $files = zeroBSCRM_files_getFiles('customer',$cID); $fileIndex = 0; if (is_array($files)) foreach ($files as $f){ // APPROVED portal files if (isset($f['portal']) && $f['portal'] == 1) $ret[$fileIndex] = $f; $fileIndex++; } return $ret; } return false; } function zeroBSCRM_updateCustomerFiles($cID=-1,$filesArray=false){ if (!empty($cID)){ global $zbs; //return update_post_meta($cID, 'zbs_customer_files', $filesArray); return $zbs->DAL->updateMeta(ZBS_TYPE_CONTACT,$cID,'files',$filesArray); } return false; } #} As of v1.1 can pass searchphrase #} As of v1.2 can pass tags #} As of v2.2 has associated func getCustomersCountIncParams for getting the TOTAL for a search (ignoring pages) #} As of v2.2 can also get ,$withTags=false,$withAssigned=false,$withLastLog=false #} As of v2.2 can also pass quickfilters (Damn this has got messy): lead, customer, over100, over200, over300, over400, over500 // ... in array like ('lead') #} 2.52+ AVOID using this, call getContacts directly plz, this is just for backward compatibility :) function zeroBS_getCustomers( $withFullDetails=false, $perPage=10, $page=0, $withInvoices=false, $withQuotes=false, $searchPhrase='', $withTransactions=false, $argsOverride=false, $companyID=false, $hasTagIDs='', $inArr = '', $withTags=false, $withAssigned=false, $withLastLog=false, $sortByField='ID', $sortOrder='DESC', $quickFilters=false, $ownedByID = false, $withValues=false ){ /* DAL3.0: $withValues */ #} Query Performance index #global $zbsQPI; if (!isset($zbsQPI)) $zbsQPI = array(); #$zbsQPI['retrieveCustomers2getCustomers'] = zeroBSCRM_mtime_float(); // $withFullDetails = irrelevant with new DB2 (always returns) // $argsOverride CAN NO LONGER WORK :) if ($argsOverride !== false) zeroBSCRM_DEPRECATEDMSG('Use of $argsOverride in zeroBS_getCustomers is no longer relevant (DB2)'); global $zbs; // this needs translating for new dbfields: // FOR NOW if ($sortByField == 'post_id') $sortByField = 'ID'; if ($sortByField == 'post_title') $sortByField = 'zbsc_lname'; if ($sortByField == 'post_excerpt') $sortByField = 'zbsc_lname'; /* we need to prepend zbsc_ when not using cf */ $custFields = $zbs->DAL->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_CONTACT)); // needs to check if field name is custom field: $sortIsCustomField = false; if (is_array($custFields) && array_key_exists($sortByField,$custFields)) $sortIsCustomField = true; if (!$sortIsCustomField && $sortByField != 'ID') $sortByField = 'zbsc_'.$sortByField; // catch empties if (empty($sortByField)) $sortByField = 'ID'; if (empty($sortOrder)) $sortOrder = 'desc'; // legacy from dal1 $actualPage = $page; if (!$zbs->isDAL2()) $actualPage = $page-1; // only DAL1 needed this if ($actualPage < 0) $actualPage = 0; // make ARGS $args = array( // Search/Filtering (leave as false to ignore) 'searchPhrase' => $searchPhrase, 'inCompany' => $companyID, 'inArr' => $inArr, 'quickFilters' => $quickFilters, 'isTagged' => $hasTagIDs, 'ownedBy' => $ownedByID, 'withCustomFields' => true, 'withQuotes' => $withQuotes, 'withInvoices' => $withInvoices, 'withTransactions' => $withTransactions, 'withLogs' => false, 'withLastLog' => $withLastLog, 'withTags' => $withTags, 'withOwner' => $withAssigned, 'withValues' => $withValues, 'sortByField' => $sortByField, 'sortOrder' => $sortOrder, 'page' => $actualPage, 'perPage' => $perPage, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT) ); // here ignore owners = true the default, because we're not really forcing ownership anywhere overall, // when we do, we should change this/make it check if ($ownedByID !== false) { $args['ignoreowner'] = false; } return $zbs->DAL->contacts->getContacts($args); } #} As of 2.2 - matches getCustomers but returns a total figure (no deets) // NOTE, params are same except first 5 + withTransactions removed: // $withFullDetails=false,$perPage=10,$page=0,$withInvoices=false,$withQuotes=false,$withTransactions=false, // - trimmed returns for efficiency (is just a count really :o dirty.) // https://codex.wordpress.org/Class_Reference/WP_Query function zeroBS_getCustomersCountIncParams( $searchPhrase='', $argsOverride=false, $companyID=false, $hasTagIDs='', $inArr = '', $quickFilters=''){ // $withFullDetails = irrelevant with new DB2 (always returns) // $argsOverride CAN NO LONGER WORK :) if ($argsOverride !== false) zeroBSCRM_DEPRECATEDMSG('Use of $argsOverride in zeroBS_getCustomersCountIncParams is no longer relevant (DB2)'); global $zbs; // make ARGS $args = array( // Search/Filtering (leave as false to ignore) 'searchPhrase' => $searchPhrase, 'inCompany' => $companyID, 'inArr' => $inArr, 'quickFilters' => $quickFilters, 'isTagged' => $hasTagIDs, // just count 'count' =>true, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT) ); return (int)$zbs->DAL->contacts->getContacts($args); } #} same as above but wrapped in contact view link function zeroBS_getCustomerIcoLinked($cID=-1,$incName=false,$extraClasses = '',$maxSize=100){ $extraHTML = ''; if ($incName){ $cName = zeroBS_getCustomerNameShort($cID); if (!empty($cName)) $extraHTML = '<span class="">'.$cName.'</span>'; } return '<div class="zbs-co-img'.$extraClasses.'"><a href = "'. jpcrm_esc_link('view',$cID,'zerobs_customer') .'">' . zeroBS_customerAvatarHTML($cID,-1,$maxSize).'</a>'.$extraHTML.'</div>'; } #} same as above but wrapped in contact view link + semantic ui label img link function zeroBS_getCustomerIcoLinkedLabel($cID=-1){ $extraHTML = ''; $cName = zeroBS_getCustomerNameShort($cID); if (!empty($cName)) $extraHTML = '<span>'.$cName.'</span>'; else { $cEmail = zeroBS_customerEmail($cID); if (!empty($cEmail)) $extraHTML = '<span>'.$cEmail.'</span>'; } $extraClasses = ' ui image label'; return '<a href="'. jpcrm_esc_link('view',$cID,'zerobs_customer') .'" class="'.$extraClasses.'">' . zeroBS_customerAvatarHTML($cID).$extraHTML.'</a>'; } #} same as above but with no image (for non-avatar mode) function zeroBS_getCustomerLinkedLabel($cID=-1){ $extraHTML = ''; $cName = zeroBS_getCustomerNameShort($cID); if (!empty($cName)) $extraHTML = '<span>'.$cName.'</span>'; else { $cEmail = zeroBS_customerEmail($cID); if (!empty($cEmail)) $extraHTML = '<span>'.$cEmail.'</span>'; } // for empties, add no if (empty($extraHTML)) $extraHTML = '<span>#'.$cID.'</span>'; $extraClasses = ' ui label'; return '<a href="'. jpcrm_esc_link('view',$cID,'zerobs_customer') .'" class="'.$extraClasses.'">' .$extraHTML.'</a>'; } /* Centralised delete customer func, including sub-element removal */ function zeroBS_deleteCustomer($id=-1,$saveOrphans=true){ if (!empty($id)){ global $zbs; return $zbs->DAL->contacts->deleteContact(array('id'=>$id,'saveOrphans'=>$saveOrphans)); } return false; } function zeroBS_getCustomerIDWithExternalSource($externalSource='',$externalID=''){ global $zbs; #} No empties, no random externalSources :) if (!empty($externalSource) && !empty($externalID) && array_key_exists($externalSource,$zbs->external_sources)){ #} If here, is legit. $approvedExternalSource = $externalSource; global $zbs; return $zbs->DAL->contacts->getContact(-1,array( 'externalSource' => $approvedExternalSource, 'externalSourceUID' => $externalID, 'onlyID' => true, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT) )); } return false; } function zeroBSCRM_getCustomerTagsByID($cID=-1,$justIDs=false){ if (!empty($cID)){ global $zbs; return $zbs->DAL->getTagsForObjID(array( 'objtypeid'=>ZBS_TYPE_CONTACT, 'objid'=>$cID, 'onlyID'=>$justIDs, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); } } // NOTE: $objType is temporary until DB2 fully rolled out all tables function zeroBS_getOwner($objID=-1,$withDeets=true,$objType=-1,$knownOwnerID=-1){ if ($objID !== -1 && $objType !== -1){ $objType = jpcrm_upconvert_obj_type( $objType ); global $zbs; $retObj = false; // if passed, save the db call if ($knownOwnerID > 0){ $userIDofOwner = $knownOwnerID; } else { $userIDofOwner = $zbs->DAL->getObjectOwner(array( 'objID' => $objID, 'objTypeID' => $objType )); } if (isset($userIDofOwner) && !empty($userIDofOwner)){ // check if user can be owner (is zbs admin) // check on the assign, is less performance impacting // if (! user_can($userIDofOwner,'admin_zerobs_usr') return false; if ($withDeets){ #} Retrieve owner deets $retObj = zeroBS_getOwnerObj($userIDofOwner); } else return $userIDofOwner; } return $retObj; } return false; } /** * Retrieves the owner object based on a given WP user ID. * * This function gets the owner's data without revealing sensitive information * (e.g. `user_pass`). * * @param int $wp_user_id The WordPress user ID. Default is -1. * * @return array|bool Returns an associative array containing the 'ID' and 'OBJ' (user data object) if successful, false otherwise. */ function zeroBS_getOwnerObj( $wp_user_id = -1 ) { if ( $wp_user_id > 0 ) { $user = get_userdata( $wp_user_id ); if ( ! isset( $user->ID ) || ! isset( $user->data ) ) { return false; } /** * Ideally we'd restructure this, but the return result is used extensively, * particularly from `zeroBS_getOwner` calls. For now we'll explicitly set what * fields are provided (e.g. don't show `user_pass`). */ $user_data = (object) array( 'ID' => $user->data->ID, 'user_login' => $user->data->user_login, 'user_nicename' => $user->data->user_nicename, 'display_name' => $user->data->display_name, ); return array( 'ID' => $wp_user_id, 'OBJ' => $user_data, ); } return false; } // NOTE - this is very generic & not to be used in future code // Use the direct $zbs->DAL->contacts->addUpdateContact code example in below rather than this generic. // kthx. function zeroBS_setOwner($objID=-1,$ownerID=-1,$objTypeID=false){ if ($objID !== -1 && $objTypeID !== false){ // here we check that the potential owner CAN even own if (!user_can($ownerID,'admin_zerobs_usr')) return false; global $zbs; return $zbs->DAL->setFieldByID(array( 'objID' => $objID, 'objTypeID' => $objTypeID, 'colname' => 'zbs_owner', 'coldatatype' => '%d', // %d/s 'newValue' => $ownerID, )); } return false; } #} Needed for Dave, added to core (but also to a custom extension for him). having it here too #} will mean when we move DB his code won't break. PLS dont rename function zeroBS_getAllContactsForOwner($owner=-1, $page=1){ if (!empty($owner)){ global $zbs; return $zbs->DAL->contacts->getContacts(array( 'ownedBy' => $owner, 'perPage' => 10, 'page' => $page )); } return false; } function zeroBSCRM_mergeCustomers($dominantID=-1,$slaveID=-1){ if (!empty($dominantID) && !empty($slaveID)){ // load both $master = zeroBS_getCustomer($dominantID); $slave = zeroBS_getCustomer($slaveID,true,true,true); if (isset($master['id']) && isset($slave['id'])){ global $zbs; try { // all set, merge $changes = array(); $conflictingChanges = array(); $fieldPrefix = ''; if (!$zbs->isDAL2()) $fieldPrefix = 'zbsc_'; // copy details from slave fields -> master fields // where detail not present? // into second address? $masterNewMeta = false; $masterHasSecondAddr = false; // this'll let us copy over first from slave if empty :) $slaveHasFirstAddr = false; $slaveHasSecondAddr = false; $slaveFirstAddrStr = ''; $slaveSecondAddrStr = ''; // if this gets filled, it'll be added as aka below $slaveEmailAddress = false; // because these are just arrays (in meta) - we do a kind of compare, save a new ver, // ..and add any mismatches to conflicting changes in a meaningful way // DB2 converted these from obj[meta] -> obj // first, just copy through slave email if present if (isset($slave['email']) && !empty($slave['email'])) $slaveEmailAddress = $slave['email']; // we start with the master :) $masterNewMeta = $master; global $zbsCustomerFields, $zbsAddressFields; // first, any empties (excluding addr) in master, get patched from secondary foreach ($zbsCustomerFields as $fieldKey => $fieldDeets){ // ignore addrs here if (!isset($fieldDeets['migrate']) || $fieldDeets['migrate'] != 'addresses'){ // present in master? if (!isset($master[$fieldKey]) || empty($master[$fieldKey])){ // NOT PRESENT IN MASTER // was not set, or empty, in master // present in slave? if (isset($slave[$fieldKey]) && !empty($slave[$fieldKey])){ // a change :) - note requires zbsc_ here for some annoying reason, leaving for now $masterNewMeta[$fieldPrefix.$fieldKey] = $slave[$fieldKey]; //hopefully DB2 doesnt.. // Does for now lol $masterNewMeta[$fieldKey] = $slave[$fieldKey]; $changes[] = __('Copied field',"zero-bs-crm").' "'.$fieldDeets[1].'" '.__('from secondary record over main record, (main was empty).',"zero-bs-crm"); } } else { // if slave had value? // (no need to worry about emails, dealt with separately) if (isset($slave[$fieldKey]) && !empty($slave[$fieldKey]) && $fieldKey !== 'email'){ // master val already present, conflicting change: $conflictingChanges[] = __('Field not copied',"zero-bs-crm").' "'.$fieldDeets[1].'" '.__('from secondary record over main record, (main had value). Value was',"zero-bs-crm").' "'.$slave[$fieldKey].'"'; } } } else { // ADDRESSES. Here we just use the foreach to check if the master has any secaddr fields // just sets a flag used below in logic :) if ( str_starts_with( $fieldKey, 'secaddr_' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // check presence (of any secaddr_ field) if (isset($master[$fieldKey]) && !empty($master[$fieldKey])) $masterHasSecondAddr = true; // does slave have secondary? if (isset($slave[$fieldKey]) && !empty($slave[$fieldKey])) { // clearly has (bits of) second addr $slaveHasSecondAddr = true; // we also build this str which'll be shown as conflicting change (so we don't "loose" this data) if (!empty($slaveSecondAddrStr)) $slaveSecondAddrStr .= ', '; $slaveSecondAddrStr .= $slave[$fieldKey]; } } else { // first address if (isset($slave[$fieldKey]) && !empty($slave[$fieldKey])) { // clearly has (bits of) first addr $slaveHasFirstAddr = true; // we also build this str which'll be shown as conflicting change (so we don't "loose" this data) if (!empty($slaveFirstAddrStr)) $slaveFirstAddrStr .= ', '; $slaveFirstAddrStr .= $slave[$fieldKey]; } } } } // addr's // if master has no sec addr, just copy first addr from slave :) if (!$masterHasSecondAddr){ // copy first addr from slave foreach ($zbsAddressFields as $addrFieldKey => $addrFieldDeets){ // from slave first to master second - note requires zbsc_ here for some annoying reason, leaving for now // Hopefully db2 doesnt $masterNewMeta[$fieldPrefix.'secaddr_'.$addrFieldKey] = $slave[$addrFieldKey]; // Does for now lol $masterNewMeta['secaddr_'.$addrFieldKey] = $slave[$addrFieldKey]; } $changes[] = __('Copied address from secondary record into "secondary address" for main record',"zero-bs-crm"); // any second addr from slave just goes into logs if ($slaveHasSecondAddr){ // provide old addr string $conflictingChanges[] = __('Address not copied. Secondary address from secondary record could not be copied (master already had two addresses).',"zero-bs-crm")."\r\n".__('Address',"zero-bs-crm").': '."\r\n".$slaveSecondAddrStr; } } else { // master already has two addresses, dump (any) secondary addresses into conflicting changes if ($slaveHasFirstAddr){ // provide old addr string $conflictingChanges[] = __('Address not copied. Address from secondary record could not be copied (master already had two addresses).',"zero-bs-crm")."\r\n".__('Address',"zero-bs-crm").': '."\r\n".$slaveFirstAddrStr; } if ($slaveHasSecondAddr){ // provide old addr string $conflictingChanges[] = __('Address not copied. Secondary address from secondary record could not be copied (master already had two addresses).',"zero-bs-crm")."\r\n".__('Address',"zero-bs-crm").': '."\r\n".$slaveSecondAddrStr; } } // assign social profiles from slave -> master // GET THESE BEFORE updating! $masterSocial = zeroBS_getCustomerSocialAccounts($dominantID); $slaveSocial = zeroBS_getCustomerSocialAccounts($slaveID); // UPDATE MASTER META: zeroBS_addUpdateCustomer($dominantID,$masterNewMeta,'','','',false,false,false,-1,$fieldPrefix); $masterNewSocial = $masterSocial; global $zbsSocialAccountTypes; if (count($zbsSocialAccountTypes) > 0) { foreach ($zbsSocialAccountTypes as $socialKey => $socialAccType){ // master / slave has this acc? // for simplicity (not perf.) we grab which has which, first $masterHas = false; $slaveHas = false; if (is_array($masterSocial) && isset($masterSocial[$socialKey]) && !empty($masterSocial[$socialKey])) { $masterHas = true; } if (is_array($slaveSocial) && isset($slaveSocial[$socialKey]) && !empty($slaveSocial[$socialKey])) { $slaveHas = true; } // what's up. if ($masterHas && $slaveHas){ // conflicting change $conflictingChanges[] = __('Social account not copied.',"zero-bs-crm").' "'.$socialAccType['name'].'" of "'.$slaveSocial[$socialKey].'" '.__('from secondary record (master already has a ',"zero-bs-crm").$socialAccType['name'].' '.__('account.',"zero-bs-crm"); } elseif ($masterHas && !$slaveHas){ // no change } elseif ($slaveHas && !$masterHas){ // copy slave -> master $masterNewSocial[$socialKey] = $slaveSocial[$socialKey]; $changes[] = __('Copied social account from secondary record into main record',"zero-bs-crm").' ('.$socialAccType['name'].').'; } } // UPDATE SOCIAL zeroBS_updateCustomerSocialAccounts($dominantID,$masterNewSocial); } // assign files from slave -> master /* Array ( [0] => Array ( [file] => /app/public/wp-content/uploads/zbscrm-store/aa250965422e9aea-Document-20243.pdf [url] => http://zbsphp5.dev/wp-content/uploads/zbscrm-store/aa250965422e9aea-Document-20243.pdf [type] => application/pdf [error] => [priv] => 1 ) ) */ $slaveFiles = zeroBSCRM_getCustomerFiles($slaveID); if (is_array($slaveFiles) && count($slaveFiles) > 0){ $masterFiles = zeroBSCRM_getCustomerFiles($dominantID); if (!is_array($masterFiles)) $masterFiles = array(); foreach ($slaveFiles as $zbsFile){ // add $masterFiles[] = $zbsFile; // changelog $filename = basename($zbsFile['file']); // if in privatised system, ignore first hash in name if (isset($zbsFile['priv'])){ $filename = substr($filename,strpos($filename, '-')+1); } $changes[] = __('Moved file to main record',"zero-bs-crm").' ('.$filename.')'; } // save master files zeroBSCRM_updateCustomerFiles($dominantID,$masterFiles); } // assign company from slave -> master $masterCompany = zeroBS_getCustomerCompanyID($dominantID); $slaveCompany = zeroBS_getCustomerCompanyID($slaveID); if (empty($masterCompany)){ // slave co present, update main if (!empty($slaveCompany)){ zeroBS_setCustomerCompanyID($dominantID,$slaveCompany); $changes[] = __('Assigned main record to secondary record\'s '.jpcrm_label_company(),"zero-bs-crm").' (#'.$slaveCompany.').'; } } else { // master has co already, does slave? if (!empty($slaveCompany) && $slaveCompany != $masterCompany){ // conflicting change $conflictingChanges[] = __('Secondary contact was assigned to '.jpcrm_label_company().', whereas main record was assigned to another '.jpcrm_label_company().'.',"zero-bs-crm").' (#'.$slaveCompany.').'; } } // assign quotes from slave -> master // got quotes? if (is_array($slave['quotes']) && count($slave['quotes']) > 0){ $quoteOffset = zeroBSCRM_getQuoteOffset(); foreach ($slave['quotes'] as $quote){ // id for passing to logs $qID = ''; #TRANSITIONTOMETANO if (isset($quote['zbsid'])) $qID = $quote['zbsid']; // for quotes, we just "switch" the owner meta :) zeroBSCRM_changeQuoteCustomer($quote['id'],$dominantID); $changes[] = __('Assigned quote from secondary record onto main record',"zero-bs-crm").' (#'.$qID.').'; } } // / has quotes // assign invs from slave -> master // got invoices? if (is_array($slave['invoices']) && count($slave['invoices']) > 0){ foreach ($slave['invoices'] as $invoice){ // for invs, we just "switch" the owner meta :) zeroBSCRM_changeInvoiceCustomer($invoice['id'],$dominantID); $changes[] = __('Assigned invoice from secondary record onto main record',"zero-bs-crm").' (#'.$invoice['id'].').'; } } // / has invoices // assign trans from slave -> master // got invoices? if (is_array($slave['transactions']) && count($slave['transactions']) > 0){ foreach ($slave['transactions'] as $transaction){ // for trans, we just "switch" the owner meta :) zeroBSCRM_changeTransactionCustomer($transaction['id'],$dominantID); $changes[] = __('Assigned transaction from secondary record onto main record',"zero-bs-crm").' (#'.$transaction['id'].').'; } } // / has invoices // assign events from slave -> master // get events $events = zeroBS_getEventsByCustomerID($slaveID,true,10000,0); if (is_array($events) && count($events) > 0){ foreach ($events as $event){ // for events, we just "switch" the meta val :) zeroBSCRM_changeEventCustomer($event['id'],$dominantID); $changes[] = __( 'Assigned task from secondary record onto main record', 'zero-bs-crm' ) . ' (#' . $event['id'] . ').'; } } // / has invoices // assign logs(?) from slave -> master // for now save these as a random text meta against customer (not sure how to expose as of yet, but don't want to loose) $slaveLogs = zeroBSCRM_getContactLogs($slaveID,true,10000,0); // id created name meta if (is_array($slaveLogs) && count($slaveLogs) > 0){ /* in fact, just save as json encode :D - rough but quicker // brutal str builder. $logStr = ''; foreach ($slaveLogs as $log){ if (!empty($logStr)) $logStr .= "\r\n"; } */ //update_post_meta($dominantID, 'zbs_merged_customer_log_bk_'.time(), json_encode($slaveLogs)); // no $change here, as this is kinda secret, kthx $zbs->DAL->updateMeta(ZBS_TYPE_CONTACT,$dominantID,'merged_customer_log_bk_'.time(),$slaveLogs); } // assign tags(?) from slave -> master // get slave tags as ID array $slaveTagsIDs = zeroBSCRM_getCustomerTagsByID($slaveID,true); if (is_array($slaveTagsIDs) && count($slaveTagsIDs) > 0){ // add tags to master (append mode) //wp_set_object_terms($dominantID, $slaveTagsIDs, 'zerobscrm_customertag', true ); $zbs->DAL->addUpdateObjectTags(array( 'objid' => $dominantID, 'objtype' => ZBS_TYPE_CONTACT, 'tagIDs' => $slaveTagsIDs, 'mode' => 'append' )); $changes[] = __('Tagged main record with',"zero-bs-crm").' '.count($slaveTagsIDs).' '.__('tags from secondary record.',"zero-bs-crm"); } // AKA / alias // second email -> alias first if (!empty($slaveEmailAddress)){ // add as alias zeroBS_addCustomerAlias($dominantID,$slaveEmailAddress); $changes[] = __('Added secondary record email as alias/aka of main record',"zero-bs-crm").' ('.$slaveEmailAddress.')'; } // Customer image //(for now, left to die) // delete slave zeroBS_deleteCustomer($slaveID,false); $changes[] = __('Removed secondary record',"zero-bs-crm").' (#'.$slaveID.')'; // assign log for changes + conflicting changes // strbuild $shortDesc ='"'.$slave['name'].'" (#'.$slave['id'].') '.__('into this record',"zero-bs-crm"); $longDesc = ''; // changes if (is_array($changes) && count($changes) > 0) { $longDesc .= '<strong>'.__('Record Changes',"zero-bs-crm").':</strong><br />'; // cycle through em foreach ($changes as $c){ $longDesc .= '<br />'.$c; } } else { $longDesc .= '<strong>'.__('No Changes',"zero-bs-crm").'</strong>'; } // conflicting changes if (is_array($conflictingChanges) && count($conflictingChanges) > 0) { $longDesc .= '<br />=============================<br /><strong>'.__('Conflicting Changes',"zero-bs-crm").':</strong><br />'; // cycle through em foreach ($conflictingChanges as $c){ $longDesc .= '<br />'.$c; } } else { $longDesc .= '<br />=============================<br /><strong>'.__('No Conflicting Changes',"zero-bs-crm").'</strong>'; } // MASTER LOG :D zeroBS_addUpdateContactLog($dominantID,-1,-1,array( 'type' => 'Bulk Action: Merge', 'shortdesc' => $shortDesc, 'longdesc' => $longDesc) ); return true; } catch (Exception $e){ // failed somehow! echo 'ERROR:'.$e->getMessage(); } } // / if id's } return false; } function zeroBS_addUpdateCustomer( $cID = -1, $cFields = array(), $externalSource='', $externalID='', $customerDate='', $fallBackLog = false, $extraMeta = false, $automatorPassthrough = false, $owner = -1, $metaBuilderPrefix = 'zbsc_' ){ #} return $ret = false; if (isset($cFields) && count($cFields) > 0){ #} New flag $newCustomer = false; $originalStatus = ''; global $zbs; if ($cID > 0){ #} Retrieve / check? $postID = $cID; #} Build "existing meta" to pass, (so we only update fields pushed here) $existingMeta = $zbs->DAL->contacts->getContact($postID,array()); $originalDate = time(); if (isset($existingMeta) && is_array($existingMeta) && isset($existingMeta['createduts']) && !empty($existingMeta['createduts'])) $originalDate = $existingMeta['createduts']; if (!empty($customerDate) && $customerDate != ''){ #} DATE PASSED TO THE FUNCTION $customerDateTimeStamp = strtotime($customerDate); #} ORIGINAL POST CREATION DATE // no need, db2 = UTS $originalDateTimeStamp = strtotime($originalDate); $originalDateTimeStamp = $originalDate; #} Compare, if $customerDateTimeStamp < then update with passed date if($customerDateTimeStamp < $originalDateTimeStamp){ // straight in there :) $zbs->DAL->contacts->addUpdateContact(array( 'id' => $postID, 'limitedFields' =>array( array('key'=>'zbsc_created','val'=>$customerDateTimeStamp,'type'=>'%d') ))); } } // WH changed 20/05/18 // 20/05/18 - Previously this would reload the EXISTING database data // THEN 'override' any passed fields // THEN save that down // ... this was required when we used old meta objs. (pre db2) // ... so if we're now DAL2, we can do away with that and simply pass what's to be updated and mode do_not_update_blanks $existingMeta = array(); } else { // DB2: Probably can rethink this whole func, (do we even need it?) e.g. header post mentality used here // for now I've just edited in place, but def refactor in time #} Set flag $newCustomer = true; #} Set up empty meta arr #} DATE PASSED TO THE FUNCTION $customerDateTimeStamp = strtotime($customerDate); #} DAL2 needs timestamp :) $existingMeta = array('created' => $customerDateTimeStamp); } #} Build using centralised func below, passing any existing meta (updates not overwrites) $zbsCustomerMeta = zeroBS_buildCustomerMeta($cFields,$existingMeta,$metaBuilderPrefix,'',true); $we_have_tags = false; // set to false.. duh.. // TAG customer (if exists) - clean etc here too if ( ! empty( $cFields['tags'] ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $tags = $cFields['tags']; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // Sanitize tags if ( is_array( $tags ) ) { $customer_tags = filter_var_array( $tags, FILTER_UNSAFE_RAW ); // Formerly this used FILTER_SANITIZE_STRING, which is now deprecated as it was fairly broken. This is basically equivalent. // @todo Replace this with something more correct. foreach ( $customer_tags as $k => $v ) { $customer_tags[ $k ] = strtr( strip_tags( $v ), // phpcs:ignore WordPress.WP.AlternativeFunctions.strip_tags_strip_tags array( "\0" => '', '"' => '&#34;', "'" => '&#39;', '<' => '', ) ); } $we_have_tags = true; } if ( $we_have_tags ) { $zbsCustomerMeta['tags'] = array(); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase foreach ( $customer_tags as $tag_name ) { // Check for existing tag under this name. $tag_id = $zbs->DAL->getTag( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -1, array( 'objtype' => ZBS_TYPE_CONTACT, 'name' => $tag_name, 'onlyID' => true, ) ); // If tag doesn't exist, create one. if ( empty( $tag_id ) ) { $tag_id = $zbs->DAL->addUpdateTag( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase array( 'data' => array( 'objtype' => ZBS_TYPE_CONTACT, 'name' => $tag_name, ), ) ); } // Add tag to list. if ( ! empty( $tag_id ) ) { $zbsCustomerMeta['tags'][] = $tag_id; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } } } } #} Add external source/externalid #} No empties, no random externalSources :) $extSourceArr = -1; $approvedExternalSource = ''; #} As this is passed to automator :) if (!empty($externalSource) && !empty($externalID) && array_key_exists($externalSource,$zbs->external_sources)){ #} If here, is legit. $approvedExternalSource = $externalSource; #} Add/Update record flag // 2.4+ Migrated away from this method to new update_post_meta($postID, 'zbs_customer_ext_'.$approvedExternalSource, $externalID); // 2.52+ Moved to new DAL method :) $extSourceArr = array( 'source' => $approvedExternalSource, 'uid' => $externalID ); // add/update // DB2, this is just used below :)zeroBS_updateExternalSource($postID,$extSourceArr); $zbsCustomerMeta['externalSources'] = array($extSourceArr); } #} Otherwise will just be a random customer no ext source #} Got owner? if ($owner !== -1) $zbsCustomerMeta['owner'] = $owner; #} Update record (All IA is now fired intrinsicly ) // DB2 update_post_meta($postID, 'zbs_customer_meta', $zbsCustomerMeta); return $zbs->DAL->contacts->addUpdateContact(array( 'id' => $cID, 'data' => $zbsCustomerMeta, 'extraMeta' => $extraMeta, 'automatorPassthrough' => $automatorPassthrough, 'fallBackLog' => $fallBackLog )); /* This now get's passed above, and dealt with by DAL #} Any extra meta keyval pairs? $confirmedExtraMeta = false; if (isset($extraMeta) && is_array($extraMeta)) { $confirmedExtraMeta = array(); foreach ($extraMeta as $k => $v){ #} This won't fix stupid keys, just catch basic fails... $cleanKey = strtolower(str_replace(' ','_',$k)); #} Brutal update //update_post_meta($postID, 'zbs_customer_extra_'.$cleanKey, $v); $zbs->DAL->updateMeta(ZBS_TYPE_CONTACT,$postID,'extra_'.$cleanKey,$v); #} Add it to this, which passes to IA $confirmedExtraMeta[$cleanKey] = $v; } } */ /* NOW DEALT WITH IN DAL2 :) #} INTERNAL AUTOMATOR #} & #} FALLBACKS if ($newCustomer){ #} Add to automator zeroBSCRM_FireInternalAutomator('customer.new',array( 'id'=>$postID, 'customerMeta'=>$zbsCustomerMeta, 'extsource'=>$approvedExternalSource, 'automatorpassthrough'=>$automatorPassthrough, #} This passes through any custom log titles or whatever into the Internal automator recipe. 'customerExtraMeta'=>$confirmedExtraMeta #} This is the "extraMeta" passed (as saved) )); // (WH) Moved this to fire on the IA... // do_action('zbs_new_customer', $postID); //fire the hook here... } else { #} Customer Update here (automator)? #} TODO #} FALLBACK #} (This fires for customers that weren't added because they already exist.) #} e.g. x@g.com exists, so add log "x@g.com filled out form" #} Requires a type and a shortdesc if ( isset($fallBackLog) && is_array($fallBackLog) && isset($fallBackLog['type']) && !empty($fallBackLog['type']) && isset($fallBackLog['shortdesc']) && !empty($fallBackLog['shortdesc']) ){ #} Brutal add, maybe validate more?! #} Long desc if present: $zbsNoteLongDesc = ''; if (isset($fallBackLog['longdesc']) && !empty($fallBackLog['longdesc'])) $zbsNoteLongDesc = $fallBackLog['longdesc']; #} Only raw checked... but proceed. $newOrUpdatedLogID = zeroBS_addUpdateContactLog($postID,-1,-1,array( #} Anything here will get wrapped into an array and added as the meta vals 'type' => $fallBackLog['type'], 'shortdesc' => $fallBackLog['shortdesc'], 'longdesc' => $zbsNoteLongDesc )); } // catch dirty flag (update of status) (note, after update_post_meta - as separate) //if (isset($_POST['zbsc_status_dirtyflag']) && $_POST['zbsc_status_dirtyflag'] == "1"){ // actually here, it's set above if (isset($statusChange) && is_array($statusChange)){ // status has changed // IA zeroBSCRM_FireInternalAutomator('customer.status.update',array( 'id'=>$postID, 'againstid' => $postID, 'userMeta'=> $zbsCustomerMeta, 'from' => $statusChange['from'], 'to' => $statusChange['to'] )); } } */ #} REQ? #} MAKE SURE if you change any post_name features you also look at: "NAMECHANGES" in this file (when a post updates it'll auto replace these...) #$newCName = zeroBS_customerName('',$zbsMeta,true,false) #} Return customerID if success :) //$ret = $postID; } return $ret; } /* ====================================================== Contact -> aliases ====================================================== */ #} See if already in use/exists function zeroBS_canUseCustomerAlias($alias=''){ // now can call this generic: return zeroBS_canUseAlias(ZBS_TYPE_CONTACT,$alias); } #} Get specific alias if exists function zeroBS_getCustomerAlias($cID=-1,$alias=''){ return zeroBS_getObjAlias(ZBS_TYPE_CONTACT,$cID,$alias); } #} Get specific alias if exists function zeroBS_getCustomerAliasByID($cID=-1,$aliasID=-1){ return zeroBS_getAliasByID(ZBS_TYPE_CONTACT,$cID,$aliasID); } #} Get All Aliases against a contact. function zeroBS_getCustomerAliases($cID=-1){ return zeroBS_getObjAliases(ZBS_TYPE_CONTACT,$cID); } #} add Aliases to a contact. function zeroBS_addCustomerAlias($cID=-1,$alias=''){ return zeroBS_addObjAlias(ZBS_TYPE_CONTACT,$cID,$alias); } #} remove Alias from an contact function zeroBS_removeCustomerAlias($cID=-1,$alias=''){ return zeroBS_removeObjAlias(ZBS_TYPE_CONTACT,$cID,$alias); } #} remove Alias from a contact. function zeroBS_removeCustomerAliasByID($cID=-1,$aliasID=-1){ return zeroBS_removeObjAliasByID(ZBS_TYPE_CONTACT,$cID,$aliasID); } /* ====================================================== / Contact -> aliases ====================================================== */ function zeroBSCRM_getLog($lID=-1){ if ($lID !== -1){ global $zbs; return $zbs->DAL->logs->getLog(array( 'id' => $lID, 'incMeta' => true, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT))); } return false; } function zeroBSCRM_getContactLogs($customerID=-1,$withFullDetails=false,$perPage=100,$page=0,$searchPhrase='',$argsOverride=false){ if (!empty($customerID) && $customerID !== -1 && $customerID !== false){ global $zbs; return $zbs->DAL->logs->getLogsForObj(array( 'objtype' => ZBS_TYPE_CONTACT, 'objid' => $customerID, 'searchPhrase' => $searchPhrase, 'incMeta' => $withFullDetails, 'sortByField' => 'zbsl_created', 'sortOrder' => 'DESC', 'page' => $page, 'perPage' => $perPage, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT) )); } return array(); } function zeroBSCRM_getAllContactLogs($withFullDetails=false,$perPage=100,$page=0,$searchPhrase='',$argsOverride=false){ global $zbs; return $zbs->DAL->logs->getLogsForANYObj(array( 'objtype' => ZBS_TYPE_CONTACT, 'searchPhrase' => $searchPhrase, 'incMeta' => $withFullDetails, 'sortByField' => 'zbsl_created', 'sortOrder' => 'DESC', 'page' => $page, 'perPage' => $perPage, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT) )); } function zeroBSCRM_getCompanyLogs($companyID=false,$withFullDetails=false,$perPage=100,$page=0,$searchPhrase='',$argsOverride=false){ // DAL 3+ :) if (!empty($companyID)){ global $zbs; return $zbs->DAL->logs->getLogsForObj(array( 'objtype' => ZBS_TYPE_COMPANY, 'objid' => $companyID, 'searchPhrase' => $searchPhrase, 'incMeta' => $withFullDetails, 'sortByField' => 'zbsl_created', 'sortOrder' => 'DESC', 'page' => $page, 'perPage' => $perPage, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT) )); } return array(); } function zeroBSCRM_getObjCreationLog($objID=-1,$objType=ZBS_TYPE_CONTACT){ if (!empty($objID) && $objID !== -1 && $objID !== false){ global $zbs; return $zbs->DAL->getLogsForObj(array( 'objtype' => $objType, 'objid' => $objID, 'notetype' => 'Created', 'incMeta' => true, 'sortByField' => 'zbsl_created', 'sortOrder' => 'ASC', 'page' => 0, 'perPage' => 1, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT) )); } } function zeroBSCRM_logTypeStrToDB($str=''){ global $zbs; return $zbs->DAL->logs->logTypeIn($str); } function zeroBSCRM_getMostRecentContactLog($objID=false,$withFullDetails=false,$restrictToTypes=false){ if (!empty($objID)){ global $zbs; return $zbs->DAL->logs->getLogsForObj(array( 'objtype' => ZBS_TYPE_COMPANY, 'objid' => $objID, 'notetypes' => $restrictToTypes, 'incMeta' => $withFullDetails, 'sortByField' => 'zbsl_created', 'sortOrder' => 'DESC', 'page' => 0, 'perPage' => 1, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT) )); } } function zeroBSCRM_getMostRecentCompanyLog($objID=false,$withFullDetails=false,$restrictToTypes=false){ if (!empty($objID)){ global $zbs; return $zbs->DAL->logs->getLogsForObj(array( 'objtype' => ZBS_TYPE_COMPANY, 'objid' => $objID, 'notetypes' => $restrictToTypes, 'incMeta' => $withFullDetails, 'sortByField' => 'zbsl_created', 'sortOrder' => 'DESC', 'page' => 0, 'perPage' => 1, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT) )); } } function zeroBS_searchLogs($querystring){ global $zbs; return $zbs->DAL->logs->getLogsForANYObj(array( 'searchPhrase' => $querystring, 'perPage' => 100, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT) )); } function zeroBS_allLogs(){ global $zbs; return $zbs->DAL->logs->getLogsForANYObj(array( 'perPage' => 100, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT) )); } function zeroBS_addUpdateLog( $cID = -1, $logID = -1, $logDate = -1, /* #} Process with metaboxes.php funcs, is easier :) $zbsNoteAgainstPostID $zbsNoteType $zbsNoteShortDesc $zbsNoteLongDesc NOTE!: as of 31/05/17 WOODY started putting 'meta_assoc_id' in these - e.g. if it's an 'email sent' log, this meta_assoc_id will be the CAMPAIGN id 'meta_assoc_src' would then be mailcamp */ $noteFields = array(), $objType='', /* contact or 'zerobs_contact' */ $owner = -1 ){ global $zbs; // DAL3 all obj logs: if ($objType == 'zerobs_customer'){ //zeroBSCRM_DEPRECATEDMSG('zeroBS_addUpdateLog has been replaced by zeroBS_addUpdateContactLog etc. or (better still) DAL2 calls direct'); //return zeroBS_addUpdateContactLog($cID,$logID,$logDate,$noteFields,$owner); // DAL3 NO CPT LOGS: //} else // fallback // translate zerobs_customer to 1 $typeID = $zbs->DAL->objTypeID($objType); // got type? if ($typeID !== -1){ // assume this'll work. (should do.) return zeroBS_addUpdateObjLog($typeID,$cID,$logID,$logDate,$noteFields,$owner); } // no TYPE zeroBSCRM_DEPRECATEDMSG( 'zeroBS_addUpdateLog has been replaced by DAL3 logging. Please do not use, or at least pass an object type.' ); return false; } // really should just be calling direct at this point, or zeroBS_addUpdateObjLog at least function zeroBS_addUpdateContactLog( $cID = -1, $logID = -1, $logDate = -1, $noteFields = array(), $owner = -1 ){ // wrapper for this: return zeroBS_addUpdateObjLog(ZBS_TYPE_CONTACT,$cID,$logID,$logDate,$noteFields,$owner); } // generic add obj log function zeroBS_addUpdateObjLog( $objTypeID = -1, $objID = -1, $logID = -1, $logDate = -1, $noteFields = array(), $owner = -1 ){ if ($objTypeID > 0){ $logType = ''; $logShortDesc = ''; $logLongDesc = ''; $logMeta = -1; $logCreated = -1; $pinned = -1; if (isset($noteFields['type'])) $logType = zeroBSCRM_permifyLogType($noteFields['type']); if (isset($noteFields['shortdesc'])) $logShortDesc = $noteFields['shortdesc']; if (isset($noteFields['longdesc'])) $logLongDesc = $noteFields['longdesc']; if (isset($noteFields['meta'])) $logMeta = $noteFields['meta']; if (isset($noteFields['pinned'])) $pinned = $noteFields['pinned']; if ($logDate !== -1) { $logCreated = strtotime($logDate); } else { $logCreated = -1; } global $zbs; return $zbs->DAL->logs->addUpdateLog(array( 'id' => $logID, 'owner' => $owner, // fields (directly) 'data' => array( 'objtype' => $objTypeID, 'objid' => $objID, 'type' => $logType, 'shortdesc' => $logShortDesc, 'longdesc' => $logLongDesc, 'meta' => $logMeta, 'pinned' => $pinned, 'created' => $logCreated ))); } return false; } // allows us to lazily 'hotswap' wp_set_post_terms in extensions (e.g. pre DAL2 it'll just fire wp_set_post_terms) // ... here it does DAL2 equiv // WH Note: if using old WP method (wp_set_post_terms) can pass tags or tagIDS - DB2 currently only accepts tagIDs - to add in // ... to get around this I've temp added $usingTagIDS=true flag // still used in bulk-tagger and groove-connect extensions as of 9 May 1923 function zeroBSCRM_DAL2_set_post_terms($cID=-1,$tags=array(),$taxonomy='zerobscrm_customertag',$append=true,$usingTagIDS=true){ zeroBSCRM_DEPRECATEDMSG( 'zeroBSCRM_DAL2_set_post_terms has been replaced by DAL3 tagging. Please do not use.' ); global $zbs; // if we have tooo.... $possibleObjTypeID = $zbs->DAL->cptTaxonomyToObjID($taxonomy); if ($possibleObjTypeID > 0){ $mode = 'replace'; if ($append) $mode = 'append'; $fieldName = 'tagIDs'; if (!$usingTagIDS) $fieldName = 'tags'; return $zbs->DAL->addUpdateObjectTags(array( 'objid' => $cID, 'objtype' => $possibleObjTypeID, $fieldName => $tags, 'mode' => $mode )); } return false; } // allows us to lazily 'hotswap' wp_set_object_terms in extensions (e.g. pre DAL2 it'll just fire wp_set_object_terms) // ... here it does DAL2 equiv // WH Note: if using old WP method (wp_set_object_terms) can pass tags or tagIDS - DB2 currently only accepts tagIDs - to add in // ... to get around this I've temp added $usingTagIDS=true flag // still used in several extensions as of 9 May 1923 function zeroBSCRM_DAL2_set_object_terms($cID=-1,$tags=array(),$taxonomy='zerobscrm_customertag',$append=true,$usingTagIDS=true){ zeroBSCRM_DEPRECATEDMSG( 'zeroBSCRM_DAL2_set_object_terms has been replaced by DAL3 tagging. Please do not use.' ); global $zbs; // if we have tooo.... $possibleObjTypeID = $zbs->DAL->cptTaxonomyToObjID($taxonomy); if ($possibleObjTypeID > 0){ $mode = 'replace'; if ($append) $mode = 'append'; $fieldName = 'tagIDs'; if (!$usingTagIDS) $fieldName = 'tags'; return $zbs->DAL->addUpdateObjectTags(array( 'objid' => $cID, 'objtype' => $possibleObjTypeID, $fieldName => $tags, 'mode' => $mode )); } return false; /* // we only switch out for customer tags, rest just go old way if ($taxonomy == 'zerobscrm_customertag'){ global $zbs; $mode = 'replace'; if ($append) $mode = 'append'; $fieldName = 'tagIDs'; if (!$usingTagIDS) $fieldName = 'tags'; return $zbs->DAL->addUpdateObjectTags(array( 'objid' => $cID, 'objtype' => ZBS_TYPE_CONTACT, $fieldName => $tags, 'mode' => $mode )); } else { //https://codex.wordpress.org/Function_Reference/wp_set_object_terms return wp_set_object_terms($cID,$tags,$taxonomy,$append); } */ } // allows us to lazily 'hotswap' wp_set_object_terms in extensions (e.g. pre DAL2 it'll just fire wp_set_object_terms) // ... here it does DAL2 equiv // WH Note: if using old WP method (wp_remove_object_terms) can pass tags or tagIDS - DB2 currently only accepts tagIDs - to add in // ... to get around this I've temp added $usingTagIDS=true flag // still used in csv-importer-pro as of 9 May 1923 function zeroBSCRM_DAL2_remove_object_terms($cID=-1,$tags=array(),$taxonomy='zerobscrm_customertag',$usingTagIDS=true){ zeroBSCRM_DEPRECATEDMSG( 'zeroBSCRM_DAL2_remove_object_terms has been replaced by DAL3 tagging. Please do not use.' ); global $zbs; // if we have tooo.... $possibleObjTypeID = $zbs->DAL->cptTaxonomyToObjID($taxonomy); if ($possibleObjTypeID > 0){ $fieldName = 'tagIDs'; if (!$usingTagIDS) $fieldName = 'tags'; return $zbs->DAL->addUpdateObjectTags(array( 'objid' => $cID, 'objtype' => $possibleObjTypeID, $fieldName => $tags, 'mode' => 'remove' )); } return false; /* // we only switch out for customer tags, rest just go old way if ($taxonomy == 'zerobscrm_customertag'){ global $zbs; $fieldName = 'tagIDs'; if (!$usingTagIDS) $fieldName = 'tags'; return $zbs->DAL->addUpdateObjectTags(array( 'objid' => $cID, 'objtype' => ZBS_TYPE_CONTACT, $fieldName => $tags, 'mode' => 'remove' )); } else { //https://codex.wordpress.org/Function_Reference/wp_remove_object_terms return wp_remove_object_terms($cID,$tags,$taxonomy); } */ } // for now, wrapper for past! - moved this to zeroBS_buildContactMeta function zeroBS_buildCustomerMeta($arraySource=array(),$startingArray=array(),$fieldPrefix='zbsc_',$outputPrefix='',$removeEmpties=false,$autoGenAutonumbers=false){ // This is no longer req, as we can use the generic from 3.0 :) //return zeroBS_buildContactMeta($arraySource,$startingArray,$fieldPrefix,$outputPrefix,$removeEmpties); return zeroBS_buildObjArr($arraySource,$startingArray,$fieldPrefix,$outputPrefix,$removeEmpties,ZBS_TYPE_CONTACT,$autoGenAutonumbers); } #} This takes an array source (can be $_POST) and builds out a meta field array for it.. #} This lets us use the same fields array for Metaboxes.php and any custom integrations #} e.g. $zbsCustomerMeta = zeroBS_buildCustomerMeta($_POST); #} e.g. $zbsCustomerMeta = zeroBS_buildCustomerMeta($importedMetaFields); #} e.g. $zbsCustomerMeta = zeroBS_buildCustomerMeta(array('zbsc_fname'=>'Woody')); #} 27/09/16: Can now also pass starting array, which lets you "override" fields present in $arraySource, without loosing originals not passed #} 12/04/18: Added prefix so as to be able to pass normal array e.g. fname (by passing empty fieldPrefix) #} 3.0: this was moved to generic zeroBS_buildObjArr :) function zeroBS_buildContactMeta($arraySource=array(),$startingArray=array(),$fieldPrefix='zbsc_',$outputPrefix='',$removeEmpties=false,$autoGenAutonumbers=false){ // moved to generic, just return that :) return zeroBS_buildObjArr($arraySource,$startingArray,$fieldPrefix,$outputPrefix,$removeEmpties,ZBS_TYPE_CONTACT,$autoGenAutonumbers); /* #} def $zbsCustomerMeta = array(); #} if passed... if (isset($startingArray) && is_array($startingArray)) $zbsCustomerMeta = $startingArray; #} go global $zbsCustomerFields,$zbs; $i=0; foreach ($zbsCustomerFields as $fK => $fV){ $i++; if (!isset($zbsCustomerMeta[$outputPrefix.$fK])) $zbsCustomerMeta[$outputPrefix.$fK] = ''; if (isset($arraySource[$fieldPrefix.$fK])) { switch ($fV[0]){ case 'tel': // validate tel? $zbsCustomerMeta[$outputPrefix.$fK] = sanitize_text_field($arraySource[$fieldPrefix.$fK]); preg_replace("/[^0-9 ]/", '', $zbsCustomerMeta[$outputPrefix.$fK]); break; case 'price': case 'numberfloat': $zbsCustomerMeta[$outputPrefix.$fK] = sanitize_text_field($arraySource[$fieldPrefix.$fK]); $zbsCustomerMeta[$outputPrefix.$fK] = preg_replace('@[^0-9\.]+@i', '-', $zbsCustomerMeta[$outputPrefix.$fK]); $zbsCustomerMeta[$outputPrefix.$fK] = floatval($zbsCustomerMeta[$outputPrefix.$fK]); break; case 'numberint': $zbsCustomerMeta[$outputPrefix.$fK] = sanitize_text_field($arraySource[$fieldPrefix.$fK]); $zbsCustomerMeta[$outputPrefix.$fK] = preg_replace('@[^0-9]+@i', '-', $zbsCustomerMeta[$outputPrefix.$fK]); $zbsCustomerMeta[$outputPrefix.$fK] = floatval($zbsCustomerMeta[$outputPrefix.$fK]); break; case 'textarea': $zbsCustomerMeta[$outputPrefix.$fK] = zeroBSCRM_textProcess($arraySource[$fieldPrefix.$fK]); break; case 'date': $zbsCustomerMeta[$outputPrefix.$fK] = sanitize_text_field($arraySource[$fieldPrefix.$fK]); break; default: $zbsCustomerMeta[$outputPrefix.$fK] = sanitize_text_field($arraySource[$fieldPrefix.$fK]); break; } } } // if DAL2, second addresses get passed differently? ¯\_(ツ)_/¯ if ($zbs->isDAL2()){ $replaceMap = array( 'secaddr1' => 'secaddr_addr1', 'secaddr2' => 'secaddr_addr2', 'seccity' => 'secaddr_city', 'seccounty' => 'secaddr_county', 'seccountry' => 'secaddr_country', 'secpostcode' => 'secaddr_postcode' ); foreach ($replaceMap as $d2key => $d1key) if (isset($zbsCustomerMeta[$outputPrefix.$d1key])){ $zbsCustomerMeta[$outputPrefix.$d2key] = $zbsCustomerMeta[$outputPrefix.$d1key]; unset($zbsCustomerMeta[$outputPrefix.$d1key]); } } // can also pass some extras :) /social $extras = array('tw','fb','li'); foreach ($extras as $fK){ if (!isset($zbsCustomerMeta[$outputPrefix.$fK])) $zbsCustomerMeta[$outputPrefix.$fK] = ''; if (isset($arraySource[$fieldPrefix.$fK])) { $zbsCustomerMeta[$outputPrefix.$fK] = sanitize_text_field($arraySource[$fieldPrefix.$fK]); } } // $removeEmpties if ($removeEmpties){ $ret = array(); foreach ($zbsCustomerMeta as $k => $v){ $intV = (int)$v; if (!is_array($v) && !empty($v) && $v != '' && $v !== 0 && $v !== -1 && $intV !== -1){ $ret[$k] = $v; } } $zbsCustomerMeta = $ret; } return $zbsCustomerMeta; */ } /* ====================================================== / Unchanged DAL2->3 (Mostly customer/contact + log relatead) ====================================================== */ // ==================================================================================================================================== // ==================================================================================================================================== // ==================== / DAL 2.0 FUNCS =============================================================================================== // ==================================================================================================================================== // ==================================================================================================================================== // ==================================================================================================================================== // ==================================================================================================================================== // ==================== DAL 3.0 FUNCS =============================================================================================== // ==================================================================================================================================== // ==================================================================================================================================== function zeroBS___________DAL30Helpers(){return;} /* ====================================================== GENERIC helpers ====================================================== */ function zeroBS___________GenericHelpers(){return;} #} This is a fill-in until we deprecate addUpdateTransaction etc. (3.5 or so) #} it'll take a DAL1 obj (e.g. transaction with 'orderid') and produce a v3 translated field variant (e.g. orderid => ref (via 'dal1key' attr on obj model)) #} param $objType = ZBS_TYPE_TRANSACTION #} param $fieldPrefix = zbst_ if fields are prefixed with function zeroBS_translateDAL1toDAL3Obj($arraySource=array(),$objType=-1,$fieldPrefix=''){ if ($objType > 0){ global $zbs; //$objectModel = $zbs->DAL->objModel($objType); $objectLayer = $zbs->DAL->getObjectLayerByType($objType); if (isset($objectLayer)){ $ret = array(); $objTranslationMatrix = $objectLayer->getDAL1toDAL3ConversionMatrix(); if (!is_array($objTranslationMatrix)) $objTranslationMatrix = array(); foreach ($arraySource as $k => $v){ $kClean = $k; if (!empty($fieldPrefix)) $kClean = str_replace($fieldPrefix,'',$k); if (isset($objTranslationMatrix[$kClean])){ // is translatable $ret[$fieldPrefix.$objTranslationMatrix[$kClean]] = $v; } else { // isn't translatable $ret[$k] = $v; } } } // / has object layer } // / has objtype return $ret; } #} This takes an array source (can be $_POST) and builds out a meta field array for it.. #} ... this is a generalised postarray->objarray creator, built from zeroBS_buildContactMeta, #} ... now produces all "meta" (objarrays) for all objs. Centralised to keep DRY #} 13/03/19: Added $autoGenAutonumbers - if TRUE, empty/non-passed autonumber custom fields will assume fresh + autogen (useful for PORTAL/SYNC generated) function zeroBS_buildObjArr($arraySource=array(),$startingArray=array(),$fieldPrefix='zbsc_',$outputPrefix='',$removeEmpties=false,$objType=ZBS_TYPE_CONTACT,$autoGenAutonumbers=false){ #} def $retArray = array(); #} if passed... if (isset($startingArray) && is_array($startingArray)) $retArray = $startingArray; #} go // req. global $zbs; // DAL3 notes: (See #globalfieldobjsdal3 in fields.php) // .. ultimately we default to using the $fields globals, then fallback to the objmodels // introduced in DAL3 objs. This allows coverage of both, for now // v3.0 RC+ this can be refactored :) // Note: To make RC1 I also added in translation, which is perhaps a step toward refactoring this: // Some RC1 field translations (requires dal1key against changed obj model fields) $arraySource = zeroBS_translateDAL1toDAL3Obj($arraySource,$objType,$fieldPrefix); // retrieve global var name $globFieldVarName = $zbs->DAL->objFieldVarName($objType); // should be $zbsCustomerFields etc. // from 3.0 this is kind of redundant, esp when dealing with events, which have none, so we skip if this case if ( !$zbs->isDAL3() && (empty($globFieldVarName) || $globFieldVarName == false || !isset($GLOBALS[ $globFieldVarName ])) ) return $retArray; // nope. (for events in DAL3) // ... potentially can turn this off for all non DAL3? may be redundant inside next {} if ($objType !== ZBS_TYPE_TASK && $objType !== ZBS_TYPE_QUOTETEMPLATE && isset($GLOBALS[$globFieldVarName])){ $i=0; foreach ($GLOBALS[$globFieldVarName] as $fK => $fV){ $i++; // if it's not an autonumber (which generates new on blank passes), set it to empty // ... or if it has $autoGenAutonumbers = true, if ( ($fV[0] !== 'autonumber' && !isset($retArray[$outputPrefix.$fK])) || $autoGenAutonumbers ) $retArray[$outputPrefix.$fK] = ''; // two EXCEPTIONS: // 1) custom field type checkbox, because it adds -0 -1 etc. to options, so this wont fire, // 2) Autonumbers which are blank to start with get caught beneath // ... see below for checkbox catch if (isset($arraySource[$fieldPrefix.$fK])) { switch ($fV[0]){ case 'tel': // validate tel? Should be an user option, allow validation. $retArray[$outputPrefix.$fK] = sanitize_text_field($arraySource[$fieldPrefix.$fK]); //$retArray[$outputPrefix.$fK] = preg_replace("/[^0-9 .+\-()]/", '', $retArray[$outputPrefix.$fK]); break; case 'price': case 'numberfloat': $retArray[$outputPrefix.$fK] = sanitize_text_field($arraySource[$fieldPrefix.$fK]); $retArray[$outputPrefix.$fK] = preg_replace('@[^0-9\.]+@i', '-', $retArray[$outputPrefix.$fK]); $retArray[$outputPrefix.$fK] = floatval($retArray[$outputPrefix.$fK]); break; case 'numberint': $retArray[$outputPrefix.$fK] = sanitize_text_field($arraySource[$fieldPrefix.$fK]); $retArray[$outputPrefix.$fK] = preg_replace('@[^0-9]+@i', '-', $retArray[$outputPrefix.$fK]); $retArray[$outputPrefix.$fK] = intval($retArray[$outputPrefix.$fK]); break; case 'textarea': // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $retArray[ $outputPrefix . $fK ] = sanitize_textarea_field( $arraySource[ $fieldPrefix . $fK ] ); break; case 'date': $safe_text = sanitize_text_field( $arraySource[ $fieldPrefix . $fK ] ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $retArray[ $outputPrefix . $fK ] = jpcrm_date_str_to_uts( $safe_text, '!Y-m-d', true ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase break; case 'datetime': $retArray[$outputPrefix.$fK] = sanitize_text_field($arraySource[$fieldPrefix.$fK]); // translate datetime to UTS (without time) // ... by default from DAL3.0 $retArray[$outputPrefix.$fK] = zeroBSCRM_locale_dateToUTS($retArray[$outputPrefix.$fK],true); break; case 'radio': case 'select': // just get value, easy. $retArray[$outputPrefix.$fK] = sanitize_text_field($arraySource[$fieldPrefix.$fK]); break; // autonumber dealt with below this if {} case 'autonumber': // pass it along :) $retArray[$outputPrefix.$fK] = sanitize_text_field($arraySource[$fieldPrefix.$fK]); break; // checkbox dealt with below this if {} default: $retArray[$outputPrefix.$fK] = sanitize_text_field($arraySource[$fieldPrefix.$fK]); break; } // / switch type } // / if isset (simple) $arraySource[$fieldPrefix.$fK] // catch checkboxes if ($fV[0] == 'checkbox'){ // there are several ways that checkbox (multiselect) inputs may be passed, depending on source // because this function catches from: // - edit page post // - client portal profile page // - Gravity forms/extension calls // - API // ... to name a few, it's sensible that we try and catch the variants (low risk/cost here) $checkboxArr = array(); // Checkbox input: Iterative // This cycles through `checkboxkey-$i` (up to 64 options) and includes if they're set // This is used by our edit pages, client portal profile page etc. for ($checkboxI = 0; $checkboxI < 64; $checkboxI++){ if (isset($arraySource[$fieldPrefix.$fK.'-'.$checkboxI])) { // retrieve $checkboxArr[] = $arraySource[$fieldPrefix.$fK.'-'.$checkboxI]; } } // Checkbox input: CSV // This can be exploded // This is used by gravity forms, when multiple 1 word options are checked (and probably elsewhere) if (isset($arraySource[$fieldPrefix.$fK]) && is_string($arraySource[$fieldPrefix.$fK])) { // one option or multi? if (strpos($arraySource[$fieldPrefix.$fK], ',')) $checkboxArr = explode(',', $arraySource[$fieldPrefix.$fK]); else $checkboxArr = array($arraySource[$fieldPrefix.$fK]); } // Checkbox input: Array // This can be straight passed // This is used by gravity forms, when at least one option with multiple words are checked (and probably elsewhere, is good to support pass through) if (isset($arraySource[$fieldPrefix.$fK]) && is_array($arraySource[$fieldPrefix.$fK])) { $checkboxArr = $arraySource[$fieldPrefix.$fK]; } if (is_array($checkboxArr)){ // sanitize $checkboxArr = array_map( 'sanitize_text_field', $checkboxArr ); // csv em $retArray[$outputPrefix.$fK] = implode(',',$checkboxArr); } else { // none selected, set blank $retArray[$outputPrefix.$fK] = ''; } } // / if checkbox // if autonumber if ($fV[0] == 'autonumber'){ // this is a generated field. // if was previously set, sticks with that, if not set, will generate new, based on custom field rule // NOTE!!!! if this is NOT SET in customerMeta, it WILL NOT be updated // ... this is because when passing incomplete update records (e.g. not passing autonumber) // ... it doesn't need a new AUTONUMBER // ... so if you want a fresh autonumber, you need to pass with $startingArray[] EMPTY value set // if not yet set if (isset($retArray[$outputPrefix.$fK]) && empty($retArray[$outputPrefix.$fK])){ // retrieve based on custom field rule $autono = ''; // retrieve rule $formatExample = ''; if (isset($fV[2])) { $formatExample = $fV[2]; } if ( ! empty( $formatExample ) && str_contains( $formatExample, '#' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // has a rule at least $formatParts = explode('#', $formatExample); // build // prefix if (!empty($formatParts[0])) $autono .= zeroBSCRM_customFields_parseAutoNumberStr($formatParts[0]); // number $no = zeroBSCRM_customFields_getAutoNumber($objType,$fK); if ($no > 0 && $no !== false) $autono .= $no; // suffix if (!empty($formatParts[2])) $autono .= zeroBSCRM_customFields_parseAutoNumberStr($formatParts[2]); // if legit, add if ($no > 0 && $no !== false) $retArray[$outputPrefix.$fK] = $autono; } } } // / if autonumber } // / foreach field } // / if global-based-fill-out // if DAL2, second addresses get passed differently? ¯\_(ツ)_/¯ // ... guess there's no harm in this, if not set wont enact... if ($zbs->isDAL2()){ $replaceMap = array( 'secaddr1' => 'secaddr_addr1', 'secaddr2' => 'secaddr_addr2', 'seccity' => 'secaddr_city', 'seccounty' => 'secaddr_county', 'seccountry' => 'secaddr_country', 'secpostcode' => 'secaddr_postcode' ); foreach ($replaceMap as $d2key => $d1key) if (isset($retArray[$outputPrefix.$d1key])){ $retArray[$outputPrefix.$d2key] = $retArray[$outputPrefix.$d1key]; unset($retArray[$outputPrefix.$d1key]); } } // if DAL3, we had a number of translations, where old fields were being passed differently ¯\_(ツ)_/¯ // ... these shouldn't be passed v3.0 onwards (fixed in metaboxes etc.) but this catches them if passed by accident/somewhere? // ... guess there's no harm in this, if not set wont enact... /* WH removed 30/04/2019 - seems redundant now. if ($zbs->isDAL3()){ // #DAL2ToDAL3FIELDCONVERSION $replaceMap = array( // QUOTES ZBS_TYPE_QUOTE => array( // dal2 => dal3 'name' => 'title', 'val' => 'value', ) ); // only use this obj type replace map $objReplaceMap = array(); if (isset($replaceMap[$objType])) $objReplaceMap = $replaceMap[$objType]; // any replaces? foreach ($objReplaceMap as $d2key => $d3key){ if (isset($retArray[$outputPrefix.$d2key])){ $retArray[$outputPrefix.$d3key] = $retArray[$outputPrefix.$d2key]; unset($retArray[$outputPrefix.$d2key]); } } } */ // can also pass some extras :) /social // for co + contact if ($objType == ZBS_TYPE_CONTACT || $objType == ZBS_TYPE_COMPANY){ $extras = array('tw','fb','li'); foreach ($extras as $fK){ if (!isset($retArray[$outputPrefix.$fK])) $retArray[$outputPrefix.$fK] = ''; if (isset($arraySource[$fieldPrefix.$fK])) { $retArray[$outputPrefix.$fK] = sanitize_text_field($arraySource[$fieldPrefix.$fK]); } } } // ... Further, from DAL3+ we now have proper object models, which probably should replace "fields" // above, but for now, churning through both, as sensitively as possible. // get an obj model, if set $potentialModel = $zbs->DAL->objModel($objType); // will be objlayer model if set if (is_array($potentialModel)){ // cycle through each field + set, if not already set by the above. foreach ($potentialModel as $fieldKey => $fieldDetail){ // there's a few we ignore :) if (in_array($fieldKey, array('ID','zbs_site','zbs_team'))) continue; // if not already set if (!isset($retArray[$outputPrefix.$fieldKey])){ // retrieve based on type switch ($fieldDetail['format']){ case 'str': case 'curr': // for now, process curr as str. (probs needs to just validate IS CURR) if (isset($arraySource[$fieldPrefix.$fieldKey])) $retArray[$outputPrefix.$fieldKey] = zeroBSCRM_textProcess($arraySource[$fieldPrefix.$fieldKey]); break; case 'int': if (isset($arraySource[$fieldPrefix.$fieldKey])) { $retArray[$outputPrefix.$fieldKey] = sanitize_text_field($arraySource[$fieldPrefix.$fieldKey]); $retArray[$outputPrefix.$fieldKey] = preg_replace('@[^0-9]+@i', '-', $retArray[$outputPrefix.$fieldKey]); $retArray[$outputPrefix.$fieldKey] = intval($retArray[$outputPrefix.$fieldKey]); } break; case 'uts': if (isset($arraySource[$fieldPrefix.$fieldKey])) { $retArray[$outputPrefix.$fieldKey] = sanitize_text_field($arraySource[$fieldPrefix.$fieldKey]); // in case of UTS dates, the $_POST likely passed may be in date format // ... if so, take the model default + translate (if set) if (isset($fieldDetail['autoconvert']) && $fieldDetail['autoconvert'] == 'date'){ // translate "01/12/2018" to UTS (without time) $retArray[$outputPrefix.$fieldKey] = zeroBSCRM_locale_dateToUTS($retArray[$outputPrefix.$fieldKey],false); } if (isset($fieldDetail['autoconvert']) && $fieldDetail['autoconvert'] == 'datetime'){ // translate datetime to UTS (with time) $retArray[$outputPrefix.$fieldKey] = zeroBSCRM_locale_dateToUTS($retArray[$outputPrefix.$fieldKey],true); } $retArray[$outputPrefix.$fieldKey] = preg_replace('@[^0-9]+@i', '-', $retArray[$outputPrefix.$fieldKey]); $retArray[$outputPrefix.$fieldKey] = intval($retArray[$outputPrefix.$fieldKey]); } break; case 'bool': if (isset($arraySource[$fieldPrefix.$fieldKey])) { $retArray[$outputPrefix.$fieldKey] = sanitize_text_field($arraySource[$fieldPrefix.$fieldKey]); $retArray[$outputPrefix.$fieldKey] = preg_replace('@[^0-9]+@i', '-', $retArray[$outputPrefix.$fieldKey]); $retArray[$outputPrefix.$fieldKey] = boolval($retArray[$outputPrefix.$fieldKey]); } break; case 'decimal': if (isset($arraySource[$fieldPrefix.$fieldKey])){ $retArray[$outputPrefix.$fieldKey] = sanitize_text_field($arraySource[$fieldPrefix.$fieldKey]); $retArray[$outputPrefix.$fieldKey] = preg_replace('@[^0-9]+@i', '-', $retArray[$outputPrefix.$fieldKey]); $retArray[$outputPrefix.$fieldKey] = floatval($retArray[$outputPrefix.$fieldKey]); } break; default: // basically str. if (isset($arraySource[$fieldPrefix.$fieldKey])) $retArray[$outputPrefix.$fieldKey] = zeroBSCRM_textProcess($arraySource[$fieldPrefix.$fieldKey]); break; } // / format switch } // / not isset } // / foreach } // / if has model // $removeEmpties if ($removeEmpties){ $ret = array(); foreach ($retArray as $k => $v){ $intV = (int)$v; if (!is_array($v) && !empty($v) && $v != '' && $v !== 0 && $v !== -1 && $intV !== -1){ $ret[$k] = $v; } } $retArray = $ret; } return $retArray; } // generally used for list view reformatting - cleans a contact array into simple format // here it takes an array of contacts, and (currently) returns 1 contact simplified // This may make more sense in the contact DAL obj layer? // >> this has a company variant too, in this file. function zeroBSCRM_getSimplyFormattedContact($contacts=array(),$requireOwner=false){ $return = false; // DAL3 + has potential for multi-links, so here we just grab first if there if (isset($contacts) && is_array($contacts) && count($contacts) > 0){ // first only for now... $contact = $contacts[0]; // w adapted so same func can be used (generic) js side // works with zeroBSCRMJS_listView_generic_customer // provides a simplified ver of customer obj (4 data transit efficiency/exposure) $email = ''; if (isset($contact['email']) && !empty($contact['email'])) $email = $contact['email']; $return = array( 'id' => $contact['id'], 'avatar' => zeroBS_customerAvatar($contact['id']), 'fullname' => zeroBS_customerName('',$contact,false,false), 'email' => $email ); if ($requireOwner) $return['owner'] = zeroBS_getOwner($contact['id'],true,'zerobs_customer'); } return $return; } /* ====================================================== / GENERIC helpers ====================================================== */ /* ====================================================== Company helpers ====================================================== */ function zeroBS___________CompanyHelpers(){return;} #} Get the COUNT of companies. function zeroBS_companyCount($status=false){ global $zbs; return $zbs->DAL->companies->getCompanyCount(array( 'withStatus'=> $status, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_COMPANY))); } // another func which should be skipped 3.0+, just do direct call :) function zeroBS_getCompany($coID=-1,$withObjs=false){ if ($coID !== -1){ global $zbs; #} Super rough. Not sure where we use this, but shouldn't. return $zbs->DAL->companies->getCompany($coID,array( 'withQuotes' => $withObjs, 'withInvoices' => $withObjs, 'withTransactions' => $withObjs, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_COMPANY)) ); } return false; } #} Wrapper func for "company" type customers // note: $inCountry returns with address 1 or 2 in country (added for logReporter for Miguel (custom extension WH)) // note: $withStatus returns with specific status (added for logReporter for Miguel (custom extension WH)) #} Adapted for 3.0+, note deprecated really, should be using DAL->companies->getCompanies directly function zeroBS_getCompanies( $withFullDetails=false, $perPage=10, $page=0, $searchPhrase='', $argsOverride=false, $withInvoices=false, $withQuotes=false, $withTransactions=false, $inCountry=false, $ownedByID=false, $withStatus=false, $inArr=false ){ // $withFullDetails = irrelevant with new DB2 (always returns) // $argsOverride CAN NO LONGER WORK :) if ($argsOverride !== false) zeroBSCRM_DEPRECATEDMSG('Use of $argsOverride in zeroBS_getCompanies is no longer relevant (DAL3.0)'); global $zbs; // legacy from dal1 $actualPage = $page; if ($zbs->isDAL1()) $actualPage = $page-1; // only DAL1 needed this if ($actualPage < 0) $actualPage = 0; // make ARGS $args = array( // Search/Filtering (leave as false to ignore) 'searchPhrase' => $searchPhrase, 'inArr' => $inArr, 'inCountry' => $inCountry, 'hasStatus' => $withStatus, 'ownedBy' => $ownedByID, 'withCustomFields' => true, 'withQuotes' => $withQuotes, 'withInvoices' => $withInvoices, 'withTransactions' => $withTransactions, 'withLogs' => false, 'withLastLog' => false, 'withTags' => false,//$withTags, 'withOwner' => false, //'sortByField' => $sortByField, //'sortOrder' => $sortOrder, 'page' => $actualPage, 'perPage' => $perPage, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_COMPANY) ); // here ignore owners = true the default, because we're not really forcing ownership anywhere overall, // when we do, we should change this/make it check if ($ownedByID !== false && is_int($ownedByID) && $ownedByID > 0) { $args['ignoreowner'] = false; } return $zbs->DAL->companies->getCompanies($args); } // returns email for a company function zeroBS_companyEmail($companyID='',$companyArr=false){ global $zbs; return $zbs->DAL->companies->getCompanyEmail($companyID); } /** * Retrieves the company ID based on its name. * * @param string $company_name The name of the company for which the ID is required. * @return int|bool Returns the ID of the company if found, false otherwise. */ function zeroBS_getCompanyIDWithName( $company_name = '' ) { if ( ! empty( $company_name ) ) { global $zbs; return $zbs->DAL->companies->get_company_id_by_name( $company_name ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase } return false; } #} ExternalID is name in this case :) function zeroBS_getCompanyIDWithExternalSource($externalSource='',$externalID=''){ global $zbs; #} No empties, no random externalSources :) if (!empty($externalSource) && !empty($externalID) && array_key_exists($externalSource,$zbs->external_sources)){ #} If here, is legit. $approvedExternalSource = $externalSource; global $zbs; return $zbs->DAL->companies->getCompany(-1,array( 'externalSource' => $approvedExternalSource, 'externalSourceUID' => $externalID, 'onlyID' => true, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_COMPANY) )); } return false; } // This should probably be deprecated and just called directly. // for now just translating function zeroBS_getCompaniesForTypeahead($searchQueryStr=''){ /* //gets them all, from a brutal SQL global $wpdb; if (!empty($searchQueryStr)){ // param query $sql = "SELECT ID as id, post_title as name, post_date as created FROM $wpdb->posts WHERE post_type = 'zerobs_company' AND post_status = 'publish' AND post_title LIKE %s"; $q = $wpdb->prepare($sql,'%'.$searchQueryStr.'%'); $results = $wpdb->get_results($q, ARRAY_A); } else { // straight query $sql = "SELECT ID as id, post_title as name, post_date as created FROM $wpdb->posts WHERE post_type = 'zerobs_company' AND post_status = 'publish'"; $results = $wpdb->get_results($sql, ARRAY_A); } return $results; */ global $zbs; return $zbs->DAL->companies->getCompanies(array( 'searchPhrase' => $searchQueryStr, 'simplified' => true, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_COMPANY) )); } function zeroBS_getCompanyIDWithEmail($custEmail=''){ if (!empty($custEmail)){ global $zbs; return $zbs->DAL->companies->getCompany(-1,array( 'email' => $custEmail, 'onlyID' => true, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_COMPANY) )); } return false; } #} Add or Update a Company - ideally use $zbs->DAL->companies->addUpdateCompany() rather than this wrapper, in proper code now :) function zeroBS_addUpdateCompany( $coID = -1, $coFields = array(), $externalSource='', $externalID='', $companyDate='', $fallBackLog = false, $extraMeta = false, $automatorPassthrough = false, $owner = -1, $metaBuilderPrefix = 'zbsc_' ){ #} Basics - /--needs status #} 27/09/16 - WH - Removed need for zeroBS_addUpdateCustomer to have a "status" passed with customer (defaults to lead for now if not present) if (isset($coFields) && count($coFields) > 0){ #} && isset($coFields['zbsc_status']) global $zbs; #} New flag $newCompany = false; $existingMeta = array(); if ($coID > 0){ #} Build "existing meta" to pass, (so we only update fields pushed here) $existingMeta = $zbs->DAL->companies->getCompany($coID,array()); #} need to check the dates here. If a date is passed which is BEFORE the current "created" date then overwrite the date with the new date. If a date is passed which is AFTER the current "created" date, then do not update the date.. #} date changed - created is only in the wp_posts table in DB v1.0 $originalDate = time(); if (isset($existingMeta) && is_array($existingMeta) && isset($existingMeta['created']) && !empty($existingMeta['created'])) $originalDate = $existingMeta['created']; if (!empty($companyDate) && $companyDate != ''){ #} DATE PASSED TO THE FUNCTION $companyDateTimeStamp = strtotime($companyDate); #} ORIGINAL POST CREATION DATE // no need, db2 = UTS $originalDateTimeStamp = strtotime($originalDate); $originalDateTimeStamp = $originalDate; #} Compare, if $companyDateTimeStamp < then update with passed date if($companyDateTimeStamp < $originalDateTimeStamp){ // straight in there :) $zbs->DAL->companies->addUpdateCompany(array( 'id' => $coID, 'limitedFields' =>array( array('key'=>'zbsco_created','val'=>$companyDateTimeStamp,'type'=>'%d') ))); } } // WH changed 20/05/18 // 20/05/18 - Previously this would reload the EXISTING database data // THEN 'override' any passed fields // THEN save that down // ... this was required when we used old meta objs. (pre db2) // ... so if we're now DAL2, we can do away with that and simply pass what's to be updated and mode do_not_update_blanks $existingMeta = array(); } else { #} Set flag $newCompany = true; if (!empty($companyDate)){ #} DATE PASSED TO THE FUNCTION $companyDateTimeStamp = strtotime($companyDate); if ($companyDateTimeStamp > 0) $existingMeta = array('created' => $companyDateTimeStamp); } } #} Build using centralised func below, passing any existing meta (updates not overwrites) $zbsCompanyMeta = zeroBS_buildCompanyMeta($coFields,$existingMeta,$metaBuilderPrefix,'',true); $we_have_tags = false; //set to false.. duh.. # TAG company (if exists) - clean etc here too if (!empty($coFields['tags'])){ $tags = $coFields['tags']; #} Santize tags if(is_array($tags) && count($tags) > 0){ $company_tags = filter_var_array($tags,FILTER_UNSAFE_RAW); // Formerly this used FILTER_SANITIZE_STRING, which is now deprecated as it was fairly broken. This is basically equivalent. // @todo Replace this with something more correct. foreach ( $company_tags as $k => $v ) { $company_tags[$k] = strtr( strip_tags( $v ), array( "\0" => '', '"' => '&#34;', "'" => '&#39;', "<" => '', ) ); } $we_have_tags = true; } if ( $we_have_tags ) { $zbsCompanyMeta['tags'] = array(); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase foreach ( $company_tags as $tag_name ) { // Check for existing tag under this name. $tag_id = $zbs->DAL->getTag( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -1, array( 'objtype' => ZBS_TYPE_COMPANY, 'name' => $tag_name, 'onlyID' => true, ) ); // If tag doesn't exist, create one. if ( empty( $tag_id ) ) { $tag_id = $zbs->DAL->addUpdateTag( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase array( 'data' => array( 'objtype' => ZBS_TYPE_COMPANY, 'name' => $tag_name, ), ) ); } // Add tag to list. if ( ! empty( $tag_id ) ) { $zbsCompanyMeta['tags'][] = $tag_id; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } } } } #} Add external source/externalid #} No empties, no random externalSources :) $extSourceArr = -1; $approvedExternalSource = ''; #} As this is passed to automator :) if (!empty($externalSource) && !empty($externalID) && array_key_exists($externalSource,$zbs->external_sources)){ #} If here, is legit. $approvedExternalSource = $externalSource; #} Add/Update record flag // 2.4+ Migrated away from this method to new update_post_meta($postID, 'zbs_customer_ext_'.$approvedExternalSource, $externalID); // 2.52+ Moved to new DAL method :) $extSourceArr = array( 'source' => $approvedExternalSource, 'uid' => $externalID ); // add/update // DB2, this is just used below :)zeroBS_updateExternalSource($postID,$extSourceArr); $zbsCompanyMeta['externalSources'] = array($extSourceArr); } #} Otherwise will just be a random customer no ext source #} Got owner? if ($owner !== -1) $zbsCompanyMeta['owner'] = $owner; #} Update record (All IA is now fired intrinsicly ) return $zbs->DAL->companies->addUpdateCompany(array( 'id' => $coID, 'data' => $zbsCompanyMeta, 'extraMeta' => $extraMeta, 'automatorPassthrough' => $automatorPassthrough, 'fallBackLog' => $fallBackLog )); } // if fields return false; } // v3.0+ this uses the generic zeroBS_buildObjArr, and accepts full args as per contact meta DAL2: function zeroBS_buildCompanyMeta($arraySource=array(),$startingArray=array(),$fieldPrefix='zbsco_',$outputPrefix='',$removeEmpties=false,$autoGenAutonumbers=false){ return zeroBS_buildObjArr($arraySource,$startingArray,$fieldPrefix,$outputPrefix,$removeEmpties,ZBS_TYPE_COMPANY,$autoGenAutonumbers); } /* Centralised delete company func, including sub-element removal */ function zeroBS_deleteCompany($id=-1,$saveOrphans=true){ if (!empty($id)){ global $zbs; return $zbs->DAL->companies->deleteCompany(array('id'=>$id,'saveOrphans'=>$saveOrphans)); } return false; } // adapted company name builder to use proper DAL3 func function zeroBS_companyName($companyID='',$companyArr=array(),$incFirstLineAddr=true,$incID=true){ global $zbs; return $zbs->DAL->companies->getCompanyNameEtc($companyID,$companyArr,array( 'incFirstLineAddr' => $incFirstLineAddr, 'incID' => $incID )); } // adapted company name builder to use proper DAL3 func function zeroBS_companyAddr($companyID='',$companyArr=array(),$addrFormat = 'short',$delimiter= ', '){ global $zbs; return $zbs->DAL->companies->getCompanyAddress($companyID,$companyArr,array( 'addrFormat' => $addrFormat, 'delimiter' => $delimiter )); } // adapted company name builder to use proper DAL3 func function zeroBS_companySecondAddr($companyID='',$companyArr=array(),$addrFormat = 'short',$delimiter= ', '){ global $zbs; return $zbs->DAL->companies->getCompany2ndAddress($companyID,$companyArr,array( 'addrFormat' => $addrFormat, 'delimiter' => $delimiter )); } // get owner of co - use proper DAL ver plz, not this forwards. function zeroBS_getCompanyOwner($companyID=-1){ if ($companyID !== -1){ global $zbs; return $zbs->DAL->companies->getCompanyOwner($companyID); } return false; } // sets tags, in future just use direct DAL func plz function zeroBSCRM_setCompanyTags($coID=-1,$tags=array(),$tagIDs=array(),$mode='replace'){ if ($coID > 0){ $args = array( 'id' => $coID, // EITHER of the following: //'tagIDs' => -1, //'tags' => -1, 'mode' => $mode ); // got tags? if (is_array($tags) && count($tags) > 0) $args['tags'] = $tags; else if (is_array($tagIDs) && count($tagIDs) > 0) $args['tagIDs'] = $tagIDs; else return false; global $zbs; return $zbs->DAL->companies->addUpdateCompanyTags($args); } return false; } // gets tags, in future just use direct DAL func plz function zeroBSCRM_getCompanyTagsByID($coID=-1,$justIDs=false){ global $zbs; $tags = $zbs->DAL->companies->getCompanyTags($coID); // lazy here, but shouldn't use these old funcs anyhow! if ($justIDs){ $ret = array(); if (is_array($tags)) foreach ($tags as $t) $ret[] = $t['id']; return $ret; } return $tags; } // generally used for list view reformatting - cleans a company array into simple format // here it takes an array of contacts, and (currently) returns 1 company simplified // This may make more sense in the company DAL obj layer? // >> this has a contact variant too, in this file. function zeroBSCRM_getSimplyFormattedCompany($companies=array(),$requireOwner=false){ $return = false; // DAL3 + has potential for multi-links, so here we just grab first if there if (isset($companies) && is_array($companies) && count($companies) > 0){ // first only for now... $company = $companies[0]; // w adapted so same func can be used (generic) js side // works with zeroBSCRMJS_listView_generic_customer // provides a simplified ver of customer obj (4 data transit efficiency/exposure) $email = ''; if (isset($company['email']) && !empty($company['email'])) $email = $company['email']; $return = array( // company only has name, id, email currently 'id' => $company['id'], //'avatar' => zeroBS_customerAvatar($company['id']), 'fullname' => $company['name'], 'email' => $email ); if ($requireOwner) $return['owner'] = zeroBS_getOwner($company['id'],true,'zerobs_company'); } return $return; } /* ====================================================== / Company helpers ====================================================== */ /* ====================================================== Quote helpers ====================================================== */ function zeroBS___________QuoteHelpers(){return;} // returns count, inc status optionally function zeroBS_quoCount($status=false){ global $zbs; return $zbs->DAL->quotes->getQuoteCount(array( 'withStatus'=> $status, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_QUOTE))); } # Quote Status (from list view) // WH note - not sure why we're building HTML here, allowing for now. // if returnAsInt - will return -1 for not published, -2 for not accepted, or 14int timestamp for accepted function zeroBS_getQuoteStatus( $item=false, $returnAsInt=false ) { #} marked accepted? $accepted = false; if (is_array($item) && isset($item['accepted'])) $accepted = $item['accepted']; # HERE TODO: # if acceptedArr = output "accepted xyz" # else if !templated outut "not yet published" # else if templated output "not yet accepted" if ($accepted > 0){ if ($returnAsInt) return $accepted; $td = '<strong>'.__('Accepted',"zero-bs-crm").' ' . date(zeroBSCRM_getDateFormat(),$accepted) . '</strong>'; } else { #} get extra deets $zbsTemplated = $item['template']; if (!empty($zbsTemplated)) { if ($returnAsInt) return -2; #} is published $td = '<strong>'.__('Created, not yet accepted',"zero-bs-crm").'</strong>'; } else { if ($returnAsInt) return -1; #} not yet published $td = '<strong>'.__('Not yet published',"zero-bs-crm").'</strong>'; } } return $td; } // Get next available sequential quote ID function zeroBSCRM_getNextQuoteID(){ #} Retrieves option, and returns, is dumb for now. // DAL1+2: return (int)get_option('quoteindx',$defaultStartingQuoteID)+1; // DAL3: $potential = (int)zeroBSCRM_getSetting('quoteindx',true); if ($potential > 0) return $potential+1; else return zeroBSCRM_getQuoteOffset()+1; } // set the current max used quoteid function zeroBSCRM_setMaxQuoteID($newMax=0){ $existingMax = zeroBSCRM_getNextQuoteID(); if ($newMax >= $existingMax){ // DAL3: global $zbs; return $zbs->settings->update('quoteindx',$newMax); } return false; } #} Minified get offset func function zeroBSCRM_getQuoteOffset(){ global $zbs; $offset = (int)$zbs->settings->get('quoteoffset'); if (empty($offset) || $offset < 0) $offset = 0; return $offset; } #} Get the content of a quote: function zeroBS_getQuoteBuilderContent($qID=-1){ global $zbs; //return $zbs->DAL->quotes->getQuoteContent($qID); // kept in old format for continued support return array( 'content' => $zbs->DAL->quotes->getQuoteContent($qID), 'template_id' => -1 ); /* replaced by this really: getQuoteContent() if ($qID !== -1){ $content = get_post_meta($qID, 'zbs_quote_content' , true ) ; $content = htmlspecialchars_decode($content, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401); return array( 'content'=>$content, 'template_id' => get_post_meta($qID, 'zbs_quote_template_id' , true ) ); } else return false; */ } #} Old get func, use proper form if writing fresh code // used to return array('id','meta','customerid','quotebuilder') // ... so any existing use may be broken (have mass replaced in core at this point) // ... use direct ->getQuotes in future anyhow. // (which is diff format! any use of zeroBS_getQuote is now borked. - couldn't find any though + did proper search.) function zeroBS_getQuote($qID=-1,$withQuoteBuilderData=false){ if ($qID !== -1){ global $zbs; #} Super rough. Not sure where we use this, but shouldn't. return $zbs->DAL->quotes->getQuote($qID,array( 'withLineItems' => $withQuoteBuilderData, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_QUOTE)) ); } return false; } #} Marks a quote as "accepted" and saves as much related data as poss on accepter // again, use DAL to do this in future (zbs->DAL->quotes->addUpdateQuoteStatus directly) function zeroBS_markQuoteAccepted($qID=-1,$quoteSignedBy=''){ if ($qID !== -1){ global $zbs; return $zbs->DAL->quotes->addUpdateQuoteAccepted(array( 'id' => $qID, 'accepted' => time(), 'signedby' => $quoteSignedBy, 'ip' => zeroBSCRM_getRealIpAddr() )); } return false; } #} UNMarks a quote as "accepted" and saves as much related data as poss on accepter // again, use DAL to do this in future (zbs->DAL->quotes->addUpdateQuoteStatus directly) function zeroBS_markQuoteUnAccepted($qID=-1){ if ($qID !== -1){ global $zbs; return $zbs->DAL->quotes->addUpdateQuoteAccepted(array( 'id' => $qID, 'accepted' => '' )); } return false; } // Please use direct dal calls in future work. function zeroBS_getQuotes( $withFullDetails=false, $perPage=10, $page=0, $withCustomerDeets=false, $searchPhrase='', $inArray=array(), $sortByField='', $sortOrder='DESC', $quickFilters=array(), $hasTagIDs=array() ){ // $withFullDetails = irrelevant with new DB2 (always returns) global $zbs; // legacy from dal1 $actualPage = $page; if ($zbs->isDAL1()) $actualPage = $page-1; // only DAL1 needed this if ($actualPage < 0) $actualPage = 0; // make ARGS $args = array( // Search/Filtering (leave as false to ignore) 'searchPhrase' => $searchPhrase, 'inArr' => $inArray, 'quickFilters' => $quickFilters, 'isTagged' => $hasTagIDs, 'withAssigned' => $withCustomerDeets, 'sortByField' => $sortByField, 'sortOrder' => $sortOrder, 'page' => $actualPage, 'perPage' => $perPage, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_QUOTE) ); return $zbs->DAL->quotes->getQuotes($args); } // Please use direct dal calls in future work. function zeroBS_getQuotesCountIncParams( $withFullDetails=false, $perPage=10, $page=0, $withCustomerDeets=false, $searchPhrase='', $inArray=array(), $sortByField='', $sortOrder='DESC', $quickFilters=array(), $hasTagIDs=array() ){ // $withFullDetails = irrelevant with new DB2 (always returns) global $zbs; // legacy from dal1 $actualPage = $page; if ($zbs->isDAL1()) $actualPage = $page-1; // only DAL1 needed this if ($actualPage < 0) $actualPage = 0; // make ARGS $args = array( // Search/Filtering (leave as false to ignore) 'searchPhrase' => $searchPhrase, 'inArr' => $inArray, 'quickFilters' => $quickFilters, 'isTagged' => $hasTagIDs, // just count thx 'count' => true, 'withAssigned' => false, //'sortByField' => $sortByField, //'sortOrder' => $sortOrder, 'page' => -1, 'perPage' => -1, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_QUOTE) ); return $zbs->DAL->quotes->getQuotes($args); } // Please use direct dal calls in future work. function zeroBS_getQuotesForCustomer( $customerID=-1, $withFullDetails=false, $perPage=10, $page=0, $withCustomerDeets=false, $withQuoteBuilderData=true ){ global $zbs; // legacy from dal1 $actualPage = $page; if ($zbs->isDAL1()) $actualPage = $page-1; // only DAL1 needed this if ($actualPage < 0) $actualPage = 0; // make ARGS $args = array( // Search/Filtering (leave as false to ignore) 'assignedContact' => $customerID, // with contact? 'withAssigned' => $withCustomerDeets, 'sortByField' => 'ID', 'sortOrder' => 'DESC' , 'page' => $actualPage, 'perPage' => $perPage, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_QUOTE) ); return $zbs->DAL->quotes->getQuotes($args); } // Please use direct dal calls in future work. function zeroBS_getQuotesForCompany( $companyID=-1, $withFullDetails=false, $perPage=10, $page=0, $withCustomerDeets=false, $withQuoteBuilderData=true ){ global $zbs; // legacy from dal1 $actualPage = $page; if ($zbs->isDAL1()) $actualPage = $page-1; // only DAL1 needed this if ($actualPage < 0) $actualPage = 0; // make ARGS $args = array( // Search/Filtering (leave as false to ignore) 'assignedCompany' => $companyID, // with contact? 'withAssigned' => $withCustomerDeets, 'sortByField' => $orderBy, 'sortOrder' => $order, 'page' => $actualPage, 'perPage' => $perPage, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_QUOTE) ); return $zbs->DAL->quotes->getQuotes($args); } // Please use direct dal calls in future work. function zeroBS_getQuoteTemplate($quoteTemplateID=-1){ if ($quoteTemplateID > 0){ /* return array( 'id'=>$tID, 'meta'=>get_post_meta($tID, 'zbs_quotemplate_meta', true), 'zbsdefault'=>get_post_meta($tID, 'zbsdefault', true), 'content'=> get_post_field('post_content', $tID) #http://wordpress.stackexchange.com/questions/9667/get-wordpress-post-content-by-post-id ); */ global $zbs; return $zbs->DAL->quotetemplates->getQuotetemplate($quoteTemplateID); } return false; } // Please use direct dal calls in future work. function zeroBS_getQuoteTemplates($withFullDetails=false,$perPage=10,$page=0,$searchPhrase=''){ global $zbs; return $zbs->DAL->quotetemplates->getQuotetemplates(array( 'searchPhrase' => $searchPhrase, 'page' => $page, 'perPage' => $perPage, 'checkDefaults' => true )); /* was returning core post + $retObj['meta'] = get_post_meta($ele->ID, 'zbs_quotemplate_meta', true); $retObj['zbsdefault'] = get_post_meta($ele->ID, 'zbsdefault', true); */ } // retrieves a count for listview retrievedata, really function zeroBS_getQuoteTemplatesCountIncParams($withFullDetails=false,$perPage=10,$page=0,$searchPhrase=''){ global $zbs; return $zbs->DAL->quotetemplates->getQuotetemplates(array( 'searchPhrase' => $searchPhrase, 'count' => 1, 'page' => -1, 'perPage' => -1, )); } // moves a quote from being assigned to one cust, to another // this is a fill-in to match old DAL2 func, however DAL3+ can accept customer/company, // ... so use the proper $DAL->addUpdateObjectLinks for fresh code function zeroBSCRM_changeQuoteCustomer($id=-1,$contactID=0){ if (!empty($id) && $contactID > 0){ global $zbs; return $zbs->DAL->quotes->addUpdateObjectLinks($id,array($contactID),ZBS_TYPE_CONTACT); } return false; } /* ====================================================== / Quote helpers ====================================================== */ /* ====================================================== Invoice helpers ====================================================== */ function zeroBS___________InvoiceHelpers(){return;} // returns count, inc status optionally function zeroBS_invCount($status=false){ global $zbs; return $zbs->DAL->invoices->getInvoiceCount(array( 'withStatus'=> $status, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_INVOICE))); } // Get next available sequential invoice ID function zeroBSCRM_getNextInvoiceID(){ // DAL3: $potential = (int)zeroBSCRM_getSetting('invoiceindx',true); if ($potential > 0) { return $potential+1; } else { return zeroBSCRM_getInvoiceOffset()+1; } } // set the current max used invid function zeroBSCRM_setMaxInvoiceID($newMax=0){ $existingMax = zeroBSCRM_getNextInvoiceID(); if ($newMax >= $existingMax){ // DAL3: global $zbs; return $zbs->settings->update('invoiceindx',$newMax); } return false; } // Minified get offset func function zeroBSCRM_getInvoiceOffset(){ global $zbs; // this only exists on legacy sites $offset = (int)$zbs->settings->get( 'invoffset' ); if ( empty($offset) || $offset < 0 ) { $offset = 0; } return $offset; } // outdated, outmoded, use proper ->DAL calls not this in fresh code function zeroBS_getInvoices( $withFullDetails=false, $perPage=10, $page=0, $withCustomerDeets=false, $searchPhrase='', $inArray=array(), $sortByField='', $sortOrder='DESC', $quickFilters=array(), $hasTagIDs=array() ){ // $withFullDetails = irrelevant with new DB2 (always returns) global $zbs; // legacy from dal1 $actualPage = $page; if ($zbs->isDAL1()) $actualPage = $page-1; // only DAL1 needed this if ($actualPage < 0) $actualPage = 0; // make ARGS $args = array( // Search/Filtering (leave as false to ignore) 'searchPhrase' => $searchPhrase, 'inArr' => $inArray, 'quickFilters' => $quickFilters, 'isTagged' => $hasTagIDs, 'withAssigned' => $withCustomerDeets, 'sortByField' => $sortByField, 'sortOrder' => $sortOrder, 'page' => $actualPage, 'perPage' => $perPage, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_INVOICE) ); return $zbs->DAL->invoices->getInvoices($args); } // outdated, outmoded, use proper ->DAL calls not this in fresh code function zeroBS_getInvoicesCountIncParams( $withFullDetails=false, $perPage=10, $page=0, $withCustomerDeets=false, $searchPhrase='', $inArray=array(), $sortByField='', $sortOrder='DESC', $quickFilters=array(), $hasTagIDs=array() ){ // $withFullDetails = irrelevant with new DB2 (always returns) global $zbs; // legacy from dal1 $actualPage = $page; if ($zbs->isDAL1()) $actualPage = $page-1; // only DAL1 needed this if ($actualPage < 0) $actualPage = 0; // make ARGS $args = array( // Search/Filtering (leave as false to ignore) 'searchPhrase' => $searchPhrase, 'inArr' => $inArray, 'quickFilters' => $quickFilters, 'isTagged' => $hasTagIDs, // just count thx 'count' => true, 'withAssigned' => false, //'sortByField' => $sortByField, //'sortOrder' => $sortOrder, 'page' => -1, 'perPage' => -1, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_INVOICE) ); return $zbs->DAL->invoices->getInvoices($args); } // DAL3 translated. // invs model now looks diff so adapt everywhere with getInvoice function zeroBS_getInvoice($invoiceID=-1){ if ($invoiceID > 0){ /* return array( 'id'=>(int)$wpPostID, 'meta'=>get_post_meta($wpPostID, 'zbs_customer_invoice_meta', true), 'customerid'=>get_post_meta($wpPostID, 'zbs_customer_invoice_customer', true), 'zbsid'=>get_post_meta($wpPostID, 'zbsid', true) ); */ global $zbs; return $zbs->DAL->invoices->getInvoice($invoiceID); } return false; } // wh quick shim - checks if (Contact) has any invoices efficiently function zeroBS_contactHasInvoice($contactID=-1){ if ($contactID > 0){ global $zbs; return $zbs->DAL->contacts->contactHasInvoice($contactID); } return false; } // just do direct call in future, plz function zeroBS_getInvoicesForCustomer( $customerID=-1, $withFullDetails=false, $perPage=10, $page=0, $withCustomerDeets=false, $orderBy='ID', $order='DESC' ){ // $withFullDetails = irrelevant with new DB2 (always returns) global $zbs; // legacy from dal1 $actualPage = $page; if ($zbs->isDAL1()) $actualPage = $page-1; // only DAL1 needed this if ($actualPage < 0) $actualPage = 0; // make ARGS $args = array( // Search/Filtering (leave as false to ignore) 'assignedContact' => $customerID, // with contact? 'withAssigned' => $withCustomerDeets, 'sortByField' => $orderBy, 'sortOrder' => $order, 'page' => $actualPage, 'perPage' => $perPage, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_INVOICE) ); return $zbs->DAL->invoices->getInvoices($args); } // just do direct call in future, plz function zeroBS_getInvoicesForCompany( $companyID=-1, $withFullDetails=false, $perPage=10, $page=0, $withCustomerDeets=false, $orderBy='post_date', $order='DESC' ){ // $withFullDetails = irrelevant with new DB2 (always returns) global $zbs; // legacy from dal1 $actualPage = $page; if ($zbs->isDAL1()) $actualPage = $page-1; // only DAL1 needed this if ($actualPage < 0) $actualPage = 0; // make ARGS $args = array( // Search/Filtering (leave as false to ignore) 'assignedCompany' => $companyID, // with contact? 'withAssigned' => $withCustomerDeets, 'sortByField' => $orderBy, 'sortOrder' => $order, 'page' => $actualPage, 'perPage' => $perPage, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_INVOICE) ); return $zbs->DAL->invoices->getInvoices($args); } // WH adapted to DAL3 function zeroBS_getTransactionsForInvoice($invID=-1){ global $zbs; return $zbs->DAL->transactions->getTransactions(array('assignedInvoice'=>$invID,'perPage'=>1000,'ignoreowner'=>zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_TRANSACTION))); /* think this was probably faulty, as it seems to always return 1 id? ... presume want array of transactions, so returning that :) global $wpdb; $ret = false; #} No empties, no validation, either. if (!empty($invID)){ #} Will find the post, if exists, no dealing with dupes here, yet? $sql = $wpdb->prepare("select post_id from $wpdb->postmeta where meta_value = '%d' And meta_key='zbs_invoice_partials'", $invID); $potentialTransactionList = $wpdb->get_results($sql); if (count($potentialTransactionList) > 0){ if (isset($potentialTransactionList[0]) && isset($potentialTransactionList[0]->post_id)){ $ret = $potentialTransactionList[0]->post_id; } } } return $ret; */ } // moves a inv from being assigned to one cust, to another // this is a fill-in to match old DAL2 func, however DAL3+ can accept customer/company, // ... so use the proper $DAL->addUpdateObjectLinks for fresh code function zeroBSCRM_changeInvoiceCustomer($id=-1,$contactID=0){ if (!empty($id) && $contactID > 0){ global $zbs; return $zbs->DAL->invoices->addUpdateObjectLinks($id,array($contactID),ZBS_TYPE_CONTACT); } return false; } // grabs invoice customer function zeroBSCRM_getInvoiceCustomer($invID=-1){ if (!empty($invWPID)){ global $zbs; return $zbs->DAL->invoices->getInvoiceContact($invID); } return false; } // updates a stauts, if inv exists. // use $zbs->DAL->invoices->setInvoiceStatus($invoiceID,$statusStr); for new code function zeroBS_updateInvoiceStatus($invoiceID=-1,$statusStr='Draft'){ if ( in_array( $statusStr, zeroBSCRM_getInvoicesStatuses() ) ){ $potentialInvoice = zeroBS_getInvoice($invoiceID); if (isset($potentialInvoice) && is_array($potentialInvoice)){ // dal3 global $zbs; return $zbs->DAL->invoices->setInvoiceStatus($invoiceID,$statusStr); } } return false; } /* ====================================================== Invoice 3.0 helpers ====================================================== */ function zeroBS___________InvoiceV3Helpers(){return;} // this function probably becomes defunct when DAL ready. Is cos right now, if invoice_meta = '' then it's a new invoice, so should return defaults. function zeroBSCRM_get_invoice_defaults( $obj_id = -1 ) { // Settings $settings = zeroBSCRM_get_invoice_settings(); $now = time(); $default_date = jpcrm_uts_to_date_str( $now, 'Y-m-d' ); // If it has reference as autonumber, determine next number. if ( $settings['reftype'] === 'autonumber' ) { $next_number = $settings['refnextnum']; $prefix = $settings['refprefix']; $suffix = $settings['refsuffix']; $id_override = $prefix . $next_number . $suffix; } else { $id_override = $settings['defaultref']; } $defaults = array( 'status' => 'Draft', 'status_label' => __( 'Draft', 'zero-bs-crm' ), 'new_invoice' => true, 'id' => $obj_id, 'invoice_items' => array(), 'invoice_hours_or_quantity' => 'quantity', 'invoice_contact' => -1, 'invoice_company' => -1, 'id_override' => $id_override, 'date_date' => $default_date, // need to sort this out on the way out (in TS to outputtable date for Date Picker) 'date' => $now, 'due' => 0, 'hash' => zeroBSCRM_hashes_GetHashForObj( $obj_id, ZBS_TYPE_INVOICE ), 'logo_url' => $settings['logo'], 'bill' => '', 'bill_name' => '', 'settings' => $settings, 'product_index' => zeroBSCRM_getProductIndex(), 'preview_link' => '/invoices/hash', 'pdf_installed' => zeroBSCRM_isExtensionInstalled( 'pdfinv' ), 'portal_installed' => zeroBSCRM_isExtensionInstalled( 'portal' ), 'totals' => array( 'invoice_discount_total' => 0, 'invoice_discount_type' => '%', 'invoice_postage_total' => 0, ), ); return $defaults; } #} wrapper as right now it was loading the full settings into the page. Tidy up page to have the translations here. #} WH - is it possible that some languages here will mess with the output? character encoding wise? function zeroBSCRM_get_invoice_settings(){ global $zbs; $all_settings = $zbs->settings->getAll(); $reference_label = zbs_ifAV( $all_settings,'reflabel','' ); if( empty( $reference_label ) ) { $reference_label = __('Reference', 'zero-bs-crm'); } // Check if it is the first invoice $first_invoice = ! $zbs->DAL->invoices->getFullCount(); $invoice_settings = array( 'b2bmode' => zbs_ifAV($all_settings,'companylevelcustomers',false), 'invtax' => zbs_ifAV($all_settings,'invtax',''), 'invpandp' => zbs_ifAV($all_settings,'invpandp',''), 'invdis' => zbs_ifAV($all_settings,'invdis',''), 'logo' => zbs_ifAV($all_settings,'invoicelogourl',''), 'bizname' => zbs_ifAV($all_settings,'businessname',''), 'yourname' => zbs_ifAV($all_settings,'businessyourname',''), 'defaultref' => zbs_ifAV($all_settings,'defaultref',''), 'reftype' => zbs_ifAV($all_settings,'reftype',''), 'refprefix' => zbs_ifAV($all_settings,'refprefix',''), 'refnextnum' => zbs_ifAV($all_settings,'refnextnum',''), 'refsuffix' => zbs_ifAV($all_settings,'refsuffix',''), 'isfirstinv' => $first_invoice, 'invhash' => zbs_ifAV($all_settings,'easyaccesslinks',''), 'hideid' => zbs_ifAV($all_settings,'invid',false), 'businessextra' => nl2br(zeroBSCRM_textExpose(zbs_ifAV($all_settings,'businessextra',''))), 'businessyouremail' => zbs_ifAV($all_settings,'businessyouremail',''), 'businessyoururl' => zbs_ifAV($all_settings,'businessyoururl',''), 'settings_slug' => admin_url("admin.php?page=" . $zbs->slugs['settings']) . "&tab=invbuilder", 'biz_settings_slug' => admin_url("admin.php?page=" . $zbs->slugs['settings']) . "&tab=bizinfo", 'addnewcontacturl' => jpcrm_esc_link('create',-1,'zerobs_customer'), 'addnewcompanyurl' => jpcrm_esc_link('create',-1,'zerobs_company'), 'contacturlprefix' => jpcrm_esc_link('edit',-1,'zerobs_customer',true), 'companyurlprefix' => jpcrm_esc_link('edit',-1,'zerobs_company',true), 'lang' => array( 'invoice_number' => zeroBSCRM_slashOut(__('ID', 'zero-bs-crm'),true), 'invoice_date' => zeroBSCRM_slashOut(__('Invoice date', 'zero-bs-crm'),true), 'invoice_status' => zeroBSCRM_slashOut( __( 'Status', 'zero-bs-crm' ), true ), 'status_unpaid' => zeroBSCRM_slashOut( __( 'Unpaid', 'zero-bs-crm' ), true ), 'status_paid' => zeroBSCRM_slashOut( __( 'Paid', 'zero-bs-crm' ), true ), 'status_overdue' => zeroBSCRM_slashOut( __( 'Overdue', 'zero-bs-crm' ), true ), 'status_draft' => zeroBSCRM_slashOut( __( 'Draft', 'zero-bs-crm' ), true ), 'status_deleted' => zeroBSCRM_slashOut( __( 'Deleted', 'zero-bs-crm' ), true ), 'reference' => zeroBSCRM_slashOut( $reference_label,true), 'autogenerated' => zeroBSCRM_slashOut( __('Generated on save', 'zero-bs-crm'),true), 'refsettings' => zeroBSCRM_slashOut( __('Set up your reference type here', 'zero-bs-crm'),true), 'nextref' => zeroBSCRM_slashOut( __('Next reference expected', 'zero-bs-crm'),true), 'due_date' => zeroBSCRM_slashOut(__('Due date', 'zero-bs-crm'),true), 'frequency' => zeroBSCRM_slashOut(__('Frequency', 'zero-bs-crm'),true), 'update' => zeroBSCRM_slashOut(__('Update', 'zero-bs-crm'),true), 'remove' => zeroBSCRM_slashOut(__('Remove', 'zero-bs-crm'),true), 'biz_info' => zeroBSCRM_slashOut(__('Your business information', 'zero-bs-crm'),true), 'add_edit' => zeroBSCRM_slashOut(__('Edit '.jpcrm_label_company().' Details', 'zero-bs-crm'),true), 'add_logo' => zeroBSCRM_slashOut(__('Add your logo', 'zero-bs-crm'),true), 'send_to' => zeroBSCRM_slashOut(__('Assign invoice to', 'zero-bs-crm'),true), 'customise' => zeroBSCRM_slashOut(__('Customise', 'zero-bs-crm'),true), 'hours' => zeroBSCRM_slashOut(__('Hours', 'zero-bs-crm'),true), 'quantity' => zeroBSCRM_slashOut(__('Quantity', 'zero-bs-crm'),true), 'description' => zeroBSCRM_slashOut(__('Description', 'zero-bs-crm'),true), 'price' => zeroBSCRM_slashOut(__('Price', 'zero-bs-crm'),true), 'rate' => zeroBSCRM_slashOut(__('Rate', 'zero-bs-crm'),true), 'tax' => zeroBSCRM_slashOut(__('Tax', 'zero-bs-crm'),true), 'add_row' => zeroBSCRM_slashOut(__('Add row', 'zero-bs-crm'),true), 'remove_row' => zeroBSCRM_slashOut(__('Remove row', 'zero-bs-crm'),true), 'amount' => zeroBSCRM_slashOut(__('Amount', 'zero-bs-crm'),true), 'discount' => zeroBSCRM_slashOut(__('Discount', 'zero-bs-crm'),true), 'shipping' => zeroBSCRM_slashOut(__('Shipping', 'zero-bs-crm'),true), 'tax_on_shipping' => zeroBSCRM_slashOut(__('Tax on shipping', 'zero-bs-crm'),true), 'due' => array( 'none' => zeroBSCRM_slashOut(__('No due date', 'zero-bs-crm'),true), 'on' => zeroBSCRM_slashOut(__('Due on receipt', 'zero-bs-crm'),true), 'ten' => zeroBSCRM_slashOut(__('Due in 10 days', 'zero-bs-crm'),true), 'fifteen' => zeroBSCRM_slashOut(__('Due in 15 days', 'zero-bs-crm'),true), 'thirty' => zeroBSCRM_slashOut(__('Due in 30 days', 'zero-bs-crm'),true), 'fortyfive' => zeroBSCRM_slashOut(__('Due in 45 days', 'zero-bs-crm'),true), 'sixty' => zeroBSCRM_slashOut(__('Due in 60 days', 'zero-bs-crm'),true), 'ninety' => zeroBSCRM_slashOut(__('Due in 90 days', 'zero-bs-crm'),true) ), 'preview' => zeroBSCRM_slashOut(__('Preview', 'zero-bs-crm'),true), 'dl_pdf' => zeroBSCRM_slashOut(__('Download PDF', 'zero-bs-crm'),true), 'bill_to' => zeroBSCRM_slashOut(__('Enter email address or name', 'zero-bs-crm'),true), 'edit_record' => zeroBSCRM_slashOut(__('Edit record', 'zero-bs-crm'),true), 'no_tax' => zeroBSCRM_slashOut(__('None', 'zero-bs-crm'),true), 'taxgrouplabel' => zeroBSCRM_slashOut(__('Rates', 'zero-bs-crm'),true), 'subtotal' => zeroBSCRM_slashOut(__('Subtotal', 'zero-bs-crm'),true), 'total' => zeroBSCRM_slashOut(__('Total', 'zero-bs-crm'),true), 'amount_due' => zeroBSCRM_slashOut(__('Amount due', 'zero-bs-crm'),true), 'partial_table' => zeroBSCRM_slashOut(__('Payments', 'zero-bs-crm'),true), 'incomplete' => zeroBSCRM_slashOut(__('Incomplete', 'zero-bs-crm'),true), 'rowtitleplaceholder' => zeroBSCRM_slashOut(__('Item title', 'zero-bs-crm'),true), 'rowdescplaceholder' => zeroBSCRM_slashOut(__('Item description', 'zero-bs-crm'),true), 'noname' => zeroBSCRM_slashOut(__('Unnamed', 'zero-bs-crm'),true), // no name on typeahead, 'noemail' => zeroBSCRM_slashOut(__('No email', 'zero-bs-crm'),true), // no email on typeahead, 'contact' => zeroBSCRM_slashOut(__('Contact', 'zero-bs-crm'),true), // contact view button (if assigned) 'company' => zeroBSCRM_slashOut(jpcrm_label_company(),true), // contact view button (if assigned) 'view' => zeroBSCRM_slashOut(__('View', 'zero-bs-crm'),true), 'addnewcontact' => zeroBSCRM_slashOut(__('Add new contact', 'zero-bs-crm'),true), 'newcompany' => zeroBSCRM_slashOut(__('new '.jpcrm_label_company(), 'zero-bs-crm'),true), 'or' => zeroBSCRM_slashOut(__('or', 'zero-bs-crm'),true), // send email modal 'send_email' => zeroBSCRM_slashOut(__('Email invoice', 'zero-bs-crm'),true), 'sendthisemail' => zeroBSCRM_slashOut(__('Send this invoice via email:', 'zero-bs-crm'),true), 'toemail' => zeroBSCRM_slashOut(__('To email:', 'zero-bs-crm'),true), 'toemailplaceholder' => zeroBSCRM_slashOut(__('e.g. mike@gmail.com', 'zero-bs-crm'),true), 'attachassoc' => zeroBSCRM_slashOut(__('Attach associated files', 'zero-bs-crm'),true), 'attachpdf' => zeroBSCRM_slashOut(__('Attach as PDF', 'zero-bs-crm'),true), 'sendthemail' => zeroBSCRM_slashOut(__('Send', 'zero-bs-crm'),true), 'sendneedsassignment' => zeroBSCRM_slashOut(__('To send an email, this invoice needs to be assigned to a contact or company with a valid email address.', 'zero-bs-crm'),true), 'sendingemail' => zeroBSCRM_slashOut(__('Sending email...', 'zero-bs-crm'),true), 'senttitle' => zeroBSCRM_slashOut(__('Invoice sent', 'zero-bs-crm'),true), 'sent' => zeroBSCRM_slashOut(__('Your invoice has been sent by email', 'zero-bs-crm'),true), 'senderrortitle' => zeroBSCRM_slashOut(__('Error sending', 'zero-bs-crm'),true), 'senderror' => zeroBSCRM_slashOut(__('There was an error sending this invoice via email.', 'zero-bs-crm'),true), ) ); return $invoice_settings; } #} Invoicing Pro - needs product index // WH: Don't like the lazy naming function zeroBSCRM_getProductIndex(){ $product_index = array(); apply_filters('zbs_product_index_array', $product_index); return $product_index; } // wrapper now for zeroBSCRM_hashes_GetObjFromHash function zeroBSCRM_invoicing_getFromHash($hash = '', $pay = -1){ return zeroBSCRM_hashes_GetObjFromHash($hash,$pay,ZBS_TYPE_INVOICE); } // wrapper now for zeroBSCRM_hashes_GetObjFromHash function zeroBSCRM_quotes_getFromHash($hash = ''){ return zeroBSCRM_hashes_GetObjFromHash($hash,-1,ZBS_TYPE_QUOTE); } // NOTE ON FOLLOWING: // ... this is MS's centralised func which centralises Inv data req. but it's still clunky. // ... here I've shimmed in DAL3 data -> this clunky centralised model. // ... could do with a complete rewrite to use proper DAL3 models tbh. // for now doing what can without taking months over it. /** * This file has the various functions used to control the invoice metaboxes * Wrappers so can be used throughout and switched over when it comes to it * * The current metabox output, has also been changed to draw with JS now given * the added complexity of the tax table and discount per line * * The calculation routine has also been reviewed to calculate the tax due * AFTER the line items discount has been applied * * Drawing a new line was already available in JS, but the initial load (new) and edit * were messily drawn in PHP * * Now it simply stores the invoice meta as one big data JSON structure outlined below * data format described below * * JSON object for invoice * * invoiceObj = { *! invoice_id: 5, // ID in the database - usually the invoice ID. *! invoice_custom_id: -1 // the ID if over-written by settings (WH REMOVED, use id_override) * *! status: paid, // not defined in settings - should be? (draft, unpaid, paid, overdue) * * preview_link: // generated from hash * pdf_dl_link: // downloaded on fly * *! hash: // the invoice hash (for front end accessible pages) * * pdf_template: // the template to use * portal_template: // allow the choice of portal template (0 = default) * email_template: // allow the choice of email template (0 = default) * * invoice_frequency: // invoicing pro only (0 = once only, 1 = week, 2 = month, 3 = year) * * invoice_number: // this is over-ridable in settings * invoice_date: // date of the invoice * invoice_due: // when due -1 (no due date), 0 (on receipt), 10, 15, 30, 45, 60, 90 (days in advance of invoice date) * *! invoice_ref: // internal reference number * * invoice_parent: // invoice pro only (0 for parent), id of parent if child * * invoice_pay_via: // 0 online, 1 bank transfer, 2 (both) - Zak addition to show online payment only for some * * *! invoice_logo_url: // url of the invoice logo (default, or custom per invoice) * invoice_business_details: // the details from settings to go on the invoice (also in settings obj) * * * invoice_send_to: // email to send the invoice to *! invoice_contact: // 0 or contact ID *! invoice_company: // 0 or company ID * invoice_address_to: // 0 contact or 1 company. So if assigned to Mike, can be address to a company (i.e. Mike Stott: Jetpack CRM, Mike Stott: Epic Plugins) etc * * * invoice_hours_or_quantity: 0 for hours, 1 for quantity * * invoice_items: { * item_id: (line_item ID) * order: (order in list, i.e. 0,1,2,3,4,5) * title: * description: * unit: * price: * tax_ids: { * id: 1, rate: 20, * id: 2, rate: 19 * }, * * },{ * * } * * invoice_discount: 0, * invoice_shipping: 0, * invoice_shipping_tax: { * tax_ids:{ * id: 1, rate: 20, * id: 2, rate: 19 * } * }, * * invoice_tip: 0, 1 (allow tip) - not in UI yet * invoice_partial: 0, 1 (allow partial payment) - in UI already (i.e. can assign multiple transactions) need to handle it via checkout (i.e. pay full amount, or pay instalments) * * transactions: { //the transactions against the invoice (array to allow for partial payments) * transaction_id: 5, * amount: 200, * status: paid, * }, * invoice_attachments: { * id: 1, * url: uploaded_url * send: 0,1 * }, * invoice_custom_fields: { * id: 1, * label: "vesting period", * type: "date", * value: "20/10/2019" * }, * //what the invoice settings are (biz info, tax etc) * settings: { * * } * * } * * * tax_linesObj = { * id: * name: (e.g. VAT, GST) * rate: (%) * } */ // this gets the data (from the current DAL and outputs it to the UI) - can get via jQuery // once happy it works and fills the current databse. This will need switching over come // the new DAL database structure but allows me to work with the UI now ahead of time. // wh Centralised, is ultimately output via ajax zeroBSCRM_AJAX_getInvoice function in Control.Invoices // was called zeroBSCRM_getInvoiceData -> zeroBSCRM_invoicing_getInvoiceData function zeroBSCRM_invoicing_getInvoiceData( $invID = -1 ) { global $zbs; $data = array(); // viable id? if ( $invID > 0 ) { // build response $data['invoiceObj'] = array(); $invoice = $zbs->DAL->invoices->getInvoice( $invID, array( // if these two passed, will search based on these 'idOverride' => false, // direcetly checks 1:1 match id_override 'searchPhrase' => false, // more generic, searches id_override (reference) (and not lineitems (toadd?)) 'externalSource' => false, 'externalSourceUID' => false, // with what? 'withLineItems' => true, 'withCustomFields' => true, 'withTransactions' => true, // gets trans associated with inv as well 'withAssigned' => true, // return ['contact'] & ['company'] objs if has link 'withTags' => true, 'withOwner' => true, // returns scalar ID of line 'onlyID' => false, 'fields' => false // false = *, array = fieldnames )); if ( !is_array( $invoice ) ) { // get blank defaults - this is for a de-headed serpent? (don't think should ever exist) $data['invoiceObj'] = zeroBSCRM_get_invoice_defaults( $invID ); } else { // process the loaded data // ... this made a lot of sense Pre DAL3, but much should be dealt with by DAL now // ... wh done best to leave only necessary here: $now = time(); $invoice_date_uts = isset( $invoice['date_date'] ) ? $invoice['date'] : $now; $invoice['date_date'] = jpcrm_uts_to_date_str( $invoice_date_uts, 'Y-m-d' ); $invoice_due_date_uts = isset( $invoice['due_date'] ) ? $invoice['due_date'] : $now; $invoice['due_date_date'] = jpcrm_uts_to_date_str( $invoice_due_date_uts, 'Y-m-d' ); // this should load it all anyhow :) (DAL3+) $data['invoiceObj'] = $invoice; // Settings $settings = zeroBSCRM_get_invoice_settings(); // catch any empty shiz? seems to be what was happening. if ( !isset( $data['invoiceObj']['invoice_logo_url'] ) ) { $data['invoiceObj']['invoice_logo_url'] = $settings['logo']; } // these two are kind of just aliases? Use straight $invoiceObj[contact] etc. $data['invoiceObj']['invoice_contact'] = false; if ( isset( $invoice['contact'] ) && is_array( $invoice['contact'] ) && count( $invoice['contact'] ) > 0 ) { $data['invoiceObj']['invoice_contact'] = $invoice['contact'][0]; } $data['invoiceObj']['invoice_company'] = false; if ( isset( $invoice['company'] ) && is_array( $invoice['company'] ) && count( $invoice['company'] ) > 0 ) { $data['invoiceObj']['invoice_company'] = $invoice['company'][0]; } $data['invoiceObj']['new_invoice'] = false; // these should probs use $invoice['contact'] etc. leaving for now for time. $billing_email = ''; $billing_name = ''; if ( isset( $data['invoiceObj']['invoice_contact'] ) && is_array( $data['invoiceObj']['invoice_contact'] ) && isset( $data['invoiceObj']['invoice_contact']['id'] ) ) { if ( isset( $data['invoiceObj']['invoice_contact']['email'] ) ) { $billing_email = $data['invoiceObj']['invoice_contact']['email']; } if ( isset( $data['invoiceObj']['invoice_contact']['name'] ) ) { $billing_name = $data['invoiceObj']['invoice_contact']['name']; } if ( empty( $billing_name ) ) { $billing_name = $zbs->DAL->contacts->getContactNameWithFallback( $data['invoiceObj']['invoice_contact']['id'] ); } } elseif ( isset( $data['invoiceObj']['invoice_company'] ) && is_array( $data['invoiceObj']['invoice_company'] ) && isset( $data['invoiceObj']['invoice_company']['id'] ) ) { if ( isset( $data['invoiceObj']['invoice_company']['email'] ) ) { $billing_email = $data['invoiceObj']['invoice_company']['email']; } if ( isset( $data['invoiceObj']['invoice_company']['name'] ) ) { $billing_name = $data['invoiceObj']['invoice_company']['name']; } } $data['invoiceObj']['bill'] = $billing_email; //add billing name here $data['invoiceObj']['bill_name'] = $billing_name; //handle if due is not set $data['invoiceObj']['due'] = -1; // default if ( isset( $invoice['due'] ) ) { $data['invoiceObj']['due'] = $invoice['due']; } $data['invoiceObj']['invoice_items'] = $invoice['lineitems']; // needs translating $hoursOrQuantity = (int) $invoice['hours_or_quantity']; // 0 = hours, 1 = quantity $hoursOrQuantityStr = 'hours'; if ( $hoursOrQuantity > 0 ) { $hoursOrQuantityStr = 'quantity'; } $data['invoiceObj']['invoice_hours_or_quantity'] = $hoursOrQuantityStr; // are PDF engine and Client Portal installed? $data['invoiceObj']['pdf_installed'] = zeroBSCRM_isExtensionInstalled( 'pdfinv' ); $data['invoiceObj']['portal_installed'] = zeroBSCRM_isExtensionInstalled( 'portal' ); // if we have Client Portal installed, build URLS $preview_link = null; if ( $data['invoiceObj']['portal_installed'] ) { // Retrieve invoice endpoint & portal root URL $invoice_endpoint = $zbs->modules->portal->get_endpoint( ZBS_TYPE_INVOICE ); $portalLink = zeroBS_portal_link(); if ( ! str_ends_with( $portalLink, '/' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $portalLink .= '/'; } // if invoice has a hash this will be a hash URL, otherwise it uses the invoice ID if ( $settings['invhash'] ) { $preview_link = esc_url( $portalLink . $invoice_endpoint . '/zh-' . $invoice['hash'] ); } else { $preview_link = esc_url( $portalLink . $invoice_endpoint . '/' . $invID ); } } // if a hash is set (or admin) load the invoice for logged out users, if agreed // will still need to load the contactID and info in the Stripe call too even if logged out $data['invoiceObj']['preview_link'] = $preview_link; // urgh. this was how we got the settings object. // refine this too. // SETTINGS array (process from main ZBS settings object) $data['invoiceObj']['settings'] = $settings; // WH shim - converts DAL3 single record attrs into an array as MS expects? $data['invoiceObj']['totals'] = array(); $data['invoiceObj']['totals']['invoice_discount_total'] = $invoice['discount']; $data['invoiceObj']['totals']['invoice_discount_type'] = $invoice['discount_type']; $data['invoiceObj']['totals']['invoice_postage_total'] = $invoice['shipping']; $data['invoiceObj']['totals']['tax'] = $invoice['tax']; // shipping total needs to return 0 in some cases if not set it is empty. GRR @ mike DB1.0 data. if ( !array_key_exists( 'invoice_postage_total', $data['invoiceObj']['totals'] ) ) { $data['invoiceObj']['totals']['invoice_postage_total'] = 0; } // Invoice PARTIALS $data['invoiceObj']['partials'] = $invoice['transactions']; } // update to get from tax table UI. Below is dummy data for UI work (UI tax table TO DO) $data['tax_linesObj'] = zeroBSCRM_getTaxTableArr(); return $data; } return false; } /* ====================================================== / Invoice 3.0 helpers ====================================================== */ #} General function to check the amount due on an invoice, if <= mark as paid. // Adapted to work V3.0+ // ... ultimately just uses zeroBSCRM_invoicing_invOutstandingBalance to check for balance + marks if paid off function zeroBSCRM_check_amount_due_mark_paid($invoice_id=-1){ if ($invoice_id > 0){ global $zbs; $outstandingBalance = $zbs->DAL->invoices->getOutstandingBalance($invoice_id); // got balance? if ($outstandingBalance <= 0 && $outstandingBalance !== false){ // mark invoice as paid $status_str = 'Paid'; $invoice_update = $zbs->DAL->invoices->setInvoiceStatus( $invoice_id, $status_str ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase return $invoice_update; } } return false; } /** * Helper function to calculate the number of deleted invoices for any particular contact / company. * * @param array $all_invoices An array of all invoice or transaction data for a contact / company. * * @returns int An int with the deleted invoices count. */ function jpcrm_deleted_invoice_counts( $all_invoices = null ) { if ( empty( $all_invoices ) ) { return 0; } $count_deleted = 0; foreach ( $all_invoices as $invoice ) { if ( $invoice['status'] === 'Deleted' ) { ++$count_deleted; } } return $count_deleted; } /* ====================================================== / Invoice helpers ====================================================== */ /* ====================================================== Transactions helpers ====================================================== */ function zeroBS___________TransactionHelpers(){return;} // returns count, inc status optionally function zeroBS_tranCount($status=false){ global $zbs; return $zbs->DAL->transactions->getTransactionCount(array( 'withStatus'=> $status, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_TRANSACTION))); } /* This function is only used in one place (the CRM Dashboard). */ function zeroBS_getTransactionsRange($ago=-1, $period='days'){ global $zbs; $utsFrom = strtotime($ago.' '.$period.' ago'); if ($utsFrom > 0){ //this has been replaced with better SQL support now since 4.0.2 return $zbs->DAL->transactions->getTransactions(array( 'newerThan' => $utsFrom, 'sortByField' => 'zbst_date', 'sortOrder' => 'DESC', 'page' => -1, 'perPage' => -1, )); } // nope? return array(); } // Please use direct dal calls in future work. function zeroBS_getTransaction($tID=-1){ if ($tID !== -1){ /* return array( 'id'=>$tID, 'meta'=>get_post_meta($tID, 'zbs_transaction_meta', true), 'customerid'=>get_post_meta($tID, 'zbs_parent_cust', true), 'companyid'=>get_post_meta($tID, 'zbs_parent_co', true) ); */ global $zbs; return $zbs->DAL->transactions->getTransaction($tID); } else return false; } // Please use direct dal calls in future work. function zeroBS_getTransactions( $withFullDetails=false, $perPage=10, $page=0, $withCustomerDeets=false, $searchPhrase='', $hasTagIDs=array(), $inArray=array(), $sortByField='', $sortOrder='DESC', $withTags=false, $quickFilters=array(), $external_source_uid = false ){ // $withFullDetails = irrelevant with new DB2 (always returns) global $zbs; // legacy from dal1 $actualPage = $page; if ($zbs->isDAL1()) $actualPage = $page-1; // only DAL1 needed this if ($actualPage < 0) $actualPage = 0; // make ARGS $args = array( // Search/Filtering (leave as false to ignore) 'searchPhrase' => $searchPhrase, 'inArr' => $inArray, 'isTagged' => $hasTagIDs, 'quickFilters' => $quickFilters, 'withAssigned' => $withCustomerDeets, 'withTags' => $withTags, 'sortByField' => $sortByField, 'sortOrder' => $sortOrder, 'page' => $actualPage, 'perPage' => $perPage, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_TRANSACTION), 'external_source_uid' => $external_source_uid ); return $zbs->DAL->transactions->getTransactions($args); } // Please use direct dal calls in future work. function zeroBS_getTransactionsCountIncParams( $withFullDetails=false, $perPage=10, $page=0, $withCustomerDeets=false, $searchPhrase='', $hasTagIDs=array(), $inArray=array(), $sortByField='', $sortOrder='DESC', $withTags=false, $quickFilters=array() ){ // $withFullDetails = irrelevant with new DB2 (always returns) global $zbs; // legacy from dal1 $actualPage = $page; if ($zbs->isDAL1()) $actualPage = $page-1; // only DAL1 needed this if ($actualPage < 0) $actualPage = 0; // make ARGS $args = array( // Search/Filtering (leave as false to ignore) 'searchPhrase' => $searchPhrase, 'inArr' => $inArray, 'isTagged' => $hasTagIDs, 'quickFilters' => $quickFilters, // just count thx 'count' => true, 'withAssigned' => false, //'sortByField' => $sortByField, //'sortOrder' => $sortOrder, 'page' => -1, 'perPage' => -1, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_TRANSACTION) ); return $zbs->DAL->transactions->getTransactions($args); } // Please use direct dal calls in future work. function zeroBS_getTransactionsForCustomer( $customerID=-1, $withFullDetails=false, $perPage=10, $page=0, $withCustomerDeets=false ){ // $withFullDetails = irrelevant with new DB2 (always returns) global $zbs; // legacy from dal1 $actualPage = $page; if ($zbs->isDAL1()) $actualPage = $page-1; // only DAL1 needed this if ($actualPage < 0) $actualPage = 0; // make ARGS $args = array( // Search/Filtering (leave as false to ignore) 'assignedContact' => $customerID, // with contact? 'withAssigned' => $withCustomerDeets, //'sortByField' => $orderBy, //'sortOrder' => $order, 'page' => $actualPage, 'perPage' => $perPage, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_TRANSACTION) ); return $zbs->DAL->transactions->getTransactions($args); } // Please use direct dal calls in future work. function zeroBS_getTransactionsForCompany( $companyID=-1, $withFullDetails=false, $perPage=10, $page=0, $withCustomerDeets=false ){ // $withFullDetails = irrelevant with new DB2 (always returns) global $zbs; // legacy from dal1 $actualPage = $page; if ($zbs->isDAL1()) $actualPage = $page-1; // only DAL1 needed this if ($actualPage < 0) $actualPage = 0; // make ARGS $args = array( // Search/Filtering (leave as false to ignore) 'assignedCompany' => $companyID, // with contact? 'withAssigned' => $withCustomerDeets, //'sortByField' => $orderBy, //'sortOrder' => $order, 'page' => $actualPage, 'perPage' => $perPage, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_TRANSACTION) ); return $zbs->DAL->transactions->getTransactions($args); } // Please use direct dal calls in future work. function zeroBS_getTransactionIDWithExternalSource($transactionExternalSource='',$transactionExternalID=''){ // retrieve external sources from $zbs now global $zbs; #} No empties, no random externalSources :) if (!empty($transactionExternalSource) && !empty($transactionExternalID) && array_key_exists($transactionExternalSource,$zbs->external_sources)){ // return id if exists return $zbs->DAL->transactions->getTransaction(-1,array( 'externalSource' => $transactionExternalSource, 'externalSourceUID' => $transactionExternalID, 'onlyID' => true, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_TRANSACTION) )); } return false; } // v3.0 + avoid using these centralised funcs (this + zeroBS_integrations_addOrUpdateTransaction) // ... direct calls all the way :D function zeroBS_addUpdateTransaction( $tID = -1, /* example: $tFields = array( REQUIRED: 'orderid' => 'UNIQUEID', 'customer' => CustomerID, 'status' => 'Completed', 'Refunded' similar. 'total' => 123.99, RECOMMENDED: 'date' => 12345TIME, 'currency' => 'USD', 'item' => 'TITLE', 'net' => 0, 'tax' => 0, 'fee' => 0, 'discount' => 0, 'tax_rate' => 0, ); */ $tFields = array(), $transactionExternalSource='', $transactionExternalID='', $transactionDate='', $transactionTags=array(), /* extra */ $fallBackLog = false, $extraMeta = false, $automatorPassthrough = false, $arrBuilderPrefix = 'zbst_' ){ // zeroBSCRM_DEPRECATEDMSG('ZBS Function Deprecated in v3.0+. zeroBS_addUpdateTransaction should now be replaced with proper zbs->DAL->calls'); global $zbs; #} Basics - /--needs unique ID, total MINIMUM if (isset($tFields) && count($tFields) > 0){ #} New flag $newTrans = false; if ($tID > 0){ #} Build "existing meta" to pass, (so we only update fields pushed here) $existingMeta = $zbs->DAL->transactions->getTransaction($tID,array()); // Do date comparison + update that where relevant $originalDate = time(); if (isset($existingMeta) && is_array($existingMeta) && isset($existingMeta['created']) && !empty($existingMeta['created'])) $originalDate = $existingMeta['created']; if (!empty($transactionDate) && $transactionDate != ''){ #} DATE PASSED TO THE FUNCTION $transactionDateTimestamp = strtotime($transactionDate); #} ORIGINAL POST CREATION DATE // no need, db2 = UTS $originalDateTimeStamp = strtotime($originalDate); $originalDateTimeStamp = $originalDate; #} Compare, if $transactionDateTimestamp < then update with passed date if($transactionDateTimestamp < $originalDateTimeStamp){ // straight in there :) $zbs->DAL->transactions->addUpdateTransaction(array( 'id' => $tID, 'limitedFields' =>array( array('key'=>'zbst_created','val'=>$transactionDateTimestamp,'type'=>'%d') ))); } } } else { #} Set flag $newTrans = true; #} DATE PASSED TO THE FUNCTION $transactionDateTimestamp = strtotime($transactionDate); $tFields['created'] = $transactionDateTimestamp; } // this is a DAL2 legacy: $existingMeta = array(); #} Build using centralised func below, passing any existing meta (updates not overwrites) $transactionMeta = zeroBS_buildTransactionMeta($tFields,$existingMeta,$arrBuilderPrefix); // format it for DAL3 addition $args = array( 'id' => $tID, 'data' => $transactionMeta, 'extraMeta' => $extraMeta, 'automatorPassthrough' => $automatorPassthrough, 'fallBackLog' => $fallBackLog ); // few DAL2 -> DAL3 translations: // owner? if (isset($tFields['owner']) > 0) $args['owner'] = $tFields['owner']; // contact/companies? if (isset($tFields['customer']) && $tFields['customer'] > 0) $args['data']['contacts'] = array((int)$tFields['customer']); if (isset($tFields['company']) && $tFields['company'] > 0) $args['data']['companies'] = array((int)$tFields['company']); #} Add external source/externalid #} No empties, no random externalSources :) $approvedExternalSource = ''; #} As this is passed to automator :) if (!empty($transactionExternalSource) && !empty($transactionExternalID) && array_key_exists($transactionExternalSource,$zbs->external_sources)){ #} If here, is legit. $approvedExternalSource = $transactionExternalSource; $extSourceArr = array( 'source' => $approvedExternalSource, 'uid' => $transactionExternalID ); $args['data']['externalSources'] = array($extSourceArr); } #} Otherwise will just be a random obj no ext source #} For now a brutal pass through: // wh: not sure why this was here? if (isset($tFields['trans_time']) && !empty($tFields['trans_time'])) $zbsTransactionMeta['trans_time'] = (int)$tFields['trans_time']; # TAG obj (if exists) - clean etc here too if (isset($transactionTags) && is_array($transactionTags)){ $transactionTags = filter_var_array($transactionTags,FILTER_UNSAFE_RAW); // Formerly this used FILTER_SANITIZE_STRING, which is now deprecated as it was fairly broken. This is basically equivalent. // @todo Replace this with something more correct. foreach ( $transactionTags as $k => $v ) { $transactionTags[$k] = strtr( strip_tags( $v ), array( "\0" => '', '"' => '&#34;', "'" => '&#39;', "<" => '', ) ); } $args['data']['tags'] = array(); foreach ( $transactionTags as $tag_name ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // Check for existing tag under this name. $tag_id = $zbs->DAL->getTag( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -1, array( 'objtype' => ZBS_TYPE_TRANSACTION, 'name' => $tag_name, 'onlyID' => true, ) ); // If tag doesn't exist, create one. if ( empty( $tag_id ) ) { $tag_id = $zbs->DAL->addUpdateTag( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase array( 'data' => array( 'objtype' => ZBS_TYPE_TRANSACTION, 'name' => $tag_name, ), ) ); } // Add tag to list. if ( ! empty( $tag_id ) ) { $args['data']['tags'][] = $tag_id; } } } // Update record (All IA is now fired intrinsicaly) return $zbs->DAL->transactions->addUpdateTransaction( $args ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase } return false; } // Please use direct dal calls in future work, not this. #} Quick wrapper to future-proof. #} Should later replace all get_post_meta's with this function zeroBS_getTransactionMeta($tID=-1){ global $zbs; // in DAL3 it's just a normal get if (!empty($tID)) return $zbs->DAL->transactions->getTransaction($tID); return false; } // filters array for fields currently used in fields.php // v3.0+ this uses the generic zeroBS_buildObjArr, and accepts full args as per contact meta DAL2: function zeroBS_buildTransactionMeta($arraySource=array(),$startingArray=array(),$fieldPrefix='zbst_',$outputPrefix='',$removeEmpties=false,$autoGenAutonumbers=false){ return zeroBS_buildObjArr($arraySource,$startingArray,$fieldPrefix,$outputPrefix,$removeEmpties,ZBS_TYPE_TRANSACTION,$autoGenAutonumbers); } function zeroBSCRM_getTransactionTagsByID($transactionID=-1,$justIDs=false){ global $zbs; $tags = $zbs->DAL->transactions->getTransactionTags($transactionID); // lazy here, but shouldn't use these old funcs anyhow! if ($justIDs){ $ret = array(); if (is_array($tags)) foreach ($tags as $t) $ret[] = $t['id']; return $ret; } return $tags; } // moves a tran from being assigned to one cust, to another // this is a fill-in to match old DAL2 func, however DAL3+ can accept customer/company, // ... so use the proper $DAL->addUpdateObjectLinks for fresh code function zeroBSCRM_changeTransactionCustomer($id=-1,$contactID=0){ if (!empty($id) && $contactID > 0){ global $zbs; return $zbs->DAL->transactions->addUpdateObjectLinks($id,array($contactID),ZBS_TYPE_CONTACT); } return false; } // moves a tran from being assigned to one company, to another // this is a fill-in to match old DAL2 func, however DAL3+ can accept customer/company, // ... so use the proper $DAL->addUpdateObjectLinks for fresh code function zeroBSCRM_changeTransactionCompany($id=-1,$companyID=0){ if (!empty($id) && $companyID > 0){ global $zbs; return $zbs->DAL->transactions->addUpdateObjectLinks($id,array($companyID),ZBS_TYPE_COMPANY); } return false; } /* ====================================================== / Transactions helpers ====================================================== */ /* ====================================================== Event helpers ====================================================== */ function zeroBS___________EventHelpers(){return;} // old way of doing - also should really be "get list of events/tasks for a contact" function zeroBSCRM_getTaskList($cID=-1){ $ret = array(); if ($cID > 0){ global $zbs; return $zbs->DAL->events->getEvents(array( 'assignedContact'=>$cID, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_TASK) )); /* these translated for DAL3 $i = 0; foreach($tasks as $task){ $ret[$i]['title'] = $task->post_title; $ret[$i]['ID'] = $task->ID; $ret[$i]['meta'] = get_post_meta($task->ID,'zbs_event_meta',true); $ret[$i]['actions'] = get_post_meta($task->ID,'zbs_event_actions',true); // titles moved into meta with MS new task ui, wh bringing them out here: if (empty($task->post_title) && is_array($ret[$i]['meta']) && isset($ret[$i]['meta']['title']) && !empty($ret[$i]['meta']['title'])){ $ret[$i]['title'] = $ret[$i]['meta']['title']; } $i++; }*/ return $ret; } return array(); } // adapted to DAL3 // NOTE: $withFullDetails is redundant here // NOTE: as with all dal3 translations, objs no longer have ['meta'] etc. // USE direct DAL calls in code, not this, for future proofing function zeroBS_getEvents( $withFullDetails=false, $perPage=10, $page=0, $ownedByID=false, $search_term='', $sortByField='', $sortOrder='DESC', $hasTagIDs=array() ){ global $zbs; $actualPage = $page; if ($actualPage < 0) $actualPage = 0; // make ARGS $args = array( 'withAssigned' => true, 'withOwner' => true, 'isTagged' => $hasTagIDs, 'sortByField' => $sortByField, 'sortOrder' => $sortOrder, 'page' => $actualPage, 'perPage' => $perPage, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_TASK) ); if ($ownedByID > 0) $args['ownedBy'] = $ownedByID; if ( !empty( $search_term ) ) $args['searchPhrase'] = $search_term; return $zbs->DAL->events->getEvents($args); } // for use in list view // NOTE: $withFullDetails is redundant here // NOTE: as with all dal3 translations, objs no longer have ['meta'] etc. // USE direct DAL calls in code, not this, for future proofing function zeroBS_getEventsCountIncParams( $withFullDetails=false, $perPage=10, $page=0, $ownedByID=false, $search_term='', $sortByField='', $sortOrder='DESC', $hasTagIDs=array()){ global $zbs; // make ARGS $args = array( // just count 'count' => true, 'page' => -1, 'perPage' => -1, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_TASK) ); if ($ownedByID > 0) $args['ownedBy'] = $ownedByID; if ( !empty( $search_term ) ) $args['searchPhrase'] = $search_term; if ( count( $hasTagIDs ) > 0 ) $args['isTagged'] = $hasTagIDs; return $zbs->DAL->events->getEvents($args); } // adapted to DAL3 // NOTE: $withFullDetails is redundant here // NOTE: as with all dal3 translations, objs no longer have ['meta'] etc. // USE direct DAL calls in code, not this, for future proofing function zeroBS_getEventsByCustomerID($cID=-1,$withFullDetails=false,$perPage=10,$page=0){ global $zbs; // legacy from dal1 $actualPage = $page; if (!$zbs->isDAL2()) $actualPage = $page-1; // only DAL1 needed this if ($actualPage < 0) $actualPage = 0; // make ARGS $args = array( 'assignedContact' => $cID, 'page' => $actualPage, 'perPage' => $perPage, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_TASK) ); return $zbs->DAL->events->getEvents($args); } // moves an event from being assigned to one cust, to another // this is a fill-in to match old DAL2 func, however DAL3+ can accept customer/company, // ... so use the proper $DAL->addUpdateObjectLinks for fresh code function zeroBSCRM_changeEventCustomer($id=-1,$contactID=0){ if (!empty($id) && $contactID > 0){ global $zbs; return $zbs->DAL->events->addUpdateObjectLinks($id,array($contactID),ZBS_TYPE_CONTACT); } return false; } // Add an event function zeroBS_addUpdateEvent($eventID = -1, $eventFields = array(), $reminders=array()){ // if using 'from' and 'to', probably using v1 dal, so translate dates: if (isset($eventFields['from'])) $eventFields['from'] = strtotime($eventFields['from']); if (isset($eventFields['to'])) $eventFields['to'] = strtotime($eventFields['to']); #} Build using centralised func below, passing any existing meta (updates not overwrites) $removeEmpties = false; $zbsEventMeta = zeroBS_buildObjArr($eventFields,array(),'','',$removeEmpties,ZBS_TYPE_TASK); // Some sanitation MS has added. Really, DAL isn't place to sanitize, // ... by time it gets here it should be sanitized (e.g. a level up) // ... leaving as I translate this to DAL3 //$zbsEventMeta = filter_var_array($eventFields,FILTER_SANITIZE_STRING); // format it for DAL3 addition $args = array( 'data' => $zbsEventMeta ); global $zbs; // few DAL2 -> DAL3 translations: // owner? if (isset($eventFields['owner']) > 0) $args['owner'] = $eventFields['owner']; // contact/companies? if (isset($eventFields['customer']) && $eventFields['customer'] > 0) $args['data']['contacts'] = array($eventFields['customer']); if (isset($eventFields['company']) && $eventFields['company'] > 0) $args['data']['companies'] = array($eventFields['company']); $args['data']['reminders'] = array(); // reminders into new DAL2 eventreminder format: if (is_array($reminders) && count($reminders) > 0) foreach ($reminders as $reminder){ // this just adds with correct fields $args['data']['reminders'][] = array( 'event' => (int)$eventID, 'remind_at' => (int)$reminder['remind_at'], // just assume is int - garbage in, garbage out ($reminder['remind_at']) ? $reminder['remind_at'] : false; // if int, this 'sent' => (isset($reminder['sent']) && $reminder['sent'] > 0) ? $reminder['sent'] : -1 ); } // updating.... if ($eventID > 0) $args['id'] = (int)$eventID; // simples return $zbs->DAL->events->addUpdateEvent($args); } /* ====================================================== / Event helpers ====================================================== */ /* ====================================================== Form helpers ====================================================== */ function zeroBS___________FormHelpers(){return;} // Please use direct dal calls in future work. // simple wrapper for Form function zeroBS_getForm($formID=-1){ if ($formID > 0){ /* return array( 'id'=>$fID, // mikes init fields 'meta'=>get_post_meta($fID,'zbs_form_field_meta',true), 'style'=>get_post_meta($fID, 'zbs_form_style', true), 'views'=>get_post_meta($fID, 'zbs_form_views', true), 'conversions'=>get_post_meta($fID, 'zbs_form_conversions', true) ); */ global $zbs; return $zbs->DAL->forms->getForm($formID); } return false; } // Please use direct dal calls in future work. function zeroBS_getForms( $withFullDetails=false, $perPage=10, $page=0, $searchPhrase='', $inArray=array(), $sortByField='', $sortOrder='DESC', $quickFilters=array(), $hasTagIDs=array() ){ // quickFilters not used for forms :) *yet // $withFullDetails = irrelevant with new DB2 (always returns) global $zbs; // legacy from dal1 $actualPage = $page; if ($zbs->isDAL1()) $actualPage = $page-1; // only DAL1 needed this if ($actualPage < 0) $actualPage = 0; // make ARGS $args = array( // Search/Filtering (leave as false to ignore) 'searchPhrase' => $searchPhrase, 'inArr' => $inArray, 'isTagged' => $hasTagIDs, 'sortByField' => $sortByField, 'sortOrder' => $sortOrder, 'page' => $actualPage, 'perPage' => $perPage, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_FORM) ); return $zbs->DAL->forms->getForms($args); } // Please use direct dal calls in future work. function zeroBS_getFormsCountIncParams( $withFullDetails=false, $perPage=10, $page=0, $searchPhrase='', $inArray=array(), $sortByField='', $sortOrder='DESC', $quickFilters=array(), $hasTagIDs=array() ){ // quickFilters not used for forms :) *yet // $withFullDetails = irrelevant with new DB2 (always returns) global $zbs; // legacy from dal1 $actualPage = $page; if ($zbs->isDAL1()) $actualPage = $page-1; // only DAL1 needed this if ($actualPage < 0) $actualPage = 0; // make ARGS $args = array( // Search/Filtering (leave as false to ignore) 'searchPhrase' => $searchPhrase, 'inArr' => $inArray, 'isTagged' => $hasTagIDs, // just count thx 'count' => true, 'page' => -1, 'perPage' => -1, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_FORM) ); return $zbs->DAL->forms->getForms($args); } /* ====================================================== / Form helpers ====================================================== */ /* ====================================================== Settings helpers ====================================================== */ function zeroBS___________SettingsHelpers(){return;} #} Minified get all settings // retrieve all settings function zeroBSCRM_getAllSettings(){ global $zbs; $zbs->checkSettingsSetup(); return $zbs->settings->getAll(); } #} Minified get setting func function zeroBSCRM_getSetting($key,$freshFromDB=false){ global $zbs; $zbs->checkSettingsSetup(); return $zbs->settings->get($key,$freshFromDB); } // checks if a setting is set to 1 function zeroBSCRM_isSettingTrue($key){ global $zbs; $setting = $zbs->settings->get($key); if ($setting == "1") return true; return false; } /* ====================================================== / Settings helpers ====================================================== */ /* ====================================================== Alias / AKA helpers ====================================================== */ // Aliases - direct SQL here, could do with moving to DAL3 #} (Generic) See if already in use/exists function zeroBS_canUseAlias($objType=ZBS_TYPE_CONTACT,$alias=''){ if (!empty($alias)) { // verify email? if (!zeroBSCRM_validateEmail($alias)) return false; // is in use? // is customer with this email? $existing = zeroBS_getCustomerIDWithEmail($alias); if (!empty($existing)) return false; global $wpdb,$ZBSCRM_t; $query = $wpdb->prepare( "SELECT ID FROM ".$ZBSCRM_t['aka']." WHERE aka_type = %d AND aka_alias = %s", $objType, $alias); $aliasID = $wpdb->get_var($query); // has alias in there already? if (!empty($aliasID)) return false; // usable return true; } return false; } #} Get specific alias if exists function zeroBS_getObjAlias($objType=ZBS_TYPE_CONTACT,$objID=-1,$alias=''){ if (!empty($objID) && !empty($alias)) { global $wpdb,$ZBSCRM_t; $query = $wpdb->prepare( "SELECT ID,aka_alias,aka_created,aka_lastupdated FROM ".$ZBSCRM_t['aka']." WHERE aka_type = %d AND aka_id = %d AND aka_alias = %s", $objType, $objID, $alias); $alias = $wpdb->get_row($query, ARRAY_A); // check it + return if (is_array($alias)) return $alias; } return false; } #} Get specific alias if exists function zeroBS_getAliasByID($objType=ZBS_TYPE_CONTACT,$objID=-1,$aliasID=-1){ if (!empty($objID) && !empty($aliasID)) { global $wpdb,$ZBSCRM_t; $query = $wpdb->prepare( "SELECT ID,aka_alias,aka_created,aka_lastupdated FROM ".$ZBSCRM_t['aka']." WHERE aka_type = %d AND aka_id = %d AND ID = %d", $objType, $objID, $aliasID); $alias = $wpdb->get_row($query, ARRAY_A); // check it + return if (is_array($alias)) return $alias; } return false; } #} Get All Aliases against an obj. function zeroBS_getObjAliases($objType=ZBS_TYPE_CONTACT,$objID=-1){ if (!empty($objID)) { global $wpdb,$ZBSCRM_t; $query = $wpdb->prepare( "SELECT ID,aka_alias,aka_created,aka_lastupdated FROM ".$ZBSCRM_t['aka']." WHERE aka_type = %d AND aka_id = %d", $objType, $objID ); $aliases = $wpdb->get_results($query, ARRAY_A); // check it + return if (is_array($aliases) && count($aliases) > 0) return $aliases; } return false; } #} add Aliases to an obj. function zeroBS_addObjAlias($objType=ZBS_TYPE_CONTACT,$objID=-1,$alias=''){ if (!empty($objID) && !empty($alias)) { // check not already there $existing = zeroBS_getObjAlias($objType,$objID,$alias); if (!is_array($existing)){ // insert global $wpdb,$ZBSCRM_t; if ($wpdb->insert( $ZBSCRM_t['aka'], array( 'aka_type' => $objType, 'aka_id' => $objID , 'aka_alias' => $alias , 'aka_created' => time() , 'aka_lastupdated' => time() ), array( '%d', '%d' , '%s' , '%d' , '%d' ) )){ // success return $wpdb->insert_id; } else { return false; } } else { // return true, already exists return true; } } return false; } #} remove Alias from an obj. function zeroBS_removeObjAlias($objType=ZBS_TYPE_CONTACT,$objID=-1,$alias=''){ if (!empty($objID) && !empty($alias)) { // check there/find ID $existing = zeroBS_getObjAlias($objType,$objID,$alias); if (is_array($existing)){ // just brutal :) global $wpdb,$ZBSCRM_t; return $wpdb->delete($ZBSCRM_t['aka'], array( 'ID' => $existing['ID'] ), array( '%d' ) ); } } return false; } #} remove Alias from an obj. function zeroBS_removeObjAliasByID($objType=ZBS_TYPE_CONTACT,$objID=-1,$aliasID=-1){ if (!empty($objID) && !empty($aliasID)) { // check there/find ID $existing = zeroBS_getAliasByID($objType,$objID,$aliasID); if (is_array($existing)){ // just brutal :) global $wpdb,$ZBSCRM_t; return $wpdb->delete($ZBSCRM_t['aka'], array( 'ID' => $existing['ID'] ), array( '%d' ) ); } } return false; } /* ====================================================== / Alias / AKA helpers ====================================================== */ /* ====================================================== Value Calculator / helpers ====================================================== */ /** * Calculates the total value associated with a contact or company entity. * * This function sums the total of invoices and transactions associated with a given entity. * It also accounts for the 'jpcrm_total_value_fields' settings to determine whether to include * invoices and transactions in the total value. Additionally, if both invoices and transactions * are included, and the 'transactions_paid_total' is set and greater than 0, it subtracts this * value from the total. * * @param array $entity The entity array containing 'invoices_total', 'transactions_total', and optionally 'transactions_paid_total'. * * @return float The calculated total value. It includes the invoices and transactions totals based on the settings, * and adjusts for 'transactions_paid_total' if applicable. */ function jpcrm_get_total_value_from_contact_or_company( $entity ) { global $zbs; $total_value = 0.0; $invoices_total = isset( $entity['invoices_total'] ) ? $entity['invoices_total'] : 0.0; $transactions_total = isset( $entity['transactions_total'] ) ? $entity['transactions_total'] : 0.0; // For compatibility reasons we include all values if the jpcrm_total_value_fields setting is inexistent. $settings = $zbs->settings->getAll(); $include_invoices_in_total = true; $include_transations_in_total = true; if ( isset( $settings['jpcrm_total_value_fields'] ) ) { $include_invoices_in_total = isset( $settings['jpcrm_total_value_fields']['invoices'] ) && $settings['jpcrm_total_value_fields']['invoices'] === 1; $include_transations_in_total = isset( $settings['jpcrm_total_value_fields']['transactions'] ) && $settings['jpcrm_total_value_fields']['transactions'] === 1; } $total_value = 0; $total_value += $include_invoices_in_total ? $invoices_total : 0; $total_value += $include_transations_in_total ? $transactions_total : 0; if ( $include_invoices_in_total && $include_transations_in_total && isset( $entity['transactions_paid_total'] ) && $entity['transactions_paid_total'] > 0 ) { $total_value -= $entity['transactions_paid_total']; } return $total_value; } // evolved for dal3.0 // left in place + translated, but FAR better to just use 'withValues' => true on a getContact call directly. // THIS STAYS THE SAME FOR DB2 until trans+invoices MOVED OVER #DB2ROUND2 #} Main function to return a customers "total value" #} At MVP that means Invoices + Transactions function zeroBS_customerTotalValue($contactID='',$customerInvoices=array(),$customerTransactions=array()){ global $zbs; $contactWithVals = $zbs->DAL->contacts->getContact($contactID,array( 'withCustomFields' => false, 'withValues' => true)); // throwaway obj apart from totals // later could optimise, but better to optimise 1 level up and not even use this func if (isset($contactWithVals['total_value'])) return $contactWithVals['total_value']; return 0; } // evolved for dal3.0 // left in place + translated, but FAR better to just use 'withValues' => true on a getContact call directly. #} Adds up value of quotes for a customer... function zeroBS_customerQuotesValue($contactID='',$customerQuotes=array()){ global $zbs; $contactWithVals = $zbs->DAL->contacts->getContact($contactID,array( 'withCustomFields' => false, 'withValues' => true)); // throwaway obj apart from totals // later could optimise, but better to optimise 1 level up and not even use this func if (isset($contactWithVals['quotes_value'])) return $contactWithVals['quotes_value']; return 0; } // evolved for dal3.0 // left in place + translated, but FAR better to just use 'withValues' => true on a getContact call directly. #} Adds up value of invoices for a customer... function zeroBS_customerInvoicesValue($contactID='',$customerInvoices=array()){ global $zbs; $contactWithVals = $zbs->DAL->contacts->getContact($contactID,array( 'withCustomFields' => false, 'withValues' => true)); // throwaway obj apart from totals // later could optimise, but better to optimise 1 level up and not even use this func if (isset($contactWithVals['invoices_value'])) return $contactWithVals['invoices_value']; return 0; } // evolved for dal3.0 // left in place + translated, but FAR better to just use 'withValues' => true on a getContact call directly. // same as above, but only for PAID invoices #} Adds up value of invoices for a customer... function zeroBS_customerInvoicesValuePaid($contactID='',$customerInvoices=array()){ // FOR NOW I've just forwarded whole amount. // ... will need to add this functionality to contact DAL, if req. // ... but on a search, this func IS NOT USED in any core code // ... so deferring return zeroBS_customerInvoicesValue($contactID); } // evolved for dal3.0 // left in place + translated, but FAR better to just use 'withValues' => true on a getContact call directly. // same as above, but only for NOT PAID invoices #} Adds up value of invoices for a customer... function zeroBS_customerInvoicesValueNotPaid($contactID='',$customerInvoices=array()){ // FOR NOW I've just forwarded whole amount. // ... will need to add this functionality to contact DAL, if req. // ... but on a search, this func IS NOT USED in any core code // ... so deferring return zeroBS_customerInvoicesValue($contactID); } // evolved for dal3.0 // left in place + translated, but FAR better to just use 'withValues' => true on a getContact call directly. // THIS STAYS THE SAME FOR DB2 until trans MOVED OVER #DB2ROUND2 #} Adds up value of transactions for a customer... function zeroBS_customerTransactionsValue($contactID='',$customerTransactions=array()){ global $zbs; $contactWithVals = $zbs->DAL->contacts->getContact($contactID,array( 'withCustomFields' => false, 'withValues' => true)); // throwaway obj apart from totals // later could optimise, but better to optimise 1 level up and not even use this func if (isset($contactWithVals['transactions_value'])) return $contactWithVals['transactions_value']; return 0; } // evolved for dal3.0 // left in place + translated, but FAR better to just use 'withValues' => true on a getContact call directly. // This can, for now, ultimately be a wrapper for zeroBS_customerInvoicesValue // used in company single view function zeroBS_companyInvoicesValue($companyID='',$companyInvoices=array()){ global $zbs; $companyWithValues = $zbs->DAL->companies->getCompany($companyID,array( 'withCustomFields' => false, 'withValues' => true)); // throwaway obj apart from totals // later could optimise, but better to optimise 1 level up and not even use this func if (isset($companyWithValues['invoices_value'])) return $companyWithValues['invoices_value']; return 0; } // evolved for dal3.0 function zeroBS_companyQuotesValue($companyID=''){ global $zbs; $companyWithValues = $zbs->DAL->companies->getCompany($companyID,array( 'withCustomFields' => false, 'withValues' => true)); // throwaway obj apart from totals // later could optimise, but better to optimise 1 level up and not even use this func if (isset($companyWithValues['quotes_value'])) return $companyWithValues['quotes_value']; return 0; } // evolved for dal3.0 // left in place + translated, but FAR better to just use 'withValues' => true on a getContact call directly. // This can, for now, ultimately be a wrapper for zeroBS_customerTransactionsValue // used in company single view function zeroBS_companyTransactionsValue($companyID='',$companyTransactions=array()){ global $zbs; $companyWithValues = $zbs->DAL->companies->getCompany($companyID,array( 'withCustomFields' => false, 'withValues' => true)); // throwaway obj apart from totals // later could optimise, but better to optimise 1 level up and not even use this func if (isset($companyWithValues['transactions_value'])) return $companyWithValues['transactions_value']; return 0; } // evolved for dal3.0 function zeroBS_companyTotalValue($companyID=''){ global $zbs; $companyWithValues = $zbs->DAL->companies->getCompany($companyID,array( 'withCustomFields' => false, 'withValues' => true)); // throwaway obj apart from totals // later could optimise, but better to optimise 1 level up and not even use this func if (isset($companyWithValues['total_value'])) return $companyWithValues['total_value']; return 0; } /* ====================================================== / Value Calculator / helpers ====================================================== */ // =============================================================================== // ======== Security Logs (used for Quote + Trans hashlink access) ============== function zeroBS___________SecurityLogHelpers(){return;} // this is fired on all req (expects a "fini" followup fire of next func to mark "success") // (defaults to failed req.) function zeroBSCRM_security_logRequest($reqType='unknown',$reqHash='',$reqID=-1){ // don't log requests for admins, who by nature, can see all // needs to match zeroBSCRM_security_finiRequest precheck if (zeroBSCRM_isZBSAdminOrAdmin()) return false; global $wpdb,$ZBSCRM_t; // if user logged in, also log id $userID = -1; $current_user = wp_get_current_user(); if (isset($current_user->ID)) $userID = (int)$current_user->ID; $userIP = zeroBSCRM_getRealIpAddr(); // validate these a bit $validTypes = array('quoteeasy','inveasy'); if (!in_array($reqType, $validTypes)) $reqType = 'na'; $reqHash = sanitize_text_field( $reqHash ); if (strlen($reqHash) > 128) $reqHash = ''; $reqID = (int)sanitize_text_field( $reqID ); if ($wpdb->insert( $ZBSCRM_t['security_log'], array( //'zbs_site' => zeroBSCRM_installSite(), //'zbs_team' => zeroBSCRM_installTeam(), 'zbs_owner' => -1, //zeroBSCRM_currentUserID(), 'zbssl_reqtype' => $reqType, 'zbssl_ip' => $userIP, 'zbssl_reqhash' => $reqHash, 'zbssl_reqid' => $reqID, 'zbssl_loggedin_id' => $userID, 'zbssl_reqstatus' => -1, // guilty until proven... 'zbssl_reqtime' => time() ), array( '%d', '%s' , '%s' , '%s' , '%d' , '%d' , '%d' , '%d' ) )){ // success return $wpdb->insert_id; } return false; } // after security validated, function zeroBSCRM_security_finiRequest($requestID=-1){ // don't log requests for admins, who by nature, can see all // needs to match zeroBSCRM_security_logRequest precheck if (zeroBSCRM_isZBSAdminOrAdmin()) return false; // basic check $requestID = (int)$requestID; if ($requestID > 0){ global $wpdb,$ZBSCRM_t; // for now just brutal update, not even comparing IP if ($wpdb->update( $ZBSCRM_t['security_log'], array( 'zbssl_reqstatus' => 1 ), array( // where 'ID' => $requestID ), array( '%d', ), array( '%d' ) ) !== false){ // return id return $requestID; } } return false; } // checks if blocked function zeroBSCRM_security_blockRequest($reqType='unknown'){ // don't log requests for admins, who by nature, can see all // needs to match zeroBSCRM_security_logRequest etc. above if (zeroBSCRM_isZBSAdminOrAdmin()) return false; global $zbs,$wpdb,$ZBSCRM_t; // see if more than X (5?) failed request accessed by this ip within last Y (48h?) $userIP = zeroBSCRM_getRealIpAddr(); $sinceTime = time()-172800; // 48h = 172800 $maxFails = 5; $query = $wpdb->prepare( "SELECT COUNT(ID) FROM ".$ZBSCRM_t['security_log']." WHERE zbssl_ip = %s AND zbssl_reqstatus <> %d AND zbssl_reqtime > %d", array($userIP,1,$sinceTime)); $countFailed = (int)$wpdb->get_var($query); // less than .. if ($countFailed < $maxFails) return false; return true; } // removes all security logs older than setting (72h at addition) // this is run DAILY by a cron job in ZeroBSCRM.CRON.php function zeroBSCRM_clearSecurityLogs(){ global $zbs,$wpdb,$ZBSCRM_t; // older than $deleteOlderThanTime = time()-259200; // 72h = 259200 // delete $wpdb->query($wpdb->prepare("DELETE FROM ".$ZBSCRM_t['security_log']." WHERE zbssl_reqtime < %d",$deleteOlderThanTime)); } function zeroBSCRM_hashes_GetHashForObj($objID = -1,$objTypeID=-1){ if ($objID > 0 && $objTypeID > 0){ global $zbs; $hash = $zbs->DAL->meta($objTypeID,$objID,'zbshash',''); // Return with PREFIX (makes it interpretable later on as this is shared between invID + invHash (for example) at endpoint /invoices/*hashorid) if (!empty($hash)) return 'zh-'.$hash; } return false; } // NOTE: This is now GENERIC, for quotes/invs whatever has meta :) (DAL3+ pass objTypeID) //function is this a hash of an INVOICE. Could be refined when DB2.0 //function for checking if a hash is valid // ... THIS WAS refactored for v3.0, now uses hash cols on objs :) function zeroBSCRM_hashes_GetObjFromHash($hash = '', $pay = -1, $objTypeID=-1){ // def $ret = array( 'success'=> false, 'data'=>array() ); //SANITIZE $hash = sanitize_text_field($hash); //sanitize it here // if prefix still present, chunk off if ( str_starts_with( $hash, 'zh-' ) ) { $hash = substr( $hash, 3 ); } // get if poss if (!empty($hash) && $objTypeID > 0){ global $zbs; switch ($objTypeID){ case ZBS_TYPE_INVOICE: // retrieve, if any $invoice = $zbs->DAL->invoices->getInvoice(-1,array('hash'=>$hash,'withAssigned'=>true)); // got inv? if (is_array($invoice) && isset($invoice['id'])){ $contactID = -1; //return the customer information that the invoice will need (i.e. Stripe customerID) same function will be used //in invoice checkout process (invoice pro) when being paid for using a HASH URL. if ($pay > 0){ //paying so need the customerID from settings otherwise just viewing so dont need to expose data // WH: I've added this for future ease: if (is_array($invoice) && isset($invoice['contact']) && is_array($invoice['contact']) && count($invoice['contact']) > 0) $contactID = $invoice['contact'][0]['id']; //$companyID = -1; if (is_array($invoice) && isset($invoice['company']) && is_array($invoice['company']) && count($invoice['company']) > 0) $companyID = $invoice['company'][0]['id']; } $ret['success'] = true; $ret['data'] = array( 'ID' => $invoice['id'], 'cID' => $contactID ); } break; case ZBS_TYPE_QUOTE: // retrieve, if any $quote = $zbs->DAL->quotes->getQuote(-1,array('hash'=>$hash,'withAssigned'=>true)); // got quote? if (is_array($quote) && isset($quote['id'])){ $ret['success'] = true; $ret['data'] = array( 'ID' => $quote['id'], 'cID' => -1 // not req for quotes? ); } break; } // / switch } // / if hash + objtypeid return $ret; } // ======== / Security Logs (used for Quote + Trans hashlink access) ============= // =============================================================================== // =============================================================================== // ======================= Tax Table Helpers ==================================== // takes a subtotal and a (potential csv) of ID's of taxtable lines // returns a £0 net value of the tax to be applied function zeroBSCRM_taxRates_getTaxValue( $subtotal = 0.0, $taxRateIDCSV = '' ) { $tax = 0.0; // retrieve tax rate(s) if ( !empty( $taxRateIDCSV ) ) { $taxRateTable = zeroBSCRM_taxRates_getTaxTableArr( true ); // get (multiple) id's $taxRatesToApply = array(); if ( strpos( $taxRateIDCSV, ',' ) ) { $taxRateIDs = explode( ',', $taxRateIDCSV ); if ( !is_array( $taxRateIDs ) ) { $taxRatesToApply = array(); } else { $taxRatesToApply = $taxRateIDs; } } else { $taxRatesToApply[] = (int)$taxRateIDCSV; } if ( is_array( $taxRatesToApply ) ) { foreach ( $taxRatesToApply as $taxRateID ) { $rateID = (int)$taxRateID; if ( isset( $taxRateTable[$rateID] ) ) { // get rate $rate = 0.0; if ( isset( $taxRateTable[$rateID]['rate'] ) ) { $rate = (float)$taxRateTable[$rateID]['rate']; } // calc + add $tax += round( $subtotal * ( $rate / 100 ), 2 ); } // else not set? } // / foreach tax rate to apply } return $tax; } return 0.0; } // gets single tax rate by id function zeroBSCRM_taxRates_getTaxRate($taxRateID=''){ // retrieve tax rate(s) if (!empty($taxRateID)){ $taxRateID = (int)$taxRateID; global $ZBSCRM_t,$wpdb; // for v3.0, brutal direct sql $query = 'SELECT * FROM '.$ZBSCRM_t['tax'].' WHERE ID = %d ORDER BY ID ASC'; try { #} Prep & run query $queryObj = $wpdb->prepare($query,array($taxRateID)); $potentialRes = $wpdb->get_row($queryObj, OBJECT); } catch (Exception $e){ } #} Interpret results (Result Set - multi-row) if (isset($potentialRes) && isset($potentialRes->ID)) { return zeroBSCRM_taxRates_tidy_taxRate($potentialRes); } } return array(); } // old alias function zeroBSCRM_getTaxTableArr(){ return zeroBSCRM_taxRates_getTaxTableArr(); } // retrieve tax table as array function zeroBSCRM_taxRates_getTaxTableArr($indexByID=false){ /* // demo/dummy data return array( //these will be populated based on the array 1 => array( 'id' => 1, 'tax' => 20, 'name' => 'VAT' ), 2 => array( 'id' => 2, 'tax' => 19, 'name' => 'GST' ) ); */ global $ZBSCRM_t,$wpdb; // for v3.0, brutal direct sql $query = 'SELECT * FROM '.$ZBSCRM_t['tax'].' ORDER BY ID ASC'; $potentialTaxRates = $wpdb->get_results($query, OBJECT); #} Interpret results (Result Set - multi-row) if (isset($potentialTaxRates) && is_array($potentialTaxRates) && count($potentialTaxRates) > 0) { $res = array(); #} Has results, tidy + return foreach ($potentialTaxRates as $resDataLine) { if ($indexByID){ $lineID = (int)$resDataLine->ID; $res[$lineID] = zeroBSCRM_taxRates_tidy_taxRate($resDataLine); } else { $res[] = zeroBSCRM_taxRates_tidy_taxRate($resDataLine); } } return $res; } return array(); } /** * adds or updates a taxrate object * * @param array $args Associative array of arguments * id (not req.), owner (not req.) data -> key/val * * @return int line ID */ function zeroBSCRM_taxRates_addUpdateTaxRate($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'owner' => -1, // fields (directly) 'data' => array( 'name' => '', 'rate' => 0.0, 'created' => -1 // override date? :( ) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ $id = (int)$id; // if owner = -1, add current if (!isset($owner) || $owner === -1) $owner = zeroBSCRM_user(); // check if exists already (where no id passed) if ( $id < 1 && isset( $data['name'] ) && isset( $data['rate'] ) ){ // simple query $query = 'SELECT ID FROM '.$ZBSCRM_t['tax'].' WHERE zbsc_tax_name = %s AND zbsc_rate = %d ORDER BY ID DESC LIMIT 0,1'; $existing_rate_id = (int)$wpdb->get_var( $wpdb->prepare( $query, $data['name'], $data['rate'] ) ); if ( $existing_rate_id > 0 ){ $id = $existing_rate_id; } } #} ========= / CHECK FIELDS =========== $dataArr = array( // ownership // no need to update these (as of yet) - can't move teams etc. //'zbs_site' => zeroBSCRM_installSite(), //'zbs_team' => zeroBSCRM_installTeam(), 'zbs_owner' => $owner, // fields 'zbsc_tax_name' => $data['name'], 'zbsc_rate' => $data['rate'], 'zbsc_lastupdated' => time() ); $dataTypes = array( // field data types '%d', '%s', '%s', '%d' ); if (isset($data['created']) && !empty($data['created']) && $data['created'] !== -1){ $dataArr['zbsc_created'] = $data['created']; $dataTypes[] = '%d'; } if (isset($id) && !empty($id) && $id > 0){ #} Check if obj exists (here) - for now just brutal update (will error when doesn't exist) #} Attempt update if ($wpdb->update( $ZBSCRM_t['tax'], $dataArr, array( // where 'ID' => $id ), $dataTypes, array( // where data types '%d' )) !== false){ // Successfully updated - Return id return $id; } else { // FAILED update return false; } } else { // set created if not set if (!isset($dataArr['zbsc_created'])) { $dataArr['zbsc_created'] = time(); $dataTypes[] = '%d'; } // add team etc $dataArr['zbs_site'] = zeroBSCRM_site(); $dataTypes[] = '%d'; $dataArr['zbs_team'] = zeroBSCRM_team(); $dataTypes[] = '%d'; #} No ID - must be an INSERT if ($wpdb->insert( $ZBSCRM_t['tax'], $dataArr, $dataTypes ) > 0){ #} Successfully inserted, lets return new ID $newID = $wpdb->insert_id; return $newID; } else { #} Failed to Insert return false; } } return false; } /** * deletes a Taxrate object * * @param array $args Associative array of arguments * id * * @return int success; */ function zeroBSCRM_taxRates_deleteTaxRate($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1 ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} Check ID & Delete :) $id = (int)$id; if (!empty($id) && $id > 0) return zeroBSCRM_db2_deleteGeneric($id,'tax'); return false; } /** * tidy's the object from wp db into clean array * * @param array $obj (DB obj) * * @return array (clean obj) */ function zeroBSCRM_taxRates_tidy_taxRate($obj=false){ $res = false; if (isset($obj->ID)){ $res = array(); $res['id'] = $obj->ID; $res['owner'] = $obj->zbs_owner; $res['name'] = $obj->zbsc_tax_name; $res['rate'] = $obj->zbsc_rate; // to maintain old obj more easily, here we refine created into datestamp $res['created'] = zeroBSCRM_locale_utsToDatetime($obj->zbsc_created); $res['createduts'] = $obj->zbsc_created; // this is the UTS (int14) $res['lastupdated'] = $obj->zbsc_lastupdated; } return $res; } // ======================= / Tax Table Helpers =================================== // =============================================================================== // =============================================================================== // ======================= File Upload Related Funcs ============================ function zeroBS___________FileHelpers(){return;} // retrieve all files for a (customer)whatever function zeroBSCRM_files_getFiles($fileType = '',$objID=-1){ global $zbs; $filesArrayKey = zeroBSCRM_files_key($fileType); if (!empty($filesArrayKey) && $objID > 0){ // DAL2+ // bit gross hard-typed, could be genericified as all is using is >DAL()->getMeta switch ($fileType){ case 'customer': case 'contact': return $zbs->DAL->contacts->getContactMeta($objID,'files'); break; case 'quotes': case 'quote': return $zbs->DAL->quotes->getQuoteMeta($objID,'files'); break; case 'invoices': case 'invoice': return $zbs->DAL->invoices->getInvoiceMeta($objID,'files'); break; case 'companies': case 'company': return $zbs->DAL->companies->getCompanyMeta($objID,'files'); break; // no default } } return array(); } // updates files array for a (whatever) function zeroBSCRM_files_updateFiles($fileType = '',$objID=-1,$filesArray=-1){ global $zbs; $filesArrayKey = zeroBSCRM_files_key($fileType); if (!empty($filesArrayKey) && $objID > 0){ // DAL2+ // bit gross hard-typed, could be genericified as all is using is >DAL()->getMeta switch ($fileType){ case 'customer': case 'contact': $zbs->DAL->updateMeta(ZBS_TYPE_CONTACT,$objID,'files',$filesArray); break; case 'quotes': case 'quote': $zbs->DAL->updateMeta(ZBS_TYPE_QUOTE,$objID,'files',$filesArray); break; case 'invoices': case 'invoice': $zbs->DAL->updateMeta(ZBS_TYPE_INVOICE,$objID,'files',$filesArray); break; case 'companies': case 'company': $zbs->DAL->updateMeta(ZBS_TYPE_COMPANY,$objID,'files',$filesArray); break; // no default } return $filesArray; } return false; } // moves all files from one objid to another objid // v3.0+ function zeroBSCRM_files_moveFilesToNewObject($fileType='',$oldObjID=-1,$objID=-1){ global $zbs; $filesArrayKey = zeroBSCRM_files_key($fileType); $filesObjTypeInt = $zbs->DAL->objTypeID($fileType); if ($filesObjTypeInt > 0 && !empty($filesArrayKey) && $oldObjID > 0 && $objID > 0){ // retrieve existing $existingFileArray = zeroBSCRM_files_getFiles($fileType,$oldObjID); // if has files if (is_array($existingFileArray)){ // put the files into new obj: $x = zeroBSCRM_files_updateFiles($fileType,$objID,$existingFileArray); // delete old reference $zbs->DAL->deleteMeta(array( 'objtype' => $filesObjTypeInt, 'objid' => $oldObjID, 'key' => $filesArrayKey )); return true; } } return false; } // gets meta key for file type arr function zeroBSCRM_files_key($fileType=''){ switch ($fileType){ case 'customer': case 'contact': return 'zbs_customer_files'; break; case 'quotes': case 'quote': return 'zbs_customer_quotes'; break; case 'invoices': case 'invoice': return 'zbs_customer_invoices'; break; case 'companies': case 'company': return 'zbs_company_files'; break; } return ''; } // ======================= / File Upload Related Funcs =========================== // =============================================================================== // =============================================================================== // =========== TEMPHASH (remains same for DAL2->3) ============================= /** * checks validity of a temporary hash object * * @return int success; */ function zeroBSCRM_checkValidTempHash($objid=-1,$type='',$hash=''){ // get a valid hash $hash = zeroBSCRM_getTempHash(-1,$type,$hash,1); // check id if (isset($hash) && is_array($hash) && isset($hash['objid'])) if ($objid == $hash['objid']) return true; return false; } /** * retrieves a temporary hash object * * @return int success; */ function zeroBSCRM_getTempHash($id=-1,$type='',$hash='',$status=-99){ $id = (int)$id; if (!empty($id) && $id > 0){ global $ZBSCRM_t,$wpdb; $whereStr = ''; $additionalWHERE = ''; $queryVars = array(); if (!empty($id)){ $queryVars[] = $id; $whereStr = 'ID = %d'; } else { if (!empty($hash)){ $queryVars[] = $hash; $whereStr = 'zbstemphash_objhash = %s'; } } if (!empty($type)){ $queryVars[] = $type; $additionalWHERE = 'AND zbstemphash_objtype = %s '; } // else will be from ANY type if ($status != -99){ $queryVars[] = $status; $additionalWHERE = 'AND zbstemphash_status = %d '; } /* -- prep started, see: #OWNERSHIP */ if (!empty($whereStr)){ $sql = "SELECT * FROM ".$ZBSCRM_t['temphash']." WHERE ".$whereStr." ".$additionalWHERE."ORDER BY ID ASC LIMIT 0,1"; $potentialReponse = $wpdb->get_row( $wpdb->prepare($sql,$queryVars), OBJECT ); } if (isset($potentialReponse) && isset($potentialReponse->ID)){ #} Retrieved :) fill + return // tidy $res = zeroBS_tidy_temphash($potentialReponse); return $res; } } return false; } /** * adds or updates a temporary hash object * * @return int success; */ function zeroBSCRM_addUpdateTempHash($id=-1,$objstatus=-1,$objtype='',$objid=-1,$objhash='',$returnHashArr=false){ // globals global $ZBSCRM_t,$wpdb; // got id? $id = (int)$id; if (!empty($id) && $id > 0){ // check exists? // for now just brutal update. if ($wpdb->update( $ZBSCRM_t['temphash'], array( //'zbs_site' => zeroBSCRM_installSite(), //'zbs_team' => zeroBSCRM_installTeam(), //'zbs_owner' => zeroBSCRM_currentUserID(), 'zbstemphash_status' => (int)$objstatus, 'zbstemphash_objtype' => $objtype, 'zbstemphash_objid' => (int)$objid, 'zbstemphash_objhash' => $objhash, //'zbsmaillink_created' => time(), 'zbstemphash_lastupdated' => time() ), array( // where 'ID' => $id ), array( '%d', '%s', '%d', '%s', '%d' ), array( '%d' ) ) !== false){ // if "return hash" if ($returnHashArr) return array('id'=>$id,'hash'=>$objhash); // return id return $id; } } else { // insert // create hash if not created :) if (empty($objhash)) $objhash = zeroBSCRM_GenerateTempHash(); // go if ($wpdb->insert( $ZBSCRM_t['temphash'], array( //'zbs_site' => zeroBSCRM_installSite(), //'zbs_team' => zeroBSCRM_installTeam(), //'zbs_owner' => zeroBSCRM_currentUserID(), 'zbstemphash_status' => (int)$objstatus, 'zbstemphash_objtype' => $objtype, 'zbstemphash_objid' => (int)$objid, 'zbstemphash_objhash' => $objhash, 'zbstemphash_created' => time(), 'zbstemphash_lastupdated' => time() ), array( //'%d', // site //'%d', // team //'%d', // owner '%d', '%s', '%d', '%s', '%d', '%d' ) ) > 0){ // inserted, let's move on $newID = $wpdb->insert_id; // if "return hash" if ($returnHashArr) return array('id'=>$id,'hash'=>$objhash); return $newID; } } return false; } /** * deletes a temporary hash object * * @param array $args Associative array of arguments * id * * @return int success; */ function zeroBSCRM_deleteTempHash($args=array()){ // Load Args $defaultArgs = array( 'id' => -1 ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) $$argK = $args[$argK]; } // globals global $ZBSCRM_t,$wpdb; $id = (int)$id; if (!empty($id) && $id > 0) return zeroBSCRM_db2_deleteGeneric($id,'temphash'); return false; } function zeroBS_tidy_temphash($obj=false){ $res = false; if (isset($obj->ID)){ $res = array(); $res['id'] = $obj->ID; $res['created'] = $obj->zbstemphash_created; $res['lastupdated'] = $obj->zbstemphash_lastupdated; $res['status'] = $obj->zbstemphash_status; $res['objtype'] = $obj->zbstemphash_objtype; $res['objid'] = $obj->zbstemphash_objid; $res['objhash'] = $obj->zbstemphash_objhash; } return $res; } // generates generic HASH (used for links etc.) function zeroBSCRM_GenerateTempHash($str=-1,$length=20){ #} Brutal hash generator, for now if (!empty($str)){ #} Semi-nonsense, not "secure" //$newMD5 = md5($postID.time().'fj30948hjfaosindf'); $newMD5 = wp_generate_password(64, false); return substr($newMD5,0,$length-1); } return ''; } // =========== / TEMPHASH ====================================================== // =============================================================================== /* ====================================================== General/WP helpers ====================================================== */ // in effect this is: get owner (WP USER)'s email // currently only used on Automations extension // use jpcrm_get_obj_owner_wordpress_email() in future... function zeroBS_getAssigneeEmail( $cID=-1 ) { return jpcrm_get_obj_owner_wordpress_email( $cID, ZBS_TYPE_CONTACT ); } // returns an obj owner's email as set against their WordPress account function jpcrm_get_obj_owner_wordpress_email( $objID, $objTypeID ) { global $zbs; if ( $objID > 0 && $zbs->DAL->isValidObjTypeID( $objTypeID ) ) { $ownerID = zeroBS_getOwner( $objID, false, $objTypeID ); if ( $ownerID > 0 ) { return get_the_author_meta( 'user_email', $ownerID ); } } return false; } // in effect this is: get owner (WP USER)'s mobile // use zeroBS_getObjOwnerWPMobile in future... (renamed, bad naming) function zeroBS_getAssigneeMobile($wpUID=-1){ return zeroBS_getObjOwnerWPMobile($wpUID); } // returns owner of obj's mobile (from WP USER) function zeroBS_getObjOwnerWPMobile($objID =-1,$objType='zerobs_customer'){ if ($objID > 0){ $ownerID = zeroBS_getOwner($objID,false,$objType); if ($ownerID > 0) return zeroBS_getWPUsersMobile($ownerID); } return false; } // in effect this is: get (WP USER)'s mobile // use zeroBS_getWPUsersMobile in future... (renamed) function zeroBS_getUserMobile($wpUID=-1){ return zeroBS_getWPUsersMobile($wpUID); } // returns an obj owner's mobile number as per their wp account function zeroBS_getWPUsersMobile($uID =-1){ if ($uID !== -1){ if (!empty($uID)){ $mobile_number = get_user_meta( 'mobile_number', $uID ); $mobile_number = apply_filters( 'zbs_filter_mobile', $mobile_number); return $mobile_number; } return false; } } /* * Gets formatted display name for user (tries to retrieve fname lname) */ function jpcrm_wp_user_name( $wordpress_user_id=-1 ){ $user_info = get_userdata( $wordpress_user_id ); if ( !$user_info ) return false; // start with display name $user_name = $user_info->display_name; // else try and use fname lname if ( empty( $user_name ) ){ $user_name = $user_info->user_firstname; if ( !empty( $user_info->user_lastname ) ){ if ( !empty( $user_name ) ){ $user_name .= ' '; } $user_name .= $user_info->user_lastname; } } // else fall back to nice name if ( empty( $user_name ) ){ $user_name = $user_info->user_nicename; } // else email? if ( empty( $user_name ) ){ $user_name = $user_info->user_email; } return $user_name; } function zeroBS_getCompanyCount(){ global $zbs; return $zbs->DAL->companies->getCompanyCount(array('ignoreowner'=>true)); } function zeroBS_getQuoteCount(){ global $zbs; return $zbs->DAL->quotes->getQuoteCount(array('ignoreowner'=>true)); } function zeroBS_getQuoteTemplateCount(){ global $zbs; return $zbs->DAL->quotetemplates->getQuotetemplateCount(array('ignoreowner'=>true)); } function zeroBS_getInvoiceCount(){ global $zbs; return $zbs->DAL->invoices->getInvoiceCount(array('ignoreowner'=>true)); } function zeroBS_getTransactionCount(){ global $zbs; return $zbs->DAL->transactions->getTransactionCount(array('ignoreowner'=>true)); } /// ======= Statuses wrappers - bit antiquated now... // outdated wrapper function zeroBS_getTransactionsStatuses(){ return zeroBSCRM_getTransactionsStatuses(); } function zeroBSCRM_getCustomerStatuses($asArray=false){ global $zbs; $setting = $zbs->DAL->setting('customisedfields',false); $zbsStatusStr = ''; #} stored here: $settings['customisedfields'] if (is_array($setting) && isset($setting['customers']['status']) && is_array($setting['customers']['status'])) $zbsStatusStr = $setting['customers']['status'][1]; if (empty($zbsStatusStr)) { #} Defaults: global $zbsCustomerFields; if (is_array($zbsCustomerFields)) $zbsStatusStr = implode(',',$zbsCustomerFields['status'][3]); } if ($asArray){ if ( str_contains( '#' . $zbsStatusStr, ',' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $arr = explode(',',$zbsStatusStr); $ret = array(); foreach ($arr as $x) { $z = trim($x); if (!empty($z)) $ret[] = $z; } return $ret; } } return $zbsStatusStr; } /** * Retrieve valid transaction statuses * * @param bool $return_array Return an array instead of a CSV. */ function zeroBSCRM_getTransactionsStatuses( $return_array = false ) { global $zbs; $setting = $zbs->DAL->setting( 'customisedfields', false ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase $zbs_status_str = ''; if ( is_array( $setting ) && isset( $setting['transactions']['status'] ) && is_array( $setting['transactions']['status'] ) ) { $zbs_status_str = $setting['transactions']['status'][1]; } if ( empty( $zbs_status_str ) ) { global $zbsTransactionFields; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase if ( is_array( $zbsTransactionFields ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $zbs_status_str = implode( ',', $zbsTransactionFields['status'][3] ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } } if ( $return_array ) { if ( str_contains( $zbs_status_str, ',' ) ) { return explode( ',', $zbs_status_str ); } else { return array(); } } return $zbs_status_str; } /** * Retrieve an array of valid invoice statuses */ function zeroBSCRM_getInvoicesStatuses() { // for DAL3+ these are hard typed, probably need to sit in the obj: return array( 'Draft', 'Unpaid', 'Paid', 'Overdue', 'Deleted', ); } function zeroBSCRM_getCompanyStatusesCSV(){ global $zbs; $setting = $zbs->DAL->setting('customisedfields',false); $zbsStatusStr = ''; #} stored here: $settings['customisedfields'] if (is_array($setting) && isset($setting['companies']['status']) && is_array($setting['companies']['status'])) $zbsStatusStr = $setting['companies']['status'][1]; if (empty($zbsStatusStr)) { #} Defaults: global $zbsCompanyFields; if (is_array($zbsCompanyFields)) $zbsStatusStr = implode(',',$zbsCompanyFields['status'][3]); } return $zbsStatusStr; } /** * Retrieve an array of valid company statuses */ function zeroBSCRM_getCompanyStatuses() { $statuses_str = zeroBSCRM_getCompanyStatusesCSV(); if ( str_contains( $statuses_str, ',' ) ) { return explode( ',', $statuses_str ); } else { return array(); } } /// ======= / Statuses wrappers - bit antiquated now... // use this, or direct call function zeroBSCRM_invoice_getContactAssigned($invID=-1){ global $zbs; return $zbs->DAL->invoices->getInvoiceContactID($invID); } // use this, or direct call function zeroBSCRM_quote_getContactAssigned($quoteID=-1){ global $zbs; return $zbs->DAL->quotes->getQuoteContactID($quoteID); } // DELETES ALL rows from any table, based on ID // no limits! be careful. function zeroBSCRM_db2_deleteGeneric($id=-1,$tableKey=''){ // req global $ZBSCRM_t,$wpdb; // lazy id check $id = (int)$id; if ( $id > 0 && !empty($tableKey) && array_key_exists( $tableKey, $ZBSCRM_t ) ){ return $wpdb->delete( $ZBSCRM_t[$tableKey], array( // where 'ID' => $id ), array( '%d' ) ); } return false; } // this has a js equivilent in global.js: zeroBSCRMJS_telURLFromNo function zeroBSCRM_clickToCallPrefix(){ $click2CallType = zeroBSCRM_getSetting('clicktocalltype'); if ($click2CallType == 1) return 'tel:'; if ($click2CallType == 2) return 'callto:'; } // this'll let you find strings in serialised arrays // super dirty :) // wh wrote for log reporter miguel function zeroBSCRM_makeQueryMetaRegexReturnVal($fieldNameInSerial=''){ /* https://regex101.com/ e.g. from a:3:{s:4:"type";s:4:"Note";s:9:"shortdesc";s:24:"Testing Notes on another";s:8:"longdesc";s:16:"Dude notes what ";} thes'll return: works, tho returns full str: /"'.$fieldNameInSerial.'";s:[0-9]*:"[a-zA-Z0-9_ ]+/ returns: `shortdesc";s:24:"Testing Notes on another` this is clean(er): (?<=shortdesc";s:)[0-9]*:"[^"]* returns: 24:"Testing Notes on another .. could get even cleaner, for now settling here // WH WORKS: // https://stackoverflow.com/questions/16926847/wildcard-for-single-digit-mysql a:3:{s:4:"type";s:4:"Note";s:9:"shortdesc";s:24:"Testing Notes on another";s:8:"longdesc";s:16:"Dude notes what ";} SELECT * FROM `wp_postmeta` WHERE post_id = 150 AND meta_value regexp binary '/shortdesc";s:[0-9]*:"/' LIMIT 50 // https://regex101.com/ */ $regexStr = '/(?<="'.$fieldNameInSerial.'";s:)[0-9]*:"[^"]*/'; if (!empty($fieldNameInSerial) && zeroBSCRM_isRegularExpression($regexStr)) return $regexStr; return false; } // this'll let you CHECK FOR strings in serialised arrays // super dirty :) // wh wrote for log reporter miguel function zeroBSCRM_makeQueryMetaRegexCheck($fieldNameInSerial='',$posval=''){ $regexStr = '/(?<="'.$fieldNameInSerial.'";s:)[0-9]*:"[^"]*'.$posval.'[^"]*/'; if (!empty($fieldNameInSerial) && !empty($posval) && zeroBSCRM_isRegularExpression($regexStr)) return $regexStr; return false; } // this'll let you CHECK FOR strings (multiple starting fieldnames) in serialised arrays // super dirty :) // wh wrote for log reporter miguel // e.g. is X in shortdesc or longdesc in serialised wp options obj function zeroBSCRM_makeQueryMetaRegexCheckMulti($fieldNameInSerialArr=array(),$posval=''){ // multi fieldnames :) // e.g. (?:shortdesc";s:|longdesc";s:)[0-9]*:"[^"]*otes[^"]* // e.g. str: a:3:{s:4:"type";s:4:"Note";s:9:"shortdedsc";s:24:"Testing Notes on another";s:8:"longdesc";s:16:"Dude notes what ";} $fieldNameInSerialStr = ''; if (count($fieldNameInSerialArr) > 0){ foreach ($fieldNameInSerialArr as $s){ if (!empty($fieldNameInSerialStr)) $fieldNameInSerialStr .= '|'; $fieldNameInSerialStr .= '"'.$s.'";s:'; } } // FOR THESE REASONS: https://stackoverflow.com/questions/18317183/1139-got-error-repetition-operator-operand-invalid-from-regexp // .. cant use this: //$regexStr = '/(?:'.$fieldNameInSerialStr.')[0-9]*:"[^"]*'.$posval.'[^"]*/'; // bt this works: $regexStr = '/('.$fieldNameInSerialStr.')[0-9]*:"[^"]*'.$posval.'[^"]*/'; if (!empty($fieldNameInSerialStr) && !empty($posval) && zeroBSCRM_isRegularExpression($regexStr)) return $regexStr; return false; } // test regex roughly // https://stackoverflow.com/questions/8825025/test-if-a-regular-expression-is-a-valid-one-in-php /*function zeroBSCRM_checkRegexWorks($pattern,$subject=''){ if (@preg_match($pattern, $subject) !== false) return true; return false; } */ function zeroBSCRM_isRegularExpression($string) { set_error_handler(function() {}, E_WARNING); $isRegularExpression = preg_match($string, "") !== FALSE; restore_error_handler(); return $isRegularExpression; } function zeroBS_getCurrentUserUsername(){ // https://codex.wordpress.org/Function_Reference/wp_get_current_user $current_user = wp_get_current_user(); if ( !($current_user instanceof WP_User) ) return; return $current_user->user_login; } function zeroBSCRM_getAddressCustomFields(){ /* v3.0 changes the methodology here, in reality, this func is now defunct, just a wrapper... */ global $zbs; return $zbs->DAL->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_ADDRESS)); } #} ZBS users page - returns list of WP user IDs, which have a ZBS role and includes name / email, etc function zeroBSCRM_crm_users_list(){ //from Permissions /* remove_role('zerobs_admin'); remove_role('zerobs_customermgr'); remove_role('zerobs_quotemgr'); remove_role('zerobs_invoicemgr'); remove_role('zerobs_transactionmgr'); remove_role('zerobs_customer'); remove_role('zerobs_mailmgr'); */ //NOT zerbs_customer - this is people who have purchased (i.e. WooCommerce folk) $role = array('zerobs_customermgr','zerobs_admin','administrator','zerobs_quotemgr', 'zerobs_invoicemgr', 'zerobs_transactionmgr', 'zerobs_mailmgr'); $crm_users = get_users(array('role__in' => $role, 'orderby' => 'ID')); //this will return what WP holds (and can interpret on the outside.) return $crm_users; } // returns a system setting for ignore ownership // ... ownership ignored, unless the setting is on + not admin function zeroBSCRM_DAL2_ignoreOwnership($objType=1){ global $zbs; // FOR NOW EVERYONE CAN SEE EVERYTHING // Later add - strict ownership? isn't this a platform UPSELL? // if ($zbs->settings->get('perusercustomers') && !current_user_can('administrator')) return false; return true; } function zeroBSCRM_DEPRECATEDMSG($msg=''){ echo '<div class="zbs info msg">'.$msg.'</div>'; error_log(strip_tags($msg)); } /** * This takes a passed object type (old or new) and returns the new type. * * @param string|int - an object type in old or new format, e.g.: * old: 'zerobs_customer' * new: 1, ZBS_TYPE_CONTACT * * @return int|bool false - the object type ID if it exists, false if not */ function jpcrm_upconvert_obj_type( $obj_type=-1 ) { global $zbs; if ( $zbs->DAL->isValidObjTypeID( $obj_type ) ) { // already a valid new obj? return (int)$obj_type; } else { // upconvert old type into new return $zbs->DAL->objTypeID( $obj_type ); } } /** * Backward compat - `zbsLink` got renamed to `jpcrm_esc_link` in 5.5 **/ function zbsLink( $key = '', $id = -1, $type = 'zerobs_customer', $prefixOnly = false, $taxonomy = false ){ return jpcrm_esc_link( $key, $id, $type, $prefixOnly, $taxonomy ); } /** * Core Link building function * Produces escaped raw URLs for links within wp-admin based CRM areas * Examples: echo '<a href="'.jpcrm_esc_link('edit',-1,'contact',false,false).'">New Contact</a>'; echo '<a href="'.jpcrm_esc_link('edit',$id,'contact',false,false).'">Edit Contact</a>'; * Notes: * - accepts new (contact,ZBS_TYPE_CONTACT) or old (zerobs_customer) references (but use NEW going forward) * - previously called `zbsLink` **/ function jpcrm_esc_link( $key = '', $id = -1, $type = 'zerobs_customer', $prefixOnly = false, $taxonomy = false ){ global $zbs; // infer objTypeID (turns contact|zerobs_contact -> ZBS_TYPE_CONTACT) $objTypeID = jpcrm_upconvert_obj_type( $type ); // switch through potentials switch ($key){ case 'list': $url = admin_url('admin.php?page='.$zbs->slugs['dash']); // switch based on type. switch ($objTypeID){ case ZBS_TYPE_CONTACT: $url = admin_url( 'admin.php?page='.$zbs->slugs['managecontacts'] ); break; case ZBS_TYPE_COMPANY: $url = admin_url( 'admin.php?page='.$zbs->slugs['managecompanies'] ); break; case ZBS_TYPE_QUOTE: $url = admin_url( 'admin.php?page='.$zbs->slugs['managequotes'] ); break; case ZBS_TYPE_INVOICE: $url = admin_url( 'admin.php?page='.$zbs->slugs['manageinvoices'] ); break; case ZBS_TYPE_TRANSACTION: $url = admin_url( 'admin.php?page='.$zbs->slugs['managetransactions'] ); break; case ZBS_TYPE_FORM: $url = admin_url( 'admin.php?page='.$zbs->slugs['manageformscrm'] ); break; case ZBS_TYPE_TASK: $url = admin_url( 'admin.php?page='.$zbs->slugs['manage-tasks'] ); break; case ZBS_TYPE_SEGMENT: $url = admin_url( 'admin.php?page='.$zbs->slugs['segments'] ); break; case ZBS_TYPE_QUOTETEMPLATE: $url = admin_url( 'admin.php?page='.$zbs->slugs['quote-templates'] ); break; } // rather than return admin.php?page=list, send to dash if not these ^ return esc_url_raw( $url ); break; case 'view': // view page (theoretically returns for all obj types, even tho contact + company only ones using view pages atm) if ($objTypeID > 0){ if ($id > 0) { // view with actual ID return esc_url_raw( admin_url( 'admin.php?page=zbs-add-edit&action=view&zbstype=' . $zbs->DAL->objTypeKey( $objTypeID ) . '&zbsid=' . $id ) ); } else if ($prefixOnly){ // prefix only return esc_url_raw( admin_url( 'admin.php?page=zbs-add-edit&action=view&zbstype=' . $zbs->DAL->objTypeKey( $objTypeID ) . '&zbsid=' ) ); } } // / got objType break; case 'edit': // edit page (returns for all obj types) if ($objTypeID > 0){ if ($id > 0) { // view with actual ID return esc_url_raw( admin_url( 'admin.php?page=zbs-add-edit&action=edit&zbstype=' . $zbs->DAL->objTypeKey( $objTypeID ) . '&zbsid=' . $id ) ); } else if ( $prefixOnly ){ // prefix only return esc_url_raw( admin_url( 'admin.php?page=zbs-add-edit&action=edit&zbstype=' . $zbs->DAL->objTypeKey( $objTypeID ) . '&zbsid=' ) ) ; } } // / got objType break; case 'create': // create page (returns for all obj types) if ( $objTypeID > 0 ){ return esc_url_raw( admin_url( 'admin.php?page=zbs-add-edit&action=edit&zbstype=' . $zbs->DAL->objTypeKey( $objTypeID ) ) ); } // / got objType // mail campaigns specific catch if ($type == 'mailcampaign' || $type == 'mailsequence'){ global $zeroBSCRM_MailCampaignsslugs; if (isset($zeroBSCRM_MailCampaignsslugs)){ return esc_url_raw( admin_url( 'admin.php?page=' . $zeroBSCRM_MailCampaignsslugs['editcamp'] ) ); } } break; case 'delete': // delete page if ( $objTypeID > 0 ){ if ( $id > 0 ) { // view with actual ID return esc_url_raw( admin_url( 'admin.php?page=zbs-add-edit&action=delete&zbstype=' . $zbs->DAL->objTypeKey( $objTypeID ) . '&zbsid=' . $id ) ); } else if ($prefixOnly){ // prefix only return esc_url_raw( admin_url( 'admin.php?page=zbs-add-edit&action=delete&zbstype=' . $zbs->DAL->objTypeKey( $objTypeID).'&zbsid=' ) ); } } // / got objType break; case 'tags': // Tag manager page (returns for all obj types) if ( $objTypeID > 0 ){ return esc_url_raw( admin_url( 'admin.php?page=' . $zbs->slugs['tagmanager'] . '&tagtype=' . $zbs->DAL->objTypeKey( $objTypeID ) ) ); } // / got objType break; case 'listtagged': // List view -> tagged (returns for all obj types) if ( $objTypeID > 0 ){ // exception: event tags if ( $objTypeID == ZBS_TYPE_TASK ) { return esc_url_raw( admin_url( 'admin.php?page=' . $zbs->slugs['manage-tasks-list'] . '&zbs_tag=' . $taxonomy ) ); } return esc_url_raw( admin_url( 'admin.php?page=' . $zbs->DAL->listViewSlugFromObjID( $objTypeID ) . '&zbs_tag=' . $taxonomy ) ); } // / got objType break; case 'email': switch ( $objTypeID ){ case ZBS_TYPE_CONTACT: if ($id > 0) { // email with actual ID return esc_url_raw( zeroBSCRM_getAdminURL( $zbs->slugs['emails'] ) . '&zbsprefill=' . $id ); } else if ( $prefixOnly ){ // page only return esc_url_raw( zeroBSCRM_getAdminURL( $zbs->slugs['emails'] ) . '&zbsprefill=' ); } break; } break; } // if $key isn't in switch, assume it's a slug :) return esc_url_raw( admin_url( 'admin.php?page=' . $key ) ); // none? DASH then! // return esc_url_raw( admin_url('admin.php?page=zerobscrm-dash') ); } #} This is run by main init :) (Installs Quote Templates etc.) function zeroBSCRM_installDefaultContent() { global $zbs; #} Quote Builder, defaults $quoteBuilderDefaultsInstalled = zeroBSCRM_getSetting('quotes_default_templates'); if (!is_array($quoteBuilderDefaultsInstalled)){ #} Need installing! $installedQuoteTemplates = array(); #} Load content $quoteBuilderDefaultTemplates = array(); #} Web Design: Example $templatedHTML = file_get_contents(ZEROBSCRM_PATH.'html/quotes/quote-template-web-design.html'); if (!empty($templatedHTML)) $quoteBuilderDefaultTemplates['webdesignexample'] = array( 'title' => __('Web Design: Example','zero-bs-crm'), 'html' => $templatedHTML, 'value' => 500.00 ); #} Install.. if (count($quoteBuilderDefaultTemplates) > 0) foreach ($quoteBuilderDefaultTemplates as $template){ // Insert via DAL3 $newTemplateID = $zbs->DAL->quotetemplates->addUpdateQuotetemplate(array( // fields (directly) 'data' => array( 'title' => $template['title'], 'value' => $template['value'], 'date_str' => '', 'date' => '', 'content' => $template['html'], 'notes' => '', 'currency' => '', 'created' => time(), 'lastupdated' => time(), ), 'extraMeta' => array('zbsdefault'=>1) )); if ($newTemplateID > 0) $installedQuoteTemplates[] = $newTemplateID; } #} Log installed $zbs->settings->update('quotes_default_templates',$installedQuoteTemplates); } } /* ====================================================== / General/WP helpers ====================================================== */
projects/plugins/crm/includes/ZeroBSCRM.IntegrationFuncs.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V1.20 * * Copyright 2020 Automattic * * Date: 01/11/16 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== Integration specific extension functions (#MIKELOOK) ====================================================== */ /* |======================================= | zeroBS_integrations_getCustomer |======================================= | Retrieves a customer record (as usual _getCustomer func) - but one that has been inserted via import from an external source | E.g. Woo Imported, Paypal imported, whatever | A customer can exist with multiple import IDs, which lets us patch across services. | E.g. Customer has a woo id of customer1@gmail.com (woo uses emails), and a paypal id of customer1@gmail.com (or another email, paypal will also use emails) | Then that customer could be called with either of these, but would get the same main "customer" record | zeroBS_integrations_getCustomer('woo','customer1@gmail.com') | zeroBS_integrations_getCustomer('pay','customer1@gmail.com') | These "externalSource"s can be flags we agree on, and add here for reference | 23/01/2015: | 'woo' = WooCommerce | 'pay' = Paypal | ... for these to work they must be added to $zbscrmApprovedExternalSources; at top of ZeroBSCRMExternalSources.php or via extension hook in | To be further expanded if req. |======================================= | Returns: | Customer obj (std class) | or | False (boolean) (customer does not exist) |======================================= | Check via: if ($customerobj !== false) |======================================= */ function zeroBS_integrations_getCustomer($externalSource='',$externalID=''){ #} Do query for ID $potentialCustomerID = zeroBS_getCustomerIDWithExternalSource($externalSource,$externalID); if ($potentialCustomerID !== false){ #} If so, pass full deets via this return zeroBS_getCustomer($potentialCustomerID); } #} If it gets here, it failed return false; } /* |======================================= | zeroBS_integrations_addOrUpdateCustomer |======================================= | Add's a new customer, or updates an existing customer, where their externalSource + externalID matches an existing customer (if specified) | e.g. if it's a woo customer import and woo uses 'usersemail' as their unique id, then you'd specify 'woo' and 'theiremail@whatever.com' as the source + ID | This only works with specific external sources, as 'zeroBS_integrations_getCustomer' | These "externalSource"s can be flags we agree on, and add here for reference | 01/06/2016: | 'woo' = WooCommerce | 'pay' = Paypal | 01/08/2016: | 'form' = Form Capture | 11/12/2016: | 'grav' = Gravity Forms | | Usage: zeroBS_integrations_addOrUpdateCustomer('woo','woodyhayday2@smt.com',array( 'zbsc_email' => 'woodyhayday2@smt.com', 'zbsc_status' => 'Lead', 'zbsc_prefix' => 'Mr', 'zbsc_fname' => 'Woody', 'zbsc_lname' => 'Hayday', 'zbsc_addr1' => 'First Addr', 'zbsc_addr2' => '2nd Addr', 'zbsc_city' => 'London', 'zbsc_county' => 'G London', 'zbsc_postcode' => 'AL1 111', 'zbsc_hometel' => '0123456789', 'zbsc_worktel' => '999', 'zbsc_mobtel' => '333', 'zbsc_notes' => 'Multi Line Notes Kick Ass', #} custom fields are set as cf(int) and so are per-install dependent, you probs don't ever want to insert these :) :D #'zbsc_cf1' => 'Google' ), 'customer_date as per mike!', 'none', false, false ); | | ... note "woo" external source flag | ... note "woodyhayday2@smt.com" - my ID within woo | ... note normal customer fields in array, prefixed with 'zbsc_' | ... NOTE: Mike added customer_date | ... Note: From v1.1.18 we also have fallback logs: | -------------------------------------------------- | Fallback Logs: | Pass either: | 'none' = do nothing if user already exists | 'auto' = automatically create log (NOT WORKING YET) | OR: | array( | 'type' => 'Form Filled',#'form_filled', | 'shortdesc' => 'Dude filled out the form x on y', | 'longdesc' => '' | ) | | (Long desc is optional) | | #} CURRENT Note Types (use first field/key e.g. "form_filled") (v1.1.18 - 20/09/16) | | 'note': { label: 'Note', ico: 'fa-sticky-note-o' }, | 'call': { label: 'Call', ico: 'fa-phone-square' }, | 'email': { label: 'Email', ico: 'fa-envelope-o' }, | 'meeting': { label: 'Meeting', ico: 'fa-users' }, | 'quote__sent': { label: 'Quote: Sent', ico: 'fa-share-square-o' }, | 'quote__accepted': { label: 'Quote: Accepted', ico: 'fa-thumbs-o-up' }, | 'quote__refused': { label: 'Quote: Refused', ico: 'fa-ban' }, | 'invoice__sent': { label: 'Invoice: Sent', ico: 'fa-share-square-o' }, | 'invoice__part_paid': { label: 'Invoice: Part Paid', ico: 'fa-money' }, | 'invoice__paid': { label: 'Invoice: Paid', ico: 'fa-money' }, | 'invoice__refunded': { label: 'Invoice: Refunded', ico: 'fa-money' }, | 'transaction': { label: 'Transaction', ico: 'fa-credit-card' }, | 'tweet': { label: 'Tweet', ico: 'fa-twitter' }, | 'facebook_post': { label: 'Facebook Post', ico: 'fa-facebook-official' }, | 'created': { label: 'Created', ico: 'fa-plus-circle' }, | 'updated': { label: 'Updated', ico: 'fa-pencil-square-o' }, | 'quote_created': { label: 'Quote Created', ico: 'fa-plus-circle' }, | 'invoice_created': { label: 'Invoice Created', ico: 'fa-plus-circle' }, | 'form_filled': { label: 'Form Filled', ico: 'fa-wpforms'} | | -------------------------------------------------- | | | | #} RE: $extraMeta (This isn't used anywhere yet, talk to WH before using) | | ... this is a key value array passable to add extra values to customers | ... should look like: | | $extraMeta = array( | | array('key_here',12345), | array('another','what') | | ) | | ... which will add the following meta to a customer: | | zbs_customer_extra_key_here = 12345 | zbs_customer_extra_another = what | | ... BRUTALLY - no checking, just overwrites! (so be careful) | | #} Re: $automatorPassthrough | | ... adding anything here allows it to be passed through to the internal automator (which currently sets notes) | ... this means you can pass an array with note str overrides... e.g. | | array( | | 'note_override' => array( | | 'type' => 'Form Filled',#'form_filled', | 'shortdesc' => 'Dude filled out the form x on y', | 'longdesc' => '' | | ) | | ) | | ... see recipes to see what's useful :) | |======================================= | 27/09/16: $emailAlreadyExistsAction | | This is a flag to say what to do in this circumstance: User obj passed has an email (in $customerFields['zbsc_email']) which matches a customer in DB already | ... options: | 'update': Update customer record (and add external source) (BRUTAL override) | 'skip': Do nothing | 'notifyexit': quit + notify | ... this func is mostly future proofing, as there may be times we want to avoid overriding existing data from an import e.g. | |======================================= | ... Made this func super easy so you can just fire it when you're not sure if add or update... :) it'll deal. |======================================= | Returns: | Customer ID | or | False (boolean) (customer create/update failed) |======================================= */ function zeroBS_integrations_addOrUpdateCustomer($externalSource='',$externalID='',$customerFields=array(), $customerDate = '', $fallbackLog='auto', $extraMeta = false, $automatorPassthroughArray = false, $emailAlreadyExistsAction = 'update',$fieldPrefix = 'zbsc_'){ #} leave this true and it'll run as normal. $usualUpdate = true; global $zbs; $potentialCustomerIDfromEmail = false; if (!empty($externalSource) && !empty($externalID) && is_array($customerFields) && count($customerFields) > 0){ if (isset($customerFields['zbsc_email']) && !empty($customerFields['zbsc_email'])){ #} First check for email in cust list $potentialCustomerIDfromEmail = zeroBS_getCustomerIDWithEmail($customerFields['zbsc_email']); #} If so... act based on $emailAlreadyExistsAction param if (!empty($potentialCustomerIDfromEmail)){ #} So we have a customer with this email... switch ($emailAlreadyExistsAction){ /* not built out yet... case 'addextsrc': #} Just add the external source break; */ case 'update': #} Just let it roll on... $usualUpdate = true; break; case 'skip': #} don't do nothin :) $usualUpdate = false; break; case 'notifyexit': #} Notify + exit echo esc_html( 'Contact Add/Update Issue: A contact already exists with the email "' . $customerFields['zbsc_email'] . '" (ID: ' . $potentialCustomerIDfromEmail . '), user could not be processed!' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase exit(); break; } } } #} ========================================================================================= #} NO existing user! Proceed as before! #} ========================================================================================= if ($usualUpdate){ // if ID specifically passed, use that :) if (isset($customerFields['id']) && !empty($customerFields['id']) && $customerFields['id'] > 0){ $potentialCustomerID = $customerFields['id']; } else { #} Do query for ID $potentialCustomerID = zeroBS_getCustomerIDWithExternalSource($externalSource,$externalID); } #} If ID empty, but $potentialCustomerIDfromEmail (from above) not, use $potentialCustomerIDfromEmail if (($potentialCustomerID === false || $potentialCustomerID == -1) && $potentialCustomerIDfromEmail !== false) $potentialCustomerID = $potentialCustomerIDfromEmail; #} Default fallback log creation $fallbackLogToPass = false; if ( !isset($fallbackLog) || !is_array($fallbackLog) ) { #} create default fallback log, unless $fallbackLog is set to 'none' if ($fallbackLog !== 'none'){ #} Autogen #} Left this out for v1.1.18... needs thought. #} Do we really want to put "woo source added"? It might get added loads. #} For now leave as manual... } } elseif (is_array($fallbackLog)){ #} Fallback log is probably set, just pass it along. $fallbackLogToPass = $fallbackLog; } #} Here we're passing along any automator pass through #} ... which will typically be overrides for creation logs or any extra params to give to internal automator. $automatorPassthrough = false; if (isset($automatorPassthroughArray) && is_array($automatorPassthroughArray)) $automatorPassthrough = $automatorPassthroughArray; #} Not yet used, ask WH // Now passing through 2.24+ $extraMeta = false; #} Brutal add/update #} MS - 3rd Jan 2019 - this (eventually) just calls the usual _addUpdateCustomer function $customerID = zeroBS_addUpdateCustomer($potentialCustomerID,$customerFields,$externalSource,$externalID, $customerDate, $fallbackLogToPass, $extraMeta, $automatorPassthrough, -1, $fieldPrefix); #} Update any title if (!$zbs->isDAL2() && $customerID !== false) zbsCustomer_updateCustomerNameInPostTitle($customerID,false); return $customerID; } #} / usual update } else{ return false; } } /* |======================================= | zeroBS_integrations_addOrUpdateCompany |======================================= | Add's a new Company, or updates an existing Company, where their externalSource + externalID matches an existing Company (if specified) | NOTE: This is different from zeroBS_integrations_addOrUpdateCustomer, in that the externalID must be COMPANY NAME | This only works with specific external sources, as 'zeroBS_integrations_getCompany' | These "externalSource"s can be flags we agree on, and add here for reference | 23/01/2015: | 'woo' = WooCommerce | 'pay' = Paypal | 'form' = Form Capture | | Usage: zeroBS_integrations_addOrUpdateCompany('woo','Dell',array( 'zbsc_coname' => 'Dell', 'zbsc_status' => 'Lead', 'zbsc_addr1' => 'First Addr', 'zbsc_addr2' => '2nd Addr', 'zbsc_city' => 'London', 'zbsc_county' => 'G London', 'zbsc_postcode' => 'AL1 111', 'zbsc_hometel' => '0123456789', 'zbsc_worktel' => '999', 'zbsc_mobtel' => '333', 'zbsc_notes' => 'Multi Line Notes Kick Ass', #} custom fields are set as cf(int) and so are per-install dependent, you probs don't ever want to insert these :) :D #'zbsc_cf1' => 'Google' ), 'customer_date as per mike!', 'none', false, false ); | | ... note "woo" external source flag | ... note "woodyhayday2@smt.com" - my ID within woo | ... note normal customer fields in array, prefixed with 'zbsc_' | ... NOTE: Mike added customer_date | ... Note: From v1.1.18 we also have fallback logs: | -------------------------------------------------- | Fallback Logs: | Pass either: | 'none' = do nothing if user already exists | 'auto' = automatically create log (NOT WORKING YET) | OR: | array( | 'type' => 'Form Filled',#'form_filled', | 'shortdesc' => 'Dude filled out the form x on y', | 'longdesc' => '' | ) | | (Long desc is optional) | | #} CURRENT Note Types (use first field/key e.g. "form_filled") (v1.1.18 - 20/09/16) | | 'note': { label: 'Note', ico: 'fa-sticky-note-o' }, | 'call': { label: 'Call', ico: 'fa-phone-square' }, | 'email': { label: 'Email', ico: 'fa-envelope-o' }, | 'meeting': { label: 'Meeting', ico: 'fa-users' }, | 'quote__sent': { label: 'Quote: Sent', ico: 'fa-share-square-o' }, | 'quote__accepted': { label: 'Quote: Accepted', ico: 'fa-thumbs-o-up' }, | 'quote__refused': { label: 'Quote: Refused', ico: 'fa-ban' }, | 'invoice__sent': { label: 'Invoice: Sent', ico: 'fa-share-square-o' }, | 'invoice__part_paid': { label: 'Invoice: Part Paid', ico: 'fa-money' }, | 'invoice__paid': { label: 'Invoice: Paid', ico: 'fa-money' }, | 'invoice__refunded': { label: 'Invoice: Refunded', ico: 'fa-money' }, | 'transaction': { label: 'Transaction', ico: 'fa-credit-card' }, | 'tweet': { label: 'Tweet', ico: 'fa-twitter' }, | 'facebook_post': { label: 'Facebook Post', ico: 'fa-facebook-official' }, | 'created': { label: 'Created', ico: 'fa-plus-circle' }, | 'updated': { label: 'Updated', ico: 'fa-pencil-square-o' }, | 'quote_created': { label: 'Quote Created', ico: 'fa-plus-circle' }, | 'invoice_created': { label: 'Invoice Created', ico: 'fa-plus-circle' }, | 'form_filled': { label: 'Form Filled', ico: 'fa-wpforms'} | | -------------------------------------------------- | | | | #} RE: $extraMeta (This isn't used anywhere yet, talk to WH before using) | | ... this is a key value array passable to add extra values to customers | ... should look like: | | $extraMeta = array( | | array('key_here',12345), | array('another','what') | | ) | | ... which will add the following meta to a customer: | | zbs_customer_extra_key_here = 12345 | zbs_customer_extra_another = what | | ... BRUTALLY - no checking, just overwrites! (so be careful) | | #} Re: $automatorPassthrough | | ... adding anything here allows it to be passed through to the intval(var)ternal automator (which currently sets notes) | ... this means you can pass an array with note str overrides... e.g. | | array( | | 'note_override' => array( | | 'type' => 'Form Filled',#'form_filled', | 'shortdesc' => 'Dude filled out the form x on y', | 'longdesc' => '' | | ) | | ) | | ... see recipes to see what's useful :) | |======================================= | 27/09/16: $conameAlreadyExistsAction | | This is a flag to say what to do in this circumstance: User obj passed has an email (in $companyFields['zbsc_coname']) which matches a company in DB already | ... options: | 'update': Update company record (and add external source) (BRUTAL override) | 'skip': Do nothing | 'notifyexit': quit + notify | ... this func is mostly future proofing, as there may be times we want to avoid overriding existing data from an import e.g. | |======================================= | ... Made this func super easy so you can just fire it when you're not sure if add or update... :) it'll deal. |======================================= | Returns: | Company ID | or | False (boolean) (Company create/update failed) |======================================= */ #} External source + (externalID = Co NAME) function zeroBS_integrations_addOrUpdateCompany( $externalSource='', $externalID='', $companyFields=array(), $companyDate = '', $fallbackLog='auto', $extraMeta = false, $automatorPassthroughArray = false, $conameAlreadyExistsAction = 'update', $fieldPrefix = 'zbsc_'){ global $zbs; #} leave this true and it'll run as normal. $usualUpdate = true; if (!empty($externalSource) && !empty($externalID) && is_array($companyFields) && count($companyFields) > 0){ $potentialCompanyIDfromName = false; $potentialCoName = ''; // <3.0 if (isset($companyFields[$fieldPrefix.'coname']) && !empty($companyFields[$fieldPrefix.'coname'])) $potentialCoName = $companyFields[$fieldPrefix.'coname']; // 3.0 if (isset($companyFields[$fieldPrefix.'name']) && !empty($companyFields[$fieldPrefix.'name'])) $potentialCoName = $companyFields[$fieldPrefix.'name']; if ($potentialCoName !== ''){ #} First check for name in company list $potentialCompanyIDfromName = zeroBS_getCompanyIDWithName($potentialCoName); #} If so... act based on $conameAlreadyExistsAction param if (!empty($potentialCompanyIDfromName)){ #} So we have a customer with this email... switch ($conameAlreadyExistsAction){ /* not built out yet... case 'addextsrc': #} Just add the external source break; */ case 'update': #} Just let it roll on... $usualUpdate = true; break; case 'skip': #} don't do nothin :) $usualUpdate = false; break; case 'notifyexit': #} Notify + exit echo esc_html( __(jpcrm_label_company().' Add/Update Issue: A '.jpcrm_label_company().' already exists with the name "','zero-bs-crm').$potentialCoName.'" (ID: '.$potentialCompanyIDfromName.'), '.__('could not be processed!','zero-bs-crm') ); exit(); break; } } } #} ========================================================================================= #} NO existing user! Proceed as before! #} ========================================================================================= if ($usualUpdate){ #} Do query for ID $potentialCompanyID = zeroBS_getCompanyIDWithExternalSource($externalSource,$externalID); #} If ID empty, but $potentialCompanyIDfromName (from above) not, use $potentialCompanyIDfromName if ($potentialCompanyID === false && $potentialCompanyIDfromName !== false) $potentialCompanyID = $potentialCompanyIDfromName; #} Default fallback log creation $fallbackLogToPass = false; if ( !isset($fallbackLog) || !is_array($fallbackLog) ) { #} create default fallback log, unless $fallbackLog is set to 'none' if ($fallbackLog !== 'none'){ #} Autogen #} Left this out for v1.1.18... needs thought. #} Do we really want to put "woo source added"? It might get added loads. #} For now leave as manual... } } elseif (is_array($fallbackLog)){ #} Fallback log is probably set, just pass it along. $fallbackLogToPass = $fallbackLog; } #} Here we're passing along any automator pass through #} ... which will typically be overrides for creation logs or any extra params to give to internal automator. $automatorPassthrough = false; if (isset($automatorPassthroughArray) && is_array($automatorPassthroughArray)) $automatorPassthrough = $automatorPassthroughArray; #} Not yet used, ask WH $extraMeta = false; #} Brutal add/update $companyID = zeroBS_addUpdateCompany($potentialCompanyID,$companyFields,$externalSource,$externalID, $companyDate, $fallbackLogToPass, $extraMeta, $automatorPassthrough,-1,$fieldPrefix); return $companyID; } #} / usual update } else return false; } /* |======================================= | zeroBS_integrations_getCompany |======================================= | Retrieves a Company record (as usual _getCompany func) - but one that has been inserted via import from an external source | E.g. Woo Imported, Paypal imported, whatever | A Company can exist with multiple import IDs, which lets us patch across services. | E.g. Company has a woo id of 1234, and a paypal Company id of x3da9j3d9jad2 | Then that Company could be called with either of these, but would get the same main "Company" record | zeroBS_integrations_getCompany('woo','1234') | zeroBS_integrations_getCompany('pay','x3da9j3d9jad2') |======================================= | Returns: | Company obj (std class) | or | False (boolean) (Company does not exist) |======================================= | Check via: if ($coobj !== false) |======================================= */ function zeroBS_integrations_getCompany($externalSource='',$externalID=''){ #} Do query for ID $potentialCompanyID = zeroBS_getCompanyIDWithExternalSource($externalSource,$externalID); if ($potentialCompanyID !== false){ #} If so, pass full deets via this return zeroBS_getCompany($potentialCompanyID); } #} If it gets here, it failed return false; } /* |======================================= | zeroBS_integrations_addOrUpdateTransaction |======================================= | Add's a new Transaction, or updates an existing Transaction, where their externalSource + externalID matches an existing Transaction (if specified) | NOTE: This is different from zeroBS_integrations_addOrUpdateCustomer, in that the externalID must be Transaction ID | This only works with specific external sources, as 'zeroBS_integrations_getTransaction' | Usage: zeroBS_integrations_addOrUpdateTransaction('woo','#123456',array( REQUIRED: 'orderid' => 'UNIQUEID', 'customer' => CustomerID, 'status' => 'Completed', 'Refunded' similar. 'total' => 123.99, RECOMMENDED: 'date' => 12345TIME, 'currency' => 'USD', 'item' => 'TITLE', 'net' => 0, 'tax' => 0, 'fee' => 0, 'discount' => 0, 'tax_rate' => 0, ), array( TAGS: 'sale','bill','chargeback','refund','echeckchargeback','cancel-rebill','uncancel-rebill' etc. ), 'date as per mike!', 'none', false, false ); | | ... note "woo" external source flag | ... note "woodyhayday2@smt.com" - my ID within woo | ... note normal customer fields in array, prefixed with 'zbsc_' | ... NOTE: Mike added date | ... Note: From v1.1.18 we also have fallback logs: | -------------------------------------------------- | Fallback Logs: | Pass either: | 'none' = do nothing if user already exists | 'auto' = automatically create log (NOT WORKING YET) | OR: | array( | 'type' => 'Form Filled',#'form_filled', | 'shortdesc' => 'Dude filled out the form x on y', | 'longdesc' => '' | ) | | (Long desc is optional) | | -------------------------------------------------- | | | #} RE: $extraMeta | | ... this is a key value array passable to add extra values to customers | ... should look like: | | $extraMeta = array( | | array('key_here',12345), | array('another','what') | | ) | | ... which will add the following meta to a customer: | | zbs_customer_extra_key_here = 12345 | zbs_customer_extra_another = what | | ... BRUTALLY - no checking, just overwrites! (so be careful) | | -------------------------------------------------- | | #} Re: $automatorPassthrough | | ... adding anything here allows it to be passed through to the internal automator (which currently sets notes) | ... this means you can pass an array with note str overrides... e.g. | | array( | | 'note_override' => array( | | 'type' => 'Form Filled',#'form_filled', | 'shortdesc' => 'Dude filled out the form x on y', | 'longdesc' => '' | | ) | | ) | | ... see recipes to see what's useful :) | |======================================= | Returns: | Transaction ID | or | False (boolean) (Transaction create/update failed) |======================================= */ function zeroBS_integrations_addOrUpdateTransaction( $transactionExternalSource='', /* Req, e.g. 'str' */ $transactionExternalID='', /* Req, e.g. 'ch_1DqSxpBy0i6Hd9AL4noH4Yhx' */ $transactionFields=array(), /* Req: array(orderid,customer,status,total) */ $transactionTags=array(), /* optional extra tags */ $transactionDate = '', $fallbackLog='auto', $extraMeta = false, $automatorPassthroughArray = false, $fieldPrefix = 'zbst_' ){ #} Check req. if ( !empty($transactionExternalSource) && !empty($transactionExternalID) && is_array($transactionFields) && count($transactionFields) > 0 && ( // v2 (isset($transactionFields['orderid']) && !empty($transactionFields['orderid'])) || // v3 (isset($transactionFields['ref']) && !empty($transactionFields['ref'])) ) && //isset($transactionFields['customer']) && !empty($transactionFields['customer']) && isset($transactionFields['status']) && !empty($transactionFields['status']) && isset($transactionFields['total']) && !empty($transactionFields['total']) ){ #} Do query for ID $potentialTransactionID = zeroBS_getTransactionIDWithExternalSource($transactionExternalSource,$transactionExternalID); #} Default fallback log creation $fallbackLogToPass = false; if ( !isset($fallbackLog) || !is_array($fallbackLog) ) { #} create default fallback log, unless $fallbackLog is set to 'none' if ($fallbackLog !== 'none'){ #} Autogen #} Left this out for v1.1.18... needs thought. #} Do we really want to put "woo source added"? It might get added loads. #} For now leave as manual... } } elseif (is_array($fallbackLog)){ #} Fallback log is probably set, just pass it along. $fallbackLogToPass = $fallbackLog; } #} Here we're passing along any automator pass through #} ... which will typically be overrides for creation logs or any extra params to give to internal automator. $automatorPassthrough = false; if (isset($automatorPassthroughArray) && is_array($automatorPassthroughArray)) $automatorPassthrough = $automatorPassthroughArray; #} Brutal add/update $transactionWPID = zeroBS_addUpdateTransaction($potentialTransactionID, $transactionFields, $transactionExternalSource, $transactionExternalID, $transactionDate, $transactionTags, $fallbackLogToPass, $extraMeta, $automatorPassthrough,$fieldPrefix); #} Update any title #} Not needed for transactions: if ($transactionWPID !== false) zbsCustomer_updateCompanyNameInPostTitle($companyID,false); return $transactionWPID; } else { // no source/id/fields return false; } } // phpcs:ignore Squiz.Commenting.FunctionComment.Missing function zeroBS_integrations_addOrUpdateTask( $task_id = -1, /* Req - the task ID */ $data_array = array(), /* Req: title,to, from */ $task_reminders = array() /* Req: remind_at,sent (v3+) */ ) { #} Check req. if ( is_array( $data_array ) && count( $data_array ) > 0 && ! empty( $data_array['title'] ) && ( // old params ( ! empty( $data_array['to'] ) && ! empty( $data_array['from'] ) ) || // new params ( ! empty( $data_array['start'] ) && ! empty( $data_array['end'] ) ) ) ) { return zeroBS_addUpdateEvent( $task_id, $data_array, $task_reminders ); } else { // no source/id/fields return false; } } /* |======================================= | zeroBS_integrations_getTransaction |======================================= | Retrieves a transaction record (as usual _getTransaction func) - but one that has been inserted via import from an external source | E.g. Woo Imported, Paypal imported, whatever | A transaction can exist with multiple import IDs, which lets us patch across services. | E.g. transaction has a woo id of 1234, and a paypal transaction id of x3da9j3d9jad2 | Then that transaction could be called with either of these, but would get the same main "transaction" record | zeroBS_integrations_getTransaction('woo','1234') | zeroBS_integrations_getTransaction('pay','x3da9j3d9jad2') |======================================= | Returns: | transaction obj (std class) | or | False (boolean) (transaction does not exist) |======================================= | Check via: if ($transobj !== false) |======================================= */ function zeroBS_integrations_getTransaction($transactionExternalSource='',$transactionExternalID=''){ #} Do query for ID $potentialTransactionID = zeroBS_getTransactionIDWithExternalSource($transactionExternalSource,$transactionExternalID); if ($potentialTransactionID !== false){ #} If so, pass full deets via this return zeroBS_getTransaction($potentialTransactionID); } #} If it gets here, it failed return false; } /* For now a wrapper, later will allow us to seemlessly feed in customer generated cats */ function zeroBS_integrations_getAllCategories($incEmpty=false){ global $zbs; if ($zbs->isDAL2()){ return array('zerobscrm_customertag' => $zbs->DAL->getTagsForObjType(array( 'objtypeid'=>ZBS_TYPE_CONTACT, 'excludeEmpty'=>!$incEmpty, 'withCount'=>true, 'ignoreowner' => true, // sort 'sortByField' => 'zbstag_name', 'sortOrder' => 'ASC' ))); } else { // DAL1 if (!$incEmpty){ $cats = array( #'zerobscrm_worktag' => get_categories(array('taxonomy'=>'zerobscrm_worktag','orderby' => 'name','order'=> 'ASC'))#, #Other Tags? 'zerobscrm_customertag' => get_categories(array('taxonomy'=>'zerobscrm_customertag','orderby' => 'name','order'=> 'ASC')) ); } else { $cats = array( #'zerobscrm_worktag' => get_categories(array('taxonomy'=>'zerobscrm_worktag','orderby' => 'name','order'=> 'ASC'))#, #Other Tags? 'zerobscrm_customertag' => get_terms(array('taxonomy'=>'zerobscrm_customertag','orderby' => 'name','order'=> 'ASC','hide_empty' => false)) ); } } return $cats; } #} For now just a wrapper function zeroBS_integrations_searchCustomers($args=array()){ if (!empty($args) && isset($args['searchPhrase'])) return zeroBS_searchCustomers($args); return array(); } #} Add log (currently a wrapper) function zeroBS_integrations_addLog( $objID = -1, /* - is add, doesn't need this: $logID = -1, */ $logDate = -1, /* NOTE!: as of 31/05/17 WOODY started putting 'meta_assoc_id' in these - e.g. if it's an 'email sent' log, this meta_assoc_id will be the CAMPAIGN id 'meta_assoc_src' would then be mailcamp */ $noteFields = array(), /* DB2 requires obj type, for now we use zerobs_customer etc. but later we will make these interchangable with TYPES e.g. ZBS_TYPE_CONTACT */ $objType = '' ){ if (!empty($objID)){ #} Add fresh log: zeroBS_addUpdateLog($objID,-1,$logDate,$noteFields,$objType); return true; } return false; } // WH added, backward compat: // only works DAL2 + function zeroBS_integrations_getCustomFields($objTypeID=-1){ $objTypeID = (int)$objTypeID; if ($objTypeID > 0){ global $zbs; if ($zbs->isDAL2()) return $zbs->DAL->getActiveCustomFields(array('objtypeid'=>$objTypeID)); } return array(); } /* ====================================================== / Integration specific extension functions ====================================================== */
projects/plugins/crm/includes/ZeroBSCRM.MetaBoxes3.QuoteTemplates.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V3.0 * * Copyright 2020 Automattic * * Date: 20/02/2019 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== Init Func ====================================================== */ function zeroBSCRM_QuotesTemplatesMetaboxSetup(){ // main detail $zeroBS__Metabox_QuoteTemplate = new zeroBS__Metabox_QuoteTemplate( __FILE__ ); // save $zeroBS__Metabox_QuoteTemplateActions = new zeroBS__Metabox_QuoteTemplateActions( __FILE__ ); } add_action( 'admin_init','zeroBSCRM_QuotesTemplatesMetaboxSetup'); /* ====================================================== / Init Func ====================================================== */ /* ====================================================== Quote Template Metabox ====================================================== */ class zeroBS__Metabox_QuoteTemplate extends zeroBS__Metabox{ // this is for catching 'new' quote templates private $newRecordNeedsRedir = false; public function __construct( $plugin_file ) { // set these $this->objType = 'quotetemplate'; $this->metaboxID = 'zerobs-quote-template-edit'; $this->metaboxTitle = __('Quote Template','zero-bs-crm'); // will be headless anyhow $this->metaboxScreen = 'zbs-add-edit-quotetemplate-edit'; $this->metaboxArea = 'normal'; $this->metaboxLocation = 'high'; $this->saveOrder = 1; $this->capabilities = array( 'can_hide' => false, // can be hidden 'areas' => array('normal'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => true, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true, // can be minimised 'can_move' => true // can be moved ); // call this $this->initMetabox(); } public function html( $quoteTemplate, $metabox ) { global $zbs; // localise ID $quoteTemplateID = -1; if (is_array($quoteTemplate) && isset($quoteTemplate['id'])) $quoteTemplateID = (int)$quoteTemplate['id']; $quoteTemplateContent = ''; if (is_array($quoteTemplate) && isset($quoteTemplate['content'])) $quoteTemplateContent = $quoteTemplate['content']; ?> <script type="text/javascript">var zbscrmjs_secToken = '<?php echo esc_js( wp_create_nonce( 'zbscrmjs-ajax-nonce' ) ); ?>';</script> <?php // pass specific placeholder list for WYSIWYG inserter // <TBC> is there a better place to pass this? $placeholder_templating = $zbs->get_templating(); $placeholder_list = $placeholder_templating->get_placeholders_for_tooling( array( 'quote', 'contact', 'global' ), false, false ); echo '<script>var jpcrm_placeholder_list = ' . json_encode( $placeholder_templating->simplify_placeholders_for_wysiwyg( $placeholder_list ) ) . ';</script>'; // Fields: // CPT just had Title + Content // DAL3 has more :) #} Retrieve fields from global /* this is all debug global $zbsCustomerQuoteFields; $fields2 = $zbsCustomerQuoteFields; // Debug echo 'Fields:<pre>'.print_r($fields2,1).'</pre>'; $fields3 = $zbs->DAL->quotetemplates->generateFieldsGlobalArr(); echo 'Fields2:<pre>'.print_r($fields3,1).'</pre>'; exit(); */ // for mvp v3.0 we now just hard-type these, as there a lesser obj rarely used. $fields = array( 'title' => array( 0 => 'text', 1 => __('Template Title','zero-bs-crm'), 2 => '', // placeholder 'essential' => 1 ), 'value' => array( 0 => 'price', 1 => __('Starting Value','zero-bs-crm'), 2 => '', // placeholder 'essential' => 1 ), 'notes' => array( 0 => 'textarea', 1 => __('Notes','zero-bs-crm'), 2 => '', // placeholder 'essential' => 1 ) ); ?> <div> <div class="jpcrm-form-grid" id="wptbpMetaBoxMainItem"> <?php // output fields $skipFields = array('content'); // dealt with below zeroBSCRM_html_editFields($quoteTemplate,$fields,'zbsqt_',$skipFields); ##WLREMOVE // template placeholder helper echo '<div class="jpcrm-form-group jpcrm-form-group-span-2" style="text-align:end;"><span class="ui basic black label">' . esc_html__( 'Did you know: You can now use Quote Placeholders?', 'zero-bs-crm' ) . ' <a href="' . esc_url( $zbs->urls['kbquoteplaceholders'] ) . '" target="_blank">' . esc_html__( 'Read More', 'zero-bs-crm' ) . '</a></span></div>'; ##/WLREMOVE $content = wp_kses( $quoteTemplateContent, $zbs->acceptable_html ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase echo '<div class="jpcrm-form-group jpcrm-form-group-span-2">'; // remove "Add contact form" button from Jetpack remove_action( 'media_buttons', 'grunion_media_button', 999 ); wp_editor( $content, 'zbs_quotetemplate_content', array( 'editor_height' => 580 )); echo '</div>'; ?> </div></div> <?php } public function save_data( $quoteTemplateID, $quoteTemplate ) { if (!defined('ZBS_OBJ_SAVED')){ define('ZBS_OBJ_SAVED',1); // DAL3.0+ global $zbs; // check this if (empty($quoteTemplateID) || $quoteTemplateID < 1) $quoteTemplateID = -1; /* old way: Was previously just a CPT */ $extraMeta = array(); // retrieve _POST into arr $autoGenAutonumbers = true; // generate if not set $quoteTemplate = zeroBS_buildObjArr($_POST,array(),$fieldPrefix='zbsqt_',$outputPrefix='',false,ZBS_TYPE_QUOTETEMPLATE,$autoGenAutonumbers); // content (from other metabox actually) if (isset($_POST['zbs_quotetemplate_content'])) { #} Save content $quoteTemplate['content'] = wp_kses( $_POST['zbs_quotetemplate_content'], $zbs->acceptable_html ); //phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase,WordPress.Security.NonceVerification.Missing,WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- to follow up with. #} update templated vars // Think this was here in err... if (isset($_POST['zbs_quote_template_id_used'])) $quote['template'] = (int)sanitize_text_field($_POST['zbs_quote_template_id_used']); } // Debug echo 'updating: <pre>'.print_r($quoteTemplate,1).'</pre>'; exit(); // add/update $addUpdateReturn = $zbs->DAL->quotetemplates->addUpdateQuoteTemplate(array( 'id' => $quoteTemplateID, 'data' => $quoteTemplate, 'extraMeta' => $extraMeta, 'limitedFields' => -1 )); // Note: For NEW objs, we make sure a global is set here, that other update funcs can catch // ... so it's essential this one runs first! // this is managed in the metabox Class :) if ($quoteTemplateID == -1 && !empty($addUpdateReturn) && $addUpdateReturn != -1) { $quoteTemplateID = $addUpdateReturn; global $zbsJustInsertedMetaboxID; $zbsJustInsertedMetaboxID = $quoteTemplateID; // set this so it redirs $this->newRecordNeedsRedir = true; } // success? if ($addUpdateReturn != -1 && $addUpdateReturn > 0){ // Update Msg // this adds an update message which'll go out ahead of any content // This adds to metabox: $this->updateMessages['update'] = zeroBSCRM_UI2_messageHTML('info olive mini zbs-not-urgent',__('Contact Updated',"zero-bs-crm"),'','address book outline','contactUpdated'); // This adds to edit page $this->updateMessage(); // catch any non-critical messages $nonCriticalMessages = $zbs->DAL->getErrors(ZBS_TYPE_QUOTETEMPLATE); if (is_array($nonCriticalMessages) && count($nonCriticalMessages) > 0) $this->dalNoticeMessage($nonCriticalMessages); } else { // fail somehow $failMessages = $zbs->DAL->getErrors(ZBS_TYPE_QUOTETEMPLATE); // show msg (retrieved from DAL err stack) if (is_array($failMessages) && count($failMessages) > 0) $this->dalErrorMessage($failMessages); else $this->dalErrorMessage(array(__('Insert/Update Failed with general error','zero-bs-crm'))); // pass the pre-fill: global $zbsObjDataPrefill; $zbsObjDataPrefill = $quoteTemplate; } } return $quoteTemplate; } // This catches 'new' contacts + redirs to right url public function post_save_data($objID,$obj){ if ($this->newRecordNeedsRedir){ global $zbsJustInsertedMetaboxID; if (!empty($zbsJustInsertedMetaboxID) && $zbsJustInsertedMetaboxID > 0){ // redir wp_redirect( jpcrm_esc_link('edit',$zbsJustInsertedMetaboxID,$this->objType) ); exit; } } } public function updateMessage(){ global $zbs; // zbs-not-urgent means it'll auto hide after 1.5s // genericified from DAL3.0 $msg = zeroBSCRM_UI2_messageHTML('info olive mini zbs-not-urgent',$zbs->DAL->typeStr($zbs->DAL->objTypeKey($this->objType)).' '.__('Updated',"zero-bs-crm"),'','address book outline','contactUpdated'); $zbs->pageMessages[] = $msg; } } /* ====================================================== / Quote Template Metabox ====================================================== */ /* ====================================================== Quote Template Actions Metabox ====================================================== */ class zeroBS__Metabox_QuoteTemplateActions extends zeroBS__Metabox{ public function __construct( $plugin_file ) { // set these $this->objType = 'quotetemplate'; $this->metaboxID = 'zerobs-quotetemplate-actions'; $this->metaboxTitle = __('Quote Template','zero-bs-crm').' '.__('Actions','zero-bs-crm'); // will be headless anyhow $this->headless = true; $this->metaboxScreen = 'zbs-add-edit-quotetemplate-edit'; $this->metaboxArea = 'side'; $this->metaboxLocation = 'high'; $this->saveOrder = 1; $this->capabilities = array( 'can_hide' => false, // can be hidden 'areas' => array('side'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => true, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true, // can be minimised 'can_move' => true // can be moved ); // call this $this->initMetabox(); } public function html( $quoteTemplate, $metabox ) { ?><div class="zbs-generic-save-wrap"> <div class="ui medium dividing header"><i class="save icon"></i> <?php esc_html_e('Template','zero-bs-crm'); ?> <?php esc_html_e('Actions','zero-bs-crm'); ?></div> <?php // localise ID & content $quoteTemplateID = -1; if (is_array($quoteTemplate) && isset($quoteTemplate['id'])) $quoteTemplateID = (int)$quoteTemplate['id']; #} if a saved obj... if ($quoteTemplateID > 0){ // existing ?> <div class="zbs-quotetemplate-actions-bottom zbs-objedit-actions-bottom"> <button class="ui button black" type="button" id="zbs-edit-save"><?php esc_html_e( 'Update', 'zero-bs-crm' ); ?> <?php esc_html_e( 'Template', 'zero-bs-crm' ); ?></button> <?php // delete? // for now just check if can modify, later better, granular perms. if ( zeroBSCRM_permsQuotes() ) { ?><div id="zbs-quotetemplate-actions-delete" class="zbs-objedit-actions-delete"> <a class="submitdelete deletion" href="<?php echo jpcrm_esc_link( 'delete', $quoteTemplateID, 'quotetemplate' ); ?>"><?php esc_html_e('Delete Permanently', "zero-bs-crm"); ?></a> </div> <?php } // can delete ?> <div class='clear'></div> </div> <?php } else { // NEW quote template ?> <div class="zbs-quotetemplate-actions-bottom zbs-objedit-actions-bottom"> <button class="ui button black" type="button" id="zbs-edit-save"><?php esc_html_e( 'Save', 'zero-bs-crm' ); ?> <?php esc_html_e( 'Template', 'zero-bs-crm' ); ?></button> </div> <?php } ?></div><?php // / .zbs-generic-save-wrap } // html // saved via main metabox } /* ====================================================== / Quote Template Action Metabox ====================================================== */
projects/plugins/crm/includes/ZeroBSCRM.List.Views.php
<?php // phpcs:ignore WordPress.Files.FileName.NotHyphenatedLowercase /* * Jetpack CRM * https://jetpackcrm.com * V1.0 * * Copyright 2020 Automattic * * Date: 26/05/16 */ // prevent direct access if ( ! defined( 'ZEROBSCRM_PATH' ) ) { exit; } /** * Renders the html for the contact list. * * @return void */ function zeroBSCRM_render_customerslist_page() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid global $zbs; // has no sync ext? Sell them $upsell_box_html = ''; // extra_js: $status_array = $zbs->settings->get( 'customisedfields' )['customers']['status']; $statuses = is_array( $status_array ) && isset( $status_array[1] ) ? explode( ',', $status_array[1] ) : array(); $extra_js = 'var zbsStatusesForBulkActions = ' . wp_json_encode( $statuses ) . ';'; // phpcs:ignore Squiz.PHP.CommentedOutCode.Found // Messages: // All messages need params to match this func: // ... zeroBSCRM_UI2_messageHTML($msgClass='',$msgHeader='',$msg='',$iconClass='',$id='') $messages = array(); $list = new zeroBSCRM_list( array( 'objType' => 'customer', 'singular' => esc_html__( 'Contact', 'zero-bs-crm' ), 'plural' => esc_html__( 'Contacts', 'zero-bs-crm' ), 'tag' => 'zerobscrm_customertag', 'postType' => 'zerobs_customer', 'postPage' => 'manage-customers', 'langLabels' => array( // bulk action labels 'deletecontacts' => esc_html__( 'Delete Contact(s)', 'zero-bs-crm' ), 'merge' => esc_html__( 'Merge Contacts', 'zero-bs-crm' ), 'export' => esc_html__( 'Export Contact(s)', 'zero-bs-crm' ), 'changestatus' => esc_html__( 'Change Status', 'zero-bs-crm' ), // bulk actions - change status 'statusupdated' => esc_html__( 'Statuses Updated', 'zero-bs-crm' ), 'statusnotupdated' => esc_html__( 'Could not update statuses!', 'zero-bs-crm' ), // bulk actions - contact deleting 'andthese' => esc_html__( 'Shall I also delete the associated Invoices, Quotes, Transactions, and Tasks?', 'zero-bs-crm' ), 'contactsdeleted' => esc_html__( 'Your contact(s) have been deleted.', 'zero-bs-crm' ), 'notcontactsdeleted' => esc_html__( 'Your contact(s) could not be deleted.', 'zero-bs-crm' ), // bulk actions - add/remove tags /* translators: placeholder is a link to add a new object tag */ 'notags' => wp_kses( sprintf( __( 'You do not have any contact tags. Do you want to <a target="_blank" href="%s">add a tag</a>?', 'zero-bs-crm' ), jpcrm_esc_link( 'tags', -1, 'zerobs_customer', false, 'contact' ) ), $zbs->acceptable_restricted_html ), // bulk actions - merge 2 records 'areyousurethesemerge' => esc_html__( 'Are you sure you want to merge these two contacts into one record? There is no way to undo this action.', 'zero-bs-crm' ) . '<br />', 'whichdominant' => esc_html__( 'Which is the "master" record (main record)?', 'zero-bs-crm' ), 'contactsmerged' => esc_html__( 'Contacts Merged', 'zero-bs-crm' ), 'contactsnotmerged' => esc_html__( 'Contacts could not be successfully merged', 'zero-bs-crm' ), // tel 'telhome' => esc_html__( 'Home', 'zero-bs-crm' ), 'telwork' => esc_html__( 'Work', 'zero-bs-crm' ), 'telmob' => esc_html__( 'Mobile', 'zero-bs-crm' ), ), 'bulkActions' => array( 'changestatus', 'delete', 'addtag', 'removetag', 'merge', 'export' ), 'unsortables' => array( 'tagged', 'editlink', 'phonelink' ), 'extraBoxes' => $upsell_box_html, 'extraJS' => $extra_js, 'messages' => $messages, ) ); $list->drawListView(); } /** * Renders the html for the companies list. * * @return void */ function zeroBSCRM_render_companyslist_page() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid global $zbs; $list = new zeroBSCRM_list( array( 'objType' => 'company', 'singular' => esc_html( jpcrm_label_company() ), 'plural' => esc_html( jpcrm_label_company( true ) ), 'tag' => 'zerobscrm_companytag', 'postType' => 'zerobs_company', 'postPage' => 'manage-companies', 'langLabels' => array( // bulk action labels /* translators: placeholder is the company label */ 'deletecompanys' => esc_html( sprintf( __( 'Delete %s(s)', 'zero-bs-crm' ), jpcrm_label_company() ) ), 'addtags' => esc_html__( 'Add tag(s)', 'zero-bs-crm' ), 'removetags' => esc_html__( 'Remove tag(s)', 'zero-bs-crm' ), 'export' => esc_html__( 'Export', 'zero-bs-crm' ), // bulk actions - company deleting 'andthese' => esc_html__( 'Shall I also delete the associated Contacts, Invoices, Quotes, Transactions, and Tasks? (This cannot be undone!)', 'zero-bs-crm' ), 'companysdeleted' => esc_html__( 'Your company(s) have been deleted.', 'zero-bs-crm' ), 'notcompanysdeleted' => esc_html__( 'Your company(s) could not be deleted.', 'zero-bs-crm' ), // bulk actions - add/remove tags /* translators: placeholder is a link to add a new object tag */ 'notags' => wp_kses( sprintf( __( 'You do not have any company tags. Do you want to <a target="_blank" href="%s">add a tag</a>?', 'zero-bs-crm' ), jpcrm_esc_link( 'tags', -1, 'zerobs_company', false, 'company' ) ), $zbs->acceptable_restricted_html ), ), 'bulkActions' => array( 'delete', 'addtag', 'removetag', 'export' ), // phpcs:ignore Squiz.PHP.CommentedOutCode.Found // default 'sortables' => array('id'), // default 'unsortables' => array('tagged','latestlog','editlink','phonelink') ) ); $list->drawListView(); } /** * Renders the html for the quotes list. * * @return void */ function zeroBSCRM_render_quoteslist_page() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid global $zbs; $list = new zeroBSCRM_list( array( 'objType' => 'quote', 'singular' => esc_html__( 'Quote', 'zero-bs-crm' ), 'plural' => esc_html__( 'Quotes', 'zero-bs-crm' ), 'tag' => '', 'postType' => 'zerobs_quote', 'postPage' => 'manage-quotes', 'langLabels' => array( 'markaccepted' => esc_html__( 'Mark Accepted', 'zero-bs-crm' ), 'markunaccepted' => esc_html__( 'Unmark Accepted', 'zero-bs-crm' ), 'delete' => esc_html__( 'Delete Quote(s)', 'zero-bs-crm' ), 'export' => esc_html__( 'Export Quote(s)', 'zero-bs-crm' ), 'andthese' => esc_html__( 'Shall I also delete the associated Invoices, Quotes, Transactions, and Tasks?', 'zero-bs-crm' ), 'quotesdeleted' => esc_html__( 'Your quote(s) have been deleted.', 'zero-bs-crm' ), 'notquotesdeleted' => esc_html__( 'Your quote(s) could not be deleted.', 'zero-bs-crm' ), 'acceptareyousurequotes' => esc_html__( 'Are you sure you want to mark these quotes as accepted?', 'zero-bs-crm' ), 'acceptdeleted' => esc_html__( 'Quote(s) Accepted', 'zero-bs-crm' ), 'acceptquotesdeleted' => esc_html__( 'Your quote(s) have been marked accepted.', 'zero-bs-crm' ), 'acceptnotdeleted' => esc_html__( 'Could not mark accepted!', 'zero-bs-crm' ), 'acceptnotquotesdeleted' => esc_html__( 'Your quote(s) could not be marked accepted.', 'zero-bs-crm' ), 'unacceptareyousurethese' => esc_html__( 'Are you sure you want to mark these quotes as unaccepted?', 'zero-bs-crm' ), 'unacceptdeleted' => esc_html__( 'Quote(s) Unaccepted', 'zero-bs-crm' ), 'unacceptquotesdeleted' => esc_html__( 'Your quote(s) have been marked unaccepted.', 'zero-bs-crm' ), 'unacceptnotdeleted' => esc_html__( 'Could not mark unaccepted!', 'zero-bs-crm' ), 'unacceptnotquotesdeleted' => esc_html__( 'Your quote(s) could not be marked unaccepted.', 'zero-bs-crm' ), /* translators: placeholder is a link to add a new object tag */ 'notags' => wp_kses( sprintf( __( 'You do not have any quote tags. Do you want to <a target="_blank" href="%s">add a tag</a>?', 'zero-bs-crm' ), jpcrm_esc_link( 'tags', -1, 'zerobs_quote', false, 'quote' ) ), $zbs->acceptable_restricted_html ), ), 'bulkActions' => array( 'markaccepted', 'markunaccepted', 'addtag', 'removetag', 'delete', 'export' ), // phpcs:ignore Squiz.PHP.CommentedOutCode.Found // default 'sortables' => array('id'), // default 'unsortables' => array('tagged','latestlog','editlink','phonelink') ) ); $list->drawListView(); } /** * Renders the html for the invoices list. * * @return void */ function zeroBSCRM_render_invoiceslist_page() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid global $zbs; $upsell_box_html = ''; $bundle = false; if ( $zbs->hasEntrepreneurBundleMin() ) { $bundle = true; } if ( ! zeroBSCRM_isExtensionInstalled( 'invpro' ) ) { if ( ! $bundle ) { $upsell_box_html = '<!-- Inv PRO box --><div class="">'; $up_title = esc_html__( 'Supercharged Invoicing', 'zero-bs-crm' ); $up_desc = esc_html__( 'Get more out of invoicing, like accepting online payments!', 'zero-bs-crm' ); $up_button = esc_html__( 'Get Invoicing Pro', 'zero-bs-crm' ); $up_target = $zbs->urls['invpro']; $upsell_box_html .= zeroBSCRM_UI2_squareFeedbackUpsell( $up_title, $up_desc, $up_button, $up_target ); $upsell_box_html .= '</div><!-- / Inv PRO box -->'; } else { $upsell_box_html = '<!-- Inv PRO box --><div class="">'; $up_title = esc_html__( 'Supercharged Invoicing', 'zero-bs-crm' ); $up_desc = esc_html__( 'You have Invoicing Pro available because you are using a bundle. Please download and install from your account:', 'zero-bs-crm' ); $up_button = esc_html__( 'Your Account', 'zero-bs-crm' ); $up_target = $zbs->urls['account']; $upsell_box_html .= zeroBSCRM_UI2_squareFeedbackUpsell( $up_title, $up_desc, $up_button, $up_target ); $upsell_box_html .= '</div><!-- / Inv PRO box -->'; } } $list = new zeroBSCRM_list( array( 'objType' => 'invoice', 'singular' => esc_html__( 'Invoice', 'zero-bs-crm' ), 'plural' => esc_html__( 'Invoices', 'zero-bs-crm' ), 'tag' => '', 'postType' => 'zerobs_invoice', 'postPage' => 'manage-invoices', 'langLabels' => array( // bulk action labels 'delete' => esc_html__( 'Delete Invoice(s)', 'zero-bs-crm' ), 'export' => esc_html__( 'Export Invoice(s)', 'zero-bs-crm' ), // bulk actions - invoice deleting 'invoicesdeleted' => esc_html__( 'Your invoice(s) have been deleted.', 'zero-bs-crm' ), 'notinvoicesdeleted' => esc_html__( 'Your invoice(s) could not be deleted.', 'zero-bs-crm' ), // bulk actions - invoice status update 'statusareyousurethese' => esc_html__( 'Are you sure you want to change the status on marked invoice(s)?', 'zero-bs-crm' ), 'statusupdated' => esc_html__( 'Invoice(s) Updated', 'zero-bs-crm' ), 'statusinvoicesupdated' => esc_html__( 'Your invoice(s) have been updated.', 'zero-bs-crm' ), 'statusnotupdated' => esc_html__( 'Could not update invoice!', 'zero-bs-crm' ), 'statusnotinvoicesupdated' => esc_html__( 'Your invoice(s) could not be updated', 'zero-bs-crm' ), 'statusdraft' => esc_html__( 'Draft', 'zero-bs-crm' ), 'statusunpaid' => esc_html__( 'Unpaid', 'zero-bs-crm' ), 'statuspaid' => esc_html__( 'Paid', 'zero-bs-crm' ), 'statusoverdue' => esc_html__( 'Overdue', 'zero-bs-crm' ), 'statusdeleted' => esc_html__( 'Deleted', 'zero-bs-crm' ), // bulk actions - add/remove tags /* translators: placeholder is a link to add a new object tag */ 'notags' => wp_kses( sprintf( __( 'You do not have any invoice tags. Do you want to <a target="_blank" href="%s">add a tag</a>?', 'zero-bs-crm' ), jpcrm_esc_link( 'tags', -1, 'zerobs_invoice', false, 'invoice' ) ), $zbs->acceptable_restricted_html ), ), 'bulkActions' => array( 'changestatus', 'addtag', 'removetag', 'delete', 'export' ), 'extraBoxes' => $upsell_box_html, ) ); $list->drawListView(); } /** * Renders the html for the transactions list. * * @return void */ function zeroBSCRM_render_transactionslist_page() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid global $zbs; $list = new zeroBSCRM_list( array( 'objType' => 'transaction', 'singular' => esc_html__( 'Transaction', 'zero-bs-crm' ), 'plural' => esc_html__( 'Transactions', 'zero-bs-crm' ), 'tag' => 'zerobscrm_transactiontag', 'postType' => 'zerobs_transaction', 'postPage' => 'manage-transactions', 'langLabels' => array( // bulk action labels 'delete' => esc_html__( 'Delete Transaction(s)', 'zero-bs-crm' ), 'export' => esc_html__( 'Export Transaction(s)', 'zero-bs-crm' ), // bulk actions - add/remove tags /* translators: placeholder is a link to add a new object tag */ 'notags' => wp_kses( sprintf( __( 'You do not have any transaction tags. Do you want to <a target="_blank" href="%s">add a tag</a>?', 'zero-bs-crm' ), jpcrm_esc_link( 'tags', -1, 'zerobs_transaction', false, 'transaction' ) ), $zbs->acceptable_restricted_html ), // statuses 'trans_status_cancelled' => esc_html__( 'Cancelled', 'zero-bs-crm' ), 'trans_status_hold' => esc_html__( 'Hold', 'zero-bs-crm' ), 'trans_status_pending' => esc_html__( 'Pending', 'zero-bs-crm' ), 'trans_status_processing' => esc_html__( 'Processing', 'zero-bs-crm' ), 'trans_status_refunded' => esc_html__( 'Refunded', 'zero-bs-crm' ), 'trans_status_failed' => esc_html__( 'Failed', 'zero-bs-crm' ), 'trans_status_completed' => esc_html__( 'Completed', 'zero-bs-crm' ), 'trans_status_succeeded' => esc_html__( 'Succeeded', 'zero-bs-crm' ), ), 'bulkActions' => array( 'addtag', 'removetag', 'delete', 'export' ), 'sortables' => array( 'id' ), 'unsortables' => array( 'tagged', 'latestlog', 'editlink', 'phonelink' ), ) ); $list->drawListView(); } /** * Renders the html for the forms list. * * @return void */ function zeroBSCRM_render_formslist_page() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid // has no sync ext? Sell them $upsell_box_html = ''; // has sync ext? Give feedback if ( ! zeroBSCRM_hasPaidExtensionActivated() ) { ##WLREMOVE // first build upsell box html $upsell_box_html = '<!-- Forms PRO box --><div class="">'; $upsell_box_html .= '<h4>' . esc_html__( 'Need More Complex Forms?', 'zero-bs-crm' ) . '</h4>'; $up_title = esc_html__( 'Fully Flexible Forms', 'zero-bs-crm' ); $up_desc = esc_html__( 'Jetpack CRM forms cover simple use contact and subscription forms, but if you need more we suggest using a form plugin like Contact Form 7 or Gravity Forms:', 'zero-bs-crm' ); $up_button = esc_html__( 'See Full Form Options', 'zero-bs-crm' ); $up_target = 'https://jetpackcrm.com/feature/forms/#benefit'; $upsell_box_html .= zeroBSCRM_UI2_squareFeedbackUpsell( $up_title, $up_desc, $up_button, $up_target ); $upsell_box_html .= '</div><!-- / Inv Forms box -->'; ##/WLREMOVE } $list = new zeroBSCRM_list( array( 'objType' => 'form', 'singular' => esc_html__( 'Form', 'zero-bs-crm' ), 'plural' => esc_html__( 'Forms', 'zero-bs-crm' ), 'tag' => '', 'postType' => 'zerobs_form', 'postPage' => 'manage-forms', 'langLabels' => array( 'naked' => esc_html__( 'Naked', 'zero-bs-crm' ), 'cgrab' => esc_html__( 'Content Grab', 'zero-bs-crm' ), 'simple' => esc_html__( 'Simple', 'zero-bs-crm' ), // bulk action labels 'delete' => esc_html__( 'Delete Form(s)', 'zero-bs-crm' ), 'export' => esc_html__( 'Export Form(s)', 'zero-bs-crm' ), // bulk actions - deleting 'formsdeleted' => esc_html__( 'Your form(s) have been deleted.', 'zero-bs-crm' ), 'notformsdeleted' => esc_html__( 'Your form(s) could not be deleted.', 'zero-bs-crm' ), ), 'bulkActions' => array( 'delete' ), // phpcs:ignore Squiz.PHP.CommentedOutCode.Found // default 'sortables' => array('id'), // default 'unsortables' => array('tagged','latestlog','editlink','phonelink') 'extraBoxes' => $upsell_box_html, ) ); $list->drawListView(); } /** * Renders the html for the segments list. * * @return void */ function zeroBSCRM_render_segmentslist_page() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid global $zbs; // Check that our segment conditions are all still available // (checking here allows us to expose errors on the list view if there are any) jpcrm_segments_compare_available_conditions_to_prev(); // has no sync ext? Sell them $upsell_box_html = ''; if ( ! zeroBSCRM_isExtensionInstalled( 'advancedsegments' ) ) { // first build upsell box html $upsell_box_html = '<div class="">'; $upsell_box_html .= '<h4>' . esc_html__( 'Using Segments?', 'zero-bs-crm' ) . '</h4>'; $up_title = esc_html__( 'Segment like a PRO', 'zero-bs-crm' ); $up_desc = esc_html__( 'Did you know that we\'ve made segments more advanced?', 'zero-bs-crm' ); $up_button = esc_html__( 'See Advanced Segments', 'zero-bs-crm' ); $up_target = $zbs->urls['advancedsegments']; $upsell_box_html .= zeroBSCRM_UI2_squareFeedbackUpsell( $up_title, $up_desc, $up_button, $up_target ); $upsell_box_html .= '</div>'; } else { // later this can point to https://kb.jetpackcrm.com/knowledge-base/how-to-get-customers-into-zero-bs-crm/ $upsell_box_html = '<div class="">'; $upsell_box_html .= '<h4>' . esc_html__( 'Got Feedback?', 'zero-bs-crm' ) . ':</h4>'; $up_title = esc_html__( 'Enjoying segments?', 'zero-bs-crm' ); $up_desc = esc_html__( 'As we grow Jetpack CRM, we\'re looking for feedback!', 'zero-bs-crm' ); $up_button = esc_html__( 'Send Feedback', 'zero-bs-crm' ); $up_target = "mailto:hello@jetpackcrm.com?subject='Segments%20Feedback'"; $upsell_box_html .= zeroBSCRM_UI2_squareFeedbackUpsell( $up_title, $up_desc, $up_button, $up_target ); $upsell_box_html .= '</div>'; } // pass this for filter links $extra_js = ''; if ( zeroBSCRM_getSetting( 'filtersfromsegments' ) == '1' ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual $extra_js = " var zbsSegmentViewStemURL = '" . jpcrm_esc_link( $zbs->slugs['managecontacts'] ) . '&quickfilters=segment_' . "';"; } $list = new zeroBSCRM_list( array( 'objType' => 'segment', 'singular' => esc_html__( 'Segment', 'zero-bs-crm' ), 'plural' => esc_html__( 'Segments', 'zero-bs-crm' ), 'tag' => '', 'postType' => 'segment', 'postPage' => $zbs->slugs['segments'], 'langLabels' => array( // compiled language 'lastCompiled' => esc_html__( 'Last Compiled', 'zero-bs-crm' ), 'notCompiled' => esc_html__( 'Not Compiled', 'zero-bs-crm' ), // bulk action labels 'deletesegments' => esc_html__( 'Delete Segment(s)', 'zero-bs-crm' ), 'export' => esc_html__( 'Export Segment(s)', 'zero-bs-crm' ), // bulk actions - segment deleting 'segmentsdeleted' => esc_html__( 'Your segment(s) have been deleted.', 'zero-bs-crm' ), 'notsegmentsdeleted' => esc_html__( 'Your segment(s) could not be deleted.', 'zero-bs-crm' ), // export segment 'exportcsv' => esc_html__( 'Export .CSV', 'zero-bs-crm' ), ), 'bulkActions' => array( 'delete' ), // phpcs:ignore Squiz.PHP.CommentedOutCode.Found // 'sortables' => array('id'), 'unsortables' => array( 'audiencecount', 'action', 'added' ), 'extraBoxes' => $upsell_box_html, 'extraJS' => $extra_js, ) ); $list->drawListView(); } /** * Renders the html for the quote templates list. * * @return void */ function zeroBSCRM_render_quotetemplateslist_page() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid // has no sync ext? Sell them $upsell_box_html = ''; $list = new zeroBSCRM_list( array( 'objType' => 'quotetemplate', 'singular' => esc_html__( 'Quote Template', 'zero-bs-crm' ), 'plural' => esc_html__( 'Quote Templates', 'zero-bs-crm' ), 'tag' => '', 'postType' => 'zerobs_quo_template', 'postPage' => 'manage-quote-templates', 'langLabels' => array( // bulk action labels 'delete' => esc_html__( 'Delete Quote Template(s)', 'zero-bs-crm' ), 'export' => esc_html__( 'Export Quote Template(s)', 'zero-bs-crm' ), // for listview 'defaulttemplate' => esc_html__( 'Default Template', 'zero-bs-crm' ), 'deletetemplate' => esc_html__( 'Delete Template', 'zero-bs-crm' ), // bulk actions - quote template deleting 'quotetemplatesdeleted' => esc_html__( 'Your Quote template(s) have been deleted.', 'zero-bs-crm' ), 'notquotetemplatesdeleted' => esc_html__( 'Your Quote template(s) could not be deleted.', 'zero-bs-crm' ), ), 'bulkActions' => array( 'delete' ), 'extraBoxes' => $upsell_box_html, ) ); $list->drawListView(); } /** * Renders the html for the tasks list. * * @return void */ function zeroBSCRM_render_tasks_list_page() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid // has no sync ext? Sell them $upsell_box_html = ''; $list = new zeroBSCRM_list( array( 'objType' => 'event', 'singular' => esc_html__( 'Task', 'zero-bs-crm' ), 'plural' => esc_html__( 'Tasks', 'zero-bs-crm' ), 'tag' => '', 'postType' => 'zerobs_event', 'postPage' => 'manage-tasks-list', 'langLabels' => array( // Status 'incomplete' => esc_html__( 'Incomplete', 'zero-bs-crm' ), 'complete' => esc_html__( 'Complete', 'zero-bs-crm' ), // bulk action labels 'delete' => esc_html__( 'Delete Task(s)', 'zero-bs-crm' ), 'markcomplete' => esc_html__( 'Mark Task(s) Completed', 'zero-bs-crm' ), 'markincomplete' => esc_html__( 'Mark Task(s) Incomplete', 'zero-bs-crm' ), // bulk actions - task actions 'tasks_deleted' => esc_html__( 'Your Task(s) have been deleted.', 'zero-bs-crm' ), 'tasks_not_deleted' => esc_html__( 'Your Task(s) could not be deleted.', 'zero-bs-crm' ), 'areyousure_tasks_completed' => esc_html__( 'Are you sure you want to mark these tasks as completed?', 'zero-bs-crm' ), 'areyousure_tasks_incomplete' => esc_html__( 'Are you sure you want to mark these tasks as incomplete?', 'zero-bs-crm' ), 'tasks_marked' => esc_html__( 'Your Task(s) have been updated.', 'zero-bs-crm' ), 'tasks_not_marked' => esc_html__( 'Your Task(s) could not be updated.', 'zero-bs-crm' ), ), 'bulkActions' => array( 'addtag', 'removetag', 'delete', 'markcomplete', 'markincomplete' ), 'unsortables' => array( 'action', 'remind', 'company', 'contact', 'showcal' ), 'extraBoxes' => $upsell_box_html, ) ); $list->drawListView(); }
projects/plugins/crm/includes/ZeroBSCRM.PerformanceTesting.php
<?php /*! * Jetpack CRM * http://www.zerobscrm.com * V2.0 * * Copyright 2020 Automattic * * Date: 19/09/2017 */ /* (BASIC) PERFORMANCE TRACKING - include for use. */ #} Store times global $zbsTimes; if (!isset($zbsTimes)) $zbsTimes = array(); function zeroBSCRM_performanceTest_startTimer($key=''){ if (!empty($key)){ global $zbsTimes; if (!isset($zbsTimes[$key]) || !is_array($zbsTimes[$key])) $zbsTimes[$key] = array('start'=>-1,'end'=>-1); #} start it $zbsTimes[$key]['start'] = microtime(true); } return false; } function zeroBSCRM_performanceTest_finishTimer($key=''){ if (!empty($key)){ global $zbsTimes; #} end it - lazy, no cheeck $zbsTimes[$key]['end'] = microtime(true); } return false; } // returns singular results for 1 timer // (used by debugger plugin) function zeroBSCRM_performanceTest_results($key=''){ if (!empty($key)){ global $zbsTimes; if (is_array($zbsTimes) && isset($zbsTimes[$key])){ $v = $zbsTimes[$key]; $time_start = -1; if (isset($v['start'])) $time_start = $v['start']; $time_end = -1; if (isset($v['end'])) $time_end = $v['end']; $sTime = -1; $sTimeExtra = ''; if ($time_start > -1 && $time_end > -1) { $sTime = round(($time_end - $time_start),3); } else { // one hasn't been set if ($time_end == -1 && $time_start > -1){ $sTime = round((microtime(true)-$time_start),3); $sTimeExtra ='+ (still running)'; } else { $sTimeExtra = '???'; } } return $sTime.$sTimeExtra; } } return false; } function zeroBSCRM_performanceTest_debugOut(){ global $zbsTimes; // debug echo '<div><h1>CRM Performance Debug</h1>'; $scriptVer = 'console.log("=============== CRM Performance Debug ==============");'; foreach ($zbsTimes as $k => $v) { $time_start = -1; if (isset($v['start'])) $time_start = $v['start']; $time_end = -1; if (isset($v['end'])) $time_end = $v['end']; $sTime = -1; $sTimeExtra = ''; if ($time_start > -1 && $time_end > -1) { $sTime = round(($time_end - $time_start),3); } else { // one hasn't been set if ($time_end == -1 && $time_start > -1){ $sTime = round((microtime(true)-$time_start),3); $sTimeExtra ='+ (still running)'; } else { $sTimeExtra = '???'; } } echo '<h2>Time: '.$k.'</h2>'; echo '<p>'.$sTime.$sTimeExtra.' seconds</p>'; $retArr = $v; $retArr['took'] = $sTime; $scriptVer .= 'console.log("'.$k.': '.$sTime.$sTimeExtra.'",'.json_encode($retArr).');'; } echo '</div>'; echo '<script type="text/javascript">'.$scriptVer.'</script>'; } #} Start a global timer :) zeroBSCRM_performanceTest_startTimer('postinc'); // ==================================================================== // ==================== General Perf Testing ========================== function zeroBSCRM_performanceTest_closeGlobalTest($key=''){ if (defined('ZBSPERFTEST')) { if (!empty($key)){ // retrieve our global (may have had any number of test res added) global $zbsPerfTest; // finish timer zeroBSCRM_performanceTest_finishTimer($key); // store in perf-reports $zbsPerfTest['results'][$key] = zeroBSCRM_performanceTest_results($key); } } } /* This got abbreviated with above: // ==================================================================== // ==================== General Perf Testing ========================== if (defined('ZBSPERFTEST')) { // retrieve our global (may have had any number of test res added) global $zbsPerfTest; // start timer (will need a 'catch + add' for this at end of whatever this is timing) zeroBSCRM_performanceTest_startTimer('includes'); } // =================== / General Perf Testing ========================= // ==================================================================== // ==================================================================== // ==================== General Perf Testing ========================== if (defined('ZBSPERFTEST')) { // finish timer zeroBSCRM_performanceTest_finishTimer('includes'); // store in perf-reports $zbsPerfTest['results']['includes'] = zeroBSCRM_performanceTest_results('includes'); } // =================== / General Perf Testing ========================= // ==================================================================== // ==================================================================== // ==================== General Perf Testing ========================== if (defined('ZBSPERFTEST')) zeroBSCRM_performanceTest_startTimer('includes'); // =================== / General Perf Testing ========================= // ==================================================================== // ==================================================================== // ==================== General Perf Testing ========================== if (defined('ZBSPERFTEST')) zeroBSCRM_performanceTest_closeGlobalTest('key'); // =================== / General Perf Testing ========================= // ==================================================================== */
projects/plugins/crm/includes/class-segment-condition-exception.php
<?php /** * Jetpack CRM Segment Condition Exception Class * Extends Exception to provide additional data. * */ namespace Automattic\JetpackCRM; defined( 'ZEROBSCRM_PATH' ) || exit; /** * Segment Condition exception class. */ class Segment_Condition_Exception extends CRM_Exception {}
projects/plugins/crm/includes/ZeroBSCRM.ScriptsStyles.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V2.4+ * * Copyright 2020 Automattic * * Date: 06/02/18 */ #} =============================================================================== #} === INIT registration & Global Style & Script setups #} =============================================================================== // WH moved this from core.php in v3.0 (filing) // Registers globally used stuff (mostly) function zeroBSCRM_scriptStyles_initStyleRegister(){ global $zbs; // =========================================== // ================ Global ================= //registers the styles on admin init wp_register_style('zbs-wp-semanticui', plugins_url('/css/ZeroBSCRM.admin.semantic-ui'.wp_scripts_get_suffix().'.css',ZBS_ROOTFILE), array(), $zbs->version ); wp_register_script('semanticuijs' ,plugins_url('/js/lib/semantic.min.js',ZBS_ROOTFILE), array(), $zbs->version ); // global wp_register_style('zerobscrmadmcss', plugins_url('/css/ZeroBSCRM.admin.global'.wp_scripts_get_suffix().'.css',ZBS_ROOTFILE),array('zbs-wp-semanticui'), $zbs->version ); wp_enqueue_script('zerobscrmadmjs', plugins_url('/js/ZeroBSCRM.admin.global'.wp_scripts_get_suffix().'.js',ZBS_ROOTFILE), array( 'jquery' ), $zbs->version ); // emerald styles wp_register_style( 'jpcrm-emerald', plugins_url( '/css/jpcrm-emerald' . wp_scripts_get_suffix() . '.css', ZBS_ROOTFILE ), array(), $zbs->version ); // ================ / Global ================ // =========================================== // =========================================== // ============ Page-specific ============== // list view wp_register_style('zerobscrmlistview', plugins_url('/css/ZeroBSCRM.admin.listview'.wp_scripts_get_suffix().'.css',ZBS_ROOTFILE), array(), $zbs->version ); wp_register_script('zerobscrmlistviewjs', plugins_url('/js/ZeroBSCRM.admin.listview'.wp_scripts_get_suffix().'.js',ZBS_ROOTFILE), array( 'jquery' ),$zbs->version ); #} localise the list view... // WH note: Pretty sure we do this on page, so should janitor this up (later) $zbs_translation_array = array( 'zbs_edit' => __( 'Edit', 'zero-bs-crm' ), 'zbs_view'=> __( 'View', "zero-bs-crm") ); wp_localize_script( 'zerobscrmlistviewjs', 'zbs_lang', $zbs_translation_array ); // Single view wp_register_style('zerobscrmsingleview', plugins_url('/css/ZeroBSCRM.admin.singleview'.wp_scripts_get_suffix().'.css',ZBS_ROOTFILE), array(), $zbs->version ); wp_register_script('zerobscrmsingleview' ,plugins_url('/js/ZeroBSCRM.admin.singleview'.wp_scripts_get_suffix().'.js',ZBS_ROOTFILE), array( 'jquery' ),$zbs->version ); // edit view wp_register_style('zerobscrmeditview', plugins_url('/css/ZeroBSCRM.admin.editview'.wp_scripts_get_suffix().'.css',ZBS_ROOTFILE), array(), $zbs->version ); wp_register_script('zerobscrmeditviewjs', plugins_url('/js/ZeroBSCRM.admin.editview'.wp_scripts_get_suffix().'.js',ZBS_ROOTFILE), array( 'jquery' ), $zbs->version ); wp_register_script('zerobscrmtagmetaboxjs', plugins_url('/js/ZeroBSCRM.admin.tags.metabox'.wp_scripts_get_suffix().'.js',ZBS_ROOTFILE), array( 'jquery' ), $zbs->version ); // Metabox manager (rearrange them) wp_register_script('zerobscrmmm', plugins_url('/js/ZeroBSCRM.admin.metabox.manager'.wp_scripts_get_suffix().'.js',ZBS_ROOTFILE),array('jquery'), $zbs->version); // Segment Editor wp_register_style('zbs-segmentedit-css', plugins_url('/css/ZeroBSCRM.admin.segmentedit'.wp_scripts_get_suffix().'.css',ZBS_ROOTFILE), array(), $zbs->version ); wp_register_script('zbs-segmentedit-js',ZEROBSCRM_URL.'/js/ZeroBSCRM.admin.segmentedit'.wp_scripts_get_suffix().'.js',array('jquery'), $zbs->version ); // home dash wp_register_style('zerobscrmhomedash', plugins_url('/css/ZeroBSCRM.admin.homedash'.wp_scripts_get_suffix().'.css',ZBS_ROOTFILE), array('zbs-wp-semanticui'), $zbs->version ); // settings page wp_register_style('zerobscrmsettings', plugins_url('/css/ZeroBSCRM.admin.settings'.wp_scripts_get_suffix().'.css',ZBS_ROOTFILE), array(), $zbs->version ); // mail delivery wizard wp_register_style('zerobscrmmaildeliverywizard', plugins_url('/css/ZeroBSCRM.admin.maildeliverywizard'.wp_scripts_get_suffix().'.css',ZBS_ROOTFILE), array(), $zbs->version ); // systems page: wp_register_script('jpcrmadminsystem' ,plugins_url('/js/jpcrm-admin-system'.wp_scripts_get_suffix().'.js',ZBS_ROOTFILE), array( 'jquery' ), $zbs->version ); // ============ / Page-specific ============== // =========================================== // =========================================== // ============ Libs ======================= // jq ui wp_register_script('zerobscrmadmjqui', plugins_url('/js/lib/jquery-ui.min.js',ZBS_ROOTFILE), array( 'jquery' ), $zbs->version ); // above didn't seem to include all libs req for draggable, this does, specific build for listviews // 29/07/2017 http://jqueryui.com/download/#!version=1.12.1&components=111111111111111110000000010000000000000000000000 wp_register_script('zerobscrmadmjquidraggable', plugins_url('/js/lib/jquery-ui.1.12.1.dragdrop.listview.min.js',ZBS_ROOTFILE), array( 'jquery' ), $zbs->version ); // jq modal wp_register_style('zerobsjsmodal', plugins_url('/css/lib/jquery.modal.min.css',ZBS_ROOTFILE), array(), $zbs->version ); wp_register_script('zerobsjsmodal' ,plugins_url('/js/lib/jquery.modal.min.js',ZBS_ROOTFILE), array('jquery'), $zbs->version ); // font awesome wp_register_style('jpcrm-fontawesome-v4-4-0-core-css', plugins_url('/css/font-awesome.min.css',ZBS_ROOTFILE), array(), $zbs->version ); // chart.js wp_register_script('zerobscrmchartjs', plugins_url('/js/lib/chart.min.js',ZBS_ROOTFILE),array('jquery'), $zbs->version ); // funnel js wp_register_script('zerobscrmfunneljs', plugins_url('/js/lib/jquery.funnel.min.js',ZBS_ROOTFILE),array('jquery'), $zbs->version ); // sweet alerts - v2 v7.29.0 - 16th nov 18 wp_register_style('zerobscrmswa', plugins_url('/css/lib/sweetalert2-7.29.0.min.css',ZBS_ROOTFILE), array(), $zbs->version ); wp_enqueue_script('zerobscrmswa', plugins_url('/js/lib/sweetalert2-7.29.0.min.js',ZBS_ROOTFILE), array( 'jquery' ), $zbs->version ); #} Bloodhound (for typeahead) - use prefetch from https://twitter.github.io/typeahead.js/examples/ #} https://github.com/twitter/typeahead.js 0.11.1 wp_enqueue_script('zerobscrmtajs-0-11-1', plugins_url('/js/lib/typeahead.bundle.min.js',ZBS_ROOTFILE), array( 'jquery' ), $zbs->version ); // ============ / Libs ======================= // =========================================== // =========================================== // ============ Whitelabel ================= // WL css overrides (3/11/18 ++) // if the file exists, this registers + enqueues css if (file_exists( dirname( ZBS_ROOTFILE ) . '/css/wl.adm.override.css')) wp_enqueue_style('zbswladmcss', plugins_url('/css/wl.adm.override.css',ZBS_ROOTFILE), array('zerobscrmadmcss','zerobscrmlistview','zerobscrmeditview'), $zbs->version ); // ============ / Whitelabel ================= // =========================================== // LEGACY SUPPORT for ext's with menus if (zeroBSCRM_isAdminPage()){ zeroBSCRM_global_admin_styles(); } } // This builds our globally available jpcrm_root object with formatting etc. settings function zeroBSCRM_scriptStyles_enqueueJSRoot(){ global $zbs; // ================================================= // ================ Global JS ROOT ================= // here we expose root for js /i refs etc. // WH: we also give locale for datetimepickers everywhere (was zbsDateLocaleOverride, now window.zbs_root.localeOptions) /* var localeOpt = { format: "DD.MM.YYYY", cancelLabel: 'Clear' }; */ // WH: We also expose our number formats (for js $ formating) $zbscrm_currency_position = $zbs->settings->get( 'currency_position' ); $zbscrm_currency_format_thousand_separator = $zbs->settings->get( 'currency_format_thousand_separator' ); $zbscrm_currency_format_decimal_separator = $zbs->settings->get( 'currency_format_decimal_separator' ); $zbscrm_currency_format_number_of_decimals = $zbs->settings->get( 'currency_format_number_of_decimals' ); $jpcrm_root = array( 'crmname' => 'Jetpack CRM', 'root' => ZEROBSCRM_URL, 'localeOptions' => zeroBSCRM_date_localeForDaterangePicker(), 'locale' => get_locale(), 'locale_short' => zeroBSCRM_getLocale( false ), 'currencyOptions' => array( 'symbol' => zeroBSCRM_getCurrencyChr(), 'currencyStr' => zeroBSCRM_getCurrencyStr(), 'position' => $zbscrm_currency_position, 'thousandSeparator' => $zbscrm_currency_format_thousand_separator, 'decimalSeparator' => $zbscrm_currency_format_decimal_separator, 'noOfDecimals' => $zbscrm_currency_format_number_of_decimals, ), 'timezone_offset' => (int) get_option( 'gmt_offset' ), 'timezone_offset_mins' => ( (int) get_option( 'gmt_offset' ) * 60 ), 'wl' => ( zeroBSCRM_isWL() ? 1 : -1 ), 'dal' => 3, ); // this is for wl peeps, if set it'll override WYSIWYG logo + settings logo $jpcrm_root['crmlogo'] = 'i/icon-32.png'; // this is for GLOBAL js (language strings pass through) $lang_array = array(); // WH: not 100% sure where to put this, for now, temporarily, here, // WH: to decide common sense location (have made filter:) $lang_array['send'] = __( 'Send', 'zero-bs-crm' ); $lang_array['sent'] = __( 'Sent', 'zero-bs-crm' ); $lang_array['notsent'] = __( 'Not Sent', 'zero-bs-crm' ); $lang_array['cancel'] = __( 'Cancel', 'zero-bs-crm' ); $lang_array['contact'] = __( 'Contact', 'zero-bs-crm' ); $lang_array['company'] = __( 'Company', 'zero-bs-crm' ); $lang_array['viewall'] = __( 'View all', 'zero-bs-crm' ); // statement send $lang_array['sendstatement'] = __( 'Send Statement', 'zero-bs-crm' ); $lang_array['sendstatementaddr'] = __( 'Send Statement to Email:', 'zero-bs-crm' ); $lang_array['enteremail'] = __( 'Enter an Email Address..', 'zero-bs-crm' ); $lang_array['statementsent'] = __( 'Statement was successfully sent', 'zero-bs-crm' ); $lang_array['statementnotsent'] = __( 'Statement could not be sent at this time', 'zero-bs-crm' ); // totals table list view, (but generically useful) $lang_array['total'] = __( 'Total', 'zero-bs-crm' ); $lang_array['totals'] = __( 'Totals', 'zero-bs-crm' ); $lang_array['quote'] = __( 'Quote', 'zero-bs-crm' ); $lang_array['quotes'] = __( 'Quotes', 'zero-bs-crm' ); $lang_array['invoice'] = __( 'Invoice', 'zero-bs-crm' ); $lang_array['invoices'] = __( 'Invoices', 'zero-bs-crm' ); $lang_array['transaction'] = __( 'Transaction', 'zero-bs-crm' ); $lang_array['transactions'] = __( 'Transactions', 'zero-bs-crm' ); $lang_array = apply_filters( 'zbs_globaljs_lang', $lang_array ); if ( is_array( $lang_array ) && count( $lang_array ) > 0 ) { $jpcrm_root['lang'] = $lang_array; } $jpcrm_root['zbsnonce'] = wp_create_nonce( 'zbscrmjs-glob-ajax-nonce' ); // GENERIC links for building view/edit links in JS globally: // v3.0+ - returns a link with _TYPE_ instead of 'contact' etc. used by js func zeroBSCRMJS_obj_viewLink (globally avail) $generic_view_link = str_replace( 'contact', '_TYPE_', jpcrm_esc_link( 'view', -1, 'zerobs_customer', true ) ); // v3.0+ - returns a link with _TYPE_ instead of 'contact' etc. used by js func zeroBSCRMJS_obj_editLink (globally avail) $generic_edit_link = str_replace( 'contact', '_TYPE_', jpcrm_esc_link( 'edit', -1, 'zerobs_customer', true ) ); $jpcrm_root['links'] = array( 'generic_view' => $generic_view_link, 'generic_edit' => $generic_edit_link, ); ##WLREMOVE unset( $jpcrm_root['crmlogo'] ); ##/WLREMOVE $jpcrm_root['jp_green'] = jpcrm_get_jp_green(); // filter jpcrm_root, allows us to pass js vars directly into the js global via filter $jpcrm_root = apply_filters( 'zbs_globaljs_vars', $jpcrm_root ); wp_localize_script( 'zerobscrmadmjs', 'zbs_root', $jpcrm_root ); // This relies on the script being registered by zeroBSCRM_initStyleRegister() above } /** * Return an array of JP Green values */ function jpcrm_get_jp_green() { $jp_green = array( '0' => '#f0f2eb', '5' => '#d0e6b8', '10' => '#9dd977', '20' => '#64ca43', '30' => '#2fb41f', '40' => '#069e08', '50' => '#008710', '60' => '#007117', '70' => '#005b18', '80' => '#004515', '90' => '#003010', '100' => '#001c09', ); return $jp_green; } #} =============================================================================== #} === / INIT registration & Global Style & Script setups #} =============================================================================== #} =============================================================================== #} === Edit View individual type functions (e.g. quotebuilder) #} =============================================================================== // Cleaned from messy core.php routine in v3.0 function zeroBSCRM_scriptStyles_admin_quoteBuilder(){ global $zbs; wp_enqueue_style('zerobscrm-quotebuilder', plugins_url('/css/ZeroBSCRM.admin.quotebuilder'.wp_scripts_get_suffix().'.css',ZBS_ROOTFILE), array(), $zbs->version ); wp_enqueue_script('zerobscrm-quotebuilderjs', plugins_url('/js/ZeroBSCRM.admin.quotebuilder'.wp_scripts_get_suffix().'.js',ZBS_ROOTFILE), array( 'jquery' ), $zbs->version ); } // Cleaned from messy core.php routine in v3.0 // NOTE, this was firing on Invoice List View (WH removed 3.0), now only fires on invoice editor (correctly) function zeroBSCRM_scriptStyles_admin_invoiceBuilder(){ global $zbs; #} Bootstrap (for the modals) #} ONLY REQUIRED in invoice editor => AND welcome wizard tour now //wp_enqueue_script('zerobscrmbsjs', plugins_url('/js/lib/bootstrap.min.js',ZBS_ROOTFILE), array( 'jquery' )); #} MS invoice stuff. xxx wp_enqueue_style('zerobscrm-invoicebuilder', plugins_url('/css/ZeroBSCRM.admin.invoicebuilder'.wp_scripts_get_suffix().'.css',ZBS_ROOTFILE), array(), $zbs->version ); wp_enqueue_script('zerobscrm-invoicebuilderjs', plugins_url('/js/ZeroBSCRM.admin.invoicebuilder'.wp_scripts_get_suffix().'.js',ZBS_ROOTFILE), array( 'jquery', 'semanticuijs' ), $zbs->version ); //localise the invoice builder strings... $zbs_invtranslation_array = array( 'zbs_item_name' => __( 'Item Name', 'zero-bs-crm' ), 'zbs_item_desc' => __('Enter a detailed description (optional)',"zero-bs-crm"), 'zbs_add_row' => __('Add Row',"zero-bs-crm"), 'zbs_remove_row' => __('Remove Row',"zero-bs-crm") ); $zbs_links = array( 'admin_url' => admin_url() ); wp_localize_script( 'zerobscrm-invoicebuilderjs', 'zbs_lang', $zbs_invtranslation_array ); wp_localize_script( 'zerobscrm-invoicebuilderjs', 'zbs_links', $zbs_links); } // edit transaction page scripts. function zeroBSCRM_scriptStyles_admin_transactionBuilder(){ global $zbs; wp_enqueue_style('zerobscrmtranscss', plugins_url('/css/ZeroBSCRM.admin.transactionedit'.wp_scripts_get_suffix().'.css',ZBS_ROOTFILE), array(), $zbs->version ); wp_enqueue_script('zerobscrm-transedit-js', ZEROBSCRM_URL .'js/ZeroBSCRM.admin.transactioneditor'.wp_scripts_get_suffix().'.js', array('jquery'), $zbs->version ); } // Cleaned from messy core.php routine in v3.0 function zeroBSCRM_scriptStyles_admin_formBuilder(){ global $zbs; wp_enqueue_style('zerobscrmformcss', plugins_url('/css/ZeroBSCRM.admin.frontendforms'.wp_scripts_get_suffix().'.css',ZBS_ROOTFILE), array(), $zbs->version ); } #} =============================================================================== #} === / Edit View individual type functions (e.g. quotebuilder) #} =============================================================================== #} =============================================================================== #} === Unsorted Styles from pre v3.0 #} =============================================================================== function zeroBSCRM_global_admin_styles(){ global $zbs; // It seems we've got this firing multiple times, (WH spotted 2.4), so am putting this lame protection place. // Ideally need to stop it firing twice if (!defined('ZBS_GAS')){ //enqueue these (via the admin_print_styles-{$page}) // prev core wp_enqueue_style( 'zerobscrmadmcss' ); wp_enqueue_style( 'zerobsjsmodal' ); wp_enqueue_style( 'jpcrm-fontawesome-v4-4-0-core-css' ); wp_enqueue_style( 'zerobscrmswa' ); wp_enqueue_script( 'zerobsjsmodal'); // emerald styles wp_enqueue_style( 'jpcrm-emerald' ); // moment everywhere (from 2.98) wp_enqueue_script( 'jpcrm-moment-v2-29-4', untrailingslashit( ZEROBSCRM_URL ) . '/js/lib/moment-with-locales.min.js', array( 'jquery' ), $zbs->version, false ); // semantic everywhere (on our pages) wp_enqueue_style( 'zbs-wp-semanticui' ); wp_enqueue_script( 'semanticuijs'); // telemetry // V3.0 No more telemetry zeroBSCRM_teleLog(''); #}bootstrap JS (for onboarding tour...) //wp_enqueue_script('zerobscrmbsjs', plugins_url('/js/lib/bootstrap.min.js',ZBS_ROOTFILE), array( 'jquery' )); #} EDIT - using STANDALONE tour now instead do_action('zbs-global-admin-styles'); // DEFINE ZBS page :) if (!defined('ZBS_PAGE')) define('ZBS_PAGE',true); // DEFINE ZBS styles fired / dupe check protection if (!defined('ZBS_GAS')) define('ZBS_GAS',true); } // / dupe check protection } // 2.98.2 - MS styles tidy up that were inline // for the Extension Manager page (was inline) function zeroBSCRM_extension_admin_styles() { global $zbs; wp_register_style( 'zerobscrmexts', ZEROBSCRM_URL . 'css/ZeroBSCRM.admin.extensions-page' . wp_scripts_get_suffix() . '.css', array(), $zbs->version ); wp_enqueue_style( 'zerobscrmexts' ); } // 2.98.2 - MS tidy up of style into compressed sheet (was inline) function zeroBSCRM_intro_admin_styles() { global $zbs; wp_register_style( 'zerobscrmintro', ZEROBSCRM_URL . 'css/ZeroBSCRM.admin.intro' . wp_scripts_get_suffix() . '.css', array(), $zbs->version ); wp_enqueue_style( 'zerobscrmintro' ); } function zeroBSCRM_email_styles() { global $zbs; wp_register_style( 'zerobscrmemails', ZEROBSCRM_URL . 'css/ZeroBSCRM.admin.email' . wp_scripts_get_suffix() . '.css', array(), $zbs->version ); wp_enqueue_style( 'zerobscrmemails' ); wp_register_script( 'zerobsjsemail' , ZEROBSCRM_URL . 'js/ZeroBSCRM.admin.email' . wp_scripts_get_suffix() . '.js', array('jquery'), $zbs->version ); wp_enqueue_script( 'zerobsjsemail'); do_action( 'zbs_extra_email_script_styles' ); } function zeroBSCRM_admin_styles_ui2_listview(){ // semantic 2.2.11 (EVENTUALLY these PROBS shouldn't be global) wp_enqueue_style( 'zerobscrmlistview' ); wp_enqueue_script( 'semanticuijs'); // Removed at request of plugin reviewers. (used wp core ver) wp_enqueue_script( 'zerobscrmadmjqui'); wp_enqueue_script('jquery-ui-sortable'); // our list view css wp_enqueue_script( 'zerobscrmlistviewjs'); zeroBSCRM_enqueue_libs_js_momentdatepicker(); // hook to allow modules etc. to add list view stylesheets do_action( 'jpcrm_enqueue_styles_listview' ); } function zeroBSCRM_admin_styles_ui2_editview(){ //enqueue these (via the admin_print_styles-{$page}) // Removed at request of plugin reviewers. (used wp core ver) wp_enqueue_script( 'zerobscrmadmjqui'); wp_enqueue_script('jquery-ui-sortable'); // semantic 2.2.11 (EVENTUALLY these PROBS shouldn't be global) wp_enqueue_style( 'zerobscrmeditview' ); wp_enqueue_script( 'semanticuijs'); wp_enqueue_script( 'zerobscrmeditviewjs'); wp_enqueue_script( 'zerobscrmtagmetaboxjs'); wp_enqueue_script( 'zerobscrmmm'); // metabox manager // daterange + moment zeroBSCRM_enqueue_libs_js_momentdatepicker(); // catch type-specific includes :) if (isset($_GET['zbstype']) && !empty($_GET['zbstype'])){ switch ($_GET['zbstype']){ case 'quote': zeroBSCRM_scriptStyles_admin_quoteBuilder(); break; case 'invoice': zeroBSCRM_scriptStyles_admin_invoiceBuilder(); break; case 'transaction': zeroBSCRM_scriptStyles_admin_transactionBuilder(); break; case 'form': zeroBSCRM_scriptStyles_admin_formBuilder(); break; case 'event': zeroBSCRM_calendar_admin_styles(); break; } } // extra scripts (e.g. Twilio Connect hooks into this - otherwise the button will not do anything) do_action('zbs_postenqueue_editview'); //zbs_extra_custeditscripts } function zeroBSCRM_settingspage_admin_styles(){ global $zbs; // needs datepicker (MS needed for paypal sync, was a gross hack elsewhere so put here) wp_enqueue_script('wh-daterangepicker-v2-1-21-js',untrailingslashit(ZEROBSCRM_URL).'/js/lib/daterangepicker.min.js', array('jquery'), $zbs->version ); wp_enqueue_style( 'zerobscrmsettings' ); wp_register_script('zerobscrm-settingspage-js' , ZEROBSCRM_URL .'js/ZeroBSCRM.admin.settings'.wp_scripts_get_suffix().'.js', array('jquery'), $zbs->version ); wp_enqueue_script( 'zerobscrm-settingspage-js'); #} Field Sorts if (isset($_GET['tab']) && $_GET['tab'] == 'fieldsorts'){ #} jQ UI //wp_enqueue_script('zerobscrmadmjqui', plugins_url('/js/lib/jquery-ui.min.js',ZBS_ROOTFILE), array( 'jquery' )); // can just call here as registered in main admin init now (2.2 29/07/2017) wp_enqueue_script( 'zerobscrmadmjqui'); #} Our custom sortables css wp_enqueue_style('zerobscrmsortscss', plugins_url('/css/ZeroBSCRM.admin.sortables'.wp_scripts_get_suffix().'.css',ZBS_ROOTFILE), array(), $zbs->version ); } } // These now get rolled into zeroBSCRM_global_admin_styles /*function zeroBSCRM_admin_styles_ui2_semantic(){ wp_enqueue_style( 'zbs-wp-semanticui' ); wp_enqueue_script( 'semanticuijs'); }*/ /* WH adding in for old ext compatibility e.g. inv pro was still producing error for lack of func */ function zeroBSCRM_admin_styles_ui2_semantic(){} function zeroBSCRM_admin_styles_ui2_semantic_settingspage(){ // These now get rolled into zeroBSCRM_global_admin_styles wp_enqueue_style( 'zbs-wp-semanticui' ); wp_enqueue_style( 'zerobscrmmaildeliverywizard' ); // These now get rolled into zeroBSCRM_global_admin_styles wp_enqueue_script( 'semanticuijs'); wp_enqueue_style('zerobscrmsettings'); } function zeroBSCRM_admin_styles_chartjs(){ wp_enqueue_script( 'zerobscrmchartjs'); wp_enqueue_script( 'zerobscrmfunneljs'); } function zeroBSCRM_admin_styles_singleview(){ // single item view wp_enqueue_style( 'zerobscrmsingleview' ); wp_enqueue_script( 'zerobscrmsingleview'); } function jpcrm_admin_scripts_systems_page(){ wp_enqueue_script( 'jpcrmadminsystem'); } function zeroBSCRM_admin_styles_homedash(){ global $zbs; //home dashboard styles and script wp_enqueue_style( 'zerobscrmhomedash' ); zeroBSCRM_enqueue_libs_js_momentdatepicker(); wp_register_script('zerobscrmjs-dash' , ZEROBSCRM_URL .'js/ZeroBSCRM.admin.dash'.wp_scripts_get_suffix().'.js', array('jquery'), $zbs->version); wp_enqueue_script( 'zerobscrmjs-dash'); wp_enqueue_script( 'jpcrm-funnel-js', ZEROBSCRM_URL . 'js/jpcrm-admin-funnel' . wp_scripts_get_suffix() . '.js', array(), $zbs->version, false ); wp_enqueue_style( 'jpcrm-funnel-css', ZEROBSCRM_URL . 'css/jpcrm-admin-funnel' . wp_scripts_get_suffix() . '.css', array(), $zbs->version ); } function zeroBSCRM_admin_scripts_editcust(){ zeroBSCRM_dequeueJSModal(); //scripts here for the edit customer page (for the "Quick Add Company, Tasks, etc") wp_enqueue_script('zerobscrmcustjs'); } function zeroBSCRM_calendar_admin_styles(){ global $zbs; zeroBSCRM_enqueue_libs_js_momentdatepicker(); wp_register_style( 'jpcrm-tasks-css', ZEROBSCRM_URL . 'css/jpcrm-admin-tasks' . wp_scripts_get_suffix() . '.css', array(), $zbs->version ); wp_register_script( 'zerobscrm-calendar-js', ZEROBSCRM_URL . 'js/lib/fullcalendar.mod' . wp_scripts_get_suffix() . '.js', array( 'jquery', 'jpcrm-moment-v2-29-4' ), $zbs->version, false ); wp_register_style('zerobscrm-calendar', ZEROBSCRM_URL .'css/lib/fullcalendar.min.css', array(), $zbs->version ); wp_register_style('zerobscrm-calendar-print', ZEROBSCRM_URL .'css/lib/fullcalendar.print.min.css', array(), $zbs->version ); wp_register_script( 'jpcrm-tasks-js', ZEROBSCRM_URL . 'js/jpcrm-admin-tasks' . wp_scripts_get_suffix() . '.js', array( 'jquery', 'jpcrm-moment-v2-29-4', 'zerobscrm-calendar-js' ), $zbs->version, false ); // LOCALE Specific $languageTag = zeroBSCRM_getLocale(); $languageTagShort = zeroBSCRM_getLocale(false); if (file_exists(ZEROBSCRM_PATH.'/js/lib/calendar-locale/'.$languageTag .'.js')){ // e.g. en-gb wp_enqueue_script('zerobscrm-calendar-js-locale', ZEROBSCRM_URL . 'js/lib/calendar-locale/'.$languageTag .'.js', array('zerobscrm-calendar-js'), $zbs->version ); } else { if (file_exists(ZEROBSCRM_PATH.'/js/lib/calendar-locale/'.$languageTagShort .'.js')){ // e.g. en wp_enqueue_script('zerobscrm-calendar-js-locale', ZEROBSCRM_URL . 'js/lib/calendar-locale/'.$languageTagShort .'.js', array('zerobscrm-calendar-js'), $zbs->version ); } else { // no language tag exists, notice? } } wp_enqueue_style( 'zerobscrm-calendar' ); wp_enqueue_style( 'jpcrm-tasks-css' ); // wp_enqueue_style( 'zerobscrm-calendar-print' ); zeroBSCRM_enqueue_libs_js_momentdatepicker(); wp_enqueue_script('zerobscrm-calendar-js'); wp_enqueue_script( 'jpcrm-tasks-js' ); } // Styles + Scripts for Beta Feedback sys function zeroBSCRM_betaFeedback_styles(){ global $zbs; // styles in global css // js here wp_register_script('zerobscrmjs-bfeedback' , ZEROBSCRM_URL .'/js/ZeroBSCRM.admin.betafeedback'.wp_scripts_get_suffix().'.js', array('jquery'), $zbs->version ); wp_enqueue_script( 'zerobscrmjs-bfeedback'); } function zeroBSCRM_dequeueJSModal(){ wp_dequeue_style('zerobsjsmodal'); wp_dequeue_script('zerobsjsmodal'); } function zeroBSCRM_add_admin_styles( $hook ) { global $post; $zeroBSCRM_custom_slug = ''; if (isset($_GET['zbsslug'])) $zeroBSCRM_custom_slug = sanitize_text_field($_GET['zbsslug']); if ( $hook == 'post-new.php' || $hook == 'post.php' || $hook == 'edit-tags.php' || 'edit.php' ) { // || $hook == 'edit.php' if (is_object($post)){ if ( 'zerobs_customer' === $post->post_type || 'zerobs_quote' === $post->post_type || 'zerobs_company' === $post->post_type || 'zerobs_invoice' === $post->post_type || 'zerobs_transaction' === $post->post_type || 'zerobs_form' === $post->post_type || 'zerobs_mailcampaign' === $post->post_type || 'zerobs_event' === $post->post_type || 'zerobs_quo_template' === $post->post_type ) { zeroBSCRM_global_admin_styles(); //semantic throughout... if('zerobs_customer' === $post->post_type || 'zerobs_quo_template' === $post->post_type || 'zerobs_transaction' === $post->post_type || 'zerobs_quote' === $post->post_type || 'zerobs_invoice' === $post->post_type || 'zerobs_form' === $post->post_type || 'zerobs_company' === $post->post_type || 'zerobs_event' === $post->post_type){ //semantic roll out (in stages) // These now get rolled into zeroBSCRM_global_admin_styles zeroBSCRM_admin_styles_ui2_semantic(); //single customer stuff (like click to SMS etc...) zeroBSCRM_admin_scripts_editcust(); do_action('zbs_extra_custeditscripts'); } if('zerobs_event' === $post->post_type){ zeroBSCRM_calendar_admin_styles(); } } }else if(isset($_GET['post_type']) && ($_GET['post_type'] == 'zerobs_customer' || $_GET['post_type'] == 'zerobs_quo_template' || $_GET['post_type'] == 'zerobs_event' || $_GET['post_type'] == 'zerobs_transaction' || $_GET['post_type'] == 'zerobs_company')){ zeroBSCRM_global_admin_styles(); // These now get rolled into zeroBSCRM_global_admin_styles zeroBSCRM_admin_styles_ui2_semantic(); }else if(isset($_GET['post_type']) && ($_GET['post_type'] == 'zerobs_form' || $_GET['post_type'] == 'zerobs_event')){ zeroBSCRM_global_admin_styles(); // These now get rolled into zeroBSCRM_global_admin_styles zeroBSCRM_admin_styles_ui2_semantic(); }else if($zeroBSCRM_custom_slug == 'zbs-add-user' || $zeroBSCRM_custom_slug == 'zbs-edit-user'){ zeroBSCRM_global_admin_styles(); // These now get rolled into zeroBSCRM_global_admin_styles zeroBSCRM_admin_styles_ui2_semantic(); } // this needed to be separate to the above for some reason on some hosts. if (isset($_GET['page']) && $_GET['page'] == 'zbs-add-edit'){ zeroBSCRM_admin_styles_singleview(); } } } add_action( 'admin_enqueue_scripts', 'zeroBSCRM_add_admin_styles', 10, 1 ); #} Public ver :) /*v3.0 removed this, no CPT's and don't think was using anyhow by 2.98+ function zeroBSCRM_add_public_scripts( $hook ) { global $post; #} Conditionally, for front end: http://wordpress.stackexchange.com/questions/10287/load-scripts-based-on-post-type #if ($post->post_type == 'zerobs_quote' && !is_admin()){ if( is_single() && get_query_var('post_type') && 'zerobs_quote' == get_query_var('post_type') ){ #} Public proposals wp_enqueue_style('zerobscrmpubquocss', ZEROBSCRM_URL .'/css/ZeroBSCRM.public.quotes.min.css' ); } } add_action( 'wp_enqueue_scripts', 'zeroBSCRM_add_public_scripts', 10, 1 ); */ // THIS IS LEGACY! It's used for <3.0 on CPT edit pages. Otherwise enqueue properly like in zeroBSCRM_settingspage_admin_styles via menus :) function zeroBSCRM_load_libs_js_momentdatepicker(){ add_action( 'admin_enqueue_scripts', 'zeroBSCRM_enqueue_libs_js_momentdatepicker' ); } function zeroBSCRM_enqueue_libs_js_momentdatepicker(){ global $zbs; wp_enqueue_script('wh-daterangepicker-v2-1-21-js',untrailingslashit(ZEROBSCRM_URL).'/js/lib/daterangepicker.min.js', array('jquery'), $zbs->version ); #} CSS is wrapped into main plugin css } #} Customer Filters function zeroBSCRM_load_libs_js_customerfilters(){ add_action( 'admin_enqueue_scripts', 'zeroBSCRM_enqueue_libs_js_customerfilters' ); } function zeroBSCRM_enqueue_libs_js_customerfilters(){ global $zbs; #} Customer Filters wp_enqueue_script('zbs-js-customerfilters-v1', ZEROBSCRM_URL.'/js/ZeroBSCRM.admin.customerfilters'.wp_scripts_get_suffix().'.js', array('jquery'), $zbs->version ); } #} Media Manager function zeroBSCRM_enqueue_media_manager(){ wp_enqueue_media(); wp_enqueue_script( 'custom-header' ); } add_action('admin_enqueue_scripts', 'zeroBSCRM_enqueue_media_manager'); function zeroBSCRM_add_admin_segmenteditor_scripts($hook) { global $zbs; // if our page page=zbs-add-edit&action=edit&zbstype=segment if(isset($_GET['page']) && $_GET['page'] == $zbs->slugs['addedit'] && isset($_GET['zbstype']) && $_GET['zbstype'] == 'segment'){ // NOTE: these are used in mail campaigns v2, make sure if change name here, change there wp_enqueue_script( 'zbs-segmentedit-js'); wp_enqueue_style( 'zbs-segmentedit-css'); zeroBSCRM_enqueue_libs_js_momentdatepicker(); } } add_action( 'admin_enqueue_scripts', 'zeroBSCRM_add_admin_segmenteditor_scripts'); // MAIL TEMPLATES #} Code Editor - limit to only our edit templates slug... :) function zeroBSCRM_mailTemplatesEnqueue(){ global $zbs, $pagenow; $slug = ''; if (isset($_GET['page'])) $slug = sanitize_text_field($_GET['page']); if ( $slug != $zbs->slugs['email-templates']) { return; } if(isset($_GET['zbs_template_editor']) && !empty($_GET['zbs_template_editor'])){ if($_GET['zbs_template_editor'] != 1){ return; } } if(!isset($_GET['zbs_template_editor'])){ return; } // Enqueue code editor and settings for manipulating HTML. $settings = wp_enqueue_code_editor( array( 'type' => 'text/html' ) ); // Bail if user disabled CodeMirror. if ( false === $settings ) { return; } // pass codemirror setting for read-only if ( !isset( $settings['codemirror'] ) ){ $settings['codemirror'] = array(); } $settings['codemirror']['readOnly'] = true; wp_add_inline_script( 'code-editor', sprintf( 'jQuery( function() { wp.codeEditor.initialize( "zbstemplatehtml", %s ); } );', wp_json_encode( $settings ) ) ); } add_action( 'admin_enqueue_scripts', 'zeroBSCRM_mailTemplatesEnqueue'); #} =============================================================================== #} === / Unsorted Styles from pre v3.0 #} =============================================================================== function zeroBSCRM_admin_styles_exportTools(){ global $zbs; wp_register_style('zbs-adm-css-export', plugins_url('/css/ZeroBSCRM.admin.export'.wp_scripts_get_suffix().'.css',ZBS_ROOTFILE),array('zbs-wp-semanticui'), $zbs->version ); wp_enqueue_style( 'zbs-adm-css-export' ); } /** * Styles and scripts for resources page */ function jpcrm_crm_resources_page_styles_scripts() { global $zbs; wp_enqueue_style( 'jpcrm-crm-sync-resources-page', plugins_url( '/css/JetpackCRM.admin.resources-page' . wp_scripts_get_suffix() . '.css', ZBS_ROOTFILE ) ); } /** * Styles and scripts for support page */ function jpcrm_support_page_styles_scripts() { global $zbs; wp_enqueue_style( 'jpcrm-support-page', plugins_url( 'css/jpcrm.admin.support-page' . wp_scripts_get_suffix() . '.css', ZBS_ROOTFILE ), array(), $zbs->version ); } // used in form templates & shortcode outputted forms. // https://wordpress.stackexchange.com/questions/165754/enqueue-scripts-styles-when-shortcode-is-present function zeroBSCRM_forms_scriptsStylesRegister(){ global $zbs; // js wp_register_script('zbsfrontendformsjs', plugins_url('/js/ZeroBSCRM.public.leadform'.wp_scripts_get_suffix().'.js',ZBS_ROOTFILE), array( 'jquery' ), $zbs->version); // css wp_register_style('zbsfrontendformscss', plugins_url('/css/ZeroBSCRM.public.frontendforms'.wp_scripts_get_suffix().'.css',ZBS_ROOTFILE), array(), $zbs->version ); } add_action( 'wp_enqueue_scripts', 'zeroBSCRM_forms_scriptsStylesRegister');
projects/plugins/crm/includes/ZeroBSCRM.NotifyMe.php
<?php /*! * Jetpack CRM - Notify Me * https://jetpackcrm.com * V2.4 * * Copyright 2020 Automattic * * Date: 11/02/18 * */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* ================================================================================================================ * * This is the "notify me" plugin from the plugin hunt theme. Written very similar to IA when I wrote it * already has lots of useful things like:- * - settings page for notifications per WP users (disabled for now) * - browser push notifications for UNREAD notifications * have built it in so it does our stuff (upsell stuff + marketing for free) * - for INTERNAL team stuff, suggest building the TEAM notifications PRO and include things like @mentions * - will write notifications system to also check a JSON file where we can post them notifications from external * - e.g. JSON(ID: message) and it marks them as read, then if we want to notify the installs, we can do that ;) * - the EXTENRAL updates is what the 'zbsnotify_reference_id' is for * * ================================================================================================================ */ //create the DB table on activation... (should move this into a classs.. probably) register_activation_hook(ZBS_ROOTFILE,'zeroBSCRM_notifyme_createDBtable'); function zeroBSCRM_notifyme_createDBtable(){ global $wpdb; $notify_table = $wpdb->prefix . "zbs_notifications"; /* reference ID is for our JSON notification check + update i.e. new posts we want to notify folks of /* will use WP cron to check that resource daily + run the script to update zbsnotify_reference_id */ $sql = "CREATE TABLE IF NOT EXISTS $notify_table ( `id` INT(32) unsigned NOT NULL AUTO_INCREMENT, `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, `zbsnotify_recipient_id` INT(32) NOT NULL, `zbsnotify_sender_id` INT(32) NOT NULL, `zbsnotify_unread` tinyint(1) NOT NULL DEFAULT '1', `zbsnotify_emailed` tinyint(1) NOT NULL DEFAULT '0', `zbsnotify_type` varchar(255) NOT NULL DEFAULT '', `zbsnotify_parameters` text NOT NULL, `zbsnotify_reference_id` INT(32) NOT NULL, `zbsnotify_created_at` INT(18) NOT NULL, PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); } function zeroBSCRM_notifyme_scripts(){ global $zbs; wp_enqueue_script("jquery"); wp_enqueue_script('notifyme-front', ZEROBSCRM_URL . 'js/lib/notifyme-front.min.js',array('jquery'), $zbs->version ); wp_enqueue_style('notifyme-css', ZEROBSCRM_URL . 'css/lib/notifyme-front.min.css', array(), $zbs->version ); #} this does the browser notifications wp_register_script( 'notifyme_push', ZEROBSCRM_URL . 'js/lib/push.min.js', array( 'jquery' ) , $zbs->version, true ); wp_enqueue_script( 'notifyme_push' ); #} this stores things in cookies, so not to keep notifying wp_register_script( 'notifyme_cookie', ZEROBSCRM_URL . 'js/lib/cookie.min.js', array( 'jquery' ) , $zbs->version, true ); wp_enqueue_script( 'notifyme_cookie' ); #} this is the browser notification icon. $notify_logo = jpcrm_get_logo(); #} this is which user to notify for.. $cid = get_current_user_id(); #} we want to browser notify our users :-) $notification_meta['browser_push'] = 1; $args = array( 'ph_notify_logo' => $notify_logo, 'current_user' => $cid, 'notification_nonce' => wp_create_nonce( "notifyme_nonce" ), 'notification_settings' => $notification_meta, 'ajaxurl' => admin_url( 'admin-ajax.php' ) ); wp_localize_script('notifyme_push','notifyme',$args); } add_action( 'zbs-global-admin-styles', 'zeroBSCRM_notifyme_scripts' ); //ADD ANY CORE FUNCTIONS FOR THE PLUGIN HERE function zeroBSCRM_notify_me(){ global $zbs, $zeroBSCRM_notifications; // jQuery fills in the number in the bubble.. if ( is_user_logged_in() && zeroBSCRM_permsNotify() ){ $url = zeroBSCRM_getAdminURL($zbs->slugs['notifications']); echo "<a id='notty' class='item' href='". esc_url( $url ) ."'><span class='notifyme' id='notifymebell'><i class='fa fa-bell'></i></span></a>"; } } #} this is the action to add the notification icon to the new admin top menu add_action('zbs-crm-notify','zeroBSCRM_notify_me'); #} can put actual settings in here later (for now just have it notify them regardless). function zeroBSCRM_notifyme_settings(){} function zeroBSCRM_notifyme_echo_type($type = '', $title = '', $sender = -999, $content = ''){ global $zbs; switch ($type) { case 'migration.blocked.errors': esc_html_e("There has been a general error with CRM migrations, a single migration appears to be blocked. Please contact support.", "zero-bs-crm"); break; case 'woosync.suggestion': esc_html_e("🎯 we have detected that you are running WooCommerce. We have a kick ass extension for that. ", "zero-bs-crm"); break; case 'salesdash.suggestion': esc_html_e( '⛽ See all your sales information in a sales dashboard built just for you.', 'zero-bs-crm') . ' '; break; case 'notifications.suggestion': echo wp_kses( sprintf( __( '🔔 Want notifications PRO? This is coming soon to our <a href="%s" target="_blank">Entrepreneur Bundle</a>. Get it while it\'s hot!', 'zero-bs-crm' ), esc_url( $zbs->urls['upgrade'] ) ), $zbs->acceptable_restricted_html ) . ' '; break; case 'extension.update': ##WLREMOVE echo wp_kses( sprintf( __( '🔔 [URGENT] Your extension(s) need updating <a href="%s" target="_blank">Click here to retrieve the new versions</a>. (If you don\'t know your login, please <a href="%s" target="_blank">Email Support</a>.)', 'zero-bs-crm' ), esc_url( $zbs->urls['account'] ), esc_url( $zbs->urls['support'] ) ), $zbs->acceptable_restricted_html ); ##/WLREMOVE break; // v2.70 - DB2 contacts migration :) case 'db2.update.253': echo esc_html( sprintf( __( '🔔 [URGENT] Your Contact Database needs migrating. Running this database update will increase your CRM load-times by up to 60x!', 'zero-bs-crm' ) ) ); break; // v2.70 - DB2 contacts migration :) FINI case 'db2.update.253.success': echo wp_kses( sprintf( __('Your contact database was successfully migrated. Please update any <a href="%s" target="_blank">PRO Extensions</a> you may have installed.',"zero-bs-crm" ), esc_url( $zbs->urls['products'] ) ), $zbs->acceptable_restricted_html ); break; // v2.70 - DB2 contacts migration :) FINI case 'db2.update.253.errors': // load errs $zbsMigrationErrors = get_option( 'zbs_db_migration_253_errors', -1); $errStr = ''; if (isset($zbsMigrationErrors) && is_array($zbsMigrationErrors)) foreach ($zbsMigrationErrors as $zme) $errStr .= '<br />'.$zme; echo sprintf( __( 'Jetpack CRM has tried to update your core CRM to 2.70 but hit errors. Please send the following error report to Support:<hr /><strong>Migration Error Report:</strong>%s</hr> <a href="%s" target="_blank">Contact Support</a>', "zero-bs-crm" ), $errStr, esc_url( $zbs->urls['support'] ) ); break; // v2.70 - DB2 contacts migration :) FINI + has extensions to update case 'db2.extupdate.253': ##WLREMOVE echo wp_kses( sprintf( __( 'Please Update your Extensions (DB Migration makes this essential!) <a href="%s">View Extension Updates</a>', "zero-bs-crm" ), jpcrm_esc_link( $zbs->slugs['connect'] ) ), $zbs->acceptable_restricted_html ); ##/WLREMOVE break; case 'extension.new.update.avail': ##WLREMOVE echo wp_kses( sprintf( __( '🔔 One or more of your extensions need updating. Please update to avoid any issues with security or compatibility <a href="%s">Learn More</a>.', "zero-bs-crm" ), esc_url( admin_url('admin.php?page=zerobscrm-connect')) ), $zbs->acceptable_restricted_html ); ##/WLREMOVE break; case 'license.update.needed': echo '⚠️ ' . $content; break; case 'general.extension.update.needed': echo '⚠️ ' . $content; break; // 2.94.2 - smtp mode changed, need to tell peeps to revalidate case 'smtp.2943.needtocheck': echo sprintf( __( 'Important: 🔔 Jetpack CRM has just updated the way it handles SMTP Delivery Methods.<br />Please check each of your Delivery Methods still works by loading <a href="%s">Mail Delivery Methods</a> and clicking \'send test\', validating that it still sends', 'zero-bs-crm' ), esc_url( admin_url('admin.php?page=zerobscrm-plugin-settings&tab=maildelivery') ) ); break; // 3.0.17 - Changed the password encryption, so get people to validate case 'smtp.3017.needtocheck': echo sprintf( __( 'Important: 🔔 Jetpack CRM has improved the encryption of SMTP passwords.<br />Please check each of your Delivery Methods still works by loading <a href="%s">Mail Delivery Methods</a> and clicking \'send test\', validating that it still sends', 'zero-bs-crm' ), jpcrm_esc_link( $zbs->slugs['settings'] . '&tab=maildelivery' ) ); break; //now do the extension updates like this case 'custom.extension.update.needed': $x = __("🔔","zero-bs-crm") . $content . ' <a href="'. esc_url( admin_url('update-core.php') ) .'">' . __("Update Now", "zero-bs-crm") . '</a>.'; ##WLREMOVE $x = __("🔔","zero-bs-crm") . $content . ' <a href="'. esc_url( admin_url('update-core.php') ) .'">' . __("Update Now", "zero-bs-crm") . '</a>.'; ##/WLREMOVE echo $x; break; //now do the extension updates like this // this is WL CORE update case 'core.update.needed': echo esc_html__("🔔","zero-bs-crm") . $content . ' <a href="'. esc_url( admin_url('update-core.php') ) .'">' . esc_html__("Update Now", "zero-bs-crm") . '</a>.'; break; // 4.5.0 - Missing template file case 'missing.template': echo wp_kses( __( 'Template File Error:<br /> It was not possible to load the following template file. This will mean that related documents will not be loaded properly.<br/>Template File: ', 'zero-bs-crm' ), $zbs->acceptable_restricted_html ) . $content; break; // ========= DAL 3 MIGRATIONS // v3.0 - DB3 objs migration :) case 'db3.update.300': echo sprintf( __( '🔔 [URGENT] Your CRM Database needs migrating. <a href="%s">Click here to run migration routine</a><div style="margin: 2em;margin-left: 4em;">Running this database update will increase your CRM load-times by up to 60x!<br /><a href="%s" target="_blank" class="ui button basic">Read Guide</a> <a href="%s" class="ui button green">Run now</a>', "zero-bs-crm" ), jpcrm_esc_link( $zbs->slugs['migratedal3'] ), esc_url( $zbs->urls['db3migrate'] ), jpcrm_esc_link( $zbs->slugs['migratedal3'] ) ); break; // v3.0 - DB3 objs migration :) FINI case 'db3.update.300.success': echo wp_kses( sprintf( __( 'Your CRM database was successfully migrated. Please update any <a href="%s" target="_blank">PRO Extensions</a> you may have installed.',"zero-bs-crm"), esc_url( $zbs->urls['products'] ) ), $zbs->acceptable_restricted_html ); break; // v3.0 - DB3 objs migration :) FINI case 'db3.update.300.errors': echo __("Jetpack CRM has tried to updated your core CRM successfully, despite a few errors:","zero-bs-crm").'</hr><a href="'. esc_url( zeroBSCRM_getAdminURL($zbs->slugs['systemstatus']) ).'&v3migrationlog=1" target="_blank">'. esc_html__('View Migration Report','zero-bs-crm').'</a>'; break; // v3.0 - DB3 objs migration :) FINI + has extensions to update case 'db3.extupdate.300': ##WLREMOVE echo esc_html__("Please Update your Extensions (DB Migration makes this essential!)","zero-bs-crm").' <a href="'. jpcrm_esc_link( $zbs->slugs['connect'] ).'">'. esc_html__("View Extension Updates","zero-bs-crm").'</a>'; ##/WLREMOVE break; // ========= / DAL 3 MIGRATIONS // ========= v5+ MIGRATIONS // v5.1 - migrate woosync sites case 'woosync.5.1.migration': echo esc_html__( 'WooSync was unable to migrate settings (5.2). Sync will be stopped until this is remedied.', 'zero-bs-crm' ) . ' ' . wp_kses( sprintf( __( 'Please <a href="%s" target="_blank">contact support</a>.', 'zero-bs-crm' ), esc_url( $zbs->urls['support'] ) ), $zbs->acceptable_restricted_html ); break; // ========= / v5+ MIGRATIONS // ========= Exceptions seen // Segment audience tried to build but some conditions produced no arguments // (likely segment created with adv segments active, then adv segments been deactivated) case 'segments.orphaned.conditions': echo esc_html__( '⚠️ A segment was retrieved which has conditions which produced no arguments. (This usually happens when a segment was made via Advanced Segments extension, then that extension is deactivated). Please reactivate any segment extending plugins you have, or contact support.', "zero-bs-crm" ); break; // ========= / Exceptions seen // ========= MC2 case 'campaign.paused.due.to.error': echo esc_html__( 'A mail campaign has been paused due to an error.', 'zero-bs-crm' ) . '&nbsp;&nbsp;&nbsp;&nbsp;' . $content; break; case 'campaign.can.be.unpaused': echo esc_html__( 'A mail campaign which was previously blocked from sending by an error is now able to send. Please unpause the campaign to continue to send.', 'zero-bs-crm' ) . '&nbsp;&nbsp;&nbsp;&nbsp;' . $content; break; // ========= / MC2 // ========= WooSync case 'woosync.conflict.deactivated': echo wp_kses( sprintf( __( 'Your standalone WooSync extension has been deactivated; WooSync is now in the core CRM! <a href="%s" target="_blank">Read more</a>', 'zero-bs-crm' ), esc_url( $zbs->urls['v5announce'] ) ), $zbs->acceptable_restricted_html ); break; case 'woosync.syncsite.paused': echo wp_kses( sprintf( __( 'Your WooSync Store connection has been paused due to three errors in connecting to the store. <a href="%s" target="_blank">View Connections</a>', 'zero-bs-crm' ), esc_url( $content ) ), $zbs->acceptable_restricted_html ); break; // ========= / WooSync // ========= Client Portal Pro case 'clientportalpro.incompatible.version.deactivated': echo esc_html__( 'You are using an outdated version of the Client Portal Pro extension, which is not compatible with this version of the CRM. It has been deactivated. Please update the extension to continue using Client Portal Pro.', 'zero-bs-crm' ); break; // ========= / Client Portal Pro // ========= Package Installer case 'package.installer.fail_count_over': echo sprintf( __( 'Package Installer was not able to install the requested package %s, after trying the maximum number of times.', 'zero-bs-crm' ), $content ) . wp_kses( sprintf( __( ' Please <a href="%s" target="_blank">contact support</a>.', 'zero-bs-crm' ), esc_url( $zbs->urls['support'] ) ), $zbs->acceptable_restricted_html ); break; case 'package.installer.dir_create_error': echo sprintf( __( 'Package Installer could not create directories needed to install the package %s.', 'zero-bs-crm' ), $content ) . wp_kses( sprintf( __( ' Please <a href="%s" target="_blank">contact support</a>.', 'zero-bs-crm' ), esc_url( $zbs->urls['support'] ) ), $zbs->acceptable_restricted_html ); break; case 'package.installer.unzip_error': echo sprintf( __( 'Package Installer was not able to expand the requested package zip file for the package %s', 'zero-bs-crm' ), $content ) . wp_kses( sprintf( __( ' Please <a href="%s" target="_blank">contact support</a>.', 'zero-bs-crm' ), esc_url( $zbs->urls['support'] ) ), $zbs->acceptable_restricted_html ); break; case 'package.installer.dl_error': echo sprintf( __( 'Package Installer was not able to download the requested package %s', 'zero-bs-crm' ), $content ) . wp_kses( sprintf( __( ' Please <a href="%s" target="_blank">contact support</a>.', 'zero-bs-crm' ), esc_url( $zbs->urls['support'] ) ), $zbs->acceptable_restricted_html ); break; case 'curl.timeout.error': echo sprintf( __( 'Failed to retrieve key file, your server may not be able to connect to the CRM CDN: %s. If this message persists, please contact support', 'zero-bs-crm' ), $content ); break; // ========= / Package Installer default: esc_html_e(" something went wrong", 'zero-bs-crm'); } } function zeroBSCRM_notifyme_time_ago($datetime){ if (is_numeric($datetime)) { $timestamp = $datetime; } else { $timestamp = strtotime($datetime); } $diff=time()-$timestamp; $min=60; $hour=60*60; $day=60*60*24; $month=$day*30; if($diff<60) //Under a min { $timeago = $diff . " seconds"; }elseif ($diff<$hour) //Under an hour { $timeago = round($diff/$min) . " mins"; }elseif ($diff<$day) //Under a day { $timeago = round($diff/$hour) . " hours"; }elseif ($diff<$month) //Under a day { $timeago = round($diff/$day) . " days"; }else { $timeago = round($diff/$month) ." months"; } return $timeago; } //function to insert the notification into the database.. /* $recipient = get_current_user_id(); i.e. WHO are we notifying (WP_user ID) $sender = -999; //in this case... we can call ZBS our -999 user ID (for bot icon stuff) and output our icon where it's system stuff. $post_id = 0; //i.e. not a post related activity (but can pass $post_id for linking to various pages) - NOT USED ^^ use that in notifications PRO to store edit links for customerID, invoiceID, etc. but with new DB this is effectively the ID of whatever $type = 'woosync.suggestion'; //this is a extension suggestion type, see zeroBSCRM_notifyme_echo_type for the switch / case here. Store the InternalAutomator actions strings here and extend where we want to notify of that.. e.g. 10 new leads have been added since you last logged in. /* DOESN'T DO - GROUPING of similar notifications. If you do have it to notify on new customer it will show a notification line for each and every one. Rather than "100 new contact since your last visit" it would show [name1 .. name100] has been added as a new conact, 100 times - SNOOZING of notifications. They're ALWAYS on. // zeroBSCRM_notifyme_insert_notification($recipient,$sender,$post_id,$type); */ function zeroBSCRM_notifyme_insert_notification($recipient = -1, $sender = -999, $post_id = -1, $type = '', $parameters = '', $reference = -1){ global $wpdb; $notify_table = $wpdb->prefix . "zbs_notifications"; $now = time(); // * WH NOTE: // ownership needed DBv2+ // no need to update these (as of yet) - can't move teams etc. //'zbs_site' => zeroBSCRM_installSite(), //'zbs_team' => zeroBSCRM_installTeam(), //'zbs_owner' => $owner, // OWNER was not_null so I've added -1 for now :) to add these 3 when makes sense #} only stores if the recipient is NOT the user if($recipient != $sender){ //need to check first whether the reference ID already exists (add with a UNIQUE REFERENCEID going forwards) //"parameters" here is really the content of the notification... $reference is the unique ID //added new "type" of custom.extension.update.needed // if $parameters is empty seems to bug out :) so forcing it to be smt if empty: if (empty($parameters)) $parameters = '-1'; if (empty($type)) $type = '-1'; $sql = $wpdb->prepare("SELECT id FROM $notify_table WHERE zbsnotify_reference_id = %d AND zbsnotify_parameters = %s", $reference, $parameters); $results = $wpdb->get_results($sql); if(count($results) == 0){ $sql = $wpdb->prepare("INSERT INTO $notify_table ( zbs_owner, zbsnotify_recipient_id , zbsnotify_sender_id, zbsnotify_unread, zbsnotify_type, zbsnotify_parameters, zbsnotify_reference_id, zbsnotify_created_at) VALUES ( %d, %d, %d, %d, %s, %s, %d, %s)", -1, $recipient, $sender, '0', $type, $parameters, $reference, $now); $wpdb->query($sql); } } } function zeroBSCRM_notifyme_activity(){ global $wpdb; $cid = get_current_user_id(); // * WH NOTE: // ownership needed DBv2+ // no need to update these (as of yet) - can't move teams etc. //'zbs_site' => zeroBSCRM_installSite(), //'zbs_team' => zeroBSCRM_installTeam(), //'zbs_owner' => $owner, $notify_table = $wpdb->prefix . "zbs_notifications"; $sql = $wpdb->prepare("SELECT * FROM $notify_table WHERE zbsnotify_recipient_id = %d ORDER BY zbsnotify_created_at DESC LIMIT 20", $cid); $notifes = $wpdb->get_results($sql); echo '<div class="ph_notification_list_wrap ui segment" id="notification-list" style="margin-right:30px;">'; if(count($notifes) == 0){ // EXAMPLE NOTIFICATION - FOR THE TOUR :-) $notify_logo_url = jpcrm_get_logo(); $sender_avatar = "<img src='".$notify_logo_url."' width='30px;float:left;'>"; $another_notty = __( 'Here is another notification example from John Doe.', 'zero-bs-crm' ); echo "<div class='ph_notification_list r0' id='mike-face' style='display:none;'>"; echo '<div class="ph_noti_img">'; echo "<img src='". esc_url( ZEROBSCRM_URL )."i/defaultDude.jpeg' width='30px;float:left;'>"; echo '</div>'; echo '<div class="ph_noti_message">'; echo esc_html( $another_notty ); echo "</div>"; echo '<div class="ph_noti_timeago">'; esc_html_e("Just now", "zero-bs-crm"); echo '</div>'; echo '</div>'; echo '<div class="clear"></div>'; echo "<div class='ph_notification_list r0' id='first-example'>"; echo '<div class="ph_noti_img">'; echo $sender_avatar; echo '</div>'; echo '<div class="ph_noti_message">'; esc_html_e("This is an example notification. Here is where you will be kept notified :) simple. effective.", "zero-bs-crm"); echo "</div>"; echo '<div class="ph_noti_timeago">'; esc_html_e("Just now", "zero-bs-crm"); echo '</div>'; echo '</div>'; }else{ foreach($notifes as $n){ $title = ''; //can pass specific title to the echo function $sender = $n->zbsnotify_sender_id; if($sender == -999){ //this is our "ZBS notifications bot". This sniffs around WP checking everything is OK.. and also lets //them know about any updates we have pinged out from our own JSON file on https:// :-) ... POW ERRRR FULL $notify_logo_url = jpcrm_get_logo(); $sender_avatar = "<img src='".$notify_logo_url."' width='30px;float:left;'>"; }else{ $sender_avatar = jpcrm_get_avatar( $n->zbsnotify_sender_id, 30); } $sender_url = ''; if (isset($n) && isset($n->sender_id)) $sender_url = get_author_posts_url($n->sender_id); echo "<div class='ph_notification_list r". esc_attr( $n->zbsnotify_unread ) ."'>"; echo '<div class="ph_noti_img">'; echo $sender_avatar; echo '</div>'; echo '<div class="ph_noti_message">'; zeroBSCRM_notifyme_echo_type($n->zbsnotify_type, $title, $n->zbsnotify_sender_id, $n->zbsnotify_parameters); echo "</div>"; echo '<div class="ph_noti_timeago">'; esc_html_e(zeroBSCRM_notifyme_time_ago($n->zbsnotify_created_at) . " ago ", "zero-bs-crm"); echo '</div>'; echo '</div>'; echo '<div class="clear"></div>'; } echo "</div>"; } //got here. Mark the notifications as read for this user :-) $sql = $wpdb->prepare("UPDATE $notify_table SET zbsnotify_unread = %d WHERE zbsnotify_recipient_id = %d", 1, $cid); $wpdb->query($sql); } add_action('wp_ajax_nopriv_notifyme_get_notifications_ajax','zeroBSCRM_notifyme_get_notifications_ajax'); add_action( 'wp_ajax_notifyme_get_notifications_ajax', 'zeroBSCRM_notifyme_get_notifications_ajax' ); function zeroBSCRM_notifyme_get_notifications_ajax(){ global $wpdb; check_ajax_referer( 'notifyme_nonce', 'security' ); $cid = get_current_user_id(); $now = date("U"); $notify_table = $wpdb->prefix . "zbs_notifications"; // * WH NOTE: // ownership needed DBv2+ // no need to update these (as of yet) - can't move teams etc. //'zbs_site' => zeroBSCRM_installSite(), //'zbs_team' => zeroBSCRM_installTeam(), //'zbs_owner' => $owner, $sql = $wpdb->prepare("SELECT * FROM $notify_table WHERE zbsnotify_recipient_id = %d AND zbsnotify_unread = %d", $cid, 0); $notifes = $wpdb->get_results($sql); $res['count'] = 0; $res['notifications'] = $notifes; if(!$notifes){ $res['count'] = 0; }else{ $res['message'] = "Passed AJAX nonce check"; $res['notifytitle'] = 'This is the title'; $res['notifybody'] = 'This is the body'; $res['count'] = count($res['notifications']); } echo json_encode($res,true); die(); } #} no need to send email from this. Only want CRM wide (i.e. from WP admin, bell icon in new UI top menu) /* function notifyme_sendemail($recipient_id, $sender_id, $type, $reference_id){ $notification_meta = get_user_meta($recipient_id, 'notifyme_user_settings', true); if($notification_meta == ''){ $notification_meta['email_comment'] = 1; $notification_meta['email_upvote'] = 1; $notification_meta['email_follow'] = 1; $notification_meta['email_follows_post'] = 1; } #} NOTE - LONGSTANDING ANNOYINB BUG HERE IN NOTIFY ME IN MY $message where it's not sending links, it's sending the actual #} HTML, i.e. <a href = ... will fix as moving into Jetpack CRM, and then possibly fix it in Notify Me $site_title = get_bloginfo( 'name' ); $recipitent = get_user_by('id' , $recipient_id); $sender = get_user_by('id' , $sender_id); $sender_url = get_author_posts_url($sender_id); $to = $recipitent->user_email; switch ($type) { case 'post.vote': if($notification_meta['email_upvote'] == 1){ $post_title = get_the_title($reference_id); //reference_id is the post ID. $subject = __($site_title . ": " . $post_title . " has been upvoted", 'zero-bs-crm'); $post_link = get_permalink($reference_id); $message = __("View the post here <a href='". esc_url($post_link) ."'>" . $post_title . "</a>", 'zero-bs-crm'); wp_mail( $to, $subject, $message); write_log('to ' . $to . ' subject ' . $subject . ' message ' . $message); } break; case 'comment.new': if($notification_meta['email_comment'] == 1){ $post_title = get_the_title($reference_id); //reference_id is the post ID. $subject = __($site_title . ": " . $post_title . " has received a comment", 'zero-bs-crm'); $post_link = get_permalink($reference_id); $message = __("View the post here <a href='". esc_url($post_link) ."'>" . $post_title . "</a>", 'zero-bs-crm'); wp_mail( $to, $subject, $message); write_log('comment new to ' . $to . ' subject ' . $subject . ' message ' . $message); } break; case 'comment.reply': if($notification_meta['email_comment'] == 1){ $post_title = get_the_title($reference_id); //reference_id is the post ID. $subject = __($site_title . ": " . $post_title . " has received a comment", 'zero-bs-crm'); $post_link = get_permalink($reference_id); $message = __("View the post here <a href='". esc_url($post_link) ."'>" . $post_title . "</a>", 'zero-bs-crm'); wp_mail( $to, $subject, $message); write_log('comment reply to ' . $to . ' subject ' . $subject . ' message ' . $message); } break; case 'user.follow': if($notification_meta['email_follow'] == 1){ $subject = __($site_title . ": " . ucfirst($sender->user_nicename). " has started tof follow you", 'zero-bs-crm'); $message = __("View them here <a href='". esc_url($sender_url) ."'>" . ucfirst($sender->user_nicename) . "</a>", 'zero-bs-crm'); wp_mail( $to, $subject, $message); write_log('user follow' . $to . ' subject ' . $subject . ' message ' . $message); } break; case 'follower.post': if($notification_meta['email_follows_post'] == 1){ $post_title = get_the_title($reference_id); //reference_id is the post ID. $subject = __($site_title . ": " . ucfirst($sender->user_nicename) . " has posted" . $post_tile, 'zero-bs-crm'); $post_link = get_permalink($reference_id); $message = __("View the post here <a href='". esc_url($post_link) ."'>" . $post_title . "</a>", 'zero-bs-crm'); wp_mail( $to, $subject, $message); write_log('follower post to ' . $to . ' subject ' . $subject . ' message ' . $message); } break; default: } } */
projects/plugins/crm/includes/ZeroBSCRM.InternalAutomatorRecipes.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V1.1.15 * * Copyright 2020 Automattic * * Date: 30/08/16 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== Setup Internal Automator Recipes: ====================================================== */ // Note on contact.vitals.update vs contact.update, // ... if contact.vitals.update fires, it will fire AS WELL as contact.update. // ... if contact.email.update fires, it will fire AS WELL as contact.update. #} Set IA Recipes (CREATED) zeroBSCRM_AddInternalAutomatorRecipe('contact.new','zeroBSCRM_IA_NewCustomerClientPortal',array()); zeroBSCRM_AddInternalAutomatorRecipe('contact.new','zeroBSCRM_IA_NewCustomerLog',array()); zeroBSCRM_AddInternalAutomatorRecipe('contact.status.update','zeroBSCRM_IA_CustomerStatusChangePortalAndLog',array()); zeroBSCRM_AddInternalAutomatorRecipe('contact.status.update','zeroBSCRM_IA_CustomerStatusChangeAutoLog',array()); zeroBSCRM_AddInternalAutomatorRecipe('contact.new','zeroBSCRM_IA_ContactSegmentCompiler',array()); // for edit + new zeroBSCRM_AddInternalAutomatorRecipe('contact.update','zeroBSCRM_IA_ContactSegmentCompiler',array()); // for edit + new zeroBSCRM_AddInternalAutomatorRecipe('company.new','zeroBSCRM_IA_NewCompanyLog',array()); zeroBSCRM_AddInternalAutomatorRecipe('quote.new','zeroBSCRM_IA_NewQuoteLog',array()); zeroBSCRM_AddInternalAutomatorRecipe('quote.new','zeroBSCRM_IA_quoteSegmentCompiler',array()); zeroBSCRM_AddInternalAutomatorRecipe('quote.update','zeroBSCRM_IA_quoteSegmentCompiler',array()); zeroBSCRM_AddInternalAutomatorRecipe('quote.accepted','zeroBSCRM_IA_AcceptedQuoteLog',array()); zeroBSCRM_AddInternalAutomatorRecipe('invoice.new','zeroBSCRM_IA_NewInvoiceLog',array()); zeroBSCRM_AddInternalAutomatorRecipe('invoice.new','zeroBSCRM_IA_invoiceSegmentCompiler',array()); zeroBSCRM_AddInternalAutomatorRecipe('invoice.update','zeroBSCRM_IA_invoiceSegmentCompiler',array()); zeroBSCRM_AddInternalAutomatorRecipe('log.new','zeroBSCRM_IA_NewLogCatchContactsDB2',array()); zeroBSCRM_AddInternalAutomatorRecipe('transaction.new','zeroBSCRM_IA_NewTransactionLog',array()); zeroBSCRM_AddInternalAutomatorRecipe('transaction.new','zeroBSCRM_IA_transactionSegmentCompiler',array()); zeroBSCRM_AddInternalAutomatorRecipe('transaction.update','zeroBSCRM_IA_transactionSegmentCompiler',array()); zeroBSCRM_AddInternalAutomatorRecipe('event.new','zeroBSCRM_IA_NewEventLog',array()); zeroBSCRM_AddInternalAutomatorRecipe('clientwpuser.new','zeroBSCRM_IA_NewClientPortalUserLog',array()); #} Set IA Recipes (UPDATED) #} - WH commented out, you need to have a corresponding function for any of these you add: #// zeroBSCRM_AddInternalAutomatorRecipe('status.change','zeroBSCRM_IA_StatusChange',array()); // WP Hook tie-ins (for Mike [and 3rd party developers!], mostly). zeroBSCRM_AddInternalAutomatorRecipe( 'contact.new', 'zeroBSCRM_IA_NewCustomerWPHook', array() ); zeroBSCRM_AddInternalAutomatorRecipe( 'contact.update', 'zeroBSCRM_IA_EditCustomerWPHook', array() ); zeroBSCRM_AddInternalAutomatorRecipe( 'contact.status.update', 'zeroBSCRM_IA_EditCustomerWPHook', array() ); zeroBSCRM_AddInternalAutomatorRecipe( 'contact.vitals.update', 'zeroBSCRM_IA_EditCustomerVitalsWPHook', array() ); zeroBSCRM_AddInternalAutomatorRecipe( 'contact.email.update', 'zeroBSCRM_IA_EditCustomerEmailWPHook', array() ); zeroBSCRM_AddInternalAutomatorRecipe( 'contact.delete', 'zeroBSCRM_IA_DeleteCustomerWPHook', array() ); zeroBSCRM_AddInternalAutomatorRecipe( 'company.new', 'zeroBSCRM_IA_NewCompanyWPHook', array() ); zeroBSCRM_AddInternalAutomatorRecipe( 'company.delete', 'zeroBSCRM_IA_DeleteCompanyWPHook', array() ); zeroBSCRM_AddInternalAutomatorRecipe( 'quote.new', 'zeroBSCRM_IA_NewQuoteWPHook', array() ); zeroBSCRM_AddInternalAutomatorRecipe( 'quote.accepted', 'zeroBSCRM_IA_AcceptedQuoteWPHook', array() ); zeroBSCRM_AddInternalAutomatorRecipe( 'quote.update', 'zeroBSCRM_IA_EditInvoiceWPHook', array() ); zeroBSCRM_AddInternalAutomatorRecipe( 'quote.status.update', 'zeroBSCRM_IA_EditInvoiceWPHook', array() ); zeroBSCRM_AddInternalAutomatorRecipe( 'quote.delete', 'zeroBSCRM_IA_DeleteQuoteWPHook', array() ); zeroBSCRM_AddInternalAutomatorRecipe( 'invoice.new', 'zeroBSCRM_IA_NewInvoiceWPHook', array() ); zeroBSCRM_AddInternalAutomatorRecipe( 'invoice.update', 'zeroBSCRM_IA_EditInvoiceWPHook', array() ); zeroBSCRM_AddInternalAutomatorRecipe( 'invoice.status.update', 'zeroBSCRM_IA_EditInvoiceWPHook', array() ); zeroBSCRM_AddInternalAutomatorRecipe( 'invoice.delete', 'zeroBSCRM_IA_DeleteInvoiceWPHook', array() ); zeroBSCRM_AddInternalAutomatorRecipe( 'transaction.new', 'zeroBSCRM_IA_NewTransactionWPHook', array() ); zeroBSCRM_AddInternalAutomatorRecipe( 'transaction.delete', 'zeroBSCRM_IA_DeleteTransactionWPHook', array() ); zeroBSCRM_AddInternalAutomatorRecipe( 'event.new', 'zeroBSCRM_IA_NewEventWPHook', array() ); zeroBSCRM_AddInternalAutomatorRecipe( 'event.update', 'zeroBSCRM_IA_UpdateEventWPHook', array() ); zeroBSCRM_AddInternalAutomatorRecipe( 'event.delete', 'zeroBSCRM_IA_DeleteEventWPHook', array() ); zeroBSCRM_AddInternalAutomatorRecipe( 'clientwpuser.new', 'zeroBSCRM_IA_NewClientPortalUserHook', array() ); zeroBSCRM_AddInternalAutomatorRecipe( 'segment.delete', 'zeroBSCRM_IA_DeleteSegmentWPHook', array() ); zeroBSCRM_AddInternalAutomatorRecipe( 'contact.before.delete', 'zeroBSCRM_IA_BeforeDeleteCustomerWPHook', array() ); // don't need to expose tbh //zeroBSCRM_AddInternalAutomatorRecipe('form.delete','zeroBSCRM_IA_DeleteFormWPHook',array()); // DAL3.0 + can use these: /* company.new company.update company.status.update quote.new quote.update log.update event.new event.update form.new form.update invoice.new invoice.update invoice.status.update transaction.new transaction.update transaction.status.update quotetemplate.new quotetemplate.update */ /* ====================================================== / Setup Internal Automator Recipes: ====================================================== */ /* ====================================================== Internal Automator Recipe Functions ====================================================== */ #} Adds a "created" log to users (if setting) function zeroBSCRM_IA_NewCustomerLog($obj=array()){ # if setting $autoLogThis = zeroBSCRM_getSetting('autolog_customer_new'); if ($autoLogThis > 0){ #} Retrieve necessary info: $zbsNoteAgainstPostID = -1; if (is_array($obj) && isset($obj['id'])) $zbsNoteAgainstPostID = (int)$obj['id']; if (isset($zbsNoteAgainstPostID) && !empty($zbsNoteAgainstPostID)){ #} First check if an override is passed... if (isset($obj['automatorpassthrough']) && is_array($obj['automatorpassthrough']) && isset($obj['automatorpassthrough']['note_override']) && is_array($obj['automatorpassthrough']['note_override']) && isset($obj['automatorpassthrough']['note_override']['type'])){ #} An overriding note has been passed, just use that #} Add log $newLogID = zeroBS_addUpdateContactLog($zbsNoteAgainstPostID,-1,-1,$obj['automatorpassthrough']['note_override']); } else { #} No override, use default processing... #} Set Deets $newCustomerName = ''; if (is_array($obj) && isset($obj['id']) && isset($obj['customerMeta']) && is_array($obj['customerMeta'])) $newCustomerName = zeroBS_customerName($obj['id'],$obj['customerMeta'],false,true); $noteShortDesc = 'Customer Created'; if (!empty($newCustomerName)) $noteShortDesc = $newCustomerName; $note_long_description = ''; // Custom short desc for external source creations if (isset($obj['extsource']) && !empty($obj['extsource'])){ $uid = ''; // We seem to pass either the external source array (woo) // ... or a string 'pay', so lets select the right one... if ( is_array( $obj['extsource'] ) && isset( $obj['extsource']['source'] ) ){ $source_key = $obj['extsource']['source']; // if we have this we also have UID $uid = $obj['extsource']['uid']; } else { $source_key = $obj['extsource']; } switch ( $source_key ){ case 'pay': $note_long_description = __( 'Created from PayPal', 'zero-bs-crm' ) . '<i class="fa fa-paypal"></i>'; break; case 'woo': $note_long_description = __( 'Created from WooCommerce Order', 'zero-bs-crm' ) . ' <i class="fa fa-shopping-cart"></i>'; break; case 'env': $note_long_description = __( 'Created from Envato', 'zero-bs-crm' ) . '<i class="fa fa-envira"></i>'; break; case 'form': $note_long_description = __( 'Created from Form Capture', 'zero-bs-crm' ) . '<i class="fa fa-wpforms"></i>'; break; case 'csv': $note_long_description = __( 'Created from CSV Import', 'zero-bs-crm' ) . '<i class="fa fa-file-text"></i>'; break; case 'gra': $note_long_description = __( 'Created from Gravity Forms', 'zero-bs-crm' ) . '<i class="fa fa-wpforms"></i>'; break; default: // Generic fallback (shouldn't ever fire) $note_long_description = __( 'Created from External Source', 'zero-bs-crm' ) . ' <i class="fa fa-users"></i>'; break; } // allow extension override via filter (e.g. WooSync) $note_long_description = apply_filters( 'jpcrm_new_contact_log', $note_long_description, $source_key, $uid ); } #} Add log $newLogID = zeroBS_addUpdateContactLog($zbsNoteAgainstPostID,-1,-1,array( 'type' => 'Created', 'shortdesc' => $noteShortDesc, 'longdesc' => $note_long_description )); } # / end of if no override } } } #} Adds a "created" log to users (if setting) function zeroBSCRM_IA_NewCompanyLog($obj=array()){ # if setting $autoLogThis = zeroBSCRM_getSetting('autolog_company_new'); if ($autoLogThis > 0){ #} Retrieve necessary info: $zbsNoteAgainstPostID = -1; if (is_array($obj) && isset($obj['id'])) $zbsNoteAgainstPostID = (int)$obj['id']; if (isset($zbsNoteAgainstPostID) && !empty($zbsNoteAgainstPostID)){ #} First check if an override is passed... if (isset($obj['automatorpassthrough']) && is_array($obj['automatorpassthrough']) && isset($obj['automatorpassthrough']['note_override']) && is_array($obj['automatorpassthrough']['note_override']) && isset($obj['automatorpassthrough']['note_override']['type'])){ #} An overriding note has been passed, just use that #} Add log $newLogID = zeroBS_addUpdateLog($zbsNoteAgainstPostID,-1,-1,$obj['automatorpassthrough']['note_override'],'zerobs_company'); } else { #} No override, use default processing... #} Set Deets $newCompanyName = ''; if (is_array($obj) && isset($obj['id']) && isset($obj['companyMeta']) && is_array($obj['companyMeta'])) $newCompanyName = zeroBS_companyName($obj['id'],$obj['companyMeta'],false,true); $noteShortDesc = 'Company Created'; if (!empty($newCompanyName)) $noteShortDesc = $newCompanyName; $note_long_description = ''; // Custom short desc for external source creations if (isset($obj['extsource']) && !empty($obj['extsource'])){ // We seem to pass either the external source array (woo) // ... or a string 'pay', so lets select the right one... if ( is_array( $obj['extsource'] ) && isset( $obj['extsource']['source'] ) ){ $source_key = $obj['extsource']['source']; // if we have this we also have UID $uid = $obj['extsource']['uid']; } else { $source_key = $obj['extsource']; } switch ( $source_key ){ case 'pay': $note_long_description = 'Created from PayPal <i class="fa fa-paypal"></i>'; break; case 'woo': if ( isset( $uid ) ){ $note_long_description = sprintf( __( 'Created from WooCommerce Order #%s', 'zero-bs-crm' ), $uid ) . ' <i class="fa fa-shopping-cart"></i>'; } else { $note_long_description = __( 'Created from WooCommerce Order', 'zero-bs-crm' ) . ' <i class="fa fa-shopping-cart"></i>'; } break; case 'env': $note_long_description = 'Created from Envato <i class="fa fa-envira"></i>'; break; case 'form': $note_long_description = 'Created from Form Capture <i class="fa fa-wpforms"></i>'; break; case 'csv': $note_long_description = 'Created from CSV Import <i class="fa fa-file-text"></i>'; break; default: #} Generic for now (SHOULD NEVER CALL) $note_long_description = 'Created from External Source <i class="fa fa-users"></i>'; break; } } #} Add log $newLogID = zeroBS_addUpdateLog($zbsNoteAgainstPostID,-1,-1,array( 'type' => 'Created', 'shortdesc' => $noteShortDesc, 'longdesc' => $note_long_description ),'zerobs_company'); } # / end of if no override } } } #} Adds a "created" log to customer (of quotes) (if setting) function zeroBSCRM_IA_NewQuoteLog($obj=array()){ # if setting $autoLogThis = zeroBSCRM_getSetting('autolog_quote_new'); if ($autoLogThis > 0){ global $zbs; // v3+ if ($zbs->isDAL3()){ // 3.0+ #} Retrieve necessary info: $noteAgainstIDs = array('contacts'=>array(),'companies'=>array()); if (is_array($obj) && isset($obj['againstids']) && is_array($obj['againstids'])){ // trusting they're correctly passed... if (isset($obj['againstids']['contacts']) && is_array($obj['againstids']['contacts'])) $noteAgainstIDs['contacts'] = $obj['againstids']['contacts']; if (isset($obj['againstids']['companies']) && is_array($obj['againstids']['companies'])) $noteAgainstIDs['companies'] = $obj['againstids']['companies']; } $quoteID = ''; if (is_array($obj) && isset($obj['id'])) $quoteID = $obj['id']; $quoteTitle = ''; if (is_array($obj) && is_array($obj['data']) && isset($obj['data']['title']) && !empty($obj['data']['title'])) $quoteTitle = $obj['data']['title']; $quoteValue = ''; if (is_array($obj) && is_array($obj['data']) && isset($obj['data']['value']) && !empty($obj['data']['value'])) $quoteValue = zeroBSCRM_formatCurrency($obj['data']['value']); $extsource = ''; if (is_array($obj) && is_array($obj['extsource']) && isset($obj['extsource']['source']) && !empty($obj['extsource']['source'])) $extsource = $obj['extsource']['source']; $extsourceID = ''; if (is_array($obj) && is_array($obj['extsource']) && isset($obj['extsource']['uid']) && !empty($obj['extsource']['uid'])) $extsourceID = $obj['extsource']['uid']; // build str $note_long_description = ''; $noteShortDesc = ''; if (!empty($quoteID)) $noteShortDesc .= '#'.$quoteID; if (!empty($quoteTitle)) $noteShortDesc .= $quoteTitle; if (!empty($quoteValue)) $noteShortDesc .= ' ('.$quoteValue.')'; if (!empty($extsource) && !empty($extsourceID)) $note_long_description = __('Created by','zero-bs-crm').' '.zeroBS_getExternalSourceTitle($extsource,$extsourceID); if (is_array($noteAgainstIDs['contacts']) && count($noteAgainstIDs['contacts']) > 0) foreach ($noteAgainstIDs['contacts'] as $cID){ #} Add log $newLogID = zeroBS_addUpdateLog($cID,-1,-1,array( 'type' => __('Quote Created','zero-bs-crm'), 'shortdesc' => $noteShortDesc, 'longdesc' => $note_long_description ),'zerobs_customer'); } } else { // legacy, <3.0 #} Retrieve necessary info: $zbsNoteAgainstPostID = -1; if (is_array($obj) && isset($obj['againstid']) && $obj['againstid'] > 0) $zbsNoteAgainstPostID = (int)$obj['againstid']; #TRANSITIONTOMETANO #$quoteID = ''; if (is_array($obj) && isset($obj['id']) && !empty($obj['id'])) $quoteID = $obj['id']; $quoteID = ''; if (is_array($obj) && isset($obj['zbsid'])) $quoteID = $obj['zbsid']; $quoteName = ''; if (is_array($obj) && isset($obj['id']) && isset($obj['quoteMeta']) && is_array($obj['quoteMeta']) && isset($obj['quoteMeta']['name'])) $quoteName = $obj['quoteMeta']['name']; $quoteValue = ''; if (is_array($obj) && isset($obj['id']) && isset($obj['quoteMeta']) && is_array($obj['quoteMeta']) && isset($obj['quoteMeta']['val'])) $quoteValue = zeroBSCRM_prettifyLongInts($obj['quoteMeta']['val']); $noteShortDesc = ''; if (!empty($quoteID)) $noteShortDesc .= ' #'.$quoteID; if (!empty($quoteName)) $noteShortDesc .= ' '.$quoteName; if (!empty($quoteValue)) $noteShortDesc .= ' ('.zeroBSCRM_getCurrencyStr().' '.$quoteValue.')'; if (isset($zbsNoteAgainstPostID) && !empty($zbsNoteAgainstPostID)){ #} Add log $newLogID = zeroBS_addUpdateLog($zbsNoteAgainstPostID,-1,-1,array( 'type' => 'Quote Created', 'shortdesc' => $noteShortDesc, 'longdesc' => '' ),'zerobs_customer'); } } } } // Adds an "accepted" log to contact (of quote) (if setting) function zeroBSCRM_IA_AcceptedQuoteLog($obj=array()){ # if setting $autoLogThis = zeroBSCRM_getSetting('autolog_quote_accepted'); if ($autoLogThis > 0){ global $zbs; // v3+ if ($zbs->isDAL3()){ // retrieve quote $quoteID = ''; if (is_array($obj) && isset($obj['id'])) $quoteID = $obj['id']; $quote = $zbs->DAL->quotes->getQuote($quoteID); if ( is_array($quote) && count($quote['contact']) > 0 ){ // get signed by if passed $signedBy = ''; if (is_array($obj) && is_array($obj['data']) && isset($obj['data']['signed']) && !empty($obj['data']['signed'])) $signedBy = $obj['data']['signed']; // could get `ip` but not really user friendly/needed // build str $note_long_description = ''; $noteShortDesc = ''; if (!empty($quoteID)) $noteShortDesc .= '#'.$quoteID; if (!empty($quoteTitle)) $noteShortDesc .= $quote['title']; if (!empty($quoteValue)) $noteShortDesc .= ' ('.zeroBSCRM_formatCurrency($quote['value']).')'; if (!empty($signedBy)) $note_long_description = __('Signed','zero-bs-crm').' '.$signedBy; if (is_array($quote['contact'])) foreach ($quote['contact'] as $contact){ #} Add log $newLogID = zeroBS_addUpdateLog($contact['id'],-1,-1,array( 'type' => __('Quote: Accepted','zero-bs-crm'), 'shortdesc' => $noteShortDesc, 'longdesc' => $note_long_description ),'zerobs_customer'); } } } } } #} Adds a "created" log to customer (of quotes) (if setting) function zeroBSCRM_IA_NewInvoiceLog($obj=array()){ # if setting $autoLogThis = zeroBSCRM_getSetting('autolog_invoice_new'); if ($autoLogThis > 0){ global $zbs; // v3+ if ($zbs->isDAL3()){ // 3.0+ #} Retrieve necessary info: $noteAgainstIDs = array('contacts'=>array(),'companies'=>array()); if (is_array($obj) && isset($obj['againstids']) && is_array($obj['againstids'])){ // trusting they're correctly passed... if (isset($obj['againstids']['contacts']) && is_array($obj['againstids']['contacts'])) $noteAgainstIDs['contacts'] = $obj['againstids']['contacts']; if (isset($obj['againstids']['companies']) && is_array($obj['againstids']['companies'])) $noteAgainstIDs['companies'] = $obj['againstids']['companies']; } $invoiceID = ''; if (is_array($obj) && isset($obj['id'])) $invoiceID = $obj['id']; $invoiceRef = ''; if (is_array($obj) && is_array($obj['data']) && isset($obj['data']['id_override']) && !empty($obj['data']['id_override'])) $invoiceRef = $obj['data']['id_override']; $invoiceValue = ''; if (is_array($obj) && is_array($obj['data']) && isset($obj['data']['total']) && !empty($obj['data']['total'])) $invoiceValue = zeroBSCRM_formatCurrency($obj['data']['total']); $extsource = ''; if (is_array($obj) && is_array($obj['extsource']) && isset($obj['extsource']['source']) && !empty($obj['extsource']['source'])) $extsource = $obj['extsource']['source']; $extsourceID = ''; if (is_array($obj) && is_array($obj['extsource']) && isset($obj['extsource']['uid']) && !empty($obj['extsource']['uid'])) $extsourceID = $obj['extsource']['uid']; // build str $note_long_description = ''; $noteShortDesc = ''; if (!empty($invoiceID) && empty($invoiceRef)) $noteShortDesc .= '#'.$invoiceID; if (!empty($invoiceRef)) $noteShortDesc .= $invoiceRef; if (!empty($invoiceValue)) $noteShortDesc .= ' ('.$invoiceValue.')'; if (!empty($extsource) && !empty($extsourceID)) $note_long_description = __('Created by','zero-bs-crm').' '.zeroBS_getExternalSourceTitle($extsource,$extsourceID); if (is_array($noteAgainstIDs['contacts']) && count($noteAgainstIDs['contacts']) > 0) foreach ($noteAgainstIDs['contacts'] as $cID){ #} Add log $newLogID = zeroBS_addUpdateLog($cID,-1,-1,array( 'type' => __('Invoice Created','zero-bs-crm'), 'shortdesc' => $noteShortDesc, 'longdesc' => $note_long_description ),'zerobs_customer'); } } else { // legacy, <3.0 #} Retrieve necessary info: $zbsNoteAgainstPostID = -1; if (is_array($obj) && isset($obj['againstid']) && $obj['againstid'] > 0) $zbsNoteAgainstPostID = (int)$obj['againstid']; #TRANSITIONTOMETANO #$invoiceNo = ''; if (is_array($obj) && isset($obj['id']) && isset($obj['invoiceMeta']) && is_array($obj['invoiceMeta']) && isset($obj['invoiceMeta']['no'])) $invoiceNo = $obj['invoiceMeta']['no']; $invoiceNo = ''; if (is_array($obj) && isset($obj['zbsid'])) $invoiceNo = $obj['zbsid']; $invoiceValue = ''; if (is_array($obj) && isset($obj['id']) && isset($obj['invoiceMeta']) && is_array($obj['invoiceMeta']) && isset($obj['invoiceMeta']['val'])) $invoiceValue = zeroBSCRM_prettifyLongInts($obj['invoiceMeta']['val']); $noteShortDesc = ''; if (!empty($invoiceNo)) $noteShortDesc .= ' #'.$invoiceNo; if (!empty($invoiceValue)) $noteShortDesc .= ' ('.zeroBSCRM_getCurrencyStr().' '.$invoiceValue.')'; if (isset($zbsNoteAgainstPostID) && !empty($zbsNoteAgainstPostID)){ #} Add log $newLogID = zeroBS_addUpdateLog($zbsNoteAgainstPostID,-1,-1,array( 'type' => 'Invoice Created', 'shortdesc' => $noteShortDesc, 'longdesc' => '' ),'zerobs_customer'); } } // / <3.0 } } #} Adds a "created" log to customer (of trans) (if setting) function zeroBSCRM_IA_NewTransactionLog($obj=array()){ $newLogID = false; #} if setting $autoLogThis = zeroBSCRM_getSetting('autolog_transaction_new'); if ($autoLogThis > 0){ global $zbs; // NOTE the lack of "automatorpassthrough" support v3.0+, this was left out to keep v3.0 MVP/lean // ... not sure where used any longer. If relevant, reintegrate from the v2 switched ver below // v3+ if ($zbs->isDAL3()){ // 3.0+ #} Retrieve necessary info: $noteAgainstIDs = array('contacts'=>array(),'companies'=>array()); if (is_array($obj) && isset($obj['againstids']) && is_array($obj['againstids'])){ // trusting they're correctly passed... if (isset($obj['againstids']['contacts']) && is_array($obj['againstids']['contacts'])) $noteAgainstIDs['contacts'] = $obj['againstids']['contacts']; if (isset($obj['againstids']['companies']) && is_array($obj['againstids']['companies'])) $noteAgainstIDs['companies'] = $obj['againstids']['companies']; } $transactionID = ''; if (is_array($obj) && isset($obj['id'])) $transactionID = $obj['id']; $transactionRef = ''; if (is_array($obj) && is_array($obj['data']) && isset($obj['data']['ref']) && !empty($obj['data']['ref'])) $transactionRef = $obj['data']['ref']; $transactionValue = ''; if (is_array($obj) && is_array($obj['data']) && isset($obj['data']['total']) && !empty($obj['data']['total'])) $transactionValue = zeroBSCRM_formatCurrency($obj['data']['total']); $extsource = ''; if (is_array($obj) && is_array($obj['extsource']) && isset($obj['extsource']['source']) && !empty($obj['extsource']['source'])) $extsource = $obj['extsource']['source']; $extsourceID = ''; if (is_array($obj) && is_array($obj['extsource']) && isset($obj['extsource']['uid']) && !empty($obj['extsource']['uid'])) $extsourceID = $obj['extsource']['uid']; // build str $note_long_description = ''; $noteShortDesc = ''; if (!empty($transactionID) && empty($transactionRef)) $noteShortDesc .= '#'.$transactionID; if (!empty($transactionRef)) $noteShortDesc .= $transactionRef; if (!empty($transactionValue)) $noteShortDesc .= ' ('.$transactionValue.')'; if (!empty($extsource) && !empty($extsourceID)) $note_long_description = __('Created by','zero-bs-crm').' '.zeroBS_getExternalSourceTitle($extsource,$extsourceID); if (is_array($noteAgainstIDs['contacts']) && count($noteAgainstIDs['contacts']) > 0) foreach ($noteAgainstIDs['contacts'] as $cID){ #} Add log $newLogID = zeroBS_addUpdateLog($cID,-1,-1,array( 'type' => __('Transaction Created','zero-bs-crm'), 'shortdesc' => $noteShortDesc, 'longdesc' => $note_long_description ),'zerobs_customer'); } } else { // legacy, <3.0 #} if has id $zbsNoteAgainstPostID = -1; if (is_array($obj) && isset($obj['againstid']) && $obj['againstid'] > 0) $zbsNoteAgainstPostID = (int)$obj['againstid']; if (isset($zbsNoteAgainstPostID) && !empty($zbsNoteAgainstPostID)){ #} First check if an override is passed... if (isset($obj['automatorpassthrough']) && is_array($obj['automatorpassthrough']) && isset($obj['automatorpassthrough']['note_override']) && is_array($obj['automatorpassthrough']['note_override']) && isset($obj['automatorpassthrough']['note_override']['type'])){ #} An overriding note has been passed, just use that #} Add log $newLogID = zeroBS_addUpdateLog($zbsNoteAgainstPostID,-1,-1,$obj['automatorpassthrough']['note_override'],'zerobs_transaction'); } else { #} No override, use default processing... #} Retrieve necessary info: $transID = ''; if (is_array($obj) && isset($obj['id']) && isset($obj['transactionMeta']) && is_array($obj['transactionMeta']) && isset($obj['transactionMeta']['orderid'])) $transID = $obj['transactionMeta']['orderid']; $transValue = ''; if (is_array($obj) && isset($obj['id']) && isset($obj['transactionMeta']) && is_array($obj['transactionMeta']) && isset($obj['transactionMeta']['total'])) $transValue = zeroBSCRM_prettifyLongInts($obj['transactionMeta']['total']); $noteShortDesc = ''; if (!empty($transID)) $noteShortDesc .= ' #'.$transID; if (!empty($transValue)) $noteShortDesc .= ' ('.zeroBSCRM_getCurrencyStr().' '.$transValue.')'; #} Add log $newLogID = zeroBS_addUpdateLog($zbsNoteAgainstPostID,-1,-1,array( 'type' => 'Transaction Created', 'shortdesc' => $noteShortDesc, 'longdesc' => '' ),'zerobs_customer'); } } } } // / if autolog return $newLogID; } #} Adds a "created" log to customer (of task) (if setting) function zeroBSCRM_IA_NewEventLog($obj=array()){ $newLogID = false; #} if setting $autoLogThis = zeroBSCRM_getSetting('autolog_event_new'); #} if has id $zbsNoteAgainstPostID = -1; if (is_array($obj) && isset($obj['againstid']) && $obj['againstid'] > 0) $zbsNoteAgainstPostID = (int)$obj['againstid']; if ($autoLogThis > 0 && isset($zbsNoteAgainstPostID) && !empty($zbsNoteAgainstPostID)){ global $zbs; // NOTE the lack of "automatorpassthrough" support v3.0+, this was left out to keep v3.0 MVP/lean // ... not sure where used any longer. If relevant, reintegrate from the v2 switched ver below // v3+ if ($zbs->isDAL3()){ // 3.0+ #} Retrieve necessary info: $noteAgainstIDs = array('contacts'=>array(),'companies'=>array()); if (is_array($obj) && isset($obj['againstids']) && is_array($obj['againstids'])){ // trusting they're correctly passed... if (isset($obj['againstids']['contacts']) && is_array($obj['againstids']['contacts'])) $noteAgainstIDs['contacts'] = $obj['againstids']['contacts']; if (isset($obj['againstids']['companies']) && is_array($obj['againstids']['companies'])) $noteAgainstIDs['companies'] = $obj['againstids']['companies']; } $taskID = ''; if (is_array($obj) && isset($obj['id'])) $taskID = $obj['id']; $taskTitle = ''; if (is_array($obj) && is_array($obj['data']) && isset($obj['data']['title']) && !empty($obj['data']['title'])) $taskTitle = $obj['data']['title']; $taskDescription = ''; if (is_array($obj) && is_array($obj['data']) && isset($obj['data']['desc']) && !empty($obj['data']['desc'])) $taskDescription = $obj['data']['desc']; $taskStart = ''; if (is_array($obj) && is_array($obj['data']) && isset($obj['data']['start']) && !empty($obj['data']['start'])) $taskStart = zeroBSCRM_locale_utsToDatetime($obj['data']['start']); // build str $note_long_description = ''; $noteShortDesc = ''; if (!empty($taskID) && empty($taskTitle)) $noteShortDesc .= '#'.$taskID; if (!empty($taskTitle)) $noteShortDesc .= $taskTitle; if (!empty($taskDescription)) $note_long_description = $taskDescription; if (!empty($taskStart)) { // pad if filled if (!empty($note_long_description)) $note_long_description .= '<br />'; // add starting date $note_long_description .= __('Starts at ','zero-bs-crm').' '.$taskStart; } if (is_array($noteAgainstIDs['contacts']) && count($noteAgainstIDs['contacts']) > 0) foreach ($noteAgainstIDs['contacts'] as $cID){ #} Add log $newLogID = zeroBS_addUpdateLog($cID,-1,-1,array( 'type' => __('Task Created','zero-bs-crm'), 'shortdesc' => $noteShortDesc, 'longdesc' => $note_long_description ),'zerobs_customer'); } } else { #} First check if an override is passed... if (isset($obj['automatorpassthrough']) && is_array($obj['automatorpassthrough']) && isset($obj['automatorpassthrough']['note_override']) && is_array($obj['automatorpassthrough']['note_override']) && isset($obj['automatorpassthrough']['note_override']['type'])){ #} An overriding note has been passed, just use that #} Add log $newLogID = zeroBS_addUpdateLog($zbsNoteAgainstPostID,-1,-1,$obj['automatorpassthrough']['note_override'],'zerobs_event'); } else { #} No override, use default processing... #} Retrieve necessary info: $task_id = ''; if (is_array($obj) && isset($obj['id'])) $task_id = $obj['id']; $task_name =''; if (!empty($task_id)) $task_name = get_the_title( $task_id ); #} got meta? $task_date_str = ''; if (is_array($obj) && isset($obj['id']) && isset($obj['eventMeta']) && is_array($obj['eventMeta']) && isset($obj['eventMeta']['from'])){ // takenfromMike's + tweaked for readability if($obj['eventMeta'] == ''){ $start_d = date('l M jS G:i',time()); $end_d = date('l M jS G:i',time()); }else{ $d = new DateTime($obj['eventMeta']['from']); $start_d = $d->format('l M jS G:i'); $d = new DateTime($obj['eventMeta']['to']); $end_d = $d->format('l M jS G:i'); } if (!empty($start_d)) $task_date_str = $start_d; if ($end_d != $start_d) $task_date_str .= ' '.__('to',"zero-bs-crm").' '.$end_d; } $noteShortDesc = ''; $note_long_description = ''; if (!empty($task_name)) { $noteShortDesc = $task_name; $note_long_description = $task_name; } if (!empty($task_date_str)) { if (!empty($note_long_description)) $note_long_description .= '<br />'; $note_long_description .= $task_date_str; } if (!empty($task_id)) { if (!empty($noteShortDesc)) $noteShortDesc .= ' '; $noteShortDesc .= '(#'.$task_id.')'; } #} Add log $newLogID = zeroBS_addUpdateLog($zbsNoteAgainstPostID,-1,-1,array( 'type' => 'Task Created', 'shortdesc' => $noteShortDesc, 'longdesc' => $note_long_description ),'zerobs_customer'); } } // / <3.0 } return $newLogID; } /** * Catches new logs and updates contact 'last contacted' if contact type log * * @param arr $obj Array containing log details. */ function zeroBSCRM_IA_NewLogCatchContactsDB2( $obj = array() ) { global $zbs; // for now, only contacts if ( is_array( $obj ) && isset( $obj['logagainsttype'] ) && ( $obj['logagainsttype'] === 'zerobs_customer' || $obj['logagainsttype'] === ZBS_TYPE_CONTACT ) ) { // check if 'contact' type $log_type = ''; if ( is_array( $obj ) && isset( $obj['logtype'] ) ) { $log_type = $obj['logtype']; } if ( ! empty( $log_type ) && in_array( $log_type, $zbs->DAL->logs->contact_log_types, true ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase // checks out..proceed // retrieve $contact_id = -1; if ( is_array( $obj ) && isset( $obj['logagainst'] ) ) { $contact_id = (int) $obj['logagainst']; } if ( ! empty( $contact_id ) && $contact_id > 0 ) { // update contact $zbs->DAL->contacts->setContactLastContactUTS( $contact_id, time() ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase } } // is a contact type log } // is log against contact } #} Adds a "created" log to customer (if setting) function zeroBSCRM_IA_NewClientPortalUserLog($obj=array()){ # if setting $autoLogThis = zeroBSCRM_getSetting('autolog_clientportal_new'); if ($autoLogThis > 0){ #} Retrieve necessary info: $zbsNoteAgainstPostID = -1; if (is_array($obj) && isset($obj['againstid']) && $obj['againstid'] > 0) $zbsNoteAgainstPostID = (int)$obj['againstid']; #TRANSITIONTOMETANO $userID = -1; if (is_array($obj) && isset($obj['id']) && $obj['id'] > 0) $userID = (int)$obj['id']; $userEmail = ''; if (is_array($obj) && isset($obj['userEmail'])) $userEmail = $obj['userEmail']; $noteShortDesc = ''; if (!empty($userEmail)) $noteShortDesc = __('Created with email',"zero-bs-crm").': '.$userEmail; if ($userID > 0) $noteShortDesc .= ' (#'.$userID.')'; if (isset($zbsNoteAgainstPostID) && !empty($zbsNoteAgainstPostID)){ #} Add log $newLogID = zeroBS_addUpdateContactLog($zbsNoteAgainstPostID,-1,-1,array( 'type' => 'Client Portal User Created', 'shortdesc' => $noteShortDesc, 'longdesc' => '' )); } } } #} creates customer client portal user (if setting) function zeroBSCRM_IA_NewCustomerClientPortal($obj=array()){ # if setting $autoFireThis = zeroBSCRM_getSetting('portalusers'); if ($autoFireThis > 0){ #} Retrieve necessary info: $userID = -1; if (is_array($obj) && isset($obj['id']) && $obj['id'] > 0) $userID = (int)$obj['id']; // yup $okayToFire = true; // Specific status mode ================================== #} If using "specific statuses only" $statusList = zeroBSCRM_getSetting('portalusers_status'); if (!is_array($statusList) && (empty($statusList) || $statusList == 'all')){ // nothing to do } else { if (is_array($statusList)){ // generate a list of "Okay" statuses that this'll check later on... $zbsStatusStr = zeroBSCRM_getCustomerStatuses(); $zbsStatuses = explode(',', $zbsStatusStr); $okayStatuses = array(); // cycle through settings + copy "full str" rather than "full_str" that it'll be saved as foreach ($zbsStatuses as $statusStr){ // permify $statusKey = strtolower(str_replace(' ','_',str_replace(':','_',$statusStr))); // present? if (in_array($statusKey, $statusList)) $okayStatuses[] = $statusStr; } // is user's status in one of these? $customerStatus = ''; if (isset($obj['customerMeta']) && is_array($obj['customerMeta']) && isset($obj['customerMeta']['status'])) $customerStatus = $obj['customerMeta']['status']; // if no status, try fill from (whatever was added) to db if (empty($customerStatus)){ $cMeta = zeroBS_getCustomerMeta($userID); if (is_array($cMeta) && isset($cMeta['status'])) $customerStatus = $cMeta['status']; } // check status if (!empty($customerStatus) && in_array($customerStatus,$okayStatuses)) $okayToFire = true; else $okayToFire = false; // customer status empty or not in approved list :) } else { // non-standard val for status list, override it to all global $zbs; $zbs->settings->update('portalusers_status','all'); // and let it fire.. } } // / Specific status mode ================================== if ($okayToFire){ // this'll check itself if already exists, so no harm in letting it (potentially) multifire if ($userID > 0) zeroBSCRM_createClientPortalUserFromRecord($userID); } } } #} Compiles any segments which this contact fits in // works for new contacts + contact edits function zeroBSCRM_IA_ContactSegmentCompiler($obj=array()){ # if setting $autoCompileSegments = 1; if ($autoCompileSegments > 0){ #} Retrieve necessary info: $zbsNoteAgainstPostID = -1; if (is_array($obj) && isset($obj['id'])) $zbsNoteAgainstPostID = (int)$obj['id']; $contactWasInSegments = array(); if (is_array($obj) && isset($obj['prevSegments']) && is_array($obj['prevSegments'])) $contactWasInSegments = $obj['prevSegments']; if (isset($zbsNoteAgainstPostID) && !empty($zbsNoteAgainstPostID)){ global $zbs; // v2 v3 switch if ($zbs->isDAL3() && isset($zbs->DAL->segments)) $zbs->DAL->segments->compileSegmentsAffectedByContact($zbsNoteAgainstPostID,$contactWasInSegments); elseif ($zbs->isDAL2() && method_exists($zbs->DAL,'compileSegmentsAffectedByContact')) $zbs->DAL->compileSegmentsAffectedByContact($zbsNoteAgainstPostID,$contactWasInSegments); } } } /* * Recompiles any segments affected by quote change * * Fires on: * quote.new * quote.update * */ function zeroBSCRM_IA_quoteSegmentCompiler( $obj=array() ){ global $zbs; // if quote passed: if ( is_array( $obj ) && isset( $obj['data'] ) ){ // requires DAL v3 if ($zbs->isDAL3() && isset($zbs->DAL->segments)){ $zbs->DAL->segments->compileSegmentsAffectedByQuote( $obj['data'] ); } } } /* * Recompiles any segments affected by invoice change * * Fires on: * invoice.new * invoice.update * */ function zeroBSCRM_IA_invoiceSegmentCompiler( $obj=array() ){ global $zbs; // if quote passed: if ( is_array( $obj ) && isset( $obj['data'] ) ){ // requires DAL v3 if ($zbs->isDAL3() && isset($zbs->DAL->segments)){ $zbs->DAL->segments->compileSegmentsAffectedByInvoice( $obj['data'] ); } } } /* * Recompiles any segments affected by transaction change * * Fires on: * transaction.new * transaction.update * */ function zeroBSCRM_IA_transactionSegmentCompiler( $obj=array() ){ global $zbs; // if quote passed: if ( is_array( $obj ) && isset( $obj['data'] ) ){ // requires DAL v3 if ($zbs->isDAL3() && isset($zbs->DAL->segments)){ $zbs->DAL->segments->compileSegmentsAffectedByTransaction( $obj['data'] ); } } } #} when customer status changes, portal access can be revoked/added based on status (if setting) function zeroBSCRM_IA_CustomerStatusChangePortalAndLog($obj=array()){ # if setting $autoFireThis = zeroBSCRM_getSetting('portalusers'); if ($autoFireThis > 0){ #} Retrieve necessary info: $userID = -1; if (is_array($obj) && isset($obj['id']) && $obj['id'] > 0) $userID = (int)$obj['id']; #} If using "specific statuses only" $statusList = zeroBSCRM_getSetting('portalusers_status'); if (!is_array($statusList) && (empty($statusList) || $statusList == 'all')){ // nothing to do - all statuses allowed } else { if (is_array($statusList)){ // generate a list of "Okay" statuses that this'll check later on... $zbsStatusStr = zeroBSCRM_getCustomerStatuses(); $zbsStatuses = explode(',', $zbsStatusStr); $okayStatuses = array(); // cycle through settings + copy "full str" rather than "full_str" that it'll be saved as foreach ($zbsStatuses as $statusStr){ // permify $statusKey = strtolower(str_replace(' ','_',str_replace(':','_',$statusStr))); // present? if (in_array($statusKey, $statusList)) $okayStatuses[] = $statusStr; } // is user's status in one of these? $customerStatus = ''; if (isset($obj['customerMeta']) && is_array($obj['customerMeta']) && isset($obj['customerMeta']['status'])) $customerStatus = $obj['customerMeta']['status']; // if no status, try fill from (whatever was added) to db if (empty($customerStatus)){ $cMeta = zeroBS_getCustomerMeta($userID); if (is_array($cMeta) && isset($cMeta['status'])) $customerStatus = $cMeta['status']; } // check status if (!empty($customerStatus) && in_array($customerStatus,$okayStatuses)){ // NEEDS account access // already got? $portalID = zeroBSCRM_getClientPortalUserID($userID); if (!empty($portalID) && $portalID > 0){ $isDisabled = zeroBSCRM_isCustomerPortalDisabled($userID); // if disabled if ($isDisabled){ // already got acc, make sure enabled zeroBSCRM_customerPortalDisableEnable($userID,'enable'); $noteShortDesc = __('Access enabled (by change of status to',"zero-bs-crm").' "'.$customerStatus.'"'; #} Add log $newLogID = zeroBS_addUpdateContactLog($userID,-1,-1,array( 'type' => 'Client Portal Access Changed', 'shortdesc' => $noteShortDesc, 'longdesc' => '' )); } } else { // make acc if ($userID > 0) { zeroBSCRM_createClientPortalUserFromRecord($userID); $noteShortDesc = __('Access created (by change of status to',"zero-bs-crm").' "'.$customerStatus.'"'; #} Add log $newLogID = zeroBS_addUpdateContactLog($userID,-1,-1,array( 'type' => 'Client Portal Access Changed', 'shortdesc' => $noteShortDesc, 'longdesc' => '' )); } } } else { // SHOULD Not have account // already got? $portalID = zeroBSCRM_getClientPortalUserID($userID); if (!empty($portalID) && $portalID > 0){ $isDisabled = zeroBSCRM_isCustomerPortalDisabled($userID); // if not already disabled if (!$isDisabled){ // disable if found zeroBSCRM_customerPortalDisableEnable($userID,'disable'); $noteShortDesc = __('Access disabled (by change of status to',"zero-bs-crm").' "'.$customerStatus.'"'; #} Add log $newLogID = zeroBS_addUpdateContactLog($userID,-1,-1,array( 'type' => 'Client Portal Access Changed', 'shortdesc' => $noteShortDesc, 'longdesc' => '' )); } } } } else { // non-standard val for status list, override it to all global $zbs; $zbs->settings->update('portalusers_status','all'); // and... nothing to do - all statuses allowed } } // / Specific status mode ================================== } // / if autofire on :) } #} Adds a "changed" log when customer status change (if setting) function zeroBSCRM_IA_CustomerStatusChangeAutoLog($obj=array()){ # if setting $autoLogThis = zeroBSCRM_getSetting('autolog_customer_statuschange'); if ($autoLogThis > 0){ #} Retrieve necessary info: $zbsNoteAgainstPostID = -1; if (is_array($obj) && isset($obj['againstid']) && $obj['againstid'] > 0) $zbsNoteAgainstPostID = (int)$obj['againstid']; #TRANSITIONTOMETANO // I nicely pass these... $from = ''; if (is_array($obj) && isset($obj['from']) && !empty($obj['from'])) $from = $obj['from']; $to = ''; if (is_array($obj) && isset($obj['to']) && !empty($obj['to'])) $to = $obj['to']; if (isset($zbsNoteAgainstPostID) && !empty($zbsNoteAgainstPostID) && isset($to) && !empty($to)){ $shortDesc = ''; if (!empty($from)) $shortDesc = __('From',"zero-bs-crm").' "'.$from.'" '.__('to',"zero-bs-crm").' "'.$to.'"'; else $shortDesc = __('To',"zero-bs-crm").' "'.$to.'"'; #} Add log $newLogID = zeroBS_addUpdateContactLog($zbsNoteAgainstPostID,-1,-1,array( 'type' => 'Status Change', 'shortdesc' => $shortDesc, 'longdesc' => '' )); } } } /* ====================================================== / Internal Automator Recipe Functions ====================================================== */ /* ====================================================== Internal Automator Recipe Functions - WP HOOK tieins... just middlemen here really ====================================================== */ #} Fires the hook & passes in the obj, for those who still want to use wp_hook's rather than IA Automator #} Fires on 'customer.new' IA function zeroBSCRM_IA_NewCustomerWPHook($obj=array()){ if (is_array($obj) && isset($obj['id']) && !empty($obj['id'])) { do_action( 'jpcrm_after_contact_insert', $obj['id'] ); // legacy, use `jpcrm_after_contact_insert` from 5.3+ do_action( 'zbs_new_customer', $obj['id'] ); } } /** * Fires on 'contact.update', 'contact.email.update', and 'contact.status.update IA. * * @param array $obj An array holding contact object data. */ function zeroBSCRM_IA_EditCustomerWPHook( $obj = array() ) { if ( is_array( $obj ) && isset( $obj['id'] ) && ! empty( $obj['id'] ) ) { do_action( 'jpcrm_after_contact_update', $obj['id'] ); // legacy, use `jpcrm_after_contact_update` from 5.3+ do_action( 'zbs_edit_customer', $obj['id'] ); } } #} Fires on 'customer.vitals.edit' IA. function zeroBSCRM_IA_EditCustomerVitalsWPHook($obj=array()){ if (is_array($obj) && isset($obj['id']) && !empty($obj['id'])) do_action('zbs_edit_customer_vitals', $obj['id']); } /** * Fires on 'contact.email.update' IA. Now legacy, redirecting to zeroBSCRM_IA_EditCustomerWPHook * * @param array $obj An array holding contact object data. */ function zeroBSCRM_IA_EditCustomerEmailWPHook($obj=array()){ if (is_array($obj) && isset($obj['id']) && !empty($obj['id'])) do_action('zbs_edit_customer_email', $obj['id']); } /** * Fires on 'contact.delete' IA. * * @param array $obj An array holding contact object data. */ function zeroBSCRM_IA_DeleteCustomerWPHook( $obj = array() ) { if ( is_array( $obj ) && isset( $obj['id'] ) && ! empty( $obj['id'] ) ) { // Legacy: do_action( 'zbs_delete_customer', $obj['id'] ); } } /** * Fires on 'contact.before.delete' IA. * * @param array $obj An array holding contact object data. */ function zeroBSCRM_IA_BeforeDeleteCustomerWPHook($obj=array()){ if ( is_array( $obj ) && isset( $obj['id'] ) && ! empty( $obj['id'] ) ) { do_action( 'jpcrm_before_delete_contact', $obj ); } } /** * Fires on 'company.new' IA. * * @param array $obj An array holding company object data. */ function zeroBSCRM_IA_NewCompanyWPHook( $obj = array() ) { if ( is_array( $obj ) && isset( $obj['id'] ) && ! empty( $obj['id'] ) ) { // Legacy: do_action( 'zbs_new_company', $obj['id'] ); } } /** * Fires on 'company.delete' IA. * * @param array $obj An array holding company object data. */ function zeroBSCRM_IA_DeleteCompanyWPHook( $obj = array() ) { if ( is_array( $obj ) && isset( $obj['id'] ) && ! empty( $obj['id'] ) ) { // Legacy: do_action( 'zbs_delete_company', $obj['id'] ); } } #} Fires on 'quote.new' IA function zeroBSCRM_IA_NewQuoteWPHook($obj=array()){ if (is_array($obj) && isset($obj['id']) && !empty($obj['id'])) do_action('zbs_new_quote', $obj['id']); } #} Fires on 'quote.accepted' IA function zeroBSCRM_IA_AcceptedQuoteWPHook($obj=array()){ if (is_array($obj) && isset($obj['id']) && !empty($obj['id'])) do_action('jpcrm_quote_accepted', $obj['id']); } #} Fires on 'quote.delete' IA function zeroBSCRM_IA_DeleteQuoteWPHook($obj=array()){ if (is_array($obj) && isset($obj['id']) && !empty($obj['id'])) do_action('zbs_delete_quote', $obj['id']); } /** * Fires on 'invoice.new' IA. * * @param array $obj An array holding invoice object data. */ function zeroBSCRM_IA_NewInvoiceWPHook( $obj = array() ) { if ( is_array( $obj ) && isset( $obj['id'] ) && ! empty( $obj['id'] ) ) { do_action( 'zbs_new_invoice', $obj['id'] ); } } /** * Fires on 'invoice.update' and 'invoice.status.update' IA. * * @param array $obj An array holding invoice object data. */ function zeroBSCRM_IA_EditInvoiceWPHook( $obj = array() ) { if ( is_array( $obj ) && isset( $obj['id'] ) && ! empty( $obj['id'] ) ) { do_action( 'zbs_new_invoice', $obj['id'] ); } } /** * Fires on 'invoice.delete' IA. * * @param array $obj An array holding invoice object data. */ function zeroBSCRM_IA_DeleteInvoiceWPHook( $obj = array() ) { if ( is_array( $obj ) && isset( $obj['id'] ) && ! empty( $obj['id'] ) ) { do_action( 'zbs_delete_invoice', $obj['id'] ); } } #} Fires on 'transaction.new' IA function zeroBSCRM_IA_NewTransactionWPHook($obj=array()){ if (is_array($obj) && isset($obj['id']) && !empty($obj['id'])) do_action('zbs_new_transaction', $obj['id']); } #} Fires on 'transaction.delete' IA function zeroBSCRM_IA_DeleteTransactionWPHook($obj=array()){ if (is_array($obj) && isset($obj['id']) && !empty($obj['id'])) do_action('zbs_delete_transaction', $obj['id']); } #} Fires on 'event.new' IA function zeroBSCRM_IA_NewEventWPHook($obj=array()){ if (is_array($obj) && isset($obj['id']) && !empty($obj['id'])) do_action('zbs_new_event', $obj['id']); } #} Fires on 'event.update' IA function zeroBSCRM_IA_UpdateEventWPHook($obj=array()){ if (is_array($obj) && isset($obj['id']) && !empty($obj['id'])) do_action('zbs_update_event', $obj['id']); } #} Fires on 'event.delete' IA function zeroBSCRM_IA_DeleteEventWPHook($obj=array()){ if (is_array($obj) && isset($obj['id']) && !empty($obj['id'])) do_action('zbs_delete_event', $obj['id']); } #} Fires on 'clientwpuser.new' IA function zeroBSCRM_IA_NewClientPortalUserHook($obj=array()){ if (is_array($obj) && isset($obj['id']) && !empty($obj['id'])) do_action('zbs_new_client_portal_user', $obj['id']); } #} Fires on 'form.delete' IA function zeroBSCRM_IA_DeleteFormWPHook($obj=array()){ if (is_array($obj) && isset($obj['id']) && !empty($obj['id'])) do_action('zbs_delete_form', $obj['id']); } #} Fires on 'segment.delete' IA function zeroBSCRM_IA_DeleteSegmentWPHook($obj=array()){ if (is_array($obj) && isset($obj['id']) && !empty($obj['id'])) do_action('zbs_delete_segment', $obj['id']); } /* ====================================================== / Internal Automator Recipe Functions - WP HOOK tieins ====================================================== */
projects/plugins/crm/includes/ZeroBSCRM.OnboardMe.php
<?php // phpcs:ignore WordPress.Files.FileName.NotHyphenatedLowercase /*! * Jetpack CRM - Onboard Me * https://jetpackcrm.com * V1.20 * * Copyright 2020 Automattic * * Date: 27th December 2017 * * * This is the "onboard me" plugin from the plugin hunt theme. The tour steps run from * /js/lib/zbs-welcome-tour.min.js * the tour runs using HOPSCOTCH * http://linkedin.github.io/hopscotch/ * this seems the BEST one for multi page tours * tried bootstrap tour, but this struggles (and has redirect issues) * also hopscotch can re position bubbles when elements clicked (such as the hide WP menu nav bar) * can work on the tour steps TOGETHER as don't want to overload them but also want to tour them * around the CRM so that they don't miss important features. */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ function zeroBS_onboardme_scripts(){ global $zbs; // Changed from bootstrap tour to hopscotch wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'onboardme-front', ZEROBSCRM_URL . 'js/lib/hopscotch.min.js', array( 'jquery' ), $zbs->version, true ); wp_enqueue_style( 'onboardme-css', ZEROBSCRM_URL . 'css/lib/hopscotch.min.css', array(), $zbs->version ); wp_enqueue_script( 'tour-front', ZEROBSCRM_URL . 'js/ZeroBSCRM.admin.tour' . wp_scripts_get_suffix() . '.js', array( 'jquery', 'onboardme-front' ), $zbs->version, true ); $zbs_tour_root = admin_url(); $zbs_tour = array( 'admin_url' => $zbs_tour_root, 'cta_url' => $zbs->urls['upgrade'], 'lang' => array( 'step1' => array( 'title' => __( 'Welcome to your Jetpack CRM', 'zero-bs-crm' ), 'content' => __( 'This quick tour will guide you through the basics.', 'zero-bs-crm' ) . '<hr />' . __( 'Clicking this logo will switch to full-screen mode. Try it!', 'zero-bs-crm' ), ), 'step2' => array( 'title' => __( 'Learn More', 'zero-bs-crm' ), 'content' => __( 'There are <strong>Learn</strong> buttons throughout the CRM. Use these to find out more about each area. Try clicking this one!', 'zero-bs-crm' ), ), 'step3' => array( 'title' => __( 'Notifications', 'zero-bs-crm' ), 'content' => __( 'Here is where your notifications can be found. This shows up-to-date events in your CRM', 'zero-bs-crm' ), ), 'step4' => array( 'title' => __( 'Notification Alert', 'zero-bs-crm' ), 'content' => __( 'When you have a notification, the icon will change. Next, we will look at what notifications are available.', 'zero-bs-crm' ), ), 'step5' => array( 'title' => __( 'Example Notification', 'zero-bs-crm' ), 'content' => __( 'Notifications are customised for your specific user. It\'s a great way to keep up-to-date (especially in teams!)', 'zero-bs-crm' ), ), 'step6' => array( 'title' => __( 'Hi from Jetpack', 'zero-bs-crm' ), 'content' => __( 'Here is another example of a notification. This time it\'s a greeting from all of us at Jetpack CRM.', 'zero-bs-crm' ), ), 'step7' => array( 'title' => __( 'Tools (Extensions)', 'zero-bs-crm' ), 'content' => __( 'When you install extensions they will appear here.', 'zero-bs-crm' ), ), 'step7a' => array( 'title' => __( 'Manage Modules', 'zero-bs-crm' ), 'content' => __( 'You can enable/disable core modules such as invoices and quotes from here.', 'zero-bs-crm' ) . '<hr />', ), 'step7b' => array( 'title' => __( 'Manage Extensions', 'zero-bs-crm' ), 'content' => __( 'You can manage your extensions from here.', 'zero-bs-crm' ) . '<hr />' . __( 'This is where Jetpack CRM shines as THE modular, "build-it-yourself" CRM!', 'zero-bs-crm' ), ), 'step9' => array( 'title' => __( 'Paid extensions', 'zero-bs-crm' ), 'content' => __( 'Here are our paid extensions. Want them all? You can take advantage of our Entrepreneur bundle.', 'zero-bs-crm' ), 'cta_label' => __( 'Upgrade to PRO', 'zero-bs-crm' ), ), 'step10' => array( 'title' => __( 'Jetpack CRM Settings', 'zero-bs-crm' ), 'content' => __( 'Here are the settings for your CRM.', 'zero-bs-crm' ) . '<hr />' . __( 'When you install extensions their settings tabs will appear here.', 'zero-bs-crm' ), ), 'step12' => array( 'title' => __( 'Override WordPress', 'zero-bs-crm' ), 'content' => __( 'If you only want Jetpack CRM to run on this WordPress install, you can enable "override mode", which removes all other WordPress sections.', 'zero-bs-crm' ), ), 'step13' => array( 'title' => __( 'Getting in touch', 'zero-bs-crm' ), 'content' => __( 'That\'s it for this quick tour. If you have any other questions, check out the knowledge base or drop us an email.', 'zero-bs-crm' ) . '<hr />' . __( 'Hover over your avatar, and select an option on the menu any time you need support. Enjoy!', 'zero-bs-crm' ), ), ), ); wp_localize_script( 'tour-front', 'zbs_tour', $zbs_tour ); } // restricted this to admins in core.php so is safe to bluntly add here add_action( 'zbs-global-admin-styles', 'zeroBS_onboardme_scripts' ); add_action('admin_footer','zeroBS_onboardme_helper'); function zeroBS_onboardme_helper(){ global $zbs; ?> <style type="text/css"> .tour-wrapper-footer { position: fixed; bottom: 10px; right: 20px; font-size: 50px; border-radius: 50%; height: 52px; width: 44px; padding: 0px; margin: 0px; line-height: 50px; cursor: pointer; } .tour-wrapper-footer a, .tour-wrapper-footer:hover a, .feedback-popup .title { color: #3f4347 !important; } .tour-wrapper-footer .fa { border-radius: 50%; height: 44px; width: 43px; padding: 0px; margin: 0px; } .tour-wrapper-footer a:focus{ outline: none !important; border: none; outline-width: 0; box-shadow: none; } .hopscotch-cta { background: #ffa502 !important; border-color: #af9163 !important; } </style> <?php }
projects/plugins/crm/includes/class-package-installer.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * Logic concerned with retrieving packages from our CDN and installing locally * */ namespace Automattic\JetpackCRM; // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; /* * Class encapsulating logic concerned with retrieving packages from our CDN and installing locally */ class Package_Installer { /* * Stores packages stack */ private $packages = array(); /* * Package install directory */ private $package_dir = false; /* * Init */ public function __construct() { // phpcs:ignore Squiz.Commenting.FunctionComment.WrongStyle $root_storage_info = jpcrm_storage_dir_info(); if ( ! $root_storage_info ) { throw new Exception( 'Jetpack CRM data folder could not be created!' ); } // set $package_dir $this->package_dir = $root_storage_info['path'] . '/packages/'; // define packages $this->packages = array( 'oauth_dependencies' => array( 'title' => __( 'OAuth Connection dependencies', 'zero-bs-crm' ), 'version' => 1.0, 'target_dir' => $this->package_dir, 'install_method' => 'unzip', 'post_install_call' => '', ), ); // does the working directory exist? If not create if ( ! file_exists( $this->package_dir ) ) { wp_mkdir_p( $this->package_dir ); // double check if ( ! file_exists( $this->package_dir ) ) { // we're going to struggle to install packages // Add admin notification zeroBSCRM_notifyme_insert_notification( get_current_user_id(), -999, -1, 'package.installer.dir_create_error', __( 'Main Working Directory', 'zero-bs-crm' ) ); } else { jpcrm_create_and_secure_dir_from_external_access( $this->package_dir, true ); } } } /* * Returns a list of packages available via our CDN */ public function list_all_available_packages( $with_install_status = false ){ // list packages available // later we could retrieve this via CDN's package_versions.json $packages = $this->packages; // if with install status, cycle through and check those if ( $with_install_status ){ $return = array(); foreach ( $packages as $package_key => $package_info ){ $return[ $package_key ] = $package_info; $return[ $package_key ]['installed'] = $this->get_package_install_info( $package_key ); // check for failed attempts $return[ $package_key ]['failed_installs'] = $this->get_fail_counter( $package_key ); } $packages = $return; } return $packages; } /* * Returns info array on package * * @param string $package_key - a slug for a particular package * */ public function get_package_info( $package_key = '' ){ if ( isset( $this->packages[ $package_key ] ) ){ $package = $this->packages[ $package_key ]; // supplement with local install info $package['installed'] = $this->get_package_install_info( $package_key ); // check for failed attempts $package['failed_installs'] = $this->get_fail_counter( $package_key ); return $package; } return false; } /* * Returns installed package info from package's version_info.json file * * @param string $package_key - a slug for a particular package * */ public function get_package_install_info( $package_key = '' ){ // retrieve version_info.json file and load info $package_version_info_file = $this->package_dir . $package_key . '/version_info.json'; if ( file_exists( $package_version_info_file ) ){ /* Example version_info.json file: { "key": "my_package_key", "version": "1.0" } */ $data = file_get_contents( $package_version_info_file ); return json_decode( $data, true ); } return false; } /* * Checks to see if a package is available on CDN * * @param string $package_key - a slug for a particular package * * @returns bool(ish) */ public function package_is_available( $package_key = '' ){ return ( $this->get_package_info( $package_key ) ? true : false ); // package doesn't exist on CDN or no connection } /* * Checks to see if a package is available locally * * @param string $package_key - a slug for a particular package * @param float $min_version - if > 0, installed version is compared and returns true only if min version met * */ public function package_is_installed( $package_key = '', $min_version = 0 ){ // retrieve installed version data if available $installed_info = $this->get_package_install_info( $package_key ); if ( !is_array( $installed_info ) ){ return false; } else { // check min version if ( $min_version > 0 ){ $local_version = $installed_info['version']; if ( version_compare( $local_version, $min_version, '>=' ) ) { // meets minimum version return true; } } else { // no min version check, but does seem to be installed return true; } } // +- check extraction endpoint (e.g. are files actually there?) return false; // package doesn't exist or isn't installed } /* * Checks to see if a package is available locally, if it isn't, installs it where possible * * @param string $package_key - a slug for a particular package * @param float $min_version - if > 0, installed version is compared and returns true only if min version met * */ public function ensure_package_is_installed( $package_key = '', $min_version = 0 ){ if ( !$this->package_is_installed( $package_key, $min_version ) ){ // not installed, try to install/update(reinstall) it return $this->retrieve_and_install_package( $package_key, true ); } // include composer autoload if it exists $potential_composer_autoload_path = $this->package_dir . '/' . $package_key . '/vendor/autoload.php'; if ( file_exists( $potential_composer_autoload_path ) ) { require_once $potential_composer_autoload_path; } return true; } /* * Retrieves a package zip from our CDN and installs it locally */ public function retrieve_and_install_package( $package_key = '', $force_reinstall = false){ global $zbs; // package exists? if ( !$this->package_is_available( $package_key) ){ return false; } // package already installed? if ( $this->package_is_installed( $package_key ) && !$force_reinstall ){ return true; } // failed already 3 times? if ( $this->get_fail_counter( $package_key ) >= 3 ){ // Add error msg zeroBSCRM_notifyme_insert_notification( get_current_user_id(), -999, -1, 'package.installer.fail_count_over', $package_key ); return false; } // here we set a failsafe which sets an option value such that if this install does not complete // ... we'll know the package install failed (e.g. page timeout shorter than download/unzip time) // ... that way we can avoid retrying 50000 times. $this->increment_fail_counter( $package_key ); // Retrieve & install the package $package_info = $this->get_package_info( $package_key ); $installed = false; // Directories $working_dir = $this->package_dir; if ( !file_exists( $working_dir ) ){ wp_mkdir_p( $working_dir ); jpcrm_create_and_secure_dir_from_external_access( $working_dir, true ); } $target_dir = $package_info['target_dir']; if ( !file_exists( $target_dir ) ) { wp_mkdir_p( $target_dir ); jpcrm_create_and_secure_dir_from_external_access( $target_dir, true ); } // did that work? if ( !file_exists( $target_dir ) || !file_exists( $working_dir ) ) { // error creating directories // Add admin notification zeroBSCRM_notifyme_insert_notification( get_current_user_id(), -999, -1, 'package.installer.dir_create_error', $package_info['title'] . ' (' . $package_key . ')' ); // return error return false; } // Filenames $source_file_name = $package_key . '.zip'; // Attempt to download and install if ( file_exists( $target_dir ) && file_exists( $working_dir ) ){ // if force reinstall, clear out previous directory contents if ( $this->package_is_installed( $package_key ) && $force_reinstall ){ // empty it out! jpcrm_delete_files_from_directory( $target_dir ); } // Retrieve package $libs = zeroBSCRM_retrieveFile( $zbs->urls['extdlpackages'] . $source_file_name, $working_dir . $source_file_name, array( 'timeout' => 30 ) ); // Process package if ( file_exists( $working_dir . $source_file_name ) ){ switch ( $package_info['install_method'] ){ // expand a zipped package case 'unzip': // Expand $expanded = zeroBSCRM_expandArchive( $working_dir . $source_file_name, $target_dir ); if ( $expanded ){ // Check success? if ( !zeroBSCRM_is_dir_empty( $target_dir ) ){ // appears to have worked, tidy up: if ( file_exists( $working_dir . $source_file_name ) ){ unlink( $working_dir . $source_file_name ); } $installed = true; } else { // Add admin notification zeroBSCRM_notifyme_insert_notification( get_current_user_id(), -999, -1, 'package.installer.unzip_error', $package_info['title'] . ' (' . $package_key . ')' ); return false; } } else { // failed to open the .zip, remove it if ( file_exists( $working_dir . $source_file_name ) ){ unlink( $working_dir . $source_file_name ); } // Add admin notification zeroBSCRM_notifyme_insert_notification( get_current_user_id(), -999, -1, 'package.installer.unzip_error', $package_info['title'] . ' (' . $package_key . ')' ); return false; } break; // 1 file package installs, copy to target location default: // TBD, add when we need this. break; } // if successfully installed, do any follow-on tasks if ( $installed ){ // Success. Reset fail counter $this->clear_fail_counter( $package_key ); // if the $package_info has ['post_install_call'] set, call that if ( isset( $package_info['post_install_call'] ) && function_exists( $package_info['post_install_call'] ) ){ call_user_func( $package_info['post_install_call'], $package_info ); } return true; } } else { // Add error msg zeroBSCRM_notifyme_insert_notification( get_current_user_id(), -999, -1, 'package.installer.dl_error', $package_info['title'] . ' (' . $package_key . ')' ); } } else { // Add error msg zeroBSCRM_notifyme_insert_notification( get_current_user_id(), -999, -1, 'package.installer.dir_create_error', $package_info['title'] . ' (' . $package_key . ')' ); } return false; } /* * Gets a package fail counter option value */ private function get_fail_counter( $package_key = ''){ return (int)get_option( 'jpcrm_package_fail_' . $package_key, 0 ); } /* * Adds a tick to a package fail counter option ( to track failed installs ) */ private function increment_fail_counter( $package_key = ''){ // here we set a failsafe which sets an option value such that if this install does not complete // ... we'll know the package install failed (e.g. page timeout shorter than download/unzip time) // ... that way we can avoid retrying 50000 times. $existing_fails = $this->get_fail_counter( $package_key ); update_option( 'jpcrm_package_fail_' . $package_key, $existing_fails + 1, false ); } /* * Resets fail counter for a package */ private function clear_fail_counter( $package_key = ''){ // simple. delete_option( 'jpcrm_package_fail_' . $package_key ); } }
projects/plugins/crm/includes/wh.currency.lib.php
<?php /*! * Woody Hayday Currency Lib * V1.0 * * Copyright 2020 Automattic * * Date: 18/09/15 */ global $whwpCurrencyList; $whwpCurrencyList = array( array('د.إ','AED'), array('؋','AFN'), array('L','ALL'), array('ƒ','ANG'), array('Kz','AOA'), array('$','ARS'), array('$','AUD'), array('ƒ','AWG'), array('KM','BAM'), array('$','BBD'), array('৳','BDT'), array('лв','BGN'), array('.د.ب','BHD'), array('Fr','BIF'), array('$','BMD'), array('$','BND'), array('Bs.','BOB'), array('R$','BRL'), array('$','BSD'), array('Nu.','BTN'), array('P','BWP'), array('Br','BYR'), array('$','BZD'), array('$','CAD'), array('Fr','CDF'), array('Fr','CHF'), array('$','CLP'), array('¥','CNY'), array('$','COP'), array('₡','CRC'), array('$','CUC'), array('$','CUP'), array('$','CVE'), array('Kč','CZK'), array('Fr','DJF'), array('kr','DKK'), array('$','DOP'), array('د.ج','DZD'), array('ج.م','EGP'), array('Nfk','ERN'), array('Br','ETB'), array('€','EUR'), array('$','FJD'), array('£','FKP'), array('£','GBP'), array('ლ','GEL'), array('£','GGP[C]'), array('₵','GHS'), array('£','GIP'), array('D','GMD'), array('Fr','GNF'), array('Q','GTQ'), array('$','GYD'), array('$','HKD'), array('L','HNL'), array('kn','HRK'), array('G','HTG'), array('Ft','HUF'), array('Rp','IDR'), array('₪','ILS'), array('£','IMP[C]'), array('₹','INR'), array('ع.د','IQD'), array('﷼','IRR'), array('kr','ISK'), array('£','JEP[C]'), array('$','JMD'), array('د.ا','JOD'), array('¥','JPY'), array('Sh','KES'), array('лв','KGS'), array('៛','KHR'), array('Fr','KMF'), array('₩','KPW'), array('₩','KRW'), array('د.ك','KWD'), array('$','KYD'), array('₭','LAK'), array('ل.ل','LBP'), array('Rs','LKR'), array('$','LRD'), array('L','LSL'), array('ل.د','LYD'), array('د. م.','MAD'), array('د.م.','MAD'), array('L','MDL'), array('Ar','MGA'), array('ден','MKD'), array('Ks','MMK'), array('₮','MNT'), array('P','MOP'), array('UM','MRO'), array('₨','MUR'), array('MK','MWK'), array('$','MXN'), array('RM','MYR'), array('MT','MZN'), array('$','NAD'), array('₦','NGN'), array('C$','NIO'), array('kr','NOK'), array('₨','NPR'), array('$','NZD'), array('ر.ع.','OMR'), array('B/.','PAB'), array('S/.','PEN'), array('K','PGK'), array('₱','PHP'), array('₨','PKR'), array('zł','PLN'), array('р.','PRB[C]'), array('₲','PYG'), array('ر.ق','QAR'), array('lei','RON'), array('дин','RSD'), array('₽','RUB'), array('Fr','RWF'), array('ر.س','SAR'), array('$','SBD'), array('₨','SCR'), array('£','SDG'), array('kr','SEK'), array('$','SGD'), array('£','SHP'), array('Le','SLL'), array('Sh','SOS'), array('$','SRD'), array('£','SSP'), array('Db','STD'), array('ل.س','SYP'), array('L','SZL'), array('฿','THB'), array('ЅМ','TJS'), array('m','TMT'), array('د.ت','TND'), array('T$','TOP'), array('₺', 'TRL'), array('$','TTD'), array('$','TWD'), array('Sh','TZS'), array('₴','UAH'), array('Sh','UGX'), array('$','USD'), array('$','UYU'), array('лв','UZS'), array('Bs F','VEF'), array('₫','VND'), array('Vt','VUV'), array('T','WST'), array('Fr','XAF'), array('$','XCD'), array('Fr','XOF'), array('₣','XPF'), array('﷼','YER'), array('R','ZAR'), array('ZK','ZMW') );
projects/plugins/crm/includes/ZeroBSCRM.DAL3.Obj.EventReminders.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V3.0+ * * Copyright 2020 Automattic * * Date: 14/01/19 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /** * ZBS DAL >> Event Reminders (for events/tasks) * * @author Woody Hayday <hello@jetpackcrm.com> * @version 2.0 * @access public * @see https://jetpackcrm.com/kb */ class zbsDAL_eventreminders extends zbsDAL_ObjectLayer { protected $objectType = ZBS_TYPE_TASK_REMINDER; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.PropertyNotSnakeCase, Squiz.Commenting.VariableComment.Missing protected $objectDBPrefix = 'zbser_'; protected $objectModel = array( // ID 'ID' => array('fieldname' => 'ID', 'format' => 'int'), // site + team generics 'zbs_site' => array('fieldname' => 'zbs_site', 'format' => 'int'), 'zbs_team' => array('fieldname' => 'zbs_team', 'format' => 'int'), 'zbs_owner' => array('fieldname' => 'zbs_owner', 'format' => 'int'), // other fields 'event' => array('fieldname' => 'zbser_event', 'format' => 'int'), 'remind_at' => array('fieldname' => 'zbser_remind_at', 'format' => 'int'), 'sent' => array('fieldname' => 'zbser_sent', 'format' => 'int'), 'created' => array('fieldname' => 'zbser_created', 'format' => 'uts'), 'lastupdated' => array('fieldname' => 'zbser_lastupdated', 'format' => 'uts') ); function __construct($args=array()) { #} =========== LOAD ARGS ============== $defaultArgs = array( //'tag' => false, ); foreach ($defaultArgs as $argK => $argV){ $this->$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $this->$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$this->$argK = $newData;} else { $this->$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= } // ==================================================================================== // =========== EVENTREMINDER ======================================================= // generic get Company (by ID) // Super simplistic wrapper used by edit page etc. (generically called via dal->contacts->getSingle etc.) public function getSingle($ID=-1){ return $this->getEventreminder($ID); } // generic get (by ID list) // Super simplistic wrapper used by MVP Export v3.0 public function getIDList($IDs=false){ return $this->getEventReminders(array( 'inArr' => $IDs, 'page' => -1, 'perPage' => -1 )); } /** * returns full eventreminder line +- details * * @param int id contact id * @param array $args Associative array of arguments * * @return array eventreminder object */ public function getEventreminder($id=-1,$args=array()){ global $zbs; #} =========== LOAD ARGS ============== $defaultArgs = array( // permissions 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership( ZBS_TYPE_TASK_REMINDER ), // this'll let you not-check the owner of obj // returns scalar ID of line 'onlyID' => false, 'fields' => false // false = *, array = fieldnames ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} Check ID $id = (int)$id; if ( (!empty($id) && $id > 0) || (!empty($email)) || (!empty($externalSource) && !empty($externalSourceUID)) ){ global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); $extraSelect = ''; #} ============= PRE-QUERY ============ $selector = 'eventreminder.*'; if (isset($fields) && is_array($fields)) { $selector = ''; // always needs id, so add if not present if (!in_array('ID',$fields)) $selector = 'eventreminder.ID'; foreach ($fields as $f) { if (!empty($selector)) $selector .= ','; $selector .= 'eventreminder.'.$f; } } else if ($onlyID){ $selector = 'eventreminder.ID'; } #} ============ / PRE-QUERY =========== #} Build query $query = "SELECT ".$selector.$extraSelect." FROM ".$ZBSCRM_t['eventreminders'].' as eventreminder'; #} ============= WHERE ================ if (!empty($id) && $id > 0){ #} Add ID $wheres['ID'] = array('ID','=','%d',$id); } #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort('ID','DESC') . $this->buildPaging(0,1); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_row($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret Results (ROW) if (isset($potentialRes) && isset($potentialRes->ID)) { #} Has results, tidy + return #} Only ID? return it directly if ($onlyID) return $potentialRes->ID; // tidy if (is_array($fields)){ // guesses fields based on table col names $res = $this->lazyTidyGeneric($potentialRes); } else { // proper tidy $res = $this->tidy_eventreminder($potentialRes); } return $res; } } // / if ID return false; } /** * returns eventreminder detail lines * * @param array $args Associative array of arguments * * @return array of eventreminder lines */ public function getEventreminders($args=array()){ global $zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( // Search/Filtering (leave as false to ignore) 'eventID' => false, // due date 'dueBefore' => false, // uts (due before) 'dueAfter' => false, // uts (due after) // status 'sent' => 0, // (if set bool) (false = hasn't been sent, true = has been sent) // returns 'count' => false, 'withDueUTS' => false, // if true returns 'due' field (UTS due) 'sortByField' => 'ID', 'sortOrder' => 'ASC', 'page' => 0, // this is what page it is (gets * by for limit) 'perPage' => 100, 'whereCase' => 'AND', // DEFAULT = AND // permissions 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership( ZBS_TYPE_TASK_REMINDER ), // this'll let you not-check the owner of obj ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= global $ZBSCRM_t,$wpdb,$zbs; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); $joinQ = ''; $extraSelect = ''; #} ============= PRE-QUERY ============ #} Capitalise this $sortOrder = strtoupper($sortOrder); // If just count, turn off any extra gumpf if ($count) { $withDueUTS = false; } // include 'due' column if ($withDueUTS){ $extraSelect .= ',(eventreminder.zbser_remind_at + (SELECT zbse_start FROM '.$ZBSCRM_t['events'].' WHERE ID = eventreminder.zbser_event)) due'; } #} ============ / PRE-QUERY =========== #} Build query $query = "SELECT eventreminder.*".$extraSelect." FROM ".$ZBSCRM_t['eventreminders'].' as eventreminder'.$joinQ; #} Count override if ($count) $query = "SELECT COUNT(eventreminder.ID) FROM ".$ZBSCRM_t['eventreminders'].' as eventreminder'.$joinQ; #} ============= WHERE ================ #} associated event id if (!empty($eventID) && $eventID > 0){ // has id + type to match to (e.g. quote 123) // simpler than this, we're not using objid links: $wheres['associatedObjType'] = array('ID','IN','(SELECT zbsol_objid_from FROM '.$ZBSCRM_t['objlinks']." WHERE zbsol_objtype_from = ".ZBS_TYPE_LINEITEM." AND zbsol_objtype_to = ".ZBS_TYPE_TASK." AND zbsol_objid_to = %d)",$eventID); $wheres['zbser_event'] = array('zbser_event','=','%d',$eventID); } #} Any additionalWhereArr? if (isset($additionalWhereArr) && is_array($additionalWhereArr) && count($additionalWhereArr) > 0){ // add em onto wheres (note these will OVERRIDE if using a key used above) // Needs to be multi-dimensional $wheres = array_merge($wheres,$additionalWhereArr); $wheres = array_merge_recursive($wheres,$additionalWhereArr); } // dueBefore if (!empty($dueBefore) && $dueBefore > 0 && $dueBefore !== false){ // is (event reminder at (e.g. -86400) + event start time (uts)) before $dueBefore $wheres['direct'][] = array('(eventreminder.zbser_remind_at + (SELECT zbse_start FROM '.$ZBSCRM_t['events'].' WHERE ID = eventreminder.zbser_event) < %d)',array($dueBefore)); } // dueAfter if (!empty($dueAfter) && $dueAfter > 0 && $dueAfter !== false){ // is (event reminder at (e.g. -86400) + event start time (uts)) after $dueAfter $wheres['direct'][] = array('(eventreminder.zbser_remind_at + (SELECT zbse_start FROM '.$ZBSCRM_t['events'].' WHERE ID = eventreminder.zbser_event) > %d)',array($dueAfter)); } // sent (if set as bool) if ($sent === true){ // has been sent $wheres['zbser_sent'] = array('zbser_sent','=','1'); } elseif ($sent === false){ // has not been sent $wheres['zbser_sent'] = array('zbser_sent','=','-1'); } #} ============ / WHERE =============== #} CHECK this + reset to default if faulty if (!in_array($whereCase,array('AND','OR'))) $whereCase = 'AND'; #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params,$whereCase); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner,'contact'); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort($sortByField,$sortOrder) . $this->buildPaging($page,$perPage); try { #} Prep & run query $queryObj = $this->prepare($query,$params); #} Catch count + return if requested if ($count) return $wpdb->get_var($queryObj); #} else continue.. $potentialRes = $wpdb->get_results($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret results (Result Set - multi-row) if (isset($potentialRes) && is_array($potentialRes) && count($potentialRes) > 0) { #} Has results, tidy + return foreach ($potentialRes as $resDataLine) { // tidy $resArr = $this->tidy_eventreminder($resDataLine); $res[] = $resArr; } } return $res; } /** * Returns a count of event reminders (owned) * .. inc by status * * @return int count */ public function getEventReminderCount($args=array()){ #} ============ LOAD ARGS ============= $defaultArgs = array( // Search/Filtering (leave as false to ignore) // permissions 'ignoreowner' => true, // this'll let you not-check the owner of obj ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= $whereArr = array(); return $this->DAL()->getFieldByWHERE(array( 'objtype' => ZBS_TYPE_TASK_REMINDER, 'colname' => 'COUNT(ID)', 'where' => $whereArr, 'ignoreowner' => $ignoreowner )); } /** * adds or updates a eventreminder object * * @param array $args Associative array of arguments * id (if update), owner, data (array of field data) * * @return int line ID */ public function addUpdateEventreminder($args=array()){ global $ZBSCRM_t,$wpdb,$zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'owner' => -1, // fields (directly) 'data' => array( 'event' => -1, 'remind_at' => '', 'sent' => '', 'lastupdated' => '', // allow this to be set for MS sync etc. 'created' => -1, ), 'limitedFields' => -1, // if this is set it OVERRIDES data (allowing you to set specific fields + leave rest in tact) // ^^ will look like: array(array('key'=>x,'val'=>y,'type'=>'%s')) 'silentInsert' => false, // this was for init Migration - it KILLS all IA for newEventreminder (because is migrating, not creating new :) this was -1 before 'do_not_update_blanks' => false // this allows you to not update fields if blank (same as fieldoverride for extsource -> in) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ $id = (int)$id; // here we check that the potential owner CAN even own if ($owner > 0 && !user_can($owner,'admin_zerobs_usr')) $owner = -1; // if owner = -1, add current if (!isset($owner) || $owner === -1) { $owner = zeroBSCRM_user(); } if (is_array($limitedFields)){ // LIMITED UPDATE (only a few fields.) if (!is_array($limitedFields) || count ($limitedFields) <= 0) return false; // REQ. ID too (can only update) if (empty($id) || $id <= 0) return false; } else { // NORMAL, FULL UPDATE } // if no eventID, return false $event = -1; if (isset($data['event'])) $event = (int)$data['event']; if ($event <= 0 && !$limitedFields) return false; #} If no status, and default is specified in settings, add that in :) /* if (is_null($data['status']) || !isset($data['status']) || empty($data['status'])){ // Default status for obj? -> this one gets for contacts -> $zbsCustomerMeta['status'] = zeroBSCRM_getSetting('defaultstatus'); } */ #} ========= / CHECK FIELDS =========== #} ========= OVERRIDE SETTING (Deny blank overrides) =========== // either ext source + setting, or set by the func call if ($do_not_update_blanks){ // this setting says 'don't override filled-out data with blanks' // so here we check through any passed blanks + convert to limitedFields // only matters if $id is set (there is somt to update not add if (isset($id) && !empty($id) && $id > 0){ // get data to copy over (for now, this is required to remove 'fullname' etc.) $dbData = $this->db_ready_eventreminder($data); //unset($dbData['id']); // this is unset because we use $id, and is update, so not req. legacy issue //unset($dbData['created']); // this is unset because this uses an obj which has been 'updated' against original details, where created is output in the WRONG format :) $origData = $data; //$data = array(); $limitedData = array(); // array(array('key'=>'zbser_x','val'=>y,'type'=>'%s')) // cycle through + translate into limitedFields (removing any blanks, or arrays (e.g. externalSources)) // we also have to remake a 'faux' data (removing blanks for tags etc.) for the post-update updates foreach ($dbData as $k => $v){ $intV = (int)$v; // only add if valuenot empty if (!is_array($v) && !empty($v) && $v != '' && $v !== 0 && $v !== -1 && $intV !== -1){ // add to update arr $limitedData[] = array( 'key' => 'zbser_'.$k, // we have to add zbser_ here because translating from data -> limited fields 'val' => $v, 'type' => $this->getTypeStr('zbser_'.$k) ); // add to remade $data for post-update updates $data[$k] = $v; } } // copy over $limitedFields = $limitedData; } // / if ID } // / if do_not_update_blanks #} ========= / OVERRIDE SETTING (Deny blank overrides) =========== #} ========= BUILD DATA =========== $update = false; $dataArr = array(); $typeArr = array(); if (is_array($limitedFields)){ // LIMITED FIELDS $update = true; // cycle through foreach ($limitedFields as $field){ // some weird case where getting empties, so added check if (!empty($field['key'])){ $dataArr[$field['key']] = $field['val']; $typeArr[] = $field['type']; } } // add update time if (!isset($dataArr['zbser_lastupdated'])){ $dataArr['zbser_lastupdated'] = time(); $typeArr[] = '%d'; } } else { // FULL UPDATE/INSERT // UPDATE $dataArr = array( // ownership // no need to update these (as of yet) - can't move teams etc. //'zbs_site' => zeroBSCRM_installSite(), //'zbs_team' => zeroBSCRM_installTeam(), //'zbs_owner' => $owner, 'zbser_event' => $data['event'], 'zbser_remind_at' => $data['remind_at'], 'zbser_sent' => $data['sent'], 'zbser_lastupdated' => time(), ); $typeArr = array( // field data types //'%d', // site //'%d', // team //'%d', // owner '%d', '%d', '%d', '%d', ); if (!empty($id) && $id > 0){ // is update $update = true; } else { // INSERT (get's few extra :D) $update = false; $dataArr['zbs_site'] = zeroBSCRM_site(); $typeArr[] = '%d'; $dataArr['zbs_team'] = zeroBSCRM_team(); $typeArr[] = '%d'; $dataArr['zbs_owner'] = $owner; $typeArr[] = '%d'; if (isset($data['created']) && !empty($data['created']) && $data['created'] !== -1){ $dataArr['zbser_created'] = $data['created'];$typeArr[] = '%d'; } else { $dataArr['zbser_created'] = time(); $typeArr[] = '%d'; } } } #} ========= / BUILD DATA =========== #} ============================================================ #} ========= CHECK force_uniques & not_empty & max_len ======== // if we're passing limitedFields we skip these, for now // #v3.1 - would make sense to unique/nonempty check just the limited fields. #gh-145 if (!is_array($limitedFields)){ // verify uniques if (!$this->verifyUniqueValues($data,$id)) return false; // / fails unique field verify // verify not_empty if (!$this->verifyNonEmptyValues($data)) return false; // / fails empty field verify } // whatever we do we check for max_len breaches and abbreviate to avoid wpdb rejections $dataArr = $this->wpdbChecks($dataArr); #} ========= / CHECK force_uniques & not_empty ================ #} ============================================================ #} Check if ID present if ($update){ #} Attempt update if ($wpdb->update( $ZBSCRM_t['eventreminders'], $dataArr, array( // where 'ID' => $id ), $typeArr, array( // where data types '%d' )) !== false){ // if passing limitedFields instead of data, we ignore the following // this doesn't work, because data is in args default as arr //if (isset($data) && is_array($data)){ // so... if (!isset($limitedFields) || !is_array($limitedFields) || $limitedFields == -1){ } // / if $data #} Any extra meta keyval pairs? // BRUTALLY updates (no checking) $confirmedExtraMeta = false; if (isset($extraMeta) && is_array($extraMeta)) { $confirmedExtraMeta = array(); foreach ($extraMeta as $k => $v){ #} This won't fix stupid keys, just catch basic fails... $cleanKey = strtolower(str_replace(' ','_',$k)); #} Brutal update //update_post_meta($postID, 'zbs_customer_extra_'.$cleanKey, $v); $this->DAL()->updateMeta( ZBS_TYPE_TASK_REMINDER, $id,'extra_' . $cleanKey, $v ); #} Add it to this, which passes to IA $confirmedExtraMeta[$cleanKey] = $v; } } // Successfully updated - Return id return $id; } else { $msg = __('DB Update Failed','zero-bs-crm'); $zbs->DAL->addError(302,$this->objectType,$msg,$dataArr); // FAILED update return false; } } else { #} No ID - must be an INSERT if ($wpdb->insert( $ZBSCRM_t['eventreminders'], $dataArr, $typeArr ) > 0){ #} Successfully inserted, lets return new ID $newID = $wpdb->insert_id; return $newID; } else { $msg = __('DB Insert Failed','zero-bs-crm'); $zbs->DAL->addError(303,$this->objectType,$msg,$dataArr); #} Failed to Insert return false; } } return false; } /** * updates sent status for an event reminder * * @param int id Event Reminder ID * @param int Sent Status (-1 = unsent, 1 = sent) * * @return bool */ public function setSentStatus($id=-1,$status=-1){ global $zbs; $id = (int)$id; if ($id > 0 && in_array($status, array(-1,1))){ return $this->addUpdateEventreminder(array( 'id'=>$id, 'limitedFields'=>array( array('key'=>'zbser_sent','val' => $status,'type' => '%d') ))); } return false; } /** * deletes a eventreminder object * * @param array $args Associative array of arguments * id * * @return int success; */ public function deleteEventreminder($args=array()){ global $ZBSCRM_t,$wpdb,$zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'saveOrphans' => true ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} Check ID & Delete :) $id = (int)$id; if (!empty($id) && $id > 0) { // delete orphans? if ($saveOrphans === false){ } return zeroBSCRM_db2_deleteGeneric($id,'eventreminders'); } return false; } /** * deletes all eventreminder objects assigned to event * * @param array $args Associative array of arguments * id * * @return int success; */ public function deleteEventRemindersForEvent($args=array()){ global $ZBSCRM_t,$wpdb,$zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( 'eventID' => -1 ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} Check ID & Delete :) $eventID = (int)$eventID; if (!empty($eventID) && $eventID > 0) { $reminders = $this->getEventreminders(array('eventID'=>$eventID,'perPage'=>1000,'ignoreowner'=>true)); $delcount = 0; if (is_array($reminders)) foreach ($reminders as $r){ $delcount += $this->deleteEventreminder(array('id'=>$r['id'])); } return $delcount; } return false; } /** * tidy's the object from wp db into clean array * * @param array $obj (DB obj) * * @return array eventreminder (clean obj) */ private function tidy_eventreminder($obj=false,$withCustomFields=false){ $res = false; if (isset($obj->ID)){ $res = array(); $res['id'] = $obj->ID; /* `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, */ $res['owner'] = $obj->zbs_owner; $res['event'] = (int)$obj->zbser_event; $res['remind_at'] = (int)$obj->zbser_remind_at; $res['sent'] = (int)$obj->zbser_sent; $res['created'] = (int)$obj->zbser_created; $res['created_date'] = (isset($obj->zbser_created) && $obj->zbser_created > 0) ? zeroBSCRM_locale_utsToDatetime($obj->zbser_created) : false; $res['lastupdated'] = (int)$obj->zbser_lastupdated; $res['lastupdated_date'] = (isset($obj->zbser_lastupdated) && $obj->zbser_lastupdated > 0) ? zeroBSCRM_locale_utsToDatetime($obj->zbser_lastupdated) : false; // if set: due if (isset($obj->due)) $res['due'] = (int)$obj->due; } return $res; } /** * remove any non-db fields from the object * basically takes array like array('owner'=>1,'fname'=>'x','fullname'=>'x') * and returns array like array('owner'=>1,'fname'=>'x') * This does so based on the objectModel! * * @param array $obj (clean obj) * * @return array (db ready arr) */ private function db_ready_eventreminder($obj=false){ // use the generic? (override here if necessary) return $this->db_ready_obj($obj); } // =========== / EVENTREMINDER ======================================================= // =============================================================================== } // / class
projects/plugins/crm/includes/class-crm-modules.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * Modules wrapper * */ namespace Automattic\JetpackCRM; // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; // Prevent PHP 8.2 deprecation notices, as we currently add each module as a dynamic property #[\AllowDynamicProperties] class CRM_Modules { /** * Setup Modules */ public function __construct() { // register modules $this->register_modules(); } /* * Autoloads the modules (core extensions) included with core * * Modularisation of this manner may allow easier drop-in integrations by third-party devs as well. */ public function register_modules(){ $module_directories = jpcrm_get_directories( JPCRM_MODULES_PATH ); if ( is_array( $module_directories ) ){ foreach ( $module_directories as $directory ){ // load module $this->register_module( $directory ); } } } /* * Registers a specific module * (Ultimately loads the `jpcrm-{$directory}-init.php` file) * * @param string $module_slug */ public function register_module( $module_slug ){ // where `jpcrm-{$directory}-init.php` present, include if ( file_exists( JPCRM_MODULES_PATH . "{$module_slug}/jpcrm-{$module_slug}-init.php" ) ){ require_once( JPCRM_MODULES_PATH . "{$module_slug}/jpcrm-{$module_slug}-init.php" ); } } /* * Load module * Loads a modules class into $zbs->modules->* */ public function load_module( $module_slug, $module_class ) { if ( isset( $this->$module_slug ) ) { return $this->$module_slug; } // double backslash due to the $ $class_name = "Automattic\JetpackCRM\\$module_class"; $this->$module_slug = new $class_name; return $this->$module_slug; } /** * Activate a new module (if needed) and redirect to its 'hub' slug */ public function activate_module_and_redirect() { global $zbs; global $zeroBSCRM_extensionsCompleteList; // Bail if activating from network, or bulk. if ( wp_doing_ajax() || is_network_admin() || ! wp_verify_nonce( $_GET['_wpnonce'], 'jpcrmmoduleactivateredirectnonce' ) || ! current_user_can( 'admin_zerobs_manage_options' ) || ! isset( $_GET['jpcrm-module-name'] ) || ! array_key_exists( $_GET['jpcrm-module-name'], $zeroBSCRM_extensionsCompleteList ) ) { return; } $module_name = sanitize_text_field( $_GET['jpcrm-module-name'] ); $safe_module_name = $this->get_safe_module_string( $module_name ); $safe_function_string = $this->get_safe_function_string( $module_name ); // if module is not installed, try to install it if ( ! zeroBSCRM_isExtensionInstalled( $module_name ) && function_exists( 'zeroBSCRM_extension_install_' . $safe_function_string ) ) { call_user_func( 'zeroBSCRM_extension_install_' . $safe_function_string ); call_user_func( 'jpcrm_load_' . $safe_function_string ); } if ( ! empty( $zbs->modules->$safe_module_name ) ) { // default to CRM dashboard $redirect_to = jpcrm_esc_link( $zbs->slugs['dash'] ); //if redirect_to is specified, use that if ( isset( $_GET['redirect_to'] ) ) { $redirect_to = sanitize_url( $_GET['redirect_to'] ); } // otherwise, if module has a hub slug use that else if ( isset( $zbs->modules->$safe_module_name->slugs['hub'] ) ) { $redirect_to = jpcrm_esc_link( $zbs->modules->$safe_module_name->slugs['hub'] ); } // redirect to URL wp_safe_redirect( $redirect_to ); exit; } else { printf( 'Module %s not found. Error #607', esc_html( $module_name ) ); } } /** These functions are used to avoid conflicts with old extension names (e.g. WooSync) * * For example: * * - the old Woo extension key is `woosync` * - the new Woo module extension key is `woo-sync` * - the install/load functions for the Woo module use `woo_sync` * - the new Woo module is loaded into `$zbs->modules->woosync` */ public function get_safe_module_string( $module_name ) { return str_replace( '-', '', $module_name ); } public function get_safe_function_string( $module_name ) { return str_replace( '-', '_', $module_name ); } }
projects/plugins/crm/includes/ZeroBSCRM.MetaBoxes3.Tags.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V3.0 * * Copyright 2020 Automattic * * Date: 20/02/2019 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== Create Tags Box ====================================================== */ class zeroBS__Metabox_Tags extends zeroBS__Metabox { public $objTypeID = false; // child fills out e.g. ZBS_TYPE_CONTACT public $showSuggestions = false; // show/hide tag suggestions public $saveAutomatically = false; // if this is true, this'll automatically update the object via addUpdateTags - this is off by default as most objects save tags themselves as part of addUpdateWhatever so that IA hooks fire correctly public $metaboxClasses = 'zbs-edit-tags-box-wrap'; // this allows us to globally apply styles in editview.css public function __construct( $plugin_file ) { // call this $this->initMetabox(); } public function html( $obj, $metabox ) { global $zbs; $objid = -1; if (is_array($obj) && isset($obj['id'])) $objid = $obj['id']; // if any already against obj, don't suggest em below $excludeIDs = false; // get tags ahead of time + only show if not empty :) $tags = $zbs->DAL->getTagsForObjID(array('objtypeid'=>$this->objTypeID,'objid'=>$objid)); // Debug echo 'Tags for '.$objid.'/'.$this->objTypeID.':<pre>'; print_r($tags); echo '</pre>'; // simplify :) $tagsArr = array(); if (is_array($tags) && count($tags) > 0) foreach ($tags as $t){ /* even simpler... $tag = array( 'id' => $t->term_id, 'name' => $t->name ); $tagsArr[] = $tag;*/ //$tagsArr[] = $t->name; $tagsArr[] = $t['name']; // exclude from suggestions: if (!is_array($excludeIDs)) $excludeIDs = array(); $excludeIDs[] = $t['id']; } $tags = $tagsArr; ?><div id="zbs-edit-tags"><?php if (zeroBSCRM_permsCustomers()){ // edit ?><div id="zbs-add-tags"> <div class="ui action left icon fluid input"> <i class="tags icon"></i> <input id="zbs-add-tag-value" type="text" placeholder="<?php esc_attr_e( 'Enter tags', 'zero-bs-crm' ); ?>"> <button id="zbs-add-tag-action" type="button" class="ui mini black button"> <?php esc_html_e('Add',"zero-bs-crm"); ?> </button> </div> </div> <input name="zbs-tag-list" id="zbs-tag-list" type="hidden" /><?php // final tags are passed via hidden inpt zbs-tag-list // look for zeroBSCRMJS_buildTagsInput in js :) JSONs it } echo '<div id="zbs-tags-wrap">'; $tagIndex = array(); ?> </div><!-- /.zbs-tags-wrap --> <?php if ($this->showSuggestions){ // Get top 20 tags, show top 5 + expand $tagSuggestions = $zbs->DAL->getTagsForObjType(array( 'objtypeid'=>$this->objTypeID, 'excludeEmpty'=>false, 'excludeIDs' => $excludeIDs, // if any already against obj, don't suggest em 'withCount'=>true, 'ignoreowner' => true, // sort 'sortByField' => 'tagcount', 'sortOrder' => 'DESC', // amount 'page' => 0, 'perPage' => 25 )); /* ( [id] =&gt; 4 [objtype] =&gt; 1 [name] =&gt; John [slug] =&gt; john [created] =&gt; 1527771665 [lastupdated] =&gt; 1527771999 [count] =&gt; 3 ) */ if (is_array($tagSuggestions) && count($tagSuggestions) > 0){ ?> <div id="zbs-tags-suggestions-wrap"> <div class="ui horizontal divider zbs-tags-suggestions-title"><?php esc_html_e('Suggested Tags','zero-bs-crm').':'; ?></div> <div id="zbs-tags-suggestions"> <?php $suggestionIndx = 0; foreach ($tagSuggestions as $tagSuggest){ if ($suggestionIndx == 5 && count($tagSuggestions) > 5){ ?><div class="ui horizontal divider" id="zbs-tag-suggestions-show-more"><i class="search plus icon"></i> <?php esc_html_e('Show More','zero-bs-crm'); ?></div> <div id="zbs-tag-suggestions-more-wrap"><?php } // brutal out ?> <div class="ui small basic black label zbsTagSuggestion" title="<?php esc_attr_e( 'Add Tag', 'zero-bs-crm' ); ?>"><?php echo esc_html( $tagSuggest['name'] ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?></div> <?php $suggestionIndx++; } if (count($tagSuggestions) > 5){ ?><div class="ui horizontal divider" id="zbs-tag-suggestions-show-less"><i class="search minus icon"></i> <?php esc_html_e('Show Less','zero-bs-crm'); ?></div></div><?php // close 'more'; } ?> </div> </div> <?php }} ?> </div> <script type="text/javascript"> var zbsCRMJS_currentTags = <?php echo json_encode($tags); ?>; </script> <?php } public function save_data( $objID, $obj ) { // Note: Most objects save tags as part of their own addUpdate routines. // so this now only fires where saveAutomatically = true if ($this->saveAutomatically){ // Save tags against objid // NEEDS AN OBJTYPE SWITCH HERE :) $potentialTags = zeroBSCRM_tags_retrieveFromPostBag(true,ZBS_TYPE_CONTACT); if (is_array($potentialTags)){ global $zbs; // new db :) /* Nope. this isn't objtype generic, so re-add later if used $zbs->DAL->addUpdateContactTags(array( 'id' => $objID, 'tags' => $tags, 'mode' => 'replace' ));*/ } // / if has tags arr } // / if saveAutomatically return $obj; } } /* ====================================================== / Create Tags Box ====================================================== */ // tag related function - retrieve tags from post function zeroBSCRM_tags_retrieveFromPostBag($returnAsIDs = true,$objectTypeID=-1){ // - NOTE THIS REQ: // final tags are passed via hidden inpt zbs-tag-list // look for zeroBSCRMJS_buildTagsInput in js :) JSONs it if (isset($_POST['zbs-tag-list']) && !empty($_POST['zbs-tag-list']) && $objectTypeID > 0){ global $zbs; // should be json // doesn't need decoding (wp done?) $potentialTags = json_decode(stripslashes($_POST['zbs-tag-list'])); // not sanitized at this point.. if (is_array($potentialTags)){ $tags = array(); foreach ($potentialTags as $tag){ $cleanTag = trim(sanitize_text_field( $tag )); if (!empty($cleanTag) && !in_array($cleanTag, $tags)) $tags[] = $cleanTag; } // / foreach tag if (!$returnAsIDs) return $tags; // returns as array(0=>'tag1') etc. else { $tagIDs = array(); // cycle through + find foreach ($tags as $tag){ $tagID = $zbs->DAL->getTag( -1, array( 'objtype' => $objectTypeID, 'name' => $tag, 'onlyID' => true, )); //echo 'looking for tag "'.$tag.'" got id '.$tagID.'!<br >'; if (!empty($tagID)) $tagIDs[] = $tagID; else { //create $tagID = $zbs->DAL->addUpdateTag( array( 'data' => array( 'objtype' => $objectTypeID, 'name' => $tag, ) ) ); //add if (!empty($tagID)) $tagIDs[] = $tagID; } } return $tagIDs; } } // / if is array } // / post return array(); }
projects/plugins/crm/includes/ZeroBSCRM.List.Tasks.php
<?php /* ! * Jetpack CRM * https://jetpackcrm.com * V1.1.19 * * Copyright 2020 Automattic * * Date: 18/10/16 */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) { exit; } function zeroBSCRM_render_tasks_calendar_page() { global $zbs; $option = 'per_page'; $args = array( 'label' => __( 'Tasks', 'zero-bs-crm' ), 'default' => 10, 'option' => 'events_per_page', ); add_screen_option( $option, $args ); $normalLoad = true; $fullCalendarView = 'month'; $current_task_user_id = false; if ( isset( $_GET['zbsowner'] ) && ! empty( $_GET['zbsowner'] ) ) { $current_task_user_id = (int) sanitize_text_field( $_GET['zbsowner'] ); } $jpcrm_tasks_users = zeroBS_getPossibleCustomerOwners(); $show_tasks_users = false; if ( count( $jpcrm_tasks_users ) > 0 && zeroBSCRM_isZBSAdminOrAdmin() ) { $show_tasks_users = true; } else { $taskOwnershipOn = zeroBSCRM_getSetting( 'taskownership' ); if ( $taskOwnershipOn == '1' ) { $current_task_user_id = get_current_user_id(); } } if ( isset( $_GET['zbs_crm_team'] ) ) { $current_task_user_id = get_current_user_id(); $fullCalendarView = 'listMonth'; } if ( $normalLoad ) { ?> <div> <div class="ui segment main-task-view"> <?php if ( $show_tasks_users ) { ?> <div style="clear:both;height: 0px;"></div><?php } ?> <?php // retrieve via DAL, just getting them ALL (pretty gross, but for now, at least more performant.) $args = array( 'sortByField' => 'ID', 'sortOrder' => 'DESC', 'page' => 0, 'perPage' => 50000, ); // belonging to specific user if ( ! empty( $current_task_user_id ) && $current_task_user_id > 0 ) { $args['ownedBy'] = $current_task_user_id; //$args['ignoreowner'] = false; } $tasks = $zbs->DAL->events->getEvents( $args ); // for now we cycle through and form into same object as MS wrote this for, // v3.0 + to rewrite display engine to use proper DAL objs on fly. if ( is_array( $tasks ) && count( $tasks ) > 0 ) { $avatar_args = array( 'size' => 24, ); $end_tasks = array(); foreach ( $tasks as $task ) { if ( isset( $task['start'] ) && $task['start'] > 0 && isset( $task['end'] ) && $task['end'] > 0 ) { $new_task = array( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase 'title' => zeroBSCRM_textExpose( $task['title'] ), 'start' => jpcrm_uts_to_datetime_str( $task['start'], 'Y-m-d H:i:s' ), 'end' => jpcrm_uts_to_datetime_str( $task['end'], 'Y-m-d H:i:s' ), 'url' => jpcrm_esc_link( 'edit', $task['id'], ZBS_TYPE_TASK ), 'owner' => $task['owner'], 'avatar' => '', // default 'showonCal' => 'hide', // default 'complete' => '-1', ); // avatar? if ( isset( $task['owner'] ) && $task['owner'] > 0 ) { $new_task['avatar'] = get_avatar_url( $task['owner'], $avatar_args ); } // show on cal if ( isset( $task['show_on_cal'] ) && $task['show_on_cal'] == 1 ) { $new_task['showonCal'] = 'show'; } // complete? if ( isset( $task['complete'] ) && $task['complete'] == 1 ) { $new_task['complete'] = 1; } // add it $end_tasks[] = $new_task; } } // pass it on and clean up $tasks = $end_tasks; unset( $end_tasks, $new_task ); } else { $tasks = array(); } // build json $task_json = json_encode( $tasks ); ?> <script> <?php /* debug var task_debug = <?php echo $task_json; ?>; console.log('tasks:',task_debug); */ ?> jQuery(function() { jQuery('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'year, month,agendaWeek, agendaDay,listMonth' }, defaultDate: '<?php echo esc_html( date( 'Y-m-d' ) ); ?>', defaultView: '<?php echo esc_html( $fullCalendarView ); ?>', navLinks: true, // can click day/week names to navigate views // editable: true, eventLimit: true, // allow "more" link when too many tasks weekends: true, disableDragging: true, events: <?php echo $task_json; ?>, firstDay: <?php echo (int) get_option( 'start_of_week', 0 ); ?> }); }); </script> <div id='calendar'></div> <br class="clear"> </div> </div> <script type="text/javascript"> jQuery(function(){ jQuery('#clearSearch').on( 'click', function(){ jQuery('#customersearch-search-input').val(''); jQuery('#search-submit').trigger( 'click' ); }); }); </script> <?php } }
projects/plugins/crm/includes/ZeroBSCRM.Forms.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V1.20 * * Copyright 2020 Automattic * * Date: 01/11/16 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== Front end Form Funcs ====================================================== */ // forms iframes, moved to templates as of 29/10/19 // include endpoint function zeroBSCRM_forms_includeEndpoint(){ // add our iframe endpoint add_rewrite_endpoint( 'crmforms', EP_ROOT ); // add action to catch on template redirect add_action( 'template_redirect', 'zeroBSCRM_forms_templateRedirect' ); } //add_action( 'init', 'zeroBSCRM_forms_includeEndpoint'); // catch template redirect if on forms function zeroBSCRM_forms_templateRedirect() { // hard typed form types $acceptableFormTypes = array('simple','naked','content'); $potentialForm = get_query_var('crmforms'); if (isset($potentialForm) && !empty($potentialForm) && in_array($potentialForm, $acceptableFormTypes)){ // require template require_once( ZEROBSCRM_PATH . 'public/forms/form-'.$potentialForm.'.php' ); exit(); } } // shortcode - e.g. [jetpackcrm_form id="26633" style="naked"] function zeroBSCRM_forms_shortcode($atts){ // retrieve attr extract( shortcode_atts( array( 'id' => 'true', 'style' => 'simple' ), $atts ) ); // force enquement zeroBSCRM_forms_enqueuements(); zeroBSCRM_exposePID(); // return the form html return zeroBSCRM_forms_build_form_html($atts['id'],$atts['style'],__('CRM Forms: You have not entered a style in your form shortcode','zero-bs-crm')); } add_shortcode('jetpackcrm_form','zeroBSCRM_forms_shortcode'); add_shortcode('zbs_form','zeroBSCRM_forms_shortcode'); function zeroBSCRM_forms_enqueuements(){ #} Assets we need specifically here // js wp_enqueue_script("jquery"); wp_enqueue_script('zbsfrontendformsjs'); // css wp_enqueue_style('zbsfrontendformscss'); } // Register Forms widget class ZBS_Form_Widget extends WP_Widget { /** * Register widget with WordPress. */ public function __construct() { parent::__construct( 'zbs_form_widget', // Base ID 'Jetpack CRM Forms', // Name array( 'description' => __( 'Embed a lead capture form to your website', 'zero-bs-crm' ), ) // Args ); } /** * Front-end display of widget. * * @see WP_Widget::widget() * * @param array $args Widget arguments. * @param array $instance Saved values from database. */ public function widget( $args, $instance ) { zeroBSCRM_forms_enqueuements(); extract( $args ); $title = apply_filters( 'widget_title', $instance['title'] ); $style = $instance['style']; $id = $instance['id']; echo $before_widget; if ( ! empty( $title ) ) { echo $before_title . $title . $after_title; } if ( ! empty( $style) && ! empty($id)) { echo zeroBSCRM_forms_build_form_html($id,$style,__('You have not entered a style or ID in the form shortcode','zero-bs-crm')); } echo $after_widget; } /** * Back-end widget form. * * @see WP_Widget::form() * * @param array $instance Previously saved values from database. */ public function form( $instance ) { if ( isset( $instance[ 'title' ] ) ) { $title = $instance[ 'title' ]; } else { $title = __( 'Contact us', 'zero-bs-crm' ); } if ( isset( $instance[ 'style' ] ) ) { $style = $instance[ 'style' ]; } else { $style = __( 'Simple', 'zero-bs-crm' ); } if ( isset( $instance[ 'id' ] ) ) { $id = $instance[ 'id' ]; } else { $id = 0; } ?> <p> <label for="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>"><?php esc_html_e( 'Title:', 'zero-bs-crm' ); ?></label> <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" /> </p> <p> <label for="<?php echo esc_attr( $this->get_field_id('text') ); ?>">Style: <select class='widefat' id="<?php echo esc_attr( $this->get_field_id('style') ); ?>" name="<?php echo esc_attr( $this->get_field_name('style') ); ?>" type="text"> <option value='naked'<?php echo ($style=='naked')?'selected':''; ?>> Naked </option> <option value='simple'<?php echo ($style=='simple')?'selected':''; ?>> Simple </option> <option value='content'<?php echo ($style=='content')?'selected':''; ?>> Content </option> </select> </label> </p> <p> <label for="<?php echo esc_attr( $this->get_field_name( 'id' ) ); ?>"><?php esc_html_e( 'Form ID:', 'zero-bs-crm' ); ?></label> <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'id' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'id' ) ); ?>" type="text" value="<?php echo esc_attr( $id ); ?>" /> </p> <?php } /** * Sanitize widget form values as they are saved. * * @see WP_Widget::update() * * @param array $new_instance Values just sent to be saved. * @param array $old_instance Previously saved values from database. * * @return array Updated safe values to be saved. */ public function update( $new_instance, $old_instance ) { $instance = array(); $instance['title'] = ( !empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : ''; $instance['style'] = ( !empty( $new_instance['style'] ) ) ? strip_tags( $new_instance['style'] ) : ''; $instance['id'] = ( !empty( $new_instance['id'] ) ) ? strip_tags( $new_instance['id'] ) : ''; return $instance; } } add_action( 'widgets_init', function() { register_widget( 'ZBS_Form_Widget' ); } ); // header func - anything here will get added to front-end header for form // (Recaptcha) function zeroBSCRM_forms_formHTMLHeader(){ $reCaptcha = zeroBSCRM_getSetting('usegcaptcha'); $reCaptchaKey = zeroBSCRM_getSetting('gcaptchasitekey'); $reCaptchaSecret = zeroBSCRM_getSetting('gcaptchasitesecret'); if ($reCaptcha && !empty($reCaptchaKey) && !empty($reCaptchaSecret)){ #} if reCaptcha include (not available in wp_enqueue_script as at 30/10/19 - https://developer.wordpress.org/reference/functions/wp_enqueue_script/) echo "<script src='https://www.google.com/recaptcha/api.js'></script>"; #} And set this global var for easy check in js echo '<script type="text/javascript">var zbscrmReCaptcha = true;</script>'; } } add_action('wp_head', 'zeroBSCRM_forms_formHTMLHeader'); // return html of form function zeroBSCRM_forms_build_form_html($formID=-1, $formStyle='content', $fallbackMessage=''){ // check form ID & style if ($formID > 0 && in_array($formStyle,array('naked','content','simple','cgrab'))){ // 'cgrab' was original 'content' if ($formStyle === 'cgrab') $formStyle = 'content'; // retrieve Form $form = zeroBS_getForm($formID); #} This checks it found something if (is_array($form)){ return call_user_func( 'jpcrm_' . $formStyle . '_form_html', $formID, $form ); } } return $fallbackMessage; } // return HTML for ReCaptcha (if using) function zeroBSCRM_forms_getRecaptcha(){ #} reCaptcha addition $reCaptcha = zeroBSCRM_getSetting('usegcaptcha'); $reCaptchaKey = zeroBSCRM_getSetting('gcaptchasitekey'); if ($reCaptcha && !empty($reCaptchaKey)) return '<div class="zbscrmReCaptcha"><div class="g-recaptcha" data-sitekey="'.$reCaptchaKey.'"></div></div>'; return ''; } // v3 form HTML builder (simple style) function jpcrm_simple_form_html( $formid = -1, $formObject = array() ) { // build $content ob_start(); ?> <div class="zbscrmFrontEndForm" id="zbs_form_<?php echo esc_attr( $formid ); ?>"> <div id="zbs_form_ajax_action" data-zbsformajax="<?php echo esc_url( admin_url('admin-ajax.php') ); ?>"></div> <div class="embed"> <div class="simple" style="border:0px !important"> <div class="content"> <h1><?php echo !empty($formObject['label_header']) ? esc_html( $formObject['label_header'] ) : esc_html__("Want to find out more?",'zero-bs-crm'); ?></h1> <h3><?php echo !empty($formObject['label_subheader']) ? esc_html( $formObject['label_subheader'] ) : esc_html__("Drop us a line. We follow up on all contacts",'zero-bs-crm'); ?></h3> <div class="form-wrapper zbsFormWrap"> <input class="input" type="text" id="zbs_email" name="zbs_email" placeholder="<?php echo !empty($formObject['label_email']) ? esc_attr( $formObject['label_email'] ) : esc_attr__("Email Address",'zero-bs-crm'); ?>" value=""/> <input class="input" type="hidden" id="zbs_hpot_email" name="zbs_hpot_email" value=""/> <input class="input" type="hidden" class="zbs_form_view_id" id="zbs_form_view_id" name="zbs_form_id" value="<?php echo esc_attr( $formid ); ?>" /> <input class="input" type="hidden" id="zbs_form_style" name="zbs_form_style" value="zbs_simple" /> <input type="hidden" name="action" value="zbs_lead_form"> <?php echo zeroBSCRM_forms_getRecaptcha(); ?> <input class="send" type="submit" value="<?php echo !empty($formObject['label_button']) ? esc_attr( $formObject['label_button'] ) : esc_attr__("Submit",'zero-bs-crm'); ?>"/> <div class="clear"></div> <div class="trailer"><?php echo !empty($formObject['label_spammsg']) ? esc_html( $formObject['label_spammsg'] ) : esc_html__("We will not send you spam. Our team will be in touch within 24 to 48 hours Mon-Fri (but often much quicker)",'zero-bs-crm'); ?></div> </div> <div class="zbsForm_success"><?php echo !empty($formObject['label_successmsg']) ? esc_html( $formObject['label_successmsg'] ) : esc_html__("Thanks. We will be in touch.",'zero-bs-crm'); ?></div> <?php ##WLREMOVE global $zbs; $showpoweredby_public = $zbs->settings->get( 'showpoweredby_public' ) === 1 ? true : false; if( $showpoweredby_public ) { ?><div class="zbs_poweredby" style="font-size:11px;">Powered by <a href="<?php echo esc_url( $zbs->urls['home'] ); ?>" target="_blank">Jetpack CRM</a></div><?php } ##/WLREMOVE ?> </div> </div> </div> </div> <?php $content = ob_get_contents(); ob_end_clean(); return $content; } // v3 form HTML builder (naked style) function jpcrm_naked_form_html( $formid = -1, $formObject = array() ) { // build $content ob_start(); ?> <div class="zbscrmFrontEndForm" id="zbs_form_<?php echo esc_attr( $formid ); ?>"> <div id="zbs_form_ajax_action" data-zbsformajax="<?php echo esc_url( admin_url('admin-ajax.php') ); ?>"></div> <div class="embed"> <div class="naked" style="border:0px !important"> <div class="content"> <div class="form-wrapper zbsFormWrap"> <input class="input" type="text" id="zbs_fname" name="zbs_fname" placeholder="<?php echo !empty($formObject['label_firstname']) ? esc_attr( $formObject['label_firstname'] ) : esc_attr__("First Name",'zero-bs-crm'); ?>" value=""/> <input class="input" type="text" id="zbs_email" name="zbs_email" placeholder="<?php echo !empty($formObject['label_email']) ? esc_attr( $formObject['label_email'] ) : esc_attr__("Email Address",'zero-bs-crm'); ?>" value=""/> <input class="input" type="hidden" id="zbs_hpot_email" name="zbs_hpot_email" value=""/> <input class="input" type="hidden" class="zbs_form_view_id" id="zbs_form_view_id" name="zbs_form_id" value="<?php echo esc_attr( $formid ); ?>" /> <input class="input" type="hidden" id="zbs_form_style" name="zbs_form_style" value="zbs_naked" /> <input type="hidden" name="action" value="zbs_lead_form"> <?php echo zeroBSCRM_forms_getRecaptcha(); ?> <input class="send" type="submit" value="<?php echo !empty($formObject['label_button']) ? esc_attr( $formObject['label_button'] ) : esc_attr__("Submit",'zero-bs-crm'); ?>"/> <div class="clear"></div> <div class="trailer"><?php echo !empty($formObject['label_spammsg']) ? esc_html( $formObject['label_spammsg'] ) : esc_html__("We will not send you spam. Our team will be in touch within 24 to 48 hours Mon-Fri (but often much quicker)",'zero-bs-crm'); ?></div> </div> <div class="zbsForm_success"><?php echo !empty($formObject['label_successmsg']) ? esc_html( $formObject['label_successmsg'] ) : esc_html__("Thanks. We will be in touch.",'zero-bs-crm'); ?></div> <?php ##WLREMOVE global $zbs; $showpoweredby_public = $zbs->settings->get( 'showpoweredby_public' ) === 1 ? true : false; if( $showpoweredby_public ) { ?><div class="zbs_poweredby" style="font-size:11px;">Powered by <a href="<?php echo esc_url( $zbs->urls['home'] ); ?>" target="_blank">Jetpack CRM</a></div><?php } ##/WLREMOVE ?> </div> </div> </div> </div> <?php $content = ob_get_contents(); ob_end_clean(); return $content; } // v3 form HTML builder (content grab style) function jpcrm_content_form_html( $formid = -1, $formObject = array() ) { // build $content ob_start(); ?> <div class="zbscrmFrontEndForm" id="zbs_form_<?php echo esc_attr( $formid ); ?>"> <div id="zbs_form_ajax_action" data-zbsformajax="<?php echo esc_url( admin_url('admin-ajax.php') ); ?>"></div> <div class="embed"> <div class="cgrab" style="border:0px !important"> <div class="content"> <h1><?php echo !empty($formObject['label_header']) ? esc_html( $formObject['label_header'] ) : esc_html__("Want to find out more?",'zero-bs-crm'); ?></h1> <h3><?php echo !empty($formObject['label_subheader']) ? esc_html( $formObject['label_subheader'] ) : esc_html__("Drop us a line. We follow up on all contacts",'zero-bs-crm'); ?></h3> <div class="form-wrapper zbsFormWrap"> <input class="input" type="text" id="zbs_fname" name="zbs_fname" placeholder="<?php echo !empty($formObject['label_firstname']) ? esc_attr( $formObject['label_firstname'] ) : esc_attr__("First Name",'zero-bs-crm'); ?>" value=""/> <input class="input" type="text" id="zbs_lname" name="zbs_lname" placeholder="<?php echo !empty($formObject['label_lastname']) ? esc_attr( $formObject['label_lastname'] ) : esc_attr__("Last Name",'zero-bs-crm'); ?>" value=""/> <input class="input" type="text" id="zbs_email" name="zbs_email" placeholder="<?php echo !empty($formObject['label_email']) ? esc_attr( $formObject['label_email'] ) : esc_attr__("Email Address",'zero-bs-crm'); ?>" value=""/> <textarea class="textarea" id="zbs_notes" name="zbs_notes" placeholder="<?php echo !empty($formObject['label_message']) ? esc_attr( $formObject['label_message'] ) : esc_attr__("Your Message",'zero-bs-crm'); ?>"></textarea> <input class="input" type="hidden" id="zbs_hpot_email" name="zbs_hpot_email" value=""/> <input class="input" type="hidden" class="zbs_form_view_id" id="zbs_form_view_id" name="zbs_form_id" value="<?php echo esc_attr( $formid ); ?>" /> <input class="input" type="hidden" id="zbs_form_style" name="zbs_form_style" value="zbs_cgrab" /> <input type="hidden" name="action" value="zbs_lead_form"> <?php echo zeroBSCRM_forms_getRecaptcha(); ?> <input class="send" type="submit" value="<?php echo !empty($formObject['label_button']) ? esc_attr( $formObject['label_button'] ) : esc_attr__("Submit",'zero-bs-crm'); ?>"/> <div class="clear"></div> <div class="trailer"><?php echo !empty($formObject['label_spammsg']) ? esc_html( $formObject['label_spammsg'] ) : esc_html__("We will not send you spam. Our team will be in touch within 24 to 48 hours Mon-Fri (but often much quicker)",'zero-bs-crm'); ?></div> </div> <div class="zbsForm_success"><?php echo !empty($formObject['label_successmsg']) ? esc_html( $formObject['label_successmsg'] ) : esc_html__("Thanks. We will be in touch.",'zero-bs-crm'); ?></div> <?php ##WLREMOVE global $zbs; $showpoweredby_public = $zbs->settings->get( 'showpoweredby_public' ) === 1 ? true : false; if( $showpoweredby_public ) { ?><div class="zbs_poweredby" style="font-size:11px;">Powered by <a href="<?php echo esc_url( $zbs->urls['home'] ); ?>" target="_blank">Jetpack CRM</a></div><?php } ##/WLREMOVE ?> </div> </div> </div> </div> <?php $content = ob_get_contents(); ob_end_clean(); return $content; } // legacy - used elsewhere (extensions?) otherwise safe to remove function zeroBSCRM_exposePID() {} /* ====================================================== / Front end Form Funcs ====================================================== */
projects/plugins/crm/includes/ZeroBSCRM.DAL3.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V1.20 * * Copyright 2020 Automattic * * Date: 01/11/16 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* DAL3.0 Notes: THIS FILE replaces previous DAL2.php, with the following changes: - Originally this was DAL2 1 x class containting methods like: - DAL->getContacts - ... in DAL3 these have moved to: - DAL->contacts->getContacts() - ... for better organisation. - This file, then, basically shuffles original DAL2 out into 4 classes: - DAL, contacts, segments, logs - As DAL, DAL->contacts, DAL->segments, DAL->logs - ... it also adds splat/catcher funcs for OLD references e.g. getContacts, - ... so that they will still function (but log need for replacement) ... so it's a kind of chimera DAL2 to bridge the gap between DAL2 + DAL3. ... should be fine to cut the chimera splats after a while though (or even pre v3.0 proper) */ /* ====================================================== DB GENERIC/OBJ Helpers (not DAL GET etc.) ====================================================== */ // =============================================================================== // =========== PERMISSIONS HELPERS ============================================= // in time this'll allow multiple 'sites' per install (E.g. site 1 = epic.zbs.com site 2 = zbs.zbs.com) // for now, this is hard-coded to 1 // replaces "zeroBSCRM_installSite" from old DAL function zeroBSCRM_site(){ return 1; } // in time this'll allow multiple 'team' per site (E.g. branch1,branch2 etc.) // for now, this is hard-coded to 1 // replaces "zeroBSCRM_installTeam" from old DAL function zeroBSCRM_team(){ return 1; } // active user id - helper func // replaces "zeroBSCRM_currentUserID" from old DAL // can alternatively user $zbs->user() function zeroBSCRM_user(){ return get_current_user_id(); } // =========== / PERMISSIONS HELPERS =========================================== // =============================================================================== // =============================================================================== // =========== TYPES ============================================================ define( 'ZBS_TYPE_CONTACT', 1 ); define( 'ZBS_TYPE_COMPANY', 2 ); define( 'ZBS_TYPE_QUOTE', 3 ); define( 'ZBS_TYPE_INVOICE', 4 ); define( 'ZBS_TYPE_TRANSACTION', 5 ); define( 'ZBS_TYPE_EVENT', 6 ); // legacy, use ZBS_TYPE_TASK instead define( 'ZBS_TYPE_TASK', 6 ); define( 'ZBS_TYPE_FORM', 7 ); define( 'ZBS_TYPE_LOG', 8 ); define( 'ZBS_TYPE_SEGMENT', 9 ); define( 'ZBS_TYPE_LINEITEM', 10 ); define( 'ZBS_TYPE_EVENTREMINDER', 11 ); // legacy, use ZBS_TYPE_TASK_REMINDER instead define( 'ZBS_TYPE_TASK_REMINDER', 11 ); define( 'ZBS_TYPE_QUOTETEMPLATE', 12 ); define( 'ZBS_TYPE_ADDRESS', 13 ); // this is a precursor to v4 where we likely need to split out addresses from current in-object model (included here as custom fields now managed as if obj) // =========== / TYPES ========================================================= // =============================================================================== /* ====================================================== / DB GENERIC/OBJ Helpers (not DAL GET etc.) ====================================================== */ /** * zbsDAL is the Data Access Layer for ZBS v2.5+ * * zbsDAL provides expanded CRUD actions to the * Jetpack CRM generally, and will be initiated globally * like the WordPress $wpdb. * * @author Woody Hayday <hello@jetpackcrm.com> * @version 2.0 * @access public * @see https://jetpackcrm.com/kb */ class zbsDAL { public $version = 3.0; /* * A general key-value pair store */ private $cache = array(); // =============================================================================== // =========== SUB DAL LAYERS ================================================== // These hold sub-objects, e.g. contact public $contacts = false; public $segments = false; public $companies = false; public $quotes = false; public $invoices = false; public $transactions = false; public $forms = false; public $events = false; public $eventreminders = false; // phpcs:ignore Squiz.Commenting.VariableComment.Missing public $logs = false; public $lineitems = false; public $quotetemplates = false; public $addresses = false; // =========== / SUB DAL LAYERS ================================================ // =============================================================================== // =============================================================================== // =========== OBJECT TYPE & GLOBAL DEFINITIONS ============================== private $typesByID = array( ZBS_TYPE_CONTACT => 'contact', ZBS_TYPE_COMPANY => 'company', ZBS_TYPE_QUOTE => 'quote', ZBS_TYPE_INVOICE => 'invoice', ZBS_TYPE_TRANSACTION => 'transaction', ZBS_TYPE_TASK => 'event', ZBS_TYPE_FORM => 'form', ZBS_TYPE_SEGMENT => 'segment', ZBS_TYPE_LOG => 'log', ZBS_TYPE_LINEITEM => 'lineitem', ZBS_TYPE_TASK_REMINDER => 'eventreminder', ZBS_TYPE_QUOTETEMPLATE => 'quotetemplate', ZBS_TYPE_ADDRESS => 'address' ); // retrieve via DAL->oldCPT(1) private $typeCPT = array( ZBS_TYPE_CONTACT => 'zerobs_customer', ZBS_TYPE_COMPANY => 'zerobs_company', ZBS_TYPE_QUOTE => 'zerobs_quote', ZBS_TYPE_INVOICE => 'zerobs_invoice', ZBS_TYPE_TRANSACTION => 'zerobs_transaction', ZBS_TYPE_TASK => 'zerobs_event', ZBS_TYPE_FORM => 'zerobs_form', // these never existed: //ZBS_TYPE_SEGMENT => 'zerobs_segment', //ZBS_TYPE_LOG => 'zerobs_log', //ZBS_TYPE_LINEITEM => 'lineitem' //ZBS_TYPE_TASK_REMINDER => 'eventreminder' ZBS_TYPE_QUOTETEMPLATE => 'zerobs_quo_template', ); /** * Retrieve via DAL->typeStr(1). * * @var array */ private $typeNames = array( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.PropertyNotSnakeCase ZBS_TYPE_CONTACT => array( 'Contact', 'Contacts' ), ZBS_TYPE_COMPANY => array( 'Company', 'Companies' ), ZBS_TYPE_QUOTE => array( 'Quote', 'Quotes' ), ZBS_TYPE_INVOICE => array( 'Invoice', 'Invoices' ), ZBS_TYPE_TRANSACTION => array( 'Transaction', 'Transactions' ), ZBS_TYPE_TASK => array( 'Task', 'Tasks' ), ZBS_TYPE_FORM => array( 'Form', 'Forms' ), ZBS_TYPE_SEGMENT => array( 'Segment', 'Segments' ), ZBS_TYPE_LOG => array( 'Log', 'Logs' ), ZBS_TYPE_LINEITEM => array( 'Line Item', 'Line Items' ), ZBS_TYPE_TASK_REMINDER => array( 'Task Reminder', 'Task Reminders' ), ZBS_TYPE_QUOTETEMPLATE => array( 'Quote Template', 'Quote Templates' ), ZBS_TYPE_ADDRESS => array( 'Address', 'Addresses' ), ); // List View refs private $listViewRefs = array( // each of these is a slug for $zbs->slugs e.g. $zbs->slugs['managecontacts'] ZBS_TYPE_CONTACT => 'managecontacts', ZBS_TYPE_COMPANY => 'managecompanies', ZBS_TYPE_QUOTE => 'managequotes', ZBS_TYPE_INVOICE => 'manageinvoices', ZBS_TYPE_TRANSACTION => 'managetransactions', ZBS_TYPE_TASK => 'manage-tasks', ZBS_TYPE_FORM => 'manageformscrm', ZBS_TYPE_SEGMENT => 'segments', //no list page ZBS_TYPE_LOG => 'managecontacts', //no list page ZBS_TYPE_LINEITEM => 'managecontacts', //no list page ZBS_TYPE_TASK_REMINDER => 'managecontacts', ZBS_TYPE_QUOTETEMPLATE => 'quote-templates' ); // field obj models // these match the $globals in fields.php - bit of a legacy chunk tbh, but used throughout private $fieldModelsByID = array( ZBS_TYPE_CONTACT => 'zbsCustomerFields', ZBS_TYPE_COMPANY => 'zbsCompanyFields', ZBS_TYPE_QUOTE => 'zbsCustomerQuoteFields', ZBS_TYPE_INVOICE => 'zbsCustomerInvoiceFields', ZBS_TYPE_TRANSACTION => 'zbsTransactionFields', //ZBS_TYPE_TASK => 'zbsFormFields', ZBS_TYPE_FORM => 'zbsFormFields', ZBS_TYPE_ADDRESS => 'zbsAddressFields' ); // legacy support. private $oldTaxonomies = array( 'zerobscrm_customertag' => ZBS_TYPE_CONTACT, 'zerobscrm_companytag' => ZBS_TYPE_COMPANY, 'zerobscrm_transactiontag' => ZBS_TYPE_TRANSACTION, 'zerobscrm_logtag' => ZBS_TYPE_LOG, ); // this is a shorthand for grabbing all addr fields private $field_list_address = array( 'zbsc_addr1','zbsc_addr2','zbsc_city','zbsc_postcode','zbsc_county','zbsc_country' ); private $field_list_address2 = array( 'zbsc_secaddr1','zbsc_secaddr2','zbsc_seccity','zbsc_secpostcode','zbsc_seccounty','zbsc_seccountry' ); private $field_list_address_full = array( 'zbsc_addr1','zbsc_addr2','zbsc_city','zbsc_postcode','zbsc_county','zbsc_country', 'zbsc_secaddr1','zbsc_secaddr2','zbsc_seccity','zbsc_secpostcode','zbsc_seccounty','zbsc_seccountry' ); // this stores any insert errors private $errorStack = array(); /** * Prefix for origin strings which are domains (should mean querying easier later) * Used throughout to specify domain */ private $prefix_domain = 'd:'; // =========== / OBJECT TYPE & GLOBAL DEFINITIONS ============================= // =============================================================================== // =============================================================================== // =========== INIT ============================================================= function __construct($args=array()) { // init sub-layers: $this->contacts = new zbsDAL_contacts; $this->segments = new zbsDAL_segments; global $zbs; if ($zbs->isDAL3()){ $this->companies = new zbsDAL_companies; $this->quotes = new zbsDAL_quotes; $this->invoices = new zbsDAL_invoices; $this->transactions = new zbsDAL_transactions; $this->forms = new zbsDAL_forms; $this->events = new zbsDAL_events; $this->eventreminders = new zbsDAL_eventreminders; $this->logs = new zbsDAL_logs; $this->lineitems = new zbsDAL_lineitems; $this->quotetemplates = new zbsDAL_quotetemplates; // Not yet implemented: // $this->addresses = new zbsDAL_addresses; } // any post-settings-loaded actions add_action( 'after_zerobscrm_settings_preinit', [ $this, 'postSettingsInit' ] ); } // =========== / INIT =========================================================== // =============================================================================== /** * Corrects label for 'Company' (could be Organisation) after the settings have loaded. * Clunky workaround for now */ public function postSettingsInit(){ // Correct any labels $this->typeNames[ZBS_TYPE_COMPANY] = array(jpcrm_label_company(),jpcrm_label_company(true)); } // =============================================================================== // =========== HELPER/GET FUNCS ================================================= public function field_list_address(){ return $this->field_list_address; } public function field_list_address2(){ return $this->field_list_address2; } public function field_list_address_full(){ return $this->field_list_address_full; } // returns object types indexed by their global (e.g. ZBS_TYPE_CONTACT = 1) public function get_object_types_by_index(){ return $this->typesByID; } // returns object types indexed by their key (e.g. 'contact' => ZBS_TYPE_CONTACT = 1) public function getObjectTypesByKey(){ return array_flip($this->typesByID); } public function getCPTObjectTypesByKey(){ return array_flip($this->typeCPT); } // returns $zbs->DAL->contacts by '1' // for now brutal switch, avoid using anywhere but internally, use proper refs elsewhere // ... avoid use where not essential as does not produce highly readable code. public function getObjectLayerByType($objTypeID=-1){ switch ($objTypeID){ case ZBS_TYPE_CONTACT: return $this->contacts; break; case ZBS_TYPE_COMPANY: return $this->companies; break; case ZBS_TYPE_QUOTE: return $this->quotes; break; case ZBS_TYPE_INVOICE: return $this->invoices; break; case ZBS_TYPE_TRANSACTION: return $this->transactions; break; case ZBS_TYPE_FORM: return $this->forms; break; case ZBS_TYPE_TASK: return $this->events; break; case ZBS_TYPE_TASK_REMINDER: return $this->eventreminders; break; case ZBS_TYPE_LOG: return $this->logs; break; case ZBS_TYPE_LINEITEM: return $this->lineitems; break; case ZBS_TYPE_QUOTETEMPLATE: return $this->quotetemplates; break; // case ZBS_TYPE_ADDRESS: // return $this->addresses; break; } return false; } /** * Returns $zbsCustomerFields global from object_type_id * designed as legacy support until we can refactor away from globals (gh-253) * * @param CRM_TYPE int object_type_id - object type ID\ * * @return bool|array - object type field global array, or false */ public function get_object_field_global( $object_type_id = -1 ){ // attempt to retrieve var $global_var_name = $this->objFieldVarName( $object_type_id ); if ( $global_var_name !== -1){ return isset( $GLOBALS[ $global_var_name ] ) ? $GLOBALS[ $global_var_name ] : null; } return false; } public function isValidObjTypeID($objTypeIn=false){ // if it's not an int type, cast it...? if (!is_int($objTypeIn)) $objTypeIn = (int)$objTypeIn; // if bigger than 0 and in our arr as a key, basic check if ($objTypeIn > 0 && isset($this->typesByID[$objTypeIn])) return true; return false; } /** * Check if a given status is valid for the given object * * @param int $obj_type_id Object type ID. * @param str $obj_status Object status string. */ public function is_valid_obj_status( $obj_type_id, $obj_status ) { switch ( $obj_type_id ) { case ZBS_TYPE_CONTACT: $valid_statuses = zeroBSCRM_getCustomerStatuses( true ); break; case ZBS_TYPE_COMPANY: $valid_statuses = zeroBSCRM_getCompanyStatuses(); break; case ZBS_TYPE_INVOICE: $valid_statuses = zeroBSCRM_getInvoicesStatuses(); break; case ZBS_TYPE_TRANSACTION: $valid_statuses = zeroBSCRM_getTransactionsStatuses( true ); break; default: return false; } // if required, check if default status is a valid one return in_array( $obj_status, $valid_statuses, true ); } // takes in an obj type str (e.g. 'contact') and returns DEFINED KEY ID = 1 public function objTypeID($objTypeStr=''){ // catch some legacy translations if ($objTypeStr == 'customer') $objTypeStr = 'contact'; $byStr = $this->getObjectTypesByKey(); if (isset($byStr[$objTypeStr])) return $byStr[$objTypeStr]; // if not, fall back to old obj cpt types $byStr = $this->getCPTObjectTypesByKey(); if (isset($byStr[$objTypeStr])) return $byStr[$objTypeStr]; return -1; } // takes in an obj type int (e.g. 1) and returns key (e.g. 'contact') public function objTypeKey($objTypeID=-1){ if (isset($this->typesByID[$objTypeID])) return $this->typesByID[$objTypeID]; return -1; } // takes in an obj type int (e.g. 1) and returns field global var name (e.g. 'zbsCustomerFields') public function objFieldVarName($objTypeID=-1){ if (isset($this->fieldModelsByID[$objTypeID])) return $this->fieldModelsByID[$objTypeID]; return -1; } // takes in an obj type (e.g. 1) and returns obj model for that type (as per sub layer) // uses getObjectLayerByType to keep generic. Use only in fairly high level generic funcs. public function objModel($objTypeID=-1){ if ($objTypeID > 0){ $objLayer = $this->getObjectLayerByType($objTypeID); // if set, $objLayer will effectively be $zbs->DAL->contacts obj if (method_exists($objLayer,'objModel')){ // all good return $objLayer->objModel(); } } return false; } // takes in an old taxonomy str (e.g. zerobscrm_customertag) and returns new obj key (e.g. 1) public function cptTaxonomyToObjID($taxonomyStr=-1){ if (isset($this->oldTaxonomies[$taxonomyStr])) return $this->oldTaxonomies[$taxonomyStr]; return -1; } // takes in an obj ID and gives back the list view slug public function listViewSlugFromObjID($objTypeID=-1){ global $zbs; if (isset($this->listViewRefs[$objTypeID]) && isset($zbs->slugs[$this->listViewRefs[$objTypeID]])) return $zbs->slugs[$this->listViewRefs[$objTypeID]]; return ''; } // retrieves single/plural 'str' for obj type id (e.g. 1 = Contact/Contacts) public function typeStr($typeInt=-1,$plural=false){ $typeInt = (int)$typeInt; if ($typeInt > 0){ if (isset($this->typeNames[$typeInt])){ // plural if ($plural) return __($this->typeNames[$typeInt][1],'zero-bs-crm'); // single return __($this->typeNames[$typeInt][0],'zero-bs-crm'); } } return ''; } // retrieves old CPT for that type public function typeCPT($typeInt=-1){ $typeInt = (int)$typeInt; if ($typeInt > 0){ if (isset($this->typeCPT[$typeInt])) return $this->typeCPT[$typeInt]; } return false; } /* * This function provides a general list of field slugs which should * be hidden on front end aspects (e.g. Portal, WooSync->WooCommerce My Account) * * @param int $obj_type_int - optionally specifies whether 'globally' non inclusive, or 'globally+objmodel specific' */ public function fields_to_hide_on_frontend( $obj_type_int = false ){ // Globals $fields_to_hide_on_frontend = array( 'status', 'email', 'zbs_site', 'zbs_team', 'zbs_owner' ); // Object type specific if ( $this->isValidObjTypeID( $obj_type_int ) ){ $obj_model = $this->objModel( $obj_type_int ); foreach ( $obj_model as $field_key => $field_array ){ if ( is_array( $field_array ) && isset( $field_array['do_not_show_on_portal'] ) && $field_array['do_not_show_on_portal'] ){ if ( !in_array( $field_key, $fields_to_hide_on_frontend ) ){ $fields_to_hide_on_frontend[] = $field_key; } } } } return $fields_to_hide_on_frontend; } /** * Returns a count of objects of a type which are associated with an assignee (eg. company or contact) * Supports Quotes, Invoices, Transactions, Events currently * * @param int $assignee_id The assignee ID (for example company / contact ID). * @param int $obj_type_id The type constant being checked (eg ZBS_TYPE_QUOTE). * @param int $zbs_type The assigne type, for example ZBS_TYPE_COMPANY, ZBS_TYPE_CONTACT (default contact). * * @return int The count of relevant objects of the given type. */ public function specific_obj_type_count_for_assignee( $assignee_id, $obj_type_id, $zbs_type = ZBS_TYPE_CONTACT ) { // phpcs:disable WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase global $ZBSCRM_t; global $wpdb; switch ( $obj_type_id ) { case ZBS_TYPE_QUOTE: $table_name = $ZBSCRM_t['quotes']; break; case ZBS_TYPE_INVOICE: $table_name = $ZBSCRM_t['invoices']; break; case ZBS_TYPE_TRANSACTION: $table_name = $ZBSCRM_t['transactions']; break; case ZBS_TYPE_TASK: $table_name = $ZBSCRM_t['events']; break; default: // For any unsupported objtype. return -1; } $obj_query = 'SELECT COUNT(obj_table.id) FROM ' . $table_name . ' obj_table' . ' INNER JOIN ' . $ZBSCRM_t['objlinks'] . ' obj_links' . ' ON obj_table.id = obj_links.zbsol_objid_from' . ' WHERE obj_links.zbsol_objtype_from = ' . $obj_type_id . ' AND obj_links.zbsol_objtype_to = ' . $zbs_type . ' AND obj_links.zbsol_objid_to = %d'; // Counting objs with objlinks to this assignee, ignoring ownership. $query = $this->prepare( $obj_query, $assignee_id ); $count = (int) $wpdb->get_var( $query ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.NoCaching -- To be refactored. return $count; // phpcs:enable WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } // =========== / HELPER/GET FUNCS ================================================ // =============================================================================== // =============================================================================== // =========== OWNERSHIP HELPERS =============================================== // This func is a side-switch alternative to now-removed zeroBS_checkOwner public function checkObjectOwner($args=array()){ #} =========== LOAD ARGS ============== $defaultArgs = array( 'objID' => -1, 'objTypeID' => -1, // id to compare to 'potentialOwnerID' => -1, // if not owned, return true? 'allowNoOwnerAccess' => -1 ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS =============) if ($objID !== -1 && $objTypeID > 0){ $ownerID = $this->getObjectOwner(array( 'objID' => $objID, 'objTypeID' => $objTypeID )); if (isset($ownerID) && $ownerID == $potentialOwnerID) return true; // no owner owns this! else if ($allowNoOwnerAccess && (!isset($potentialOwner) || $potentialOwner == -1)) return true; } return false; } // This func is a side-switch alternative to zeroBS_getOwner public function getObjectOwner($args=array()){ #} =========== LOAD ARGS ============== $defaultArgs = array( 'objID' => -1, 'objTypeID' => -1 ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS =============) if ($objID !== -1 && $objTypeID > 0){ return $this->getFieldByID(array( 'id' => $objID, 'objtype' => $objTypeID, 'colname' => 'zbs_owner', 'ignoreowner'=>true)); } return false; } // This func is a side-switch alternative to zeroBS_setOwner public function setObjectOwner($args=array()){ #} =========== LOAD ARGS ============== $defaultArgs = array( 'objID' => -1, 'objTypeID' => -1, 'ownerID' => -1 ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS =============) if ($objID !== -1 && $objTypeID > 0){ return $this->setFieldByID(array( 'objID' => $objID, 'objTypeID' => $objTypeID, 'colname' => 'zbs_owner', 'coldatatype' => '%d', // %d/s 'newValue' => $ownerID )); } return false; } // this is used to get specific user's settings via userSetting private $userSettingPrefix = 'usrset_'; // completes via usrset_*ID*_key /* old way of doing it: (we now use zbs_owner :)) private function getUserSettingPrefix($userID=-1){ // completes usrset_*ID*_key return $this->userSettingPrefix.$userID.'_'; } */ // Note: Following MUST be used together. // this makes query vars (as appropriate) team + site (and owner if $ignoreOwner not false) public function ownershipQueryVars($ignoreOwner=false){ $queryVars = array(); // add site // FOR V3.0 SITE + TEAM NOT YET USED, (BUT THIS'll WORK) //$queryVars[] = zeroBSCRM_site(); // add team // FOR V3.0 SITE + TEAM NOT YET USED, (BUT THIS'll WORK) //$queryVars[] = zeroBSCRM_team(); // add owner if (!$ignoreOwner) $queryVars[] = zeroBSCRM_user(); return $queryVars; } // this makes query str (as appropriate) team + site (and owner if $ignoreOwner not false) // $table ONLY needed when is a LEFT JOIN or similar. public function ownershipSQL($ignoreOwner=false,$table=''){ // build $q = ''; $tableStr = ''; if (!empty($table)) $tableStr = $table.'.'; // add site // FOR V3.0 SITE + TEAM NOT YET USED, (BUT THIS'll WORK) //$q = $this->spaceAnd($q).$tableStr.'zbs_site = %d'; // add team // FOR V3.0 SITE + TEAM NOT YET USED, (BUT THIS'll WORK) //$q = $this->spaceAnd($q).$tableStr.'zbs_team = %d'; // add owner if (!$ignoreOwner) $q = $this->spaceAnd($q).$tableStr.'zbs_owner = %d'; return $q; } // =========== / OWNERSHIP HELPERS ============================================= // =============================================================================== // =============================================================================== // =========== ERROR HELPER FUNCS =============================================== /* These are shared between DAL2 + DAL3, though are only included from v3.0 + */ // retrieve errors from dal error stack public function getErrors($objTypeID=-1){ // all: if ($objTypeID < 0) return $this->errorStack; // specific if (is_array($this->errorStack) && isset($this->errorStack[$objTypeID])) return $this->errorStack[$objTypeID]; // ?? return array(); } // add error to dal error stack public function addError($errorCode=-1,$objTypeID=-1,$errStr='',$extraParam=false){ if ($objTypeID > 0 && !empty($errStr)){ // init if (!isset($this->errorStack) || !is_array($this->errorStack)) $this->errorStack = array(); if (!isset($this->errorStack[$objTypeID]) || !is_array($this->errorStack[$objTypeID])) $this->errorStack[$objTypeID] = array(); // if $errorCode, add to string if ($errorCode > 0) $errStr .= ' ('.__('Error #','zero-bs-crm').$errorCode.')'; // add $this->errorStack[$objTypeID][] = array('code'=>$errorCode,'str'=>$errStr,'param'=>$extraParam); } } // =========== / ERROR HELPER FUNCS ============================================== // =============================================================================== /* ====================================================== DAL CRUD ====================================================== */ // =============================================================================== // =========== OBJ LINKS ======================================================= /** * returns objects against an obj (e.g. company's against contact id 101) * This is like getObjsLinksLinkedToObj, only it returns actual objs :) * * @param array $args Associative array of arguments * obj array * * @return array result */ public function getObjsLinkedToObj($args=array()){ #} =========== LOAD ARGS ============== $defaultArgs = array( 'objtypefrom' => -1, 'objtypeto' => -1, // either or here, to specify direction of relationship 'objfromid' => -1, 'objtoid' => -1, // this will be passed to the getCompanies(array()) func, if given 'objRetrievePassthrough' => array(), 'count' => false, // only return count // permissions //'ignoreowner' => false // this'll let you not-check the owner of obj // NOTE 'owner' will ALWAYS be ignored by this, but allows for team/site // settings don't need owners yet :) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= // hard ignored for now :) $ignoreowner = true; if (!isset($objtypefrom) || empty($objtypefrom)) return false; if ($this->objTypeKey($objtypefrom) === -1) return false; if (!isset($objtypeto) || empty($objtypeto)) return false; if ($this->objTypeKey($objtypeto) === -1) return false; #} Check ID $direction = 'from'; $objfromid = (int)$objfromid; $objtoid = (int)$objtoid; if ($objtoid > 0) $direction = 'to'; if ( (!empty($objfromid) && $objfromid > 0) || (!empty($objtoid) && $objtoid > 0) ){ $res = array(); // get links - this could all be one query... optimise once other db objects moved over $objLinks = $this->getObjsLinksLinkedToObj(array( 'objtypefrom' => $objtypefrom, // contact 'objtypeto' => $objtypeto, // company 'objfromid' => $objfromid, //-1 or id 'objtoid' => $objtoid)); if ($count) { if (is_array($objLinks)) return count($objLinks); else return 0; } if (is_array($objLinks) && count($objLinks) > 0){ // make an id array (useful) $idArray = array(); foreach ($objLinks as $l) { // switched direction $xid = $l['objidto']; if ($direction == 'to') $xid = $l['objidfrom']; if (!in_array($xid, $idArray)) $idArray[] = $xid; } // load them all (type dependent) switch ($objtypeto){ // not yet used, but will work :) case ZBS_TYPE_CONTACT: return $this->contacts->getContacts(array('inArr'=>$idArray)); break; case ZBS_TYPE_COMPANY: return $this->companies->getCompanies(array('inArr'=>$idArray)); break; case ZBS_TYPE_QUOTE: return $this->quotes->getQuotes(array('inArr'=>$idArray)); break; case ZBS_TYPE_INVOICE: return $this->invoices->getInvoices(array('inArr'=>$idArray)); break; case ZBS_TYPE_TRANSACTION: return $this->transactions->getTransactions(array('inArr'=>$idArray)); break; case ZBS_TYPE_TASK: return $this->events->getEvents(array('inArr'=>$idArray)); break; case ZBS_TYPE_QUOTETEMPLATE: return $this->quotetemplates->getQuotetemplate(array('inArr'=>$idArray)); break; /* not used case ZBS_TYPE_LOG: return $this->logs->getLogs(array('inArr'=>$idArray)); break; case ZBS_TYPE_LINEITEM: return $this->events->getEvents(array('inArr'=>$idArray)); break; case ZBS_TYPE_TASK_REMINDER: return $this->events->getEvents(array('inArr'=>$idArray)); break; */ } } return $res; } // / if ID return false; } /** * returns object link lines against an obj (e.g. link id, company id's against contact id 101) * * @param array $args Associative array of arguments * objtypeid, objid * * @return array result */ public function getObjsLinksLinkedToObj($args=array()){ #} =========== LOAD ARGS ============== $defaultArgs = array( 'objtypefrom' => -1, 'objtypeto' => -1, // either or here, to specify direction of relationship // if 'direction' = 'both', it'll check both 'objfromid' => -1, 'objtoid' => -1, 'direction' => 'from', // from, to, both (both checks for both id's and is used to validate if links exist) 'count' => false, // only return count // permissions //'ignoreowner' => false // this'll let you not-check the owner of obj // NOTE 'owner' will ALWAYS be ignored by this, but allows for team/site // settings don't need owners yet :) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= // hard ignored for now $ignoreowner = true; if (!isset($objtypefrom) || empty($objtypefrom)) return false; if ($this->objTypeKey($objtypefrom) === -1) return false; if (!isset($objtypeto) || empty($objtypeto)) return false; if ($this->objTypeKey($objtypeto) === -1) return false; #} Check ID $objfromid = (int)$objfromid; $objtoid = (int)$objtoid; if ($objtoid > 0 && $direction != "both") $direction = 'to'; if ( (!empty($objfromid) && $objfromid > 0) || (!empty($objtoid) && $objtoid > 0) ){ global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); #} Build query $query = "SELECT * FROM ".$ZBSCRM_t['objlinks']; #} ============= WHERE ================ #} Add $wheres['zbsol_objtype_from'] = array('zbsol_objtype_from','=','%s',$objtypefrom); $wheres['zbsol_objtype_to'] = array('zbsol_objtype_to','=','%s',$objtypeto); // which direction? if ($direction == 'from' || $direction == 'both') $wheres['zbsol_objid_from'] = array('zbsol_objid_from','=','%s',$objfromid); if ($direction == 'to' || $direction == 'both') $wheres['zbsol_objid_to'] = array('zbsol_objid_to','=','%s',$objtoid); #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort('ID','DESC') . $this->buildPaging(0,10000); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_results($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret results (Result Set - multi-row) if (isset($potentialRes) && is_array($potentialRes) && count($potentialRes) > 0) { // if count? if ($count) return count($potentialRes); #} Has results, tidy + return foreach ($potentialRes as $resDataLine) { // tidy $resArr = $this->tidy_objlink($resDataLine); $res[] = $resArr; } } // if count? if ($count) return 0; return $res; } // / if ID return false; } /** * returns ID of first obj of link type (to obj) * e.g. ID first invoice linked to transaction ID (X) * (useful where transactions:invoices are only ever linked 1:1) * * @param array $args Associative array of arguments * objtypeid, objid * * @return array result */ public function getFirstIDLinkedToObj($args=array()){ #} =========== LOAD ARGS ============== $defaultArgs = array( 'objtypefrom' => -1, 'objtypeto' => -1, 'objfromid' => -1, // permissions //'ignoreowner' => false // this'll let you not-check the owner of obj // NOTE 'owner' will ALWAYS be ignored by this, but allows for team/site // settings don't need owners yet :) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= // hard ignored for now $ignoreowner = true; if (!isset($objtypefrom) || empty($objtypefrom)) return false; if ($this->objTypeKey($objtypefrom) === -1) return false; if (!isset($objtypeto) || empty($objtypeto)) return false; if ($this->objTypeKey($objtypeto) === -1) return false; #} Check ID $objfromid = (int)$objfromid; if (!empty($objfromid) && $objfromid > 0){ global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); #} Build query $query = "SELECT zbsol_objid_to FROM ".$ZBSCRM_t['objlinks']; #} ============= WHERE ================ #} Add $wheres['zbsol_objtype_from'] = array('zbsol_objtype_from','=','%s',$objtypefrom); $wheres['zbsol_objtype_to'] = array('zbsol_objtype_to','=','%s',$objtypeto); $wheres['zbsol_objid_from'] = array('zbsol_objid_from','=','%s',$objfromid); #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort('ID','DESC') . $this->buildPaging(0,1); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_var($queryObj); if ($potentialRes > -1) return (int)$potentialRes; } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } } // / if ID return false; } /** * adds or updates a link object * E.G. Contact -> Company * this says "match obj X with obj Y" (effectively 'tagging' it) * Using this generic format, but as of v2.5+ there's only contact->company links in here * * @param array $args Associative array of arguments * id (if update - probably never used here), data(objtype,objid,tagid) * * @return int line ID */ public function addUpdateObjLink($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, // OWNERS will all be set to -1 for objlinks for now :) //'owner' => -1 // fields (directly) 'data' => array( 'objtypefrom' => -1, 'objtypeto' => -1, 'objfromid' => -1, 'objtoid' => -1 ) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ // check obtype is completed + legit if (!isset($data['objtypefrom']) || empty($data['objtypefrom'])) return false; if ($this->objTypeKey($data['objtypefrom']) === -1) return false; if (!isset($data['objtypeto']) || empty($data['objtypeto'])) return false; if ($this->objTypeKey($data['objtypeto']) === -1) return false; // if owner = -1, add current // for now, all -1 - not needed yet (makes tags dupe e.g.) if (!isset($owner) || $owner === -1) $owner = zeroBSCRM_user(); $owner = -1; #} check obj ids if (empty($data['objfromid']) || $data['objfromid'] < 1 || empty($data['objtoid']) || $data['objtoid'] < 1) return false; #} ========= / CHECK FIELDS =========== #} Check if ID present $id = (int)$id; if (!empty($id) && $id > 0){ #} Check if obj exists (here) - for now just brutal update (will error when doesn't exist) #} Attempt update if ($wpdb->update( $ZBSCRM_t['objlinks'], array( // ownership // no need to update these (as of yet) - can't move teams etc. //'zbs_site' => zeroBSCRM_installSite(), //'zbs_team' => zeroBSCRM_installTeam(), 'zbs_owner' => $owner, // fields 'zbsol_objtype_from' => $data['objtypefrom'], 'zbsol_objtype_to' => $data['objtypeto'], 'zbsol_objid_from' => $data['objfromid'], 'zbsol_objid_to' => $data['objtoid'] ), array( // where 'ID' => $id ), array( // field data types '%d', '%d', '%d', '%d', '%d' ), array( // where data types '%d' )) !== false){ // Successfully updated - Return id return $id; } else { // FAILED update return false; } } else { #} No ID - must be an INSERT if ($wpdb->insert( $ZBSCRM_t['objlinks'], array( // ownership 'zbs_site' => zeroBSCRM_site(), 'zbs_team' => zeroBSCRM_team(), 'zbs_owner' => $owner, // fields 'zbsol_objtype_from' => $data['objtypefrom'], 'zbsol_objtype_to' => $data['objtypeto'], 'zbsol_objid_from' => $data['objfromid'], 'zbsol_objid_to' => $data['objtoid'] ), array( // field data types '%d', // site '%d', // team '%d', // owner '%d', '%d', '%d', '%d' ) ) > 0){ #} Successfully inserted, lets return new ID $newID = $wpdb->insert_id; return $newID; } else { #} Failed to Insert return false; } } return false; } /** * adds or updates object - object link against an obj * this says "match company X,Y,Z with contact Y" * * @param array $args Associative array of arguments * objtype,objid,tags (array of tagids) * * @return array $tags */ public function addUpdateObjLinks($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'owner' => -1, 'objtypefrom' => -1, 'objtypeto' => -1, 'objfromid' => -1, 'objtoids' => -1, // array of ID's 'mode' => 'replace' // replace|append|remove ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ // check obtype is completed + legit if (!isset($objtypefrom) || empty($objtypefrom)) return false; if ($this->objTypeKey($objtypefrom) === -1) return false; if (!isset($objtypeto) || empty($objtypeto)) return false; if ($this->objTypeKey($objtypeto) === -1) return false; // if owner = -1, add current if (!isset($owner) || $owner === -1) $owner = zeroBSCRM_user(); // tagging id $objfromid = (int)$objfromid; if (empty($objfromid) || $objfromid < 1) return false; // to obj list if (!is_array($objtoids)) return false; // mode if (gettype($mode) != 'string' || !in_array($mode, array('replace','append','remove'))) return false; #} ========= / CHECK FIELDS =========== switch ($mode){ case 'replace': // cull all previous $deleted = $this->deleteObjLinks(array( 'objtypefrom' => $objtypefrom, // contact 'objtypeto' => $objtypeto, // company 'objfromid' => $objfromid)); // where contact id = // cycle through & add foreach ($objtoids as $objtoid){ $added = $this->addUpdateObjLink(array( 'data'=>array( 'objtypefrom' => $objtypefrom, 'objtypeto' => $objtypeto, 'objfromid' => $objfromid, 'objtoid' => $objtoid, 'owner' => $owner ))); } break; case 'append': // get existing $objLinks = $this->getObjsLinksLinkedToObj(array( 'objtypefrom' => $objtypefrom, // contact 'objtypeto' => $objtypeto, // company 'objfromid' => $objfromid)); // make just ids $existingLinkIDs = array(); foreach ($objLinks as $l) $existingLinkIDs[] = $l['id']; // cycle through& add foreach ($objtoids as $objtoid){ if (!in_array($objtoid,$existingLinkIDs)){ // add a link $this->addUpdateObjLink(array( 'data'=>array( 'objtypefrom' => $objtypefrom, 'objtypeto' => $objtypeto, 'objfromid' => $objfromid, 'objtoid' => $objtoid, 'owner' => $owner ))); } } break; case 'remove': // cycle through & remove links foreach ($objtoids as $objtoid){ // add a link $this->deleteObjLinks(array( 'objtypefrom' => $objtypefrom, // contact 'objtypeto' => $objtypeto, // company 'objfromid' => $objfromid, 'objtoid' => $objtoid)); // where contact id = } break; } return false; } /** * deletes all object links for a specific obj * * @param array $args Associative array of arguments * id * * @return int success; */ public function deleteObjLinks($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'objtypefrom' => -1, 'objtypeto' => -1, 'objfromid' => -1, 'objtoid' => -1 // only toid/fromid to be set if want to delete all contact->company links ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ // check obtype is completed + legit if (!isset($objtypefrom) || empty($objtypefrom)) return false; if ($this->objTypeKey($objtypefrom) === -1) return false; if (!isset($objtypeto) || empty($objtypeto)) return false; if ($this->objTypeKey($objtypeto) === -1) return false; // obj id $objfromid = (int)$objfromid; $objtoid = (int)$objtoid; if ( (empty($objfromid) || $objfromid < 1) && (empty($objtoid) || $objtoid < 1) ) return false; // CHECK PERMISSIONS? #} ========= / CHECK FIELDS =========== // basics $where = array( // where 'zbsol_objtype_from' => $objtypefrom, 'zbsol_objtype_to' => $objtypeto ); $whereFormat = array( // where '%d', '%d' ); // any to add? if (!empty($objfromid) && $objfromid > 0){ $where['zbsol_objid_from'] = $objfromid; $whereFormat[] = '%d'; } if (!empty($objtoid) && $objtoid > 0){ $where['zbsol_objid_to'] = $objtoid; $whereFormat[] = '%d'; } // brutal return $wpdb->delete( $ZBSCRM_t['objlinks'], $where, $whereFormat); } /** * tidy's the object from wp db into clean array * * @param array $obj (DB obj) * * @return array (clean obj) */ private function tidy_objlink($obj=false){ $res = false; if (isset($obj->ID)){ $res = array(); $res['id'] = $obj->ID; /* `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, */ $res['objtypefrom'] = $obj->zbsol_objtype_from; $res['objtypeto'] = $obj->zbsol_objtype_to; $res['objidfrom'] = $obj->zbsol_objid_from; $res['objidto'] = $obj->zbsol_objid_to; } return $res; } // =========== OBJ LINKS ===================================================== // =============================================================================== // =============================================================================== // =========== SETTINGS ====================================================== /** * Wrapper, use $this->setting($key) for easy retrieval of singular * Simplifies $this->getSetting * * @param string key * * @return bool result */ public function setting( $key = '', $default = false, $accept_cached = false){ if ( !empty( $key ) ){ return $this->getSetting(array( 'key' => $key, 'fullDetails' => false, 'default' => $default, 'accept_cached' => $accept_cached )); } return $default; } /** * Wrapper, use $this->userSetting($key) for easy retrieval of singular setting FOR USER ID * Simplifies $this->getSetting * Specific for USER settings, this prefixes setting keys with usrset_ID_ * * @param string key * * @return bool result */ public function userSetting($userID=-1,$key='',$default=false){ if (!empty($key) && $userID > 0){ return $this->getSetting(array( // old way of doing it'key' => $this->getUserSettingPrefix($userID).$key, 'key' => $this->userSettingPrefix.$key, 'fullDetails' => false, 'default' => $default, // this makes it 'per user' 'ownedBy' => $userID )); } return $default; } /** * returns full setting line +- details * * @param array $args Associative array of arguments * key, fullDetails, default * * @return array result */ public function getSetting($args=array()){ #} =========== LOAD ARGS ============== $defaultArgs = array( 'key' => false, 'default' => false, 'fullDetails' => false, // set this to 1 and get ID|key|val, rather than just the val // permissions - these are currently only used by screenoptions 'ignoreowner' => true, // this'll let you not-check the owner of obj 'ownedBy' => -1, // returns scalar ID of line 'onlyID' => false, // whether or not to accept cached variant. // Added in gh-2019, we often recall this function on one load, this allows us to accept a once-loaded version 'accept_cached' => false, ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} Check key if (!empty($key)){ // if accepting a cached obj and is present, pass that to save the query // (only do so on singular return step, not full details) if ( !$fullDetails && $accept_cached ){ $cached = $this->get_cache_var( 'setting_' . $key ); if ( $cached ){ return $cached; } } global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); #} Build query $query = "SELECT * FROM ".$ZBSCRM_t['settings']; #} ============= WHERE ================ #} Add ID $wheres['zbsset_key'] = array('zbsset_key','=','%s',$key); #} Owned by if (!empty($ownedBy) && $ownedBy > 0){ // would never hard-type this in (would make generic as in buildWPMetaQueryWhere) // but this is only here until MIGRATED to db2 globally //$wheres['incompany'] = array('ID','IN','(SELECT DISTINCT post_id FROM '.$wpdb->prefix."postmeta WHERE meta_key = 'zbs_company' AND meta_value = %d)",$inCompany); // Use obj links now $wheres['ownedBy'] = array('zbs_owner','=','%s',$ownedBy); } #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort('ID','DESC') . $this->buildPaging(0,1); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_row($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret Results (ROW) if (isset($potentialRes) && isset($potentialRes->ID)) { // Has results, tidy + return // Only ID? return it directly if ($onlyID === true) return $potentialRes->ID; // full line or scalar setting val if ( $fullDetails ){ $setting = $this->tidy_setting($potentialRes); } else { $setting = $this->tidy_settingSingular($potentialRes); // cache (commonly retrieved) $this->update_cache_var( 'setting_' . $key, $setting ); } return $setting; } } // / if ID return $default; } /** * returns all settings as settings arr (later add autoload) * * @param array $args Associative array of arguments * * @return array of settings lines */ public function getSettings($args=array()){ #} ============ LOAD ARGS ============= $defaultArgs = array( 'autoloadOnly' => true, 'fullDetails' => false, // if true returns inc id etc. // permissions //'ignoreowner' => false // this'll let you not-check the owner of obj // NOTE 'owner' will ALWAYS be ignored by this, but allows for team/site // settings don't need owners yet :) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} ========== CHECK FIELDS ============ // check obtype is legit // autoload? $fields = 'ID,zbsset_key,zbsset_val'; if ($fullDetails) $fields = '*'; // always ignore owner for now (settings global) $ignoreowner = true; #} ========= / CHECK FIELDS =========== global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); #} Build query $query = "SELECT $fields FROM ".$ZBSCRM_t['settings']; #} ============= WHERE ================ #} autoload? #} ============ / WHERE =============== #} Build out any WHERE clauses $wheresArr= $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort('ID','ASC') . $this->buildPaging(0,10000); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_results($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret results (Result Set - multi-row) if (isset($potentialRes) && is_array($potentialRes) && count($potentialRes) > 0) { #} Has results, tidy + return foreach ($potentialRes as $resDataLine) { // DEBUG echo $resDataLine->zbsset_key.' = '; if ($fullDetails){ // tidy $resArr = $this->tidy_setting($resDataLine); $res[$resArr['key']] = $resArr; } else $res[$resDataLine->zbsset_key] = $this->tidy_settingSingular($resDataLine); } } return $res; } /** * Wrapper, use $this->updateSetting($key,$val) for easy update of setting * Uses $this->addUpdateSetting * * @param string key * @param string value * * @return bool result */ public function updateSetting($key='',$val=''){ if (!empty($key)){ return $this->addUpdateSetting(array( 'data' => array( 'key' => $key, 'val' => $val ) )); } return false; } /** * Wrapper, use $this->updateSetting($key,$val) for easy update of setting * Uses $this->addUpdateSetting * * @param string key * @param string value * * @return bool result */ public function updateUserSetting($userID=-1,$key='',$val=''){ // if -1 passed use current user? if (!empty($key) && $userID > 0){ // because the following addUpdateSetting is dumb to owners (e.g. can't update 'per owner') // we must set perOwnerSetting to force 1 setting per key per user (owner) return $this->addUpdateSetting(array( 'owner' => $userID, 'data' => array( // old way of doing it'key' => $this->getUserSettingPrefix($userID).$key, 'key' => $this->userSettingPrefix.$key, 'val' => $val, ), 'perOwnerSetting' => true )); } return false; } /** * adds or updates a setting object * ... for a quicker wrapper, use $this->updateSetting($key,$val) * * @param array $args Associative array of arguments * id (not req.), owner (not req.) data -> key/val * * @return int line ID */ public function addUpdateSetting($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, // NOTE 'owner' will ALWAYS be ignored by this, but allows for team/site // meta don't need owners yet :) // not anymore! use this for screenoptions, will be ignored unless specifically set 'owner' => -1, // fields (directly) 'data' => array( 'key' => '', 'val' => '', ), 'perOwnerSetting' => false // if set to true this'll make sure only 1 key per 'owner' (potentially multi-key if set incorrectly, so beware) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ $id = (int)$id; // if owner = -1, add current // Hard -1 for now - settings don't need - if (!isset($owner) || $owner === -1) $owner = zeroBSCRM_user(); // ... they do now, (screen options) $owner = -1; if (isset($owner) && $owner !== -1) $owner = (int)$owner; // check key present + legit if (!isset($data['key']) || empty($data['key'])) return false; // setting ID finder - if obj key provided, check setting not already present (if so overwrite) // keeps unique... if ((empty($id) || $id <= 0) && (isset($data['key']) && !empty($data['key']))) { // if perOwnerSetting it's 1 key-ed ret per owner, so query bit diff here: if (!$perOwnerSetting){ // check existence + return ID $potentialID = (int)$this->getSetting(array( 'key' => $data['key'], 'onlyID' => true )); } else { // perownedBy // if no owner, return false, cannot be (shouldn't be cos of above) if ($owner <= 0) return false; // check existence + return ID $potentialID = (int)$this->getSetting(array( 'key' => $data['key'], 'onlyID' => true, 'ownedBy' => $owner )); } // override empty ID if (!empty($potentialID) && $potentialID > 0) $id = $potentialID; } #} ========= / CHECK FIELDS =========== #} Var up any val (json_encode) if (in_array(gettype($data['val']),array("object","array"))){ // WH note: it was necessary to add JSON_UNESCAPED_SLASHES to properly save down without issue // combined with a more complex zeroBSCRM_stripSlashes recurrsive // https://stackoverflow.com/questions/7282755/how-to-remove-backslash-on-json-encode-function $data['val'] = json_encode($data['val'],JSON_UNESCAPED_SLASHES); } if (isset($id) && !empty($id) && $id > 0){ //echo 'updating setting id '.$id.'!'; #} Check if obj exists (here) - for now just brutal update (will error when doesn't exist) #} Attempt update if ($wpdb->update( $ZBSCRM_t['settings'], array( // ownership // no need to update these (as of yet) - can't move teams etc. //'zbs_site' => zeroBSCRM_installSite(), //'zbs_team' => zeroBSCRM_installTeam(), 'zbs_owner' => $owner, // fields 'zbsset_key' => $data['key'], 'zbsset_val' => $data['val'], 'zbsset_lastupdated' => time() ), array( // where 'ID' => $id ), array( // field data types '%d', '%s', '%s', '%d' ), array( // where data types '%d' )) !== false){ // Successfully updated - Return id return $id; } else { // FAILED update return false; } } else { #} No ID - must be an INSERT if ($wpdb->insert( $ZBSCRM_t['settings'], array( // ownership 'zbs_site' => zeroBSCRM_site(), 'zbs_team' => zeroBSCRM_team(), 'zbs_owner' => $owner, // fields 'zbsset_key' => $data['key'], 'zbsset_val' => $data['val'], 'zbsset_created' => time(), 'zbsset_lastupdated' => time() ), array( // field data types '%d', // site '%d', // team '%d', // owner '%s', '%s', '%d', '%d' ) ) > 0){ #} Successfully inserted, lets return new ID $newID = $wpdb->insert_id; return $newID; } else { #} Failed to Insert return false; } } return false; } /** * deletes a setting object * * @param array $args Associative array of arguments * id * * @return int success; */ public function deleteSetting($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'key' => '' ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ // if ID passed, Check ID & Delete :) $id = (int)$id; if ( $id > 0) { return zeroBSCRM_db2_deleteGeneric($id,'settings'); } // if key, find and delete if ( !empty( $key ) ){ $setting_id = $this->getSetting( array( 'key' => $key, 'onlyID' => true ) ); return zeroBSCRM_db2_deleteGeneric( $setting_id, 'settings' ); } return false; } /** * tidy's the object from wp db into clean array * * @param array $obj (DB obj) * * @return array (clean obj) */ private function tidy_setting( $obj=false ){ $res = false; if (isset($obj->ID)){ $res = array(); $res['id'] = $obj->ID; $res['key'] = $obj->zbsset_key; $res['val'] = $this->unpack_setting( $obj->zbsset_val ); $res['created'] = $obj->zbsset_created; $res['updated'] = $obj->zbsset_lastupdated; } return $res; } /** * tidy's the object from wp db into clean array * * @param array $obj (DB obj) * * @return string */ private function tidy_settingSingular( $obj=false ){ if (isset($obj->ID)){ return $this->unpack_setting( $obj->zbsset_val ); } return false; } /** * Takes a setting as db value and attempts to cast it correctly * * @param mixed $var (DB value) * * @return mixed */ private function unpack_setting( $var=false ){ if ($var !== false){ $value = $this->stripSlashes($this->decodeIfJSON($var)); // catch this oddly non-decoded case if ($value == '[]') return array(); // if we've a string, check it isn't viably an int // .. if so, cast as int if ( is_string($value) && jpcrm_is_int($value) ) $value = (int)$value; return $value; } // fallback to returning the value passed return $var; } // =========== / SETTINGS ======================================================= // =============================================================================== // =============================================================================== // =========== META ============================================================ /** * Wrapper, use $this->meta($objtype,$objid,$key) for easy retrieval of singular * Simplifies $this->getMeta * * @param int objtype * @param int objid * @param string key * * @return bool result */ public function meta($objtype=-1,$objid=-1,$key='',$default=false){ if (!empty($key)){ return $this->getMeta(array( 'objtype' => $objtype, 'objid' => $objid, 'key' => $key, 'fullDetails' => false, 'default' => $default )); } return $default; } /** * returns full meta line +- details * * @param array $args Associative array of arguments * key, fullDetails, default * * @return array result */ public function getMeta($args=array()){ #} =========== LOAD ARGS ============== $defaultArgs = array( 'objid' => -1, // Object ID 'objtype' => -1, // Object Type 'key' => false, // key *Required 'default' => false, 'fullDetails' => false, // set this to 1 and get ID|key|val, rather than just the val // permissions //'ignoreowner' => false // this'll let you not-check the owner of obj // NOTE 'owner' will ALWAYS be ignored by this, but allows for team/site // meta don't need owners yet :) 'onlyID' => false, // returns scalar ID of line 'return_all_lines' => false, // if just specifying a key and setting this to true, will return all meta lines with key ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} =========== CHECK FIELDS ============= // check obtype is legit if ( isset( $objtype ) && $objtype !== -1 && $this->objTypeKey( $objtype ) === -1) return false; // obj id $objid = (int)$objid; // for now, meta hard ignores owners $ignoreowner = true; #} =========== / CHECK FIELDS ============= #} Check key if (!empty($key)){ global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); #} Build query $query = "SELECT * FROM ".$ZBSCRM_t['meta']; #} ============= WHERE ================ // Add ID if ( $objid > 0 ) { $wheres['zbsm_objid'] = array('zbsm_objid','=','%d',$objid); } // Add OBJTYPE if ( $objtype > 0 ){ $wheres['zbsm_objtype'] = array('zbsm_objtype','=','%d',$objtype); } // Add KEY $wheres['zbsm_key'] = array('zbsm_key','=','%s',$key); #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort('ID','DESC'); if ( !$return_all_lines ){ $query .= $this->buildPaging(0,1); } try { #} Prep & run query $queryObj = $this->prepare($query,$params); if ( !$return_all_lines ){ // singular $result = $wpdb->get_row($queryObj, OBJECT); } else { // multi-line $result = $wpdb->get_results( $queryObj, OBJECT ); } } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } // results if ( isset( $result ) ){ #} Has results, tidy + return if ( !$return_all_lines ){ #} Only ID? return it directly if ( $onlyID === true ){ return $result->ID; } #} full line or scalar setting val if ( $fullDetails ){ return $this->tidy_meta( $result ); } else { return $this->tidy_metaSingular( $result ); } } else { // multi-line $results_array = array(); foreach ( $result as $index => $meta_line ){ $results_array[] = $this->tidy_meta( $meta_line ); } return $results_array; } } } // / if ID return $default; } /** * returns FIRST ID which has matching meta keval pair * * @param array $args Associative array of arguments * key, fullDetails, default * * @return array result */ public function getIDWithMeta($args=array()){ #} =========== LOAD ARGS ============== $defaultArgs = array( 'objtype' => -1, // REQ 'key' => false, // REQ 'val' => false, // REQ // permissions //'ignoreowner' => false // this'll let you not-check the owner of obj // NOTE 'owner' will ALWAYS be ignored by this, but allows for team/site // meta don't need owners yet :) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} =========== CHECK FIELDS ============= // check obtype is completed + legit if (!isset($objtype) || empty($objtype)) return false; if ($this->objTypeKey($objtype) === -1) return false; // meta key if (empty($key) || empty($val) || $key == false || $val == false) return false; // for now, meta hard ignores owners $ignoreowner = true; #} =========== / CHECK FIELDS ============= #} Check key if (!empty($key)){ global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); #} Build query $query = "SELECT zbsm_objid FROM ".$ZBSCRM_t['meta']; #} ============= WHERE ================ #} Add OBJTYPE $wheres['zbsm_objtype'] = array('zbsm_objtype','=','%d',$objtype); #} Add KEY $wheres['zbsm_key'] = array('zbsm_key','=','%s',$key); #} Add VAL $wheres['zbsm_val'] = array('zbsm_val','=','%s',$val); #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort('ID','DESC') . $this->buildPaging(0,1); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $v = (int)$wpdb->get_var($queryObj); if ($v > -1) return $v; } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } } // / if ID return -1; } /** * Wrapper, use $this->updateMeta($objtype,$objid,$key,$val) for easy update of setting * Uses $this->addUpdateMeta * ... USE sub-layer rather than this direct, gives a degree of abstraction * * @param string key * @param string value * * @return bool result */ public function updateMeta($objtype=-1,$objid=-1,$key='',$val=''){ if (!empty($key)){ // && !empty($val) return $this->addUpdateMeta(array( 'data' => array( 'objid' => $objid, 'objtype' => $objtype, 'key' => $key, 'val' => $val ) )); } return false; } /** * adds or updates a setting object * ... for a quicker wrapper, use $this->updateMeta($key,$val) * * @param array $args Associative array of arguments * id (not req.), owner (not req.) data -> key/val * * @return int line ID */ public function addUpdateMeta($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, // owner HARD disabled for this for now - not req. for each meta //'owner' => -1, // fields (directly) 'data' => array( 'objid' => -1, 'objtype' => -1, 'key' => '', 'val' => '', ) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ $id = (int)$id; // if owner = -1, add current //if (!isset($owner) || $owner === -1) $owner = zeroBSCRM_user(); // owner HARD disabled for this for now - not req. for each meta $owner = -1; // check key present + legit if (!isset($data['key']) || empty($data['key'])) return false; // check obtype is completed + legit if (!isset($data['objtype']) || empty($data['objtype'])) return false; if ($this->objTypeKey($data['objtype']) === -1) return false; // obj id $objid = (int)$data['objid']; if (empty($objid) || $objid < 1) return false; // meta ID finder - if obj key provided, check meta not already present (if so overwrite) // keeps unique... if ((empty($id) || $id <= 0) && (isset($data['key']) && !empty($data['key'])) // no need to check obj id + type here, as will return false above if not legit :) ) { // check existence + return ID $potentialID = (int)$this->getMeta(array( 'objid' => $objid, 'objtype' => $data['objtype'], 'key' => $data['key'], 'onlyID' => true )); // override empty ID if (!empty($potentialID) && $potentialID > 0) $id = $potentialID; } #} ========= / CHECK FIELDS =========== #} Var up any val (json_encode) if (in_array(gettype($data['val']),array("object","array"))){ $data['val'] = json_encode($data['val']); } if (isset($id) && !empty($id) && $id > 0){ #} Check if obj exists (here) - for now just brutal update (will error when doesn't exist) #} Attempt update if ($wpdb->update( $ZBSCRM_t['meta'], array( // ownership // no need to update these (as of yet) - can't move teams etc. //'zbs_site' => zeroBSCRM_installSite(), //'zbs_team' => zeroBSCRM_installTeam(), 'zbs_owner' => $owner, // fields 'zbsm_objtype' => $data['objtype'], 'zbsm_objid' => $objid, 'zbsm_key' => $data['key'], 'zbsm_val' => $data['val'], 'zbsm_lastupdated' => time() ), array( // where 'ID' => $id ), array( // field data types '%d', '%d', '%d', '%s', '%s', '%d' ), array( // where data types '%d' )) !== false){ // Successfully updated - Return id return $id; } else { // FAILED update return false; } } else { #} No ID - must be an INSERT if ($wpdb->insert( $ZBSCRM_t['meta'], array( // ownership 'zbs_site' => zeroBSCRM_site(), 'zbs_team' => zeroBSCRM_team(), 'zbs_owner' => $owner, // fields 'zbsm_objtype' => $data['objtype'], 'zbsm_objid' => $objid, 'zbsm_key' => $data['key'], 'zbsm_val' => $data['val'], 'zbsm_created' => time(), 'zbsm_lastupdated' => time() ), array( // field data types '%d', // site '%d', // team '%d', // owner '%d', '%d', '%s', '%s', '%d', '%d' ) ) > 0){ #} Successfully inserted, lets return new ID $newID = $wpdb->insert_id; return $newID; } else { #} Failed to Insert return false; } } return false; } /** * deletes a meta object based on objid + key * * @param array $args Associative array of arguments * id * * @return int success; */ public function deleteMeta($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'objtype' => -1, 'objid' => -1, 'key' => '' ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} Check ID, find, & Delete :) $objtype = (int)$objtype; if (isset($objtype) && $objtype !== -1 && $this->objTypeKey($objtype) === -1) return false; $objid = (int)$objid; if (empty($objid) || $objid < 1) return false; if (empty($key)) return false; #} FIND? $potentialID = (int)$this->getMeta(array( 'objid' => $objid, 'objtype' => $objtype, 'key' => $key, 'onlyID' => true )); // override empty ID if (!empty($potentialID) && $potentialID > 0) { return $this->deleteMetaByMetaID(array('id'=>$potentialID)); } return false; } /** * deletes a meta object from a meta id * * @param array $args Associative array of arguments * id * * @return int success; */ public function deleteMetaByMetaID($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1 ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} Check ID & Delete :) $id = (int)$id; return zeroBSCRM_db2_deleteGeneric( $id, 'meta' ); } /** * tidy's the object from wp db into clean array * * @param array $obj (DB obj) * * @return array (clean obj) */ private function tidy_meta( $obj=false ){ $res = false; if (isset($obj->ID)){ $res = array(); $res['id'] = $obj->ID; $res['objtype'] = $obj->zbsm_objtype; $res['objid'] = $obj->zbsm_objid; $res['key'] = $obj->zbsm_key; $res['val'] = $this->stripSlashes($obj->zbsm_val); $res['created'] = $obj->zbsm_created; $res['updated'] = $obj->zbsm_lastupdated; } return $res; } /** * tidy's the object from wp db into clean array * * @param array $obj (DB obj) * * @return string */ private function tidy_metaSingular($obj=false){ $res = false; if (isset($obj->ID)) return $this->stripSlashes($this->decodeIfJSON($obj->zbsm_val)); return $res; } // =========== / META =========================================================== // =============================================================================== // =============================================================================== // =========== TAGS =========================================================== /** * returns full tag line +- details * * @param int id tag id * @param array $args Associative array of arguments * withStats * * @return array result */ public function getTag($id=-1,$args=array()){ #} =========== LOAD ARGS ============== $defaultArgs = array( // Alternative search criteria to ID :) // .. LEAVE blank if using ID // objtype + name or slug 'objtype' => -1, 'name' => '', 'slug' => '', 'withStats' => false, // permissions //'ignoreowner' => false // this'll let you not-check the owner of obj // NOTE 'owner' will ALWAYS be ignored by this, but allows for team/site // Tags don't need owners yet :) // returns scalar ID of line 'onlyID' => false, 'onlySlug' => false, ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} ========== CHECK FIELDS ============ $id = (int)$id; // got objtype / name/slug? // check obtype is legit (if completed) if (isset($objtype) && $objtype !== -1 && $this->objTypeKey($objtype) === -1) { // if using obj type - check name/slug if (empty($name) && empty($slug)) return false; // ... else should be good to search } // Tags don't need owners yet :) $ignoreowner = true; #} ========= / CHECK FIELDS =========== #} Check ID or name/type if ( $id > 0 || $objtype > 0 ) { global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); #} Build query $query = "SELECT * FROM ".$ZBSCRM_t['tags']; #} ============= WHERE ================ // ID if ( $id > 0 ) { $wheres['ID'] = array( 'ID', '=', '%d', $id ); } // Object Type if ( $objtype > 0 ) { $wheres['zbstag_objtype'] = array( 'zbstag_objtype', '=', '%d', $objtype ); } // Name if ( ! empty( $name ) ) { $wheres['zbstag_name'] = array( 'zbstag_name', '=', '%s', $name ); } // Slug if ( ! empty( $slug) ) { $wheres['zbstag_slug'] = array( 'zbstag_slug', '=', '%s', $slug ); } #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort('ID','DESC') . $this->buildPaging(0,1); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_row($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret Results (ROW) if (isset($potentialRes) && isset($potentialRes->ID)) { #} Has results, tidy + return #} Only ID? return it directly if ($onlyID === true) return $potentialRes->ID; #} Only slug? return it directly if ($onlySlug === true) return $potentialRes->zbstag_slug; // tidy $res = $this->tidy_tag($potentialRes); // with stats? if (isset($withStats) && $withStats){ // add all stats lines $res['stats'] = $this->getTagStats(array('tagid'=>$potentialRes->ID)); } return $res; } } // / if ID return false; } /** * returns tag detail lines * * @param array $args Associative array of arguments * withStats, searchPhrase, sortByField, sortOrder, page, perPage * * @return array of tag lines */ public function getAllTags($args=array()){ #} ============ LOAD ARGS ============= $defaultArgs = array( 'searchPhrase' => '', 'withStats' => false, 'sortByField' => 'ID', 'sortOrder' => 'ASC', 'page' => 0, 'perPage' => 100, // permissions //'ignoreowner' => false // this'll let you not-check the owner of obj // NOTE 'owner' will ALWAYS be ignored by this, but allows for team/site // Tags don't need owners yet :) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= // Tags don't need owners yet :) $ignoreowner = true; global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); #} Build query $query = "SELECT * FROM ".$ZBSCRM_t['tags']; #} ============= WHERE ================ #} Add Search phrase if (!empty($searchPhrase)){ $wheres['zbstag_name'] = array('zbstag_name','LIKE','%s','%'.$searchPhrase.'%'); } #} ============ / WHERE =============== #} Build out any WHERE clauses $wheresArr= $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort($sortByField,$sortOrder) . $this->buildPaging($page,$perPage); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_results($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret results (Result Set - multi-row) if (isset($potentialRes) && is_array($potentialRes) && count($potentialRes) > 0) { #} Has results, tidy + return foreach ($potentialRes as $resDataLine) { // tidy $resArr = $this->tidy_tag($resDataLine); // with stats? if (isset($withStats) && $withStats){ // add all stats lines $res['stats'] = $this->getTagStats(array('tagid'=>$resDataLine->ID)); } $res[] = $resArr; } } return $res; } /** * adds or updates a tag object * * @param array $args Associative array of arguments * id (if update), ??? * * @return int line ID */ public function addUpdateTag($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, // fields (directly) 'data' => array( 'objtype' => -1, 'name' => '', 'slug' => '', // OWNERS will all be set to -1 for tags for now :) //'owner' => -1 ) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ $id = (int)$id; // check obtype is completed + legit if (!isset($data['objtype']) || empty($data['objtype'])) return false; if ($this->objTypeKey($data['objtype']) === -1) return false; // if owner = -1, add current // tags don't really need this level of ownership // so leaving as -1 for now :) //if (!isset($data['owner']) || $data['owner'] === -1) $data['owner'] = zeroBSCRM_user(); $data['owner'] = -1; // check name present + legit if (!isset($data['name']) || empty($data['name'])) return false; if ( empty( $data['slug'] ) ) { $potential_slug = sanitize_key( $data['name'] ); // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable // catch empty slugs as per gh-462, chinese characters, for example if ( empty( $potential_slug ) ) { $this->get_new_tag_slug( $data['objtype'], 'tag', true ); // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable } else { $data['slug'] = $this->get_new_tag_slug( $data['objtype'], $potential_slug ); // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable } // if slug STILL empty (e.g. database error?), return false for now... if ( empty( $data['slug'] ) ) { return false; } } // tag ID finder - if obj name provided, check tag not already present (if so overwrite) // keeps unique... if ((empty($id) || $id <= 0) && ( (isset($data['name']) && !empty($data['name'])) || (isset($data['slug']) && !empty($data['slug'])) )) { // check by slug // check existence + return ID $potentialID = (int)$this->getTag(-1,array( 'objtype' => $data['objtype'], 'slug' => $data['slug'], 'onlyID' => true )); // override empty ID if (!empty($potentialID) && $potentialID > 0) $id = $potentialID; } #} ========= / CHECK FIELDS =========== #} Check if ID present $id = (int)$id; if (!empty($id) && $id > 0){ #} Check if obj exists (here) - for now just brutal update (will error when doesn't exist) #} Attempt update if ($wpdb->update( $ZBSCRM_t['tags'], array( // ownership // no need to update these (as of yet) - can't move teams etc. //'zbs_site' => zeroBSCRM_installSite(), //'zbs_team' => zeroBSCRM_installTeam(), 'zbs_owner' => $data['owner'], // fields 'zbstag_objtype' => $data['objtype'], 'zbstag_name' => $data['name'], 'zbstag_slug' => $data['slug'], 'zbstag_lastupdated' => time() ), array( // where 'ID' => $id ), array( // field data types '%d', '%d', '%s', '%s', '%d' ), array( // where data types '%d' )) !== false){ // Successfully updated - Return id return $id; } else { // FAILED update return false; } } else { #} No ID - must be an INSERT if ($wpdb->insert( $ZBSCRM_t['tags'], array( // ownership 'zbs_site' => zeroBSCRM_site(), 'zbs_team' => zeroBSCRM_team(), 'zbs_owner' => $data['owner'], // fields 'zbstag_objtype' => $data['objtype'], 'zbstag_name' => $data['name'], 'zbstag_slug' => $data['slug'], 'zbstag_created' => time(), 'zbstag_lastupdated' => time() ), array( // field data types '%d', // site '%d', // team '%d', // owner '%d', '%s', '%s', '%d', '%d' ) ) > 0){ #} Successfully inserted, lets return new ID $newID = $wpdb->insert_id; return $newID; } else { #} Failed to Insert return false; } } return false; } /** * adds or updates any object's tags * ... this is really just a wrapper for addUpdateTagObjLinks * * @param array $args Associative array of arguments * id (if update), owner, data (array of field data) * * @return int line ID */ public function addUpdateObjectTags($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'objid' => -1, // REQ 'objtype' => -1, // REQ // generic pass-through (array of tag strings or tag IDs): 'tag_input' => -1, // or either specific: 'tagIDs' => -1, 'tags' => -1, 'mode' => 'replace' ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ // check id $objid = (int)$objid; if (empty($objid) || $objid <= 0) return false; // check obtype is legit (if completed) if (!isset($objtype) || $objtype == -1 || $this->objTypeKey($objtype) == -1) return false; #} ========= / CHECK FIELDS =========== // If passed tag_input, infer if using ID's or tags if ( is_array($tag_input)){ // assume ID's $tagIDs = $tag_input; // got strings? foreach ( $tag_input as $tag ){ // if it's not an int, we can assume it's a string if ( !jpcrm_is_int($tag) ){ // process as strings (tags) $tagIDs = -1; $tags = $tag_input; break; } } } #} If using tags, convert these to id's :) if ($tags !== -1 && is_array($tags)){ // overwrite $tagIDs = array(); // cycle through + find foreach ($tags as $tag){ $tagID = $this->getTag(-1,array( 'objtype' => $objtype, 'name' => $tag, 'onlyID' => true )); //echo 'looking for tag "'.$tag.'" got id '.$tagID.'!<br >'; if (!empty($tagID)) $tagIDs[] = $tagID; else { //create $tagID = $this->addUpdateTag(array( 'data'=>array( 'objtype' => $objtype, 'name' => $tag))); //add if (!empty($tagID)) $tagIDs[] = $tagID; } } } return $this->addUpdateTagObjLinks(array( 'objtype' =>$objtype, 'objid' =>$objid, 'tagIDs' =>$tagIDs, 'mode' =>$mode)); } /** * deletes a tag object * * @param array $args Associative array of arguments * id * * @return int success; */ public function deleteTag($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'deleteLinks' => true ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} Check ID & Delete :) $id = (int)$id; if (!empty($id) && $id > 0) { $deleted = zeroBSCRM_db2_deleteGeneric($id,'tags'); // if links, also delete them! if ($deleteLinks){ $deletedLinks = $wpdb->delete( $ZBSCRM_t['taglinks'], array( // where 'zbstl_tagid' => $id ), array( '%d' ) ); } return $deleted; } return false; } /** * retrieves stats for tag (how many contacts/obj's use this tag) (effectively counts tag links split per obj) * * @param array $args Associative array of arguments * id * * @return array */ public function getAllTagStats($args=array()){ #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'owner' => -1, // permissions //'ignoreowner' => false // this'll let you not-check the owner of obj // NOTE 'owner' will ALWAYS be ignored by this, but allows for team/site // Tags don't need owners yet :) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ $ignoreowner = true; #} Check ID $id = (int)$id; if (!empty($id) && $id > 0){ global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); #} Build query $query = "SELECT COUNT(zbstl_objid) c, zbstl_objtype FROM ".$ZBSCRM_t['taglinks']; #} ============= WHERE ================ #} Add ID $wheres['zbstl_tagid'] = array('zbstl_tagid','=','%d',$id); #} If 'owner' is set then have to ignore owner, because can't do both if (isset($owner) && $owner > 0) { // stops ownership check $ignoreowner = true; // adds owner to query $wheres['zbs_owner'] = array('zbs_owner','=','%d',$owner); } #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} ============ CUSTOM GROUP/ORDERBY ============== // this allows grouping :) $orderByCustom = ' GROUP BY zbstl_objtype ORDER BY c ASC'; #} ============ / CUSTOM GROUP/ORDERBY ============ #} Append to sql (and use our custom order by etc.) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $orderByCustom; try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_results($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret results (Result Set - multi-row) if (isset($potentialRes) && is_array($potentialRes) && count($potentialRes) > 0) { #} Has results, tidy + return foreach ($potentialRes as $resDataLine) { // tidy $res[] = $this->tidy_tagstat($resDataLine); } } return $res; } // / if ID return false; } /** * retrieves stats for tag (how many contacts/obj's use this tag) * this version returns specific count of uses for an objtypeid * * @param array $args Associative array of arguments * id * * @return array */ public function getTagObjStats($args=array()){ #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'objtypeid' => -1, 'owner' => -1, // permissions //'ignoreowner' => false // this'll let you not-check the owner of obj // NOTE 'owner' will ALWAYS be ignored by this, but allows for team/site // Tags don't need owners yet :) // returns scalar ID of line 'onlyID' => false ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ $ignoreowner = true; #} Check ID $id = (int)$id; if (!empty($id) && $id > 0){ global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); #} Build query $query = "SELECT COUNT(zbstl_objid) c, zbstl_objtype FROM ".$ZBSCRM_t['taglinks']; #} ============= WHERE ================ #} Add ID $wheres['zbstl_tagid'] = array('zbstl_tagid','=','%d',$id); #} Adds a specific type id if (!empty($objtypeid)){ $wheres['zbstl_objtype'] = array('zbstl_objtype','=','%d',$objtypeid); } #} If 'owner' is set then have to ignore owner, because can't do both if (isset($owner) && $owner > 0) { // stops ownership check $ignoreowner = true; // adds owner to query $wheres['zbs_owner'] = array('zbs_owner','=','%d',$owner); } #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} ============ CUSTOM GROUP/ORDERBY ============== // this allows grouping :) $orderByCustom = ' GROUP BY zbstl_objtype ORDER BY c ASC LIMIT 0,1'; #} ============ / CUSTOM GROUP/ORDERBY ============ #} Append to sql (and use our custom order by etc.) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $orderByCustom; try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_row($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret Results (ROW) if (isset($potentialRes) && isset($potentialRes->ID)) { #} Only ID? return it directly if ($onlyID === true) return $potentialRes->ID; #} Has results, tidy + return return $this->tidy_tagstat($potentialRes); } } // / if ID return false; } /** * Checks if a tag slug exists * * @param int $obj_type_id Object type id. * @param string $slug Tag slug to check. * * @return string tag slug */ public function tag_slug_exists( int $obj_type_id, string $slug ) { $slug_exists = $this->getTag( -1, array( 'objtype' => $obj_type_id, 'slug' => $slug, 'onlyID' => true, ) ); return $slug_exists !== false; } /** * Get a unique tag slug * * @param int $obj_type_id Object type id. * @param string $slug Tag slug to check. * @param bool $force_iteration Force iteration to occur (e.g. use `slug-N` instead of `slug`). * * @return string unique tag slug */ public function get_new_tag_slug( int $obj_type_id, string $slug, bool $force_iteration = false ) { global $wpdb, $ZBSCRM_t; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $slug_exists = $this->tag_slug_exists( $obj_type_id, $slug ); // slug as provided doesn't exist, so use that if ( ! $slug_exists && ! $force_iteration ) { return $slug; } $slug_base = $slug . '-'; // get last iteration of tag slug $sql_query = 'SELECT CAST(TRIM(LEADING %s FROM zbstag_slug) AS SIGNED) AS slug_iteration FROM ' . $ZBSCRM_t['tags'] . ' WHERE zbstag_slug LIKE CONCAT(%s,"%") AND zbstag_objtype = %d ORDER BY slug_iteration DESC LIMIT 1'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $cur_slug_iteration = $wpdb->get_var( $wpdb->prepare( $sql_query, $slug_base, $slug_base, $obj_type_id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared // slug hasn't yet iterated, so use first iteration if ( $cur_slug_iteration === null ) { return $slug_base . '1'; } // otherwise use next iteration $next_slug_iteration = (int) $cur_slug_iteration + 1; return $slug_base . $next_slug_iteration; } /** * tidy's the object from wp db into clean array * * @param array $obj (DB obj) * * @return array (clean obj) */ private function tidy_tag($obj=false){ $res = false; if (isset($obj->ID)){ $res = array(); $res['id'] = $obj->ID; /* `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, */ $res['objtype'] = $obj->zbstag_objtype; $res['name'] = $this->stripSlashes($obj->zbstag_name); $res['slug'] = $obj->zbstag_slug; $res['created'] = $obj->zbstag_created; $res['lastupdated'] = $obj->zbstag_lastupdated; } return $res; } /** * tidy's the object from wp db into clean array * * @param array $obj (DB obj) * * @return array (clean obj) */ private function tidy_tagstat($obj=false){ $res = false; if (isset($obj->ID)){ $res = array(); $res['count'] = $obj->c; $res['objtypeid'] = $obj->zbstl_objtype; $res['objtype'] = $this->objTypeKey($obj->zbstl_objtype); } return $res; } // =========== / TAGS ======================================================= // =============================================================================== // =============================================================================== // =========== TAG LINKS ======================================================= /** * returns tags against an obj type (e.g. contact tags) * * @param array $args Associative array of arguments * objtypeid * * @return array result */ public function getTagsForObjType($args=array()){ #} =========== LOAD ARGS ============== $defaultArgs = array( 'objtypeid' => -1, // select 'excludeEmpty' => -1, 'excludeIDs' => -1, // if is an array of tag id's will exclude these :) // with 'withCount' => -1, // sort 'sortByField' => 'zbstag_name', 'sortOrder' => 'ASC', 'page' => 0, // this is what page it is (gets * by for limit) 'perPage' => 10000 // permissions //'ignoreowner' => false // this'll let you not-check the owner of obj // NOTE 'owner' will ALWAYS be ignored by this, but allows for team/site // Tags don't need owners yet :) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= $ignoreowner = true; #} Check ID $objtypeid = (int)$objtypeid; if (!empty($objtypeid) && $objtypeid > 0){ global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); #} ============ EXTRA SELECT ============== $extraSelect = ''; if ($withCount !== -1 || $excludeEmpty !== -1) { // could make this distinct zbstl_objid if need more precision // NOTE! Ownership leak here - this'll count GLOBALLY! todo: add ownership into this subquery $extraSelect = ',(SELECT COUNT(taglink.ID) FROM '.$ZBSCRM_t['taglinks'].' taglink WHERE zbstl_tagid = tags.ID AND zbstl_objtype = %d) tagcount'; $params[] = $objtypeid; } #} ============ / EXTRA SELECT ============== #} Build query $query = "SELECT tags.*".$extraSelect." FROM ".$ZBSCRM_t['tags'].' tags'; #} ============= WHERE ================ // type id $wheres['zbstag_objtype'] = array('zbstag_objtype','=','%d',$objtypeid); // if exclude empty if ($excludeEmpty){ $wheres['direct'][] = array('(SELECT COUNT(taglink.ID) FROM '.$ZBSCRM_t['taglinks'].' taglink WHERE zbstl_tagid = tags.ID AND zbstl_objtype = %d) > 0',array($objtypeid)); } if (is_array($excludeIDs)){ $checkedExcludedIDs = array(); foreach ($excludeIDs as $potentialID){ $pID = (int)$potentialID; if ($pID > 0 && !in_array($pID, $checkedExcludedIDs)) $checkedExcludedIDs[] = $pID; } if (count($checkedExcludedIDs) > 0){ // add exclude ids query part (okay to directly inject here, as validated ints above.) $wheres['excludedids'] = array('ID','NOT IN','('.implode(',', $checkedExcludedIDs).')'); } } #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort($sortByField,$sortOrder) . $this->buildPaging($page,$perPage); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_results($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret results (Result Set - multi-row) if (isset($potentialRes) && is_array($potentialRes) && count($potentialRes) > 0) { #} Has results, tidy + return foreach ($potentialRes as $resDataLine) { // tidy $resArr = $this->tidy_tag($resDataLine); if ($withCount !== -1){ if (isset($resDataLine->tagcount)) $resArr['count'] = $resDataLine->tagcount; else $resArr['count'] = -1; } $res[] = $resArr; } } return $res; } // / if ID return false; } /** * returns tags against an obj (e.g. contact id 101) * * @param array $args Associative array of arguments * objtypeid, objid * * @return array result */ public function getTagsForObjID($args=array()){ #} =========== LOAD ARGS ============== $defaultArgs = array( 'objtypeid' => -1, 'objid' => -1, // with 'withCount' => -1, 'onlyID' => -1, // permissions //'ignoreowner' => false // this'll let you not-check the owner of obj // NOTE 'owner' will ALWAYS be ignored by this, but allows for team/site // Tags don't need owners yet :) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= $ignoreowner = true; #} Check ID $objtypeid = (int)$objtypeid; $objid = (int)$objid; if (!empty($objtypeid) && $objtypeid > 0 && !empty($objid) && $objid > 0){ global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); #} Build query $query = "SELECT * FROM ".$ZBSCRM_t['tags']; #} ============= WHERE ================ #} Add ID // rather than using the $wheres, here we have to manually add, because sub queries don't work otherwise. $whereStr = ' WHERE ID in (SELECT zbstl_tagid FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = %d)'; $params[] = $objtypeid; $params[] = $objid; #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort('ID','DESC') . $this->buildPaging(0,10000); //echo $query; print_r($params); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_results($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret results (Result Set - multi-row) if (isset($potentialRes) && is_array($potentialRes) && count($potentialRes) > 0) { #} Has results, tidy + return foreach ($potentialRes as $resDataLine) { #} Only ID? return it directly if ($onlyID === true) $resObj = $resDataLine->ID; else // tidy $resObj = $this->tidy_tag($resDataLine); if ($withCount){ } $res[] = $resObj; } } return $res; } // / if ID return false; } /** * adds or updates a tag link object * this says "match tag X with obj Y" (effectively 'tagging' it) * NOTE: DO NOT CALL DIRECTLY, ALWAYS use addUpdateTagObjLinks (or it's wrappers) - because those fire actions :) * * @param array $args Associative array of arguments * id (if update - probably never used here), data(objtype,objid,tagid) * * @return int line ID */ public function addUpdateTagObjLink($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'owner' => -1, // fields (directly) 'data' => array( 'objtype' => -1, 'objid' => -1, 'tagid' => -1 ) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ // check obtype is completed + legit if (!isset($data['objtype']) || empty($data['objtype'])) return false; if ($this->objTypeKey($data['objtype']) === -1) return false; // if owner = -1, add current if (!isset($owner) || $owner === -1) $owner = zeroBSCRM_user(); $objid = (int)$data['objid']; $tagid = (int)$data['tagid']; if (empty($data['objid']) || $data['objid'] < 1 || empty($data['tagid']) || $data['tagid'] < 1) return false; #} ========= / CHECK FIELDS =========== #} Check if ID present $id = (int)$id; if (!empty($id) && $id > 0){ #} Check if obj exists (here) - for now just brutal update (will error when doesn't exist) #} Attempt update if ($wpdb->update( $ZBSCRM_t['taglinks'], array( // ownership // no need to update these (as of yet) - can't move teams etc. //'zbs_site' => zeroBSCRM_installSite(), //'zbs_team' => zeroBSCRM_installTeam(), 'zbs_owner' => $owner, // fields 'zbstl_objtype' => $data['objtype'], 'zbstl_objid' => $data['objid'], 'zbstl_tagid' => $data['tagid'] ), array( // where 'ID' => $id ), array( // field data types '%d', '%d', '%d', '%d' ), array( // where data types '%d' )) !== false){ // Successfully updated - Return id return $id; } else { // FAILED update return false; } } else { #} No ID - must be an INSERT if ($wpdb->insert( $ZBSCRM_t['taglinks'], array( // ownership 'zbs_site' => zeroBSCRM_site(), 'zbs_team' => zeroBSCRM_team(), 'zbs_owner' => $owner, // fields 'zbstl_objtype' => $data['objtype'], 'zbstl_objid' => $data['objid'], 'zbstl_tagid' => $data['tagid'] ), array( // field data types '%d', // site '%d', // team '%d', // owner '%d', '%d', '%d' ) ) > 0){ #} Successfully inserted, lets return new ID $newID = $wpdb->insert_id; return $newID; } else { #} Failed to Insert return false; } } return false; } /** * adds or updates tag link objects against an obj * this says "match tag X,Y,Z with obj Y" (effectively 'tagging' it) * * @param array $args Associative array of arguments * objtype,objid,tags (array of tagids) * * @return array $tags */ public function addUpdateTagObjLinks($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'owner' => -1, 'objtype' => -1, 'objid' => -1, 'tagIDs' => -1, // array of tag ID's 'mode' => 'replace' // replace|append|remove ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ // check obtype is completed + legit if (!isset($objtype) || empty($objtype)) return false; if ($this->objTypeKey($objtype) === -1) return false; // if owner = -1, add current if (!isset($owner) || $owner === -1) $owner = zeroBSCRM_user(); // tagging id $objid = (int)$objid; if (empty($objid) || $objid < 1) return false; // tag list if (!is_array($tagIDs)) return false; // mode if (gettype($mode) != 'string' || !in_array($mode, array('replace','append','remove'))) return false; #} ========= / CHECK FIELDS =========== switch ($mode){ case 'replace': // (for actions) log starting objs $existingTagIDs = $this->getTagsForObjID(array('objtypeid'=>$objtype,'objid'=>$objid,'onlyID'=>true)); if (!is_array($existingTagIDs)) $existingTagIDs = array(); $removedTagsByID = array(); $addedTagsByID = array(); // cull all previous $deleted = $this->deleteTagObjLinks(array('objid'=>$objid,'objtype'=>$objtype)); // cycle through & add foreach ($tagIDs as $tid){ $added = $this->addUpdateTagObjLink(array( 'data'=>array( 'objid' => $objid, 'objtype' => $objtype, 'tagid' => $tid))); if ($added !== false){ if (!in_array($tid, $existingTagIDs)) $addedTagsByID[] = $tid; // tag was added //else // tag was already in there, just re-added } } // actions // check removed foreach ($existingTagIDs as $tid){ if (!in_array($tid, $tagIDs)) $removedTagsByID[] = $tid; } // fire actions for each tag // added to if (count($addedTagsByID) > 0) foreach ($addedTagsByID as $tagID) do_action('zbs_tag_added_to_objid',$tagID, $objtype, $objid); // removed from if (count($removedTagsByID) > 0) foreach ($removedTagsByID as $tagID) do_action('zbs_tag_removed_from_objid',$tagID, $objtype, $objid); // return return true; break; case 'append': // get existing $existingTagIDs = $this->getTagsForObjID(array('objtypeid'=>$objtype,'objid'=>$objid,'onlyID'=>true)); // make just ids // no need, added ,'onlyID'=>true above //$existingTagIDs = array(); foreach ($tags as $t) $existingTagIDs[] = $t['id']; // cycle through& add foreach ($tagIDs as $tid){ if (!in_array($tid,$existingTagIDs)){ // add a link $this->addUpdateTagObjLink(array( 'data'=>array( 'objid' => $objid, 'objtype' => $objtype, 'tagid' => $tid))); // fire action do_action('zbs_tag_added_to_objid',$tid, $objtype, $objid); } } $this->compile_segments_from_tagIDs( $tagIDs, $owner ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase,VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable return true; break; case 'remove': // get existing $existingTagIDs = $this->getTagsForObjID(array('objtypeid'=>$objtype,'objid'=>$objid,'onlyID'=>true)); // cycle through & remove links foreach ($tagIDs as $tid){ if (in_array($tid, $existingTagIDs)){ // delete link $this->deleteTagObjLink(array( 'objid' => $objid, 'objtype' => $objtype, 'tagid' => $tid)); // action do_action('zbs_tag_removed_from_objid',$tid, $objtype, $objid); } } $this->compile_segments_from_tagIDs( $tagIDs, $owner ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase,VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable return true; break; } return false; } /** * Compiles segments based on an array of given tag IDs * * @param array $tagIDs An array of tag IDs. * @param ID $owner An ID representing the owner of the current tagID. */ public function compile_segments_from_tagIDs( $tagIDs, $owner ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase global $zbs; $segments = $zbs->DAL->segments->getSegments( $owner, 1000, 0, true ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase foreach ( $segments as $segment ) { foreach ( $segment['conditions'] as $condition ) { if ( $condition['type'] === 'tagged' && in_array( $condition['value'], $tagIDs ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase,WordPress.PHP.StrictInArray.MissingTrueStrict $zbs->DAL->segments->compileSegment( $segment['id'] ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase } } } } /** * deletes a tag object link * * @param array $args Associative array of arguments * id * * @return int success; */ public function deleteTagObjLink($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, // or... 'objtype' => -1, 'objid' => -1, 'tagid' => -1 ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} Check ID & Delete :) (IF ID PRESENT) $id = (int)$id; if ( $id > 0 ) { return zeroBSCRM_db2_deleteGeneric($id,'taglinks'); } #} ... else delete by objtype etc. #} ========== CHECK FIELDS ============ // check obtype is completed + legit if (!isset($objtype) || empty($objtype)) return false; if ($this->objTypeKey($objtype) === -1) return false; // obj id $objid = (int)$objid; if (empty($objid) || $objid < 1) return false; // tag id $tagid = (int)$tagid; if (empty($tagid) || $tagid < 1) return false; // CHECK PERMISSIONS? #} ========= / CHECK FIELDS =========== #} ... if here then is trying to delete specific tag linkid return $wpdb->delete( $ZBSCRM_t['taglinks'], array( // where 'zbstl_objtype' => $objtype, 'zbstl_objid' => $objid, 'zbstl_tagid' => $tagid ), array( '%d', '%d', '%d' ) ); } /** * deletes all tag object links for a specific obj * * @param array $args Associative array of arguments * id * * @return int success; */ public function deleteTagObjLinks($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'objtype' => -1, 'objid' => -1, ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ // check obtype is completed + legit if (!isset($objtype) || empty($objtype)) return false; if ($this->objTypeKey($objtype) === -1) return false; // obj id $objid = (int)$objid; if (empty($objid) || $objid < 1) return false; // CHECK PERMISSIONS? #} ========= / CHECK FIELDS =========== // brutal return $wpdb->delete( $ZBSCRM_t['taglinks'], array( // where 'zbstl_objtype' => $objtype, 'zbstl_objid' => $objid ), array( '%d', '%d' ) ); } /** * tidy's the object from wp db into clean array * * @param array $obj (DB obj) * * @return array (clean obj) */ private function tidy_taglink($obj=false){ $res = false; if (isset($obj->ID)){ $res = array(); $res['id'] = $obj->ID; /* `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, */ $res['objtype'] = $obj->zbstag_objtype; $res['name'] = $this->stripSlashes($obj->zbstag_name); $res['slug'] = $obj->zbstag_slug; $res['created'] = $obj->zbstag_created; $res['lastupdated'] = $obj->zbstag_lastupdated; } return $res; } // =========== / TAG LINKS ================================================== // =============================================================================== // =============================================================================== // =========== CUSTOM FIELDS ================================================= /** * returns true if field key exists as custom field for CONTACT * * @param array $args Associative array of arguments * objtypeid * * @return array of customfield field keys */ public function isActiveCustomField_Contact($customFieldKey=''){ #} These are simply stored in settings with a key of customfields_objtype e.g. customfields_contact if (!empty($objtypeid) && $objtypeid > 0 && !empty($customFieldKey)) { // get custom fields $customFields = $this->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_CONTACT)); // validate there if (is_array($customFields)) foreach ($customFields as $cfK => $cfV){ if ($cfK == $customFieldKey) return true; } } return false; } /** * returns true if field key exists as custom field for obj * * @param array $args Associative array of arguments * objtypeid * * @return array of customfield field keys */ public function isActiveCustomField($args=array()){ #} ============ LOAD ARGS ============= $defaultArgs = array( 'objtypeid' => -1, 'customFieldKey' => '' ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} These are simply stored in settings with a key of customfields_objtype e.g. customfields_contact if (!empty($objtypeid) && $objtypeid > 0 && !empty($customFieldKey)) { // get custom fields $customFields = $this->getActiveCustomFields(array('objtypeid'=>$objtypeid)); // validate there if (is_array($customFields)) foreach ($customFields as $cfK => $cfV){ if ($cfK == $customFieldKey) return true; } } return false; } /** * returns active custom field keys for an obj type * * @param array $args Associative array of arguments * objtypeid * * @return array of customfield field keys */ public function getActiveCustomFields( $args=array() ){ #} ============ LOAD ARGS ============= $defaultArgs = array( // object type id 'objtypeid' => -1, // whether or not to accept cached variant. // Added in gh-2019, we often recall this function on one load, this allows us to accept a once-loaded version 'accept_cached' => true, ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} These are simply stored in settings with a key of customfields_objtype e.g. customfields_contact if (!empty($objtypeid) && $objtypeid > 0) { // retrieve return $this->setting( 'customfields_'.$this->objTypeKey( $objtypeid ), array(), $accept_cached ); } return array(); } /** * updates active custom field keys for an obj type * No checking whatsoever * * @param array $args Associative array of arguments * objtypeid * * @return array of customfield field keys */ public function updateActiveCustomFields($args=array()){ #} ============ LOAD ARGS ============= $defaultArgs = array( 'objtypeid' => -1, 'fields' => array() ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} These are simply stored in settings with a key of customfields_objtype e.g. customfields_contact if (!empty($objtypeid) && $objtypeid > 0) { return $this->updateSetting('customfields_'.$this->objTypeKey($objtypeid),$fields); } return array(); } /** * returns scalar value of 1 custom field line (or it's ID) * ... real custom fields will be got as part of getCustomers more commonly (this is for 1 alone) * * @param array $args Associative array of arguments * objtypeid,objid,objkey * * @return array result */ public function getCustomFieldVal($args=array()){ #} =========== LOAD ARGS ============== $defaultArgs = array( 'objtypeid' => -1, // e.g. 1 = contact 'objid' => -1, // e.g. contact #101 'objkey' => '', // e.g. notes // permissions 'ignoreowner' => false, // this'll let you not-check the owner of obj // returns scalar ID of line 'onlyID' => false ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} Check IDs $objtypeid = (int)$objtypeid; $objid = (int)$objid; if (!empty($objtypeid) && $objtypeid > 0 && !empty($objid) && $objid > 0 && !empty($objkey)){ global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); #} Build query $query = "SELECT ID,zbscf_objval FROM ".$ZBSCRM_t['customfields']; #} ============= WHERE ================ #} Add obj type $wheres['zbscf_objtype'] = array('zbscf_objtype','=','%d',$objtypeid); #} Add obj ID $wheres['zbscf_objid'] = array('zbscf_objid','=','%d',$objid); #} Add obj key $wheres['zbscf_objkey'] = array('zbscf_objkey','=','%s',$objkey); #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort('ID','DESC') . $this->buildPaging(0,1); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_row($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret Results (ROW) if (isset($potentialRes) && isset($potentialRes->ID)) { #} Has results, tidy + return #} Only ID? return it directly if ($onlyID === true) return $potentialRes->ID; // tidy $res = $this->tidy_customfieldvalSingular($potentialRes); return $res; } } // / if ID return false; } /** * adds or updates a customfield object * NOTE: because these are specific to unique ID of obj, there's no need for site/team etc. here * * @param array $args Associative array of arguments * id (if update), owner, data (array of field data) * * @return int line ID */ public function addUpdateCustomField($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, // Custom field line ID (not obj id!) 'owner' => -1, // fields (directly) 'data' => array( 'objtype' => -1, 'objid' => -1, 'objkey' => '', 'objval' => 'NULL' ) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ $id = (int)$id; if (isset($data['objid'])) $data['objid'] = (int)$data['objid']; if (isset($data['objtype'])) $data['objtype'] = (int)$data['objtype']; // check obtype is completed + legit if (!isset($data['objtype']) || empty($data['objtype'])) return false; if ($this->objTypeKey($data['objtype']) === -1) return false; // check key + ID present if (!isset($data['objkey']) || empty($data['objkey'])) return false; if (!isset($data['objid']) || $data['objid'] <= 0) return false; // if owner = -1, add current if (!isset($owner) || $owner === -1) $owner = zeroBSCRM_user(); // ID finder - if obj id + key + val + typeid provided, check CF not already present (if so overwrite) if ((empty($id) || $id <= 0) && (isset($data['objtype']) && !empty($data['objtype'])) && (isset($data['objid']) && !empty($data['objid'])) && (isset($data['objkey']) && !empty($data['objkey']))) { // check existence + return ID $potentialID = (int)$this->getCustomFieldVal(array( 'objtypeid' => $data['objtype'], 'objid' => $data['objid'], 'objkey' => $data['objkey'], 'onlyID' => true, 'ignoreowner' => true )); // override empty ID if (!empty($potentialID) && $potentialID > 0) $id = $potentialID; } // handle radio, select, and checkbox fields if( is_array( $data['objval'] ) ) { $data['objval'] = implode( ',', $data['objval'] ); } #} ========= / CHECK FIELDS =========== #} Check if ID present if (!empty($id) && $id > 0){ #} Check if obj exists (here) - for now just brutal update (will error when doesn't exist) #} Attempt update if ($wpdb->update( $ZBSCRM_t['customfields'], array( // ownership // no need to update these (as of yet) - can't move teams etc. //'zbs_site' => zeroBSCRM_installSite(), //'zbs_team' => zeroBSCRM_installTeam(), 'zbs_owner' => $owner, // fields 'zbscf_objtype' => $data['objtype'], 'zbscf_objid' => $data['objid'], 'zbscf_objkey' => $data['objkey'], 'zbscf_objval' => $data['objval'], //'zbscf_created' => time(), 'zbscf_lastupdated' => time() ), array( // where 'ID' => $id ), array( // field data types //'%d', // site //'%d', // team '%d', // owner '%d', '%d', '%s', '%s', '%d' // last updated ), array( // where data types '%d' )) !== false){ // Successfully updated - Return id return $id; } else { // FAILED update return false; } } else { #} No ID - must be an INSERT if ($wpdb->insert( $ZBSCRM_t['customfields'], array( // ownership 'zbs_site' => zeroBSCRM_site(), 'zbs_team' => zeroBSCRM_team(), 'zbs_owner' => $owner, // fields 'zbscf_objtype' => $data['objtype'], 'zbscf_objid' => $data['objid'], 'zbscf_objkey' => $data['objkey'], 'zbscf_objval' => $data['objval'], 'zbscf_created' => time(), 'zbscf_lastupdated' => time() ), array( // field data types '%d', // site '%d', // team '%d', // owner '%d', '%d', '%s', '%s', '%d', '%d' ) ) > 0){ #} Successfully inserted, lets return new ID $newID = $wpdb->insert_id; return $newID; } else { #} Failed to Insert return false; } } return false; } /** * deletes a customfield object * * @param array $args Associative array of arguments * id * * @return int success; */ public function deleteCustomField($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1 ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} Check ID & Delete :) $id = (int)$id; return zeroBSCRM_db2_deleteGeneric( $id, 'customfields' ); } /** * tidy's the object from wp db into clean array * * @param array $obj (DB obj) * * @return array (clean obj) */ private function tidy_customfieldvalSingular($obj=false){ $res = false; if (isset($obj->ID)){ // just return the value here! $res = $this->stripSlashes($obj->zbscf_objval); } return $res; } // =========== / CUSTOM FIELDS =============================================== // =============================================================================== // =============================================================================== // =========== EXTERNAL SOURCES =============================================== /** * returns first external source line +- details * * @param int id tag id * @param array $args Associative array of arguments * withStats * * @return array result */ public function getExternalSource( $id=-1, $args=array() ){ #} =========== LOAD ARGS ============== $defaultArgs = array( // Alternative search criteria to ID :) // .. LEAVE blank if using ID //'contactID' => -1, // NOTE: This only returns the FIRST source, if using multiple sources, use getExternalSourcesForContact 'objectID' => -1, 'objectType' => -1, 'source' => -1, // Optional, if used with contact ID will return 1 line :D 'origin' => '', // Optional // permissions 'ignoreowner' => true, // this'll let you not-check the owner of obj // returns scalar ID of line 'onlyID' => false ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} ========== CHECK FIELDS ============ $id = (int)$id; $objectID = (int)$objectID; $objectType = (int)$objectType; #} ========= / CHECK FIELDS =========== #} Check ID or name/type if ( $objectType > 0 && ( (!empty($id) && $id > 0) || (!empty($objectID) && $objectID > 0) ) ){ global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); #} Build query $query = "SELECT * FROM ".$ZBSCRM_t['externalsources']; #} ============= WHERE ================ // Line ID if (!empty($id) && $id > 0) { $wheres['ID'] = array('ID','=','%d',$id); } // Object ID if (!empty($objectID) && $objectID > 0) { $wheres['zbss_objid'] = array( 'zbss_objid', '=', '%d', $objectID ); } // Object Type if (!empty($objectType) && $objectType > 0) { $wheres['zbss_objtype'] = array( 'zbss_objtype', '=', '%d', $objectType ); } // Source if (!empty($source) && $source !== -1) { $wheres['zbss_source'] = array( 'zbss_source', '=', '%s', $source ); } // Origin if ( !empty( $origin ) ) { $wheres['zbss_origin'] = array( 'zbss_origin', '=', '%s', $origin ); } #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort('ID','DESC') . $this->buildPaging(0,1); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_row($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret Results (ROW) if (isset($potentialRes) && isset($potentialRes->ID)) { #} Has results, tidy + return #} Only ID? return it directly if ($onlyID === true) return $potentialRes->ID; // tidy $res = $this->tidy_externalsource($potentialRes); return $res; } } // / if ID return false; } /** * returns multiple external source line +- details * * @param int id tag id * @param array $args Associative array of arguments * withStats * * @return array results */ public function getExternalSources($id=-1,$args=array()){ #} =========== LOAD ARGS ============== $defaultArgs = array( 'objectID' => -1, 'objectType' => -1, 'grouped_by_source' => false, // if true, will return array organised by source (e.g. array('woo'=>array({woosources}))) // permissions 'ignoreowner' => true, // this'll let you not-check the owner of obj ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} ========== CHECK FIELDS ============ $id = (int)$id; $objectID = (int)$objectID; $objectType = (int)$objectType; #} ========= / CHECK FIELDS =========== #} Check ID or name/type if ( $objectType > 0 && ( (!empty($id) && $id > 0) || (!empty($objectID) && $objectID > 0) ) ){ global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); #} Build query $query = "SELECT * FROM ".$ZBSCRM_t['externalsources']; #} ============= WHERE ================ #} Add ID if (!empty($id) && $id > 0) $wheres['ID'] = array('ID','=','%d',$id); #} zbss_objid if (!empty($objectID) && $objectID > 0) $wheres['zbss_objid'] = array('zbss_objid','=','%d',$objectID); #} zbss_objid if (!empty($objectType) && $objectType > 0) $wheres['zbss_objtype'] = array('zbss_objtype','=','%d',$objectType); #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort('ID','DESC') . $this->buildPaging(0,1000); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_results($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } $res = array(); #} Interpret results (Result Set - multi-row) if (isset($potentialRes) && is_array($potentialRes) && count($potentialRes) > 0) { #} Has results, tidy + return foreach ( $potentialRes as $data_line ){ // default simple array if ( !$grouped_by_source ){ // tidy $res[] = $this->tidy_externalsource( $data_line ); } else { $tidied_line = $this->tidy_externalsource( $data_line ); // grouped by source adds another dimension to array, keyed by source (e.g. 'woo') if ( !isset( $res[ $tidied_line['source'] ] ) ){ $res[ $tidied_line['source'] ] = array(); } $res[ $tidied_line['source'] ][] = $tidied_line; } } } return $res; } // / if ID return false; } /** * adds or updates an external source object * * @param array $args Associative array of arguments * * @return int line ID */ public function addUpdateExternalSource($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, // fields (directly) 'data' => array( 'objectType' => -1, 'objectID' => -1, 'source' => '', 'uid' => '', 'origin' => '', 'owner' => 0 // -1 for current user, for now, disregard owenship for ext sources ) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ $id = (int)$id; // objectType if (!isset($data['objectType']) || $data['objectType'] <= 0) return false; // objectID if (!isset($data['objectID']) || $data['objectID'] <= 0) return false; // if owner = -1, add current if (!isset($data['owner']) || $data['owner'] === -1) $data['owner'] = zeroBSCRM_user(); // check name present + legit if (!isset($data['source']) || empty($data['source'])) return false; // extsource ID finder - if obj source + cid provided, check not already present (if so overwrite) // keeps unique... if ((empty($id) || $id <= 0) && ( (isset($data['objectType']) && !empty($data['objectType'])) || (isset($data['objectID']) && !empty($data['objectID'])) || (isset($data['source']) && !empty($data['source'])) )) { $args = array( 'objectType' => $data['objectType'], 'objectID' => $data['objectID'], 'source' => $data['source'], 'onlyID' => true ); // check by source + cid // check existence + return ID $potentialID = (int)$this->getExternalSource( -1, $args ); // override empty ID if (!empty($potentialID) && $potentialID > 0) $id = $potentialID; } #} ========= / CHECK FIELDS =========== #} Check if ID present $id = (int)$id; if (!empty($id) && $id > 0){ #} Check if obj exists (here) - for now just brutal update (will error when doesn't exist) #} Attempt update if ($wpdb->update( $ZBSCRM_t['externalsources'], array( // ownership // no need to update these (as of yet) - can't move teams etc. //'zbs_site' => zeroBSCRM_installSite(), //'zbs_team' => zeroBSCRM_installTeam(), 'zbs_owner' => $data['owner'], // fields 'zbss_objid' => $data['objectID'], 'zbss_objtype' => $data['objectType'], 'zbss_source' => $data['source'], 'zbss_uid' => $data['uid'], 'zbss_origin' => $data['origin'], 'zbss_lastupdated' => time() ), array( // where 'ID' => $id ), array( // field data types '%d', '%d', '%d', '%s', '%s', '%s', '%d' ), array( // where data types '%d' )) !== false){ // Successfully updated - Return id return $id; } else { // FAILED update return false; } } else { #} No ID - must be an INSERT if ($wpdb->insert( $ZBSCRM_t['externalsources'], array( // ownership 'zbs_site' => zeroBSCRM_site(), 'zbs_team' => zeroBSCRM_team(), 'zbs_owner' => $data['owner'], // fields 'zbss_objid' => $data['objectID'], 'zbss_objtype' => $data['objectType'], 'zbss_source' => $data['source'], 'zbss_uid' => $data['uid'], 'zbss_origin' => $data['origin'], 'zbss_created' => time(), 'zbss_lastupdated' => time() ), array( // field data types '%d', // site '%d', // team '%d', // owner '%d', '%d', '%s', '%s', '%s', '%d', '%d' ) ) > 0){ #} Successfully inserted, lets return new ID $newID = $wpdb->insert_id; return $newID; } else { #} Failed to Insert return false; } } return false; } /** * adds or updates an object's external sources * * @param array $args Associative array of arguments * * @return bool success */ public function addUpdateExternalSources( $args = array() ) { // ============ LOAD ARGS ============= $defaultArgs = array( 'obj_id' => -1, 'obj_type_id' => -1, 'external_sources' => array(), ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } // =========== / LOAD ARGS ============ $obj_id = (int)$obj_id; $obj_type_id = (int)$obj_type_id; if ( !is_array( $external_sources ) ) { return ''; } $approvedExternalSource = ''; // for IA foreach ( $external_sources as $es ) { $external_source_id = isset( $es['id'] ) ? $es['id'] : -1; $origin = isset( $es['origin'] ) ? $es['origin'] : null; $external_source_id = $this->addUpdateExternalSource( array( 'id' => $external_source_id, // fields (directly) 'data' => array( 'objectID' => $obj_id, 'objectType' => $obj_type_id, 'source' => $es['source'], 'origin' => $origin, 'uid' => $es['uid'], ), ) ); $approvedExternalSource = array( 'id' => $external_source_id, 'objID' => $obj_id, 'objType' => $obj_type_id, 'source' => $es['source'], 'origin' => $origin, 'uid' => $es['uid'], ); } // / each ext source // this is a bit hackish, but allows DRY code without a refactor return $approvedExternalSource; } /** * deletes an external source object * * @param array $args Associative array of arguments * id * * @return int success; */ public function deleteExternalSource($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1 ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} Check ID & Delete :) $id = (int)$id; return zeroBSCRM_db2_deleteGeneric( $id, 'externalsources' ); } /** * deletes all external source lines for a specific obj * * @param array $args Associative array of arguments * id * * @return int success; */ public function delete_external_sources( $args = array() ){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'obj_type' => -1, 'obj_id' => -1, 'obj_source' => 'all', // 'all' = every source ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ // checks if ( empty( $obj_type ) || $this->objTypeKey( $obj_type ) === -1) { return false; } if ( empty( $obj_id ) ){ return false; } #} ========= / CHECK FIELDS =========== // basics $where = array( // where 'zbss_objtype' => $obj_type, 'zbss_objid' => $obj_id ); $whereFormat = array( // where '%d', '%d' ); // add source if passed add where clause for it (can delete just for a particular source) if ( $obj_source !== 'all' ){ $where['zbss_source'] = $obj_source; $whereFormat[] = '%s'; } // brutal return $wpdb->delete( $ZBSCRM_t['externalsources'], $where, $whereFormat); } /** * tidy's the object from wp db into clean array * * @param array $obj (DB obj) * * @return array (clean obj) */ public function tidy_externalsource($obj=false){ $res = false; if (isset($obj->ID)){ $res = array(); $res['id'] = $obj->ID; /* `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, */ $res['objid'] = $obj->zbss_objid; $res['objtype'] = $obj->zbss_objtype; $res['source'] = $obj->zbss_source; $res['uid'] = $this->stripSlashes( $obj->zbss_uid ); $res['origin'] = $this->stripSlashes( $obj->zbss_origin ); $res['created'] = $obj->zbss_created; $res['lastupdated'] = $obj->zbss_lastupdated; } return $res; } /** * Returns a clean domain origin string for use with external sources, where possible * * @return string|bool(false) - tidied up domain origin, or false */ public function clean_external_source_domain_string( $domain ){ // clean it up a bit $origin = str_replace( array( 'https://', 'http://' ), '', $domain ); $origin = rtrim( $origin, "/" ); // prefix it for later querying if ( !empty( $origin ) ){ return $origin; } return false; } // =========== / External Sources =========================================== // =============================================================================== // =============================================================================== // =========== Origin Helpers ============================================== // To start with these will help store origin strings for external sources in a // machine-readable format /** * Returns a prefixed origin string * (Currently only origins stored are domains) * * @param string $string - string to prefix * @param string $origin_type - a type of origin record * * @return string|bool(false) - prefixed origin string, or false */ public function add_origin_prefix( $string, $origin_type ){ switch ( $origin_type ){ case 'domain': return $this->prefix_domain . $string; break; } return false; } /** * Returns a de-prefixed origin string * * @param string $string - string to prefix * * @return string|bool(false) - deprefixed origin string, or false */ public function remove_origin_prefix( $string ){ // split at first : $split_point = strpos( $string, ':' ); if ( $split_point ){ return substr( $string, $split_point+1 ); } return false; } /** * Returns an origin string and type from a prefixed origin string * * @param string $string Prefixed origin string. * * @return array|bool(false) - origin string and type, or false */ public function hydrate_origin( $string ) { // domain if ( str_starts_with( $string, 'd:' ) ) { return array( 'origin' => $this->remove_origin_prefix( $string ), 'origin_type' => 'domain', ); } return false; } // =========== / Origin Helpers ============================================= // =============================================================================== // =============================================================================== // =========== Web Tracking (UTM etc.) ======================================== /** * returns full tracking line +- details * * @param int id tag id * @param array $args Associative array of arguments * withStats * * @return array result */ public function getTracking($id=-1,$args=array()){ #} =========== LOAD ARGS ============== $defaultArgs = array( // permissions 'ignoreowner' => false, // this'll let you not-check the owner of obj // returns scalar ID of line 'onlyID' => false ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} ========== CHECK FIELDS ============ $id = (int)$id; #} ========= / CHECK FIELDS =========== #} Check ID or name/type if (!empty($id) && $id > 0){ global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); #} Build query $query = "SELECT * FROM ".$ZBSCRM_t['tracking']; #} ============= WHERE ================ #} Add ID if (!empty($id) && $id > 0) $wheres['ID'] = array('ID','=','%d',$id); #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort('ID','DESC') . $this->buildPaging(0,1); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_row($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret Results (ROW) if (isset($potentialRes) && isset($potentialRes->ID)) { #} Has results, tidy + return #} Only ID? return it directly if ($onlyID === true) return $potentialRes->ID; // tidy $res = $this->tidy_tracking($potentialRes); return $res; } } // / if ID return false; } /** * adds or updates a tracking object * * @param array $args Associative array of arguments * * @return int line ID */ public function addUpdateTracking($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, // fields (directly) 'data' => array( 'contactID' => -1, 'action' => '', 'action_detail' => '', 'referrer' => '', 'utm_source' => '', 'utm_medium' => '', 'utm_name' => '', 'utm_term' => '', 'utm_content' => '', 'owner' => -1 ) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ $id = (int)$id; // contactID if (!isset($data['contactID']) || $data['contactID'] <= 0) return false; // if owner = -1, add current if (!isset($data['owner']) || $data['owner'] === -1) $data['owner'] = zeroBSCRM_user(); // check action present + legit if (!isset($data['action']) || empty($data['action'])) return false; #} ========= / CHECK FIELDS =========== #} Check if ID present $id = (int)$id; if (!empty($id) && $id > 0){ #} Check if obj exists (here) - for now just brutal update (will error when doesn't exist) #} Attempt update if ($wpdb->update( $ZBSCRM_t['tracking'], array( // ownership // no need to update these (as of yet) - can't move teams etc. //'zbs_site' => zeroBSCRM_installSite(), //'zbs_team' => zeroBSCRM_installTeam(), 'zbs_owner' => $data['owner'], // fields 'zbst_contactid' => $data['contactID'], 'zbst_action' => $data['action'], 'zbst_action_detail' => $data['action_detail'], 'zbst_referrer' => $data['referrer'], 'zbst_utm_source' => $data['utm_source'], 'zbst_utm_medium' => $data['utm_medium'], 'zbst_utm_name' => $data['utm_name'], 'zbst_utm_term' => $data['utm_term'], 'zbst_utm_content' => $data['utm_content'], 'zbst_lastupdated' => time() ), array( // where 'ID' => $id ), array( // field data types '%d', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ), array( // where data types '%d' )) !== false){ // Successfully updated - Return id return $id; } else { // FAILED update return false; } } else { #} No ID - must be an INSERT if ($wpdb->insert( $ZBSCRM_t['tracking'], array( // ownership 'zbs_site' => zeroBSCRM_site(), 'zbs_team' => zeroBSCRM_team(), 'zbs_owner' => $data['owner'], // fields 'zbst_contactid' => $data['contactID'], 'zbst_action' => $data['action'], 'zbst_action_detail' => $data['action_detail'], 'zbst_referrer' => $data['referrer'], 'zbst_utm_source' => $data['utm_source'], 'zbst_utm_medium' => $data['utm_medium'], 'zbst_utm_name' => $data['utm_name'], 'zbst_utm_term' => $data['utm_term'], 'zbst_utm_content' => $data['utm_content'], 'zbst_created' => time(), 'zbst_lastupdated' => time() ), array( // field data types '%d', // site '%d', // team '%d', // owner '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%d' ) ) > 0){ #} Successfully inserted, lets return new ID $newID = $wpdb->insert_id; return $newID; } else { #} Failed to Insert return false; } } return false; } /** * deletes a tracking object * * @param array $args Associative array of arguments * id * * @return int success; */ public function deleteTracking($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1 ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} Check ID & Delete :) $id = (int)$id; return zeroBSCRM_db2_deleteGeneric( $id, 'tracking' ); } /** * tidy's the object from wp db into clean array * * @param array $obj (DB obj) * * @return array (clean obj) */ private function tidy_tracking($obj=false){ $res = false; if (isset($obj->ID)){ $res = array(); $res['id'] = $obj->ID; /* `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, */ $res['contactid'] = $obj->zbss_contactid; $res['action'] = $obj->zbst_action; $res['action_detail'] = $obj->zbst_action_detail; $res['referrer'] = $obj->zbst_referrer; $res['utm_source'] = $obj->zbst_utm_source; $res['utm_medium'] = $obj->zbst_utm_medium; $res['utm_name'] = $obj->zbst_utm_name; $res['utm_term'] = $obj->zbst_utm_term; $res['utm_content'] = $obj->zbst_utm_content; $res['created'] = $obj->zbst_created; $res['lastupdated'] = $obj->zbst_lastupdated; } return $res; } // =========== / Web Tracking (UTM etc.) ==================================== // =============================================================================== // =============================================================================== // =========== LOGS ========================================================== /** * returns cron log lines * * @param array $args Associative array of arguments * searchPhrase, sortByField, sortOrder, page, perPage * * @return array of tag lines */ public function getCronLogs($args=array()){ // ============ LOAD ARGS ============= $with_notes = true; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $defaultArgs = array( 'job' => '', 'sortByField' => 'ID', // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase 'sortOrder' => 'DESC', // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase 'page' => 0, 'perPage' => 100, // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase 'with_notes' => true, 'ignoreowner' => false, // this'll let you not-check the owner of obj ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} ========== CHECK FIELDS ============ #} ========= / CHECK FIELDS =========== global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); #} Build query $query = "SELECT * FROM ".$ZBSCRM_t['cronmanagerlogs']; #} ============= WHERE ================ #} job if (!empty($job) && $job > 0) $wheres['job'] = array('job','=','%s',$job); if ( $with_notes ) { $wheres['notes'] = array( 'jobnotes', '<>', '%s', '' ); } #} ============ / WHERE =============== #} Build out any WHERE clauses $wheresArr= $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort($sortByField,$sortOrder) . $this->buildPaging($page,$perPage); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_results($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret results (Result Set - multi-row) if (isset($potentialRes) && is_array($potentialRes) && count($potentialRes) > 0) { #} Has results, tidy + return foreach ($potentialRes as $resDataLine) { // tidy $resArr = $this->tidy_cronlog($resDataLine); $res[] = $resArr; } } return $res; } /** * adds or updates a cron log object * * @param array $args Associative array of arguments * id (not req.), owner (not req.) data -> key/val * * @return int line ID */ public function addUpdateCronLog($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'owner' => -1, // fields (directly) 'data' => array( 'job' => '', 'jobstatus' => -1, 'jobstarted' => -1, 'jobfinished' => -1, 'jobnotes' => '' ) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ $id = (int)$id; // if owner = -1, add current if (!isset($owner) || $owner === -1) $owner = zeroBSCRM_user(); #} ========= / CHECK FIELDS =========== $dataArr = array( // ownership // no need to update these (as of yet) - can't move teams etc. //'zbs_site' => zeroBSCRM_installSite(), //'zbs_team' => zeroBSCRM_installTeam(), 'zbs_owner' => $owner, // fields 'job' => $data['job'], 'jobstatus' => $data['jobstatus'], 'jobstarted' => $data['jobstarted'], 'jobfinished' => $data['jobfinished'], 'jobnotes' => $data['jobnotes'] ); $dataTypes = array( // field data types '%d', '%s', '%d', '%d', '%d', '%s' ); if (isset($id) && !empty($id) && $id > 0){ #} Check if obj exists (here) - for now just brutal update (will error when doesn't exist) #} Attempt update if ($wpdb->update( $ZBSCRM_t['cronmanagerlogs'], $dataArr, array( // where 'ID' => $id ), $dataTypes, array( // where data types '%d' )) !== false){ // Successfully updated - Return id return $id; } else { // FAILED update return false; } } else { // add team etc $dataArr['zbs_site'] = zeroBSCRM_site(); $dataTypes[] = '%d'; $dataArr['zbs_team'] = zeroBSCRM_team(); $dataTypes[] = '%d'; #} No ID - must be an INSERT if ($wpdb->insert( $ZBSCRM_t['cronmanagerlogs'], $dataArr, $dataTypes ) > 0){ #} Successfully inserted, lets return new ID $newID = $wpdb->insert_id; return $newID; } else { #} Failed to Insert return false; } } return false; } /** * deletes a CRON Log object * NOTE! this doesn't yet delete any META! * * @param array $args Associative array of arguments * id * * @return int success; */ public function deleteCronLog($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1 ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} Check ID & Delete :) $id = (int)$id; return zeroBSCRM_db2_deleteGeneric( $id, 'cronmanagerlogs' ); } /** * tidy's the object from wp db into clean array * * @param array $obj (DB obj) * * @return array (clean obj) */ private function tidy_cronlog($obj=false){ $res = false; if (isset($obj->ID)){ $res = array(); $res['id'] = $obj->ID; $res['owner'] = $obj->zbs_owner; $res['job'] = $obj->job; $res['jobstatus'] = $obj->jobstatus; $res['jobstarted'] = $obj->jobstarted; $res['jobfinished'] = $obj->jobfinished; $res['jobnotes'] = $obj->jobnotes; } return $res; } // =========== / CRONLOGS ======================================================= // =============================================================================== // =============================================================================== // ============= GENERIC ======================================================== /** * Wrapper function for emptying tables (use with care) * ... can only truncate tables in our ZBSCRM_t * * @param string $tableKey (refers to ZBSCRM_t global) * * @return result */ public function truncate($tableKey=''){ global $ZBSCRM_t; if (is_string($tableKey) && !empty($tableKey) && isset($ZBSCRM_t[$tableKey])){ global $wpdb; return $wpdb->query("TRUNCATE TABLE `".$ZBSCRM_t[$tableKey]."`"); } return false; } // =========== / GENERIC ======================================================== // =============================================================================== // =============================================================================== // =========== FIELD HELPERS =============================================== /** * Returns a field from an object model if it exists * * @param CRM_TYPE int object_type_id - object type ID * @param string field_key - key of field (e.g. `status`) * * @return bool|array - field type info (as per direct from the object_model) */ public function get_model_field_info( $object_type_id = -1, $field_key = ''){ // valid obj type id and key? if ( $this->isValidObjTypeID( $object_type_id ) && !empty( $field_key ) ){ // get object layer and load object model $object_layer = $this->getObjectLayerByType( $object_type_id ); if ( $object_layer ){ $object_model = $object_layer->objModel( true ); // if set, return if ( is_array( $object_model ) && isset( $object_model[ $field_key ] ) ){ return $object_model[ $field_key ]; } } // as a temporary workaround until we have addresses loaded from DAL3 // check address field presence via global if ( $object_type_id == ZBS_TYPE_ADDRESS ){ // effectively returns $zbsAddressFields: $obj_model_global = $this->get_object_field_global( ZBS_TYPE_ADDRESS ); if ( isset( $obj_model_global[ $field_key ] ) ){ // As an aside, the $potential_field format will be different here // as this takes from the globals model, not the DAL model // ... please bear this in mind if interacting with address fields this way return $obj_model_global[ $field_key ]; } } } return false; } /** * Returns true if a field from an object model exists * * @param CRM_TYPE int object_type_id - object type ID * @param string field_key - key of field (e.g. `status`) * * @return bool - does field exist */ public function does_model_field_exist( $object_type_id = -1, $field_key = ''){ // valid obj type id and key? if ( $this->isValidObjTypeID( $object_type_id ) && !empty( $field_key ) ){ // Check for field existence $potential_field = $this->get_model_field_info( $object_type_id, $field_key ); if ( $potential_field !== false ){ // found it return true; } } return false; } // =========== / FIELD HELPERS =============================================== // =============================================================================== /* ====================================================== / DAL CRUD ====================================================== */ /* ====================================================== Formatters (Generic) ====================================================== */ // legacy signpost, this is now overwritten by DAL->contacts->fullname public function format_fullname( $contactArr=array() ){ return $this->contacts->format_fullname( $contactArr ); } // legacy signpost, this is now overwritten by DAL->[contacts|companies]->format_name_etc public function format_name_etc( $objectArr=array(), $args=array() ){ #} =========== LOAD ARGS ============== $defaultArgs = array( 'incFirstLineAddr' => false, 'incID' => false, 'company' => false, // if true, looks for 'name' not 'fname+lname' ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= if ( !$company ) return $this->contacts->format_name_etc( $objectArr, $args ); else return $this->companies->format_name_etc( $objectArr, $args ); } /** * Returns a formatted address * via getContactFullName this replaces zeroBS_customerAddr in dal1 * NOTE, post v3.0 applies to ANY form of addr. * * @param array $obj (tidied db obj) * * @return string address */ public function format_address($contactArr=array(),$args=array()){ #} =========== LOAD ARGS ============== $defaultArgs = array( 'addrFormat' => 'short', 'delimiter' => ', ', // could use <br> 'secondaddr' => false // if true, use second address (if present in contact_arr) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= $ret = ''; $fieldPrefix = ''; if ($secondaddr) $fieldPrefix = 'sec'; // v3.0 exception, contacts need this prefix for second :/ // attempt to account for that: if ($secondaddr && !isset($contactArr[$fieldPrefix.'addr1']) && isset($contactArr['secaddr_'.'addr1'])) $fieldPrefix = 'secaddr_'; #} Legacy from DAL1: $addrCustomFields = $this->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_ADDRESS)); if ($addrFormat == 'short'){ if (isset($contactArr[$fieldPrefix.'addr1']) && !empty($contactArr[$fieldPrefix.'addr1'])) $ret = $contactArr[$fieldPrefix.'addr1']; if (isset($contactArr[$fieldPrefix.'city']) && !empty($contactArr[$fieldPrefix.'city'])) $ret .= $this->delimiterIf($delimiter,$ret).$contactArr[$fieldPrefix.'city']; } else if ($addrFormat == 'full'){ if (isset($contactArr[$fieldPrefix.'addr1']) && !empty($contactArr[$fieldPrefix.'addr1'])) $ret = $contactArr[$fieldPrefix.'addr1']; if (isset($contactArr[$fieldPrefix.'addr2']) && !empty($contactArr[$fieldPrefix.'addr2'])) $ret .= $this->delimiterIf($delimiter,$ret).$contactArr[$fieldPrefix.'addr2']; if (isset($contactArr[$fieldPrefix.'city']) && !empty($contactArr[$fieldPrefix.'city'])) $ret .= $this->delimiterIf($delimiter,$ret).$contactArr[$fieldPrefix.'city']; if (isset($contactArr[$fieldPrefix.'county']) && !empty($contactArr[$fieldPrefix.'county'])) $ret .= $this->delimiterIf($delimiter,$ret).$contactArr[$fieldPrefix.'county']; if (isset($contactArr[$fieldPrefix.'postcode']) && !empty($contactArr[$fieldPrefix.'postcode'])) $ret .= $this->delimiterIf($delimiter,$ret).$contactArr[$fieldPrefix.'postcode']; if (isset($contactArr[$fieldPrefix.'country']) && !empty($contactArr[$fieldPrefix.'country']) && zeroBSCRM_getSetting('countries') == 1) $ret .= $this->delimiterIf($delimiter,$ret).$contactArr[$fieldPrefix.'country']; // any custom fields here if (is_array($addrCustomFields) && count($addrCustomFields) > 0){ foreach ($addrCustomFields as $cK => $cF){ // v2: //$cKN = (int)$cK+1; //$cKey = $fieldPrefix.'addr_cf'.$cKN; // v3: $cKey = ($secondaddr) ? 'secaddr_'.$cK : 'addr_'.$cK; if (isset($contactArr[$cKey]) && !empty($contactArr[$cKey])) { // if someone is using date custom fields here, output date, not uts - super edge case gh-349 if (isset($contactArr[$cKey.'_cfdate']) && !empty($contactArr[$cKey.'_cfdate'])) $ret .= $this->delimiterIf($delimiter,$ret).$contactArr[$cKey.'_cfdate']; else $ret .= $this->delimiterIf($delimiter,$ret).$contactArr[$cKey]; } } } } $trimRet = trim($ret); return $trimRet; } public function makeSlug($string, $replace = array(), $delimiter = '-') { // NOTE: the following can likely be replaced with sanitize_title // https://wordpress.stackexchange.com/questions/74415/how-does-wordpress-generate-url-slugs //return sanitize_title(sanitize_title($string, '', 'save'), '', 'query'); // https://github.com/phalcon/incubator/blob/master/Library/Phalcon/Utils/Slug.php // and // https://stackoverflow.com/questions/4910627/php-iconv-translit-for-removing-accents-not-working-as-excepted //if (!extension_loaded('iconv')) { // throw new Exception('iconv module not loaded'); //} // Save the old locale and set the new locale to UTF-8 $oldLocale = setlocale(LC_ALL, '0'); setlocale(LC_ALL, 'en_US.UTF-8'); // replace non letter or digits by - $clean = preg_replace('#[^\\pL\d]+#u', '-', $string); // transliterate if (function_exists('iconv')) $clean = @iconv('UTF-8', 'ASCII//TRANSLIT', $clean); // else? smt else? // replace if (!empty($replace)) { $clean = str_replace((array) $replace, ' ', $clean); } // clean $clean = $this->makeSlugCleanStr($clean,$delimiter); // Revert back to the old locale setlocale(LC_ALL, $oldLocale); return $clean; } private function makeSlugCleanStr($string='', $delimiter='-'){ // fix for ascii passing (I think) of ' resulting in -039- in place of ' $string = str_replace('-039-','',$string); // replace non letter or non digits by - $string = preg_replace('#[^\pL\d]+#u', '-', $string); // Trim trailing - $string = trim($string, '-'); $clean = preg_replace('~[^-\w]+~', '', $string); $clean = strtolower($clean); $clean = preg_replace('#[\/_|+ -]+#', $delimiter, $clean); $clean = trim($clean, $delimiter); return $clean; } /* ====================================================== / Formatters ====================================================== */ /* ====================================================== To be sorted helpers ====================================================== */ /** * helper - returns single field against db table WHERE X * Will only work for native fields (not Cutom fields) * * @param array WHERE clauses (not Req.) * @param string tablename * @param string colname * * @return string */ public function getFieldByWHERE($args=array()){ #} =========== LOAD ARGS ============== $defaultArgs = array( 'where' => -1, 'objtype' => -1, 'colname' => '', // permissions 'ignoreowner' => false // this'll let you not-check the owner of obj ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} ========== CHECK FIELDS ============ // check obtype is legit $objtype = (int)$objtype; if (!isset($objtype) || $objtype == -1 || $this->objTypeKey($objtype) === -1) return false; // check field (or 'COUNT(x)') if (empty($colname)) return false; #} ========= / CHECK FIELDS =========== global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); #} Build query - NOTE this is vulnerable to injection. $query = "SELECT $colname FROM ".$this->lazyTable($objtype); //$params[] = $colname; #} ============= WHERE ================ #} Add any where's $wheres = $where; #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort('ID','DESC') . $this->buildPaging(0,1); try { #} Prep & run query $queryObj = $this->prepare($query,$params); return $wpdb->get_var($queryObj); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } return false; } /** * helper - returns single field against db table (where ID =) * Will only work for native fields (not Cutom fields) * * @param int objID object id * @param int objTypeID objectType id * @param string colname * * @return string */ public function getFieldByID($args=array()){ #} =========== LOAD ARGS ============== $defaultArgs = array( 'id' => -1, 'objtype' => -1, 'colname' => '', // permissions 'ignoreowner' => false // this'll let you not-check the owner of obj ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} ========== CHECK FIELDS ============ // check id $id = (int)$id; if (!isset($id) || $id < 1) return false; // check obtype is legit $objtype = (int)$objtype; if (!isset($objtype) || $objtype == -1 || $this->objTypeKey($objtype) === -1) return false; // check field if (empty($colname)) return false; #} ========= / CHECK FIELDS =========== global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); #} Build query - NOTE this is vulnerable to injection. $query = "SELECT $colname FROM ".$this->lazyTable($objtype); //$params[] = $colname; #} ============= WHERE ================ #} Add ID if (!empty($id) && $id > 0) $wheres['ID'] = array('ID','=','%d',$id); #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort('ID','DESC') . $this->buildPaging(0,1); try { #} Prep & run query $queryObj = $this->prepare($query,$params); return $wpdb->get_var($queryObj); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } return false; } /** * helper - forces update of field for obj id + type, * THIS IS HARD usage, not for beginners/non-directors. * ... can break things if using this, so only use strictly for globally generic columns * ... e.g. zbs_owner, which appears in all obj. * ... ALWAYS use the DAL->contacts->whatever before this, where possible * // NOTE NOTE - THIS does not update "lastupdated" for each obj... AVOID USE! * * @param int objID object id * @param int objTypeID objectType id * @param string colname * * @return string */ public function setFieldByID($args=array()){ #} =========== LOAD ARGS ============== $defaultArgs = array( 'objID' => -1, 'objTypeID' => -1, 'colname' => '', 'coldatatype' => '%d', // %d/s 'newValue' => -99, ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= // this'll only update columnames present in here: $restrictedToColumns = array('zbs_owner'); if (in_array($colname,$restrictedToColumns) && $objID > 0 && $objTypeID > 0 && !empty($colname) && !empty($coldatatype) && $newValue !== -99){ global $wpdb; // got table? $tableName = $this->lazyTable($objTypeID); if (empty($tableName)) return false; #} Attempt update if ($wpdb->update( $tableName, array( $colname => $newValue ), array( // where 'ID' => $objID ), array( // field data types $coldatatype ), array( // where data types '%d' )) !== false){ // Successfully updated - Return id return $objID; } else { // FAILED update return false; } } return false; } // brutal switch for lazy tablenames public function lazyTable($objType=-1){ global $ZBSCRM_t; switch ($objType){ case ZBS_TYPE_CONTACT: return $ZBSCRM_t['contacts']; break; // dal3: case ZBS_TYPE_COMPANY: return $ZBSCRM_t['companies']; break; case ZBS_TYPE_QUOTE: return $ZBSCRM_t['quotes']; break; case ZBS_TYPE_INVOICE: return $ZBSCRM_t['invoices']; break; case ZBS_TYPE_TRANSACTION: return $ZBSCRM_t['transactions']; break; case ZBS_TYPE_TASK: return $ZBSCRM_t['events']; break; case ZBS_TYPE_FORM: return $ZBSCRM_t['forms']; break; case ZBS_TYPE_LOG: return $ZBSCRM_t['logs']; break; case ZBS_TYPE_SEGMENT: return $ZBSCRM_t['segments']; break; case ZBS_TYPE_LINEITEM: return $ZBSCRM_t['lineitems']; break; case ZBS_TYPE_TASK_REMINDER: return $ZBSCRM_t['eventreminders']; break; case ZBS_TYPE_QUOTETEMPLATE: return $ZBSCRM_t['quotetemplates']; break; } return false; } // brutal switch for lazy tidy func public function lazyTidy($objType=-1,$obj=false){ switch ($objType){ case ZBS_TYPE_CONTACT: return $this->contacts->tidy_contact($obj); break; // dal3: case ZBS_TYPE_COMPANY: return $this->companies->tidy_company($obj); break; case ZBS_TYPE_QUOTE: return $this->quotes->tidy_quote($obj); break; case ZBS_TYPE_INVOICE: return $this->invoices->tidy_invoice($obj); break; case ZBS_TYPE_TRANSACTION: return $this->transactions->tidy_transaction($obj); break; case ZBS_TYPE_TASK: return $this->events->tidy_event($obj); break; case ZBS_TYPE_FORM: return $this->forms->tidy_form($obj); break; case ZBS_TYPE_LOG: return $this->logs->tidy_log($obj); break; case ZBS_TYPE_SEGMENT: return $this->segments->tidy_segment($obj); break; case ZBS_TYPE_LINEITEM: return $this->lineitems->tidy_lineitem($obj); break; case ZBS_TYPE_TASK_REMINDER: return $this->eventreminders->tidy_eventreminder($obj); break; case ZBS_TYPE_QUOTETEMPLATE: return $this->quotetemplates->tidy_quotetemplate($obj); break; } return false; } // guesses at a tidy... lazy, remove these if hit walls public function lazyTidyGeneric($obj=false){ $res = false; foreach ($obj as $propKey => $prop){ if (!is_array($res)) $res = array(); if ($propKey != 'ID' && strpos($propKey, '_') > 0){ // zbs_owner -> owner $newKey = substr($propKey,strpos($propKey, '_')+1); $res[$newKey] = $this->stripSlashes($prop); } else $res['id'] = $prop; } return $res; } // appends a space, if req. (lazy helper for amongst queries) public function space($str='',$pre=false){ if (!empty($str)) if ($pre) return ' '.$str; else return $str.' '; return $str; } // appends a space and 'AND', if req. (lazy helper for amongst queries) public function spaceAnd($str=''){ if (!empty($str)) return $str.' AND '; return $str; } // appends a space and 'Where', if req. (lazy helper for amongst queries) public function spaceWhere($str=''){ $trimmedStr = trim($str); if (!empty($trimmedStr)) return ' WHERE '.$trimmedStr; return $str; } // returns delimiter, if str != epty // used to be zeroBS_delimiterIf pre dal1 public function delimiterIf($delimiter,$ifStr=''){ if (!empty($ifStr)) return $delimiter; return ''; } // internal middle man for zeroBSCRM_stripSlashes where ALWAYS returns public function stripSlashes($obj=false){ return zeroBSCRM_stripSlashes($obj,true); } // if it thinks str is json, it'll decode + return obj, otherwise returns str // this only works with arr/obj // Note that `[]` doesn't hydrate into array with this public function decodeIfJSON($str=''){ if (zeroBSCRM_isJson($str)) return json_decode($str,true); // true req. https://stackoverflow.com/questions/22878219/json-encode-turns-array-into-an-object return $str; } /* * Builds Custom Fields Order by Str * .. ultimately returns $sortByField unless numeric, if so casts the custom field (varchar) * .. into an INT/DECIMAL in MySQL for the search */ public function build_custom_field_order_by_str( $sortByField='', $customField=array() ){ // check if this custom field requires any special casting in it's sort string // where the CF is a numeric field, we'll need to also use CAST(* AS SIGNED) if ( $customField[0] == 'numberint' ){ $sortByField = 'CAST('.$sortByField.' AS SIGNED)'; } // where the CF is a decimal field, we'll need to use CAST(* AS DECIMAL) if ( $customField[0] == 'numberfloat' ){ $sortByField = 'CAST('.$sortByField.' AS DECIMAL(18,2))'; } return $sortByField; } /* * Build's an escaped imploded, DB safe CSV * e.g. "'a','b','c'" as used in SELECT * FROM x WHERE y in ('a','b','c') */ public function build_csv($array=array()){ // only arrays if (!is_array($array)) return ''; // Generate escaped csv, e.g. 'Call','Email' $array = array_map(function($v) { return "'" . esc_sql($v) . "'"; }, $array); // return return implode(',', $array); } // takes wherestr + additionalwhere and outputs legit SQL // GENERIC helper for all queries :) public function buildWhereStr($whereStr='',$additionalWhere=''){ //echo 'W:'.$whereStr.'<br >AW:'.$additionalWhere.'!!<br ><Br >'; #} Build $where = trim($whereStr); #} Any additional if (!empty($additionalWhere)){ if (!empty($where)) $where = $this->spaceAnd($where); else $where = 'WHERE '; $where .= $additionalWhere; } return $this->space($where,true); } // add where's to SQL // + // feed in params // GENERIC helper for all queries :) public function buildWheres($wheres=array(),$whereStr='',$params=array(),$andOr='AND',$includeInitialWHERE=true){ $ret = array('where'=>$whereStr,'params'=>$params); if ($andOr != 'AND' && $andOr != 'OR') $andOr = 'AND'; // clear empty direct if (isset($wheres['direct']) && is_array($wheres['direct']) && count($wheres['direct']) == 0) unset($wheres['direct']); if (is_array($wheres) && count($wheres) > 0) foreach ($wheres as $key => $whereArr) { if (empty($ret['where']) && $includeInitialWHERE) $ret['where'].= ' WHERE '; // Where's are passed 2 ways, "direct": // array(SQL,array(params)) if ($key == 'direct'){ // several under 1 direct foreach ($whereArr as $directWhere){ if (isset($directWhere[0]) && isset($directWhere[1])){ // multi-direct ANDor if (!empty($ret['where']) && $ret['where'] != ' WHERE '){ $ret['where'] .= ' '.$andOr.' '; } // ++ query $ret['where'] .= $directWhere[0]; // ++ params (any number, if set) if (is_array($directWhere[1])) foreach ($directWhere[1] as $x) $ret['params'][] = $x; else $ret['params'][] = $directWhere[1]; } } } else { if (!empty($ret['where']) && $ret['where'] != ' WHERE '){ $ret['where'] .= ' '.$andOr.' '; } // Other way: // irrelevantKEY => array(fieldname,operator,comparisonval,array(params)) // e.g. array('ID','=','%d',array(123)) // e.g. array('ID','IN','(SUBSELECT)',array(123)) // build where (e.g. "X = Y" or "Z IN (1,2,3)") $ret['where'] .= $whereArr[0]. ' '.$whereArr[1].' '.$whereArr[2]; // ++ params (any number, if set) if (isset($whereArr[3])) { if (is_array($whereArr[3])) foreach ($whereArr[3] as $x) $ret['params'][] = $x; else $ret['params'][] = $whereArr[3]; } /* legacy // add in - NOTE: this is TRUSTING key + whereArr[0] $ret['where'] .= $key.' '.$whereArr[0].' '.$whereArr[2]; // feed in params $ret['params'][] = $whereArr[1]; */ } } return $ret; } // takes sortby field + order and returns str if not empty :) // Note: Is trusting legitimacy of $sortByField as parametised in wp db doesn't seem to work // can also now pass array (multi-sort) // e.g. $sortByField = 'zbsc_fname' OR $sortByField = array('zbsc_fname'=>'ASC','zbsc_lname' => 'DESC'); public function buildSort($sortByField='',$sortOrder='ASC'){ #} Sort by if (!is_array($sortByField) && !empty($sortByField)){ $sortOrder = strtoupper($sortOrder); if (!in_array($sortOrder, array('DESC','ASC'))) $sortOrder = 'DESC'; return ' ORDER BY '.$sortByField.' '.$sortOrder; } else if (is_array($sortByField)){ $orderByStr = ''; foreach ($sortByField as $field => $order){ if (!empty($orderByStr)) $orderByStr .= ', '; $orderByStr .= $field.' '.strtoupper($order); } if (!empty($orderByStr)) return ' ORDER BY '.$orderByStr; } return ''; } // takes $page and $perPage and adds limit str if req. public function buildPaging($page=-1,$perPage=-1){ #} Pagination if ($page == -1 && $perPage == -1){ // NO LIMITS :o } else { $perPage = (int)$perPage; // Because SQL USING zero indexed page numbers, we remove -1 here // ... DO NOT change this without seeing usage of the function (e.g. list view) - which'll break $page = (int)$page-1; if ($page < 0) $page = 0; // page needs multiplying :) if ($page > 0) $page = $page * $perPage; // check params realistic // todo, for now, brute pass return ' LIMIT '.(int)$page.','.(int)$perPage; } return ''; } // builds WHERE query for meta key / val pairs. // e.g. Get customers in Company id 9: // ... contacts where their ID is in post_id WHERE meta_key = zbs_company and meta_value = 9 // infill for half-migrated stuff public function buildWPMetaQueryWhere($metaKey=-1,$metaVal=-1){ if (!empty($metaKey) && !empty($metaVal)){ global $wpdb; return array( 'sql' => 'ID IN (SELECT DISTINCT post_id FROM '.$wpdb->prefix.'postmeta WHERE meta_key = %s AND meta_value = %d)', 'params' => array($metaKey,$metaVal) ); } return false; } /** * Generates GROUP_CONCAT SQL compatible with both SQLite and MySQL * * @param string $field Field that will be concatenated. * @param string $separator Separator added between concatenated fields. * * @return string */ public function build_group_concat( $field, $separator ) { $db_engine = jpcrm_database_engine(); if ( $db_engine === 'sqlite' ) { return sprintf( 'GROUP_CONCAT(%s, "%s")', $field, $separator ); } else { return sprintf( 'GROUP_CONCAT(%s SEPARATOR "%s")', $field, $separator ); } } // this returns %s etc. for common field names, will default to %s unless somt obv a date public function getTypeStr($fieldKey=''){ if ($fieldKey == 'zbs_site' || $fieldKey == 'zbs_team' || $fieldKey == 'zbs_owner') return '%d'; if (strpos($fieldKey, '_created') > 0) return '%d'; if (strpos($fieldKey, '_lastupdated') > 0) return '%d'; if (strpos($fieldKey, '_lastcontacted') > 0) return '%d'; if (strpos($fieldKey, '_id') > 0) return '%d'; if (strpos($fieldKey, '_ID') > 0) return '%d'; if ($fieldKey == 'id' || $fieldKey == 'ID') return '%d'; return '%s'; } /* * Converts verbs such as 'equal' to '=' * Note: these are relatively idiosyncratic as were part of segmentation layer but got generalised here */ public function comparison_to_sql_symbol( $comparison_verb ){ switch ( $comparison_verb ){ case 'equal': case 'equals': return '='; break; case 'notequal': return '<>'; break; case 'larger': return '>'; break; case 'largerequal': return '>='; break; case 'less': return '<'; break; case 'lessequal': return '<='; break; case 'floatrange': // this is somewhat like hotglue, e.g. `WHERE column_a [BETWEEN %s AND ] %s` return 'BETWEEN %s AND '; break; case 'intrange': // this is somewhat like hotglue, e.g. `WHERE column_a [BETWEEN %d AND ] %d` return 'BETWEEN %d AND '; break; } return false; } public function prepare($sql='',$params=array()){ global $wpdb; // empty arrays causes issues in wpdb prepare if (is_array($params) && count($params) <= 0) return $sql; // normal return return $wpdb->prepare($sql,$params); } // not yet used public function catchSQLError($errObj=-1){ // log? return false; } /* * Retrieves a key-value pair from centralised global * * @param string $key * */ public function get_cache_var( $key ){ if ( isset( $this->cache[ $key ] ) ){ return $this->cache[ $key ]; } return false; } /* * Stores a key-value pair in centralised global * This is designed to allow basic caching at a DAL level without spawning multiple globals * * @param string $key * @param mixed $value * */ public function update_cache_var( $key, $value ){ // simplistic $this->cache[ $key ] = $value; } /* ====================================================== / To be sorted helpers ====================================================== */ /* ====================================================== Middle Man funcs (until DAL3.1) ====================================================== */ // TEMP LOGGING to BACKTRACE LEGACY CALLS: /* CREATE TABLE `templogs` ( `ID` int(32) NOT NULL AUTO_INCREMENT PRIMARY KEY, `funcname` varchar(500) NOT NULL, `filename` varchar(500) NOT NULL, `notes` longtext NOT NULL, `time` int(14) NOT NULL ) ENGINE='InnoDB' COLLATE 'utf8_general_ci'; */ // temporary function used in v3.0 prep to weed out bad/old reference use // logs to table 'templogs' if table exists // left in until 3.1 - see #gh-146 private function v3templogBacktrace($funcName='',$caller=false,$backtrace=false){ global $ZBSCRM_t,$wpdb; $tableExist = $wpdb->get_results("SHOW TABLES LIKE 'templogs'"); if (count($tableExist) >= 1){ if ($wpdb->insert( 'templogs', array( // fields 'funcname' => $funcName, 'filename' => $caller['file'].':'.$caller['line'], 'notes' => print_r($backtrace,1),//, 'time' => time() ), array( '%s', '%s', '%s', '%d' ) ) <= 0) exit('ERROR: Failed to log backtrace error ('.$funcName.')!<pre>'.print_r(array($backtrace,$caller,$funcName),1).'</pre>'); } return true; } // polite flag: private function ____MIDDLEMAN_FUNCS(){} public function getContact(...$args){ // hard-typed $funcName = 'getContact'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function getContacts(...$args){ // hard-typed $funcName = 'getContacts'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function addUpdateContact(...$args){ // hard-typed $funcName = 'addUpdateContact'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function addUpdateContactTags(...$args){ // hard-typed $funcName = 'addUpdateContactTags'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function addUpdateContactCompanies(...$args){ // hard-typed $funcName = 'addUpdateContactCompanies'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function addUpdateContactWPID(...$args){ // hard-typed $funcName = 'addUpdateContactWPID'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function deleteContact(...$args){ // hard-typed $funcName = 'deleteContact'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function tidy_contact(...$args){ // hard-typed $funcName = 'tidy_contact'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function db_ready_contact(...$args){ // hard-typed $funcName = 'db_ready_contact'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function getContactOwner(...$args){ // hard-typed $funcName = 'getContactOwner'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function getContactStatus(...$args){ // hard-typed $funcName = 'getContactStatus'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function getContactEmail(...$args){ // hard-typed $funcName = 'getContactEmail'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function getContactMobile(...$args){ // hard-typed $funcName = 'getContactMobile'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function getContactFullName(...$args){ // hard-typed $funcName = 'getContactFullName'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function getContactFullNameEtc(...$args){ // hard-typed $funcName = 'getContactFullNameEtc'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function getContactAddress(...$args){ // hard-typed $funcName = 'getContactAddress'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function getContact2ndAddress(...$args){ // hard-typed $funcName = 'getContact2ndAddress'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function getContactTags(...$args){ // hard-typed $funcName = 'getContactTags'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function getContactLastContactUTS(...$args){ // hard-typed $funcName = 'getContactLastContactUTS'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function setContactLastContactUTS(...$args){ // hard-typed $funcName = 'setContactLastContactUTS'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function getContactSocials(...$args){ // hard-typed $funcName = 'getContactSocials'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function getContactWPID(...$args){ // hard-typed $funcName = 'getContactWPID'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function getContactDoNotMail(...$args){ // hard-typed $funcName = 'getContactDoNotMail'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function setContactDoNotMail(...$args){ // hard-typed $funcName = 'setContactDoNotMail'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function getContactAvatarURL(...$args){ // hard-typed $funcName = 'getContactAvatarURL'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function getContactAvatar(...$args){ // hard-typed $funcName = 'getContactAvatar'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function getContactAvatarHTML(...$args){ // hard-typed $funcName = 'getContactAvatarHTML'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function getContactCount(...$args){ // hard-typed $funcName = 'getContactCount'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function getContactCompanies(...$args){ // hard-typed $funcName = 'getContactCompanies'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function getContactPrevNext(...$args){ // hard-typed $funcName = 'getContactPrevNext'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->contacts, $funcName)) return call_user_func_array(array($this->contacts,$funcName),func_get_args()); // ultimate fallback return false; } public function getSegments(...$args){ // hard-typed $funcName = 'getSegments'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->segments, $funcName)) return call_user_func_array(array($this->segments,$funcName),func_get_args()); // ultimate fallback return false; } public function getSegmentCount(...$args){ // hard-typed $funcName = 'getSegmentCount'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->segments, $funcName)) return call_user_func_array(array($this->segments,$funcName),func_get_args()); // ultimate fallback return false; } public function deleteSegment(...$args){ // hard-typed $funcName = 'deleteSegment'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->segments, $funcName)) return call_user_func_array(array($this->segments,$funcName),func_get_args()); // ultimate fallback return false; } public function tidy_segment(...$args){ // hard-typed $funcName = 'tidy_segment'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->segments, $funcName)) return call_user_func_array(array($this->segments,$funcName),func_get_args()); // ultimate fallback return false; } public function tidy_segment_condition(...$args){ // hard-typed $funcName = 'tidy_segment_condition'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->segments, $funcName)) return call_user_func_array(array($this->segments,$funcName),func_get_args()); // ultimate fallback return false; } public function getSegmentsCountIncParams(...$args){ // hard-typed $funcName = 'getSegmentsCountIncParams'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->segments, $funcName)) return call_user_func_array(array($this->segments,$funcName),func_get_args()); // ultimate fallback return false; } public function previewSegment(...$args){ // hard-typed $funcName = 'previewSegment'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->segments, $funcName)) return call_user_func_array(array($this->segments,$funcName),func_get_args()); // ultimate fallback return false; } public function segmentConditionsToArgs(...$args){ // hard-typed $funcName = 'segmentConditionsToArgs'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->segments, $funcName)) return call_user_func_array(array($this->segments,$funcName),func_get_args()); // ultimate fallback return false; } public function getSegmentBySlug(...$args){ // hard-typed $funcName = 'getSegmentBySlug'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->segments, $funcName)) return call_user_func_array(array($this->segments,$funcName),func_get_args()); // ultimate fallback return false; } public function getSegment(...$args){ // hard-typed $funcName = 'getSegment'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->segments, $funcName)) return call_user_func_array(array($this->segments,$funcName),func_get_args()); // ultimate fallback return false; } public function getSegementAudience(...$args){ // hard-typed $funcName = 'getSegementAudience'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->segments, $funcName)) return call_user_func_array(array($this->segments,$funcName),func_get_args()); // ultimate fallback return false; } public function getSegmentsContainingContact(...$args){ // hard-typed $funcName = 'getSegmentsContainingContact'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->segments, $funcName)) return call_user_func_array(array($this->segments,$funcName),func_get_args()); // ultimate fallback return false; } public function isContactInSegment(...$args){ // hard-typed $funcName = 'isContactInSegment'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->segments, $funcName)) return call_user_func_array(array($this->segments,$funcName),func_get_args()); // ultimate fallback return false; } public function compileSegmentsAffectedByContact(...$args){ // hard-typed $funcName = 'compileSegmentsAffectedByContact'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->segments, $funcName)) return call_user_func_array(array($this->segments,$funcName),func_get_args()); // ultimate fallback return false; } public function getSegmentConditions(...$args){ // hard-typed $funcName = 'getSegmentConditions'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->segments, $funcName)) return call_user_func_array(array($this->segments,$funcName),func_get_args()); // ultimate fallback return false; } public function updateSegmentCompiled(...$args){ // hard-typed $funcName = 'updateSegmentCompiled'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->segments, $funcName)) return call_user_func_array(array($this->segments,$funcName),func_get_args()); // ultimate fallback return false; } public function addUpdateSegment(...$args){ // hard-typed $funcName = 'addUpdateSegment'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->segments, $funcName)) return call_user_func_array(array($this->segments,$funcName),func_get_args()); // ultimate fallback return false; } public function addUpdateSegmentConditions(...$args){ // hard-typed $funcName = 'addUpdateSegmentConditions'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->segments, $funcName)) return call_user_func_array(array($this->segments,$funcName),func_get_args()); // ultimate fallback return false; } public function addUpdateSegmentCondition(...$args){ // hard-typed $funcName = 'addUpdateSegmentCondition'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->segments, $funcName)) return call_user_func_array(array($this->segments,$funcName),func_get_args()); // ultimate fallback return false; } public function removeSegmentConditions(...$args){ // hard-typed $funcName = 'removeSegmentConditions'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->segments, $funcName)) return call_user_func_array(array($this->segments,$funcName),func_get_args()); // ultimate fallback return false; } public function segmentConditionArgs(...$args){ // hard-typed $funcName = 'segmentConditionArgs'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->segments, $funcName)) return call_user_func_array(array($this->segments,$funcName),func_get_args()); // ultimate fallback return false; } public function segmentBuildDirectOrClause(...$args){ // hard-typed $funcName = 'segmentBuildDirectOrClause'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->segments, $funcName)) return call_user_func_array(array($this->segments,$funcName),func_get_args()); // ultimate fallback return false; } public function compileSegment(...$args){ // hard-typed $funcName = 'compileSegment'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->segments, $funcName)) return call_user_func_array(array($this->segments,$funcName),func_get_args()); // ultimate fallback return false; } public function getLog(...$args){ // hard-typed $funcName = 'getLog'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->logs, $funcName)) return call_user_func_array(array($this->logs,$funcName),func_get_args()); // ultimate fallback return false; } public function getLogsForObj(...$args){ // hard-typed $funcName = 'getLogsForObj'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->logs, $funcName)) return call_user_func_array(array($this->logs,$funcName),func_get_args()); // ultimate fallback return false; } public function getLogsForANYObj(...$args){ // hard-typed $funcName = 'getLogsForANYObj'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->logs, $funcName)) return call_user_func_array(array($this->logs,$funcName),func_get_args()); // ultimate fallback return false; } public function addUpdateLog(...$args){ // hard-typed $funcName = 'addUpdateLog'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->logs, $funcName)) return call_user_func_array(array($this->logs,$funcName),func_get_args()); // ultimate fallback return false; } public function deleteLog(...$args){ // hard-typed $funcName = 'deleteLog'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->logs, $funcName)) return call_user_func_array(array($this->logs,$funcName),func_get_args()); // ultimate fallback return false; } public function tidy_log(...$args){ // hard-typed $funcName = 'tidy_log'; // retrieve backtrace $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1); $caller = array_shift($backtrace); // log to db, if logging $this->v3templogBacktrace($funcName,$caller,$backtrace); // return, if available if (method_exists($this->logs, $funcName)) return call_user_func_array(array($this->logs,$funcName),func_get_args()); // ultimate fallback return false; } // polite flag: private function ____MIDDLEMAN_FUNCS_END(){} /* ====================================================== / Middle Man funcs (until DAL3.0) ====================================================== */ } // / DAL class
projects/plugins/crm/includes/class-missing-settings-exception.php
<?php /** * Jetpack CRM Missing Settings Exception Class * Extends Exception to provide additional data. * */ namespace Automattic\JetpackCRM; defined( 'ZEROBSCRM_PATH' ) || exit; /** * Missing Settings exception class. */ class Missing_Settings_Exception extends CRM_Exception {}
projects/plugins/crm/includes/ZeroBSCRM.DataIOValidation.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V1.20 * * Copyright 2020 Automattic * * Date: 01/11/16 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== Data Processing Functions ====================================================== */ // Ensures storage and return as UTF8 without slashes function zeroBSCRM_textProcess($string=''){ return htmlentities(stripslashes($string),ENT_QUOTES,'UTF-8'); } function zeroBSCRM_textExpose($string=''){ return html_entity_decode($string,ENT_QUOTES,'UTF-8'); } // hitting this issue // https://core.trac.wordpress.org/ticket/43087 // + // https://core.trac.wordpress.org/ticket/32315#comment:43 // (pasted emoji's in inputs (log text) would cause a silent wpdb error) // so for now, passing any emoji-ridden text through here: function zeroBSCRM_preDBStr($string=''){ // encode emoji's - https://core.trac.wordpress.org/ticket/43087 return wp_encode_emoji($string); } // strips all except <br /> function zeroBSCRM_stripExceptLineBreaks($string=''){ // simplistic switchout. can surely be done more elegantly $brs = array('<br />','<br>','<br/>','<BR />','<BR>','<BR/>'); $str = str_replace($brs,'###BR###',$string); $str = wp_strip_all_tags($str,1); $str = str_replace('###BR###','<br />',$str); return $str; } /* * sanitize_text_field, but allows whitespace through :roll-eyes: * https://developer.wordpress.org/reference/functions/sanitize_text_field/ */ function jpcrm_sanitize_text_field_allow_whitespace( $string = '' ){ $string = str_replace( ' ', '**WHITESPACE**', $string ); $string = sanitize_text_field( $string ); return str_replace( '**WHITESPACE**', ' ', $string ); } // lol https://stackoverflow.com/questions/6063184/how-to-strip-all-characters-except-for-alphanumeric-and-underscore-and-dash function zeroBSCRM_strings_stripNonAlphaNumeric_dash($str=''){ return preg_replace("/[^a-z0-9_\-\s]+/i", "", $str); } // https://stackoverflow.com/questions/33993461/php-remove-all-non-numeric-characters-from-a-string function zeroBSCRM_strings_stripNonNumeric($str=''){ return preg_replace("/[^0-9]/", "", $str); } /* ====================================================== / Data Processing Functions ====================================================== */ /* ====================================================== Data Validation Functions ====================================================== */ /* * Taking a variable, this function checks if it could be an int * (returns true if is an int or a string which could be an int) .. with a little help from my friends: https://stackoverflow.com/questions/2012187/how-to-check-that-a-string-is-an-int-but-not-a-double-etc */ function jpcrm_is_int( $var = false ){ // straight check if ( is_int($var) ) return true; // string check if ( is_string($var) ){ // catch negative if ( str_starts_with( $var, '-' ) ) { // use ctype where available if ( function_exists('ctype_digit') ){ return ctype_digit( substr($var, 1) ); } else { return is_numeric( $var ); } } // use ctype_digit where available to check the string only contains digits if ( function_exists('ctype_digit') ){ return ctype_digit( $var ); } else { return is_numeric( $var ); } } return false; } /** * Checks if a given string is a URL * * @param string $s Potential URL string. * @param boolean $do_tld_check use TLD check instead of regex to confirm if it is a valid URL. * * @return boolean */ function jpcrm_is_url( $s, $do_tld_check = false ) { if ( $do_tld_check ) { return jpcrm_has_valid_tld( $s ); } return preg_match( '/^(https?:\/\/|www\.)\w+(\.\w+)*?(\/[^\s]*)?$/', $s ); } /** * Checks if host of a given URL is using a whitelisted TLD * * @param string $s URL string. * @param array $valid_tlds List of approved TLDs. * * @return boolean */ function jpcrm_has_valid_tld( $s, $valid_tlds = array( '.com', '.net', '.org', '.edu', '.gov', '.co.uk' ) ) { $host = wp_parse_url( jpcrm_url_with_scheme( $s ), PHP_URL_HOST ); if ( ! $host ) { return false; } foreach ( $valid_tlds as $tld ) { if ( str_ends_with( $host, $tld ) ) { return true; } } return false; } /* * adds a scheme to a URL string if it doesn't exist * * @param str $s as a URL string * @param str $scheme as an optional default scheme * * return scheme + str */ //adapted from https://stackoverflow.com/a/14701491 function jpcrm_url_with_scheme($s, $scheme='https') { return parse_url($s, PHP_URL_SCHEME) === null ? $scheme . '://' . ltrim($s,'/') : $s; } #} Checks an email addr function zeroBSCRM_validateEmail($emailAddr){ if (filter_var($emailAddr, FILTER_VALIDATE_EMAIL)) return true; return false; } function zeroBSCRM_dataIO_postedArrayOfInts($array=false){ $ret = array(); if (is_array($array)) $ret = $array; // sanitize $ret = array_map( 'sanitize_text_field', $ret ); $ret = array_map( 'intval', $ret ); return $ret; } /* * Checks file path doesn't use unsafe/undesirable protocols */ function jpcrm_dataIO_file_path_seems_unsafe( $file_path_string ){ // this one is important enough to be hard typed here #gh-2501 if ( str_contains( $file_path_string, 'phar' ) ) { return true; } // these we block with their full string (unless we find a reason to open them up) $blocked_protocols = array( 'file', 'http', 'ftp', 'php', 'zlib', 'data', 'glob', 'ssh2', 'rar', 'ogg', 'expect' ); foreach ( $blocked_protocols as $protocol ) { if ( str_contains( $file_path_string, $protocol . '://' ) ) { return true; } } // this is only as accurate as what we know here and now (!) return false; } /** * A check which does its best to ensure a URI is an url with the same root as existing site * * @param string $url_string A URL string. * @param string $site_path The site path if applicable. */ function jpcrm_url_appears_to_match_site( $url_string, $site_path = '' ) { $this_site_url = site_url( $site_path ); if ( str_starts_with( $url_string, $this_site_url ) ) { return true; } return false; } /* ====================================================== / Data Validation Functions ====================================================== */ /* ====================================================== Data Validation Functions: Segments ====================================================== */ // filters out segment conditions (From anything passed) which are not 'safe' // e.g. on our zeroBSCRM_segments_availableConditions() list // ACCEPTS a POST arr // $processCharacters dictates whether or not to pass strings through zeroBSCRM_textProcess // ... only do so pre-save, not pre "preview" because this html encodes special chars. // note $processCharacters now legacy/defunct. function zeroBSCRM_segments_filterConditions($conditions=array(),$processCharacters=true){ if (is_array($conditions) && count($conditions) > 0){ $approvedConditions = array(); $availableConditions = zeroBSCRM_segments_availableConditions(); $availableConditionOperators = zeroBSCRM_segments_availableConditionOperators(); foreach ($conditions as $c){ // has proper props if (isset($c['type']) && isset($c['operator']) && isset($c['value'])){ // retrieve val $val = $c['value']; if ($processCharacters) $val = zeroBSCRM_textProcess($val); // only pre-saving $val = sanitize_text_field( $val ); // conversions (e.g. date to uts) $val = zeroBSCRM_segments_typeConversions($val,$c['type'],$c['operator'],'in'); // okay. (passing only expected + validated) $addition = array( 'type' => $c['type'], 'operator' => $c['operator'], 'value' => $val ); // ranges: // int/floatval if (isset($c['value2'])){ // retrieve val2 $val2 = $c['value2']; if ($processCharacters) $val2 = zeroBSCRM_textProcess($val2); // only pre-saving $val2 = sanitize_text_field( $val2 ); $addition['value2'] = $val2; } // daterange || datetimerange if ( ( $c['operator'] == 'daterange' || $c['operator'] == 'datetimerange' ) && !empty( $val ) ){ // hmmm what if peeps use ' - ' in their date formats? This won't work if they do! if ( str_contains( $val, ' - ' ) ) { $dates = explode( ' - ', $val ); if ( count( $dates ) === 2 ) { $local_date_time = new DateTime( $dates[0], wp_timezone() ); $local_date_time->setTimezone( new DateTimeZone( 'UTC' ) ); $value = $local_date_time->format( 'Y-m-d H:i' ); $local_date_time_2 = new DateTime( $dates[1], wp_timezone() ); $local_date_time_2->setTimezone( new DateTimeZone( 'UTC' ) ); $value_2 = $local_date_time_2->format( 'Y-m-d H:i' ); // Set the converted dates to UTC. $addition['value'] = zeroBSCRM_locale_dateToUTS( $value ); $addition['value2'] = zeroBSCRM_locale_dateToUTS( $value_2 ); } } } // if intrange force it if ($c['type'] == 'intrange' && !isset($addition['value2'])) $addition['value2'] = 0; $approvedConditions[] = $addition; } } return $approvedConditions; } return array(); } // uses zeroBSCRM_textExpose to make query-ready strings, // .. because conditions are saved in encoded format, e.g. é = &eacute; function zeroBSCRM_segments_unencodeConditions($conditions=array()){ if (is_array($conditions) && count($conditions) > 0){ $ret = array(); foreach ($conditions as $c){ // for now it's just value we're concerned with $nC = $c; if (isset($nC['value'])) $nC['value'] = zeroBSCRM_textExpose($nC['value']); if (isset($nC['value2'])) $nC['value2'] = zeroBSCRM_textExpose($nC['value2']); // simple. $ret[] = $nC; } return $ret; } return array(); } /* ====================================================== / Data Validation Functions: Segments ====================================================== */
projects/plugins/crm/includes/ZeroBSCRM.Inventory.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V1.1.19 * * Copyright 2020 Automattic * * Date: 25/10/16 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== Declare Globals ====================================================== */ #} Used throughout global $zbsCustomerFields,$zbsCustomerQuoteFields,$zbsCustomerInvoiceFields; /* ====================================================== / Declare Globals ====================================================== */
projects/plugins/crm/includes/ZeroBSCRM.Social.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V2.2 * * Copyright 2020 Automattic * * Date: 16/11/16 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== Hard Coded Social Types ====================================================== */ global $zbsSocialAccountTypes; /* WH added 2.2 - this drives what "social accounts" are shown everywhere for contacts etc. */ $zbsSocialAccountTypes = array( 'tw' => array( 'name' => 'Twitter', 'slug' => 'twitter', 'placeholder' => 'example', 'fa' => 'fa-twitter', 'urlprefix' => 'https://twitter.com/' ), 'li' => array( 'name' => 'Linked In', 'slug' => 'linked-in', 'placeholder' => 'example', 'fa' => 'fa-linkedin', 'urlprefix' => 'https://www.linkedin.com/in/' ), 'fb' => array( 'name' => 'Facebook', 'slug' => 'facebook', 'placeholder' => 'example', 'fa' => 'fa-facebook', 'urlprefix' => 'https://fb.com/' ) ); /* ====================================================== / Hard Coded Social Types ====================================================== */ /* ====================================================== Social helper funcs ====================================================== */ // returns an url (E.g. https://twitter.com/woodyhayday) from a social acc obj function zeroBSCRM_getSocialLink( $key, $userSocialAccs ){ if (isset($key) && isset($userSocialAccs) && is_array($userSocialAccs)){ global $zbsSocialAccountTypes; // got acc? if (isset($userSocialAccs[$key]) && !empty($userSocialAccs[$key])){ // get prefix $URL = $zbsSocialAccountTypes[$key]['urlprefix']; // finish it off + return return $URL . $userSocialAccs[$key]; } } return '#'; } /** * Shows business social links * * @returns {string} A string with all filled out Social links. */ function show_social_links() { $social_links_string = ''; if ( '' !== zeroBSCRM_getSetting( 'facebook' ) ) { $social_links_string = 'Facebook: ' . zeroBSCRM_getSetting( 'facebook' ) . '<br/>'; } if ( '' !== zeroBSCRM_getSetting( 'twitter' ) ) { $social_links_string .= 'Twitter: ' . zeroBSCRM_getSetting( 'twitter' ) . '<br/>'; } if ( '' !== zeroBSCRM_getSetting( 'linkedin' ) ) { $social_links_string .= 'LinkedIn: ' . zeroBSCRM_getSetting( 'linkedin' ); } return $social_links_string; } /* ====================================================== / Social helper funcs ====================================================== */
projects/plugins/crm/includes/ZeroBSCRM.DAL3.Obj.Logs.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V3.0+ * * Copyright 2020 Automattic * * Date: 14/01/19 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /** * ZBS DAL >> Logs * * @author Woody Hayday <hello@jetpackcrm.com> * @version 2.0 * @access public * @see https://jetpackcrm.com/kb */ class zbsDAL_logs extends zbsDAL_ObjectLayer { protected $objectType = ZBS_TYPE_LOG; protected $objectModel = array( // ID 'ID' => array('fieldname' => 'ID', 'format' => 'int'), // site + team generics 'zbs_site' => array('fieldname' => 'zbs_site', 'format' => 'int'), 'zbs_team' => array('fieldname' => 'zbs_team', 'format' => 'int'), 'zbs_owner' => array('fieldname' => 'zbs_owner', 'format' => 'int'), // other fields 'objtype' => array('fieldname' => 'zbsl_objtype', 'format' => 'int'), 'objid' => array('fieldname' => 'zbsl_objid', 'format' => 'int'), 'type' => array('fieldname' => 'zbsl_type', 'format' => 'str'), 'shortdesc' => array('fieldname' => 'zbsl_shortdesc', 'format' => 'str'), 'longdesc' => array('fieldname' => 'zbsl_longdesc', 'format' => 'str'), 'pinned' => array('fieldname' => 'zbsl_pinned', 'format' => 'int'), 'created' => array('fieldname' => 'zbsl_created', 'format' => 'uts'), 'lastupdated' => array('fieldname' => 'zbsl_lastupdated', 'format' => 'uts'), ); /** * Returns log types which count as 'contact' * (These effect what updates 'last contacted' field against customer and 'latest contact log') * - For now hard typed */ public $contact_log_types = array( 'call', 'email', 'mail', 'meeting', 'feedback', 'invoice__sent', 'quote__sent', 'feedback', 'tweet', 'facebook_post', 'other_contact' ); function __construct($args=array()) { #} =========== LOAD ARGS ============== $defaultArgs = array( //'tag' => false, ); foreach ($defaultArgs as $argK => $argV){ $this->$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $this->$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$this->$argK = $newData;} else { $this->$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= } // =============================================================================== // =========== LOGS =========================================================== // generic get Company (by ID) // Super simplistic wrapper used by edit page etc. (generically called via dal->contacts->getSingle etc.) public function getSingle($ID=-1){ return $this->getLog(array('id'=>$ID)); } /** * returns full Log line +- details * * @param array $args Associative array of arguments * key, fullDetails, default * * @return array result */ public function getLog($args=array()){ #} =========== LOAD ARGS ============== $defaultArgs = array( // search args: 'id' => -1, // include: 'incMeta' => false, // permissions 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_LOG), // this'll let you not-check the owner of obj // returns scalar ID of line 'onlyID' => false ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} ========== CHECK FIELDS ============ // check id $id = (int)$id; if (empty($id) || $id <= 0) return false; #} ========= / CHECK FIELDS =========== #} Check key if (!empty($id)){ global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); #} Build query $query = "SELECT * FROM ".$ZBSCRM_t['logs']; #} ============= WHERE ================ #} Add ID $wheres['ID'] = array('ID','=','%d',$id); #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort('ID','DESC') . $this->buildPaging(0,1); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_row($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret Results (ROW) if (isset($potentialRes) && isset($potentialRes->ID)) { #} Has results, tidy + return #} Only ID? return it directly if ($onlyID === true) return $potentialRes->ID; if ($incMeta) $potentialRes->meta = $this->DAL()->getMeta(array( 'objtype' => ZBS_TYPE_LOG, 'objid' => $potentialRes->ID, 'key' => 'logmeta', 'fullDetails' => false, 'default' => -1 )); return $this->tidy_log($potentialRes); } } // / if ID return $default; } /** * returns log lines for an obj * * @param array $args Associative array of arguments * searchPhrase, sortByField, sortOrder, page, perPage * * @return array of tag lines */ public function getLogsForObj($args=array()){ #} ============ LOAD ARGS ============= $defaultArgs = array( // search args: 'objtype' => -1, 'objid' => -1, 'searchPhrase' => '', // specify to search through all note descs 'notetype' => -1, // specify a permified type to grab collection 'notetypes' => -1, // specify an array of permified types to grab collection 'only_pinned' => false, 'meta_pair' => -1, // where array('key'=>x,'value'=>y) will find logs with this meta // return 'incMeta' => false, 'sortByField' => 'ID', 'sortOrder' => 'ASC', 'page' => 0, 'perPage' => 100, // permissions 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_LOG) // this'll let you not-check the owner of obj ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} ========== CHECK FIELDS ============ // ID $objid = (int)$objid; if (empty($objid) || $objid <= 0) return false; // This was returning false when $objid was 0 (or -1) if ($objid < 0) return false; // check obtype is legit.. $objtype = (int)$objtype; if (!isset($objtype) || $objtype == -1 || $this->DAL()->objTypeKey($objtype) === -1) return false; #} ========= / CHECK FIELDS =========== global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); #} Build query $query = "SELECT * FROM ".$ZBSCRM_t['logs']; #} ============= WHERE ================ #} objid if (!empty($objid) && $objid > 0) $wheres['zbsl_objid'] = array('zbsl_objid','=','%d',$objid); #} objtype if (!empty($objtype) && $objtype !== -1) $wheres['zbsl_objtype'] = array('zbsl_objtype','=','%d',$objtype); #} notetype if (!empty($notetype) && $notetype !== -1) $wheres['zbsl_type'] = array('zbsl_type','=','%s',$notetype); #} notetypes if (is_array($notetypes) && count($notetypes) > 0){ // Generate escaped csv, e.g. 'Call','Email' $notetypesStr = $this->build_csv($notetypes); // add it as a direct where clause to avoid double escaping $wheres['direct'][] = array('zbsl_type IN ('.$notetypesStr.')',array()); } // pinned if ( $only_pinned ){ $wheres['direct'][] = array('zbsl_pinned = 1',array()); } #} Search if (!empty($searchPhrase)) { $wheres['zbsl_shortdesc'] = array('zbsl_shortdesc','LIKE','%s','%'.$searchPhrase.'%'); $wheres['zbsl_longdesc'] = array('zbsl_longdesc','LIKE','%s','%'.$searchPhrase.'%'); } // meta_pair if ( is_array( $meta_pair ) && isset( $meta_pair['key'] ) && isset( $meta_pair['value'] ) ){ // make a clean version $meta_pair_key = $this->DAL()->makeSlug( $meta_pair['key'] ); // search for it $wheres['log_meta'] = array('ID','IN',"(SELECT zbsm_objid FROM ".$ZBSCRM_t['meta']." WHERE zbsm_objtype = " . ZBS_TYPE_LOG . " AND zbsm_key = %s AND zbsm_val = %s)", array( $meta_pair_key, $meta_pair['value'] ) ); } #} ============ / WHERE =============== #} Build out any WHERE clauses $wheresArr= $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort($sortByField,$sortOrder) . $this->buildPaging($page,$perPage); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_results($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret results (Result Set - multi-row) if (isset($potentialRes) && is_array($potentialRes) && count($potentialRes) > 0) { #} Has results, tidy + return foreach ($potentialRes as $resDataLine) { if ($incMeta) $resDataLine->meta = $this->DAL()->getMeta(array( 'objtype' => ZBS_TYPE_LOG, 'objid' => $resDataLine->ID, 'key' => 'logmeta', 'fullDetails' => false, 'default' => -1 )); // tidy $resArr = $this->tidy_log($resDataLine); $res[] = $resArr; } } return $res; } /** * returns log lines, ignoring obj/owner - added to infill a few funcs ms added, not sure where used (not core) * (zeroBS_searchLogs + allLogs) * * @param array $args Associative array of arguments * searchPhrase, sortByField, sortOrder, page, perPage * * @return array of tag lines */ public function getLogsForANYObj($args=array()){ #} ============ LOAD ARGS ============= $defaultArgs = array( 'objtype' => -1, // optional 'searchPhrase' => -1, // specify to search through all note descs 'notetype' => -1, // specify a permified type to grab collection 'notetypes' => -1, // specify an array of permified types to grab collection // return 'incMeta' => false, 'sortByField' => 'ID', 'sortOrder' => 'ASC', 'page' => 0, 'perPage' => 100, // permissions 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_LOG) // this'll let you not-check the owner of obj ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} ========== CHECK FIELDS ============ // check obtype is legit $objtype = (int)$objtype; #} ========= / CHECK FIELDS =========== global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); #} Build query $query = "SELECT * FROM ".$ZBSCRM_t['logs']; #} ============= WHERE ================ #} objtype if (!empty($objtype)) $wheres['zbsl_objtype'] = array('zbsl_objtype','=','%d',$objtype); #} notetype if (!empty($notetype) && $notetype != -1) $wheres['zbsl_type'] = array('zbsl_type','=','%s',$notetype); #} notetypes if (is_array($notetypes) && count($notetypes) > 0){ $notetypesStr = ''; foreach ($notetypes as $nt){ if (!empty($notetypesStr)) $notetypesStr .= ','; $notetypesStr .= '"'.$nt.'"'; } $wheres['zbsl_types'] = array('zbsl_type','IN','%s','('.$notetypesStr.')'); } #} Search if (!empty($searchPhrase)) { $wheres['zbsl_shortdesc'] = array('zbsl_shortdesc','LIKE','%s','%'.$searchPhrase.'%'); $wheres['zbsl_longdesc'] = array('zbsl_longdesc','LIKE','%s','%'.$searchPhrase.'%'); } #} ============ / WHERE =============== #} Build out any WHERE clauses $wheresArr= $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort($sortByField,$sortOrder) . $this->buildPaging($page,$perPage); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_results($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret results (Result Set - multi-row) if (isset($potentialRes) && is_array($potentialRes) && count($potentialRes) > 0) { #} Has results, tidy + return foreach ($potentialRes as $resDataLine) { if ($incMeta) $resDataLine->meta = $this->DAL()->getMeta(array( 'objtype' => ZBS_TYPE_LOG, 'objid' => $resDataLine->ID, 'key' => 'logmeta', 'fullDetails' => false, 'default' => -1 )); // tidy $resArr = $this->tidy_log($resDataLine); $res[] = $resArr; } } return $res; } /** * Returns a count of logs (owned) * * @return int count */ public function getLogCount($args=array()){ #} ============ LOAD ARGS ============= $defaultArgs = array( // Search/Filtering (leave as false to ignore) 'withType' => false, // will be str if used // permissions 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_LOG), // this'll let you not-check the owner of obj ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= $whereArr = array(); if ($withType !== false && !empty($withType)) $whereArr['status'] = array('zbsl_type','=','%s',$withType); return $this->DAL()->getFieldByWHERE(array( 'objtype' => ZBS_TYPE_LOG, 'colname' => 'COUNT(ID)', 'where' => $whereArr, 'ignoreowner' => $ignoreowner)); } /** * adds or updates a log object * * @param array $args Associative array of arguments * id (not req.), owner (not req.) data -> key/val * * @return int line ID */ public function addUpdateLog($args=array()){ global $zbs,$ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'owner' => -1, // fields (directly) 'data' => array( 'objtype' => -1, 'objid' => -1, 'type' => '', // log type e.g. zbsOc1 (zbsencoded) or custom e.g. "ALARM" 'shortdesc' => '', 'longdesc' => '', 'pinned' => -1, 'meta' => -1, // can be any obj which'll be stored in meta table :) 'created' => -1 // override date? :( ), // where this is true, if a log of matching description strings and type are added to a single object // no add or update will be enacted 'ignore_if_existing_desc_type' => false, // where this is true, if a log with the given array('key','value') exists against an objid/type // no add or update will be enacted 'ignore_if_meta_matching' => false, ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ $id = (int)$id; // if owner = -1, add current if (!isset($owner) || $owner === -1) $owner = zeroBSCRM_user(); // check obtype is legit $data['objtype'] = (int)$data['objtype']; if (!isset($data['objtype']) || $data['objtype'] == -1 || $this->DAL()->objTypeKey($data['objtype']) === -1) return false; // check id present + legit $data['objid'] = (int)$data['objid']; if (empty($data['objid']) || $data['objid'] <= 0) return false; // check type not empty if (empty($data['type'])) return false; // check for existing log which has same type and description values $has_desc_matching_record = false; if ( $ignore_if_existing_desc_type ){ // find existing - will become unperformant if a contact ever gets 10's of thousands of notes of a type $existing_logs = $this->getLogsForObj( array( 'objtype' => $data['objtype'], 'objid' => $data['objid'], 'notetype' => $data['type'], 'page' => -1, 'perPage' => -1, )); if ( is_array( $existing_logs ) ){ foreach ( $existing_logs as $log ){ if ( $log['shortdesc'] == $data['shortdesc'] && $log['longdesc'] == $data['longdesc'] ){ // log with this type and matching description strings already exists against this object $has_desc_matching_record = true; } } } } // check for exsting with meta $has_meta_matching_record = false; if ( is_array( $ignore_if_meta_matching ) && isset( $ignore_if_meta_matching['key'] ) && isset( $ignore_if_meta_matching['value'] ) ){ // find existing $existing_logs = $this->getLogsForObj( array( 'objtype' => $data['objtype'], 'objid' => $data['objid'], 'meta_pair' => array( 'key' => $ignore_if_meta_matching['key'], 'value' => $ignore_if_meta_matching['value'], ) )); if ( is_array( $existing_logs ) && count( $existing_logs ) > 0 ){ // log with this meta already exists against this object $has_meta_matching_record = true; } } // here we allow either or | both | none // this lets us say 'is there a record with these meta + matching short/long desc' together // both if ( $ignore_if_existing_desc_type && is_array( $ignore_if_meta_matching ) && isset( $ignore_if_meta_matching['key'] ) && isset( $ignore_if_meta_matching['value'] ) ){ // both or fail if ( $has_meta_matching_record && $has_desc_matching_record ){ return false; } // either or } else if ( $ignore_if_existing_desc_type || is_array( $ignore_if_meta_matching ) && isset( $ignore_if_meta_matching['key'] ) && isset( $ignore_if_meta_matching['value'] ) ){ // either = fail if ( $has_meta_matching_record || $has_desc_matching_record ){ return false; } } #} ========= / CHECK FIELDS =========== $dataArr = array( // ownership // no need to update these (as of yet) - can't move teams etc. //'zbs_site' => zeroBSCRM_installSite(), //'zbs_team' => zeroBSCRM_installTeam(), 'zbs_owner' => $owner, // fields 'zbsl_objtype' => $data['objtype'], 'zbsl_objid' => $data['objid'], 'zbsl_type' => $data['type'], 'zbsl_shortdesc' => $data['shortdesc'], 'zbsl_longdesc' => $data['longdesc'], 'zbsl_pinned' => $data['pinned'], 'zbsl_lastupdated' => time() ); $dataTypes = array( // field data types '%d', '%d', '%d', '%s', '%s', '%s', '%d', '%d' ); if (isset($data['created']) && !empty($data['created']) && $data['created'] !== -1){ $dataArr['zbsl_created'] = $data['created']; $dataTypes[] = '%d'; } if (isset($id) && !empty($id) && $id > 0){ #} Check if obj exists (here) - for now just brutal update (will error when doesn't exist) #} Attempt update if ($wpdb->update( $ZBSCRM_t['logs'], $dataArr, array( // where 'ID' => $id ), $dataTypes, array( // where data types '%d' )) !== false){ // any meta if ( isset( $data['meta']) && is_array( $data['meta'] ) ){ // add/update each meta key pair foreach ( $data['meta'] as $k => $v ){ // simple add $this->DAL()->updateMeta( ZBS_TYPE_LOG, $id, $this->DAL()->makeSlug( $k ), $v ); } } #} Internal Automator if (!empty($id)){ zeroBSCRM_FireInternalAutomator('log.update',array( 'id'=>$id, 'logagainst'=>$data['objid'], 'logagainsttype'=>$data['objtype'], 'logtype'=> $data['type'], 'logshortdesc' => $data['shortdesc'], 'loglongdesc' => $data['longdesc'] )); } // Successfully updated - Return id return $id; } else { $msg = __('DB Update Failed','zero-bs-crm'); $zbs->DAL->addError(302,$this->objectType,$msg,$dataArr); // FAILED update return false; } } else { // set created if not set if (!isset($dataArr['zbsl_created'])) { $dataArr['zbsl_created'] = time(); $dataTypes[] = '%d'; } // add team etc $dataArr['zbs_site'] = zeroBSCRM_site(); $dataTypes[] = '%d'; $dataArr['zbs_team'] = zeroBSCRM_team(); $dataTypes[] = '%d'; #} No ID - must be an INSERT if ($wpdb->insert( $ZBSCRM_t['logs'], $dataArr, $dataTypes ) > 0){ #} Successfully inserted, lets return new ID $newID = $wpdb->insert_id; // any meta if ( isset( $data['meta']) && is_array( $data['meta'] ) ){ // add/update each meta key pair foreach ( $data['meta'] as $k => $v ){ // simple add $this->DAL()->updateMeta( ZBS_TYPE_LOG, $newID, $this->DAL()->makeSlug( $k ), $v ); } } #} Internal Automator if (!empty($newID)){ zeroBSCRM_FireInternalAutomator('log.new',array( 'id'=>$newID, 'logagainst'=>$data['objid'], 'logagainsttype'=>$data['objtype'], 'logtype'=> $data['type'], 'logshortdesc' => $data['shortdesc'], 'loglongdesc' => $data['longdesc'] )); } return $newID; } else { $msg = __('DB Insert Failed','zero-bs-crm'); $zbs->DAL->addError(303,$this->objectType,$msg,$dataArr); #} Failed to Insert return false; } } return false; } /** * deletes a Log object * NOTE! this doesn't yet delete any META! * * @param array $args Associative array of arguments * id * * @return int success; */ public function deleteLog($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1 ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} Check ID & Delete :) $id = (int)$id; if (!empty($id) && $id > 0) return zeroBSCRM_db2_deleteGeneric($id,'logs'); return false; } /** * Pins a log object to its contact * * @param array $args Associative array of arguments * id * * @return int success; */ public function set_log_pin_status( $args = array() ){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'pinned' => 1 ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ if ( $pinned !== 1 ){ $pinned = -1; } // attempt update return $wpdb->update( $ZBSCRM_t['logs'], array( 'zbsl_pinned' => $pinned ), array( // where 'ID' => $id ), array( // field data types '%d', ), array( // where data types '%d' )); } /** * tidy's the object from wp db into clean array * * @param array $obj (DB obj) * * @return array (clean obj) */ private function tidy_log($obj=false){ $res = false; if (isset($obj->ID)){ $res = array(); $res['id'] = $obj->ID; $res['owner'] = $obj->zbs_owner; // added these two for backward compatibility / alias of (TROY modifications): // please use owner ideally :) $res['authorid'] = $obj->zbs_owner; $res['author'] = get_the_author_meta('display_name',$obj->zbs_owner); $res['objtype'] = $obj->zbsl_objtype; $res['objid'] = $obj->zbsl_objid; $res['type'] = $this->stripSlashes($obj->zbsl_type); $res['shortdesc'] = $this->stripSlashes($obj->zbsl_shortdesc); $res['longdesc'] = $this->stripSlashes($obj->zbsl_longdesc); $res['pinned'] = ( (int)$obj->zbsl_pinned === 1 ); // to maintain old obj more easily, here we refine created into datestamp $res['created'] = zeroBSCRM_locale_utsToDatetime($obj->zbsl_created); $res['createduts'] = $obj->zbsl_created; // this is the UTS (int14) $res['lastupdated'] = $obj->zbsl_lastupdated; if (isset($obj->meta)) $res['meta'] = $obj->meta; } return $res; } /** * Translates a clear text log type to a lowercase (kinda) permalink * ... this is kinda DAL1 legacy * * @param string * * @return string */ public function logTypeIn($str=''){ $x = str_replace(' ','_',$str); $x = str_replace(':','_',$x); return strtolower($x); } /** * Translates a db text log type to a clear text output * ... this is kinda DAL1 legacy * *UNTESTED * * @param string * * @return string */ public function logTypeOut($str=''){ $x = str_replace('_',' ',$str); $x = str_replace(' ',': ',$x); return ucwords($x); } // =========== / LOGS ======================================================= // =============================================================================== } // / class
projects/plugins/crm/includes/ZeroBSCRM.SystemChecks.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V1.20 * * Copyright 2020 Automattic * * Date: 01/11/16 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== Generic System Check Wrapper/Helper funcs ====================================================== */ /** * Check if a PHP systems/library is correctly installed. * * @param string $key The feature we want to know the status off. * @param bool $with_info Weather we should return a message or not. * * @return array|false */ function zeroBSCRM_checkSystemFeat( $key = '', $with_info = false ) { $feat_list = array( 'zlib', 'dompdf', 'mb_internal_encoding', 'pdffonts', 'curl', 'phpver', 'wordpressver', 'locale', 'assetdir', 'executiontime', 'memorylimit', 'postmaxsize', 'uploadmaxfilesize', 'wpuploadmaxfilesize', 'dbver', 'dalver', 'corever', 'local', 'localtime', 'serverdefaulttime', 'sqlrights', 'devmode', 'permalinks', 'dbserver', 'innodb', 'fontinstalled', 'encryptionmethod', ); if ( in_array( $key, $feat_list, true ) ) { if ( function_exists( 'zeroBSCRM_checkSystemFeat_' . $key ) ) { return call_user_func_array( 'zeroBSCRM_checkSystemFeat_' . $key, array( $with_info ) ); } if ( function_exists( 'zbscrm_check_system_feat_' . $key ) ) { return call_user_func_array( 'zbscrm_check_system_feat_' . $key, array( $with_info ) ); } } if ( ! $with_info ) { return false; } else { return array( false, __( 'No Check!', 'zero-bs-crm' ) ); } } function zeroBSCRM_checkSystemFeat_permalinks(){ if(zeroBSCRM_checkPrettyPermalinks()){ $enabled = true; $enabledStr = 'Permalinks ' . get_option('permalink_structure'); return array($enabled, $enabledStr); }else{ $enabled = false; $enabledStr = ' Pretty Permalinks need to be enabled'; return array($enabled, $enabledStr); } } function zeroBSCRM_checkSystemFeat_fontinstalled($withInfo=false){ global $zbs; $fonts = $zbs->get_fonts(); if (!$withInfo) return $fonts->default_fonts_installed(); else { $enabled = $fonts->default_fonts_installed(); if ( $enabled ){ $enabledStr = __( "Font installed", 'zero-bs-crm' ); } else { $enabledStr = sprintf( __( 'Font not installed (<a href="%s" target="_blank">reinstall pdf engine module</a>)', 'zero-bs-crm' ), jpcrm_esc_link( $zbs->slugs['modules'] ) ); } return array($enabled, $enabledStr); } } function zeroBSCRM_checkSystemFeat_corever($withInfo=false){ global $zbs; if (!$withInfo) return $zbs->version; else { $enabled = true; $enabledStr = 'Version ' . $zbs->version; return array($enabled, $enabledStr); } } function zeroBSCRM_checkSystemFeat_dbver($withInfo=false){ global $zbs; if (!$withInfo) return $zbs->db_version; else { $enabled = true; $enabledStr = 'Database Version ' . $zbs->db_version; return array($enabled, $enabledStr); } } function zeroBSCRM_checkSystemFeat_dalver($withInfo=false){ global $zbs; if (!$withInfo) return $zbs->dal_version; else { $enabled = true; $enabledStr = 'Data Access Layer Version ' . $zbs->dal_version; return array($enabled, $enabledStr); } } function zeroBSCRM_checkSystemFeat_phpver($withInfo=false){ if (!$withInfo) return PHP_VERSION; else { $enabled = true; $enabledStr = 'PHP Version ' . PHP_VERSION; return array($enabled, $enabledStr); } } function zeroBSCRM_checkSystemFeat_wordpressver($withInfo=false){ global $wp_version; if (!$withInfo) return $wp_version; else { $enabled = true; $enabledStr = sprintf(__("WordPress Version %s", 'zero-bs-crm'), $wp_version); return array($enabled, $enabledStr); } } function zeroBSCRM_checkSystemFeat_local($withInfo=false){ $local = zeroBSCRM_isLocal(); if (!$withInfo) return !$local; else { $enabled = !$local; if ($local) $enabledStr = 'Running Locally<br />This may cause connectivity issues with SMTP (Emails) and updates/feature downloads.'; else $enabledStr = 'Connectivity Okay.'; return array($enabled, $enabledStr); } } function zeroBSCRM_checkSystemFeat_serverdefaulttime($withInfo=false){ /*if (function_exists('locale_get_default')) $locale = locale_get_default(); else $locale = Locale::getDefault(); */ $tz = date_default_timezone_get(); if (!$withInfo) return true; else { $enabled = true; $enabledStr = $tz; return array($enabled, $enabledStr); } } function zeroBSCRM_checkSystemFeat_localtime($withInfo=false){ $enabled = true; if (!$withInfo) return true; else { $enabledStr = 'CRM Time: '.zeroBSCRM_date_i18n('Y-m-d H:i:s', time() ).' (GMT: '.date_i18n('Y-m-d H:i:s', time(),true).')'; return array($enabled, $enabledStr); } } // in devmode or not? function zeroBSCRM_checkSystemFeat_devmode($withInfo=false){ $isLocal = zeroBSCRM_isLocal(); if (!$withInfo) return $isLocal; else { global $zbs; $devModeStr = ''; if (!$isLocal){ // check if overriden $key = $zbs->DAL->setting('localoverride',false); // if set, less than 48h ago, is overriden if ($key !== false && $key > time()-172800) $devModeStr = __('Production','zero-bs-crm').' (override)'; else // normal production (99% users) $devModeStr = __('Production','zero-bs-crm'); } else { // devmode proper $devModeStr = __('Developer Mode','zero-bs-crm'); } return array($isLocal, $devModeStr); } } // https://wordpress.stackexchange.com/questions/6424/mysql-database-user-which-privileges-are-needed // can we create tables? function zeroBSCRM_checkSystemFeat_sqlrights($withInfo=false){ global $wpdb; // run check tables zeroBSCRM_checkTablesExist(); $lastError = $wpdb->last_error; $okay = true; if ( str_contains( $lastError, 'command denied' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $okay = false; } if (!$withInfo) return $okay; else { global $zbs; $enabled = $okay; if ($enabled) $enabledStr = __('Appears Okay','zero-bs-crm'); else $enabledStr = __('Error','zero-bs-crm').': '.$lastError; return array($enabled, $enabledStr); } } /** * Get info about the database server engine and version. * * @param boolean $with_info Provides extra info. */ function zeroBSCRM_checkSystemFeat_dbserver( $with_info = false ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid if ( ! $with_info ) { return zeroBSCRM_database_getVersion(); } else { return array( 1, jpcrm_database_engine( true ) . ' (' . zeroBSCRM_database_getVersion() . ')' ); } } // got InnoDB? function zeroBSCRM_checkSystemFeat_innodb($withInfo=false){ if (!$withInfo) return zeroBSCRM_DB_canInnoDB() ? __('Available','zero-bs-crm') : __('Not Available','zero-bs-crm'); else { $innoDB = zeroBSCRM_DB_canInnoDB(); return array($innoDB, ($innoDB ? __('Available','zero-bs-crm') : __('Not Available','zero-bs-crm'))); } } // below here: https://stackoverflow.com/questions/8744107/increase-max-execution-time-in-php function zeroBSCRM_checkSystemFeat_executiontime($withInfo=false){ $maxExecution = ini_get('max_execution_time'); if (!$withInfo) return $maxExecution; else { $str = $maxExecution.' seconds'; // catch infinites if ($maxExecution == '0') $str = 'No Limit'; return array($maxExecution,$str); } } function zeroBSCRM_checkSystemFeat_memorylimit($withInfo=false){ $maxMemory = ini_get('memory_limit'); if (!$withInfo) return $maxMemory; else { $str = $maxMemory; return array($maxMemory,$str); } } function zeroBSCRM_checkSystemFeat_postmaxsize($withInfo=false){ $post_max_size = ini_get('post_max_size'); if (!$withInfo) return $post_max_size; else { $str = $post_max_size; return array($post_max_size,$str); } } function zeroBSCRM_checkSystemFeat_uploadmaxfilesize($withInfo=false){ $upload_max_filesize = ini_get('upload_max_filesize'); if (!$withInfo) return $upload_max_filesize; else { $str = $upload_max_filesize; return array($upload_max_filesize,$str); } } function zeroBSCRM_checkSystemFeat_wpuploadmaxfilesize($withInfo=false){ //https://codex.wordpress.org/Function_Reference/wp_max_upload_size $wp_max_upload_size = zeroBSCRM_prettyformatBytes(wp_max_upload_size()); if (!$withInfo) return $wp_max_upload_size; else { $str = $wp_max_upload_size; return array($wp_max_upload_size,$str); } } /* * Encryption method check */ function zeroBSCRM_checkSystemFeat_encryptionmethod( $withInfo = false ){ global $zbs; // load encryption $encryption = $zbs->load_encryption(); // any issues? $return_string = ''; // check if has flipped fallback previously $fallback_blocked = zeroBSCRM_getSetting( 'enc_fallback_blocked' ); if ( !empty( $fallback_blocked ) ) { $return_string = __( '<span class="ui label red">Warning!</span> Encryption disabled due to no available encryption method. Please contact support.', 'zero-bs-crm' ); } // check if has flipped fallback previously $fallback_active = zeroBSCRM_getSetting( 'enc_fallback_active' ); if ( !empty( $fallback_active ) ) { $return_string = sprintf( __( '<span class="ui label orange">Note:</span> Encryption using fallback method (%s) due to no available encryption method. Please contact support.', 'zero-bs-crm' ), $encryption->cipher_method() ); } if ( !$withInfo ){ return $encryption->ready_to_encrypt(); } else { if ( empty( $return_string ) ){ $return_string = $encryption->cipher_method(); } return array( $encryption->ready_to_encrypt(), $return_string ); } } // https://codex.wordpress.org/Using_Permalinks#Tips_and_Tricks function zeroBSCRM_checkPrettyPermalinks(){ if ( get_option('permalink_structure') ) { return true; }else{ return false; } } /* ====================================================== / Generic System Check Wrapper/Helper funcs ====================================================== */ /* ====================================================== Specific System Check Wrapper/Helper funcs ====================================================== */ function zeroBSCRM_checkSystemFeat_zlib($withInfo=false){ if ( !$withInfo ) return class_exists('ZipArchive'); else { $enabled = class_exists('ZipArchive'); $str = __('zlib is properly enabled on your server.','zero-bs-crm'); if ( !$enabled ) { $str = __('zlib is disabled on your server.','zero-bs-crm'); // see if fallback pclzip is working if ( class_exists('PclZip') ){ // it's probably all fine $enabled = true; $str .= ' '.__("But don't worry, as the fallback PclZip appears to work.",'zero-bs-crm'); } } return array($enabled,$str); } } /** * * Verify mb_internal_encoding (required by dompdf) * */ function zeroBSCRM_checkSystemFeat_mb_internal_encoding( $withInfo=false ) { $enabled = function_exists( 'mb_internal_encoding' ); if ( !$withInfo ) { return $enabled; } $str = __( 'The mbstring PHP module is properly enabled on your server.', 'zero-bs-crm' ); if ( !$enabled ) { $str = __( 'The mbstring PHP module is disabled on your server, which may prevent PDFs from being generated.', 'zero-bs-crm' ); } return array( $enabled, $str ); } /** * Check if Dompdf is installed correctly on the server. * * @param false $with_info Determine if the returning results contains an explanatory string. * * @return array|bool */ function zbscrm_check_system_feat_dompdf( $with_info = false ) { $enabled = class_exists( Dompdf\Dompdf::class ); if ( ! $with_info ) { return $enabled; } if ( ! $enabled ) { return array( $enabled, __( 'PDF Engine is not installed on your server.', 'zero-bs-crm' ), ); } try { $dompdf = new \Dompdf\Dompdf(); $version = $dompdf->version; } catch ( \Exception $e ) { $version = 'unknown'; } return array( $enabled, /* translators: %s a version that explain which library is used and what version number it's running. */ sprintf( __( 'PDF Engine is properly installed on your server (Version: %s).', 'zero-bs-crm' ), $version ), ); } function zeroBSCRM_checkSystemFeat_pdffonts($withInfo=false){ // get fonts dir $fonts_dir = jpcrm_storage_fonts_dir_path(); $fonts_installed = file_exists( $fonts_dir . 'fonts-info.txt' ); if (!$withInfo) { return $fonts_installed; } else { $str = 'PDF fonts appear to be installed on your server.'; if ( !$fonts_installed ) { $str = 'PDF fonts do not appear to be installed on your server.'; } return array($fonts_installed,$str); } } function zeroBSCRM_checkSystemFeat_curl($withInfo=false){ if (!$withInfo) return function_exists('curl_init'); else { $enabled = function_exists('curl_init'); $str = 'CURL is enabled on your server.'; if (!$enabled) $str = 'CURL is not enabled on your server.'; return array($enabled,$str); } } function zeroBSCRM_checkSystemFeat_locale($withInfo=false){ if (!$withInfo) return true; else { $locale = zeroBSCRM_getLocale(); $str = 'WordPress Locale is set to <strong>'.$locale.'</strong>'; $str .= ' (Server: '.zeroBSCRM_locale_getServerLocale().')'; return array(true,$str); } } function zeroBSCRM_checkSystemFeat_assetdir(){ $potentialDirObj = zeroBSCRM_privatisedDirCheck(); if (is_array($potentialDirObj) && isset($potentialDirObj['path'])) $potentialDir = $potentialDirObj['path']; else $potentialDir = false; $enabled = false; $enabledStr = 'Using Default WP Upload Library'; if (!empty($potentialDir)) { $enabled = true; $enabledStr = $potentialDir; } return array($enabled, $enabledStr); }
projects/plugins/crm/includes/ZeroBSCRM.Core.DateTime.php
<?php /* ! * Jetpack CRM * http://www.zerobscrm.com * V2.98.2+ * * Copyright 2020 Automattic * * Date: 05/03/2019 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) { exit; } /* ====================================================== / Breaking Checks ====================================================== */ // https://stackoverflow.com/questions/1416697/converting-timestamp-to-time-ago-in-php-e-g-1-day-ago-2-days-ago // ^^ so many semi-working solutions
projects/plugins/crm/includes/ZeroBSCRM.ScreenOptions.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V2.76+ * * Copyright 2020 Automattic * * Date: 27/05/18 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ // outputs top of page screen options panel :) // (based on rights + pagekey) function zeroBSCRM_screenOptionsPanel(){ global $zbs; $screenOptionsHTML = ''; $options = array(); $rights = true; // this is 'okay for everyone' - current_user_can('administrator')? $screenOpts = $zbs->global_screen_options(); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase switch ($zbs->pageKey){ // contact edit case 'zbs-add-edit-contact-edit': $options['metaboxes'] = zeroBSCRM_getCurrentMetaboxesFlatArr(); break; // company view case 'zbs-add-edit-company-view': if(!array_key_exists('tablecolumns', $options)){ $options['tablecolumns'] = array(); } if (!is_array($options['tablecolumns'])) $options['tablecolumns'] = array(); // global $zbsTransactionFields; // get existing from setting $activeTransactionColumns = array('date','id','total','status'); // default // not from setting, from screenopt $allColumns = zeroBSCRM_getSetting('company_view_docs_columns'); //if (isset($allColumns['transactions']) && is_array($allColumns['transactions']) && count($allColumns['transactions']) > 0) $zbsTransactionFields = $allColumns['transactions']; if ( isset($screenOpts) && is_array($screenOpts) && isset($screenOpts['tablecolumns']) && is_array($screenOpts['tablecolumns']) && isset($screenOpts['tablecolumns']['transactions']) && is_array($screenOpts['tablecolumns']['transactions']) && count($screenOpts['tablecolumns']['transactions']) > 0 ) $activeTransactionColumns = $screenOpts['tablecolumns']['transactions']; $options['tablecolumns']['transactions'] = $activeTransactionColumns; break; } // build html if (count($options) > 0){ // build metabox show/hide if (isset($options['metaboxes'])){ // get hidden list $hidden = array(); if (is_array($screenOpts) && isset($screenOpts['mb_hidden']) && is_array($screenOpts['mb_hidden'])) $hidden = $screenOpts['mb_hidden']; // allow rearrange? // Don't use anymore :) MS UI input $rearrangeButton = '<button class="ui mini button orange" type="button" id="zbs-metabox-manager"><i class="arrows alternate icon"></i>'.__('Re-arrange','zero-bs-crm').'</button>'; $rearrangeButton = ''; // build html list $screenOptionsHTML .= '<div class="zbs-screenoptions-opt zbs-screenoptions-metaboxes"><div class="ui dividing header">'.__('Boxes','zero-bs-crm').$rearrangeButton.'</div><div class="ui divided grid"><div class="row">'; // show lists - normal if (isset($options['metaboxes']['normal']) && is_array($options['metaboxes']['normal']) && count($options['metaboxes']['normal']) > 0){ // for now, just doing lines $screenOptionsHTML .= '<div class="ten wide column">'; $screenOptionsHTML .= '<div class="sixteen wide column"><h4 class="ui header">'.__('Main Column','zero-bs-crm').'</h4>'; foreach ($options['metaboxes']['normal'] as $mbID => $mb){ $mbTitle = $mbID; if (is_array($mb) && isset($mb['title'])) $mbTitle = $mb['title']; // if can hide $canHide = true; if (isset($mb['capabilities']) && isset($mb['capabilities']['can_hide']) && $mb['capabilities']['can_hide'] == false) $canHide = false; if ($canHide){ $screenOptionsHTML .= '<div class="ui checkbox zbs-metabox-checkbox"><input type="checkbox" id="zbs-mb-'.$mbID.'"'; if (!in_array($mbID, $hidden)) $screenOptionsHTML .= ' checked="checked"'; $screenOptionsHTML .= ' /><label for="zbs-mb-'.$mbID.'">'.$mbTitle.'</label></div>'; } else { $screenOptionsHTML .= '<div class="ui checkbox zbs-metabox-checkbox"><input type="checkbox" id="zbs-mb-'.$mbID.'" checked="checked" disabled="disabled"><label for="zbs-mb-'.$mbID.'">'.$mbTitle.'</label></div>'; } } $screenOptionsHTML .= '</div>'; } // show list - side if (isset($options['metaboxes']['side']) && is_array($options['metaboxes']['side']) && count($options['metaboxes']['side']) > 0){ // for now, just doing lines $screenOptionsHTML .= '<div class="six wide column">'; $screenOptionsHTML .= '<div class="sixteen wide column"><h4 class="ui header">'.__('Side','zero-bs-crm').'</h4>'; foreach ($options['metaboxes']['side'] as $mbID => $mb){ $mbTitle = $mbID; if (is_array($mb) && isset($mb['title'])) $mbTitle = $mb['title']; // if can hide $canHide = true; if (isset($mb['capabilities']) && isset($mb['capabilities']['can_hide']) && $mb['capabilities']['can_hide'] == false) $canHide = false; if ($canHide){ $screenOptionsHTML .= '<div class="ui checkbox zbs-metabox-checkbox"><input type="checkbox" id="zbs-mb-'.$mbID.'"'; if (!in_array($mbID, $hidden)) $screenOptionsHTML .= ' checked="checked"'; $screenOptionsHTML .= ' /><label for="zbs-mb-'.$mbID.'">'.$mbTitle.'</label></div>'; } else { $screenOptionsHTML .= '<div class="ui checkbox zbs-metabox-checkbox"><input type="checkbox" id="zbs-mb-'.$mbID.'" checked="checked" disabled="disabled"><label for="zbs-mb-'.$mbID.'">'.$mbTitle.'</label></div>'; } } $screenOptionsHTML .= '</div>'; } $screenOptionsHTML .= '</div></div></div>'; // end row + grid + group } // build tablecolumns on/off if (isset($options['tablecolumns']) && is_array($options['tablecolumns']) && count($options['tablecolumns']) > 0){ // build html list $screenOptionsHTML .= '<div class="zbs-screenoptions-opt zbs-screenoptions-tablecolumns"><div class="ui dividing header">'.__('Document Table Columns','zero-bs-crm').'</div><div class="ui divided grid"><div class="row">'; foreach ($options['tablecolumns'] as $type => $selectedColumns){ switch ($type){ case 'transactions': // get whole list (of poss columns - list fields, then columns) // these are in two types of arrays, so first, shuffle them into a kinda standardised type global $zbsTransactionFields, $zeroBSCRM_columns_transaction; // exclusions (wh temp workaround) $excludeColumnKeys = array('customer','customer_name','currency','tagged','added','tax_rate','customeremail'); $availableColumns = array(); // all fields (inc custom:) if (isset($zbsTransactionFields) && is_array($zbsTransactionFields) && count($zbsTransactionFields) > 0) foreach ($zbsTransactionFields as $tKey => $tDeets){ // key => name if (!in_array($tKey, $excludeColumnKeys)) $availableColumns[$tKey] = $tDeets[1]; } // all columns (any with same key will override) if (isset($zeroBSCRM_columns_transaction['all']) && is_array($zeroBSCRM_columns_transaction['all']) && count($zeroBSCRM_columns_transaction['all']) > 0) foreach ($zeroBSCRM_columns_transaction['all'] as $tKey => $tDeets){ // key => name if (!in_array($tKey, $excludeColumnKeys)) $availableColumns[$tKey] = $tDeets[0]; } // show list of cols if (isset($availableColumns) && is_array($availableColumns) && count($availableColumns) > 0){ // for now, just doing lines $screenOptionsHTML .= '<div class="ten wide column">'; $screenOptionsHTML .= '<div class="sixteen wide column" id="zbs-tablecolumns-'.$type.'"><h4 class="ui header">'.__('Transactions Table','zero-bs-crm').'</h4>'; foreach ($availableColumns as $colKey => $colName){ $screenOptionsHTML .= '<div class="ui checkbox zbs-tablecolumn-checkbox" data-colkey="'.$colKey.'"><input type="checkbox" id="zbs-tc-'.$colKey.'"'; if (in_array($colKey, $selectedColumns)) $screenOptionsHTML .= ' checked="checked"'; $screenOptionsHTML .= ' /><label for="zbs-tc-'.$colKey.'">'.$colName.'</label></div>'; } $screenOptionsHTML .= '</div>'; } break; } } // foreach type $screenOptionsHTML .= '</div></div></div>'; // end row + grid } // if tablecolumns } if (!empty($screenOptionsHTML)){ ?> <div id="zbs-screen-options" class="ui segment hidden"> <?php echo ( $rights ? $screenOptionsHTML : '' ); /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped,WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase */ ?> </div> <?php } } function zeroBS_outputScreenOptions(){ global $zbs; $screenOpts = $zbs->global_screen_options(); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?><script type="text/javascript">var zbsPageKey = '<?php echo esc_html( $zbs->pageKey ); ?>';var zbsScreenOptions = <?php echo json_encode($screenOpts); ?>;</script><?php } add_action('admin_footer','zeroBS_outputScreenOptions'); function zeroBS_canUpdateScreenOptions(){ // does this need to check if is zbs wp usr? $id = get_current_user_id(); if ($id > 0) return true; return false; }
projects/plugins/crm/includes/ZeroBSCRM.MetaBoxes3.Logs.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V3.0 * * Copyright 2020 Automattic * * Date: 20/02/2019 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== Init Func ====================================================== */ function zeroBSCRM_LogsMetaboxSetup(){ // req. for custom log types zeroBSCRM_setupLogTypes(); } add_action( 'after_zerobscrm_settings_init','zeroBSCRM_LogsMetaboxSetup'); /* ====================================================== / Init Func ====================================================== */ /* ====================================================== Declare Globals ====================================================== */ global $zeroBSCRM_logTypes; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $zeroBSCRM_logTypes = array( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // // phpcs:disable WordPress.Arrays.ArrayDeclarationSpacing.AssociativeArrayFound 'zerobs_customer' => array( 'note' => array( 'label' => __( 'Note', 'zero-bs-crm' ), 'ico' => 'fa-sticky-note-o' ), 'call' => array( 'label' => __( 'Call', 'zero-bs-crm' ), 'ico' => 'fa-phone-square' ), 'email' => array( 'label' => __( 'Email', 'zero-bs-crm' ), 'ico' => 'fa-envelope-o' ), 'mail' => array( 'label' => __( 'Mail', 'zero-bs-crm' ), 'ico' => 'fa-envelope-o' ), 'meeting' => array( 'label' => __( 'Meeting', 'zero-bs-crm' ), 'ico' => 'fa-users' ), 'quote__sent' => array( 'label' => __( 'Quote: Sent', 'zero-bs-crm' ), 'ico' => 'fa-share-square-o' ), 'quote__accepted' => array( 'label' => __( 'Quote: Accepted', 'zero-bs-crm' ), 'ico' => 'fa-thumbs-o-up' ), 'quote__refused' => array( 'label' => __( 'Quote: Refused', 'zero-bs-crm' ), 'ico' => 'fa-ban' ), 'invoice__sent' => array( 'label' => __( 'Invoice: Sent', 'zero-bs-crm' ), 'ico' => 'fa-share-square-o' ), 'invoice__part_paid' => array( 'label' => __( 'Invoice: Part Paid', 'zero-bs-crm' ), 'ico' => 'fa-money' ), 'invoice__paid' => array( 'label' => __( 'Invoice: Paid', 'zero-bs-crm' ), 'ico' => 'fa-money' ), 'invoice__refunded' => array( 'label' => __( 'Invoice: Refunded', 'zero-bs-crm' ), 'ico' => 'fa-money' ), 'transaction' => array( 'label' => __( 'Transaction', 'zero-bs-crm' ), 'ico' => 'fa-credit-card' ), 'feedback' => array( 'label' => __( 'Feedback', 'zero-bs-crm' ), 'ico' => 'fa-commenting' ), 'tweet' => array( 'label' => __( 'Tweet', 'zero-bs-crm' ), 'ico' => 'fa-twitter' ), 'facebook_post' => array( 'label' => __( 'Facebook Post', 'zero-bs-crm' ), 'ico' => 'fa-facebook-official' ), 'other_contact' => array( 'label' => __( 'Other contact', 'zero-bs-crm' ), 'ico' => 'fa-users' ), 'created' => array( 'locked' => true, 'label' => __( 'Created', 'zero-bs-crm' ), 'ico' => 'fa-plus-circle' ), 'updated' => array( 'locked' => true, 'label' => __( 'Updated', 'zero-bs-crm' ), 'ico' => 'fa-pencil-square-o' ), 'quote_created' => array( 'locked' => true, 'label' => __( 'Quote Created', 'zero-bs-crm' ), 'ico' => 'fa-plus-circle' ), 'invoice_created' => array( 'locked' => true, 'label' => __( 'Invoice Created', 'zero-bs-crm' ), 'ico' => 'fa-plus-circle' ), 'event_created' => array( 'locked' => true, 'label' => __( 'Task Created', 'zero-bs-crm' ), 'ico' => 'fa-calendar' ), 'task_created' => array( 'locked' => true, 'label' => __( 'Task Created', 'zero-bs-crm' ), 'ico' => 'fa-calendar' ), 'transaction_created' => array( 'locked' => true, 'label' => __( 'Transaction Created', 'zero-bs-crm' ), 'ico' => 'fa-credit-card' ), 'transaction_updated' => array( 'locked' => true, 'label' => __( 'Transaction Updated', 'zero-bs-crm' ), 'ico' => 'fa-credit-card' ), 'transaction_deleted' => array( 'locked' => true, 'label' => __( 'Transaction Deleted', 'zero-bs-crm' ), 'ico' => 'fa-credit-card' ), 'form_filled' => array( 'locked' => true, 'label' => __( 'Form Filled', 'zero-bs-crm' ), 'ico' => 'fa-wpforms' ), 'api_action' => array( 'locked' => true, 'label' => __( 'API Action', 'zero-bs-crm' ), 'ico' => 'fa-random' ), 'bulk_action__merge' => array( 'locked' => true, 'label' => __( 'Bulk Action: Merge', 'zero-bs-crm' ), 'ico' => 'fa-compress' ), 'client_portal_user_created' => array( 'locked' => true, 'label' => __( 'Client Portal User Created', 'zero-bs-crm' ), 'ico' => 'fa-id-card' ), 'client_portal_access_changed' => array( 'locked' => true, 'label' => __( 'Client Portal Access Changed', 'zero-bs-crm' ), 'ico' => 'fa-id-card' ), 'status_change' => array( 'locked' => true, 'label' => __( 'Status Change', 'zero-bs-crm' ), 'ico' => 'fa-random' ), 'contact_changed_details_via_portal' => array( 'locked' => true, 'label' => __( 'Contact Changed via Portal', 'zero-bs-crm' ), 'ico' => 'fa-id-card' ), 'contact_changed_details_via_wpprofile' => array( 'locked' => true, 'label' => __( 'Contact Changed via WordPress Profile', 'zero-bs-crm' ), 'ico' => 'fa-id-card' ), 'contact_changed_details_via_woomyacc' => array( 'locked' => true, 'label' => __( 'Contact Changed via WooCommerce My Account', 'zero-bs-crm' ), 'ico' => 'fa-id-card' ), 'contact_changed_details_via_mailpoet' => array( 'locked' => true, 'label' => __( 'Contact Changed via MailPoet', 'zero-bs-crm' ), 'ico' => 'fa-id-card' ), 'subscriber_deleted_in_mailpoet' => array( 'locked' => true, 'label' => __( 'Subscriber deleted in MailPoet', 'zero-bs-crm' ), 'ico' => 'fa-times' ), 'contact_change_details_attempt' => array( 'locked' => true, 'label' => __( 'Attempted Contact detail change', 'zero-bs-crm' ), 'ico' => 'fa-id-card' ), ), 'zerobs_company' => array( 'note' => array( 'label' => __( 'Note', 'zero-bs-crm' ), 'ico' => 'fa-sticky-note-o' ), 'call' => array( 'label' => __( 'Call', 'zero-bs-crm' ), 'ico' => 'fa-phone-square' ), 'email' => array( 'label' => __( 'Email', 'zero-bs-crm' ), 'ico' => 'fa-envelope-o' ), 'created' => array( 'locked' => true, 'label' => __( 'Created', 'zero-bs-crm' ), 'ico' => 'fa-plus-circle' ), 'updated' => array( 'locked' => true, 'label' => __( 'Updated', 'zero-bs-crm' ), 'ico' => 'fa-pencil-square-o' ), ), // // phpcs:enable WordPress.Arrays.ArrayDeclarationSpacing.AssociativeArrayFound ); function zeroBSCRM_permifyLogType($logTypeStr=''){ return strtolower(str_replace(' ','_',str_replace(':','_',$logTypeStr))); } function zeroBSCRM_setupLogTypes(){ global $zeroBSCRM_logTypes; // hide log types for objects that are disabled $hide_quotes = zeroBSCRM_getSetting('feat_quotes') == -1; $hide_invoices = zeroBSCRM_getSetting('feat_invs') == -1; $hide_transactions = zeroBSCRM_getSetting('feat_transactions') == -1; foreach ( $zeroBSCRM_logTypes['zerobs_customer'] as $log_type => $log_type_value) { if ( $hide_quotes && str_starts_with( $log_type, 'quote' ) || $hide_invoices && str_starts_with( $log_type, 'invoice' ) || $hide_transactions && str_starts_with( $log_type, 'transaction' ) ) { $zeroBSCRM_logTypes['zerobs_customer'][$log_type]['locked'] = true; } } // apply filters $zeroBSCRM_logTypes = apply_filters('zbs_logtype_array', $zeroBSCRM_logTypes); } /* ====================================================== / Declare Globals ====================================================== */ /* ====================================================== Logs (v3 DB3) Metabox ====================================================== */ class zeroBS__Metabox_LogsV2 extends zeroBS__Metabox { public $objtypeid = false; // child fills out e.g. ZBS_TYPE_CONTACT public $metaboxLocation = 'normal'; /** * The legacy object name (e.g. 'zerobs_customer') * * @var string */ private $postType; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.PropertyNotSnakeCase public function __construct( $plugin_file ) { // call this $this->initMetabox(); } public function html( $obj, $metabox ) { global $zbs; // needs conversion to set this v3+ // // obj type (1 => zerobs_customer) // we load from DAL defaults, if objTypeID passed (overriding anything passed, if empty/false) if (isset($this->objtypeid)){ //$zbs->isDAL3() && $objTypeID = (int)$this->objtypeid; if ($objTypeID > 0){ // obj type (1 => zerobs_customer) $objTypeStr = $zbs->DAL->typeCPT($objTypeID); if ((!isset($this->postType) || $this->postType == false) && !empty($objTypeStr)) $this->postType = $objTypeStr; } //echo 'loading from '.$this->objTypeID.':<pre>'.print_r(array($objTypeStr,$objSingular,$objPlural,$objSlug),1).'</pre>'; exit(); } $objid = -1; if (is_array($obj) && isset($obj['id'])) $objid = $obj['id']; #} Only load if is legit. //if (in_array($this->postType,array('zerobs_customer'))){ if (in_array($this->objtypeid,array(ZBS_TYPE_CONTACT,ZBS_TYPE_COMPANY))){ #} Proceed #} Retrieve $zbsLogs = $zbs->DAL->logs->getLogsForObj(array( 'objtype' => $this->objtypeid, 'objid' => $objid, 'searchPhrase' => '', 'incMeta' => false, 'sortByField' => 'zbsl_created', 'sortOrder' => 'DESC', 'page' => 0, 'perPage' => 100, 'ignoreowner' => true )); if (!is_array($zbsLogs)) $zbsLogs = array(); ?> <script type="text/javascript">var zbscrmjs_logsSecToken = '<?php echo esc_js( wp_create_nonce( 'zbscrmjs-ajax-nonce-logs' ) ); ?>';</script> <table class="form-table wh-metatab wptbp" id="wptbpMetaBoxLogs"> <tr> <td><h4><span id="zbsActiveLogCount"><?php echo esc_html( zeroBSCRM_prettifyLongInts( count( $zbsLogs ) ) ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?></span> <?php esc_html_e( 'Logs', 'zero-bs-crm' ); ?></h4></td> <td><button type="button" class="ui button black jpcrm-button" id="zbscrmAddLog"><?php esc_html_e( 'Add Log', 'zero-bs-crm' ); ?></button></td> </tr> <!-- this line will pop/close with "add log" button --> <tr id="zbsAddLogFormTR" style="display:none"><td colspan="2"> <div id="zbsAddLogForm"> <div id="zbsAddLogIco"> <!-- this will change with select changing... --> <i class="fa fa-sticky-note-o" aria-hidden="true"></i> </div> <label for="zbsAddLogType"><?php esc_html_e("Activity Type","zero-bs-crm");?>:</label> <select id="zbsAddLogType" class="form-control zbsUpdateTypeAdd"> <?php global $zeroBSCRM_logTypes; if (isset($zeroBSCRM_logTypes[$this->postType]) && count($zeroBSCRM_logTypes[$this->postType]) > 0) foreach ($zeroBSCRM_logTypes[$this->postType] as $logKey => $logType){ // not for locked logs if (isset($logType['locked']) && $logType['locked']){ // nope } else { ?><option value="<?php echo esc_attr( $logKey ); ?>"><?php esc_html_e($logType['label'],"zero-bs-crm"); ?></option><?php } } ?> </select> <br /> <label for="zbsAddLogMainDesc"><?php esc_html_e("Activity Description","zero-bs-crm")?>:</label> <input type="text" class="form-control" id="zbsAddLogMainDesc" placeholder="e.g. <?php esc_attr_e( 'Called and talked to Todd about service x, seemed keen', 'zero-bs-crm' ); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>" /> <label for="zbsAddLogDetailedDesc"><?php esc_html_e("Activity Detailed Notes","zero-bs-crm");?>:</label> <textarea class="form-control" id="zbsAddLogDetailedDesc" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>"></textarea> <label for="zbsAddLogPinNote"><?php esc_html_e( 'Pin note', 'zero-bs-crm' ); ?>:</label> <input type="checkbox" id="zbsAddLogPinNote" /> <div id="zbsAddLogActions"> <div id="zbsAddLogUpdateMsg"></div> <button type="button" class="jpcrm-button white-bg" id="zbscrmAddLogCancel"><?php esc_html_e( 'Cancel', 'zero-bs-crm' ); ?></button> <button type="button" class="jpcrm-button" id="zbscrmAddLogSave"><?php esc_html_e( 'Save Log', 'zero-bs-crm' ); ?></button> </div> </div> <!-- edit log form is to be moved about by edit routines :) --> <div id="zbsEditLogForm"> <div id="zbsEditLogIco"> <!-- this will change with select changing... --> <i class="fa fa-sticky-note-o" aria-hidden="true"></i> </div> <label for="zbsEditLogType"><?php esc_html_e("Activity Type","zero-bs-crm");?>:</label> <select id="zbsEditLogType" class="form-control zbsUpdateTypeEdit" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>"> <?php global $zeroBSCRM_logTypes; if (isset($zeroBSCRM_logTypes[$this->postType]) && count($zeroBSCRM_logTypes[$this->postType]) > 0) foreach ($zeroBSCRM_logTypes[$this->postType] as $logKey => $logType){ // not for locked logs if (isset($logType['locked']) && $logType['locked']){ // nope } else { ?><option value="<?php echo esc_attr( $logKey ); ?>"><?php echo esc_html( $logType['label'] ); ?></option><?php } } ?> </select> <br /> <label for="zbsEditLogMainDesc"><?php esc_html_e("Activity Description","zero-bs-crm");?>:</label> <input type="text" class="form-control" id="zbsEditLogMainDesc" placeholder="e.g. 'Called and talked to Todd about service x, seemed keen'" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>" /> <label for="zbsEditLogDetailedDesc"><?php esc_html_e("Activity Detailed Notes","zero-bs-crm");?>:</label> <textarea class="form-control" id="zbsEditLogDetailedDesc" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>"></textarea> <label for="zbsEditLogPinNote"><?php esc_html_e( 'Pin note', 'zero-bs-crm' ); ?>:</label> <input type="checkbox" id="zbsEditLogPinNote" /> <div id="zbsEditLogActions"> <div id="zbsEditLogUpdateMsg"></div> <button type="button" class="button button-info button-large" id="zbscrmEditLogCancel"><?php esc_html_e("Cancel","zero-bs-crm");?></button> <button type="button" class="button button-primary button-large" id="zbscrmEditLogSave"><?php esc_html_e("Save Log","zero-bs-crm");?></button> </div> </div> </td></tr> <?php if (isset($wDebug)) { ?><tr><td colspan="2"><pre><?php print_r($zbsLogs) ?></pre></td></tr><?php } ?> <tr><td colspan="2"> <?php # Output logs (let JS do this!) #if (count($zbsLogs) > 0){ } ?> <div id="zbsAddLogOutputWrap"></div> </td></tr> </table> <style type="text/css"> #submitdiv { display:none; } </style> <script type="text/javascript"> var zbsLogPerms = <?php echo json_encode(array('addedit'=>zeroBSCRM_permsLogsAddEdit(),'delete'=>zeroBSCRM_permsLogsDelete())); ?>; var zbsLogAgainstID = <?php echo esc_html( $objid ); ?>; var zbsLogProcessingBlocker = false; <?php if (isset($_GET['addlog']) && $_GET['addlog'] == "1"){ // this just opens new log for those who've clicked through from another page echo 'var initialiseAddLog = true;'; } #} Centralised log types :) global $zeroBSCRM_logTypes; #} Build array of locked logs $lockedLogs = array(); if (isset($zeroBSCRM_logTypes[$this->postType]) && count($zeroBSCRM_logTypes[$this->postType]) > 0) foreach ($zeroBSCRM_logTypes[$this->postType] as $logTypeKey => $logTypeDeet){ if (isset($logTypeDeet['locked']) && $logTypeDeet['locked']) $lockedLogs[$logTypeKey] = true; } echo 'var zbsLogsLocked = '.json_encode($lockedLogs).';'; /* var zbsLogsLocked = { 'created': true, 'updated': true, 'quote_created': true, 'invoice_created': true, 'form_filled': true }; */ if (isset($zeroBSCRM_logTypes[$this->postType]) && count($zeroBSCRM_logTypes[$this->postType]) > 0) { echo 'var zbsLogTypes = '.json_encode($zeroBSCRM_logTypes[$this->postType]).';'; } ?> var zbsLogIndex = <?php #} Array or empty if (count($zbsLogs) > 0 && is_array($zbsLogs)) { $zbsLogsExpose = array(); foreach ($zbsLogs as $zbsLog){ $retLine = $zbsLog; if (isset($retLine) && isset($retLine['longdesc'])) $retLine['longdesc'] = wp_kses( html_entity_decode( $retLine['longdesc'], ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 ), $zbs->acceptable_restricted_html ); $zbsLogsExpose[] = $retLine; } echo json_encode($zbsLogsExpose); } else echo json_encode(array()); // phpcs:disable Generic.WhiteSpace.DisallowSpaceIndent.SpacesUsed ?>; var zbsLogEditing = -1; // def ico var zbsLogDefIco = 'fa-sticky-note-o'; jQuery(function(){ // build log ui zbscrmjs_buildLogs(); // if url has addlogs=1, init open addlogs :) // passed down from php via var higher up in this file setTimeout(function(){ if (typeof window.initialiseAddLog != "undefined"){ jQuery('#zbscrmAddLog').trigger( 'click' ); } },500); // add log button jQuery('#zbscrmAddLog').on( 'click', function(){ if (jQuery(this).css('display') == 'block'){ jQuery('#zbsAddLogFormTR').slideDown('400', function() { }); jQuery(this).hide(); } else { jQuery('#zbsAddLogFormTR').hide(); jQuery(this).show(); } }); // cancel jQuery('#zbscrmAddLogCancel').on( 'click', function(){ jQuery('#zbsAddLogFormTR').hide(); jQuery('#zbscrmAddLog').show(); }); // save jQuery('#zbscrmAddLogSave').on( 'click', function(){ //jQuery('#zbsAddLogFormTR').hide(); //jQuery('#zbscrmAddLog').show(); /* zbsnagainstid zbsntype zbsnshortdesc zbsnlongdesc zbsnoverwriteid pinned */ // get / check data var data = {sec:window.zbscrmjs_logsSecToken,zbsnobjtype:'<?php echo esc_html( $this->postType ); ?>'}; var errs = 0; if ((jQuery('#zbsAddLogType').val()).length > 0) data.zbsntype = jQuery('#zbsAddLogType').val(); if ((jQuery('#zbsAddLogMainDesc').val()).length > 0) data.zbsnshortdesc = jQuery('#zbsAddLogMainDesc').val(); if ((jQuery('#zbsAddLogDetailedDesc').val()).length > 0) data.zbsnlongdesc = jQuery('#zbsAddLogDetailedDesc').val(); else data.zbsnlongdesc = ''; if (jQuery('#zbsAddLogPinNote').is(':checked')) { data.pinned = true; } // post id & no need for overwrite id as is new data.zbsnagainstid = parseInt(window.zbsLogAgainstID); // debug console.log('posting new note: ',data); // validate var msgOut = ''; if (typeof data.zbsntype == "undefined" || data.zbsntype == '') { errs++; msgOut = 'Note Type is required!'; jQuery('#zbsAddLogType').css('border','2px solid orange'); setTimeout(function(){ jQuery('#zbsAddLogUpdateMsg').html(''); jQuery('#zbsAddLogType').css('border','1px solid #ddd'); },1500); } if (typeof data.zbsnshortdesc == "undefined" || data.zbsnshortdesc == '') { errs++; if (msgOut == 'Note Type is required!') msgOut = 'Note Type and Description are required!'; else msgOut += 'Note Description is required!'; jQuery('#zbsAddLogMainDesc').css('border','2px solid orange'); setTimeout(function(){ jQuery('#zbsAddLogUpdateMsg').html(''); jQuery('#zbsAddLogMainDesc').css('border','1px solid #ddd'); },1500); } if (errs === 0){ // add action data.action = 'zbsaddlog'; zbscrmjs_addNewNote(data,function(newLog){ // success // msg jQuery('#zbsAddLogUpdateMsg').html('Saved!'); // then hide form, build new log gui, clear form // hide + clear form jQuery('#zbsAddLogFormTR').hide(); jQuery('#zbscrmAddLog').show(); jQuery('#zbsAddLogType').val('note'); jQuery('#zbsAddLogMainDesc').val(''); jQuery('#zbsAddLogDetailedDesc').val(''); jQuery('#zbsAddLogPinNote').prop('checked', false); jQuery('#zbsAddLogUpdateMsg').html(''); // add it (build example obj) var newLogObj = { id: newLog.logID, created: '', //moment(), type: newLog.zbsntype, shortdesc: newLog.zbsnshortdesc, longdesc: zbscrmjs_nl2br(newLog.zbsnlongdesc) } if (newLog.pinned) { newLogObj.pinned = true; } zbscrmjs_addNewNoteLine(newLogObj,true); // also add to window obj window.zbsLogIndex.push(newLogObj); // bind ui setTimeout(function(){ zbscrmjs_bindNoteUIJS(); zbscrmjs_updateLogCount(); },0); },function(){ // failure // msg + do nothing jQuery('#zbsAddLogUpdateMsg').html('There was an error when saving this note!'); }); } else { if (typeof msgOut !== "undefined" && msgOut != '') jQuery('#zbsAddLogUpdateMsg').html(msgOut); } }); // note ico - works for both edit + add jQuery('#zbsAddLogType, #zbsEditLogType').on( 'change', function(){ // get perm var logPerm = zbscrmjs_permify(jQuery(this).val()); // jQuery('#zbsAddLogType').val() var thisIco = window.zbsLogDefIco; // find ico if (typeof window.zbsLogTypes[logPerm] != "undefined") thisIco = window.zbsLogTypes[logPerm].ico; // override all existing classes with ones we want: if (jQuery(this).hasClass('zbsUpdateTypeAdd')) jQuery('#zbsAddLogIco i').attr('class','fa ' + thisIco); if (jQuery(this).hasClass('zbsUpdateTypeEdit')) jQuery('#zbsEditLogIco i').attr('class','fa ' + thisIco); }); }); function zbscrmjs_updateLogCount(){ var count = 0; if (window.zbsLogIndex.length > 0) count = parseInt(window.zbsLogIndex.length); jQuery('#zbsActiveLogCount').html(zbscrmjs_prettifyLongInts(count)); } // build log ui function zbscrmjs_buildLogs(){ // get from obj var theseLogs = window.zbsLogIndex; jQuery.each(theseLogs,function(ind,ele){ zbscrmjs_addNewNoteLine(ele); }); // bind ui setTimeout(function(){ zbscrmjs_bindNoteUIJS(); zbscrmjs_updateLogCount(); },0); } function zbscrmjs_addNewNoteLine(ele,prepflag,replaceExisting){ // localise var logMeta = ele; if (typeof ele.meta != "undefined") logMeta = ele.meta; // get perm var logPerm = zbscrmjs_permify(logMeta.type); // classes (pinned) var classes = ''; if ( typeof ele.pinned !== "undefined" && ele.pinned ){ classes = ' jpcrm-pinned'; } // build it var thisLogHTML = '<div class="zbsLogOut' + classes + '" data-logid="' + ele.id + '" id="zbsLogOutLine' + ele.id + '" data-logtype="' + logPerm + '">'; // type ico var thisIco = window.zbsLogDefIco; // find ico if (typeof window.zbsLogTypes[logPerm] != "undefined") thisIco = window.zbsLogTypes[logPerm].ico; // output thisLogHTML += '<div class="zbsLogOutIco"><i class="fa ' + thisIco + '" aria-hidden="true"></i></div>'; // created date if (typeof ele.created !== "undefined" && ele.created !== '') { // not req: var offsetStr = zbscrmjs_getTimeZoneOffset(); // date, inc any timezone offset as set in wp: window.zbs_root.timezone_offset //console.log("Creating moment bare",[moment(ele.created + ' ' + offsetStr, 'YYYY-MM-DD HH:mm:ss Z'), moment(ele.created + ' ' + offsetStr, 'YYYY-MM-DD HH:mm:ss Z','en'), offsetStr, moment(ele.created, 'YYYY-MM-DD HH:mm:ss').utcOffset(offsetStr)]); //var createdMoment = moment(ele.created + ' ' + offsetStr, 'YYYY-MM-DD HH:mm:ss Z', 'en'); //var createdMoment = moment(ele.created, 'YYYY-MM-DD HH:mm:ss').utcOffset(offsetStr); //var nowAdjusted = moment(); //.utcOffset(offsetStr); //console.log("compare",[createdMoment.format(),nowAdjusted.format(),createdMoment.from(nowAdjusted),createdMoment.fromNow()]); // this works best in the end, just add / - any offset var createdMoment = moment.unix(ele.createduts); thisLogHTML += '<div class="zbsLogOutCreated" data-zbscreated="' + ele.created + '" title="' + createdMoment.format('lll') + '">' + createdMoment.fromNow() + '</div>'; } else { // empty created means just created obj var createdMoment = moment(); thisLogHTML += '<div class="zbsLogOutCreated" data-zbscreated="' + createdMoment + '" title="' + createdMoment.format('lll') + '">' + createdMoment.fromNow() + '</div>'; } // title var thisTitle = ''; // find type var thisType = ucwords(logMeta.type); if (typeof window.zbsLogTypes[logPerm] != "undefined") thisType = window.zbsLogTypes[logPerm].label; // type if (typeof thisType !== "undefined") thisTitle += '<span>' + thisType + '</span>'; // desc if (typeof logMeta.shortdesc !== "undefined") { if (thisTitle != '') thisTitle += ': '; thisTitle += jpcrm_strip_scripts(logMeta.shortdesc); } var logEditElements = '<div class="zbsLogOutEdits"><i class="fa fa-pencil-square-o zbsLogActionEdit" title="<?php esc_attr_e('Edit Log',"zero-bs-crm");?>"></i><i class="fa fa-thumb-tack jpcrm_log_pin" title="<?php esc_attr_e('Pin log to contact', 'zero-bs-crm' ); ?>"></i><i class="fa fa-thumb-tack jpcrm_log_unpin" title="<?php esc_attr_e('Unpin log from contact', 'zero-bs-crm' ); ?>"></i><i class="fa fa-trash-o zbsLogActionRemove last" title="<?php esc_attr_e('Delete Log',"zero-bs-crm");?>"></i><span></span></div>'; thisLogHTML += '<div class="zbsLogOutTitle">' + thisTitle + logEditElements + '</div>'; // desc if (typeof logMeta.longdesc !== "undefined" && logMeta.longdesc !== '' && logMeta.longdesc !== null) thisLogHTML += '<div class="zbsLogOutDesc">' + jpcrm_strip_scripts(logMeta.longdesc) + '</div>'; thisLogHTML += '</div>'; if (typeof replaceExisting == "undefined"){ // normal // add it if (typeof prepflag !== "undefined") jQuery('#zbsAddLogOutputWrap').prepend(thisLogHTML); else jQuery('#zbsAddLogOutputWrap').append(thisLogHTML); } else { // replace existing jQuery('#zbsLogOutLine' + ele.id).replaceWith(thisLogHTML); } } function zbscrmjs_bindNoteUIJS(){ // show hide edit controls jQuery('.zbsLogOut').on( 'mouseenter', function(){ var logType = jQuery(this).attr('data-logtype'); // only if not editing another :) + Log Type is not one we don't have in our set if (window.zbsLogEditing == -1 && typeof window.zbsLogTypes[logType] != "undefined"){ // check if locked log or not! if (typeof logType == "undefined") logType = ''; // if log type empty, or has a key in window.zbsLogsLocked, don't allow edits // ... and finally check perms too if ( logType != '' && !window.zbsLogsLocked.hasOwnProperty(logType) && window.zbsLogPerms.addedit // can add edit ){ // check if can delete if (window.zbsLogPerms.delete){ // can jQuery('.zbsLogActionRemove',jQuery(this)).css('display','inline-block'); } else { // can't jQuery('.zbsLogActionRemove',jQuery(this)).css('display','none'); } // yep (overall) jQuery('.zbsLogOutEdits',jQuery(this)).css('display','inline-block'); } } }).on( 'mouseleave', function(){ jQuery('.zbsLogOutEdits',jQuery(this)).not('.stayhovered').css('display','none'); }); // bind del jQuery('.zbsLogOutEdits .zbsLogActionRemove').off('click').on( 'click', function(){ if (window.zbsLogPerms.delete){ // append "deleting" jQuery(this).closest('.zbsLogOutEdits').addClass('stayhovered'); jQuery('span',jQuery(this).closest('.zbsLogOutEdits')).html('<?php esc_html_e( 'Deleting', 'zero-bs-crm' ); ?>...'); var noteID = parseInt(jQuery(this).closest('.zbsLogOut').attr('data-logid')); if (noteID > 0){ var thisEle = this; zbscrmjs_deleteNote(noteID,function(){ // success // localise var nID = noteID; // append "deleted" and then vanish jQuery('span',jQuery(thisEle).closest('.zbsLogOutEdits')).html('Deleted!...'); var that = thisEle; setTimeout(function(){ // localise var thisNoteID = nID; // also del from window obj zbscrmjs_removeItemFromLogIndx(thisNoteID); // update count span zbscrmjs_updateLogCount(); // slide up jQuery(that).closest('.zbsLogOut').slideUp(400,function(){ // and remove itself? }); },500); },function(){ //TODO: proper error msg console.error('There was an issue retrieving this note for editing/deleting'); }); } else console.error('There was an issue retrieving this note for editing/deleting'); //TODO: proper error msg } // if perms }); // bind pin jQuery('.zbsLogOutEdits .jpcrm_log_pin').off('click').on( 'click', function(){ // append "pinning" jQuery(this).closest('.zbsLogOutEdits').addClass('stayhovered'); jQuery('span',jQuery(this).closest('.zbsLogOutEdits')).html('<?php esc_html_e( 'Pinning', 'zero-bs-crm' ); ?>...'); var noteID = parseInt(jQuery(this).closest('.zbsLogOut').attr('data-logid')); if (noteID > 0){ var thisEle = this; jpcrm_js_pin_note( noteID, function(){ // success // localise var nID = noteID; // append "pinned" jQuery('span',jQuery(thisEle).closest('.zbsLogOutEdits')).html('<?php esc_html_e( 'Pinned', 'zero-bs-crm' ); ?>'); var that = thisEle; setTimeout(function(){ // add pinned jQuery(that).closest('.zbsLogOut').addClass( 'jpcrm-pinned' ); jQuery('span',jQuery(that).closest('.zbsLogOutEdits')).html(''); jQuery(that).closest('.zbsLogOutEdits').removeClass( 'stayhovered' ); jQuery(that).closest('.zbsLogOutEdits').css('display','none'); },500); },function(){ //TODO: proper error msg console.error('There was an issue pinning this log'); }); } else console.error('There was an issue pinning this log'); //TODO: proper error msg }); // bind unpin jQuery('.zbsLogOutEdits .jpcrm_log_unpin').off('click').on( 'click', function(){ // append "pinning" jQuery(this).closest('.zbsLogOutEdits').addClass('stayhovered'); jQuery('span',jQuery(this).closest('.zbsLogOutEdits')).html('<?php esc_html_e( 'Removing Pin', 'zero-bs-crm' ); ?>...'); var noteID = parseInt(jQuery(this).closest('.zbsLogOut').attr('data-logid')); if (noteID > 0){ var thisEle = this; jpcrm_js_unpin_note( noteID, function(){ // success // localise var nID = noteID; // append "pinned" jQuery('span',jQuery(thisEle).closest('.zbsLogOutEdits')).html('<?php esc_html_e( 'Unpinned', 'zero-bs-crm' ); ?>'); var that = thisEle; setTimeout(function(){ // remove pinned jQuery(that).closest('.zbsLogOut').removeClass( 'jpcrm-pinned' ); jQuery('span',jQuery(that).closest('.zbsLogOutEdits')).html(''); jQuery(that).closest('.zbsLogOutEdits').removeClass( 'stayhovered' ); jQuery(that).closest('.zbsLogOutEdits').css('display','none'); },500); },function(){ //TODO: proper error msg console.error('There was an issue pinning this log'); }); } else console.error('There was an issue pinning this log'); //TODO: proper error msg }); // bind edit jQuery('.zbsLogOutEdits .zbsLogActionEdit').off('click').on( 'click', function(){ if (window.zbsLogPerms.addedit){ // one at a time please sir... if (window.zbsLogEditing == -1){ // get edit id var noteID = parseInt(jQuery(this).closest('.zbsLogOut').attr('data-logid')); // get edit obj var editObj = zbscrmjs_retrieveItemFromIndex(noteID); // move edit box to before here jQuery('#zbsEditLogForm').insertBefore('#zbsLogOutLine' + noteID); setTimeout(function(){ var lObj = editObj; if (typeof lObj.meta != "undefined") lObj = lObj.meta; // pre dal2 // update edit box texts etc. jQuery('#zbsEditLogMainDesc').val(lObj.shortdesc); jQuery('#zbsEditLogDetailedDesc').val(zbscrmjs_reversenl2br(lObj.longdesc)); jQuery('#zbsEditLogPinNote').prop('checked', lObj.pinned); jQuery('#zbsEditLogType option').each(function(){ if (zbscrmjs_permify(jQuery(this).text()) == lObj.type) { jQuery(this).attr('selected', 'selected'); return false; } return true; }); // type ico // get perm var logPerm = zbscrmjs_permify(lObj.type); var thisIco = window.zbsLogDefIco; // find ico if (typeof window.zbsLogTypes[logPerm] != "undefined") thisIco = window.zbsLogTypes[logPerm].ico; // update jQuery('#zbsEditLogIco i').attr('class','fa ' + thisIco); },10); // set edit vars window.zbsLogEditing = noteID; // hide line / show edit jQuery('#zbsLogOutLine' + noteID).slideUp(); jQuery('#zbsEditLogForm').slideDown(); // bind zbscrmjs_bindEditNote(); } } // if perms }); } function zbscrmjs_bindEditNote(){ // cancel jQuery('#zbscrmEditLogCancel').on( 'click', function(){ // get note id var noteID = window.zbsLogEditing; // hide edit from jQuery('#zbsEditLogForm').hide(); // show back log jQuery('#zbsLogOutLine' + noteID).show(); // unset noteID window.zbsLogEditing = -1; }); // save jQuery('#zbscrmEditLogSave').on( 'click', function(){ if (window.zbsLogEditing > -1){ // get note id var noteID = window.zbsLogEditing; //jQuery('#zbsEditLogFormTR').hide(); //jQuery('#zbscrmEditLog').show(); /* zbsnagainstid zbsntype zbsnshortdesc zbsnlongdesc zbsnoverwriteid */ // get / check data var data = {sec:window.zbscrmjs_logsSecToken,zbsnobjtype:'<?php echo $this->postType; ?>'}; var errs = 0; // same as add code, but with note id: data.zbsnprevid = noteID; if ((jQuery('#zbsEditLogType').val()).length > 0) data.zbsntype = jQuery('#zbsEditLogType').val(); if ((jQuery('#zbsEditLogMainDesc').val()).length > 0) data.zbsnshortdesc = jQuery('#zbsEditLogMainDesc').val(); if ((jQuery('#zbsEditLogDetailedDesc').val()).length > 0) data.zbsnlongdesc = jQuery('#zbsEditLogDetailedDesc').val(); else data.zbsnlongdesc = ''; if (jQuery('#zbsEditLogPinNote').is(':checked')) { data.pinned = true; } // post id & no need for overwrite id as is new data.zbsnagainstid = parseInt(window.zbsLogAgainstID); // validate var msgOut = ''; if (typeof data.zbsntype == "undefined" || data.zbsntype == '') { errs++; msgOut = 'Note Type is required!'; jQuery('#zbsEditLogType').css('border','2px solid orange'); setTimeout(function(){ jQuery('#zbsEditLogUpdateMsg').html(''); jQuery('#zbsEditLogType').css('border','1px solid #ddd'); },1500); } if (typeof data.zbsnshortdesc == "undefined" || data.zbsnshortdesc == '') { errs++; if (msgOut == 'Note Type is required!') msgOut = 'Note Type and Description are required!'; else msgOut += 'Note Description is required!'; jQuery('#zbsEditLogMainDesc').css('border','2px solid orange'); setTimeout(function(){ jQuery('#zbsEditLogUpdateMsg').html(''); jQuery('#zbsEditLogMainDesc').css('border','1px solid #ddd'); },1500); } if (errs === 0){ // add action data.action = 'zbsupdatelog'; zbscrmjs_updateNote(data,function(newLog){ // success // msg jQuery('#zbsEditLogUpdateMsg').html('Changes Saved!'); // then hide form, build new log gui, clear form // hide + clear form jQuery('#zbsEditLogForm').hide(); jQuery('#zbsEditLogType').val('Note'); jQuery('#zbsEditLogMainDesc').val(''); jQuery('#zbsEditLogDetailedDesc').val(''); jQuery('#zbsEditLogPinNote').prop('checked', false); jQuery('#zbsEditLogUpdateMsg').html(''); // update it (build example obj) var newLogObj = { id: newLog.logID, created: '', meta: { type: newLog.zbsntype, shortdesc: newLog.zbsnshortdesc, // have to replace the nl2br for long desc: longdesc: zbscrmjs_nl2br(newLog.zbsnlongdesc) } } if (newLog.pinned) { newLogObj.pinned = true; } zbscrmjs_addNewNoteLine(newLogObj,true,true); // third param here is "replace existing" // also add to window obj in prev place //window.zbsLogIndex.push(newLogObj); zbscrmjs_replaceItemInLogIndx(newLog.logID,newLogObj); // unset noteID window.zbsLogEditing = -1; // bind ui setTimeout(function(){ zbscrmjs_bindNoteUIJS(); zbscrmjs_updateLogCount(); },0); },function(){ // failure // msg + do nothing jQuery('#zbsEditLogUpdateMsg').html('There was an error when saving this note!'); }); } else { if (typeof msgOut !== "undefined" && msgOut != '') jQuery('#zbsEditLogUpdateMsg').html(msgOut); } } // if note id }); } function zbscrmjs_removeItemFromLogIndx(noteID){ var logIndex = window.zbsLogIndex; var newLogIndex = []; jQuery.each(logIndex,function(ind,ele){ if (typeof ele.id != "undefined" && ele.id != noteID) newLogIndex.push(ele); }); window.zbsLogIndex = newLogIndex; // fini return window.zbsLogIndex; } function zbscrmjs_replaceItemInLogIndx(noteIDToReplace,newObj){ var logIndex = window.zbsLogIndex; var newLogIndex = []; jQuery.each(logIndex,function(ind,ele){ if (typeof ele.id != "undefined") if (ele.id != noteIDToReplace) newLogIndex.push(ele); else // is to replace newLogIndex.push(newObj); }); window.zbsLogIndex = newLogIndex; // fini return window.zbsLogIndex; } function zbscrmjs_retrieveItemFromIndex(noteID){ var logIndex = window.zbsLogIndex; var logObj = -1; jQuery.each(logIndex,function(ind,ele){ if (typeof ele.id != "undefined" && ele.id == noteID) logObj = ele; }); return logObj; } // function assumes a legit dataArr :) (validate above) function zbscrmjs_addNewNote(dataArr,cb,errcb){ // needs nonce. <!--#NONCENEEDED --> if (!window.zbsLogProcessingBlocker){ // blocker window.zbsLogProcessingBlocker = true; // msg jQuery('#zbsAddLogUpdateMsg').html('<?php esc_html_e('Saving...',"zero-bs-crm");?>'); // Send jQuery.ajax({ type: "POST", url: ajaxurl, // admin side is just ajaxurl not wptbpAJAX.ajaxurl, "data": dataArr, dataType: 'json', timeout: 20000, success: function(response) { // Debug console.log("RESPONSE",response); // blocker window.zbsLogProcessingBlocker = false; // this also has true/false on update... if (typeof response.processed != "undefined" && response.processed){ // callback // make a merged item... var retArr = dataArr; dataArr.logID = response.processed; if (typeof cb == "function") cb(retArr); } else { // .. was an error :) // callback if (typeof errcb == "function") errcb(response); } }, error: function(response){ // Debug console.error("RESPONSE",response); // blocker window.zbsLogProcessingBlocker = false; // callback if (typeof errcb == "function") errcb(response); } }); } else { // end of blocker jQuery('#zbsAddLogUpdateMsg').html('... already processing!'); setTimeout(function(){ jQuery('#zbsAddLogUpdateMsg').html(''); },2000); } } // function assumes a legit dataArr :) (validate above) // is almost a clone of _addNote (homogenise later) function zbscrmjs_updateNote(dataArr,cb,errcb){ // needs nonce. <!--#NONCENEEDED --> if (!window.zbsLogProcessingBlocker){ // blocker window.zbsLogProcessingBlocker = true; // msg jQuery('#zbsEditLogUpdateMsg').html('<?php esc_html_e('Saving...',"zero-bs-crm");?>'); // Send jQuery.ajax({ type: "POST", url: ajaxurl, // admin side is just ajaxurl not wptbpAJAX.ajaxurl, "data": dataArr, dataType: 'json', timeout: 20000, success: function(response) { // Debug console.log("RESPONSE",response); // blocker window.zbsLogProcessingBlocker = false; // this also has true/false on update... if (typeof response.processed != "undefined" && response.processed){ // callback // make a merged item... var retArr = dataArr; dataArr.logID = response.processed; if (typeof cb == "function") cb(retArr); } else { // .. was an error :) // callback if (typeof errcb == "function") errcb(response); } }, error: function(response){ // Debug console.error("RESPONSE",response); // blocker window.zbsLogProcessingBlocker = false; // callback if (typeof errcb == "function") errcb(response); } }); } else { // end of blocker jQuery('#zbsEditLogUpdateMsg').html('... already processing!'); setTimeout(function(){ jQuery('#zbsEditLogUpdateMsg').html(''); },2000); } } // function assumes a legit noteID + perms :) (validate above) function zbscrmjs_deleteNote(noteID,cb,errcb){ // needs nonce. <!--#NONCENEEDED --> if (!window.zbsLogProcessingBlocker){ // blocker window.zbsLogProcessingBlocker = true; // -package var dataArr = { action : 'zbsdellog', zbsnid : noteID, sec:window.zbscrmjs_logsSecToken }; // Send jQuery.ajax({ type: "POST", url: ajaxurl, // admin side is just ajaxurl not wptbpAJAX.ajaxurl, "data": dataArr, dataType: 'json', timeout: 20000, success: function(response) { // Debug console.log("RESPONSE",response); // blocker window.zbsLogProcessingBlocker = false; // this also has true/false on update... if (typeof response.processed != "undefined" && response.processed){ // Debug console.log("SUCCESS"); // callback if (typeof cb == "function") cb(response); } else { // .. was an error :) // Debug console.log("ERRZ"); // callback if (typeof errcb == "function") errcb(response); } }, error: function(response){ // Debug console.error("RESPONSE",response); // blocker window.zbsLogProcessingBlocker = false; // callback if (typeof errcb == "function") errcb(response); } }); } else { // end of blocker } } // function assumes a legit noteID + perms :) (validate above) function jpcrm_js_pin_note(noteID,cb,errcb){ // needs nonce. <!--#NONCENEEDED --> if (!window.zbsLogProcessingBlocker){ // blocker window.zbsLogProcessingBlocker = true; // -package var dataArr = { action : 'jpcrmpinlog', zbsnid : noteID, sec:window.zbscrmjs_logsSecToken }; // Send jQuery.ajax({ type: "POST", url: ajaxurl, // admin side is just ajaxurl not wptbpAJAX.ajaxurl, "data": dataArr, dataType: 'json', timeout: 20000, success: function(response) { // Debug console.log("RESPONSE",response); // blocker window.zbsLogProcessingBlocker = false; // this also has true/false on update... if (typeof response.processed != "undefined" && response.processed){ // Debug console.log("SUCCESS"); // callback if (typeof cb == "function") cb(response); } else { // .. was an error :) // Debug console.log("ERRZ"); // callback if (typeof errcb == "function") errcb(response); } }, error: function(response){ // Debug console.error("RESPONSE",response); // blocker window.zbsLogProcessingBlocker = false; // callback if (typeof errcb == "function") errcb(response); } }); } else { // end of blocker } } // function assumes a legit noteID + perms :) (validate above) function jpcrm_js_unpin_note(noteID,cb,errcb){ // needs nonce. <!--#NONCENEEDED --> if (!window.zbsLogProcessingBlocker){ // blocker window.zbsLogProcessingBlocker = true; // -package var dataArr = { action : 'jpcrmunpinlog', zbsnid : noteID, sec:window.zbscrmjs_logsSecToken }; // Send jQuery.ajax({ type: "POST", url: ajaxurl, // admin side is just ajaxurl not wptbpAJAX.ajaxurl, "data": dataArr, dataType: 'json', timeout: 20000, success: function(response) { // Debug console.log("RESPONSE",response); // blocker window.zbsLogProcessingBlocker = false; // this also has true/false on update... if (typeof response.processed != "undefined" && response.processed){ // Debug console.log("SUCCESS"); // callback if (typeof cb == "function") cb(response); } else { // .. was an error :) // Debug console.log("ERRZ"); // callback if (typeof errcb == "function") errcb(response); } }, error: function(response){ // Debug console.error("RESPONSE",response); // blocker window.zbsLogProcessingBlocker = false; // callback if (typeof errcb == "function") errcb(response); } }); } else { // end of blocker } } </script><?php // phpcs:enable Generic.WhiteSpace.DisallowSpaceIndent.SpacesUsed } // / if post type } public function save_data( $objID, $obj ) { // not req. ajax return $obj; } } /* ====================================================== / Logs V2 - DB2 Metabox ====================================================== */ #} Mark as included :) define('ZBSCRM_INC_LOGSMB',true);
projects/plugins/crm/includes/jpcrm-segment-conditions.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * Core Segment Conditions * */ // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; /* * Returns the default segment conditions */ function jpcrm_segments_default_conditions() { return array( 'status' => array( 'name' => __( 'Status', 'zero-bs-crm' ), 'category' => __( 'Contact Fields', 'zero-bs-crm' ), 'position' => 1, 'description' => __( 'Select contacts based on their status', 'zero-bs-crm' ), 'operators' => array( 'equal', 'notequal'), 'fieldname' => 'status' ), 'fullname' => array( 'name' => __( 'Full Name', 'zero-bs-crm' ), 'category' => __( 'Contact Fields', 'zero-bs-crm' ), 'position' => 1, 'description' => __( 'Select contacts based on their full name ', 'zero-bs-crm' ), 'operators' => array( 'equal', 'notequal', 'contains' ), 'fieldname' => 'fullname' ), 'email' => array( 'name' => __( 'Email', 'zero-bs-crm' ), 'category' => __( 'Contact Fields', 'zero-bs-crm' ), 'position' => 1, 'description' => __( 'Select contacts based on their email address', 'zero-bs-crm' ), 'operators' => array( 'equal', 'notequal', 'contains' ), 'fieldname' => 'email' ), 'dateadded' => array( 'name' => __( 'Date Added', 'zero-bs-crm' ), 'category' => __( 'Contact Fields', 'zero-bs-crm' ), 'description' => __( 'Select contacts by when they were added to the CRM', 'zero-bs-crm' ), 'operators' => array( 'before', 'after', 'daterange', 'datetimerange', 'beforeequal', 'afterequal', 'previousdays' ), 'fieldname' => 'dateadded', 'conversion' => 'date-to-uts' ), 'datelastcontacted' => array( 'name' => __( 'Date Last Contacted', 'zero-bs-crm' ), 'category' => __( 'Contact Fields', 'zero-bs-crm' ), 'description' => __( 'Select contacts by the date that they were last contacted', 'zero-bs-crm' ), 'operators' => array( 'before', 'after', 'daterange', 'datetimerange', 'beforeequal', 'afterequal', 'previousdays' ), 'fieldname' => 'datelastcontacted', 'conversion' => 'date-to-uts' ), 'tagged' => array( 'name' => __( 'Has Tag', 'zero-bs-crm' ), 'category' => __( 'Contact Fields', 'zero-bs-crm' ), 'description' => __( 'Select Contacts who have a specific tag', 'zero-bs-crm' ), 'operators' => array( 'tag' ), 'fieldname' => 'tagged' ), 'nottagged' => array( 'name' => __( 'Is Not Tagged', 'zero-bs-crm' ), 'category' => __( 'Contact Fields', 'zero-bs-crm' ), 'description' => __( 'Select contacts who do not have a specific tag', 'zero-bs-crm' ), 'operators' => array( 'tag' ), 'fieldname' => 'nottagged' ), ); } /* * Returns segment condition category positions (to effect the display order) */ function jpcrm_segments_condition_category_positions() { global $zbs; return apply_filters( 'jpcrm_segment_condition_category_positions', array( $zbs->DAL->makeSlug( __( 'Contact Fields', 'zero-bs-crm' ) ) => 1, $zbs->DAL->makeSlug( __( 'Contact Address Fields', 'zero-bs-crm' ) ) => 2, $zbs->DAL->makeSlug( __( 'Quotes', 'zero-bs-crm' ) ) => 3, $zbs->DAL->makeSlug( __( 'Invoices', 'zero-bs-crm' ) ) => 4, $zbs->DAL->makeSlug( __( 'Transactions', 'zero-bs-crm' ) ) => 5, $zbs->DAL->makeSlug( __( 'Source', 'zero-bs-crm' ) ) => 6, $zbs->DAL->makeSlug( __( 'Ownership', 'zero-bs-crm' ) ) => 7, 'general' => 99 // end of list )); } /* * Retrieves available segment conditions */ function zeroBSCRM_segments_availableConditions( $split_by_category = false ){ global $zbs; // retrieve conditions $available_conditions = apply_filters('zbs_segment_conditions', jpcrm_segments_default_conditions() ); // compare with previous available conditions // (fires jpcrm_segment_conditions_changed action if changes in available conditions) // Note that we only fire this if it's not already been fired on this load (to avoid looping) if ( !defined( 'jpcrm_segments_compared' ) ) { // blocker. This is a prime candidate for core states (#XXX) define( 'jpcrm_segments_compared', 1 ); // compare jpcrm_segments_compare_available_conditions_to_prev( $available_conditions ); } // if not split by category, return as it was if ( !$split_by_category ){ return $available_conditions; } // else, split by category, so build that and return: $category_positions = jpcrm_segments_condition_category_positions(); $conditions_by_category = array( 'general' => array( 'name' => __( 'General', 'zero-bs-crm' ), 'conditions' => array(), 'position' => 99 ) ); foreach ( $available_conditions as $key => $condition ){ if ( isset( $condition['category'] ) ){ $category = $zbs->DAL->makeSlug( $condition['category'] ); $category_position = 99; // to enact category positions, we see if the category has a position, if so we use that as a prefix if ( isset( $category_positions[ $category ] ) ){ $category_position = $category_positions[ $category ]; } // if not set, create it if ( !isset( $conditions_by_category[ $category ] ) ){ $conditions_by_category[ $category ] = array( 'key' => $category, 'name' => $condition['category'], 'conditions' => array(), 'position' => $category_position ); } } else $category = 'general'; // add condition $conditions_by_category[ $category ]['conditions'][ $key ] = $condition; } // sort categories usort( $conditions_by_category, 'jpcrm_segments_sort_conditions_and_categories'); // in turn sort each conditions sub-list by position $conditions_by_category_array = array(); foreach ( $conditions_by_category as $category_key => $category ){ $conditions = $category['conditions']; usort( $conditions, 'jpcrm_segments_sort_conditions_and_categories'); $conditions_by_category_array[ $category_key ] = $category; $conditions_by_category_array[ $category_key ]['conditions'] = $conditions; } ksort( $conditions_by_category_array ); return $conditions_by_category_array; } /* * Sorting function for categories and conditions */ function jpcrm_segments_sort_conditions_and_categories($a, $b){ $position_a = 99; $position_b = 99; if ( isset( $a['position'] ) ){ $position_a = $a['position']; } if ( isset( $b['position'] ) ){ $position_b = $b['position']; } return $position_a < $position_b ? -1 : ($position_a == $position_b ? 0 : 1); } function zeroBSCRM_segments_availableConditionOperators(){ return array( 'equal' => array( 'name' => __( 'Equals (=)', 'zero-bs-crm' ) ), 'notequal' => array( 'name' => __( 'Not equals (!=)', 'zero-bs-crm' ) ), 'contains' => array( 'name' => __( 'Contains (*)', 'zero-bs-crm' ) ), 'doesnotcontain' => array( 'name' => __( 'Does not contain (*)', 'zero-bs-crm' ) ), 'larger' => array( 'name' => __( 'Greater than (>)', 'zero-bs-crm' ) ), 'less' => array( 'name' => __( 'Less than (<)', 'zero-bs-crm' ) ), 'before' => array( 'name' => __( 'Before datetime', 'zero-bs-crm' ) ), 'after' => array( 'name' => __( 'After datetime', 'zero-bs-crm' ) ), 'beforeequal' => array( 'name' => __( 'On or before date', 'zero-bs-crm' ) ), 'afterequal' => array( 'name' => __( 'On or after date', 'zero-bs-crm' ) ), 'nextdays' => array( 'name' => __( 'In the next X days', 'zero-bs-crm' ) ), 'previousdays' => array( 'name' => __( 'In the previous X days', 'zero-bs-crm' ) ), 'daterange' => array( 'name' => __( 'In date range', 'zero-bs-crm' ) ), 'datetimerange' => array( 'name' => __( 'In datetime range', 'zero-bs-crm' ) ), 'floatrange' => array( 'name' => __( 'In range', 'zero-bs-crm' ) ), 'intrange' => array( 'name' => __( 'In range', 'zero-bs-crm' ) ), 'istrue' => array( 'name' => __( 'Is True', 'zero-bs-crm' ) ), 'isfalse' => array( 'name' => __( 'Is False', 'zero-bs-crm' ) ), 'largerequal' => array( 'name' => __( 'Greater than or equal to (>=)', 'zero-bs-crm' ) ), 'lessequal' => array( 'name' => __( 'Less than or equal to (<=)', 'zero-bs-crm' ) ), ); } /* * Compares available segment conditions to previously logged available conditions * Fires `jpcrm_segment_conditions_changed` action if change observed. * * @param array $available_conditions - segment conditions available */ function jpcrm_segments_compare_available_conditions_to_prev( $available_conditions = false ){ global $zbs; // if not passed, retrieve if ( !$available_conditions ){ // retrieve conditions $available_conditions = apply_filters('zbs_segment_conditions', jpcrm_segments_default_conditions() ); } // retrieve previous hash $previous_conditions_hash = $zbs->settings->get( 'segment-condition-hash' ); // generate new $available_conditions_hash = jpcrm_generate_hash_of_obj( $available_conditions ); // if different, conditions available have changed, so regenerate segment audiences if ( $available_conditions_hash != $previous_conditions_hash ){ // fire action which can be hooked into to check segments for errors // e.g. if using advanced segments or custom code to add custom conditions // ... then that code is removed/deactivated, therefor you lose access to conditions do_action( 'jpcrm_segment_conditions_changed' ); // save hash $zbs->settings->update( 'segment-condition-hash', $available_conditions_hash ); } } /* * Segment conditions available have changed, let's rebuild segment counts * (which inadvertantly checks for segments where conditions are no longer present) * * Fired on `jpcrm_segment_conditions_changed`. */ function jpcrm_segments_conditions_have_changed(){ global $zbs; // recompile all segments $zbs->DAL->segments->compile_all_segments(); } add_action('jpcrm_segment_conditions_changed', 'jpcrm_segments_conditions_have_changed');
projects/plugins/crm/includes/ZeroBSCRM.CustomerFilters.php
<?php /* ! * Jetpack CRM * https://jetpackcrm.com * V1.20 * * Copyright 2020 Automattic * * Date: 01/11/16 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) { exit; } /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== Customer Typeaheads ====================================================== */ // } Outputs the html for a customer type-ahead list function zeroBSCRM_CustomerTypeList( $jsCallbackFuncStr = '', $inputDefaultValue = '', $showFullWidthSmaller = false, $jsChangeCallbackFuncStr = '' ) { $ret = ''; $extraClasses = ''; if ( $showFullWidthSmaller ) { $extraClasses .= 'zbsbtypeaheadfullwidth'; } // } Wrap $ret .= '<div class="zbstypeaheadwrap ' . $extraClasses . '">'; // } Build input $ret .= '<input class="zbstypeahead" type="text" value="' . esc_attr( $inputDefaultValue ) . '" placeholder="' . __( 'Contact name or email...', 'zero-bs-crm' ) . '" data-zbsopencallback="' . $jsCallbackFuncStr . '" data-zbschangecallback="' . $jsChangeCallbackFuncStr . '" autocomplete="' . esc_attr( jpcrm_disable_browser_autocomplete() ) . '" data-autokey="cotypelist">'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // } close wrap $ret .= '</div>'; // } Also need to make sure this is dumped out for js global $haszbscrmBHURLCustomersOut; if ( ! isset( $haszbscrmBHURLCustomersOut ) ) { $nonce = wp_create_nonce( 'wp_rest' ); $rest_base_url = get_rest_url(); // handle bare permalink structure if ( empty( get_option( 'permalink_structure' ) ) ) { $param_separator = '&'; } else { $param_separator = '?'; } $rest_url = $rest_base_url . 'zbscrm/v1/contacts' . $param_separator . '_wpnonce=' . $nonce; $ret .= '<script type="text/javascript">var zbscrmBHURLCustomers = "' . $rest_url . '";</script>'; $haszbscrmBHURLCustomersOut = true; } // } Global JS does the rest ;) // } see zbscrm_JS_Bind_Typeaheads_Customers return $ret; } // } Outputs the html for a Company type-ahead list function zeroBSCRM_CompanyTypeList( $jsCallbackFuncStr = '', $inputDefaultValue = '', $showFullWidthSmaller = false, $jsChangeCallbackFuncStr = '' ) { $ret = ''; $extraClasses = ''; if ( $showFullWidthSmaller ) { $extraClasses .= 'zbsbtypeaheadfullwidth'; } // typeahead or select? // turned off until JS bind's work // #TODOCOLIST in /wdev/ZeroBSCRM/zerobs-core/js/ZeroBSCRM.admin.global.js if ( isset( $neverGoingToBeSet ) && zeroBS_companyCount() < 50 ) { // } Wrap $ret .= '<div class="zbs-company-select ' . $extraClasses . '">'; // } Build input $companies = zeroBS_getCompanies( true, 10000, 0 ); $ret .= '<select class="zbs-company-select-input" autocomplete="' . esc_attr( jpcrm_disable_browser_autocomplete() ) . '" data-zbsopencallback="' . $jsCallbackFuncStr . '" data-zbschangecallback="' . $jsChangeCallbackFuncStr . '">'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase if ( is_array( $companies ) ) { foreach ( $companies as $co ) { if ( isset( $co['name'] ) && $co['name'] !== 'Auto Draft' ) { $ret .= '<option value="' . $co['id'] . '"'; if ( $co['name'] == $inputDefaultValue ) { $ret .= ' selected="selected"'; } $ret .= '>' . esc_html( $co['name'] ) . '</option>'; } } } $ret .= '</select>'; // } close wrap $ret .= '</div>'; } else { // typeahead // } Wrap $ret .= '<div class="zbstypeaheadwrap ' . $extraClasses . '">'; $ret .= '<input class="zbstypeaheadco" type="text" value="' . $inputDefaultValue . '" placeholder="' . __( jpcrm_label_company() . ' name...', 'zero-bs-crm' ) . '" data-zbsopencallback="' . $jsCallbackFuncStr . '" data-zbschangecallback="' . $jsChangeCallbackFuncStr . '" autocomplete="' . esc_attr( jpcrm_disable_browser_autocomplete() ) . '" data-autokey="cotypelist">'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase,WordPress.WP.I18n.NonSingularStringLiteralText // } close wrap $ret .= '</div>'; // } Also need to make sure this is dumped out for js global $haszbscrmBHURLCompaniesOut; if ( ! isset( $haszbscrmBHURLCompaniesOut ) ) { $nonce = wp_create_nonce( 'wp_rest' ); $rest_base_url = get_rest_url(); // handle bare permalink structure if ( empty( get_option( 'permalink_structure' ) ) ) { $param_separator = '&'; } else { $param_separator = '?'; } $rest_url = $rest_base_url . 'zbscrm/v1/companies' . $param_separator . '_wpnonce=' . $nonce; $ret .= '<script type="text/javascript">var zbscrmBHURLCompanies = "' . $rest_url . '";</script>'; $haszbscrmBHURLCompaniesOut = true; } // } Global JS does the rest ;) // } see zbscrm_JS_Bind_Typeaheads_Customers } return $ret; } // WH NOTE: WHY is this getting ALL of them and not s? param // } Returns json representing the first 10k customers in db... brutal // } MS NOTE: useful to return EMAIL in the response (for auto filling - WITHOUT getting ALL meta)? function zeroBSCRM_cjson() { header( 'Content-Type: application/json' ); $ret = array(); if ( is_user_logged_in() && zeroBSCRM_permsCustomers() ) { $ret = zeroBS_getCustomers( true, 10000, 0, false, false, '', false, false, false ); // quickfix (not req DAL2) global $zbs; if ( ! $zbs->isDAL2() ) { $retA = array(); foreach ( $ret as $r ) { if ( isset( $r['name'] ) && $r['name'] !== 'Auto Draft' ) { $retA[] = $r; } } $ret = $retA; unset( $retA ); } } echo json_encode( $ret ); exit(); } // WH NOTE: WHY is this getting ALL of them and not s? param // } Returns json representing the first 10k customers in db... brutal function zeroBSCRM_cojson() { header( 'Content-Type: application/json' ); $ret = array(); if ( is_user_logged_in() && zeroBSCRM_permsCustomers() ) { // $ret = zeroBS_getCustomers(false,10000,0,false,false,'',false,false,false); $ret = zeroBS_getCompanies( true, 10000, 0 ); // quickfix required until we move co to dal2 // if (!$zbs->isDAL2()){ $retA = array(); foreach ( $ret as $r ) { if ( isset( $r['name'] ) && $r['name'] !== 'Auto Draft' ) { $retA[] = $r; } } $ret = $retA; unset( $retA ); // } } echo json_encode( $ret ); exit(); } /* ====================================================== / Customer Typeaheads ====================================================== */ /* ====================================================== Customer Filter Funcs ====================================================== */ function zbs_customerFiltersGetApplied( $srcArr = 'usepost', $requireEmail = false ) { $fieldPrefix = ''; global $zbs; // } Can't use post as a default, so... if ( is_string( $srcArr ) && $srcArr == 'usepost' ) { $srcArr = $_POST; // } Also, posted fields need this prefix $fieldPrefix = 'zbs-crm-customerfilter-'; $fromPost = true; } // } Req. global $zbsCustomerFields, $zbsCustomerFiltersInEffect, $zbsCustomerFiltersPosted; $allZBSTags = zeroBS_integrations_getAllCategories(); // } start $appliedFilters = array(); $activeFilters = 0; /* status (str) namestr (str) source (str) linked to cf1 valuefrom valueto addedfrom addedto zbs-crm-customerfilter-tag-'.$tagGroupKey.'-'.$tag->term_id hasquote (bool int) hasinv (bool int) hastransact (bool int) postcode (str) To add: #} modifiedfromtoo #} External source/id (LATER) */ // } process filters $possibleFilters = array( // } key => array(type, matching field(notyetused)) 'status' => array( 'str', 'status' ), 'namestr' => array( 'str', 'custom:fullname' ), 'source' => array( 'str', 'cf1' ), 'valuefrom' => array( 'float', 'custom:totalval' ), 'valueto' => array( 'float', 'custom:totalval' ), 'addedrange' => array( 'str', '' ), // x - y (dates) // } these will be added by func below // 'addedfrom' => array('str',''), // 'addedto' => array('str',''), 'hasquote' => array( 'bool', '' ), 'hasinv' => array( 'bool', '' ), 'hastransact' => array( 'bool', '' ), 'postcode' => array( 'str', 'postcode' ), ); // } Tags dealt with seperately. foreach ( $possibleFilters as $key => $filter ) { $type = $filter[0]; if ( isset( $srcArr[ $fieldPrefix . $key ] ) ) { switch ( $type ) { case 'str': // } Is it a str? cleanse? if ( ! empty( $srcArr[ $fieldPrefix . $key ] ) ) { // } add $appliedFilters[ $key ] = sanitize_text_field( $srcArr[ $fieldPrefix . $key ] ); ++$activeFilters; } break; case 'float': // } Is it a no? cleanse? if ( ! empty( $srcArr[ $fieldPrefix . $key ] ) ) { // } Cast $no = (float) sanitize_text_field( $srcArr[ $fieldPrefix . $key ] ); // } add $appliedFilters[ $key ] = $no; ++$activeFilters; } break; case 'int': // } Is it a no? cleanse? if ( ! empty( $srcArr[ $fieldPrefix . $key ] ) ) { // } Cast $no = (int) sanitize_text_field( $srcArr[ $fieldPrefix . $key ] ); // } add $appliedFilters[ $key ] = $no; ++$activeFilters; } break; case 'bool': // } Is it a bool? cleanse? // } double check? no need... // } made a hack bool here - is either: // } empty (not set) // } 1 = true // } -1 = false if ( isset( $srcArr[ $fieldPrefix . $key ] ) ) { if ( $srcArr[ $fieldPrefix . $key ] == '1' ) { // } add $appliedFilters[ $key ] = true; ++$activeFilters; } elseif ( $srcArr[ $fieldPrefix . $key ] == '-1' ) { // } add $appliedFilters[ $key ] = false; ++$activeFilters; } } break; } } } // / foreach // } Added date range if ( isset( $appliedFilters['addedrange'] ) && ! empty( $appliedFilters['addedrange'] ) ) { // } Try split if ( strpos( $appliedFilters['addedrange'], '-' ) > 0 ) { $dateParts = explode( ' - ', $appliedFilters['addedrange'] ); if ( count( $dateParts ) == 2 ) { // } No validation here (yet) if ( ! empty( $dateParts[0] ) ) { $appliedFilters['addedfrom'] = $dateParts[0]; ++$activeFilters; } if ( ! empty( $dateParts[1] ) ) { $appliedFilters['addedto'] = $dateParts[1]; ++$activeFilters; } } } } // } Tags (From POST) if ( isset( $fromPost ) ) { $appliedFilters['tags'] = array(); if ( isset( $allZBSTags ) && count( $allZBSTags ) > 0 ) { // } Cycle through + catch active foreach ( $allZBSTags as $tagGroupKey => $tagGroup ) { if ( count( $tagGroup ) > 0 ) { foreach ( $tagGroup as $tag ) { // DAL support $tagID = -1; $tagName = ''; if ( $zbs->isDAL2() ) { $tagID = $tag['id']; $tagName = $tag['name']; } else { $tagID = $tag->term_id; $tagName = $tag->name; } // } set? if ( isset( $_POST[ 'zbs-crm-customerfilter-tag-' . $tagGroupKey . '-' . $tagID ] ) ) { // } Tagged :) Add $appliedFilters['tags'][ $tagGroupKey ][ $tagID ] = true; ++$activeFilters; } } } } } } else { // } From passed array, so just make sure it's an array of arrays and pass :) // } This all assumes passing a json obj made into array with (array) cast (see mail camp search #tempfilterjsonpass) $appliedFilters['tags'] = array(); if ( isset( $srcArr['tags'] ) ) { $srcTags = (array) $srcArr['tags']; if ( is_array( $srcTags ) && count( $srcTags ) > 0 ) { foreach ( $srcTags as $tagKey => $tagObj ) { $appliedFilters['tags'][ $tagKey ] = (array) $tagObj; } } } } // } if req email if ( $requireEmail || ( isset( $srcArr[ $fieldPrefix . 'require-email' ] ) && ! empty( $srcArr[ $fieldPrefix . 'require-email' ] ) ) ) { $appliedFilters['require_email'] = true; } // } this will only be set if filters have been posted/some actually apply: // } $zbsCustomerFiltersPosted; if ( $activeFilters > 0 ) { $zbsCustomerFiltersPosted = $activeFilters; } return $appliedFilters; } /* zbs_customerFiltersRetrieveCustomers #} Retrieves array of customers filtered by zbs_customerFilters #} Notes: - This can + will be fired by zeroBS__customerFiltersRetrieveCustomerCount if that is fired BEFORE THIS .. Thereafter it'll use a cached list (and apply paging) - unless $forceRefresh is set to true */ function zbs_customerFiltersRetrieveCustomers( $perPage = 10, $page = 1, $forcePaging = false, $forceRefresh = false ) { // } Query Performance index // global $zbsQPI; if (!isset($zbsQPI)) $zbsQPI = array(); // $zbsQPI['retrieveCustomers1'] = zeroBSCRM_mtime_float(); // } Req. global $zbs,$zbsCustomerFields, $zbsCustomerFiltersInEffect, $zbsCustomerFiltersCurrentList; // } Already cached? if ( // } Already cached - yep + force refresh ( isset( $zbsCustomerFiltersCurrentList ) && is_array( $zbsCustomerFiltersCurrentList ) && $forceRefresh ) || // } Not cached ( ! isset( $zbsCustomerFiltersCurrentList ) || ! is_array( $zbsCustomerFiltersCurrentList ) ) ) { // DEBUG echo 'NOT CACHED: zbs_customerFiltersRetrieveCustomers<br />'; // } Any applied filters will be here: $zbsCustomerFiltersInEffect $appliedFilters = array(); // } No validation here if ( isset( $zbsCustomerFiltersInEffect ) && is_array( $zbsCustomerFiltersInEffect ) && count( $zbsCustomerFiltersInEffect ) > 0 ) { $appliedFilters = $zbsCustomerFiltersInEffect; } // } Output // } First build query // } PAGING NOTE: // } MOVED TO POST retrieve, to allow for counts to be made :) // } MVP... search #postpaging // } Note $forcePaging FORCES pre-paging // } Page legit? - lazy check if ( $forcePaging ) { if ( $perPage < 0 ) { $perPageArg = 10; } else { $perPageArg = (int) $perPage; } } else { $perPageArg = 10000; // } lol. } // } Defaults $args = array( 'post_type' => 'zerobs_customer', 'post_status' => 'publish', 'posts_per_page' => $perPageArg, 'order' => 'DESC', 'orderby' => 'post_date', ); if ( $forcePaging ) { // } Add page if page... - dodgy meh $actualPage = $page - 1; if ( $actualPage < 0 ) { $actualPage = 0; } if ( $actualPage > 0 ) { $args['offset'] = $perPageArg * $actualPage; } } // DAL 2 support :) $dal2Args = array( 'perPage' => $perPageArg, 'sortByField' => 'zbsc_created', 'sortOrder' => 'DESC', 'ignoreowner' => true, 'withQuotes' => true, 'withInvoices' => true, 'withTransactions' => true, ); // } This is brutal, and needs rethinking #v1.2 // } For now, is split into two sections // 1) Can be queried via wp_post args // 2) Can't be... (filtered post query...) // } Inefficient, but for launch... // } =============================================================== // } get_posts queriable attrs // } =============================================================== // } Name // } As of v1.1 // 'name' => $customerEle->post_title if ( isset( $appliedFilters['namestr'] ) && ! empty( $appliedFilters['namestr'] ) ) { // } Simples $args['s'] = $appliedFilters['namestr']; // DAL2 $dal2Args['searchPhrase'] = $appliedFilters['namestr']; } // } Added From + To // 'created' => $customerEle->post_date_gmt OR post_modified_gmt for modified if ( isset( $appliedFilters['addedfrom'] ) && ! empty( $appliedFilters['addedfrom'] ) ) { // } add holder if req if ( ! isset( $args['date_query'] ) ) { $args['date_query'] = array(); } // } Add $args['date_query'][] = array( 'column' => 'post_date_gmt', 'after' => $appliedFilters['addedfrom'], ); // DAL2 // TBC $dal2Args['searchPhrase'] = $appliedFilters['namestr']; } if ( isset( $appliedFilters['addedto'] ) && ! empty( $appliedFilters['addedto'] ) ) { // } add holder if req if ( ! isset( $args['date_query'] ) ) { $args['date_query'] = array(); } // } Add $args['date_query'][] = array( 'column' => 'post_date_gmt', 'before' => $appliedFilters['addedto'], ); // DAL2 // TBC $dal2Args['searchPhrase'] = $appliedFilters['namestr']; } // } Tags if ( isset( $appliedFilters['tags'] ) && is_array( $appliedFilters['tags'] ) && count( $appliedFilters['tags'] ) > 0 ) { // } Temp holder $tagQueryArrays = array(); // DAL2 - ignoring taxonomy here $tagIDS = array(); // } Foreach taxonomy type: foreach ( $appliedFilters['tags'] as $taxonomyKey => $tagItem ) { $thisTaxonomyArr = array(); // } Foreach tag in taxonomy foreach ( $tagItem as $tagID => $activeFlag ) { // } If logged here, is active, disregard $activeFlag $thisTaxonomyArr[] = $tagID; // dal2 $tagIDS[] = $tagID; } if ( count( $thisTaxonomyArr ) > 0 ) { // } Add it $tagQueryArrays[] = array( 'taxonomy' => $taxonomyKey, 'field' => 'term_id', 'terms' => $thisTaxonomyArr, ); } /* #} Later for "not in" 'terms' => array( 103, 115, 206 ), 'operator' => 'NOT IN', */ } // } Any to add? if ( count( $tagQueryArrays ) > 0 ) { // } Set $args['tax_query'] = array(); // } if multiple, needs this if ( count( $tagQueryArrays ) > 1 ) { $args['tax_query']['relation'] = 'AND'; } // } Add em all :) foreach ( $tagQueryArrays as $tqArr ) { $args['tax_query'][] = $tqArr; } } // DAL2 if ( count( $tagIDS ) > 0 ) { $dal2Args['isTagged'] = $tagIDS; } } // } =============================================================== // } / end of get_posts queriable attrs // } =============================================================== // Debug echo '<h2>ARGS</h2><pre>'; print_r($args); echo '</pre>'; // } QPI // $zbsQPI['retrieveCustomers1'] = round(zeroBSCRM_mtime_float() - #$zbsQPI['retrieveCustomers1'],2).'s'; // $zbsQPI['retrieveCustomers2'] = zeroBSCRM_mtime_float(); // } Run query // $potentialCustomerList = get_posts( $args ); if ( $zbs->isDAL2() ) { $potentialCustomerList = $zbs->DAL->contacts->getContacts( $dal2Args ); } else { // DAL1 $potentialCustomerList = zeroBS_getCustomers( true, 10, 0, true, true, '', true, $args ); } // $endingCustomerList = zeroBS_getCustomers(true,10,0,true,true,'',true,$args); $endingCustomerList = array(); // } QPI // $zbsQPI['retrieveCustomers2'] = round(zeroBSCRM_mtime_float() - #$zbsQPI['retrieveCustomers2'],2).'s'; // $zbsQPI['retrieveCustomers3'] = zeroBSCRM_mtime_float(); // } =============================================================== // } filter post-query // } =============================================================== $x = 0; if ( count( $potentialCustomerList ) > 0 ) { foreach ( $potentialCustomerList as $potentialCustomer ) { // } Innocent until proven... $includeThisCustomer = true; // } Stops excess queries // $botheredAboutQuotes = false; if (isset($appliedFilters['hasquote']) && $appliedFilters['hasquote']) $botheredAboutQuotes = true; // $botheredAboutInvs = false; if (isset($appliedFilters['hasinv']) && $appliedFilters['hasinv']) $botheredAboutInvs = true; // $botheredAboutTransactions = false; if (isset($appliedFilters['hastransact']) && $appliedFilters['hastransact']) $botheredAboutTransactions = true; // } Need them all, whatever, for total value etc. $botheredAboutQuotes = true; $botheredAboutInvs = true; $botheredAboutTransactions = true; // } Retrieve full cust // $fullCustomer = zeroBS_getCustomer($potentialCustomer->ID,$botheredAboutQuotes,$botheredAboutInvs,$botheredAboutTransactions); // } Optimised away from this :) $fullCustomer = $potentialCustomer; // } Require email? if ( isset( $appliedFilters['require_email'] ) ) { if ( ! zeroBSCRM_validateEmail( $fullCustomer['email'] ) ) { $includeThisCustomer = false; } } // } Status if ( isset( $appliedFilters['status'] ) && ! empty( $appliedFilters['status'] ) ) { // } Check status if ( $appliedFilters['status'] != $fullCustomer['status'] ) { $includeThisCustomer = false; } } // } Source - ASSUMES is CF1!!! if ( isset( $appliedFilters['source'] ) && ! empty( $appliedFilters['source'] ) ) { // } Check Source if ( $appliedFilters['source'] != $fullCustomer['cf1'] ) { $includeThisCustomer = false; } } // } Postcode (can be AL1* etc.) if ( isset( $appliedFilters['postcode'] ) && ! empty( $appliedFilters['postcode'] ) ) { // } Remove spaces from both $cleanPostcode = str_replace( ' ', '', $fullCustomer['postcode'] ); $filterPostcode = str_replace( ' ', '', $appliedFilters['postcode'] ); // } Check Postcode if ( ! str_starts_with( $cleanPostcode, $filterPostcode ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $includeThisCustomer = false; } } // } Value From + To // } Calc total $totVal = zeroBS_customerTotalValue( $potentialCustomer['id'], $fullCustomer['invoices'], $fullCustomer['transactions'] ); // } Compare if ( isset( $appliedFilters['valuefrom'] ) && ! empty( $appliedFilters['valuefrom'] ) ) { // } If less than valuefrom, then remove if ( $totVal < $appliedFilters['valuefrom'] ) { $includeThisCustomer = false; } } if ( isset( $appliedFilters['valueto'] ) && ! empty( $appliedFilters['valueto'] ) ) { // } If more than valueto, then remove if ( $totVal > $appliedFilters['valueto'] ) { $includeThisCustomer = false; } } // } Has Quote, inv, transaction if ( isset( $appliedFilters['hasquote'] ) && $appliedFilters['hasquote'] && count( $fullCustomer['quotes'] ) < 1 ) { $includeThisCustomer = false; } if ( isset( $appliedFilters['hasinv'] ) && $appliedFilters['hasinv'] && count( $fullCustomer['invoices'] ) < 1 ) { $includeThisCustomer = false; } if ( isset( $appliedFilters['hastransact'] ) && $appliedFilters['hastransact'] && count( $fullCustomer['transactions'] ) < 1 ) { $includeThisCustomer = false; } // } Finally... include or not? if ( $includeThisCustomer ) { $endingCustomerList[] = $fullCustomer; } } } // } =============================================================== // } / end filter post-query // } =============================================================== // } External source/id (LATER) // 'meta_key' => 'zbs_customer_ext_'.$approvedExternalSource, // 'meta_value' => $externalID // } Set as global $zbsCustomerFiltersCurrentList = $endingCustomerList; } else { // } / end of "is already cached/not needed" // } Use cached list $endingCustomerList = $zbsCustomerFiltersCurrentList; } // } Do paging (lol wrong end) #postpaging if ( ! $forcePaging ) { // } Per Page if ( $perPage < 0 ) { $perPage = 10; } else { $perPage = (int) $perPage; } // } Offset $thisOffset = 0; $actualPage = $page - 1; if ( $actualPage < 0 ) { $actualPage = 0; } if ( $actualPage > 0 ) { $thisOffset = $perPage * $actualPage; } // } Anything to do? if ( isset( $thisOffset ) ) { // } SLICE $endingCustomerList = array_slice( $endingCustomerList, $thisOffset, $perPage ); } } // DEBUG echo '<h2>endingCustomerList</h2><pre>'; print_r($endingCustomerList); echo '</pre>'; // } QPI // $zbsQPI['retrieveCustomers3'] = round(zeroBSCRM_mtime_float() - #$zbsQPI['retrieveCustomers3'],2).'s'; // } Return return $endingCustomerList; } // } Only used by AJAX, also returns top X customers :) function zeroBS__customerFiltersRetrieveCustomerCountAndTopCustomers( $countToReturn = 3 ) { // } REQUIRES that zbs_customerFiltersRetrieveCustomers has been run BEFORE this global $zbsCustomerFiltersCurrentList; if ( isset( $zbsCustomerFiltersCurrentList ) && is_array( $zbsCustomerFiltersCurrentList ) ) { // } return return array( 'count' => count( $zbsCustomerFiltersCurrentList ), 'top' => array_slice( $zbsCustomerFiltersCurrentList, 0, $countToReturn ), ); } else { // } Run - without params it'll return first page, but retrieve all into cache var (what we need for count) $zbsCustomersFiltered = zbs_customerFiltersRetrieveCustomers(); // } return count return array( 'count' => count( $zbsCustomerFiltersCurrentList ), 'top' => array_slice( $zbsCustomersFiltered, 0, $countToReturn ), ); } } /* ====================================================== / Customer Filter Funcs ====================================================== */
projects/plugins/crm/includes/ZeroBSCRM.DAL3.Obj.Forms.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V3.0+ * * Copyright 2020 Automattic * * Date: 14/01/19 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /** * ZBS DAL >> Forms * * @author Woody Hayday <hello@jetpackcrm.com> * @version 2.0 * @access public * @see https://jetpackcrm.com/kb */ class zbsDAL_forms extends zbsDAL_ObjectLayer { protected $objectType = ZBS_TYPE_FORM; protected $objectDBPrefix = 'zbsf_'; protected $objectModel = array( // ID 'ID' => array('fieldname' => 'ID', 'format' => 'int'), // site + team generics 'zbs_site' => array('fieldname' => 'zbs_site', 'format' => 'int'), 'zbs_team' => array('fieldname' => 'zbs_team', 'format' => 'int'), 'zbs_owner' => array('fieldname' => 'zbs_owner', 'format' => 'int'), // other fields 'title' => array( // db model: 'fieldname' => 'zbsf_title', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'Form Title', 'placeholder'=>'', 'essential' => true, 'max_len' => 200 ), 'style' => array('fieldname' => 'zbsf_style', 'format' => 'str'), 'views' => array('fieldname' => 'zbsf_views', 'format' => 'int'), 'conversions' => array('fieldname' => 'zbsf_conversions', 'format' => 'int'), 'label_header' => array( // db model: 'fieldname' => 'zbsf_label_header', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'Header', 'placeholder'=> 'Want to find out more?', 'nocolumn'=>true, 'max_len' => 200 ), 'label_subheader' => array( // db model: 'fieldname' => 'zbsf_label_subheader', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'Sub Header', 'placeholder'=> 'Drop us a line. We follow up on all contacts', 'nocolumn'=>true, 'max_len' => 200 ), 'label_firstname' => array( // db model: 'fieldname' => 'zbsf_label_firstname', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'First Name Placeholder', 'placeholder'=> 'First Name', 'nocolumn'=>true, 'max_len' => 200 ), 'label_lastname' => array( // db model: 'fieldname' => 'zbsf_label_lastname', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'Last Name Placeholder', 'placeholder'=> 'Last Name', 'nocolumn'=>true, 'max_len' => 200 ), 'label_email' => array( // db model: 'fieldname' => 'zbsf_label_email', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'Email Placeholder', 'placeholder'=> 'Email', 'nocolumn'=>true, 'max_len' => 200 ), 'label_message' => array( // db model: 'fieldname' => 'zbsf_label_message', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'Message Placeholder', 'placeholder'=> 'Your Message', 'nocolumn'=>true, 'max_len' => 200 ), 'label_button' => array( // db model: 'fieldname' => 'zbsf_label_button', 'format' => 'str', // output model 'input_type' => 'text', 'label' => 'Submit Button', 'placeholder'=> 'Submit', 'nocolumn'=>true, 'max_len' => 200 ), 'label_successmsg' => array( // db model: 'fieldname' => 'zbsf_label_successmsg', 'format' => 'str', // output model 'input_type' => 'textarea', 'label' => 'Success Message', 'placeholder'=> 'Thanks. We will be in touch.', 'nocolumn'=>true, 'max_len' => 200 ), 'label_spammsg' => array( // db model: 'fieldname' => 'zbsf_label_spammsg', 'format' => 'str', // output model 'input_type' => 'textarea', 'label' => 'Spam Message', 'placeholder'=> 'We will not send you spam. Our team will be in touch within 24 to 48 hours Mon-Fri (but often much quicker)', 'nocolumn'=>true, 'max_len' => 200 ), 'include_terms_check' => array( // db model: 'fieldname' => 'zbsf_include_terms_check', 'format' => 'bool', /* not live in v3.0, to add v3.1+ // output model 'input_type' => 'checkbox', 'label' => 'Include "Terms and Conditions Check"', 'placeholder'=>'', 'nocolumn'=>true */ ), 'terms_url' => array( // db model: 'fieldname' => 'zbsf_terms_url', 'format' => 'str', /* not live in v3.0, to add v3.1+ // output model 'input_type' => 'text', 'label' => 'Terms and Conditions URL', 'placeholder'=>'', 'nocolumn'=>true, 'max_len' => 200 */ ), 'redir_url' => array( // db model: 'fieldname' => 'zbsf_redir_url', 'format' => 'str', /* not live in v3.0, to add v3.1+ // output model 'input_type' => 'text', 'label' => 'Redirection URL', 'placeholder'=>'', 'nocolumn'=>true, 'max_len' => 200 */ ), 'font' => array('fieldname' => 'zbsf_font', 'format' => 'str'), 'colour_bg' => array('fieldname' => 'zbsf_colour_bg', 'format' => 'str'), 'colour_font' => array('fieldname' => 'zbsf_colour_font', 'format' => 'str'), 'colour_emphasis' => array('fieldname' => 'zbsf_colour_emphasis', 'format' => 'str'), 'created' => array('fieldname' => 'zbsf_created', 'format' => 'uts'), 'lastupdated' => array('fieldname' => 'zbsf_lastupdated', 'format' => 'uts'), ); function __construct($args=array()) { #} =========== LOAD ARGS ============== $defaultArgs = array( //'tag' => false, ); foreach ($defaultArgs as $argK => $argV){ $this->$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $this->$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$this->$argK = $newData;} else { $this->$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= } // =============================================================================== // =========== FORM =========================================================== // generic get Company (by ID) // Super simplistic wrapper used by edit page etc. (generically called via dal->contacts->getSingle etc.) public function getSingle($ID=-1){ return $this->getForm($ID); } // generic get (by ID list) // Super simplistic wrapper used by MVP Export v3.0 public function getIDList($IDs=false){ return $this->getForms(array( 'inArr' => $IDs, 'page' => -1, 'perPage' => -1 )); } // generic get (EVERYTHING) // expect heavy load! public function getAll($IDs=false){ return $this->getForms(array( 'sortByField' => 'ID', 'sortOrder' => 'ASC', 'page' => -1, 'perPage' => -1, )); } // generic get count of (EVERYTHING) public function getFullCount(){ return $this->getForms(array( 'count' => true, 'page' => -1, 'perPage' => -1, )); } /** * returns full form line +- details * * @param int id form id * @param array $args Associative array of arguments * * @return array form object */ public function getForm($id=-1,$args=array()){ global $zbs; #} =========== LOAD ARGS ============== $defaultArgs = array( // with what? 'withTags' => false, 'withOwner' => false, // permissions 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_FORM), // this'll let you not-check the owner of obj // returns scalar ID of line 'onlyID' => false, 'fields' => false // false = *, array = fieldnames ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} Check ID $id = (int)$id; if ( (!empty($id) && $id > 0) || (!empty($email)) || (!empty($externalSource) && !empty($externalSourceUID)) ){ global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); $extraSelect = ''; #} ============= PRE-QUERY ============ $selector = 'form.*'; if (isset($fields) && is_array($fields)) { $selector = ''; // always needs id, so add if not present if (!in_array('ID',$fields)) $selector = 'form.ID'; foreach ($fields as $f) { if (!empty($selector)) $selector .= ','; $selector .= 'form.'.$f; } } else if ($onlyID){ $selector = 'form.ID'; } #} ============ / PRE-QUERY =========== #} Build query $query = "SELECT ".$selector.$extraSelect." FROM ".$ZBSCRM_t['forms'].' as form'; #} ============= WHERE ================ if (!empty($id) && $id > 0){ #} Add ID $wheres['ID'] = array('ID','=','%d',$id); } #} ============ / WHERE ============== #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort('ID','DESC') . $this->buildPaging(0,1); try { #} Prep & run query $queryObj = $this->prepare($query,$params); $potentialRes = $wpdb->get_row($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret Results (ROW) if (isset($potentialRes) && isset($potentialRes->ID)) { #} Has results, tidy + return #} Only ID? return it directly if ($onlyID) return $potentialRes->ID; // tidy if (is_array($fields)){ // guesses fields based on table col names $res = $this->lazyTidyGeneric($potentialRes); } else { // proper tidy $res = $this->tidy_form($potentialRes);//$withCustomFields } if ($withTags){ // add all tags lines $res['tags'] = $this->DAL()->getTagsForObjID(array('objtypeid'=>ZBS_TYPE_FORM,'objid'=>$potentialRes->ID)); } return $res; } } // / if ID return false; } /** * returns form detail lines * * @param array $args Associative array of arguments * * @return array of form lines */ public function getForms($args=array()){ global $zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( // Search/Filtering (leave as false to ignore) 'searchPhrase' => '', // searches title 'inArr' => false, 'isTagged' => false, // 1x INT OR array(1,2,3) 'isNotTagged' => false, // 1x INT OR array(1,2,3) 'ownedBy' => false, 'olderThan' => false, // uts 'newerThan' => false, // uts // returns 'count' => false, 'withTags' => false, 'withOwner' => false, 'onlyColumns' => false, // if passed (array('fname','lname')) will return only those columns (overwrites some other 'return' options). NOTE: only works for base fields (not custom fields) 'sortByField' => 'ID', 'sortOrder' => 'ASC', 'page' => 0, // this is what page it is (gets * by for limit) 'perPage' => 100, 'whereCase' => 'AND', // DEFAULT = AND // permissions 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_FORM), // this'll let you not-check the owner of obj ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= global $ZBSCRM_t,$wpdb,$zbs; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); $joinQ = ''; $extraSelect = ''; #} ============= PRE-QUERY ============ #} Capitalise this $sortOrder = strtoupper($sortOrder); #} If just count, turn off any extra gumpf if ($count) { $withTags = false; $withOwner = false; } #} If onlyColumns, validate if ($onlyColumns){ #} onlyColumns build out a field arr if (is_array($onlyColumns) && count($onlyColumns) > 0){ $onlyColumnsFieldArr = array(); foreach ($onlyColumns as $col){ // find db col key from field key (e.g. fname => zbsc_fname) $dbCol = ''; if (isset($this->objectModel[$col]) && isset($this->objectModel[$col]['fieldname'])) $dbCol = $this->objectModel[$col]['fieldname']; if (!empty($dbCol)){ $onlyColumnsFieldArr[$dbCol] = $col; } } } // if legit cols: if (isset($onlyColumnsFieldArr) && is_array($onlyColumnsFieldArr) && count($onlyColumnsFieldArr) > 0){ $onlyColumns = true; // If onlyColumns, turn off extras $withTags = false; $withOwner = false; } else { // deny $onlyColumns = false; } } #} ============ / PRE-QUERY =========== #} Build query $query = "SELECT form.*".$extraSelect." FROM ".$ZBSCRM_t['forms'].' as form'.$joinQ; #} Count override if ($count) $query = "SELECT COUNT(form.ID) FROM ".$ZBSCRM_t['forms'].' as form'.$joinQ; #} onlyColumns override if ($onlyColumns && is_array($onlyColumnsFieldArr) && count($onlyColumnsFieldArr) > 0){ $columnStr = ''; foreach ($onlyColumnsFieldArr as $colDBKey => $colStr){ if (!empty($columnStr)) $columnStr .= ','; // this presumes str is db-safe? could do with sanitation? $columnStr .= $colDBKey; } $query = "SELECT ".$columnStr." FROM ".$ZBSCRM_t['forms'].' as form'.$joinQ; } #} ============= WHERE ================ #} Add Search phrase if (!empty($searchPhrase)){ // search? - ALL THESE COLS should probs have index of FULLTEXT in db? $searchWheres = array(); $searchWheres['search_ID'] = array('ID','=','%d',$searchPhrase); $searchWheres['search_title'] = array('zbsf_title','LIKE','%s','%'.$searchPhrase.'%'); // 3.0.13 - Added ability to search custom fields (optionally) $customFieldSearch = zeroBSCRM_getSetting('customfieldsearch'); if ($customFieldSearch == 1){ // simplistic add // NOTE: This IGNORES ownership of custom field lines. $searchWheres['search_customfields'] = array('ID','IN',"(SELECT zbscf_objid FROM ".$ZBSCRM_t['customfields']." WHERE zbscf_objval LIKE %s AND zbscf_objtype = ".ZBS_TYPE_FORM.")",'%'.$searchPhrase.'%'); } // This generates a query like 'zbsf_fname LIKE %s OR zbsf_lname LIKE %s', // which we then need to include as direct subquery (below) in main query :) $searchQueryArr = $this->buildWheres($searchWheres,'',array(),'OR',false); if (is_array($searchQueryArr) && isset($searchQueryArr['where']) && !empty($searchQueryArr['where'])){ // add it $wheres['direct'][] = array('('.$searchQueryArr['where'].')',$searchQueryArr['params']); } } #} In array (if inCompany passed, this'll currently overwrite that?! (todo2.5)) if (is_array($inArr) && count($inArr) > 0){ // clean for ints $inArrChecked = array(); foreach ($inArr as $x){ $inArrChecked[] = (int)$x; } // add where $wheres['inarray'] = array('ID','IN','('.implode(',',$inArrChecked).')'); } #} Owned by if (!empty($ownedBy) && $ownedBy > 0){ // would never hard-type this in (would make generic as in buildWPMetaQueryWhere) // but this is only here until MIGRATED to db2 globally //$wheres['incompany'] = array('ID','IN','(SELECT DISTINCT post_id FROM '.$wpdb->prefix."postmeta WHERE meta_key = 'zbs_company' AND meta_value = %d)",$inCompany); // Use obj links now $wheres['ownedBy'] = array('zbs_owner','=','%s',$ownedBy); } // quick addition for mike #} olderThan if (!empty($olderThan) && $olderThan > 0 && $olderThan !== false) $wheres['olderThan'] = array('zbsf_created','<=','%d',$olderThan); #} newerThan if (!empty($newerThan) && $newerThan > 0 && $newerThan !== false) $wheres['newerThan'] = array('zbsf_created','>=','%d',$newerThan); #} Any additionalWhereArr? if (isset($additionalWhereArr) && is_array($additionalWhereArr) && count($additionalWhereArr) > 0){ // add em onto wheres (note these will OVERRIDE if using a key used above) // Needs to be multi-dimensional $wheres = array_merge($wheres,$additionalWhereArr); $wheres = array_merge_recursive($wheres,$additionalWhereArr); } #} Is Tagged (expects 1 tag ID OR array) // catch 1 item arr if (is_array($isTagged) && count($isTagged) == 1) $isTagged = $isTagged[0]; if (!is_array($isTagged) && !empty($isTagged) && $isTagged > 0){ // add where tagged // 1 int: $wheres['direct'][] = array('((SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = form.ID AND zbstl_tagid = %d) > 0)',array(ZBS_TYPE_FORM,$isTagged)); } else if (is_array($isTagged) && count($isTagged) > 0){ // foreach in array :) $tagStr = ''; foreach ($isTagged as $iTag){ $i = (int)$iTag; if ($i > 0){ if ($tagStr !== '') $tagStr .','; $tagStr .= $i; } } if (!empty($tagStr)){ $wheres['direct'][] = array('((SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = form.ID AND zbstl_tagid IN (%s)) > 0)',array(ZBS_TYPE_FORM,$tagStr)); } } #} Is NOT Tagged (expects 1 tag ID OR array) // catch 1 item arr if (is_array($isNotTagged) && count($isNotTagged) == 1) $isNotTagged = $isNotTagged[0]; if (!is_array($isNotTagged) && !empty($isNotTagged) && $isNotTagged > 0){ // add where tagged // 1 int: $wheres['direct'][] = array('((SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = form.ID AND zbstl_tagid = %d) = 0)',array(ZBS_TYPE_FORM,$isNotTagged)); } else if (is_array($isNotTagged) && count($isNotTagged) > 0){ // foreach in array :) $tagStr = ''; foreach ($isNotTagged as $iTag){ $i = (int)$iTag; if ($i > 0){ if ($tagStr !== '') $tagStr .','; $tagStr .= $i; } } if (!empty($tagStr)){ $wheres['direct'][] = array('((SELECT COUNT(ID) FROM '.$ZBSCRM_t['taglinks'].' WHERE zbstl_objtype = %d AND zbstl_objid = form.ID AND zbstl_tagid IN (%s)) = 0)',array(ZBS_TYPE_FORM,$tagStr)); } } #} ============ / WHERE =============== #} ============ SORT ============== // Obj Model based sort conversion // converts 'addr1' => 'zbsco_addr1' generically if (isset($this->objectModel[$sortByField]) && isset($this->objectModel[$sortByField]['fieldname'])) $sortByField = $this->objectModel[$sortByField]['fieldname']; // Mapped sorts // This catches listview and other exception sort cases $sort_map = array( ); if ( array_key_exists( $sortByField, $sort_map ) ) { $sortByField = $sort_map[ $sortByField ]; } #} ============ / SORT ============== #} CHECK this + reset to default if faulty if (!in_array($whereCase,array('AND','OR'))) $whereCase = 'AND'; #} Build out any WHERE clauses $wheresArr = $this->buildWheres($wheres,$whereStr,$params,$whereCase); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$this->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $this->ownershipSQL($ignoreowner,'contact'); if (!empty($ownQ)) $additionalWhere = $this->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $this->buildWhereStr($whereStr,$additionalWhere) . $this->buildSort($sortByField,$sortOrder) . $this->buildPaging($page,$perPage); try { #} Prep & run query $queryObj = $this->prepare($query,$params); #} Catch count + return if requested if ($count) return $wpdb->get_var($queryObj); #} else continue.. $potentialRes = $wpdb->get_results($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $this->catchSQLError($e); } #} Interpret results (Result Set - multi-row) if (isset($potentialRes) && is_array($potentialRes) && count($potentialRes) > 0) { #} Has results, tidy + return foreach ($potentialRes as $resDataLine) { // using onlyColumns filter? if ($onlyColumns && is_array($onlyColumnsFieldArr) && count($onlyColumnsFieldArr) > 0){ // only coumns return. $resArr = array(); foreach ($onlyColumnsFieldArr as $colDBKey => $colStr){ if (isset($resDataLine->$colDBKey)) $resArr[$colStr] = $resDataLine->$colDBKey; } } else { // tidy $resArr = $this->tidy_form($resDataLine);// $withCustomFields } if ($withTags){ // add all tags lines $resArr['tags'] = $this->DAL()->getTagsForObjID(array('objtypeid'=>ZBS_TYPE_FORM,'objid'=>$resDataLine->ID)); } $form_id = $resArr['id']; $res[] = $resArr; } } return $res; } /** * Returns a count of forms (owned) * * @return int count */ public function getFormCount($args=array()){ #} ============ LOAD ARGS ============= $defaultArgs = array( // Search/Filtering (leave as false to ignore) // permissions 'ignoreowner' => true, // this'll let you not-check the owner of obj ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= $whereArr = array(); return $this->DAL()->getFieldByWHERE(array( 'objtype' => ZBS_TYPE_FORM, 'colname' => 'COUNT(ID)', 'where' => $whereArr, 'ignoreowner' => $ignoreowner)); } /** * adds or updates a form object * * @param array $args Associative array of arguments * id (if update), owner, data (array of field data) * * @return int line ID */ public function addUpdateForm($args=array()){ global $ZBSCRM_t,$wpdb,$zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'owner' => -1, // fields (directly) 'data' => array( 'title' => '', 'style' => '', 'views' => '', 'conversions' => '', 'label_header' => '', 'label_subheader' => '', 'label_firstname' => '', 'label_lastname' => '', 'label_email' => '', 'label_message' => '', 'label_button' => '', 'label_successmsg' => '', 'label_spammsg' => '', 'include_terms_check' => '', 'terms_url' => '', 'redir_url' => '', 'font' => '', 'colour_bg' => '', 'colour_font' => '', 'colour_emphasis' => '', // tags 'tags' => -1, // pass an array of tag ids or tag strings 'tag_mode' => 'replace', // replace|append|remove // allow this to be set for MS sync etc. 'created' => -1, 'lastupdated' => '', ), 'limitedFields' => -1, // if this is set it OVERRIDES data (allowing you to set specific fields + leave rest in tact) // ^^ will look like: array(array('key'=>x,'val'=>y,'type'=>'%s')) // this function as DAL1 func did. 'extraMeta' => -1, 'automatorPassthrough' => -1, 'silentInsert' => false, // this was for init Migration - it KILLS all IA for newForm (because is migrating, not creating new :) this was -1 before 'do_not_update_blanks' => false // this allows you to not update fields if blank (same as fieldoverride for extsource -> in) ); foreach ( $defaultArgs as $argK => $argV ) { $$argK = $argV; if ( is_array( $args ) && isset( $args[$argK] ) ) { if ( is_array( $args[ $argK] ) ) { $newData = $$argK; if ( ! is_array( $newData ) ) { $newData = array(); } foreach ( $args[ $argK ] as $subK => $subV ) { $newData[$subK] = $subV; } $$argK = $newData; } else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ $id = (int) $id; // here we check that the potential owner CAN even own if ($owner > 0 && !user_can($owner,'admin_zerobs_usr')) $owner = -1; // if owner = -1, add current if (!isset($owner) || $owner === -1) { $owner = zeroBSCRM_user(); } if (is_array($limitedFields)){ // LIMITED UPDATE (only a few fields.) if (!is_array($limitedFields) || count ($limitedFields) <= 0) return false; // REQ. ID too (can only update) if (empty($id) || $id <= 0) return false; } else { // NORMAL, FULL UPDATE } #} If no style, add it in if (is_null($data['style']) || !isset($data['style']) || empty($data['style'])){ //def $data['style'] = 'simple'; } #} ========= / CHECK FIELDS =========== #} ========= OVERRIDE SETTING (Deny blank overrides) =========== // either ext source + setting, or set by the func call if ($do_not_update_blanks){ // this setting says 'don't override filled-out data with blanks' // so here we check through any passed blanks + convert to limitedFields // only matters if $id is set (there is somt to update not add if (isset($id) && !empty($id) && $id > 0){ // get data to copy over (for now, this is required to remove 'fullname' etc.) $dbData = $this->db_ready_form($data); //unset($dbData['id']); // this is unset because we use $id, and is update, so not req. legacy issue //unset($dbData['created']); // this is unset because this uses an obj which has been 'updated' against original details, where created is output in the WRONG format :) $origData = $data; //$data = array(); $limitedData = array(); // array(array('key'=>'zbsf_x','val'=>y,'type'=>'%s')) // cycle through + translate into limitedFields (removing any blanks, or arrays (e.g. externalSources)) // we also have to remake a 'faux' data (removing blanks for tags etc.) for the post-update updates foreach ($dbData as $k => $v){ $intV = (int)$v; // only add if valuenot empty if (!is_array($v) && !empty($v) && $v != '' && $v !== 0 && $v !== -1 && $intV !== -1){ // add to update arr $limitedData[] = array( 'key' => 'zbsf_'.$k, // we have to add zbsf_ here because translating from data -> limited fields 'val' => $v, 'type' => $this->getTypeStr('zbsf_'.$k) ); // add to remade $data for post-update updates $data[$k] = $v; } } // copy over $limitedFields = $limitedData; } // / if ID } // / if do_not_update_blanks #} ========= / OVERRIDE SETTING (Deny blank overrides) =========== #} ========= BUILD DATA =========== $update = false; $dataArr = array(); $typeArr = array(); if (is_array($limitedFields)){ // LIMITED FIELDS $update = true; // cycle through foreach ($limitedFields as $field){ // some weird case where getting empties, so added check if (!empty($field['key'])){ $dataArr[$field['key']] = $field['val']; $typeArr[] = $field['type']; } } // add update time if (!isset($dataArr['zbsf_lastupdated'])){ $dataArr['zbsf_lastupdated'] = time(); $typeArr[] = '%d'; } } else { // FULL UPDATE/INSERT // UPDATE $dataArr = array( // ownership // no need to update these (as of yet) - can't move teams etc. //'zbs_site' => zeroBSCRM_installSite(), //'zbs_team' => zeroBSCRM_installTeam(), //'zbs_owner' => $owner, 'zbsf_title' => $data['title'], 'zbsf_style' => $data['style'], 'zbsf_views' => $data['views'], 'zbsf_conversions' => $data['conversions'], 'zbsf_label_header' => $data['label_header'], 'zbsf_label_subheader' => $data['label_subheader'], 'zbsf_label_firstname' => $data['label_firstname'], 'zbsf_label_lastname' => $data['label_lastname'], 'zbsf_label_email' => $data['label_email'], 'zbsf_label_message' => $data['label_message'], 'zbsf_label_button' => $data['label_button'], 'zbsf_label_successmsg' => $data['label_successmsg'], 'zbsf_label_spammsg' => $data['label_spammsg'], 'zbsf_include_terms_check' => $data['include_terms_check'], 'zbsf_terms_url' => $data['terms_url'], 'zbsf_redir_url' => $data['redir_url'], 'zbsf_font' => $data['font'], 'zbsf_colour_bg' => $data['colour_bg'], 'zbsf_colour_font' => $data['colour_font'], 'zbsf_colour_emphasis' => $data['colour_emphasis'], 'zbsf_lastupdated' => time(), ); $typeArr = array( // field data types //'%d', // site //'%d', // team //'%d', // owner '%s', '%s', '%d', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%d', ); if (!empty($id) && $id > 0){ // is update $update = true; } else { // INSERT (get's few extra :D) $update = false; $dataArr['zbs_site'] = zeroBSCRM_site(); $typeArr[] = '%d'; $dataArr['zbs_team'] = zeroBSCRM_team(); $typeArr[] = '%d'; $dataArr['zbs_owner'] = $owner; $typeArr[] = '%d'; if (isset($data['created']) && !empty($data['created']) && $data['created'] !== -1){ $dataArr['zbsf_created'] = $data['created'];$typeArr[] = '%d'; } else { $dataArr['zbsf_created'] = time(); $typeArr[] = '%d'; } } } #} ========= / BUILD DATA =========== #} ============================================================ #} ========= CHECK force_uniques & not_empty & max_len ======== // if we're passing limitedFields we skip these, for now // #v3.1 - would make sense to unique/nonempty check just the limited fields. #gh-145 if (!is_array($limitedFields)){ // verify uniques if (!$this->verifyUniqueValues($data,$id)) return false; // / fails unique field verify // verify not_empty if (!$this->verifyNonEmptyValues($data)) return false; // / fails empty field verify } // whatever we do we check for max_len breaches and abbreviate to avoid wpdb rejections $dataArr = $this->wpdbChecks($dataArr); #} ========= / CHECK force_uniques & not_empty ================ #} ============================================================ #} Check if ID present if ($update){ #} Attempt update if ($wpdb->update( $ZBSCRM_t['forms'], $dataArr, array( // where 'ID' => $id ), $typeArr, array( // where data types '%d' )) !== false){ // if passing limitedFields instead of data, we ignore the following // this doesn't work, because data is in args default as arr //if (isset($data) && is_array($data)){ // so... if (!isset($limitedFields) || !is_array($limitedFields) || $limitedFields == -1){ // tags if (isset($data['tags']) && is_array($data['tags'])) { $this->addUpdateFormTags( array( 'id' => $id, 'tag_input' => $data['tags'], 'mode' => $data['tag_mode'] ) ); } } // / if $data #} Any extra meta keyval pairs? // BRUTALLY updates (no checking) $confirmedExtraMeta = false; if (isset($extraMeta) && is_array($extraMeta)) { $confirmedExtraMeta = array(); foreach ($extraMeta as $k => $v){ #} This won't fix stupid keys, just catch basic fails... $cleanKey = strtolower(str_replace(' ','_',$k)); #} Brutal update //update_post_meta($postID, 'zbs_customer_extra_'.$cleanKey, $v); $this->DAL()->updateMeta(ZBS_TYPE_FORM,$id,'extra_'.$cleanKey,$v); #} Add it to this, which passes to IA $confirmedExtraMeta[$cleanKey] = $v; } } #} INTERNAL AUTOMATOR #} & #} FALLBACKS // UPDATING CONTACT if (!$silentInsert){ // IA General form update (2.87+) zeroBSCRM_FireInternalAutomator('form.update',array( 'id'=>$id, 'againstid' => $id, 'data'=> $dataArr )); } // Successfully updated - Return id return $id; } else { $msg = __('DB Update Failed','zero-bs-crm'); $zbs->DAL->addError(302,$this->objectType,$msg,$dataArr); // FAILED update return false; } } else { #} No ID - must be an INSERT if ($wpdb->insert( $ZBSCRM_t['forms'], $dataArr, $typeArr ) > 0){ #} Successfully inserted, lets return new ID $newID = $wpdb->insert_id; // tags if (isset($data['tags']) && is_array($data['tags'])) { $this->addUpdateFormTags( array( 'id' => $newID, 'tag_input' => $data['tags'], 'mode' => $data['tag_mode'] ) ); } #} Any extra meta keyval pairs? // BRUTALLY updates (no checking) $confirmedExtraMeta = false; if (isset($extraMeta) && is_array($extraMeta)) { $confirmedExtraMeta = array(); foreach ($extraMeta as $k => $v){ #} This won't fix stupid keys, just catch basic fails... $cleanKey = strtolower(str_replace(' ','_',$k)); #} Brutal update //update_post_meta($postID, 'zbs_customer_extra_'.$cleanKey, $v); $this->DAL()->updateMeta(ZBS_TYPE_FORM,$newID,'extra_'.$cleanKey,$v); #} Add it to this, which passes to IA $confirmedExtraMeta[$cleanKey] = $v; } } #} INTERNAL AUTOMATOR #} & #} FALLBACKS // NEW CONTACT if (!$silentInsert){ #} Add to automator zeroBSCRM_FireInternalAutomator('form.new',array( 'id'=>$newID, 'data'=>$dataArr, 'automatorpassthrough'=>$automatorPassthrough, #} This passes through any custom log titles or whatever into the Internal automator recipe. 'extraMeta'=>$confirmedExtraMeta #} This is the "extraMeta" passed (as saved) )); } return $newID; } else { $msg = __('DB Insert Failed','zero-bs-crm'); $zbs->DAL->addError(303,$this->objectType,$msg,$dataArr); #} Failed to Insert return false; } } return false; } /** * adds or updates a form's tags * ... this is really just a wrapper for addUpdateObjectTags * * @param array $args Associative array of arguments * id (if update), owner, data (array of field data) * * @return int line ID */ public function addUpdateFormTags($args=array()){ global $ZBSCRM_t,$wpdb; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, // generic pass-through (array of tag strings or tag IDs): 'tag_input' => -1, // or either specific: 'tagIDs' => -1, 'tags' => -1, 'mode' => 'append' ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} ========== CHECK FIELDS ============ // check id $id = (int)$id; if (empty($id) || $id <= 0) return false; #} ========= / CHECK FIELDS =========== return $this->DAL()->addUpdateObjectTags( array( 'objtype' => ZBS_TYPE_FORM, 'objid' => $id, 'tag_input' => $tag_input, 'tags' => $tags, 'tagIDs' => $tagIDs, 'mode' => $mode ) ); } /** * deletes a form object * * @param array $args Associative array of arguments * id * * @return int success; */ public function deleteForm($args=array()){ global $ZBSCRM_t,$wpdb,$zbs; #} ============ LOAD ARGS ============= $defaultArgs = array( 'id' => -1, 'saveOrphans' => true ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============ #} Check ID & Delete :) $id = (int)$id; if (!empty($id) && $id > 0) { // delete orphans? if ($saveOrphans === false){ // delete any tag links $this->DAL()->deleteTagObjLinks(array( 'objtype' => ZBS_TYPE_FORM, 'objid' => $id )); // delete any external source information $this->DAL()->delete_external_sources( array( 'obj_type' => ZBS_TYPE_FORM, 'obj_id' => $id, 'obj_source' => 'all', )); } $del = zeroBSCRM_db2_deleteGeneric($id,'forms'); #} Add to automator zeroBSCRM_FireInternalAutomator('form.delete',array( 'id'=>$id, 'saveOrphans'=>$saveOrphans )); return $del; } return false; } /** * tidy's the object from wp db into clean array * * @param array $obj (DB obj) * * @return array form (clean obj) */ private function tidy_form($obj=false,$withCustomFields=false){ $res = false; if (isset($obj->ID)){ $res = array(); $res['id'] = $obj->ID; /* `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, */ $res['owner'] = $obj->zbs_owner; $res['title'] = $this->stripSlashes($obj->zbsf_title); $res['style'] = $this->stripSlashes($obj->zbsf_style); $res['views'] = (int)$obj->zbsf_views; $res['conversions'] = (int)$obj->zbsf_conversions; $res['label_header'] = $this->stripSlashes($obj->zbsf_label_header); $res['label_subheader'] = $this->stripSlashes($obj->zbsf_label_subheader); $res['label_firstname'] = $this->stripSlashes($obj->zbsf_label_firstname); $res['label_lastname'] = $this->stripSlashes($obj->zbsf_label_lastname); $res['label_email'] = $this->stripSlashes($obj->zbsf_label_email); $res['label_message'] = $this->stripSlashes($obj->zbsf_label_message); $res['label_button'] = $this->stripSlashes($obj->zbsf_label_button); $res['label_successmsg'] = $this->stripSlashes($obj->zbsf_label_successmsg); $res['label_spammsg'] = $this->stripSlashes($obj->zbsf_label_spammsg); $res['include_terms_check'] = (bool)$obj->zbsf_include_terms_check; $res['terms_url'] = $this->stripSlashes($obj->zbsf_terms_url); $res['redir_url'] = $this->stripSlashes($obj->zbsf_redir_url); $res['font'] = $this->stripSlashes($obj->zbsf_font); $res['colour_bg'] = $this->stripSlashes($obj->zbsf_colour_bg); $res['colour_font'] = $this->stripSlashes($obj->zbsf_colour_font); $res['colour_emphasis'] = $this->stripSlashes($obj->zbsf_colour_emphasis); $res['created'] = (int)$obj->zbsf_created; //$res['created_date'] = (isset($obj->zbsf_created) && $obj->zbsf_created > 0) ? zeroBSCRM_locale_utsToDatetime($obj->zbsf_created) : false; $res['created_date'] = (isset($obj->zbsf_created) && $obj->zbsf_created > 0) ? zeroBSCRM_date_i18n(-1,$obj->zbsf_created,false,true) : false; $res['lastupdated'] = (int)$obj->zbsf_lastupdated; //$res['lastupdated_date'] = (isset($obj->zbsf_lastupdated) && $obj->zbsf_lastupdated > 0) ? zeroBSCRM_locale_utsToDatetime($obj->zbsf_lastupdated) : false; $res['lastupdated_date'] = (isset($obj->zbsf_lastupdated) && $obj->zbsf_lastupdated > 0) ? zeroBSCRM_date_i18n(-1,$obj->zbsf_lastupdated,false,true) : false; } return $res; } /** * Wrapper, use $this->getFormMeta($contactID,$key) for easy retrieval of singular form * Simplifies $this->getMeta * * @param int objtype * @param int objid * @param string key * * @return array form meta result */ public function getFormMeta($id=-1,$key='',$default=false){ global $zbs; if (!empty($key)){ return $this->DAL()->getMeta(array( 'objtype' => ZBS_TYPE_FORM, 'objid' => $id, 'key' => $key, 'fullDetails' => false, 'default' => $default, 'ignoreowner' => true // for now !! )); } return $default; } /** * Returns an ownerid against a form * * @param int id form ID * * @return int form owner id */ public function getFormOwner($id=-1){ global $zbs; $id = (int)$id; if ($id > 0){ return $this->DAL()->getFieldByID(array( 'id' => $id, 'objtype' => ZBS_TYPE_FORM, 'colname' => 'zbs_owner', 'ignoreowner'=>true)); } return false; } /** * remove any non-db fields from the object * basically takes array like array('owner'=>1,'fname'=>'x','fullname'=>'x') * and returns array like array('owner'=>1,'fname'=>'x') * This does so based on the objectModel! * * @param array $obj (clean obj) * * @return array (db ready arr) */ private function db_ready_form($obj=false){ // use the generic? (override here if necessary) return $this->db_ready_obj($obj); } /** * Takes full object and makes a "list view" boiled down version * Used to generate listview objs * * @param array $obj (clean obj) * * @return array (listview ready obj) */ public function listViewObj($form=false,$columnsRequired=array()){ if (is_array($form) && isset($form['id'])){ $resArr = $form; // a lot of this is legacy <DAL3 stuff just mapped. def could do with an improvement for efficacy's sake. // lol needed none for DAL 3 :) perfect object. // $resArr['style'] = get_post_meta($form['id'], 'zbs_form_style',true); // $resArr['views'] = get_post_meta($form['id'], 'zbs_form_views',true); // $resArr['conversions'] = get_post_meta($form['id'], 'zbs_form_conversions',true); // $resArr['id'] = $form['id']; // $resArr['title'] = $form['title']; // $d = new DateTime($form['created']); // $formatted_date = $d->format(zeroBSCRM_getDateFormat()); // use Proper field $resArr['added'] = $formatted_date; return $resArr; } return false; } /** * Increase the form views in +1 * * @param $form_id The form ID * @return mixed Return the total views */ public function add_form_view( $form_id ) { $form = $this->getForm( $form_id ); $form[ 'views' ]++; $this->addUpdateForm( array( 'id' => $form_id, 'data' => $form, ) ); return $form[ 'views' ]; } /** * Increase the form conversions in +1 * * @param $form_id The form ID * @return mixed Return the total conversions */ public function add_form_conversion( $form_id ) { $form = $this->getForm( $form_id ); $form[ 'conversions' ]++; $this->addUpdateForm( array( 'id' => $form_id, 'data' => $form, ) ); return $form[ 'conversions' ]; } // =========== / FORM ======================================================= // =============================================================================== } // / class
projects/plugins/crm/includes/ZeroBSCRM.MetaBoxes3.ExternalSources.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V3.0 * * Copyright 2020 Automattic * * Date: 20/02/2019 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== Create External Source Metabox ====================================================== */ class zeroBS__Metabox_ExtSource extends zeroBS__Metabox { private $acceptableTypes = array('contact','company','transaction','invoice'); /** * The object type ID using this metabox. * * @since 6.2.0 * @var int */ private $objTypeID; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.PropertyNotSnakeCase public function __construct( $plugin_file, $objType='contact',$metaboxScreen='zbs-add-edit-contact-edit' ) { global $zbs; // set these // DAL3 switched for objType $this->postType = 'zerobs_customer'; $this->objType = 'contact'; $this->objTypeID = ZBS_TYPE_CONTACT; $this->metaboxID = 'zerobs-externalsource'; $this->metaboxTitle = __('External Source',"zero-bs-crm"); $this->metaboxScreen = 'zbs-add-edit-contact-edit'; // DEFAULT (overriden by metaboxScreens below) // Better than this, is initiating multiple of this class with diff screens/objtypes // ... because that presevers obj type unlike this solution: $this->metaboxScreens = array('zbs-add-edit-contact-edit','zbs-add-edit-company-edit'); // (since v3.0 we can add multiple, overrides metaboxScreen) $this->metaboxArea = 'side'; $this->metaboxLocation = 'low'; $this->saveOrder = 1; $this->capabilities = array( 'can_hide' => false, // can be hidden 'areas' => array('side'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => true, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true, // can be minimised 'can_move' => true // can be moved ); // Catch any passed params as overrides // (this allows us to have multiple initialised (e.g. one for contacts, one co's)) if (isset($objType)) $this->objType = $objType; if (isset($objType)) $this->objTypeID = $zbs->DAL->objTypeID($this->objType); if (isset($metaboxScreen)) $this->metaboxScreen = $metaboxScreen; // set typeint based on type $this->typeInt = $zbs->DAL->objTypeID($this->objType); // contact -> ZBS_TYPE_CONTACT = 1 #} Only load if is legit. // also hide if "new" (not edit) - as defies point of extsource $isEdit = false; if (isset($_GET['action']) && $_GET['action'] == 'edit' && isset($_GET['zbsid']) && !empty($_GET['zbsid'])) $isEdit = true; if (in_array($this->objType,$this->acceptableTypes) && $isEdit){ // call this $this->initMetabox(); } } public function html( $obj, $metabox ) { global $zbs; // Only load if is legit. if ( in_array( $this->objType, $this->acceptableTypes ) ){ $object_id = -1; if ( is_array( $obj ) && isset( $obj['id'] ) ) { $object_id = (int)$obj['id']; } // use centralised function to draw jpcrm_render_external_sources_by_id( $object_id, $this->objTypeID ); } // / only load if post type } } /* ====================================================== / Create External Source Metabox ====================================================== */
projects/plugins/crm/includes/ZeroBSCRM.MetaBoxes3.Ownership.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V3.0 * * Copyright 2020 Automattic * * Date: 20/02/2019 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ class zeroBS__Metabox_Ownership extends zeroBS__Metabox { public $saveAutomatically = false; // if this is true, this'll automatically update the object owner- this is off by default as most objects save owners themselves as part of addUpdateWhatever so that IA hooks fire correctly public function __construct( $plugin_file, $typeInt = ZBS_TYPE_CONTACT ) { global $zbs; // set these via init (defaults) $this->typeInt = $typeInt; // these then use objtypeint to generate: $typeStr = $zbs->DAL->objTypeKey( $typeInt ); $this->objType = $typeStr; $this->metaboxID = 'zerobs-'.$typeStr.'-owner'; // zerobs-contact-owner $this->metaboxScreen = 'zbs-add-edit-'.$typeStr.'-edit'; //'zbs-add-edit-contact-edit' $this->metaboxArea = 'side'; $this->metaboxLocation = 'low'; $this->metaboxTitle = __( 'Assigned To', 'zero-bs-crm' ); // call this $this->initMetabox(); } public function html( $obj, $metabox ) { global $zbs; // localise ID if ( is_array( $obj ) && isset( $obj['id'] ) ) { $objID = (int)$obj['id']; $zbsThisOwner = zeroBS_getOwnerObj( $obj['owner'] ); } else { $objID = -1; $zbsThisOwner = array(); } // can even change owner? $canGiveOwnership = $zbs->settings->get( 'usercangiveownership' ); $canChangeOwner = ( $canGiveOwnership == "1" || current_user_can( 'administrator' ) ); // init $zbsPossibleOwners = array(); switch ($this->typeInt){ case ZBS_TYPE_CONTACT: // If allowed to change assignment, load other possible users if ($canChangeOwner) $zbsPossibleOwners = zeroBS_getPossibleCustomerOwners(); break; case ZBS_TYPE_COMPANY: // If allowed to change assignment, load other possible users if ($canChangeOwner) $zbsPossibleOwners = zeroBS_getPossibleCompanyOwners(); break; default: $zbsThisOwner = array(); break; } // Can change owner, or has owner details, then show... (this whole box will be hidden if setting says no ownerships) if ($canChangeOwner || isset($zbsThisOwner['ID'])){ // Either: "assigned to DAVE" or "assigned to DAVE (in drop down list)" if (!$canChangeOwner) { // simple unchangable ?> <div style="text-align:center"> <?php echo esc_html( $zbsThisOwner['OBJ']->display_name ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?> </div> <?php } else { // DDL ?> <div style="text-align:center"> <select class="" id="zerobscrm-owner" name="zerobscrm-owner"> <option value="-1"><?php esc_html_e('None',"zero-bs-crm");?></option> <?php if ( is_array( $zbsPossibleOwners ) && count( $zbsPossibleOwners ) > 0 ) { foreach ( $zbsPossibleOwners as $possOwner ) { $is_selected = isset($zbsThisOwner['ID']) && $possOwner->ID == $zbsThisOwner['ID']; echo '<option value="' . esc_attr( $possOwner->ID ) . '"' . ($is_selected ? ' selected="selected"' : '') . '>' . esc_html( $possOwner->display_name ) . '</option>'; } } ?> </select> </div> <?php } } } public function save_data( $objID, $obj ) { // Note: Most objects save owners as part of their own addUpdate routines. // so this now only fires where saveAutomatically = true if ($this->saveAutomatically){ $newOwner = -1; if (isset( $_POST['zerobscrm-owner'] ) && !empty( $_POST['zerobscrm-owner'] ) ) { $newOwner = (int)sanitize_text_field( $_POST['zerobscrm-owner'] ); } // If newly created and no new owner specified, use self: if ( isset( $_POST['zbscrm_newcustomer'] ) && $newOwner === -1 ){ $newOwner = get_current_user_id(); } // Save if ( $objID > 0 && $this->typeInt > 0 ){ $zbs->DAL->setObjectOwner( array( 'objID' => $objID, 'objTypeID' => $this->typeInt, 'ownerID' => $newOwner ) ); } } return $obj; } }
projects/plugins/crm/includes/ZeroBSCRM.MetaBoxes3.Contacts.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V3.0 * * Copyright 2020 Automattic * * Date: 20/02/2019 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== Init Func ====================================================== */ function zeroBSCRM_CustomersMetaboxSetup(){ if (zeroBSCRM_is_customer_edit_page()){ // Customer Fields $zeroBS__Metabox_Contact = new zeroBS__Metabox_Contact( __FILE__ ); // Actions $zeroBS__Metabox_ContactActions = new zeroBS__Metabox_ContactActions( __FILE__ ); // Logs // req. for custom log types zeroBSCRM_setupLogTypes(); // metabox $zeroBS__Metabox_ContactLogs = new zeroBS__Metabox_ContactLogs( __FILE__ ); // Tags $zeroBS__Metabox_ContactTags = new zeroBS__Metabox_ContactTags( __FILE__ ); // External sources //$zeroBS__Metabox_ContactExternalSources = new zeroBS__Metabox_ContactExternalSources( __FILE__ ); $zeroBS__Metabox_ExtSource = new zeroBS__Metabox_ExtSource( __FILE__, 'contact','zbs-add-edit-contact-edit'); // Quotes, Invs, Trans // Don't need now we have singular :) //$zeroBS__MetaboxAssociated = new zeroBS__MetaboxAssociated( __FILE__ ); // Client Portal access if (zeroBSCRM_isExtensionInstalled('portal')) $zeroBS__Metabox_ContactPortal = new zeroBS__Metabox_ContactPortal( __FILE__ ); // Customer File Attachments // Custom file attachment boxes if (zeroBSCRM_is_customer_edit_page()){ /* old way $settings = zeroBSCRM_getSetting('customfields'); $cfbInd = 1; if (isset($settings['customersfiles']) && is_array($settings['customersfiles']) && count($settings['customersfiles']) > 0) foreach ($settings['customersfiles'] as $cfb){ $cfbName = ''; if (isset($cfb[0])) $cfbName = $cfb[0]; //add_meta_box('zerobs-customer-files-'.$cfbInd, $cfbName, 'zeroBS__MetaboxFilesCustom', 'zerobs_customer', 'normal', 'low',$cfbName); $zeroBS__Metabox_ContactCustomFiles = new zeroBS__Metabox_ContactCustomFiles( __FILE__, 'zerobs-customer-files-'.$cfbInd , $cfbName); $cfbInd++; } */ $fileSlots = zeroBSCRM_fileSlots_getFileSlots(); if (count($fileSlots) > 0) foreach ($fileSlots as $fs){ $zeroBS__Metabox_ContactCustomFiles = new zeroBS__Metabox_ContactCustomFiles( __FILE__, 'zerobs-customer-files-'.$fs['key'] , $fs['name']); } } #} Social if (zeroBSCRM_getSetting('usesocial') == "1") $zeroBS__Metabox_ContactSocial = new zeroBS__Metabox_ContactSocial( __FILE__ ); #} AKA if (zeroBSCRM_getSetting('useaka') == "1") $zeroBS__Metabox_ContactAKA = new zeroBS__Metabox_ContactAKA( __FILE__ ); #} Ownership if (zeroBSCRM_getSetting('perusercustomers') == "1") $zeroBS__Metabox_Ownership = new zeroBS__Metabox_Ownership( __FILE__, ZBS_TYPE_CONTACT); #} B2B mode (assign to co) if (zeroBSCRM_getSetting('companylevelcustomers') == "1") $zeroBS__Metabox_ContactCompany = new zeroBS__Metabox_ContactCompany( __FILE__ ); } // Activity box on view page if ( zeroBSCRM_is_customer_view_page() ) { $zeroBS__Metabox_Contact_Activity = new zeroBS__Metabox_Contact_Activity( __FILE__ ); if ( zeroBSCRM_isExtensionInstalled( 'portal' ) ) { $zeroBS__Metabox_ContactPortal = new zeroBS__Metabox_ContactPortal( __FILE__, 'zbs-view-contact' ); } } } add_action( 'admin_init', 'zeroBSCRM_CustomersMetaboxSetup' ); /* ====================================================== / Init Func ====================================================== */ /* ====================================================== Declare Globals ====================================================== */ #} Used throughout // Don't know who added this, but GLOBALS are out of scope here //global $zbsCustomerFields,$zbsCustomerQuoteFields,$zbsCustomerInvoiceFields; /* ====================================================== / Declare Globals ====================================================== */ // PerfTest: zeroBSCRM_performanceTest_startTimer('custmetabox'); /* ====================================================== Customer Metabox ====================================================== */ class zeroBS__Metabox_Contact extends zeroBS__Metabox{ // this is for catching 'new' contacts private $newRecordNeedsRedir = false; public function __construct( $plugin_file ) { // set these $this->objType = 'contact'; $this->metaboxID = 'zerobs-customer-edit'; $this->metaboxTitle = __('Contact Details',"zero-bs-crm"); $this->metaboxScreen = 'zbs-add-edit-contact-edit'; //'zerobs_edit_contact'; // we can use anything here as is now using our func $this->metaboxArea = 'normal'; $this->metaboxLocation = 'high'; $this->saveOrder = 1; $this->capabilities = array( 'can_hide' => false, // can be hidden 'areas' => array('normal'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => true, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true, // can be minimised 'can_move' => true // can be moved ); // call this $this->initMetabox(); } /** * This method generates HTML content for contact and metadata. * * It contains a series of operations to format and display contact data * and metadata according to the parameters. This includes information retrieval, * settings configuration, field hiding, address display and others. * * @param array $contact An associative array containing contact details. * @param array $metabox Metabox information. * * @return void */ public function html( $contact, $metabox ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable global $zbs; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase global $zbsContactEditing; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase global $zbsCustomerFields; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase if ( ! isset( $zbsContactEditing ) && isset( $contact['id'] ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $customer = zeroBS_getCustomer( $contact['id'], false, false, false ); $zbsContactEditing = $customer; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } else { $customer = $zbsContactEditing; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } $fields_to_hide = $zbs->settings->get( 'fieldhides' ); $show_id = (int) $zbs->settings->get( 'showid' ); $fields = $zbsCustomerFields; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $show_addresses = zeroBSCRM_getSetting( 'showaddress' ); $show_second_address = (int) zeroBSCRM_getSetting( 'secondaddress' ); $show_country_fields = zeroBSCRM_getSetting( 'countries' ); $second_address_label = zeroBSCRM_getSetting( 'secondaddresslabel' ); if ( empty( $second_address_label ) ) { $second_address_label = __( 'Second Address', 'zero-bs-crm' ); } ?> <script type="text/javascript">var zbscrmjs_secToken = '<?php echo esc_js( wp_create_nonce( 'zbscrmjs-ajax-nonce' ) ); ?>';</script> <?php if ( gettype( $customer ) !== 'array' ) { echo '<input type="hidden" name="zbscrm_newcustomer" value="1" />'; } ?> <div> <div class="jpcrm-form-grid" id="wptbpMetaBoxMainItem"> <?php $avatar_mode = (int) zeroBSCRM_getSetting( 'avatarmode' ); if ( $avatar_mode === 2 ) : ?> <div class="jpcrm-form-group jpcrm-form-group-span-2"> <label class="jpcrm-form-label"><?php esc_html_e( 'Profile Picture', 'zero-bs-crm' ); ?>:</label> <?php $avatar_url = isset( $contact['id'] ) ? $zbs->DAL->contacts->getContactAvatar( $contact['id'] ) : zeroBSCRM_getDefaultContactAvatar(); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase $empty_avatar_url = zeroBSCRM_getDefaultContactAvatar(); ?> <div class="zbs-text-input"> <div class="jpcrm-customer-profile-picture-container" style="margin-right:10px;"> <img src="<?php echo esc_attr( $avatar_url ); ?>" id="profile-picture-img" class="jpcrm-customer-profile-picture" /> <img src="<?php echo esc_attr( $empty_avatar_url ); ?>" id="empty-profile-picture" class="jpcrm-customer-profile-picture" style="display:none;" /> <br /> <label for="zbsc_profile-picture-file" class="jpcrm-customer-file-upload"> <?php esc_html_e( 'Change Picture', 'zero-bs-crm' ); ?> <input id="zbsc_profile-picture-file" type="file" name="zbsc_profile-picture-file" class="jpcrm-customer-input-file"/> </label> <label id="zbsc_remove-profile-picture-button" class="jpcrm-customer-file-upload-remove"> <?php esc_html_e( 'Remove', 'zero-bs-crm' ); ?> <input type="hidden" id="zbsc_remove-profile-picture" name="zbsc_remove-profile-picture" value="0" /> </label> </div> </div> </div> <?php endif; if ( $show_id === 1 && isset( $contact['id'] ) && ! empty( $contact['id'] ) ) : ?> <div class="jpcrm-form-group"> <label class="jpcrm-form-label"><?php esc_html_e( 'Contact ID', 'zero-bs-crm' ); ?>:</label> <b>#<?php echo isset( $contact['id'] ) ? esc_html( $contact['id'] ) : ''; ?></b> </div> <div class="jpcrm-form-group"> </div> <?php endif; global $zbsFieldsEnabled; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase if ( $show_second_address === 1 ) { $zbsFieldsEnabled['secondaddress'] = true; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } $field_group = ''; foreach ( $fields as $field_key => $field_value ) { $show_field = ! isset( $field_value['opt'] ) || isset( $zbsFieldsEnabled[ $field_value['opt'] ] ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $show_field = isset( $fields_to_hide['customer'] ) && is_array( $fields_to_hide['customer'] ) && in_array( $field_key, $fields_to_hide['customer'] ) // phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict ? false : $show_field; $show_field = isset( $field_value[0] ) && 'selectcountry' === $field_value[0] && 0 === $show_country_fields ? false : $show_field; if ( isset( $field_value['area'] ) && $field_value['area'] !== '' ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase if ( $show_addresses !== 1 ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase continue; } elseif ( $field_group === '' ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase echo '<div class="jpcrm-form-grid" style="padding:0px;grid-template-columns: 1fr;">'; echo '<div class="jpcrm-form-group"><label>'; echo esc_html__( $field_value['area'], 'zero-bs-crm' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, WordPress.WP.I18n.NonSingularStringLiteralText echo '</label></div>'; } elseif ( $field_group !== $field_value['area'] ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase echo '</div>'; echo '<div class="jpcrm-form-grid" style="padding:0px;grid-template-columns: 1fr;">'; echo '<div class="jpcrm-form-group"><label>'; echo $show_field ? esc_html( $second_address_label ) : ''; echo '</label></div>'; } $field_group = $field_value['area']; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, WordPress.WP.I18n.NonSingularStringLiteralText } if ( $field_group !== '' && ( ! isset( $field_value['area'] ) || $field_value['area'] === '' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $field_group = ''; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase echo '</div>'; echo '<div class="jpcrm-form-group jpcrm-form-group-span-2">&nbsp;</div>'; } if ( $show_field ) { if ( isset( $field_value[0] ) ) { if ( $field_group === 'Second Address' ) { $field_value[1] = str_replace( ' (' . $second_address_label . ')', '', $field_value[1] ); } zeroBSCRM_html_editField( $customer, $field_key, $field_value, 'zbsc_' ); } } } ?> </div> </div> <?php } public function save_data( $contact_id, $contact ) { if (!defined('ZBS_C_SAVED')){ // debug if (get_current_user_id() == 12) echo 'FIRING<br>'; define('ZBS_C_SAVED',1); global $zbs; // check this if (empty($contact_id) || $contact_id < 1) $contact_id = -1; $dataArr = zeroBS_buildContactMeta($_POST); // Use the tag-class function to retrieve any tags so we can add inline. // Save tags against objid $dataArr['tags'] = zeroBSCRM_tags_retrieveFromPostBag(true,ZBS_TYPE_CONTACT); // owner - saved here now, rather than ownership box, to allow for pre-hook update. (as tags) $owner = -1; // Only allow an existing contact to change owners if they have permission to do so. if ( $contact_id > -1 ) { $can_edit_all_contacts = current_user_can( 'admin_zerobs_customers' ) && $zbs->settings->get( 'perusercustomers' ) == 0; // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual,WordPress.WP.Capabilities.Unknown -- capability was defined in ZeroBSCRM.Permissions.php $can_give_ownership = $zbs->settings->get( 'usercangiveownership' ) == 1; // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual -- also above, there is the chance the numbers could be strings here, as expected elsewhere in the plugin. $can_change_owner = ( $can_give_ownership || current_user_can( 'manage_options' ) || $can_edit_all_contacts ); if ( $can_change_owner ) { if ( isset( $_POST['zerobscrm-owner'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- todo - noted in zero-bs-crm 2457. $potential_owner = (int) sanitize_text_field( wp_unslash( $_POST['zerobscrm-owner'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- todo - noted in zero-bs-crm 2457. if ( $potential_owner > 0 ) { $owner = $potential_owner; } } } else { $owner = (int) $zbs->DAL->getContactOwner( $contact_id ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase } } // now we check whether a user with this email already exists (separate to this contact id), so we can warn them // ... that it wont have changed the email if ( !empty( $dataArr['email'] ) ) { if ( !zeroBSCRM_validateEmail( $dataArr['email'] ) ) { $this->update_invalid_email( $dataArr['email'] ); $dataArr['email'] = ''; } else { $potentialID = zeroBS_getCustomerIDWithEmail( $dataArr['email'] ); if ( !empty( $potentialID ) && $potentialID != $contact_id ) { // no go. $this->updateEmailDupeMessage( $potentialID ); // unset email change (leave as was) $dataArr['email'] = zeroBS_customerEmail( $contact_id ); } } } // phpcs:disable WordPress.NamingConventions.ValidVariableName -- to be refactored. // We have to explicitly retrieve the avatar from the DB. $dataArr['avatar'] = ( $contact_id !== -1 ) ? $zbs->DAL->contacts->getContactAvatar( $contact_id ) : ''; //phpcs:enable WordPress.NamingConventions.ValidVariableName // make a copy for IA below (just fields) $contactData = $dataArr; // Company assignment? if (isset($_POST['zbs_company'])) $dataArr['companies'] = array((int)sanitize_text_field($_POST['zbs_company'])); // Stripslashes // This avoids us adding `O\'toole ltd' into the db. see #1107 // ...this is more sensitive than using zeroBSCRM_stripSlashesFromArr // in the long term it may make more sense to stripslashes pre insert/update in the DAL // in the case of contacts, there are no core fields which will be broken by stripslashes at this time (4.0.11) $data_array = $dataArr; foreach ($dataArr as $key => $val){ // op strings $value = $val; if ( is_string( $value ) ) $value = stripslashes( $value ); // pass into final array $data_array[$key] = $value; } // add update directly $addUpdateReturn = $zbs->DAL->contacts->addUpdateContact(array( 'id' => $contact_id, 'owner' => $owner, 'data' => $data_array, 'limitedFields' => -1, /* array( 'email' => $userDeets['email'], // Unique Field ! 'status' => $userDeets['status'], 'prefix' => $userDeets['prefix'], 'fname' => $userDeets['fname'], 'lname' => $userDeets['lname'], 'addr1' => $userDeets['addr1'], 'addr2' => $userDeets['addr2'], 'city' => $userDeets['city'], 'county' => $userDeets['county'], 'country' => $userDeets['country'], 'postcode' => $userDeets['postcode'], 'secaddr1' => $userDeets['secaddr_addr1'], 'secaddr2' => $userDeets['secaddr_addr2'], 'seccity' => $userDeets['secaddr_city'], 'seccounty' => $userDeets['secaddr_county'], 'seccountry' => $userDeets['secaddr_country'], 'secpostcode' => $userDeets['secaddr_postcode'], 'hometel' => $userDeets['hometel'], 'worktel' => $userDeets['worktel'], 'mobtel' => $userDeets['mobtel'], 'wpid' => -1, 'avatar' => $avatarURL, // Note Custom fields may be passed here, but will not have defaults so check isset() 'tags' => $tags, // wh added for later use. 'lastcontacted' => $lastcontacted, 'companies' => $companies // array of co id's :) ) */ )); // Note: For NEW contacts, we make sure a global is set here, that other update funcs can catch // ... so it's essential this one runs first! // this is managed in the metabox Class :) if ($contact_id == -1 && !empty($addUpdateReturn) && $addUpdateReturn != -1) { $contact_id = $addUpdateReturn; global $zbsJustInsertedMetaboxID; $zbsJustInsertedMetaboxID = $contact_id; // set this so it redirs $this->newRecordNeedsRedir = true; } // success? if ($addUpdateReturn != -1 && $addUpdateReturn > 0){ $this->save_profile_picture( $contact_id, $contact ); // Update Msg // this adds an update message which'll go out ahead of any content // This adds to metabox: $this->updateMessages['update'] = zeroBSCRM_UI2_messageHTML('info olive mini zbs-not-urgent',__('Contact Updated',"zero-bs-crm"),'','address book outline','contactUpdated'); // This adds to edit page $this->updateMessage( $this->newRecordNeedsRedir ); // catch any non-critical messages $nonCriticalMessages = $zbs->DAL->getErrors(ZBS_TYPE_CONTACT); if (is_array($nonCriticalMessages) && count($nonCriticalMessages) > 0) $this->dalNoticeMessage($nonCriticalMessages); } else { // fail somehow $failMessages = $zbs->DAL->getErrors(ZBS_TYPE_CONTACT); // show msg (retrieved from DAL err stack) if (is_array($failMessages) && count($failMessages) > 0) $this->dalErrorMessage($failMessages); else $this->dalErrorMessage(array(__('Insert/Update Failed with general error','zero-bs-crm'))); // pass the pre-fill: global $zbsObjDataPrefill; $zbsObjDataPrefill = $dataArr; } } return $contact; } /* * Saves the profile picture */ public function save_profile_picture( $contact_id, $crm_contact ) { global $zbs; $contact_dir_info = jpcrm_storage_dir_info_for_contact( $contact_id ); $field_key = 'jpcrm-profile-picture'; $is_remove_flag_set = isset( $_POST['zbsc_remove-profile-picture'] ) && $_POST['zbsc_remove-profile-picture'] == '1'; $remove_old_avatar = false; $has_new_avatar_file = isset( $_FILES['zbsc_profile-picture-file'] ) && empty( $_FILES['zbsc_profile-picture-file']['error'] ) && is_uploaded_file( $_FILES['zbsc_profile-picture-file']['tmp_name'] ); if ( $is_remove_flag_set ) { $zbs->DAL->contacts->addUpdateContact( array( 'id' => $contact_id, 'limitedFields' => array( array( 'key' => 'zbsc_avatar', 'val' => '', 'type' => '%s' ) ) )); $remove_old_avatar = true; } else if ( $has_new_avatar_file ) { // verify image file type $allowed_image_types = array('image/jpeg' => 'jpg', 'image/jpg' => 'jpg', 'image/gif' => 'gif', 'image/png' => 'png'); $allowed_file_extensions = array( '.jpg', '.jpeg', '.gif', '.png' ); $allowed_mime_types = array( 'image/jpeg','image/jpg', 'image/gif', 'image/png' ); if ( !jpcrm_file_check_mime_extension( $_FILES['zbsc_profile-picture-file'], $allowed_file_extensions, $allowed_mime_types ) ){ $this->dalErrorMessage ( array( __( 'Error: Profile Picture only accepts jpg, png, and gif images!', 'zero-bs-crm' ) ) ); return; } if ( $contact_dir_info === false ) { $this->dalErrorMessage ( array( __( 'Error while retrieving the contact\'s folder.', 'zero-bs-crm' ) ) ); return; } $avatar_path = $contact_dir_info['avatar']['path']; $contact_folder_exists = jpcrm_create_and_secure_dir_from_external_access( $avatar_path, false ); if ( ! $contact_folder_exists ) { $this->dalErrorMessage ( array( __( 'There was an error creating the profile picture directory.', 'zero-bs-crm' ) ) ); return; } $zbs->load_encryption(); $avatar_filename = sprintf( 'avatar_%s.%s', $zbs->encryption->get_rand_hex( 10 ), $allowed_image_types[ $_FILES['zbsc_profile-picture-file']['type'] ] // extension for this filetype ); if ( ! file_exists( $avatar_path . '/' . $avatar_filename ) && move_uploaded_file( $_FILES['zbsc_profile-picture-file']['tmp_name'], $avatar_path . '/' . $avatar_filename) ) { $zbs->DAL->contacts->addUpdateContact( array( 'id' => $contact_id, 'limitedFields' => array( array( 'key' => 'zbsc_avatar', 'val' => $contact_dir_info['avatar']['url'] . '/' . $avatar_filename, 'type' => '%s' ) ) )); $remove_old_avatar = true; } else { $this->dalErrorMessage ( array( __( 'There was an error updating the profile picture.', 'zero-bs-crm' ) ) ); } } if ( $remove_old_avatar && ! empty( $crm_contact['avatar'] ) ) { $previous_avatar_full_path = $contact_dir_info['avatar']['path'] . '/' . basename( $crm_contact['avatar'] ); if ( file_exists( $previous_avatar_full_path ) ) { unlink( $previous_avatar_full_path ); } } } // This catches 'new' contacts + redirs to right url public function post_save_data($objID,$obj){ if ($this->newRecordNeedsRedir){ global $zbs, $zbsJustInsertedMetaboxID; if (!empty($zbsJustInsertedMetaboxID) && $zbsJustInsertedMetaboxID > 0){ // redir $zbs->new_record_edit_redirect( 'zerobs_customer', $zbsJustInsertedMetaboxID ); } } } public function updateMessage( $created = false ){ $text = $created ? __('Contact Created',"zero-bs-crm") : __('Contact Updated',"zero-bs-crm"); // zbs-not-urgent means it'll auto hide after 1.5s $msg = zeroBSCRM_UI2_messageHTML('info olive mini zbs-not-urgent',$text,'','address book outline','contactUpdated'); // quick + dirty global $zbs; $zbs->pageMessages[] = $msg; } public function update_invalid_email( $invalid_email ) { global $zbs; $msg = zeroBSCRM_UI2_messageHTML( 'info orange mini', sprintf( __( 'The contact email specified (%s) is not valid.', 'zero-bs-crm' ), $invalid_email ), '', 'address book outline', 'contactUpdated' ); $zbs->pageMessages[] = $msg; } public function updateEmailDupeMessage($otherContactID=-1){ $viewHTML = ' <a href="'.jpcrm_esc_link('view',$otherContactID,'zerobs_customer').'" target="_blank">'.__('View Contact','zero-bs-crm').'</a>'; $msg = zeroBSCRM_UI2_messageHTML('info orange mini',__('Contact email could not be updated because a contact already exists with this email address.',"zero-bs-crm").$viewHTML,'','address book outline','contactUpdated'); // quick + dirty global $zbs; $zbs->pageMessages[] = $msg; } } /* ====================================================== / Customer Metabox ====================================================== */ /* ====================================================== Create Actions Box ====================================================== */ class zeroBS__Metabox_ContactActions extends zeroBS__Metabox{ private $actions = array(); public function __construct( $plugin_file ) { $this->objType = 'contact'; $this->metaboxID = 'zerobs-customer-actions'; $this->metaboxTitle = __('Contact Actions',"zero-bs-crm"); $this->metaboxScreen = 'zbs-add-edit-contact-edit'; //'zerobs_edit_contact'; // we can use anything here as is now using our func $this->metaboxArea = 'side'; $this->metaboxLocation = 'high'; $this->headless = true; $this->capabilities = array( 'can_hide' => false, // can be hidden 'areas' => array('side'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => false, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => false, // can be minimised 'can_move' => false // can be moved ); // hacky id check for now: if (isset($_GET['zbsid']) && !empty($_GET['zbsid'])) { $id = (int)sanitize_text_field($_GET['zbsid']); // call this, if actions $this->actions = zeroBS_contact_actions($id); } $this->initMetabox(); } public function html( $contact, $metabox ) { $avatarMode = zeroBSCRM_getSetting( 'avatarmode' ); $avatarStr = ''; $is_new_contact = count( $this->actions ) > 0 ? false : true; if ( $avatarMode !== 3 ) { $cID = -1; if (is_array($contact) && isset($contact['id'])) $cID = (int)$contact['id']; $avatarStr = zeroBS_customerAvatarHTML($cID); } ?> <div class="zbs-generic-save-wrap"> <div class="ui medium dividing header"><i class="save icon"></i> <?php esc_html_e( 'Contact Actions', 'zero-bs-crm' ); ?></div> <div class="clear"></div> <?php # https://codepen.io/kyleshockey/pen/bdeLrE if ( ! $is_new_contact ) { ?> <script type="text/javascript"> var zbsContactAvatarLang = { 'upload': '<?php esc_html_e("Upload Image","zero-bs-crm");?>', }; </script> <div class="action-wrap"> <div class="ui dropdown jpcrm-button white-bg jpcrm-dropdown"><?php esc_html_e( 'Contact Actions', 'zero-bs-crm' ); ?><i class="fa fa-angle-down"></i> <div class="menu" style="margin: 4px;"> <?php foreach ($this->actions as $actKey => $action){ // filter out 'edit' as on that page :) if ($actKey != 'edit'){ ?> <div class="item zbs-contact-action" id="zbs-contact-action-<?php echo esc_attr( $actKey ); ?>"<?php // if url isset, pass that data-action, otherwise leave for js to attach to if (isset($action['url']) && !empty($action['url'])){ ?> data-action="<?php if (isset($action['url'])) echo 'url'; ?>" data-url="<?php if (isset($action['url'])) echo esc_attr( $action['url'] ); ?>"<?php } // got extra attributes? if (isset($action['extraattr']) && is_array($action['extraattr'])){ // dump extra attr into item foreach ($action['extraattr'] as $k => $v){ echo ' data-'. esc_attr( $k ) .'="'. esc_attr( $v ) .'"'; } } ?>> <?php // got ico? if (isset($action['ico'])) echo '<i class="'. esc_attr( $action['ico'] ) .'"></i>'; // got text? if (isset($action['label'])) echo esc_html( $action['label'] ); ?> </div> <?php } }?> </div> </div> </div> <script type="text/javascript"> jQuery(function(){ // actions drop down jQuery('.ui.dropdown').dropdown(); // action items jQuery('.zbs-contact-action').off('click').on( 'click', function(){ // get action type (at launch, only url) var actionType = jQuery(this).attr('data-action'); if (typeof actionType != "undefined") switch (actionType){ case 'url': var u = jQuery(this).attr('data-url'); if (typeof u != "undefined" && u != '') window.location = u; break; } }); }); </script> <?php } ?> <div class="zbs-contact-actions-bottom zbs-objedit-actions-bottom"> <button class="jpcrm-button" type="button" id="zbs-edit-save"><?php $is_new_contact ? esc_html_e( 'Save', 'zero-bs-crm' ) : esc_html_e( 'Update', 'zero-bs-crm' ); ?> <?php esc_html_e( 'Contact', 'zero-bs-crm' ); ?></button> <div class='clear'></div> </div> <?php } public function save_data( $contact_id, $contact ) { // avatar changes saved by main contact save func (field editor), allowing for all-in-one creation/updates, see #AVATARSAVE return $contact; } } /* ====================================================== / Create Actions Box ====================================================== */ /* ====================================================== Attach (custom) fileboxes to customer metabox ====================================================== */ class zeroBS__Metabox_ContactCustomFiles extends zeroBS__Metabox{ public function __construct( $plugin_file, $idOverride='',$titleOverride='' ) { $this->objType = 'contact'; $this->metaboxID = 'zerobs-customer-custom-files'; $this->metaboxTitle = __('Other Files',"zero-bs-crm"); $this->metaboxScreen = 'zbs-add-edit-contact-edit'; //'zerobs_edit_contact'; // we can use anything here as is now using our func $this->metaboxArea = 'normal'; $this->metaboxLocation = 'low'; $this->capabilities = array( 'can_hide' => true, // can be hidden 'areas' => array('normal'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => false, // can/can't accept tabs onto it 'can_become_tab' => true, // can be added as tab 'can_minimise' => true // can be minimised ); if (!empty($idOverride)) $this->metaboxID = $idOverride; if (!empty($titleOverride)) $this->metaboxTitle = __($titleOverride,"zero-bs-crm"); // call this $this->initMetabox(); } public function html( $contact, $args ) { global $zbs; $html = ''; $thisFileSlotName = ''; if (isset($args['title'])) $thisFileSlotName = $args['title']; $filePerma = ''; if (isset($thisFileSlotName) && !empty($thisFileSlotName)) { //$filePerma = strtolower(str_replace(' ','_',str_replace('.','_',substr($thisFileSlotName,0,20)))); $filePerma = $zbs->DAL->makeSlug($thisFileSlotName); } #} retrieve - shouldn't these vars be "other files"... confusing $zbsFiles = zeroBSCRM_getCustomerFiles($contact['id']); // This specifically looks for $args['title'] file :) //$fileSlotSrc = get_post_meta($contact['id'],'cfile_'.$filePerma,true); $fileSlotSrc = zeroBSCRM_fileslots_fileInSlot($filePerma,$contact['id'],ZBS_TYPE_CONTACT); // check for file + only show that $zbsFilesArr = array(); if ($fileSlotSrc !== '' && is_array($zbsFiles) && count($zbsFiles) > 0) foreach ($zbsFiles as $f) if ($f['file'] == $fileSlotSrc) $zbsFilesArr[] = $f; $zbsFiles = $zbsFilesArr; // while we only have 1 file per slot, we can do this: // *js uses this to empty if deleted elsewhere (other metabox) $fileSlotURL = ''; if (is_array($zbsFiles) && count($zbsFiles) == 1) $fileSlotURL = $zbsFiles[0]['url']; ?> <table class="form-table wh-metatab wptbp zbsFileSlotTable" data-sloturl="<?php echo esc_attr( $fileSlotURL ); ?>" id="<?php echo esc_attr( $this->metaboxID ); ?>-tab"> <?php #} Any slot filled? if (is_array($zbsFiles) && count($zbsFiles) > 0){ ?><tr class="wh-large zbsFileSlotWrap"><th class="zbsFileSlotTitle"><label><?php echo '<span>' . esc_html( count( $zbsFiles ) ) . '</span> '.esc_html__('File(s)','zero-bs-crm').':'; ?></label></th> <td class=""> <?php $fileLineIndx = 1; foreach($zbsFiles as $zbsFile){ /* $file = basename($zbsFile['file']); // if in privatised system, ignore first hash in name if (isset($zbsFile['priv'])){ $file = substr($file,strpos($file, '-')+1); } */ $file = zeroBSCRM_files_baseName($zbsFile['file'],isset($zbsFile['priv'])); echo '<div class="zbsFileLine" id="zbsFileLineCustomer'. esc_attr( $fileLineIndx ) .'"><a href="'. esc_url( $zbsFile['url'] ) .'" target="_blank">'. esc_html( $file ) .'</a> </div>'; // if using portal.. state shown/hidden // this is also shown in each file slot :) if you change any of it change that too if(defined('ZBS_CLIENTPRO_TEMPLATES')){ if(isset($zbsFile['portal']) && $zbsFile['portal']){ echo "<p><i class='icon check circle green inverted'></i> ".esc_html__('Shown on Portal','zero-bs-crm').'</p>'; }else{ echo "<p><i class='icon ban inverted red'></i> ".esc_html__('Not shown on Portal','zero-bs-crm').'</p>'; } } $fileLineIndx++; } ?> </td></tr><?php } ?> <?php #adapted from http://code.tutsplus.com/articles/attaching-files-to-your-posts-using-wordpress-custom-meta-boxes-part-1--wp-22291 // will be done by mainfunc wp_nonce_field(plugin_basename(__FILE__), 'zbsc_file_attachment_nonce'); $html .= '<input type="file" id="zbsc_file_'.$filePerma.'" name="zbsc_file_'.$filePerma.'" size="25" class="zbs-dc">'; ?><tr class="wh-large"><th><label><?php esc_html_e('Add File',"zero-bs-crm");?>:</label><br />(<?php esc_html_e('Optional',"zero-bs-crm");?>)<br /><?php esc_html_e('Accepted File Types',"zero-bs-crm");?>:<br /><?php echo esc_html( zeroBS_acceptableFileTypeListStr() ); ?></th> <td><?php echo $html; ?></td></tr> </table> <?php // PerfTest: zeroBSCRM_performanceTest_finishTimer('custmetabox'); // PerfTest: zeroBSCRM_performanceTest_debugOut(); ?> <script type="text/javascript"> jQuery(function(){ }); </script> <?php // PerfTest: zeroBSCRM_performanceTest_finishTimer('other'); } public function save_data( $contact_id, $contact ) { // when multiple custom file boxes, this only needs to fire once :) if (zeroBSCRM_is_customer_edit_page() && !defined('ZBS_CUSTOMFILES_SAVED')){ define('ZBS_CUSTOMFILES_SAVED',1); global $zbsc_justUploadedCustomer,$zbs; $settings = $zbs->settings->get('customfields'); $cfbInd = 1; $cfbsubs = array(); if (isset($settings['customersfiles']) && is_array($settings['customersfiles']) && count($settings['customersfiles']) > 0) foreach ($settings['customersfiles'] as $cfb){ $thisFileSlotName = ''; if (isset($cfb[0])) $thisFileSlotName = $cfb[0]; $filePerma = ''; if (isset($thisFileSlotName) && !empty($thisFileSlotName)) { //$filePerma = strtolower(str_replace(' ','_',str_replace('.','_',substr($thisFileSlotName,0,20)))); $filePerma = $zbs->DAL->makeSlug($thisFileSlotName); } if (!empty($thisFileSlotName) && !empty($filePerma)) $cfbsubs[$filePerma] = $thisFileSlotName; } if (count($cfbsubs) > 0) foreach ($cfbsubs as $cfSubKey => $cfSubName){ /* --- security verification --- */ if (isset($_POST['zbsc_file_attachment_nonce'])) if(!wp_verify_nonce($_POST['zbsc_file_attachment_nonce'], plugin_basename(__FILE__))) { return $contact_id; } // end if if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $contact_id; } // end if /* Switched out for WH Perms model 19/02/16 if('page' == $_POST['post_type']) { if(!current_user_can('edit_page', $contact_id)) { return $contact_id; } // end if } else { if(!current_user_can('edit_page', $contact_id)) { return $contact_id; } // end if } // end if */ if (!zeroBSCRM_permsCustomers()){ return $contact_id; } /* - end security verification - */ if(!empty($_FILES['zbsc_file_'.$cfSubKey]['name']) && (!isset($zbsc_justUploadedCustomer) || (isset($zbsc_justUploadedCustomer) && $zbsc_justUploadedCustomer != $_FILES['zbsc_file_'.$cfSubKey]['name']) ) ) { // Blocking repeat-upload bug $zbsc_justUploadedCustomer = $_FILES['zbsc_file_'.$cfSubKey]['name']; // verify file extension and mime type if ( jpcrm_file_check_mime_extension( $_FILES['zbsc_file_'.$cfSubKey] ) ){ $upload = wp_upload_bits($_FILES['zbsc_file_'.$cfSubKey]['name'], null, file_get_contents($_FILES['zbsc_file_'.$cfSubKey]['tmp_name'])); if ( isset( $upload['error'] ) && $upload['error'] != 0 ) { wp_die('There was an error uploading your file. The error is: ' . esc_html( $upload['error'] ) ); } else { //update_post_meta($contact_id, 'zbsc_file_'.$cfSubKey, $upload); // v2.13 - also privatise the file (move to our asset store) // $upload will have 'file' and 'url' $fileName = basename($upload['file']); $fileDir = dirname($upload['file']); $privateThatFile = zeroBSCRM_privatiseUploadedFile($fileDir,$fileName); if (is_array($privateThatFile) && isset($privateThatFile['file'])){ // successfully moved to our store // modify URL + file attributes $upload['file'] = $privateThatFile['file']; $upload['url'] = $privateThatFile['url']; // add this extra identifier if in privatised sys $upload['priv'] = true; } else { // couldn't move to store, leave in uploaded for now :) } // w mod - adds to array :) $zbsCustomerFiles = zeroBSCRM_getCustomerFiles($contact_id); if (is_array($zbsCustomerFiles)){ //add it $zbsCustomerFiles[] = $upload; } else { // first $zbsCustomerFiles = array($upload); } ///update_post_meta($contact_id, 'zbs_customer_files', $zbsCustomerFiles); zeroBSCRM_updateCustomerFiles($contact_id,$zbsCustomerFiles); // actually got wrappers now :) $zbs->updateMeta(ZBS_TYPE_CONTACT,$contact_id,'cfile_'.$cfSubKey,$upload['file']); // this'll override any prev in that slot, too zeroBSCRM_fileslots_addToSlot($cfSubKey,$upload['file'],$contact_id,ZBS_TYPE_CONTACT,true); // Fire any 'post-upload-processing' (e.g. CPP makes thumbnails of pdf, jpg, etc.) do_action('zbs_post_upload_contact',$upload); } } else { wp_die("The file type that you've uploaded is not an accepted file format."); } } // if file } /// / foreach } return $contact; } } /* ====================================================== / Attach (custom) fileboxes to customer metabox ====================================================== */ /* ====================================================== Attach files to customer metabox ====================================================== */ /* ====================================================== Contact Files Metabox ====================================================== */ /* function zeroBS__addCustomerMetaBoxes() { add_meta_box('zerobs-customer-files', __('Contact Files',"zero-bs-crm"), 'zeroBS__MetaboxFilesOther', 'zerobs_customer', 'normal', 'low'); } add_action('add_meta_boxes', 'zeroBS__addCustomerMetaBoxes'); */ class zeroBS__Metabox_ContactFiles extends zeroBS__Metabox{ public function __construct( $plugin_file ) { $this->objType = 'contact'; $this->metaboxID = 'zerobs-customer-files'; $this->metaboxTitle = __('Other Files',"zero-bs-crm"); $this->metaboxScreen = 'zbs-add-edit-contact-edit'; //'zerobs_edit_contact'; // we can use anything here as is now using our func $this->metaboxArea = 'normal'; $this->metaboxLocation = 'low'; $this->capabilities = array( 'can_hide' => true, // can be hidden 'areas' => array('normal'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => true, // can/can't accept tabs onto it 'can_become_tab' => true, // can be added as tab 'can_minimise' => true // can be minimised ); // call this $this->initMetabox(); } public function html( $contact, $metabox ) { global $zbs; $html = ''; // wmod #} retrieve - shouldn't these vars be "other files"... confusing $zbsFiles = false; if (isset($contact['id'])) $zbsFiles = zeroBSCRM_getCustomerFiles($contact['id']); ?><table class="form-table wh-metatab wptbp" id="wptbpMetaBoxMainItemFiles"> <?php #} Whole file delete method could do with rewrite #} Also sort JS into something usable - should be ajax all this #} Any existing if (is_array($zbsFiles) && count($zbsFiles) > 0){ ?><tr class="wh-large zbsFileDetails"><th class="zbsFilesTitle"><label><?php echo '<span>'.count($zbsFiles).'</span> '.esc_html__('File(s)','zero-bs-crm').':'; ?></label></th> <td id="zbsFileWrapOther"> <table class="ui celled table" id="zbsFilesTable"> <thead> <tr> <th><?php esc_html_e("File", 'zero-bs-crm');?></th> <th class="collapsing center aligned"><?php esc_html_e("Actions", 'zero-bs-crm');?></th> </tr> </thead><tbody> <?php $fileLineIndx = 1; foreach($zbsFiles as $zbsFile){ /* $file = basename($zbsFile['file']); // if in privatised system, ignore first hash in name if (isset($zbsFile['priv'])){ $file = substr($file,strpos($file, '-')+1); } */ $file = zeroBSCRM_files_baseName($zbsFile['file'],isset($zbsFile['priv'])); $fileEditUrl = admin_url('admin.php?page='.$zbs->slugs['editfile']) . "&customer=".$contact['id']."&fileid=" . ($fileLineIndx-1); echo '<tr class="zbsFileLineTR" id="zbsFileLineTRCustomer'. esc_attr( $fileLineIndx ) .'">'; echo '<td><div class="zbsFileLine" id="zbsFileLineCustomer'. esc_attr( $fileLineIndx ) .'"><a href="' . esc_url( $zbsFile['url'] ) . '" target="_blank">' . esc_html( $file ) . '</a></div>'; // if using portal.. state shown/hidden // this is also shown in each file slot :) if you change any of it change that too if(defined('ZBS_CLIENTPRO_TEMPLATES')){ if(isset($zbsFile['portal']) && $zbsFile['portal']){ echo "<p><i class='icon check circle green inverted'></i> ".esc_html__('Shown on Portal','zero-bs-crm').'</p>'; }else{ echo "<p><i class='icon ban inverted red'></i> ".esc_html__('Not shown on Portal','zero-bs-crm').'</p>'; } } echo '</td>'; echo '<td class="collapsing center aligned"><span class="zbsDelFile ui button basic" data-delurl="' . esc_attr( $zbsFile['url'] ) . '"><i class="trash alternate icon"></i> '.esc_html__('Delete','zero-bs-crm').'</span> <a href="' . esc_url( $fileEditUrl) . '" target="_blank" class="ui button basic"><i class="edit icon"></i> '.esc_html__('Edit','zero-bs-crm').'</a></td></tr>'; $fileLineIndx++; } ?> </tbody></table> </td></tr><?php } ?> <?php #adapted from http://code.tutsplus.com/articles/attaching-files-to-your-posts-using-wordpress-custom-meta-boxes-part-1--wp-22291 $html .= '<input type="file" id="zbsc_file_attachment" name="zbsc_file_attachment" size="25" class="zbs-dc">'; ?><tr class="wh-large"><th><label><?php esc_html_e('Add File',"zero-bs-crm");?>:</label><br />(<?php esc_html_e('Optional',"zero-bs-crm");?>)<br /><?php esc_html_e('Accepted File Types',"zero-bs-crm");?>:<br /><?php echo esc_html( zeroBS_acceptableFileTypeListStr() ); ?></th> <td><?php wp_nonce_field(plugin_basename(__FILE__), 'zbsc_file_attachment_nonce'); echo $html; ?></td></tr> </table> <?php // PerfTest: zeroBSCRM_performanceTest_finishTimer('custmetabox'); // PerfTest: zeroBSCRM_performanceTest_debugOut(); ?> <script type="text/javascript"> var zbsCustomerCurrentlyDeleting = false; var zbsMetaboxFilesLang = { 'error': '<?php echo esc_html( zeroBSCRM_slashOut(__('Error','zero-bs-crm')) ); ?>', 'unabletodelete': '<?php echo esc_html( zeroBSCRM_slashOut(__('Unable to delete this file.','zero-bs-crm')) ); ?>' }; jQuery(function(){ jQuery('.zbsDelFile').on( 'click', function(){ if (!window.zbsCustomerCurrentlyDeleting){ // blocking window.zbsCustomerCurrentlyDeleting = true; var delUrl = jQuery(this).attr('data-delurl'); //var lineIDtoRemove = jQuery(this).closest('.zbsFileLine').attr('id'); var lineToRemove = jQuery(this).closest('tr'); if (typeof delUrl != "undefined" && delUrl != ''){ // postbag! var data = { 'action': 'delFile', 'zbsfType': 'customer', 'zbsDel': delUrl, // could be csv, never used though 'zbsCID': <?php if (!empty($contact['id']) && $contact['id'] > 0) echo esc_html( $contact['id'] ); else echo -1; ?>, 'sec': window.zbscrmjs_secToken }; // Send it Pat :D jQuery.ajax({ type: "POST", url: ajaxurl, // admin side is just ajaxurl not wptbpAJAX.ajaxurl, "data": data, dataType: 'json', timeout: 20000, success: function(response) { var localLineToRemove = lineToRemove, localDelURL = delUrl; // visually remove jQuery(localLineToRemove).remove(); // update number var newNumber = jQuery('#zbsFilesTable tr').length-1; if (newNumber > 0) jQuery('#wptbpMetaBoxMainItemFiles .zbsFilesTitle span').html(); else jQuery('#wptbpMetaBoxMainItemFiles .zbsFileDetails').remove(); // remove any filled slots (with this file) jQuery('.zbsFileSlotTable').each(function(ind,ele){ if (jQuery(ele).attr('data-sloturl') == localDelURL){ jQuery('.zbsFileSlotWrap',jQuery(ele)).remove(); } }); // file deletion errors, show msg: if (typeof response.errors != "undefined" && response.errors.length > 0){ jQuery.each(response.errors,function(ind,ele){ jQuery('#zerobs-customer-files-box').append('<div class="ui warning message" style="margin-top:10px;">' + ele + '</div>'); }); } }, error: function(response){ jQuery('#zerobs-customer-files-box').append('<div class="ui warning message" style="margin-top:10px;"><strong>' + window.zbsMetaboxFilesLang.error + ':</strong> ' + window.zbsMetaboxFilesLang.unabletodelete + '</div>'); } }); } window.zbsCustomerCurrentlyDeleting = false; } // / blocking }); }); </script><?php // PerfTest: zeroBSCRM_performanceTest_finishTimer('other'); } public function save_data( $contact_id, $contact ) { global $zbsc_justUploadedCustomer; if(!empty($_FILES['zbsc_file_attachment']['name']) && (!isset($zbsc_justUploadedCustomer) || (isset($zbsc_justUploadedCustomer) && $zbsc_justUploadedCustomer != $_FILES['zbsc_file_attachment']['name']) ) ) { /* --- security verification --- */ if(!wp_verify_nonce($_POST['zbsc_file_attachment_nonce'], plugin_basename(__FILE__))) { return $id; } // end if if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $id; } // end if /* Switched out for WH Perms model 19/02/16 if('page' == $_POST['post_type']) { if(!current_user_can('edit_page', $id)) { return $id; } // end if } else { if(!current_user_can('edit_page', $id)) { return $id; } // end if } // end if */ if (!zeroBSCRM_permsCustomers()){ return $contact_id; } /* - end security verification - */ // Blocking repeat-upload bug $zbsc_justUploadedCustomer = $_FILES['zbsc_file_attachment']['name']; // verify file extension and mime type if ( jpcrm_file_check_mime_extension( $_FILES['zbsc_file_attachment'] ) ){ $upload = wp_upload_bits($_FILES['zbsc_file_attachment']['name'], null, file_get_contents($_FILES['zbsc_file_attachment']['tmp_name'])); if ( isset( $upload['error'] ) && $upload['error'] != 0 ) { wp_die('There was an error uploading your file. The error is: ' . esc_html( $upload['error'] ) ); } else { //update_post_meta($id, 'zbsc_file_attachment', $upload); // v2.13 - also privatise the file (move to our asset store) // $upload will have 'file' and 'url' $fileName = basename($upload['file']); $fileDir = dirname($upload['file']); $privateThatFile = zeroBSCRM_privatiseUploadedFile($fileDir,$fileName); if (is_array($privateThatFile) && isset($privateThatFile['file'])){ // successfully moved to our store // modify URL + file attributes $upload['file'] = $privateThatFile['file']; $upload['url'] = $privateThatFile['url']; // add this extra identifier if in privatised sys $upload['priv'] = true; } else { // couldn't move to store, leave in uploaded for now :) } // w mod - adds to array :) $zbsCustomerFiles = zeroBSCRM_getCustomerFiles($contact_id); if (is_array($zbsCustomerFiles)){ //add it $zbsCustomerFiles[] = $upload; } else { // first $zbsCustomerFiles = array($upload); } ///update_post_meta($id, 'zbs_customer_files', $zbsCustomerFiles); zeroBSCRM_updateCustomerFiles($contact_id,$zbsCustomerFiles); // Fire any 'post-upload-processing' (e.g. CPP makes thumbnails of pdf, jpg, etc.) do_action('zbs_post_upload_contact',$upload); } } else { wp_die("The file type that you've uploaded is not an accepted file format."); } } return $contact; } } /* ====================================================== / Attach files to customer metabox ====================================================== */ /* ====================================================== Create Client Portal ====================================================== */ class zeroBS__Metabox_ContactPortal extends zeroBS__Metabox{ public function __construct( $plugin_file, $metabox_screen = 'zbs-add-edit-contact-edit' ) { $this->objType = 'contact'; $this->metaboxID = 'zerobs-customer-portal'; $this->metaboxTitle = __('Client Portal',"zero-bs-crm"); $this->metaboxScreen = $metabox_screen; // we can use anything here as is now using our func $this->metaboxArea = 'side'; $this->metaboxLocation = 'high'; $this->capabilities = array( 'can_hide' => true, // can be hidden 'areas' => array('side'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => false, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true // can be minimised ); // call this $this->initMetabox(); } public function html( $contact, $metabox ) { // PerfTest: zeroBSCRM_performanceTest_startTimer('portal-draw'); global $plugin_page, $zbs; $screen = get_current_screen(); $wp_user_id = ''; #} Rather than reload all the time :) global $zbsContactEditing; #} retrieve //$zbsCustomer = get_post_meta($contact['id'], 'zbs_customer_meta', true); if (!isset($zbsContactEditing) && isset($contact['id'])){ $zbsCustomer = zeroBS_getCustomer($contact['id'],false,false,false); $zbsContactEditing = $zbsCustomer; } else { $zbsCustomer = $zbsContactEditing; } if ( isset($zbsCustomer) && is_array($zbsCustomer) && isset($zbsCustomer['email']) ){ //check customer link to see if it exists - wh moved to dal $wp_user_id = zeroBSCRM_getClientPortalUserID( $contact['id'] ); /* nope if($wp_user_id == ''){ $wp_user_id = email_exists( $zbsCustomer['email'] ); } */ } echo '<div class="waiting-togen">'; // get user obj $user_object = get_userdata( $wp_user_id ); if ( $user_object ){ // a user already exists with this email echo '<div class="zbs-customerportal-activeuser">'; esc_html_e('WordPress User Linked',"zero-bs-crm"); echo ' #<span class="zbs-user-id">'. esc_html( $wp_user_id ) .'</span>:<br />'; echo '<span class="ui label">'. esc_html( $user_object->user_email ) .'</span>'; // wp admins get link if ( zeroBSCRM_isWPAdmin() ){ $url = admin_url('user-edit.php?user_id='.$wp_user_id); echo '<br /><a style="font-size: 12px;color:black;font-weight:600;" href="' . esc_url( $url ) . '" target="_blank"><i class="wordpress simple icon"></i> ' . esc_html__( 'View WordPress Profile', 'zero-bs-crm' ) . '</a>'; // phpcs:ignore WordPress.WP.CapitalPDangit.MisspelledInText } echo '</div>'; // user ID will now have access to this area.. echo '<hr /><div class="zbs-customerportal-activeuser-actions">'; echo esc_html( __( 'Client Portal Access:', 'zero-bs-crm' ) ); $customerPortalActive = true; if (zeroBSCRM_isCustomerPortalDisabled($contact['id'])) $customerPortalActive = false; if ( $customerPortalActive ) { // revoke/disable access echo ' <span class="ui green empty circular label"></span> <span class="zbs-portal-label">' . esc_html( __( 'Enabled', 'zero-bs-crm' ) ) . '</span>'; // wp admins get reset link, unless the crm contact is assigned to any other role than CRM Customer if ( zeroBSCRM_isWPAdmin() && jpcrm_role_check( $user_object, array(), array(), array( 'zerobs_customer' ) ) ) { echo '<div id="zbs-customerportal-access-actions" class="zbs-customerportal-activeuser">'; echo '<button type="button" id="zbs-customerportal-resetpw" class="ui mini button white">' . esc_html( __( 'Reset Password', 'zero-bs-crm' ) ) . '</button>'; echo '<button type="button" id="zbs-customerportal-toggle" data-zbsportalaction="disable" class="ui mini button white negative">' . esc_html( __( 'Disable Access', 'zero-bs-crm' ) ) . '</button>'; echo '</div>'; } else { // explainer - rarely shown echo '<p style="font-size: 0.9em;margin-top: 0.5em;">' . esc_html__( 'The WordPress user has a role other than CRM Contact. They will need to reset their password via the WP login page.', 'zero-bs-crm' ) . '</p>'; } echo '<hr /><div class="zbs-customerportal-activeuser-actions">'; printf( '<a target="_blank" href="%s" class="ui mini button white">%s</a>', esc_url( zeroBS_portal_link() ), esc_html( __( 'Preview Portal', 'zero-bs-crm' ) ) ); echo '</div>'; } else { // enable access echo ' <span class="ui red empty circular label"></span> <span class="zbs-portal-label">' . esc_html( __( 'Disabled', 'zero-bs-crm' ) ) . '</span>'; // wp admins get enable link, unless the crm contact is assigned to any other role than CRM Customer if ( zeroBSCRM_isWPAdmin() && jpcrm_role_check( $user_object, array(), array(), array( 'zerobs_customer' ) ) ) { echo '<div id="zbs-customerportal-access-actions">'; echo '<button type="button" id="zbs-customerportal-toggle" data-zbsportalaction="enable" class="ui mini button positive">' . esc_html( __( 'Enable Access', 'zero-bs-crm' ) ) . '</button>'; echo '</div>'; } } echo '<input type="hidden" id="zbsportalaction-ajax-nonce" value="' . esc_attr( wp_create_nonce( 'zbsportalaction-ajax-nonce' ) ) . '" />'; echo '</div>'; } else if ( is_array($zbsCustomer) && isset($zbsCustomer['email']) && !empty($zbsCustomer['email'])){ echo '<div class="no-gen" style="text-align:center">'; echo esc_html( __( 'No WordPress User exists with this email', 'zero-bs-crm' ) ); echo '<br/><br/>'; echo '<div class="ui primary black button button-primary wp-user-generate">'; echo esc_html( __( 'Generate WordPress User', 'zero-bs-crm' ) ); echo '</div>'; echo '<input type="hidden" name="newwp-ajax-nonce" id="newwp-ajax-nonce" value="' . esc_attr( wp_create_nonce( 'newwp-ajax-nonce' ) ) . '" />'; echo '</div>'; }else{ echo esc_html( __( 'Save your contact, or add an email to enable Client Portal functionality', 'zero-bs-crm' ) ); } echo '</div>'; ?><script type="text/javascript"> jQuery(function(){ // bind activate/deactivate jQuery('#zbs-customerportal-toggle').off("click").on('click',function(e){ // action var action = jQuery(this).attr('data-zbsportalaction'); // fire ajax var t = { action: "zbsPortalAction", portalAction: action, cid: <?php if (!empty($contact['id']) && $contact['id'] > 0) echo esc_html( $contact['id'] ); else echo -1; ?>, security: jQuery( '#zbsportalaction-ajax-nonce' ).val() } i = jQuery.ajax({ url: ajaxurl, type: "POST", data: t, dataType: "json" }); i.done(function(e) { //console.log(e); if(typeof e.success != "undefined"){ // localise var cAction = action; if (action == 'enable'){ // switch label jQuery('.ui.circular.label',jQuery('.zbs-customerportal-activeuser-actions')).removeClass('red').addClass('green'); jQuery('.zbs-portal-label',jQuery('.zbs-customerportal-activeuser-actions')).html('<?php echo esc_html( __( 'Enabled', 'zero-bs-crm' ) ); ?>'); jQuery('#zbs-customerportal-toggle').removeClass('positive').addClass('negative').html('<?php echo esc_html( __( 'Disable Access', 'zero-bs-crm' ) ); ?>').attr('data-zbsportalaction','disable'); } else if (action == 'disable'){ // switch label jQuery('.ui.circular.label',jQuery('.zbs-customerportal-activeuser-actions')).addClass('red').removeClass('green'); jQuery('.zbs-portal-label',jQuery('.zbs-customerportal-activeuser-actions')).html('<?php echo esc_html( __( 'Disabled', 'zero-bs-crm' ) ); ?>'); jQuery('#zbs-customerportal-toggle').removeClass('negative').addClass('positive').html('<?php echo esc_html( __( 'Enable Access', 'zero-bs-crm' ) ); ?>').attr('data-zbsportalaction','enable'); } } }), i.fail(function(e) { //error }); }); // bind reset pw jQuery('#zbs-customerportal-resetpw').off("click").on('click',function(e){ // fire ajax var t = { action: "zbsPortalAction", portalAction: 'resetpw', cid: <?php if (!empty($contact['id']) && $contact['id'] > 0) echo esc_html( $contact['id'] ); else echo -1; ?>, security: jQuery( '#zbsportalaction-ajax-nonce' ).val() } i = jQuery.ajax({ url: ajaxurl, type: "POST", data: t, dataType: "json" }); i.done(function(e) { //console.log(e); if(typeof e.success != "undefined"){ var newPassword = '<?php zeroBSCRM_slashOut(esc_html__('Unknown',"zero-bs-crm")); ?>'; if (typeof e.pw != "undefined") newPassword = e.pw; if ( newPassword !== false ){ // swal confirm swal( '<?php zeroBSCRM_slashOut(esc_html__('Client Portal Password Reset',"zero-bs-crm")); ?>', '<?php zeroBSCRM_slashOut(esc_html__('Client Portal password has been reset for this contact, and they have been emailed with the new password. The new password is:',"zero-bs-crm")); ?><br /><span class="ui label">' + newPassword + '</span>', 'info' ); } else { // swal confirm swal( '<?php zeroBSCRM_slashOut(esc_html__('Client Portal Password Reset Error',"zero-bs-crm")); ?>', '<?php zeroBSCRM_slashOut(esc_html__('Error: Client Portal password has not been reset for this contact.',"zero-bs-crm")); ?>', 'info' ); } } }), i.fail(function(e) { //error }); }); // bind create jQuery('.wp-user-generate').off("click").on('click',function(e){ email = jQuery('#email').val(); customerid = <?php if (!empty($contact['id']) && $contact['id'] > 0) echo esc_html( $contact['id'] ); else echo -1; ?>; if(email == ''){ alert("The email field is blank. Please fill in the email and save"); return false; } var t = { action: "zbs_new_user", email: email, cid: customerid, security: jQuery( '#newwp-ajax-nonce' ).val(), } i = jQuery.ajax({ url: ajaxurl, type: "POST", data: t, dataType: "json" }); i.done(function(e) { console.log(e); if(e.success){ jQuery('.zbs-user-id').html(e.user_id); jQuery('.no-gen').remove(); jQuery('.waiting-togen').html('<div class="alert alert-success">Success: ' + e.message + '</div>'); } else { jQuery('.no-gen').remove(); jQuery('.waiting-togen').html('<div class="alert alert-danger">Error: ' + e.message + '</div>'); } }), i.fail(function(e) { //error }); }); }); </script><?php // PerfTest: zeroBSCRM_performanceTest_finishTimer('portal-draw'); // PerfTest: zeroBSCRM_performanceTest_finishTimer('portal'); } } /* ====================================================== / Create Client Portal ====================================================== */ /* ====================================================== Create Social Box ====================================================== */ class zeroBS__Metabox_ContactSocial extends zeroBS__Metabox{ public function __construct( $plugin_file ) { $this->objType = 'contact'; $this->metaboxID = 'zerobs-customer-social'; $this->metaboxTitle = __('Social Profiles',"zero-bs-crm"); $this->metaboxScreen = 'zbs-add-edit-contact-edit'; //'zerobs_edit_contact'; // we can use anything here as is now using our func $this->metaboxArea = 'side'; $this->metaboxLocation = 'high'; $this->capabilities = array( 'can_hide' => true, // can be hidden 'areas' => array('side'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => false, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true // can be minimised ); // call this $this->initMetabox(); } public function html( $contact, $metabox ) { global $plugin_page, $zbs; // declare + load existing global $zbsSocialAccountTypes; $zbsSocials = false; if (isset($contact['id'])) $zbsSocials = zeroBS_getCustomerSocialAccounts($contact['id']); if (count($zbsSocialAccountTypes) > 0) foreach ($zbsSocialAccountTypes as $socialKey => $socialAccType){ ?><div class="zbs-social-acc <?php echo esc_attr( $socialAccType['slug'] ); ?>" title="<?php echo esc_attr( $socialAccType['name'] ); ?>"> <?php if (is_array($zbsSocials) && isset($zbsSocials[$socialKey]) && !empty($zbsSocials[$socialKey])){ // got acc? link to it $socialLink = zeroBSCRM_getSocialLink( $socialKey, $zbsSocials ); ?> <a href="<?php echo esc_url( $socialLink ); ?>" target="_blank" title="<?php echo esc_attr__('View',"zero-bs-crm") . ' ' . esc_attr( $socialAccType['name'] ); ?>"><i class="fa <?php echo esc_attr( $socialAccType['fa'] ); ?>" aria-hidden="true"></i></a> <?php } else { ?> <i class="fa <?php echo esc_attr( $socialAccType['fa'] ); ?>" aria-hidden="true"></i> <?php } ?> <input type="text" class="zbs-social-acc-input zbs-dc" title="<?php echo esc_attr( $socialAccType['name'] ); ?>" name="zbs-social-<?php echo esc_attr( $socialAccType['slug'] ); ?>" id="zbs-social-<?php echo esc_attr( $socialAccType['slug'] ); ?>" value="<?php if (is_array($zbsSocials) && isset($zbsSocials[$socialKey]) && !empty($zbsSocials[$socialKey])) echo esc_attr( $zbsSocials[$socialKey] ); ?>" placeholder="<?php echo esc_attr( $socialAccType['placeholder'] ); ?>" /> </div><?php } // ++ get counts etc. } public function save_data( $contact_id, $contact ) { $zbsSocials = array(); global $zbsSocialAccountTypes; foreach ($zbsSocialAccountTypes as $socialKey => $socialAccType){ // set $zbsSocials[$socialKey] = false; // get from post if present if (isset($_POST['zbs-social-'.$socialAccType['slug']]) && !empty($_POST['zbs-social-'.$socialAccType['slug']])) $zbsSocials[$socialKey] = sanitize_text_field($_POST['zbs-social-'.$socialAccType['slug']]); } zeroBS_updateCustomerSocialAccounts($contact_id,$zbsSocials); return $contact; } } /* ====================================================== / Create Social Box ====================================================== */ /* ====================================================== Create AKA Box ====================================================== */ class zeroBS__Metabox_ContactAKA extends zeroBS__Metabox{ public function __construct( $plugin_file ) { $this->objType = 'contact'; $this->metaboxID = 'zerobs-customer-aka'; $this->metaboxTitle = __('Contact Aliases (AKA)',"zero-bs-crm"); $this->metaboxScreen = 'zbs-add-edit-contact-edit'; //'zerobs_edit_contact'; // we can use anything here as is now using our func $this->metaboxArea = 'side'; $this->metaboxLocation = 'low'; $this->capabilities = array( 'can_hide' => true, // can be hidden 'areas' => array('side'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => false, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true // can be minimised ); // call this $this->initMetabox(); } public function html( $contact, $metabox ) { global $plugin_page, $zbs; $screen = get_current_screen(); ?> <div class="ui active inverted dimmer" style="display:none" id="zbs-aka-alias-loader"></div> <?php #} Rather than reload all the time :) global $zbsContactEditing; #} retrieve //$zbsCustomer = get_post_meta($contact['id'], 'zbs_customer_meta', true); if (!isset($zbsContactEditing) && isset($contact['id'])){ $zbsCustomer = zeroBS_getCustomer($contact['id'],false,false,false); $zbsContactEditing = $zbsCustomer; } else { $zbsCustomer = $zbsContactEditing; } if (gettype($zbsCustomer) != "array"){ // new cust, can't add till saved. ?><div class="ui message"><?php esc_html_e('You will not be able to add an alias until you\'ve saved this contact',"zero-bs-crm"); ?></div><?php } else { // customer saved, so proceed - aka mode // declare + load existing $customerAliases = zeroBS_getCustomerAliases($contact['id']); ?><div id="zbs-aka-alias-wrap"><?php // each alias: ID,aka_alias,aka_create,aka_lastupdated if (is_array($customerAliases) && count($customerAliases) > 0) foreach ($customerAliases as $alias){ ?><div class="zbs-aka-alias" id="zbs-aka-alias-<?php echo esc_attr( $alias['ID'] ); ?>"> <div class="ui label"><?php echo esc_html( $alias['aka_alias'] ); ?> <button type="button" class="ui mini icon button negative zbs-aka-alias-remove" data-akaid="<?php echo esc_attr( $alias['ID'] ); ?>" title="<?php esc_attr_e('Remove Alias',"zero-bs-crm"); ?>"><i class="icon remove"></i></button></div> </div><?php } ?></div><?php ?><div id="zbs-aka-alias-input-wrap"> <input type="text" class="zbs-aka-alias-input" placeholder="<?php esc_attr_e('Add Alias.. e.g.', 'zero-bs-crm'); ?> mike2@domain.com" /> <div class="ui pointing label" style="display:none;margin-bottom: 1em;margin-top: 0;" id="zbs-aka-alias-input-msg"><?php esc_html_e('Must be a valid email','zero-bs-crm'); ?></div> <button type="button" class="ui small black button primary" id="zbs-aka-alias-add"><?php esc_html_e( 'Add Alias', 'zero-bs-crm' ); ?></button> </div> <script type="text/javascript"> var zbsAliasAKABlocker = false; jQuery(function(){ jQuery('.zbs-aka-alias-input').on( 'keydown', function(){ // hide 'must be valid email' jQuery('#zbs-aka-alias-input-msg').hide(); }); jQuery('#zbs-aka-alias-add').off('click').on( 'click', function(){ var v = jQuery('.zbs-aka-alias-input').val(); if ( typeof v === 'string' ) { v = v.trim(); } // lazy check for now if (v != "" && zbscrm_JS_validateEmail(v)){ // blocker if (!window.zbsAliasAKABlocker){ // block window.zbsAliasAKABlocker = true; jQuery('#zbs-aka-alias-loader').show(); // postbag! var data = { 'action': 'addAlias', 'cid': <?php if (!empty($contact['id']) && $contact['id'] > 0) echo esc_html( $contact['id'] ); else echo -1; ?>, 'aka': v, 'sec': window.zbscrmjs_secToken }; // Send it Pat :D jQuery.ajax({ type: "POST", url: ajaxurl, // admin side is just ajaxurl not wptbpAJAX.ajaxurl, "data": data, dataType: 'json', timeout: 20000, success: function(response) { if (typeof response.res != "undefined"){ //console.log('added:',response); var id = response.res; var alias = v; var lineHTML = '<div class="zbs-aka-alias" id="zbs-aka-alias-' + id + '"><div class="ui label">' + alias + ' <button type="button" class=" ui mini icon button negative zbs-aka-alias-remove" data-akaid="' + id + '""><i class="icon remove"></i></button></div></div>'; // add to ui jQuery('#zbs-aka-alias-wrap').append(lineHTML); // empty this jQuery('.zbs-aka-alias-input').val(''); // bind setTimeout(function(){ zeroBSJS_bindAKAMode(); },0); //unblock window.zbsAliasAKABlocker = false; jQuery('#zbs-aka-alias-loader').hide(); } else { if (typeof response.fail != "undefined"){ if (response.fail == 'existing'){ // already in use err swal( '<?php esc_html_e('Error',"zero-bs-crm"); ?>', '<?php esc_html_e('This Alias is already in use by another contact.',"zero-bs-crm"); ?>', 'warning' ); } } else { // general err swal( '<?php esc_html_e('Error',"zero-bs-crm"); ?>', '<?php esc_html_e('There was an error adding this alias',"zero-bs-crm"); ?>', 'warning' ); } //unblock window.zbsAliasAKABlocker = false; jQuery('#zbs-aka-alias-loader').hide(); } }, error: function(response){ // err swal( '<?php esc_html_e('Error',"zero-bs-crm"); ?>', '<?php esc_html_e('There was an error adding this alias',"zero-bs-crm"); ?>', 'warning' ); //unblock window.zbsAliasAKABlocker = false; jQuery('#zbs-aka-alias-loader').hide(); } }); } // / blocker } // / if not empty else { // not valid email, showxxx jQuery('#zbs-aka-alias-input-msg').show(); // hide after 2s setTimeout(function(){ jQuery('#zbs-aka-alias-input-msg').hide(); },2000); } }); // other bind zeroBSJS_bindAKAMode(); }); function zeroBSJS_bindAKAMode(){ // hover over jQuery('.zbs-aka-alias').on( 'mouseenter', function () { jQuery(this).addClass("hovering"); }).on( 'mouseleave', function () { jQuery(this).removeClass("hovering"); }); // remoe aka jQuery('.zbs-aka-alias-remove').off('click').on( 'click', function(){ // blocker if (!window.zbsAliasAKABlocker){ // block window.zbsAliasAKABlocker = true; jQuery('#zbs-aka-alias-loader').show(); // get id var akaID = jQuery(this).attr('data-akaid'); if (akaID > 0){ // postbag! var data = { 'action': 'removeAlias', 'cid': <?php if (!empty($contact['id']) && $contact['id'] > 0) echo esc_html( $contact['id'] ); else echo -1; ?>, 'akaid': akaID, 'sec': window.zbscrmjs_secToken }; // Send it Pat :D jQuery.ajax({ type: "POST", url: ajaxurl, // admin side is just ajaxurl not wptbpAJAX.ajaxurl, "data": data, dataType: 'json', timeout: 20000, success: function(response) { if (typeof response.res != "undefined"){ console.log('removed:',response); var lID = akaID; // remove from ui jQuery('#zbs-aka-alias-' + lID).remove(); //unblock window.zbsAliasAKABlocker = false; jQuery('#zbs-aka-alias-loader').hide(); } else { // err swal( '<?php esc_html_e('Error',"zero-bs-crm"); ?>', '<?php esc_html_e('There was an error removing this alias',"zero-bs-crm"); ?>', 'warning' ); //unblock window.zbsAliasAKABlocker = false; jQuery('#zbs-aka-alias-loader').hide(); } }, error: function(response){ // err swal( '<?php esc_html_e('Error',"zero-bs-crm"); ?>', '<?php esc_html_e('There was an error removing this alias',"zero-bs-crm"); ?>', 'warning' ); //unblock window.zbsAliasAKABlocker = false; jQuery('#zbs-aka-alias-loader').hide(); } }); } // / akai id present } }); } </script> <?php } // / if cust defined } } /* ====================================================== / Create AKA Box ====================================================== */ /* ====================================================== Create Tags Box ====================================================== */ class zeroBS__Metabox_ContactTags extends zeroBS__Metabox_Tags{ public function __construct( $plugin_file ) { $this->objTypeID = ZBS_TYPE_CONTACT; $this->objType = 'contact'; $this->metaboxID = 'zerobs-customer-tags'; $this->metaboxTitle = __('Contact Tags',"zero-bs-crm"); $this->metaboxScreen = 'zbs-add-edit-contact-edit'; //'zerobs_edit_contact'; // we can use anything here as is now using our func $this->metaboxArea = 'side'; $this->metaboxLocation = 'high'; $this->showSuggestions = true; $this->capabilities = array( 'can_hide' => true, // can be hidden 'areas' => array('side'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => false, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true // can be minimised ); // call this $this->initMetabox(); } // html + save dealt with by parent class :) } /* ====================================================== / Create Tags Box ====================================================== */ /* ====================================================== Create Logs Box ====================================================== */ class zeroBS__Metabox_ContactLogs extends zeroBS__Metabox_LogsV2{ public function __construct( $plugin_file ) { $this->objtypeid = ZBS_TYPE_CONTACT; $this->objType = 'contact'; $this->metaboxID = 'zerobs-customer-logs'; $this->metaboxTitle = __('Activity Log',"zero-bs-crm"); $this->metaboxScreen = 'zbs-add-edit-contact-edit'; //'zerobs_edit_contact'; // we can use anything here as is now using our func $this->metaboxArea = 'normal'; $this->metaboxLocation = 'high'; $this->capabilities = array( 'can_hide' => true, // can be hidden 'areas' => array('normal'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => true, // can/can't accept tabs onto it 'can_become_tab' => true, // can be added as tab 'can_minimise' => true, // can be minimised 'hide_on_new' => true // no point in adding logs while adding contact, add after creation :) ); // call this $this->initMetabox(); } // html + save dealt with by parent class :) } /* ====================================================== / Create Logs Box ====================================================== */ /* ====================================================== "Contacts at Company" Metabox ====================================================== */ class zeroBS__Metabox_ContactCompany extends zeroBS__Metabox{ public function __construct( $plugin_file ) { # (language switch) $companyOrOrg = zeroBSCRM_getSetting('coororg'); $companyLabel = jpcrm_label_company(); $this->objType = 'contact'; $this->metaboxID = 'zerobs-customer-company'; $this->metaboxTitle = __($companyLabel, "zero-bs-crm"); $this->metaboxScreen = 'zbs-add-edit-contact-edit'; //'zerobs_edit_contact'; // we can use anything here as is now using our func $this->metaboxArea = 'side'; $this->metaboxLocation = 'core'; $this->capabilities = array( 'can_hide' => true, // can be hidden 'areas' => array('side'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => false, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true // can be minimised ); // call this $this->initMetabox(); } public function html( $contact, $metabox ) { global $plugin_page, $zbs; // PerfTest: zeroBSCRM_performanceTest_startTimer('companydropdown'); # (language switch) $companyOrOrg = zeroBSCRM_getSetting('coororg'); $companyLabel = jpcrm_label_company(); #} Typeahead instead echo "<div id='zbscompnew'>"; echo "<span>" . esc_html( sprintf( __( 'Type to assign %s', 'zero-bs-crm' ), jpcrm_label_company() ) ) . '</span>'; #} Co Name Default $coName = ''; $coID = ''; if ( 'contact' == $this->objType ){ $coID = -1; if (is_array($contact) && isset($contact['id'])) $coID = zeroBS_getCustomerCompanyID($contact['id']); if (!empty($coID)){ $co = zeroBS_getCompany($coID); // 3.0 if (isset($co) && isset($co['name'])) $coName = $co['name']; // < 3.0 if (isset($co) && isset($co['meta']) && isset($co['meta']['coname'])) $coName = $co['meta']['coname']; if (empty($coName) && isset($co['coname'])) $coName = $co['coname']; } } #} Output if ( get_option('permalink_structure') == '' ){ echo "<div class='ui message red'>" . esc_html__('You are using Plain Permalinks. Please set your permalinks to %postname% by visiting ','zero-bs-crm') . "<a href='" . esc_url( admin_url('options-permalink.php') )."'>".esc_html__('here','zero-bs-crm')."</a></div>"; }else{ echo zeroBSCRM_CompanyTypeList('zbscrmjs_customer_setCompany',$coName,true,'zbscrmjs_customer_changedCompany'); } #} Hidden input (real input) & Callback func ?><input type="hidden" name="zbs_company" id="zbs_company" value="<?php echo esc_attr( $coID ); ?>" /> <script type="text/javascript"> // custom fuction to copy company details from typeahead company deets function zbscrmjs_customer_setCompany(obj){ if (typeof obj.id != "undefined"){ // set vals jQuery("#zbs_company").val(obj.id); // set dirty zbscrm_JS_addDirty('zbs-company'); } } // custom fuction to copy company details from typeahead company deets // this one fires on any change, but here we're just using to catch empties :) // in fact, this one now overrides above^ function zbscrmjs_customer_changedCompany(newval){ if (typeof newval == "undefined" || newval == ''){ // set vals jQuery("#zbs_company").val(''); // set dirty zbscrm_JS_addDirty('zbs-company'); } } </script> </div><?php // PerfTest: zeroBSCRM_performanceTest_finishTimer('companydropdown'); } public function save_data( $contact_id, $contact ) { return $contact; } } /* DEPRECATED! */ function zbsCustomer_companyDropdown( $default = '', $companies = array() ) { echo 'zbsCustomer_companyDropdown is Deprecated!<br />'; foreach ($companies as $co){ echo "\n\t" . '<option value="'. esc_attr( $co['id'] ) .'"'; if ($co['id'] == $default) echo ' selected="selected"'; //echo '>'.$co['meta']['coname'].'</option>'; $coName = ''; if (isset($co) && isset($co['meta']) && isset($co['meta']['coname'])) $coName = $co['meta']['coname']; # Shouldn't need this? WH attempted fix for caching, not here tho.. if (empty($coName) && isset($co['coname'])) $coName = $co['coname']; if (empty($coName)) $coName = jpcrm_label_company().' #'.$co['id']; echo '>'. esc_html( $coName ) .'</option>'; } } /* ====================================================== / "Contacts at Company" Metabox Related Funcs ====================================================== */ /* ====================================================== Contact Activity Metabox ====================================================== */ class zeroBS__Metabox_Contact_Activity extends zeroBS__Metabox { public function __construct( $plugin_file ) { $this->metaboxID = 'zbs-contact-activity-metabox'; $this->metaboxTitle = __('Activity', 'zero-bs-crm'); $this->metaboxIcon = 'heartbeat'; $this->metaboxScreen = 'zbs-view-contact'; // we can use anything here as is now using our func $this->metaboxArea = 'side'; $this->metaboxLocation = 'high'; // call this $this->initMetabox(); } public function html( $obj, $metabox ) { global $zbs, $zeroBSCRM_logTypes; $objid = -1; if (is_array($obj) && isset($obj['id'])) $objid = $obj['id']; // output any pinned logs $pinned_logs = $zbs->DAL->logs->getLogsForObj(array( 'objtype' => ZBS_TYPE_CONTACT, 'objid' => $objid, 'only_pinned' => true, 'incMeta' => true, 'sortByField' => 'zbsl_created', 'sortOrder' => 'DESC', 'page' => -1, 'perPage' => -1, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership( ZBS_TYPE_CONTACT ) )); if ( is_array( $pinned_logs ) && count( $pinned_logs ) > 0 ){ $pinned_log_count = 0; echo '<h4 style="text-align:right" class="ui top attached header" id="jpcrm-pinned-logs-header">' . esc_attr__( 'Pinned Logs', 'zero-bs-crm' ) . '</h4>'; echo '<div class="jpcrm-pinned-logs ui green attached segment">'; foreach ( $pinned_logs as $log ){ if (is_array($log) && isset($log['created'])){ if ( $pinned_log_count > 0 ){ ?><div class="ui divider"></div><?php } echo '<div class="jpcrm-pinned-log">'; // ico? $ico = ''; $logKey = strtolower(str_replace(' ','_',str_replace(':','_',$log['type']))); if (isset($zeroBSCRM_logTypes['zerobs_customer'][$logKey])) $ico = $zeroBSCRM_logTypes['zerobs_customer'][$logKey]['ico']; // these are FA ico's at this point // compile this first, so can catch default (empty types) $logTitle = ''; if (!empty($ico)) $logTitle .= '<i class="fa '.$ico.'"></i> '; // DAL 2 saves type as permalinked if (isset($zeroBSCRM_logTypes['zerobs_customer'][$logKey])) $logTitle .= __($zeroBSCRM_logTypes['zerobs_customer'][$logKey]['label'],"zero-bs-crm"); ?> <?php // short desc if (isset($log['shortdesc']) && !empty($log['shortdesc'])){ ?> <h4 class="jpcrm-pinned-log-shortdesc"> <?php echo $logTitle . ' | ' . esc_html( $log['shortdesc'] ); ?> </h4> <?php } ?> <?php // long desc if (isset($log['longdesc']) && !empty($log['longdesc'])){ ?> <div class="jpcrm-pinned-log-longdesc"> <?php echo wp_kses( html_entity_decode( $log['longdesc'], ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 ), $zbs->acceptable_restricted_html ); ?> </div> <?php } ?> <div class="jpcrm-pinned-log-author-date-meta"> <?php $meta_string = ''; if ( !empty( $log['author'] ) ) { $meta_string = $log['author']; } if ( !empty($log['createduts'] ) && $log['createduts'] > 0 ) { if ( !empty( $meta_string ) ){ $meta_string .= ' &mdash; '; } $meta_string .= jpcrm_uts_to_date_str( $log['createduts'] ); } echo esc_html( $meta_string ); ?></div> </div><?php $pinned_log_count++; } } ?></div><?php } // normal activity output echo '<div class="zbs-activity">'; echo '<div class="">'; $zbsCustomerActivity = zeroBSCRM_getContactLogs($objid,true,100,0,'',false); zeroBSCRM_html_contactTimeline($objid,$zbsCustomerActivity,$obj); echo '</div>'; echo '</div>'; } // nothing to save here. public function save_data( $objID, $obj ) { return $obj; } } /* ====================================================== / Contact Activity Metabox ====================================================== */
projects/plugins/crm/includes/ZeroBSCRM.DAL3.Export.php
<?php /* ! * Jetpack CRM * https://jetpackcrm.com * V3.0 * * Copyright 2020 Automattic * * Date: 24/05/2019 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) { exit; } /* ====================================================== / Breaking Checks ====================================================== */ // temp/mvp solution. Some fields need different labels for export! function zeroBSCRM_export_fieldReplacements() { return array( // Contacts/co 'wpid' => __( 'WordPress ID', 'zero-bs-crm' ), 'tw' => __( 'Twitter Handle', 'zero-bs-crm' ), 'fb' => __( 'Facebook Page', 'zero-bs-crm' ), 'li' => __( 'LinkedIn', 'zero-bs-crm' ), 'avatar' => __( 'Avatar', 'zero-bs-crm' ), 'created' => __( 'Created Date', 'zero-bs-crm' ), 'lastupdated' => __( 'Last Updated Date', 'zero-bs-crm' ), 'lastcontacted' => __( 'Last Contacted Date', 'zero-bs-crm' ), // Quotes 'id_override' => __( 'Reference', 'zero-bs-crm' ), 'currency' => __( 'Currency', 'zero-bs-crm' ), 'hash' => __( 'Hash', 'zero-bs-crm' ), 'lastviewed' => __( 'Last Viewed', 'zero-bs-crm' ), 'viewed_count' => __( 'Viewed Count', 'zero-bs-crm' ), 'accepted' => __( 'Accepted Date', 'zero-bs-crm' ), 'acceptedsigned' => __( 'Signed Date', 'zero-bs-crm' ), 'acceptedip' => __( 'Signed via IP', 'zero-bs-crm' ), // inv 'status' => __( 'Status', 'zero-bs-crm' ), // trans 'origin' => __( 'Origin', 'zero-bs-crm' ), 'customer_ip' => __( 'Contact IP', 'zero-bs-crm' ), ); } function zeroBSCRM_export_blockedFields() { return array( // global 'zbs_site', 'zbs_team', // quotes 'template', 'content', 'notes', 'send_attachments', // inv 'pay_via', 'logo_url', 'pdf_template', 'portal_template', 'email_template', 'invoice_frequency', 'address_to_objtype', 'allow_partial', 'allow_tip', 'hours_or_quantity', // trans 'parent', 'taxes', 'shipping_taxes', ); } /* ====================================================== Export Tools UI ====================================================== */ // render export page function zeroBSCRM_page_exportRecords() { jpcrm_load_admin_page( 'export/main' ); jpcrm_render_export_page(); } /* ====================================================== / Export Tools UI ====================================================== */ /* ====================================================== Export Tools -> Actual Export File ====================================================== */ function jpcrm_export_process_file_export() { global $zbs; // Check if valid posted export request // ++ nonce verifies // ++ is admin side // ++ is our page // ++ has perms if ( isset( $_POST ) && isset( $_POST['jpcrm-export-request'] ) && isset( $_POST['jpcrm-export-request-nonce'] ) && wp_verify_nonce( $_POST['jpcrm-export-request-nonce'], 'zbs_export_request' ) && is_admin() && isset( $_GET['page'] ) && $_GET['page'] == $zbs->slugs['export-tools'] && zeroBSCRM_permsExport() ) { $obj_type_id = -1; $objIDArr = array(); $fields = array(); $extraParams = array( 'all' => false ); // == Param Retrieve ================================================ // check obj type if ( isset( $_POST['jpcrm-export-request-objtype'] ) ) { $potentialObjTypeID = (int) sanitize_text_field( $_POST['jpcrm-export-request-objtype'] ); if ( $zbs->DAL->isValidObjTypeID( $potentialObjTypeID ) ) { $obj_type_id = $potentialObjTypeID; } } // check id's if ( isset( $_POST['jpcrm-export-request-objids'] ) ) { $potentialIDStr = sanitize_text_field( $_POST['jpcrm-export-request-objids'] ); $potentialIDs = explode( ',', $potentialIDStr ); foreach ( $potentialIDs as $potentialID ) { $i = (int) $potentialID; if ( $i > 0 && ! in_array( $i, $objIDArr ) ) { $objIDArr[] = $i; } } } // catch extra params if ( isset( $potentialIDStr ) && $potentialIDStr == 'all' ) { $extraParams['all'] = true; } // get segment id, if exporting segment // (only for contacts) if ( $obj_type_id == ZBS_TYPE_CONTACT && ! empty( $_POST['jpcrm-export-request-segment-id'] ) ) { // segment export $potential_segment_id = sanitize_text_field( $_POST['jpcrm-export-request-segment-id'] ); $potential_segment = $zbs->DAL->segments->getSegment( $potential_segment_id ); if ( is_array( $potential_segment ) ) { $extraParams['segment'] = $potential_segment; } } // retrieve fields if ( is_array( $_POST ) ) { foreach ( $_POST as $k => $v ) { // retrieve all posted pre-keys if ( str_starts_with( $k, 'zbs-export-field-' ) ) { // is *probably* one of ours (doesn't guarantee) $fieldKey = sanitize_text_field( $v ); // some generic replacements: if ( $fieldKey == 'ID' ) { $fieldKey = 'id'; } if ( $fieldKey == 'owner' ) { $fieldKey = 'zbs_owner'; } // add if ( ! in_array( $fieldKey, $fields ) ) { $fields[] = $fieldKey; } } } } // == / Param Retrieve ============================================= // == FINAL CHECKS? ================================================ // Got acceptable objtype // Got fields to export // Got ID's to export (or all, or segment) if ( $obj_type_id > 0 && is_array( $fields ) && count( $fields ) > 0 && ( ( is_array( $objIDArr ) && count( $objIDArr ) > 0 ) || $extraParams['all'] || ( isset( $extraParams['segment'] ) && is_array( $extraParams['segment'] ) ) // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ) ) { $extra_file_name_str = ''; // == obj type loading ========================================= // obj layer $objDALLayer = $zbs->DAL->getObjectLayerByType( $obj_type_id ); // what fields do we have to export? $fieldsAvailable = zeroBSCRM_export_produceAvailableFields( $obj_type_id ); // language $objTypeSingular = $zbs->DAL->typeStr( $obj_type_id, false ); $objTypePlural = $zbs->DAL->typeStr( $obj_type_id, true ); // basic label 'contact/contacts' $exportTypeLabel = $objTypeSingular; if ( count( $objIDArr ) > 1 ) { $exportTypeLabel = $objTypePlural; } // == / obj type loading ======================================= // == segment specific loading ================================= if ( isset( $extraParams['segment'] ) && is_array( $extraParams['segment'] ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $extra_file_name_str = '-segment-' . $extraParams['segment']['id']; } // == / segment specific loading =============================== // general $filename = 'exported-' . $objTypePlural . $extra_file_name_str . '-' . date( 'd-m-Y_g-i-a' ) . '.csv'; // == file start =================================================== // send header header( 'Content-Type: text/csv; charset=utf-8' ); header( 'Content-Disposition: attachment; filename= ' . $filename ); // open output $output = fopen( 'php://output', 'w' ); // == / file start ================================================= // == file gen ===================================================== // column headers $columnHeaders = array(); foreach ( $fields as $fK ) { $label = $fK; if ( isset( $fieldsAvailable[ $fK ] ) ) { $label = $fieldsAvailable[ $fK ]; } $columnHeaders[] = $label; // for owners we add two columns, 1 = Owner ID, 2 = Owner username if ( $fK == 'zbs_owner' ) { $columnHeaders[] = __( 'Owner Username', 'zero-bs-crm' ); } } fputcsv( $output, $columnHeaders ); // actual export lines // retrieve objs if ( $extraParams['all'] ) { $availObjs = $objDALLayer->getAll( $objIDArr ); } elseif ( isset( $extraParams['segment'] ) && is_array( $extraParams['segment'] ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // Retrieve segment. $availObjs = $zbs->DAL->segments->getSegmentAudience( $extraParams['segment']['id'], -1, // All, no paging. -1 // All, no paging. ); } else { $availObjs = $objDALLayer->getIDList( $objIDArr ); } if ( is_array( $availObjs ) ) { foreach ( $availObjs as $obj ) { // per obj $objRow = array(); foreach ( $fields as $fK ) { $v = ''; // default (means always right col count) if ( isset( $obj[ $fK ] ) ) { $v = zeroBSCRM_textExpose( $obj[ $fK ] ); } // date objs use _date (which are formatted) if ( isset( $obj[ $fK . '_date' ] ) ) { $v = $obj[ $fK . '_date' ]; } // custom field dates too: if ( isset( $obj[ $fK . '_cfdate' ] ) ) { $v = $obj[ $fK . '_cfdate' ]; } // ownership - column 1 (ID) if ( $fK == 'zbs_owner' && ! empty( $obj['owner']['ID'] ) ) { $v = $obj['owner']['ID']; } // catch legacy secaddr_addr1 issues. (only for contacts) // blurgh. // secaddr1 => secaddr_addr1 if ( $obj_type_id == ZBS_TYPE_CONTACT && str_starts_with( $fK, 'sec' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase,Universal.Operators.StrictComparisons.LooseEqual if ( isset( $obj[ str_replace( 'sec', 'secaddr_', $fK ) ] ) ) { $v = $obj[ str_replace( 'sec', 'secaddr_', $fK ) ]; } } // here we account for linked objects // as of 4.1.1 this is contact/company for quote/invoice/transaction // passed in format: linked_obj_{OBJTYPEINT}_{FIELD} if ( str_starts_with( $fK, 'linked_obj_' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // take objtype from field $linked_obj_type_int_and_field = substr( $fK, 11 ); // split type and field $linked_obj_type_parts = explode( '_', $linked_obj_type_int_and_field, 2 ); $linked_obj_type_int = (int) $linked_obj_type_parts[0]; // e.g. ZBS_TYPE_CONTACT = 1 $linked_obj_field = $linked_obj_type_parts[1]; // e.g. 'ID' // retrieve sub object $linked_obj = jpcrm_export_retrieve_linked_object( $obj, $linked_obj_type_int ); // retrieve field value if ( isset( $linked_obj[ $linked_obj_field ] ) ) { // pass field as value, (provided is set) // e.g. id // note, other fields are also present here, so could expand to pass name etc. $v = $linked_obj[ $linked_obj_field ]; } } // if -1 kill if ( $v == -1 ) { $v = ''; } $objRow[] = $v; // ownership - column 2 (Username) if ( $fK == 'zbs_owner' ) { $v2 = ''; /* With -1 owner it looks like this: 'owner' => array ( 'ID' => '-1', 'OBJ' => false, ), With 0 owner it looks like this: 'owner' => false, With actual WP owner looks like this: 'owner' => array ( 'ID' => '234', 'OBJ' => (object)WP_User, ), */ // if has an owner if ( ! empty( $obj['owner']['OBJ'] ) ) { $v2 = $obj['owner']['OBJ']->user_login; } $objRow[] = $v2; } } // / foreach field in each obj row // output row fputcsv( $output, $objRow ); } // / foreach obj } // == / file gen =================================================== // == file fini ==================================================== // send end fclose( $output ); exit(); // == / file fini ================================================== } // / final checks } // / Check if valid posted export request } add_action( 'jpcrm_post_wp_loaded', 'jpcrm_export_process_file_export' ); /** * Takes an object being exported, and a linked object type, and returns the subobject * e.g. $obj could be a quote, linkedType could be contact, this would return the contact object against the quote * * @param array $obj (line being exported), int $linkedObjTypeInt CRM Object type * * @return array $sub object */ function jpcrm_export_retrieve_linked_object( $obj = array(), $linkedObjTypeInt = -1 ) { global $zbs; // turn 1 into `contact` $linkedObjTypeKey = $zbs->DAL->objTypeKey( $linkedObjTypeInt ); // set contact ID // objects like quotes will have these as arrays under `contact` and `company` if ( is_array( $obj[ $linkedObjTypeKey ] ) && count( $obj[ $linkedObjTypeKey ] ) > 0 ) { // noting here that object links can allow 1:many links, we only take the first if ( is_array( $obj[ $linkedObjTypeKey ][0] ) ) { return $obj[ $linkedObjTypeKey ][0]; } } return array(); } // retrieves a formatted obj field array of what's actually 'allowed' to be exported // Tested a few ways of achieving this, given the $globalfield limbo that v3 is in (legacy) // - Using the $globalField method was unreliable, so rolled fresh using db-driven custom fields // ... this could be rolled back into how we do $globalFields in road to v4 // gh-253 function zeroBSCRM_export_produceAvailableFields( $objTypeToExport = false, $includeAreas = false ) { global $zbs; // def $fieldsAvailable = array(); // obj layer $objDALLayer = $zbs->DAL->getObjectLayerByType( $objTypeToExport ); // fields avail to export // just base fields: $objLayerFields = $objDALLayer->objModel(); // base fields + custom fields: $objLayerFields = $objDALLayer->objModelIncCustomFields(); // process if ( is_array( $objLayerFields ) ) { $blockedFields = zeroBSCRM_export_blockedFields(); // ,'zbs_owner' $relabel = zeroBSCRM_export_fieldReplacements(); foreach ( $objLayerFields as $fieldKey => $field ) { // cf's need to alter this, so we var $fieldKeyOutput = $fieldKey; if ( ! in_array( $fieldKey, $blockedFields ) ) { // simplify for output if ( ! array_key_exists( $fieldKey, $fieldsAvailable ) ) { /* e.g. : [email] => Array ( [fieldname] => zbsc_email [format] => str [input_type] => email [label] => Email [placeholder] => e.g. john@gmail.com [essential] => 1 ) Note: 3.0.7+ also includes custom fields: [test] => Array ( [0] => text [1] => test [2] => test [3] => test [custom-field] => 1 ) */ $label = $fieldKey; $area = ''; if ( ! isset( $field['custom-field'] ) ) { // Non CF stuff: // label if ( isset( $field['label'] ) ) { $label = $field['label']; } // relabel? if ( isset( $relabel[ $fieldKey ] ) ) { $label = $relabel[ $fieldKey ]; } // addresses/areas (append) if ( isset( $field['area'] ) ) { if ( ! $includeAreas ) { $label .= ' (' . $field['area'] . ')'; } $area = $field['area']; } // one exception: if ( $label == 'zbs_owner' ) { $label = __( 'Owner', 'zero-bs-crm' ); } } else { // prefix $fieldKeyOutput $fieldKeyOutput = 'cf-' . $fieldKeyOutput; // Custom field passing if ( isset( $field[1] ) ) { $label = $field[1]; } // addresses/areas (append) if ( isset( $field['area'] ) ) { if ( ! $includeAreas ) { $label .= ' (' . $field['area'] . ')'; } $area = $field['area']; } if ( $area == '' ) { $area = __( 'Custom Fields', 'zero-bs-crm' ); } } if ( $includeAreas ) { // with area $fieldsAvailable[ $fieldKey ] = array( 'label' => $label, 'area' => $area, ); } else { // simpler $fieldsAvailable[ $fieldKey ] = $label; } } } } } // Add additional fields which are stored in the DB via obj links // e.g. Invoice Contact $linkedTypes = $objDALLayer->linkedToObjectTypes(); foreach ( $linkedTypes as $objectType ) { // for now, hard typed, we only add `ID`, `email`, and `name`, as these are a given for contacts + companies // retrieve label (e.g. 'Contact') $obj_label = $zbs->DAL->typeStr( $objectType ); // ID $label = $obj_label . ' ID'; if ( $includeAreas ) { // with area $fieldsAvailable[ 'linked_obj_' . $objectType . '_id' ] = array( 'label' => $label, 'area' => __( 'Linked Data', 'zero-bs-crm' ), ); } else { // simpler $fieldsAvailable[ 'linked_obj_' . $objectType . '_id' ] = $label; } // name $label = $obj_label . ' ' . __( 'Name', 'zero-bs-crm' ); if ( $includeAreas ) { // with area $fieldsAvailable[ 'linked_obj_' . $objectType . '_name' ] = array( 'label' => $label, 'area' => __( 'Linked Data', 'zero-bs-crm' ), ); } else { // simpler $fieldsAvailable[ 'linked_obj_' . $objectType . '_name' ] = $label; } // email $label = $obj_label . ' ' . __( 'Email', 'zero-bs-crm' ); if ( $includeAreas ) { // with area $fieldsAvailable[ 'linked_obj_' . $objectType . '_email' ] = array( 'label' => $label, 'area' => __( 'Linked Data', 'zero-bs-crm' ), ); } else { // simpler $fieldsAvailable[ 'linked_obj_' . $objectType . '_email' ] = $label; } } return $fieldsAvailable; } /* ====================================================== / Export Tools -> Actual Export File ====================================================== */
projects/plugins/crm/includes/ZeroBSCRM.MetaBoxes3.Invoices.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V3.0 * * Copyright 2020 Automattic * * Date: 20/02/2019 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== Init Func ====================================================== */ function zeroBSCRM_InvoicesMetaboxSetup() { // main detail $zeroBS__Metabox_Invoice = new zeroBS__Metabox_Invoice( __FILE__ ); // actions (status + save) $zeroBS__Metabox_InvoiceActions = new zeroBS__Metabox_InvoiceActions( __FILE__ ); // invoice tags box $zeroBS__Metabox_InvoiceTags = new zeroBS__Metabox_InvoiceTags( __FILE__ ); // external sources $zeroBS__Metabox_ExtSource = new zeroBS__Metabox_ExtSource( __FILE__, 'invoice', 'zbs-add-edit-invoice-edit' ); // files $zeroBS__Metabox_InvoiceFiles = new zeroBS__Metabox_InvoiceFiles( __FILE__ ); } add_action( 'admin_init', 'zeroBSCRM_InvoicesMetaboxSetup' ); /* ====================================================== / Init Func ====================================================== */ /* ====================================================== Invoicing Metabox ====================================================== */ class zeroBS__Metabox_Invoice extends zeroBS__Metabox { // this is for catching 'new' invoice private $newRecordNeedsRedir = false; public function __construct( $plugin_file ) { // set these $this->objType = 'invoice'; $this->metaboxID = 'zerobs-invoice-edit'; $this->metaboxTitle = __( 'Invoice Information', 'zero-bs-crm' ); // will be headless anyhow $this->headless = true; $this->metaboxScreen = 'zbs-add-edit-invoice-edit'; $this->metaboxArea = 'normal'; $this->metaboxLocation = 'high'; $this->saveOrder = 1; $this->capabilities = array( 'can_hide' => false, // can be hidden 'areas' => array( 'normal' ), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => true, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true, // can be minimised 'can_move' => true, // can be moved ); // call this $this->initMetabox(); } public function html( $invoice, $metabox ) { // localise ID $invoiceID = is_array( $invoice ) && isset( $invoice['id'] ) ? (int)$invoice['id'] : -1; global $zbs; // Prefill ID and OBJ are added to the #zbs_invoice to aid in prefilling the data (when drawn with JS) $prefill_id = -1; $prefill_obj = -1; $prefill_email = ''; $prefill_name = ''; if ( !empty( $_GET['zbsprefillcust'] ) ) { $prefill_id = (int)$_GET['zbsprefillcust']; $prefill_obj = ZBS_TYPE_CONTACT; $prefill_email = zeroBS_customerEmail( $prefill_id ); $prefill_name = $zbs->DAL->contacts->getContactNameWithFallback( $prefill_id ); } if ( !empty( $_GET['zbsprefillco'] ) ) { $prefill_id = (int)$_GET['zbsprefillco']; $prefill_obj = ZBS_TYPE_COMPANY; $prefill_email = zeroBS_companyEmail( $prefill_id ); $prefill_name = $zbs->DAL->companies->getCompanyNameEtc( $prefill_id ); } ?> <?php /* AJAX NONCE */ ?> <script type="text/javascript">var zbscrmjs_secToken = '<?php echo esc_js( wp_create_nonce( 'zbscrmjs-ajax-nonce' ) ); ?>';</script> <?php /* END OF NONCE */ ?> <?php // AJAX NONCE for inv sending... defunct v3.0? echo '<input type="hidden" name="inv-ajax-nonce" id="inv-ajax-nonce" value="' . esc_attr( wp_create_nonce( 'inv-ajax-nonce' ) ) . '" />'; // invoice UI divs (loader and canvas) echo '<div id="zbs_loader"><div class="ui active dimmer inverted"><div class="ui text loader">' . esc_html( __( 'Loading Invoice...', 'zero-bs-crm' ) ) . '</div></div><p></p></div>'; echo "<div id='zbs_invoice' class='zbs_invoice_html_canvas' data-invid='" . esc_attr( $invoiceID ) . "'></div>"; // we pass the hash along the chain here too :) if ( isset( $invoice['hash'] ) ) { echo '<input type="hidden" name="zbsi_hash" id="zbsi_hash" value="' . esc_attr( $invoice['hash'] ) . '" />'; } // custom fields $customFields = $zbs->DAL->getActiveCustomFields( array( 'objtypeid' => ZBS_TYPE_INVOICE ) ); if ( !is_array( $customFields ) ) { $customFields = array(); } // pass data: ?> <script type="text/javascript"> <?php if ( $prefill_obj > 0 ) { echo 'var zbsJS_prefillobjtype = ' . esc_js( $prefill_obj ) . ';'; } if ( $prefill_id > 0 ) { echo 'var zbsJS_prefillid = ' . esc_js( $prefill_id ) . ';'; } echo 'var zbsJS_prefillemail = \'' . esc_js( $prefill_email ) . '\';'; echo 'var zbsJS_prefillname = \'' . esc_js( $prefill_name ) . '\';'; // only sendemail if have active template :) echo 'var zbsJS_invEmailActive = ' . ( zeroBSCRM_get_email_status( ZBSEMAIL_EMAILINVOICE ) == 1 ? '1' : '-1' ) . ';'; ?> </script> <div id="zbs-invoice-custom-fields-holder" style="display:none"> <table> <?php // here we put the fields out then: // 1) copy the fields into the UI foreach ( $customFields as $cfK => $cF ) { zeroBSCRM_html_editField_for_invoices( $invoice, $cfK, $cF, 'zbsi_' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } ?> </table> </div> <?php // allow hook-ins from invoicing pro etc. do_action( 'zbs_invoicing_append' ); } public function save_data( $invoiceID, $invoice ) { if ( !defined( 'ZBS_OBJ_SAVED' ) ) { define( 'ZBS_OBJ_SAVED', 1 ); global $zbs; // check this if ( empty( $invoiceID ) || $invoiceID < 1 ) { $invoiceID = -1; } // retrieve existing $existing_invoice = $zbs->DAL->invoices->getInvoice( $invoiceID ); $autoGenAutonumbers = true; // generate if not set :) $removeEmpties = false; // req for autoGenAutonumbers $invoice = zeroBS_buildObjArr( $_POST, array(), 'zbsi_', '', $removeEmpties, ZBS_TYPE_INVOICE, $autoGenAutonumbers ); // Use the tag-class function to retrieve any tags so we can add inline. // Save tags against objid $invoice['tags'] = zeroBSCRM_tags_retrieveFromPostBag( true, ZBS_TYPE_INVOICE ); // pay via $invoice['pay_via'] = isset( $_POST['pay_via'] ) && (int)$_POST['pay_via'] === -1 ? -1 : 0; // new way.. now not limited to 30 lines as now they are stored in [] type array in JS draw $zbsInvoiceLines = array(); // gather lineitem data from POST // really this could use a refactor on the JS side so the POST data is structured how we want foreach ( $_POST['zbsli_itemname'] as $k => $v ) { $ks = sanitize_text_field( $k ); // at least this if ( !isset( $zbsInvoiceLines[$ks]['net'] ) ) { $zbsInvoiceLines[$ks]['net'] = 0.0; } $zbsInvoiceLines[$ks]['title'] = sanitize_text_field( $_POST['zbsli_itemname'][$k] ); $zbsInvoiceLines[$ks]['desc'] = sanitize_textarea_field( $_POST['zbsli_itemdes'][$k] ); $zbsInvoiceLines[$ks]['quantity'] = sanitize_text_field( $_POST['zbsli_quan'][$k] ); $zbsInvoiceLines[$ks]['price'] = sanitize_text_field( $_POST['zbsli_price'][$k] ); // calc a net, if have elements if ( !empty( $zbsInvoiceLines[$ks]['quantity'] ) && !empty( $zbsInvoiceLines[$ks]['price'] ) ) { $zbsInvoiceLines[$ks]['net'] = $zbsInvoiceLines[$ks]['quantity'] * $zbsInvoiceLines[$ks]['price']; } else { // leave net as empty :) } // taxes now stored as csv in 'taxes', 'tax' contains a total, but that's not passed by MS UI (yet? not needed?) $zbsInvoiceLines[$ks]['tax'] = 0; $zbsInvoiceLines[$ks]['taxes'] = empty( $_POST['zbsli_tax'][$k] ) ? '' : sanitize_text_field( $_POST['zbsli_tax'][$k] ); /* as at 22/2/19, each lineitem here could hold: 'order' => '', 'title' => '', 'desc' => '', 'quantity' => '', 'price' => '', 'currency' => '', 'net' => '', 'discount' => '', 'fee' => '', 'shipping' => '', 'shipping_taxes' => '', 'shipping_tax' => '', 'taxes' => '', 'tax' => '', 'total' => '', 'created' => '', 'lastupdated' => '', */ } if ( count( $zbsInvoiceLines ) > 0 ) { $invoice['lineitems'] = $zbsInvoiceLines; } // other items to update // hours or quantity switch if ( !empty( $_POST['invoice-customiser-type'] ) ) { $invoice['hours_or_quantity'] = $_POST['invoice-customiser-type'] === 'hours' ? 0 : 1; } // totals passed $invoice['discount'] = empty( $_POST['invoice_discount_total'] ) ? 0 : (float)sanitize_text_field( $_POST['invoice_discount_total'] ); $invoice['discount_type'] = empty( $_POST['invoice_discount_type'] ) ? 0 : sanitize_text_field( $_POST['invoice_discount_type'] ); $invoice['shipping'] = empty( $_POST['invoice_postage_total'] ) ? 0 : (float)sanitize_text_field( $_POST['invoice_postage_total'] ); // phpcs:ignore WordPress.Security.NonceVerification.Missing $invoice['shipping_taxes'] = empty( $_POST['zbsli_tax_ship'] ) ? 0 : (float) sanitize_text_field( wp_unslash( $_POST['zbsli_tax_ship'] ) ); // or shipping_taxes (not set by MS script) // ... js pass through :o Will be overwritten on php calc on addUpdate, actually, v3.0+ $invoice['total'] = empty( $_POST['zbs-inv-grand-total-store'] ) ? 0 : (float)sanitize_text_field( $_POST['zbs-inv-grand-total-store'] ); // assignments $zbsInvoiceContact = (int)$_POST['zbs_invoice_contact']; $invoice['contacts'] = $zbsInvoiceContact > 0 ? array( $zbsInvoiceContact ) : array(); $zbsInvoiceCompany = (int)$_POST['zbs_invoice_company']; $invoice['companies'] = $zbsInvoiceCompany > 0 ? array( $zbsInvoiceCompany ) : array(); // Later use: 'address_to_objtype' // other fields if ( isset( $_POST['invoice_status'] ) ) { $invoice['status'] = sanitize_text_field( $_POST['invoice_status'] ); } if ( isset( $_POST['zbsi_logo'] ) ) { $invoice['logo_url'] = sanitize_url( $_POST['zbsi_logo'] ); } $ref_type = $zbs->settings->get( 'reftype' ); if ( $invoiceID === -1 && $ref_type === 'autonumber' ) { $next_number = $zbs->settings->get( 'refnextnum' ); $prefix = $zbs->settings->get( 'refprefix' ); $suffix = $zbs->settings->get( 'refsuffix' ); $invoice['id_override'] = $prefix . $next_number . $suffix; $next_number++; $zbs->settings->update( 'refnextnum', $next_number ); } elseif ( isset( $_POST['zbsi_ref'] ) ) { $invoice['id_override'] = sanitize_text_field( $_POST['zbsi_ref'] ); } else { // ref should exist if ( empty( $invoice['id_override'] ) && isset( $existing_invoice['id_override'] ) ) { // override empty with existing $invoice['id_override'] = $existing_invoice['id_override']; } } // this needs to be translated to UTS (GMT) if ( isset( $_POST['zbsi_date'] ) ) { $invoice['date'] = sanitize_text_field( $_POST['zbsi_date'] ); $invoice['date'] = jpcrm_date_str_to_uts( $invoice['date'] ); } // due date is now calculated on save, then stored as UTS, if passed this way: // ... if due_date not set, editor will keep showing "due in x days" select // ... once set, that'll always show as a datepicker, based on the UTS in due_date if ( isset( $_POST['zbsi_due'] ) ) { // days (-1 - 90) $dueInDays = sanitize_text_field( $_POST['zbsi_due'] ); // got date + due days? if ( isset( $invoice['date'] ) && $dueInDays >= 0 ) { // project it forward $invoice['due_date'] = $invoice['date'] + ( $dueInDays * 60 * 60 * 24 ); } } // ... this then catches datepicker-picked dates (if passed by datepicker variant to due_days) if ( isset( $_POST['zbsi_due_date'] ) ) { $invoice['due_date'] = sanitize_text_field( $_POST['zbsi_due_date'] ); $invoice['due_date'] = jpcrm_date_str_to_uts( $invoice['due_date'] ); } // Custom Fields. /*$customFields = $zbs->DAL->getActiveCustomFields(array('objtypeid' => ZBS_TYPE_INVOICE)); if (!is_array($customFields)) $customFields = array(); foreach ($customFields as $cfK => $cfV){ if (isset($_POST['zbsi_'.$cfK])) $invoice[$cfK] = sanitize_text_field($_POST['zbsi_'.$cfK]); }*/ // add/update $addUpdateReturn = $zbs->DAL->invoices->addUpdateInvoice( array( 'id' => $invoiceID, 'data' => $invoice, 'limitedFields' => -1, // here we want PHP to calculate the total, tax etc. where we don't calc all the specifics in js 'calculate_totals' => 1, ) ); // Note: For NEW objs, we make sure a global is set here, that other update funcs can catch // ... so it's essential this one runs first! // this is managed in the metabox Class :) if ( $invoiceID === -1 && !empty( $addUpdateReturn ) && $addUpdateReturn != -1 ) { $invoiceID = $addUpdateReturn; global $zbsJustInsertedMetaboxID; $zbsJustInsertedMetaboxID = $invoiceID; // set this so it redirs $this->newRecordNeedsRedir = true; } // success? if ( $addUpdateReturn > 0 ) { // Update Msg // this adds an update message which'll go out ahead of any content // This adds to metabox: $this->updateMessages['update'] = zeroBSCRM_UI2_messageHTML('info olive mini zbs-not-urgent',__('Contact Updated',"zero-bs-crm"),'','address book outline','contactUpdated'); // This adds to edit page $this->updateMessage(); // catch any non-critical messages $nonCriticalMessages = $zbs->DAL->getErrors( ZBS_TYPE_INVOICE ); if ( is_array( $nonCriticalMessages ) && count( $nonCriticalMessages ) > 0 ) { $this->dalNoticeMessage( $nonCriticalMessages ); } } else { // fail somehow $failMessages = $zbs->DAL->getErrors( ZBS_TYPE_INVOICE ); // show msg (retrieved from DAL err stack) if ( is_array( $failMessages ) && count( $failMessages ) > 0 ) { $this->dalErrorMessage( $failMessages ); } else { $this->dalErrorMessage( array( __( 'Insert/Update Failed with general error', 'zero-bs-crm' ) ) ); } // pass the pre-fill: global $zbsObjDataPrefill; $zbsObjDataPrefill = $invoice; } } return $invoice; } // This catches 'new' contacts + redirs to right url public function post_save_data( $objID, $obj ) { if ( $this->newRecordNeedsRedir ) { global $zbsJustInsertedMetaboxID; if ( !empty( $zbsJustInsertedMetaboxID ) && $zbsJustInsertedMetaboxID > 0 ) { // redir wp_redirect( jpcrm_esc_link( 'edit', $zbsJustInsertedMetaboxID, $this->objType ) ); exit; } } } public function updateMessage() { global $zbs; // zbs-not-urgent means it'll auto hide after 1.5s // genericified from DAL3.0 $msg = zeroBSCRM_UI2_messageHTML( 'info olive mini zbs-not-urgent', $zbs->DAL->typeStr( $zbs->DAL->objTypeKey( $this->objType ) ) . ' ' . __( 'Updated', 'zero-bs-crm' ), '', 'address book outline', 'contactUpdated' ); $zbs->pageMessages[] = $msg; } } /* ====================================================== / Invoicing Metabox ====================================================== */ /* ====================================================== Invoice Files Metabox ====================================================== */ class zeroBS__Metabox_InvoiceFiles extends zeroBS__Metabox{ public function __construct( $plugin_file ) { // DAL3 switched for objType $this->postType = 'zerobs_customer'; $this->objType = 'invoice'; $this->metaboxID = 'zerobs-invoice-files'; $this->metaboxTitle = __('Associated Files',"zero-bs-crm"); $this->metaboxScreen = 'zbs-add-edit-invoice-edit'; //'zerobs_edit_contact'; // we can use anything here as is now using our func $this->metaboxArea = 'normal'; $this->metaboxLocation = 'low'; $this->capabilities = array( 'can_hide' => true, // can be hidden 'areas' => array('normal'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => true, // can/can't accept tabs onto it 'can_become_tab' => true, // can be added as tab 'can_minimise' => true // can be minimised ); // call this $this->initMetabox(); } public function html( $invoice, $metabox ) { global $zbs; $html = ''; // localise ID $invoiceID = -1; if (is_array($invoice) && isset($invoice['id'])) $invoiceID = (int)$invoice['id']; #} retrieve $zbsFiles = array(); if ($invoiceID > 0) $zbsFiles = zeroBSCRM_files_getFiles('invoice',$invoiceID); ?><table class="form-table wh-metatab wptbp" id="wptbpMetaBoxMainItemFiles"> <?php // WH only slightly updated this for DAL3 - could do with a cleanup run (contact file edit has more functionality) #} Any existing if (is_array($zbsFiles) && count($zbsFiles) > 0){ ?><tr class="wh-large"><th><label><?php printf( esc_html( _n( '%s associated file', '%s associated files', count($zbsFiles), 'text-domain' ) ), esc_html( number_format_i18n( count($zbsFiles) ) ) ); ?></label></th> <td id="zbsFileWrapInvoices"> <?php $fileLineIndx = 1; foreach($zbsFiles as $zbsFile){ $file = zeroBSCRM_files_baseName($zbsFile['file'],isset($zbsFile['priv'])); echo '<div class="zbsFileLine" id="zbsFileLineInvoice'. esc_attr( $fileLineIndx ) .'"><a href="'. esc_url( $zbsFile['url'] ) .'" target="_blank">'. esc_html( $file ) .'</a> (<span class="zbsDelFile" data-delurl="'. esc_attr( $zbsFile['url'] ) .'"><i class="fa fa-trash"></i></span>)</div>'; $fileLineIndx++; } ?> </td></tr><?php } ?> <?php #adapted from http://code.tutsplus.com/articles/attaching-files-to-your-posts-using-wordpress-custom-meta-boxes-part-1--wp-22291 $html .= '<input type="file" id="zbsobj_file_attachment" name="zbsobj_file_attachment" size="25" class="zbs-dc">'; ?><tr class="wh-large"><th><label><?php esc_html_e('Add File',"zero-bs-crm");?>:</label><br />(<?php esc_html_e('Optional',"zero-bs-crm");?>)<br /><?php esc_html_e('Accepted File Types',"zero-bs-crm");?>:<br /><?php echo esc_html( zeroBS_acceptableFileTypeListStr() ); ?></th> <td><?php wp_nonce_field(plugin_basename(__FILE__), 'zbsobj_file_attachment_nonce'); echo $html; ?></td></tr> </table> <script type="text/javascript"> var zbsInvoicesCurrentlyDeleting = false; var zbsMetaboxFilesLang = { 'err': '<?php echo esc_html( zeroBSCRM_slashOut(__('Error',"zero-bs-crm")) ); ?>', 'unabletodel' : '<?php echo esc_html( zeroBSCRM_slashOut(__('Unable to delete this file',"zero-bs-crm")) ); ?>', 'viewcontact' : '<?php echo esc_html__( 'View contact', 'zero-bs-crm' ); ?>', 'viewcompany' : '<?php echo esc_html( __( 'View', 'zero-bs-crm' ) . ' ' . jpcrm_label_company() ); ?>', } jQuery(function(){ jQuery('.zbsDelFile').on( 'click', function(){ if (!window.zbsInvoicesCurrentlyDeleting){ // blocking window.zbsInvoicesCurrentlyDeleting = true; var delUrl = jQuery(this).attr('data-delurl'); var lineIDtoRemove = jQuery(this).closest('.zbsFileLine').attr('id'); if (typeof delUrl != "undefined" && delUrl != ''){ // postbag! var data = { 'action': 'delFile', 'zbsfType': 'invoices', 'zbsDel': delUrl, // could be csv, never used though 'zbsCID': <?php echo esc_html( $invoiceID ); ?>, 'sec': window.zbscrmjs_secToken }; // Send it Pat :D jQuery.ajax({ type: "POST", url: ajaxurl, // admin side is just ajaxurl not wptbpAJAX.ajaxurl, "data": data, dataType: 'json', timeout: 20000, success: function(response) { // visually remove jQuery('#' + lineIDtoRemove).remove(); // file deletion errors, show msg: if (typeof response.errors != "undefined" && response.errors.length > 0){ jQuery.each(response.errors,function(ind,ele){ jQuery('#zerobs-invoice-files-box').append('<div class="ui warning message" style="margin-top:10px;">' + ele + '</div>'); }); } }, error: function(response){ jQuery('#zerobs-invoice-files-box').append('<div class="ui warning message" style="margin-top:10px;"><strong>' + window.zbsMetaboxFilesLang.err + ':</strong> ' + window.zbsMetaboxFilesLang.unabletodel + '</div>'); } }); } window.zbsInvoicesCurrentlyDeleting = false; } // / blocking }); }); </script><?php } public function save_data( $invoiceID, $invoice ) { global $zbsobj_justUploadedObjFile; $id = $invoiceID; if(!empty($_FILES['zbsobj_file_attachment']['name']) && (!isset($zbsobj_justUploadedObjFile) || (isset($zbsobj_justUploadedObjFile) && $zbsobj_justUploadedObjFile != $_FILES['zbsobj_file_attachment']['name']) ) ) { /* --- security verification --- */ if(!wp_verify_nonce($_POST['zbsobj_file_attachment_nonce'], plugin_basename(__FILE__))) { return $id; } // end if if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $id; } // end if if (!zeroBSCRM_permsInvoices()){ return $id; } /* - end security verification - */ // Blocking repeat-upload bug $zbsobj_justUploadedObjFile = $_FILES['zbsobj_file_attachment']['name']; // verify file extension and mime type if ( jpcrm_file_check_mime_extension( $_FILES['zbsobj_file_attachment'] ) ){ $invoice_dir_info = jpcrm_storage_dir_info_for_invoices( $invoiceID ); $upload = jpcrm_save_admin_upload_to_folder( 'zbsobj_file_attachment', $invoice_dir_info['files'] ); if ( isset( $upload['error'] ) && $upload['error'] != 0 ) { wp_die('There was an error uploading your file. The error is: ' . esc_html( $upload['error'] ) ); } else { // w mod - adds to array :) $zbsFiles = zeroBSCRM_files_getFiles('invoice',$invoiceID); if (is_array($zbsFiles)){ //add it $zbsFiles[] = $upload; } else { // first $zbsFiles = array($upload); } // update zeroBSCRM_files_updateFiles('invoice',$invoiceID, $zbsFiles); // Fire any 'post-upload-processing' (e.g. CPP makes thumbnails of pdf, jpg, etc.) // not req invoicing: do_action('zbs_post_upload_contact',$upload); } } else { wp_die("The file type that you've uploaded is not an accepted file format."); } } return $invoice; } } /* ====================================================== / Attach files to invoice metabox ====================================================== */ /* ====================================================== Invoicing Metabox Helpers ====================================================== */ function zeroBS__InvoicePro(){ $upTitle = __('Want more from invoicing?',"zero-bs-crm"); $upDesc = __('Accept Payments Online with Invoicing Pro.',"zero-bs-crm"); $upButton = __('Buy Now',"zero-bs-crm"); $upTarget = "https://jetpackcrm.com/product/invoicing-pro/"; echo zeroBSCRM_UI2_squareFeedbackUpsell($upTitle,$upDesc,$upButton,$upTarget); } /* ====================================================== / Invoicing Metabox Helpers ====================================================== */ /* ====================================================== Create Tags Box ====================================================== */ class zeroBS__Metabox_InvoiceTags extends zeroBS__Metabox_Tags{ public function __construct( $plugin_file ) { $this->objTypeID = ZBS_TYPE_INVOICE; // DAL3 switched for objType $this->postType = 'zerobs_customer'; $this->objType = 'invoice'; $this->metaboxID = 'zerobs-invoice-tags'; $this->metaboxTitle = __('Invoice Tags',"zero-bs-crm"); $this->metaboxScreen = 'zbs-add-edit-invoice-edit'; //'zerobs_edit_contact'; // we can use anything here as is now using our func $this->metaboxArea = 'side'; $this->metaboxLocation = 'high'; $this->showSuggestions = true; $this->capabilities = array( 'can_hide' => true, // can be hidden 'areas' => array('side'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => false, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true // can be minimised ); // call this $this->initMetabox(); } // html + save dealt with by parent class :) } /* ====================================================== / Create Tags Box ====================================================== */ /* ====================================================== Invoice Actions Metabox ====================================================== */ class zeroBS__Metabox_InvoiceActions extends zeroBS__Metabox{ public function __construct( $plugin_file ) { // set these $this->objType = 'invoice'; $this->metaboxID = 'zerobs-invoice-actions'; $this->metaboxTitle = __('Invoice Actions','zero-bs-crm'); // will be headless anyhow $this->headless = true; $this->metaboxScreen = 'zbs-add-edit-invoice-edit'; $this->metaboxArea = 'side'; $this->metaboxLocation = 'high'; $this->saveOrder = 1; $this->capabilities = array( 'can_hide' => false, // can be hidden 'areas' => array('side'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => true, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true, // can be minimised 'can_move' => true // can be moved ); // call this $this->initMetabox(); } public function html( $invoice, $metabox ) { // debug print_r($invoice); exit(); ?><div class="zbs-generic-save-wrap"> <div class="ui medium dividing header"><i class="save icon"></i> <?php esc_html_e('Invoice Actions','zero-bs-crm'); ?></div> <?php // localise ID & content $invoiceID = -1; if (is_array($invoice) && isset($invoice['id'])) $invoiceID = (int)$invoice['id']; if ($invoiceID > 0){ // existing ?> <?php do_action('zbs_invpro_itemlink'); ?> <div class="clear"></div> <div class="zbs-invoice-actions-bottom zbs-objedit-actions-bottom"> <button class="ui button black" type="button" id="zbs-edit-save"><?php esc_html_e( 'Update', 'zero-bs-crm' ); ?> <?php esc_html_e( 'Invoice', 'zero-bs-crm' ); ?></button> <?php #} Quick ver of this: http://themeflection.com/replace-wordpress-submit-meta-box/ ?><div id="zbs-invoice-actions-delete" class="zbs-objedit-actions-delete"><?php // for now just check if can modify invs, later better, granular perms. if ( zeroBSCRM_permsInvoices() ) { /* WP Deletion: no trash (at least v3.0) if ( !EMPTY_TRASH_DAYS ) $delete_text = __('Delete Permanently', "zero-bs-crm"); else $delete_text = __('Move to Trash', "zero-bs-crm"); ?><a class="submitdelete deletion" href="<?php echo get_delete_post_link($post->ID); ?>"><?php echo $delete_text; ?></a><?php */ $delete_text = __('Delete Permanently', "zero-bs-crm"); ?><a class="submitdelete deletion" href="<?php echo jpcrm_esc_link( 'delete', $invoiceID, 'invoice' ); ?>"><?php echo esc_html( $delete_text ); ?></a><?php } //if ?> </div> <div class='clear'></div> </div> <?php } else { ?> <?php do_action('zbs_invpro_itemlink'); ?> <button class="ui button black" type="button" id="zbs-edit-save"><?php esc_html_e( 'Save', 'zero-bs-crm' ); ?> <?php esc_html_e( 'Invoice', 'zero-bs-crm' ); ?></button> <?php #} If it's a new post #} Gross hide :/ } ?></div><?php // / .zbs-generic-save-wrap } // saved via main metabox }
projects/plugins/crm/includes/ZeroBSCRM.PluginUpdates.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V2.14+ * * Copyright 2017+ ZeroBSCRM.com * * Date: 26/09/2017 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ #} Note: This update check will only run in the presence of a license key, or Paid-for extension (separate to the free Core CRM Plugin on wp.org) #} Users of Paid extensions have separately accepted our general privacy policy which allows the #} passing of data to our update server/license check system. For core-crm-only users, this will never fire, and no private data will ever be sent or collected. class zeroBSCRM_Plugin_Updater { // vars private $api_url = ''; private $api_ver = ''; private $api_data = array(); private $name = ''; private $slug = ''; private $version = ''; private $wp_override = false; private $installedExts = false; private $nag_every = 432000; // php5.5 doesn't like this: (5 * 24 * 3600); //60; //nag every 5 days.. 5 * 24 * 3600 /* =============================================================================================== ======================================= init functions ========================================== =============================================================================================== */ /** * Class constructor. * * @uses plugin_basename() * @uses hook() * * @param string $_api_url The URL pointing to the custom API endpoint. * @param string $_api_ver ??WH: Is not clear? (is passing 1.0 currently) * @param string $_plugin_file Path to the plugin file. * @param array $_api_data Optional data to send with API calls. */ public function __construct( $_api_url, $_api_ver, $_plugin_file, $_api_data = null ) { global $zbs_plugin_data; $this->api_url = trailingslashit( $_api_url ); $this->api_ver = untrailingslashit( $_api_ver ); // wh: not used as of this check? 17/8/18 if ( is_array( $_api_data ) ) { // Prevent warning if it's null $this->api_data = $_api_data; $this->version = $_api_data['version']; $this->wp_override = isset( $_api_data['wp_override'] ) ? (bool) $_api_data['wp_override'] : false; } // Set up hooks. $this->init(); } /** * Set up WordPress filters to hook into WP's update process. * - pre_set_transient is the info on whether it needs updating * - plugins_api is when the 'view version [x.x] details' is clicked. */ public function init() { // actual check for updates add_filter( 'pre_set_site_transient_update_plugins', array( $this, 'check_update' ) ); // can also use this, but untested: add_filter( 'site_transient_update_plugins', array( $this, 'check_update' ) ); // Set our own get_info call add_filter( 'plugins_api', array( $this, 'get_info' ),10,3); // this 'renames' the source // fixes a WP bug where wp renames zero-bs-extension-password-manager to zero-bs-extension-password-manager-KGBdBz // (removes trailing group) // not req: add_filter('upgrader_clear_destination', array($this, 'delete_old_plugin'), 100, 4); add_filter( 'upgrader_source_selection', array( $this, 'maybe_adjust_source_dir' ), 1, 4 ); } /* =============================================================================================== ===================================== / init functions ========================================== =============================================================================================== */ /* =============================================================================================== ==================================== main call functions ======================================== =============================================================================================== */ public function check_update( $transient ) { // req global $zbs; // define $zbs_plugins = array(); $zbs_check_update_start = time(); $installedExts = 0; // retrieves all active/all WP plugins installed (not just ours) // Further gets other configs of same... $active_plugins = get_option('active_plugins'); $zbs_active_plugins = zeroBSCRM_activePluginListSimple(); $zbs_all_plugins_and_ver = zeroBSCRM_allPluginListSimple(); $zbs_extensions_on_site = zeroBSCRM_installedProExt(); $active_core_modules = jpcrm_core_modules_installed(); $installedExts = zeroBSCRM_extensionsInstalledCount(); // 7/1/19 - needs to do if key entered, regardless of if ext, because some peeps enter it before adding extensions if( $installedExts > 0 || $this->get_license_key() !== false ) { // retrieve license key info (later overwritten if updating) $key_info = $zbs->settings->get( 'license_key' ); // api request (will retrieve cached from this func, if just called same request) $response = $this->api_request( 'all_info', array( 'slug' => 'all', 'zbs-extensions' => $zbs_extensions_on_site, 'active-extensions' => $active_plugins, 'telemetry-active' => $zbs_active_plugins, 'telemetry-all' => $zbs_all_plugins_and_ver, 'core-modules' => $active_core_modules ) ); //, 'license'=>$lk // if got response if ( ! is_wp_error( $response ) ) { // check presence of license_key_valid // ... this catches the faulty/empty/devmode ones if ( isset( $response['license_key_valid'] ) && ( $response['license_key_valid'] == 'false' || $response['license_key_valid'] == 'empty' || $response['license_key_valid'] == '' || $response['license_key_valid'] == 'expired' ) ) { // is it dev mode? if ( isset( $response['devmode'] ) ) { // updates server thinks this user is in dev mode // ... so, no need to hassle. or do nout. } else { // invalid license key $key_info['validity'] = ''; if ( isset( $key_info['validity'] ) ) { $key_info['validity'] = $response['license_key_valid']; } // if this is saying false, then send a notification IF we haven't nagged for 5 days if ( !get_transient( 'zbs-nag-license-key-now' ) ) { // generate nag $link = admin_url( 'admin.php?page=zerobscrm-plugin-settings&tab=license' ); $parameters = __( 'Your License Key is incorrect.', 'zero-bs-crm' ) . ' <a href="' . $link . '">' . __( 'Please enter your license key here.', 'zero-bs-crm') . '</a>'; $reference = time(); $cid = get_current_user_id(); #NAG-ME-PLZ zeroBSCRM_notifyme_insert_notification( $cid, -999, -1, 'license.update.needed', $parameters, $reference ); set_transient( 'zbs-nag-license-key-now', 'nag', $this->nag_every ); } // / if set nag } // / if not dev mode // Otherwise, this is a valid license key // so next check if it's a rebranded one } else if ( $response['license_key_valid'] == 'brand.template' ) { // set validity - no brand template $key_info['validity'] = ''; if ( isset( $key_info['validity'] ) ) { $key_info['validity'] = 'brand.template'; } // This gives specific unbranded nag, so that wl peeps can forward to us, then we can say // "you need to add a brand template?" // if this is saying false, then send a notification IF we haven't nagged for 5 days // (rebrandr template needed) if ( !get_transient( 'zbs-nag-license-key-now' ) ) { // generate nag $link = admin_url( 'admin.php?page=zerobscrm-plugin-settings&tab=license' ); $parameters = __( 'Your License Key is not linked to a CRM Brand (Error #401)', 'zero-bs-crm') . ' <a href="' . $link .'">' . __( 'Please enter your license key here.', 'zero-bs-crm') . '</a>'; $reference = time(); $cid = get_current_user_id(); #NAG-ME-PLZ zeroBSCRM_notifyme_insert_notification( $cid, -999, -1, 'license.update.needed', $parameters, $reference ); set_transient( 'zbs-nag-license-key-now', 'nag', $this->nag_every ); } // otherwise this is a legit key :) } else { // set validity $key_info['validity'] = 'true'; // if passed, copy access level + expires if ( isset( $response['access'] ) ) { $key_info['access'] = sanitize_text_field( $response['access'] ); } if ( isset( $response['expires'] ) ) { $key_info['expires'] = (int)sanitize_text_field( $response['expires'] ); } // if this was the first time this api been used, it'll also send this back: if ( isset( $response['claimed'] ) ) { // define this just the once, it'll show a msg on license page if on the page global $zbsLicenseClaimed; $zbsLicenseClaimed = true; } } // here we build a var containing the correct 'up to date versions' $official_ver = $response['extensions']; // ... and we start with presumption everything is up to date $extensions_all_updated = true; // cycle through each ext on site & check against list recieved via api_request // this is safer + more longterm stable: foreach ( $zbs_extensions_on_site as $name => $pluginDetails ) { // Here we also now have 'key' to check against, which will in future // ... allow rebrandr auto updates // ... so what we do is go through all extensions on site... // ... and compare with dl'd versions: if ( is_array( $official_ver ) ) { foreach ( $official_ver as $extUpdateInfo ) { // if the key is set & matches if ( isset( $extUpdateInfo['zbskey'] ) && $extUpdateInfo['zbskey'] == $pluginDetails['key'] ) { // this is our ext :) - check the version to see if newer than installed if ( version_compare( $pluginDetails['ver'], $extUpdateInfo['version'], '<' ) ) { // =========================== // Local Mods to dl obj - these are needed in get_info and all_info (here) $newSlug = ''; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $e = false; if ( is_array( $pluginDetails ) && isset( $pluginDetails['path'] ) ) { $e = explode( '/', $pluginDetails['path'] ); } if ( is_array( $e ) ) { $newSlug = $e[0]; } if ( empty( $newSlug ) ) { $newSlug = $extUpdateInfo['slug']; } // this isn't needed once dl link fixed server side :) // actually, is a fairly legit fix for now // ... MAKES SURE installs in same dir as current for that ext, even in rebranded $modifiedDLLink = false; if ( isset( $extUpdateInfo['download_link'] ) ) { $modifiedDLLink = $extUpdateInfo['download_link']; $modifiedDLLink = str_replace( '?', '/' . $newSlug . '.zip?', $modifiedDLLink ); } // / Local Mods to dl obj - these are needed in get_info and all_info (here) // =========================== // Build 'update needed' obj ref $obj = new stdClass(); $obj->slug = $newSlug; $obj->plugin = ( isset( $pluginDetails['path'] ) ? $pluginDetails['path'] : '' ); $obj->new_version = $extUpdateInfo['version']; $obj->tested = $extUpdateInfo['tested']; $obj->package = $modifiedDLLink; // these errored on some rebrandr, so setting defaults $obj->url = false; // these errored on some rebrandr, so checking first to stop php notices if ( isset( $extUpdateInfo['url'] ) ) { $obj->url = $extUpdateInfo['url']; } if ( isset( $pluginDetails['path'] ) ) { $transient->response[$pluginDetails['path']] = $obj; } else { $transient->response[] = $obj; } // generate nag // then we are adding the notification to "please update Jetpack CRM extension "X") $parameters = sprintf( __( 'Please update %s from version %s to version %s.', 'zero-bs-crm' ), $pluginDetails['name'], $pluginDetails['ver'], $extUpdateInfo['version'] ); $ref = $pluginDetails['ver'] . $extUpdateInfo['version']; #NAG-ME-PLZ $reference = $pluginDetails['key'] . str_replace( '.', '', $ref ); $cid = get_current_user_id(); zeroBSCRM_notifyme_insert_notification( $cid, -999, -1, 'custom.extension.update.needed', $parameters, $reference ); // make note that something needs an update $extensions_all_updated = false; } // / end if ver is newer } // / end if key matches } // / end cycle through $official_ver } } // / end cycle through $zbs_extensions_on_site // This checks that this plugin_update is being called on a rebranded plugin // .. further, it then proceeds to check if the WL ver of CORE CRM needs updating // .. as that's not hosted on wp.org, it's a rebrand/remix :) if ( zeroBSCRM_isWL() ) { // get core ver $core = zeroBSCRM_installedWLCore(); // is core wl? if ( isset( $core ) && is_array( $core ) && isset( $core['ver'] ) ) { // get ext update info for core $coreUpdateInfo = false; if ( is_array( $official_ver ) ) { foreach ( $official_ver as $extUpdateInfo ) { if ( isset( $extUpdateInfo['zbskey'] ) && $extUpdateInfo['zbskey'] == 'core' ) { $coreUpdateInfo = $extUpdateInfo; break; } } } // this checks if it's the core & if the ver is older than latest if ( $coreUpdateInfo && version_compare( $core['ver'], $coreUpdateInfo['version'], '<' ) ) { // =========================== // Local Mods to dl obj - these are needed in get_info and all_info (here) $newSlug = ''; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $e = explode( '/', $core['path'] ); if ( is_array( $e ) ) { $newSlug = $e[0]; } if ( empty( $newSlug ) ) { $newSlug = $coreUpdateInfo['slug']; } // this isn't needed once dl link fixed server side :) // actually, is a fairly legit fix for now // ... MAKES SURE installs in same dir as current for that ext, even in rebranded $modifiedDLLink = $coreUpdateInfo['download_link']; $modifiedDLLink = str_replace( '?', '/' . $newSlug . '.zip?', $modifiedDLLink ); // / Local Mods to dl obj - these are needed in get_info and all_info (here) // =========================== // Build 'update needed' obj ref $obj = new stdClass(); $obj->slug = $newSlug; $obj->plugin = $core['path']; $obj->new_version = $coreUpdateInfo['version']; $obj->url = $coreUpdateInfo['url']; $obj->tested = $coreUpdateInfo['tested']; $obj->package = $modifiedDLLink; $transient->response[ $core['path'] ] = $obj; // generate nag // then we are adding the notification to "please update Jetpack CRM extension "X") $parameters = sprintf( __( 'Please update %s from version %s to version %s.', 'zero-bs-crm' ), $core['name'], $core['ver'], $coreUpdateInfo['version'] ); $ref = $core['ver'] . $coreUpdateInfo['version']; #NAG-ME-PLZ $reference = $core['key'] . str_replace( '.', '', $ref ); $cid = get_current_user_id(); zeroBSCRM_notifyme_insert_notification( $cid, -999, -1, 'core.update.needed', $parameters, $reference ); // make note that something needs an update $extensions_all_updated = false; } // / core crm rebrand has update } // / has core rebrand installed } // if is rebranded // If not all the Jetpack CRM extensions are updated. Fire off the warning shot. if( !$extensions_all_updated ) { // 1+ ext needs update // Recently nagged? if( !get_transient( 'zbs-nag-extension-update-now' ) ) { // generate nag $parameters = __( 'You are running extensions which are out of date and not supported. Please update to avoid any issues.', 'zero-bs-crm' ); $reference = time(); $cid = get_current_user_id(); #NAG-ME-PLZ zeroBSCRM_notifyme_insert_notification( $cid, -999, -1, 'general.extension.update.needed', $parameters, $reference ); set_transient( 'zbs-nag-extension-update-now', 'nag', $this->nag_every ); } // set extensions_updated to false in license info setting $key_info['extensions_updated'] = false; } else { // all exts are up to date // set extensions_updated to true in license info setting $key_info['extensions_updated'] = true; } } else { // There was a WP Error } // Brutally, update the settings obj containing license info // name is a legacy throwback to old sys $zbs->settings->update( 'license_key', $key_info ); } // / if $installdExts // return the trans :) // (modified or not) return $transient; } #} This fires when a user clicks "view version x.x.x information" next to an update in plugins.php or update-core.php // ... showing the info in the modal popup public function get_info($obj, $action, $arg){ // is this an info req? & is slug set? if ( $action === 'plugin_information' && isset( $arg->slug ) ) { // Grab the extension, if it is one of ours :) $possibleExtension = $this->getCRMExtension( $arg->slug ); // or is it core? if ( ! is_array( $possibleExtension ) ) { $possibleExtension = $this->getCoreWLCRM( $arg->slug ); } // if this is an array, it's either one of our ext or the core (or either rebranded) if ( is_array( $possibleExtension ) ) { // we'll need this: global $zbs; // do api request to get the info from api.jetpackcrm.com $res = $this->api_request( 'ext_info', array( 'slug' => $arg->slug, 'key' => $possibleExtension['key'] ) ); // is it a WP error? if ( ! is_wp_error( $res ) ) { // =========================== // Local Mods to dl obj - these are needed in get_info (here) and all_info $newSlug = ''; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $modifiedDLLink = ''; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $e = explode('/',$possibleExtension['path']); if (is_array($e)) $newSlug = $e[0]; if (empty($newSlug)) $newSlug = $res['slug']; if (isset($res['download_link']) && $res['download_link'] !== 'false' && !empty($newSlug)) { // this isn't needed once dl link fixed server side :) // actually, is a fairly legit fix for now // ... MAKES SURE installs in same dir as current for that ext, even in rebranded $modifiedDLLink = $res['download_link']; $modifiedDLLink = str_replace('?','/'.$newSlug.'.zip?',$modifiedDLLink); } // / Local Mods to dl obj - these are needed in get_info (here) and all_info // =========================== // Build 'update needed' obj ref $obj = new stdClass(); $obj->slug = $newSlug; $obj->plugin_name = $res['slug']; $obj->new_version = $res['version']; $obj->requires = $res['requires']; // name if (isset($res['name'])) $obj->name = $res['name']; elseif (isset($possibleExtension['name'])) $obj->name = $possibleExtension['name']; else $obj->name = ''; // tested to if (isset($res['tested'])) $obj->tested = $res['tested']; else // default to latest in core $obj->tested = $zbs->wp_tested; // url if (isset($res['url'])) $obj->url = $res['url']; else // default to core $obj->url = $zbs->urls['home']; // mod link if (isset($modifiedDLLink) && !empty($modifiedDLLink)){ $obj->download_link = $modifiedDLLink; $obj->package = $modifiedDLLink; } // html sections if (isset($res['sections'])) $obj->sections = $res['sections']; else // default $obj->sections = array(); // optional if (isset($res['banners'])) $obj->banners = $res['banners']; if (isset($res['downloaded'])) $obj->downloaded = $res['downloaded']; if (isset($res['last_updated'])) $obj->last_updated = $res['last_updated']; } // / end if ! wp error } // / end if is one of ours } // / end if slug set && is plugin_information // return the singular update obj return $obj; } /* =============================================================================================== =================================== / main call functions ======================================== =============================================================================================== */ /* =============================================================================================== ===================================== helper functions ========================================== =============================================================================================== */ // Retrieves license key, (if is one), from settings obj public function get_license_key(){ global $zbs; $settings = $zbs->settings->get('license_key'); // checks if exists and it's not empty if ( ! empty( $settings['key'] ) ) { return $settings['key']; } return false; } public function isLicenseValid(){ // taken wholesale out of adminPages license key page. $licenseKeyArr = zeroBSCRM_getSetting('license_key'); // simplify following: $licenseValid = false; if (isset($licenseKeyArr['validity'])) $licenseValid = ($licenseKeyArr['validity'] === 'true'); return $licenseValid; } /** * This is used to verify if is one of our extensions * >> only hook in if the slug is one of our plugins!! :) */ public function isCRMExtension($slug=''){ // req. global $zbs; // if slug passed if (!empty($slug)){ // get latest list (or cache) if (!is_array($this->installedExts)) $this->installedExts = zeroBSCRM_installedProExt(); // cycle through em foreach ($this->installedExts as $extName => $extDeets){ // debug echo 'checking '.$extDeets['slug'].' against '.$slug.'<br>'; // is slug in this arr? if (is_array($extDeets) && isset($extDeets['slug']) && $extDeets['slug'] == $slug) return true; } } return false; } #} Retireve extension details array based on the plugin slug public function getCRMExtension( $slug='' ) { global $zbs; // if slug if ( ! empty( $slug ) && $slug !== 'jetpack' && $slug !== 'zero-bs-crm' ) { // get latest list (or cache) if ( ! is_array( $this->installedExts ) ) { $this->installedExts = zeroBSCRM_installedProExt(); } // cycle through each, check if matches foreach ( $this->installedExts as $extName => $extDeets ) { if ( // something else we changed, changed this. Use first part of path now, not slug. ( is_array( $extDeets ) && isset( $extDeets['path'] ) && str_starts_with( $extDeets['path'], $slug ) ) // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ) { // simple return. $x = $extDeets; $x['shortname'] = $extName; return $x; } } } // / if slug // no luck return false; } #} Retireve rebranded core crm plugin details array based on the plugin slug public function getCoreWLCRM( $slug = '' ) { // req. global $zbs; // is this install rebranded, and is there a slug? if ( zeroBSCRM_isWL() && ! empty( $slug ) && $slug !== 'jetpack' ) { // get core ver $core = zeroBSCRM_installedWLCore(); //echo 'core:';print_r($core); // is core wl? if (isset($core) && is_array($core) && isset($core['ver'])){ // is this it? if ( // something else we changed, changed this. Use first part of path now, not slug. ( is_array( $core ) && isset( $core['path'] ) && str_starts_with( $core['path'], $slug ) ) ) { $x = $core; $x['shortname'] = $core['name']; return $x; } } // / this is core & it has a ver } // / is this install rebranded, and is there a slug? return false; } // Retrieves the latest info for ZBS extension list, or singular (if get_info) // 13/12/18 - this now caches, as is recalled for each plugin when getting all_info. // cachcing = side-hack for v1.0 public function api_request($action, $data){ // req. global $zbs; // discern multisite, WL $multisite = false; $wl = false; $multisite = is_multisite(); if ($multisite == ''){ $multisite = false; } if (zeroBSCRM_isWL()) $wl = true; // build request data package $api_params = array( 'zbs-action' => $action, 'license' => $this->get_license_key(), 'url' => home_url(), 'method' => 'POST', 'is_multi_site' => $multisite, 'is_wl' => $wl, 'country' => '', 'core_ver' => $zbs->version ); // sites $sites['sites'] = zeroBSCRM_multisite_getSiteList(); // combine sites list, our package, and any passed $data $api_params = array_merge($api_params, $sites); $api_params = array_merge($api_params, $data); /* Ultimately that'll make this remote post: 1 big array: $api_params = array( 'zbs-action' => $action, 'license' => $this->get_license_key(), 'url' => home_url(), 'method' => 'POST', 'is_multi_site' => $multisite, 'is_wl' => $wl, 'country' => $country, 'core_ver' => $zbs->version ++ 'slug'=> 'all', 'zbs-extensions'=> $zbs_extensions_on_site, 'active-extensions' => $active_plugins, 'telemetry-active' => $zbs_active_plugins, 'telemetry-all' => $zbs_all_plugins_and_ver ++ 'sites' => array() ); */ // got cache? (we don't cache ext_info) global $zbsExtUpdateCache; if ($action !== 'ext_info' && isset($zbsExtUpdateCache) && is_array($zbsExtUpdateCache)){ return $zbsExtUpdateCache; } else { // note, if we have recurring failures in this license key retrieve, it's likely that their is an SSL issue // // https://wordpress.stackexchange.com/questions/167898/is-it-safe-to-use-sslverify-true-for-with-wp-remote-get-wp-remote-post $licensingAttempts = $zbs->DAL->setting('licensingcount',0); // check for setting $hasHitError = $zbs->DAL->setting('licensingerror',false); if (is_array($hasHitError)) $hasHitError = true; // if 1 + no success, turn this off for third $sslIgnore = false; if ($licensingAttempts > 0 && !$this->isLicenseValid() && $hasHitError) $sslIgnore = true; if ($sslIgnore){ add_filter( 'https_ssl_verify', '__return_false' ); } // run the req. $responseFull = wp_remote_post( $this->api_url, array( 'method' => 'POST', 'timeout' => 60, 'redirection' => 5, 'httpversion' => '1.0', 'blocking' => true, 'headers' => array(), 'body' => $api_params, 'cookies' => array() ) ); // remove filter if set if ($sslIgnore){ remove_filter( 'https_ssl_verify', '__return_false' ); } // up count. $zbs->DAL->updateSetting('licensingcount',($licensingAttempts+1)); // hmmm - was wary of only allowing 200, but probs makes more sense than this? $unacceptableHTTPCodes = array(500,443); $httpCode = wp_remote_retrieve_response_code($responseFull); // got wp err? if ( ! is_wp_error( $responseFull ) && !in_array($httpCode,$unacceptableHTTPCodes)) { // decode $response = json_decode( $responseFull['body'],true ); // set cache $zbsExtUpdateCache = $response; // clear any err $zbs->DAL->updateSetting('licensingerror',false); // return return $response; } else { // wp err if (is_wp_error( $responseFull )){ // log the err $zbs->DAL->updateSetting('licensingerror',array('time'=>time(), 'err' => $responseFull->get_error_message())); } // http err if (in_array($httpCode,$unacceptableHTTPCodes)) { // log the err $msg = ''; if (is_array($responseFull) && isset($responseFull['message'])) $msg = $responseFull['message']; $zbs->DAL->updateSetting('licensingerror',array('time'=>time(), 'err' => 'Error:'.$httpCode.' '.$msg)); } } } return false; } /* This is a WH hack using .... https://github.com/CherryFramework/cherry-plugin-wizard/blob/master/includes/class-cherry-plugin-wizard-plugin-upgrader.php#L71 ... as a base ... which shoves itself in the middle of all plugin installs/upgrades ... IF it finds that the plugin being updated is one of OURS, it'll intercede and change: ... zero-bs-extension-password-manager-KGBdBz ... to ... zero-bs-extension-password-manager Useful: https://core.trac.wordpress.org/browser/tags/5.0/src/wp-admin/includes/class-plugin-upgrader.php#L21 https://core.trac.wordpress.org/browser/tags/5.0/src/wp-admin/includes/class-wp-upgrader.php#L502 https://developer.wordpress.org/reference/hooks/upgrader_process_complete/ */ /** * Adjust the plugin directory name if necessary. * * The final destination directory of a plugin is based on the subdirectory name found in the * (un)zipped source. In some cases - most notably GitHub repository plugin downloads -, this * subdirectory name is not the same as the expected slug and the plugin will not be recognized * as installed. This is fixed by adjusting the temporary unzipped source subdirectory name to * the expected plugin slug. * * @since 1.0.0 * @param string $source Path to upgrade/zip-file-name.tmp/subdirectory/. * @param string $remote_source Path to upgrade/zip-file-name.tmp. * @param \WP_Upgrader $upgrader Instance of the upgrader which installs the plugin. * @return string $source */ public function maybe_adjust_source_dir( $source, $remote_source, $upgrader, $extraArgs ) { // is this one of our plugins that's being updated? (will be called by all) $ours = false; $pluginPath = false; if (isset($extraArgs) && isset($extraArgs['plugin']) && !empty($extraArgs['plugin'])) $pluginPath = $extraArgs['plugin']; // normal ext + rebranded ext test if ($pluginPath !== false){ $ourExts = zeroBSCRM_installedProExt(); if (is_array($ourExts)) foreach ($ourExts as $x => $ext) if ($ext['path'] == $pluginPath) $ours = true; } // wl(rebranded) core test if ($pluginPath !== false && zeroBSCRM_isWL()){ // core check $core = zeroBSCRM_installedWLCore(); // if wl core is installed if (isset($core) && is_array($core) && isset($core['ver'])){ if ($core['path'] == $pluginPath) $ours = true; } } // if not ours, just return $source for now // otherwise use ORIGINAL plugin dir :) // https://core.trac.wordpress.org/browser/tags/5.0/src/wp-admin/includes/class-wp-upgrader.php#L502 if (!$ours) return $source; // req. global $wp_filesystem; if (! is_object( $wp_filesystem ) ) { return $source; } // check from path $from_path = untrailingslashit( $source ); $desired_slug = isset( $extraArgs['plugin'] ) ? $extraArgs['plugin'] : false; if (!empty($desired_slug)) { $e = explode('/',$desired_slug); if (is_array($e)) $desired_slug = $e[0]; if (empty($desired_slug)) return $source; } if ( ! $desired_slug ) { return $source; } // holder dir $to_path = untrailingslashit( $source ); // remove working dir // ?? not req. // attempt to build a 'proper' to_path if (!empty($to_path)) { $to_path = substr($to_path,0,strrpos($to_path,'/')); $to_path .= '/'.$desired_slug; } // if checks out... if ( ! empty( $to_path ) && $to_path !== $from_path ) { //echo 'from:'.$from_path.'<br>to:'.$to_path; //exit(); if ( true === $wp_filesystem->move( $from_path, $to_path ) ) { return trailingslashit( $to_path ); } else { return new WP_Error( 'rename_failed', esc_html__( 'The remote plugin package does not contain a folder with the desired slug and renaming did not work.', 'zero-bs-crm' ) . ' ' . esc_html__( 'Please contact the plugin provider and ask them to package their plugin according to the WordPress guidelines.', 'zero-bs-crm' ), array( 'found' => $to_path, 'expected' => $desired_slug ) ); } } elseif ( empty( $to_path ) ) { return new WP_Error( 'packaged_wrong', esc_html__( 'The remote plugin package consists of more than one file, but the files are not packaged in a folder.', 'zero-bs-crm' ) . ' ' . esc_html__( 'Please contact the plugin provider and ask them to package their plugin according to the WordPress guidelines.', 'zero-bs-crm' ), array( 'found' => $to_path, 'expected' => $desired_slug ) ); } return $source; } /* =============================================================================================== ==================================== / helper functions ========================================== =============================================================================================== */ } //https://stackoverflow.com/questions/2053245/how-can-i-detect-if-the-user-is-on-localhost-in-php // fullCheck = true = also checks in with our sever (max 1 x 24h) to see if we have an override rule in place // defaults to full check as of 2.97.9 // SELECT * FROM `zbs_app_users_licenses_requests` WHERE action = 'localcheck' function zeroBSCRM_isLocal($fullCheck=true) { // quick caching if (jpcrm_is_devmode_override()) return false; // is local, unless override setting set within past 48h $whitelist = array( '127.0.0.1', 'localhost', '::1' ); if ( in_array( zeroBSCRM_getRealIpAddr(), $whitelist, true ) ) { if ($fullCheck){ global $zbs; // appears to be local // see if setting (if this is set, it's legit, and its the last timestamp it was 'checked') $key = $zbs->DAL->setting('localoverride',false); // debug echo 'settinglocal:'.$key.' vs '.(time()-172800).'!<br>'; // how often to recheck $ageOkay = time()-(7*86400); // if set, less than xxx ago if ($key !== false && $key > $ageOkay) return false; // it appears not to be dev mode else { // is probably dev mode, if last check was more than xxx days ago, recheck $lastcheck = $zbs->DAL->setting('localoverridecheck',false); // debug echo 'lastcheck:'.$lastcheck.'!<br>'; // has last check if ($lastcheck !== false && $lastcheck > $ageOkay) // was checked less than a day ago, so is probs dev mode return true; else { // check + return $check = zeroBSCRM_localDblCheck(); // debug echo 'check:'.$check.'!<br>'; return $check; } } } else { // non-full-check return true; } } return false; } /* This function connects to https://api.jetpackcrm.com/localcheck ... passing this site url ... it's to be used to test if we have an "override" logged for this siteurl ... (to say that it's NOT a dev server, at this site url.) .. this should only ever be run once a day or so max, as calls API. .. in this case it's called by zeroBSCRM_isLocal itself, on param */ function zeroBSCRM_localDblCheck(){ // quick caching if (jpcrm_is_devmode_override()) return false; // req. global $zbs; // build request data package $api_params = array( 'siteurl' => home_url(), 'method' => 'POST', ); // run the req. $responseFull = wp_remote_post( $zbs->urls['apilocalcheck'], array( 'method' => 'POST', 'timeout' => 60, 'redirection' => 5, 'httpversion' => '1.0', 'blocking' => true, 'headers' => array(), 'body' => $api_params, 'cookies' => array() ) ); // log that it was checked $zbs->DAL->updateSetting('localoverridecheck',time()); // got wp err? if ( ! is_wp_error( $responseFull ) ) { // decode $response = json_decode( $responseFull['body'],true ); // infer if (isset($response['overridemode']) && $response['overridemode'] == 1){ //debug echo home_url().' is override'; // is legit, set here + Return false, this is to be override (not a local site) $zbs->DAL->updateSetting('localoverride',time()); // we also set this runtime global to avoid us having to multicheck settings define('JPCRM_DEVOVERRIDE',true); return false; } else { // debug echo home_url().' Not override'; // nope. not override (return true, is a local site) return true; } } else { // log the err //$zbs->DAL->updateSetting('licensingerror',array('time'=>time(), 'err' => $responseFull->get_error_message())); } // nope. not override (return true, is a local site) return true; } // checks if a plugin has an update. // adapted from https://wordpress.stackexchange.com/questions/228468/plugin-update-warning // ... for pre-checking new ver releases (e.g. <3.0 to 3.0) to enable pre-warning as in ZeroBSCRM.PluginUpdates.ImminentRelease.php // name = Jetpack CRM // textdom = zero-bs-crm (in lieu of slug) function zeroBSCRM_updates_pluginHasUpdate($name='',$textDomain=''){ if ( ! function_exists( 'get_plugin_updates' ) ) { require_once ABSPATH . 'wp-admin/includes/update.php'; require_once ABSPATH . 'wp-admin/includes/plugin.php'; } $list = get_plugin_updates(); $data = array(); foreach( $list as $i => $item ) { // debug echo 'item:<pre>'.print_r($item,1).'</pre><br>'; if ( (!empty($name) && strtolower( $name ) == strtolower( $item->Name ) ) || (!empty($textDomain) && strtolower( $textDomain ) == strtolower( $item->TextDomain ) ) ) { // simpler... return $list[$i]; } } /* not req. if( ! empty( $data ) ) { return array( 'name' => $data->Name, 'version' => $data->Version, 'new_version' => $data->update->new_version, 'url' => $data->update->url, 'package' => $data->update->package ); } */ return array(); }
projects/plugins/crm/includes/ZeroBSCRM.Edit.Segment.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V2.5 * * Copyright 2020 Automattic * * Date: 09/01/18 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if (! defined('ZEROBSCRM_PATH')) { exit; } /* ====================================================== / Breaking Checks ====================================================== */ function zeroBSCRM_pages_addEditSegment($potentialID = -1) { zeroBSCRM_html_addEditSegment($potentialID); } function zeroBSCRM_html_addEditSegment($potentialID = -1) { global $zbs; #} New or edit $newSegment = true; // potential $segmentID = (int)$potentialID; // attempt retrieve (including has rights) $segment = $zbs->DAL->segments->getSegment($segmentID, true); $matchtype = !empty( $segment['matchtype'] ) ? $segment['matchtype'] : ''; if (isset($segment) && isset($segment['id'])) { // checks out $newSegment = false; } else { // no perms/doesn't checkout $segment = false; } // retrieve conditions/helpers $available_conditions = zeroBSCRM_segments_availableConditions(); $available_conditions_by_category = zeroBSCRM_segments_availableConditions( true ); $available_condition_operators = zeroBSCRM_segments_availableConditionOperators(); $available_tags_contacts = $zbs->DAL->getTagsForObjType( array( 'objtypeid'=>ZBS_TYPE_CONTACT ) ); $available_tags_transactions = $zbs->DAL->getTagsForObjType( array( 'objtypeid' => ZBS_TYPE_TRANSACTION ) ); $availableStatuses = zeroBSCRM_getCustomerStatuses(true); #} Refresh 2 ?><div class="zbs-semantic wrap" id="zbs-segment-editor"> <!-- load blocker not used. <div class="ui segment hidden" id="zbs-segment-editor-blocker"> <div class="ui active inverted dimmer"> <div class="ui text loader"><?php esc_html_e('Saving', 'zero-bs-crm'); ?></div> </div> <p></p> </div> --> <!-- edit title --> <div class="ui huge centralsimple"> <div class="field required"> <label><?php esc_html_e('Name this Segment', 'zero-bs-crm' ); ?></label> <p style="font-size:0.8em"><?php esc_html_e('Enter a descriptive title. This is shown on internal pages and reports.', 'zero-bs-crm' ); ?></p> <input placeholder="<?php esc_attr_e('e.g. VIP Customers', 'zero-bs-crm' ); ?>" type="text" id="zbs-segment-edit-var-title" name="zbs-segment-edit-var-title" class="max500" value="<?php echo !empty( $segment['name'] ) ? esc_attr( $segment['name'] ) : ''; ?>"> <?php echo zeroBSCRM_UI2_messageHTML('mini error hidden', '', __('This field is required', 'zero-bs-crm' ), '', 'zbs-segment-edit-var-title-err'); ?> </div> </div> <!-- error segment --> <?php if ( is_array($segment) && isset( $segment['error'] ) ) { ?> <div style="max-width: 600px; margin-left: auto; margin-right: auto; margin-top: 2.5em;"> <?php // generate a user message re: segment error $error_code = $zbs->getErrorCode( $segment['error'] ); if ($error_code && isset( $error_code['user_message'] ) ) { $error_message = $error_code['user_message']; } else { // error code not present in global error-code array, show code $error_message = $segment['error']; } echo zeroBSCRM_UI2_messageHTML( 'warning', __('Segment Warning', 'zero-bs-crm'), __('There is an issue with this segment:', 'zero-bs-crm') . '<br>' . $error_message, 'warning', 'segment-condition-error' ); ?> </div> <?php } ?> <!-- edit conditions segment --> <div class="ui large centralsimple segment"> <div class="field" style="padding-top:0;padding-bottom: 0"> <button class="ui icon small button primary black right floated" type="button" id="zbs-segment-edit-act-add-condition"> <?php esc_html_e('Add Condition', 'zero-bs-crm' ); ?> <i class="plus icon"></i> </button> <label><?php esc_html_e('Conditions', 'zero-bs-crm' ); ?></label> <p><?php esc_html_e('Select conditions which will define this segment.', 'zero-bs-crm' ); ?></p> </div> <div id="zbs-segment-edit-conditions" class="ui segments"> <!-- built via js --> </div> <div class="field" style="padding-top:0"> <?php echo zeroBSCRM_UI2_messageHTML('mini hidden', '', __('Segments require at least one condition', 'zero-bs-crm' ), '', 'zbs-segment-edit-conditions-err'); ?> </div> <div class="field" style="padding-top:1em"> <label><?php esc_html_e('Match Type', 'zero-bs-crm' ); ?></label> <p><?php _e( 'Should contacts in this segment match <i>any</i> or <i>all</i> of the above conditions?', 'zero-bs-crm' ); ?></p> <select class="ui dropdown" id="zbs-segment-edit-var-matchtype"> <option value="all"<?php echo $matchtype === 'all' ? ' selected' : ''; ?>><?php esc_html_e('Match all Conditions', 'zero-bs-crm' ); ?></option> <option value="one"<?php echo $matchtype === 'one' ? ' selected' : ''; ?>><?php esc_html_e('Match any one Condition', 'zero-bs-crm' ); ?></option> </select> </div> <h4 class="ui horizontal header divider"><?php esc_html_e('Continue', 'zero-bs-crm' ); ?></h4> <div class="jog-on"> <button class="ui submit black large icon button" id="zbs-segment-edit-act-p2preview"><?php esc_html_e( 'Preview Segment', 'zero-bs-crm' ); ?> <i class="unhide icon"></i></button> <?php // where saved, show export button, and mailpoet: if ( ! $newSegment ) { // export if ( zeroBSCRM_permsExport() ){ ?> <a class="ui submit black large icon button" href="<?php echo jpcrm_esc_link( $zbs->slugs['export-tools'] . '&segment-id=' . $segment['id'] ); ?>"><?php esc_html_e( 'Export Segment (.CSV)', 'zero-bs-crm' ); ?> <i class="icon cloud download"></i></a> <?php } // mailpoet support do_action( 'jpcrm_segment_edit_export_mailpoet_button' ); } ?> </div> </div> <!-- preview segment --> <div class="ui large form centralsimple segment hidden" id="zbs-segment-edit-preview"> <div id="zbs-segment-edit-preview-output"> </div> <?php echo zeroBSCRM_UI2_messageHTML('hidden', '', __('Your conditions did not produce any matching Contacts. You can still save this segment, but currently there is no one in it!', 'zero-bs-crm' ), '', 'zbs-segment-edit-emptypreview-err'); ?> <div class="jog-on"> <button class="ui submit positive large icon button" id="zbs-segment-edit-act-p2submit"><?php esc_html_e('Save Segment', 'zero-bs-crm' ); ?> <i class="pie chart icon"></i></button> </div> </div> <?php // ajax + lang bits ?><script type="text/javascript"> var zbsSegment = <?php echo json_encode($segment); ?>; var jpcrm_available_conditions = <?php echo json_encode($available_conditions); ?>; var jpcrm_available_conditions_by_category = <?php echo json_encode($available_conditions_by_category); ?>; var zbsAvailableConditionOperators = <?php echo json_encode($available_condition_operators); ?>; var jpcrm_available_contact_tags = <?php echo json_encode( $available_tags_contacts ); ?>; var jpcrm_available_transaction_tags = <?php echo json_encode( $available_tags_transactions ); ?>; var zbsAvailableStatuses = <?php echo json_encode($availableStatuses); ?>; var zbsSegmentStemURL = '<?php echo jpcrm_esc_link( 'edit', -1, 'segment', true ); ?>'; var jpcrm_contact_stem_URL = '<?php echo jpcrm_esc_link( 'view', -1, 'contact', true ); ?>'; var zbsSegmentListURL = '<?php echo jpcrm_esc_link( $zbs->slugs['segments'] ); ?>'; var zbsSegmentSEC = '<?php echo esc_js( wp_create_nonce("zbs-ajax-nonce") ); ?>'; var zbsSegmentLang = { generalerrortitle: '<?php esc_html_e('General Error', 'zero-bs-crm' ); ?>', generalerror: '<?php esc_html_e('There was a general error.', 'zero-bs-crm' ); ?>', currentlyInSegment: '<?php esc_html_e('Contacts currently match these conditions.', 'zero-bs-crm' ); ?>', previewTitle: '<?php esc_html_e('Contacts Preview (randomised)', 'zero-bs-crm' ); ?>', noName: '<?php esc_html_e('Unnamed Contact', 'zero-bs-crm' ); ?>', noEmail: '<?php esc_html_e('No Email', 'zero-bs-crm' ); ?>', notags: '<?php esc_html_e('No Tags Found', 'zero-bs-crm' ); ?>', nostatuses: '<?php esc_html_e('No Statuses Found', 'zero-bs-crm' ); ?>', noextsources: '<?php esc_html_e('No External Sources Found', 'zero-bs-crm' ); ?>', no_mailpoet_statuses: '<?php esc_html_e('No MailPoet Statuses Found', 'zero-bs-crm' ); ?>', nosegmentid: '<?php esc_html_e('No Segment ID Found.', 'zero-bs-crm' ); ?>', to: '<?php esc_html_e('to', 'zero-bs-crm' ); ?>', eg: '<?php esc_html_e('e.g.', 'zero-bs-crm' ); ?>', saveSegment: '<?php echo esc_html( zeroBSCRM_slashOut('Save Segment', true) ).' <i class="save icon">'; ?>', savedSegment: '<?php echo esc_html( zeroBSCRM_slashOut('Segment Saved', true) ).' <i class="check circle outline icon">'; ?>', contactfields: '=== <?php esc_html_e('Contact Fields', 'zero-bs-crm' ); ?> ===', default_description: '<?php echo esc_html( zeroBSCRM_slashOut( 'Condition which selects contacts based on given value', true ) ); ?>', }; var jpcrm_external_source_list = <?php // simplify our external sources array $external_source_array = array(); foreach ($zbs->external_sources as $external_source_key => $external_source_info) { $external_source_array[] = array( 'key' => $external_source_key, 'name' => $external_source_info[0] ); } // sort by name usort($external_source_array, function ($a, $b) { return strcmp($a['key'], $b['key']); }); echo json_encode($external_source_array); // any extra js? e.g. MailPoet Export functionality do_action( 'segment_edit_extra_js' ); ?>; var jpcrm_mailpoet_status_list = <?php $jpcrm_mailpoet_status_list = array( array( 'key' => 'subscribed', 'name' => __( 'Subscribed', 'mailpoet' ), ), array( 'key' => 'unconfirmed', 'name' => __( 'Unconfirmed', 'mailpoet' ), ), array( 'key' => 'unsubscribed', 'name' => __( 'Unsubscribed', 'mailpoet' ), ), array( 'key' => 'inactive', 'name' => __( 'Inactive', 'mailpoet' ), ), array( 'key' => 'bounced', 'name' => __( 'Bounced', 'mailpoet' ), ), ); echo json_encode( $jpcrm_mailpoet_status_list ); ?> </script> </div><?php } function zeroBSCRM_segments_typeConversions( $value = '', $type = '', $operator = '', $direction = 'in' ){ if (!empty($value)) { $available_conditions = zeroBSCRM_segments_availableConditions(); if (isset($available_conditions[$type]['conversion'])) { // INBOUND (e.g. post -> db) // For dates, convert to UTS here. (EXCEPT FOR daterange/datetimerange!, dealing with that in zeroBSCRM_segments_filterConditions for now) if ($direction == 'in' && $operator != 'daterange' && $operator != 'datetimerange' && $operator != 'nextdays' && $operator != 'previousdays' ) { switch ($available_conditions[$type]['conversion']) { case 'date-to-uts': $local_date_time = new DateTime( $value, wp_timezone() ); $local_date_time->setTimezone( new DateTimeZone( 'UTC' ) ); $value = $local_date_time->format( 'Y-m-d H:i' ); // convert date to uts $value = zeroBSCRM_locale_dateToUTS($value, true); // for cases where we're saying 'after' {timestamp} we add 1 second if ($operator == 'after') { $value += 1; } break; } } elseif ( $direction == 'out' && $operator != 'nextdays' && $operator != 'previousdays' ) { // OUTBOUND (e.g. exposing dates in segment editor) // OUTBOUND (e.g. exposing dates in segment editor) switch ($available_conditions[$type]['conversion']) { case 'date-to-uts': // for cases where we're saying 'after' {timestamp} we add 1 second // here we retract that addition if ($operator == 'after') { $value -= 1; } // convert uts back to date $value = zeroBSCRM_date_i18n_plusTime( 'Y-m-d', $value ); break; } } } } return $value; }
projects/plugins/crm/includes/ZeroBSCRM.Core.License.php
<?php /* ! * Jetpack CRM * https://jetpackcrm.com * V2.4+ * * Copyright 2020 Automattic * * Date: 05/02/2017 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) { exit; } /* ====================================================== / Breaking Checks ====================================================== */ // } System Nag messages for license key and upgrades add_action( 'wp_after_admin_bar_render', 'zeroBSCRM_admin_nag_footer', 12 ); // } This will nag if there's anytihng amiss with the settings function zeroBSCRM_admin_nag_footer() { global $zbs; // only nag if paid extensions are active if ( $zbs->extensionCount( true ) > 0 ) { // if transient already set, nothing to do if ( get_transient( 'jpcrm-license-modal' ) ) { return; } // if not in dev mode (as we can't add a key in dev mode currently) if ( ! zeroBSCRM_isLocal( true ) ) { // on one of our pages except settings if ( zeroBSCRM_isAdminPage() && ( ( isset( $_GET['page'] ) && $_GET['page'] != 'zerobscrm-plugin-settings' ) || ( ! isset( $_GET['page'] ) ) ) ) { // retrieve license $license = zeroBSCRM_getSetting( 'license_key' ); if ( isset( $license ) && ! empty( $license ) ) { // License key is empty if ( ( isset( $license['key'] ) && $license['key'] == '' ) || ! isset( $license['key'] ) ) { // build message $message = '<h3>' . __( 'License Key Needed', 'zero-bs-crm' ) . '</h3>'; $message .= '<p>' . __( 'To continue to use CRM extensions you need will need to enter your Jetpack CRM license key.', 'zero-bs-crm' ) . '</p>'; $message .= '<p><a href="' . esc_url_raw( $zbs->urls['licensekeys'] ) . '" class="ui button green" target="_blank">' . __( 'Retrieve License Key', 'zero-bs-crm' ) . '</a>&nbsp;&nbsp;&nbsp;<a href="' . jpcrm_esc_link( $zbs->slugs['settings'] . '&tab=license' ) . '" class="ui button blue">' . __( 'License Settings', 'zero-bs-crm' ) . '</a></p>'; // output modal zeroBSCRM_show_admin_nag_modal( $message ); return; } // License key is not valid if ( $license['validity'] == false && $license['extensions_updated'] != false ) { // $message = __('Your License Key is Incorrect. Please update your license key for this site.', 'zero-bs-crm'); // zeroBSCRM_show_admin_bottom_nag($message); // build message $message = '<h3>' . __( 'License Key Incorrect', 'zero-bs-crm' ) . '</h3>'; $message .= '<p>' . __( 'Please update your license key. You can get your license key from your account and enter it in settings.', 'zero-bs-crm' ) . '</p>'; $message .= '<p><a href="' . $zbs->urls['kblicensefaq'] . '" class="ui button blue" target="_blank">' . __( 'Read about license keys', 'zero-bs-crm' ) . '</a>&nbsp;&nbsp;&nbsp;<a href="' . $zbs->urls['licensekeys'] . '" target="_blank" class="ui button green">' . __( 'Retrieve License Key', 'zero-bs-crm' ) . '</a></p>'; // output modal zeroBSCRM_show_admin_nag_modal( $message ); return; } // Extensions need updating if ( isset( $license['extensions_updated'] ) && $license['extensions_updated'] == false ) { // $message = __('You are running extension versions which are not supported. Please update immediately to avoid any issues.', 'zero-bs-crm'); // zeroBSCRM_show_admin_bottom_nag($message); // build message $message = '<h3>' . __( 'Extension Update Required', 'zero-bs-crm' ) . '</h3>'; if ( $license['validity'] == 'empty' ) { // no license $message .= '<p>' . __( 'You are running extension versions which are not supported. Please enter your license key to enable updates.', 'zero-bs-crm' ) . '</p>'; $message .= '<p><a href="' . $zbs->urls['licensekeys'] . '" class="ui button green" target="_blank">' . __( 'Retrieve License Key', 'zero-bs-crm' ) . '</a>&nbsp;&nbsp;&nbsp;<a href="' . jpcrm_esc_link( $zbs->slugs['settings'] . '&tab=license' ) . '" class="ui button blue">' . __( 'License Settings', 'zero-bs-crm' ) . '</a></p>'; // output modal zeroBSCRM_show_admin_nag_modal( $message ); return; } elseif ( $license['validity'] == false ) { // invalid license $message .= '<p>' . __( 'You are running extension versions which are not supported. Please enter a valid license key to enable updates.', 'zero-bs-crm' ) . '</p>'; $message .= '<p><a href="' . $zbs->urls['kblicensefaq'] . '" class="ui button blue" target="_blank">' . __( 'Read about license keys', 'zero-bs-crm' ) . '</a>&nbsp;&nbsp;&nbsp;<a href="' . $zbs->urls['licensekeys'] . '" target="_blank" class="ui button green">' . __( 'Retrieve License Key', 'zero-bs-crm' ) . '</a></p>'; // output modal zeroBSCRM_show_admin_nag_modal( $message ); return; } else { // valid license // Suppressing here because it came across as a bit intense // $message .= '<p>'.__('You are running extension versions which are not supported. Please update your extension plugins immediately.', 'zero-bs-crm').'</p>'; // $message .= '<p><button class="jpcrm-licensing-modal-set-transient-and-go ui button green" data-href="'.esc_url(admin_url('plugins.php')).'">'.__('Update Plugins','zero-bs-crm').'</button></p>'; } } } } } // / is not local/devmode (normal) } } function zeroBSCRM_show_admin_bottom_nag( $message = '' ) { ?><div class='zbs_nf'> <i class='ui icon warning'></i><?php echo $message; ?> </div> <?php } // Show admin nag modal (e.g. if no license, but extensions) function zeroBSCRM_show_admin_nag_modal( $message = '' ) { if ( ! get_transient( 'jpcrm-license-modal' ) ) { ?> <script type="text/javascript">var jpcrm_modal_message_licensing_nonce = '<?php echo esc_js( wp_create_nonce( 'jpcrm-set-transient-nonce' ) ); ?>';</script> <div class="zbs_overlay" id="jpcrm-modal-message-licensing"> <div class='close_nag_modal'> <span id="jpcrm-close-licensing-modal">x</span> </div> <div class='zbs-message-body'> <img style="max-width:350px;margin-bottom:1.4em" src="<?php echo esc_url( jpcrm_get_logo( false, 'white' ) ); ?>" alt="" style="cursor:pointer;" /> <div class='zbs-message'> <?php echo $message; ?> </div> </div> </div> <?php } } /* ====================================================== License related funcs ====================================================== */ function zeroBSCRM_license_check() { global $zbs; // this should force an update check (and update keys) $pluginUpdater = new zeroBSCRM_Plugin_Updater( $zbs->urls['api'], $zbs->api_ver, 'zero-bs-crm' ); $zbs_transient = new stdClass(); $pluginUpdater->check_update( $zbs_transient ); } // } gets a list of multi site function zeroBSCRM_multisite_getSiteList() { global $wpdb; $sites = array(); $table = $wpdb->prefix . 'blogs'; if ( $wpdb->get_var( "SHOW TABLES LIKE '$table'" ) == $table ) { $sql = "SELECT * FROM $table"; $sites = $wpdb->get_results( $sql ); } // clean up (reduce bandwidth of pass/avoid overburdening) if ( is_array( $sites ) && count( $sites ) > 0 ) { $ret = array(); foreach ( $sites as $site ) { $ret[] = zeroBSCRM_tidy_multisite_site( $site ); } $sites = $ret; } return $sites; // debug print_r(zeroBSCRM_multisite_getSiteList()); exit(); /* we don't need all this [blog_id] => 1 [site_id] => 1 [domain] => multisitetest.local [path] => / [registered] => 2018-08-10 15:29:31 [last_updated] => 2018-08-10 15:30:43 [public] => 1 [archived] => 0 [mature] => 0 [spam] => 0 [deleted] => 0 [lang_id] => 0 */ } function zeroBSCRM_tidy_multisite_site( $siteRow = array() ) { if ( isset( $siteRow->blog_id ) ) { // active if not archived, spam, deleted $isActive = 1; if ( $siteRow->archived ) { $isActive = -1; } if ( $siteRow->spam ) { $isActive = -1; } if ( $siteRow->deleted ) { $isActive = -1; } return array( // not req. always same?? 'site_id' => $siteRow->site_id, 'blog_id' => $siteRow->blog_id, 'domain' => $siteRow->domain, 'path' => $siteRow->path, // active if not archived, spam, deleted 'active' => $isActive, // log these (useful) 'deleted' => $siteRow->deleted, 'archived' => $siteRow->archived, 'spam' => $siteRow->spam, 'lang_id' => $siteRow->lang_id, // not req. / not useful // 'mature' => $siteRow->mature, // 'public' => $siteRow->public, // 'registered' => $siteRow->registered, // 'last_updated' => $siteRow->last_updated, ); } return false; } /* ====================================================== / License related funcs ====================================================== */
projects/plugins/crm/includes/jpcrm-templating.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * Copyright 2021 Automattic */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /** * Retrieve Template file path * * This checks existence in /wp-content/theme/{active_theme}/jetpack-crm/* * ... and if doesn't exist, falls back to /wp-content/plugin/{this_plugin}/templates/* * * @param string template_file - the file path _after_ the /templates/ directory * * @return string|bool false - the full file path to template if exists, false if not */ function jpcrm_template_file_path( $template_file = '' ) { if ( !empty( $template_file ) ){ global $zbs; // Search for template file in theme folder. $template_file_path = locate_template( array( $zbs->template_path . '/' . $template_file, $template_file ) ); // check any other externally added locations // default to our core template if no theme or external variant if ( !$template_file_path ){ // see if we have any other locations // note this'll effectively 'pick' the first added & viable in this situation. $extra_template_locations = apply_filters( 'jpcrm_template_locations', array() ); if ( is_array( $extra_template_locations ) ){ foreach ( $extra_template_locations as $location ){ if ( file_exists( $location[ 'path' ] . $template_file ) ){ // use this template $template_file_path = $location[ 'path' ] . $template_file; break; } } } // no theme template // no filter-given template // default to core version: if ( empty( $template_file_path ) || !$template_file_path ){ $template_file_path = ZEROBSCRM_PATH . 'templates/' . $template_file; } } // do we have a valid template? if ( !empty( $template_file_path ) && file_exists( $template_file_path ) ){ return $template_file_path; } } return false; } /** * Retrieve Template file * * This checks existence in /wp-content/theme/{active_theme}/jetpack-crm/* * ... and if doesn't exist, falls back to /wp-content/plugin/{this_plugin}/templates/* * * @param string template_file - the file path _after_ the /templates/ directory * @param bool load - if true will include * * @return string {contents_of_template_file} */ function jpcrm_retrieve_template( $template_file = '', $load = true ) { $template_contents = ''; if ( !empty( $template_file ) ){ // retrieve path $template_file_path = jpcrm_template_file_path( $template_file ); // do we have a valid template? if ( !empty( $template_file_path ) && file_exists( $template_file_path ) ){ // Prevent file traversal attacks. $allowed_template_paths = jpcrm_get_allowed_template_paths(); if ( ! jpcrm_is_allowed_path( $template_file_path, $allowed_template_paths ) ) { return __( 'Unable to load template.', 'zero-bs-crm' ); } // load or return contents if ( $load ){ // load the file directly (no support for require_once here, expand via params if needed) include $template_file_path; } else { // retrieve contents if (function_exists('file_get_contents')){ try { $template_contents = file_get_contents( $template_file_path ); return $template_contents; } catch (Exception $e){ // Nada // basic dialog _doing_it_wrong( __FUNCTION__, sprintf( '<code>%s</code> could not be retrieved.', esc_html( $template_file_path ) ), '4.5.0' ); // add admin notification if ( zeroBSCRM_isZBSAdminOrAdmin() ){ jpcrm_template_missing_notification( $template_file ); } } } } } else { // if current user is an admin, let's return a useful debug string if ( zeroBSCRM_isZBSAdminOrAdmin() ){ // add admin notification jpcrm_template_missing_notification( $template_file ); // return explainer string (note this'll get rolled into PDF/page output) return sprintf( __( 'Failed to retrieve <code>%s</code> - Template file does not exist.', 'zero-bs-crm' ), $template_file ); } else { // non-admin user retrieved a non-existent template. Let's return blank // _doing_it_wrong( __FUNCTION__, sprintf( '<code>%s</code> does not exist.', $template_file ) ); } } } // no dice return ''; } /** * Returns an array of allowed template paths. */ function jpcrm_get_allowed_template_paths() { global $zbs; $allowed_template_paths = array( 'default' => ZEROBSCRM_PATH . 'templates/', 'theme' => get_stylesheet_directory() . '/' . $zbs->template_path . '/', 'template' => get_template_directory() . '/' . $zbs->template_path . '/', 'theme-compat' => ABSPATH . WPINC . '/theme-compat/' . $zbs->template_path . '/', ); return $allowed_template_paths; } /** * Attempts to find variants of a template file and returns as an array * * @param string original_template_path - original template location for template, e.g. 'invoices/invoice-pdf.html' * * @return array */ function jpcrm_retrieve_template_variants( $original_template_path = '' ) { global $zbs; $variants = array(); if ( !empty( $original_template_path ) ){ // get extension (e.g. html) $file_extension = pathinfo( $original_template_path, PATHINFO_EXTENSION ); // split out pre-extension path $pre_extension_path = substr( $original_template_path, 0, ( strlen( $original_template_path ) - ( strlen( $file_extension ) + 1 ) ) ); // check in locations: // 1. theme/jetpack-crm/* // 2. core/templates/* // Finally, pass back via hook, to allow client portal pro to append // to provide some form of protection here, we only allow zbs admins to do this // (as we're iterating through directories) if ( !zeroBSCRM_isZBSAdminOrAdmin() ) return false; // Seeks out template files matching a pattern (in wp theme directories, and our core template directory) // Adapted from locate_template: https://core.trac.wordpress.org/browser/tags/5.8/src/wp-includes/template.php#L697 $template_locations = array( array( 'name' => __( 'Theme directory', 'zero-bs-crm' ), 'path' => get_stylesheet_directory() . '/' . $zbs->template_path . '/', ), array( 'name' => __( 'Template Path directory', 'zero-bs-crm' ), 'path' => get_template_directory() . '/' . $zbs->template_path . '/', ), array( 'name' => __( 'Theme Compat directory', 'zero-bs-crm' ), 'path' => ABSPATH . WPINC . '/theme-compat/' . $zbs->template_path . '/', ), array( 'name' => __( 'Core Plugin', 'zero-bs-crm' ), 'path' => ZEROBSCRM_PATH . 'templates/', ), ); // we flip the array, so that top-down preference is maintained $template_locations = array_reverse( $template_locations ); // pass our viable locations through a filter so extensions can append their directories. $template_locations = apply_filters( 'jpcrm_template_locations', $template_locations ); // cycle through locations and seek out templates if ( is_array( $template_locations ) ) { foreach ( $template_locations as $directory ){ // locate matching files $template_files = glob( $directory['path'] . $pre_extension_path . '*.' . $file_extension); // determine viable if ( is_array( $template_files ) ){ foreach ( $template_files as $file_path ) { // (dirty) replace $directory to give clean template_path $path = str_replace( $directory['path'], '', $file_path ); $variants[ $path ] = array( 'full_path' => $file_path, 'filename' => basename( $file_path ), 'origin' => $directory['name'], 'name' => '' // tbc ); } } } } } // return passed through filter so the likes of client portal pro could append return apply_filters( 'jpcrm_template_variants', $variants, $original_template_path ); } /** * Adds an admin notice for missing template * * @param string template_file - template file location for template, e.g. 'invoices/invoice-pdf.html' * * @return bool - true (if outstanding notification), false if no notifcation */ function jpcrm_template_missing_notification( $template_file = '' ) { if ( !empty( $template_file ) ){ global $zbs; // generate a transient key to use $transient_key = 'jpcrm-missing-' . $zbs->DAL->makeSlug( $template_file ); // check not fired within past week $existing_transient = get_transient( $transient_key ); if ( $existing_transient ) { return true; } // add notice & transient zeroBSCRM_notifyme_insert_notification( get_current_user_id(), -999, -1, 'missing.template', $template_file ); set_transient( $transient_key, $template_file, HOUR_IN_SECONDS * 24 * 7 ); return true; } return false; } /* * Function to return html file related to PDF * we've done away with the need for this via the jpcrm_templating_placeholders class. */ function zeroBSCRM_retrievePDFTemplate($template='default'){ zeroBSCRM_DEPRECATEDMSG('zeroBSCRM_retrievePDFTemplate was deprecated in v4.5.0, please use the jpcrm_templating_placeholders class'); return ''; } /* * Function to return html file of a quote template * we've done away with the need for this via the jpcrm_templating_placeholders class. */ function zeroBSCRM_retrieveQuoteTemplate($template='default'){ zeroBSCRM_DEPRECATEDMSG('zeroBSCRM_retrieveQuoteTemplate was deprecated in v4.5.0, please use the jpcrm_templating_placeholders class'); return ''; } /* WH Notes: There was all this note-age from old vers: Customer Meta Translation - 2.90 #}PUT THE EMAIL THROUGH THE FILTERS (FOR THE #FNAME# NEW CUSTOMER TAGS do prepare_email_{trigger}_template #} WH: Let's do this as filters :) ... but I think these funcs needed a bit of a clean up ... should be backward compatible, and safe to stick to using the filter: zeroBSCRM_replace_customer_placeholders ... MC2.0 uses this indirectly through 'zerobscrm_mailcamp_merge' and 'zerobscrm_mailcamp_merge_text' ... so be careful with it ... v3.0 I've made them DAL3 safe, not fully refactored as approaching deadline */ // Note: this function is deprecated from ~4.3.0, please use $zbs->get_templating()->replace_placeholders() function zeroBSCRM_replace_customer_placeholders($html = '', $cID = -1, $contactObj = false){ if ($cID > 0 && $html != ''){ global $zbs; if (is_array($contactObj) && isset($contactObj['id'])) $contact = $contactObj; else { if ($zbs->isDAL3()) // v3.0 $contact = $zbs->DAL->contacts->getContact($cID,array( 'withCustomFields' => true, // need any of these? 'withQuotes' => false, 'withInvoices' => false, 'withTransactions' => false, 'withLogs' => false, 'withLastLog' => false, 'withTags' => false, 'withCompanies' => false, 'withOwner' => false, 'withValues' => false, )); else // pre v3.0 $contact = zeroBS_getCustomerMeta($cID); } // replace all placeholders :) $newHTML = $html; foreach ($contact as $k => $v){ $newHTML = str_replace('##CONTACT-'.strtoupper($k) . '##' ,$v, $newHTML); } $html = $newHTML; } return $html; } add_filter( 'zerobscrm_quote_html_generate','zeroBSCRM_replace_customer_placeholders', 20, 2); // as above, but replaces with 'demo data' function zeroBSCRM_replace_customer_placeholders_demo( $html = '' ){ if ( !empty( $html ) ){ global $zbs; // load templater $placeholder_templating = $zbs->get_templating(); // assigned-to-* $replacements = array( 'assigned-to-name' => __( 'Demo Contact Owner', 'zero-bs-crm' ), 'assigned-to-email' => 'demo.contact.owner@example.com', 'assigned-to-username' => 'demo.contact.owner.username', 'assigned-to-mob' => '999 999 999', ); // return the example, with demo contact fields and assignments replaced return $placeholder_templating->replace_placeholders( array( 'global', 'contact' ), $html, $replacements, array( ZBS_TYPE_CONTACT => zeroBS_getDemoCustomer() ), true ); } return $html; }
projects/plugins/crm/includes/ZeroBSCRM.DAL3.ObjectLayer.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V3.0+ * * Copyright 2020 Automattic * * Date: 14/01/19 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /** * ZBS DAL >> Object Class * * @author Woody Hayday <hello@jetpackcrm.com> * @version 2.0 * @access public * @see https://jetpackcrm.com/kb */ class zbsDAL_ObjectLayer { protected $objectType = -1; // e.g. ZBS_TYPE_CONTACT protected $objectModel = -1; // array('DBFIELD(e.g. zbs_owner'=>array('Local field (e.g. owner)','format (int)')) // formats: // int = (int) // uts = uts + converted to locale date _datestr // protected $objectTableName = -1; protected $objectFieldCSV = -1; // assumes model wont change mid-load :) protected $include_in_templating = false; // if true, object types fields will be accessible in templating // hardtyped list of types this object type is commonly linked to // Note that as of 4.1.1 this mechanism is only used via DAL3.Export to know what typical links to look for, it is not a hard rule, or currently respected anywhere else. // e.g. Invoice object type may be commonly linked to 'contact' or 'company' object types protected $linkedToObjectTypes = array(); function __construct($args=array()) { #} =========== LOAD ARGS ============== $defaultArgs = array( //'tag' => false, ); foreach ($defaultArgs as $argK => $argV){ $this->$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $this->$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$this->$argK = $newData;} else { $this->$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= // check objectModel + err if not legit // ==== AUTO TRANSLATION // Any labels passed with $objectModel need passing through translation :) if (is_array($this->objectModel)) foreach ($this->objectModel as $key => $fieldArr){ if (isset($fieldArr['label'])) $fieldArr['label'] = __($fieldArr['label'],'zero-bs-crm'); if (isset($fieldArr['placeholder'])) $fieldArr['placeholder'] = __($fieldArr['placeholder'],'zero-bs-crm'); if (isset($fieldArr['options']) && is_array($fieldArr['options'])){ $newOptions = array(); foreach ($fieldArr['options'] as $o){ $newOptions[] =__($o,'zero-bs-crm'); } $fieldArr['options'] = $newOptions; unset($newOptions); } } } // return core vars public function objTableName(){ return $this->objectTableName; } public function objType(){ return $this->objectType; } public function objModel($appendCustomFields=false){ return $this->objectModel; } public function linkedToObjectTypes(){ return $this->linkedToObjectTypes; } public function is_included_in_templating(){ return $this->include_in_templating; } // return the objModel with additional custom fields as if they were db-ready fields // Note: This is a bridging function currently only used in DAL3.Exports.php, // ... a refactoring of the dbmodel+customfields+globalfieldarrays is necessary pre v4.0 // ... in mean time, avoid usage in the initial field setup linkages // // Note: Also the format of the custom field arr will differ from the objmodel field arr's // ... to distinguish, look for attribute 'custom-field' // ... but probably best to generally avoid usage of this function until reconciled the above note. // see gh-253 public function objModelIncCustomFields(){ global $zbs; $customFields = false; $model = $this->objectModel; // turn ZBS_TYPE_CONTACT (1) into "contact" $typeStr = $this->DAL()->objTypeKey($this->objectType); // Direct retrieval v3+ if (!empty($typeStr)) $customFields = $zbs->DAL->setting('customfields_'.$typeStr,array()); // if is an obj which has custom field capacity: if (isset($customFields) && is_array($customFields)){ // add to model foreach ($customFields as $fieldKey => $field){ // Unpacks csv options and sets 'custom-field' attr // Adds it to arr // ignores potential collisions (e.g. custom field with key 'status'), these should be blocked by UI $model[$fieldKey] = zeroBSCRM_customFields_processCustomField($field); } } // if obj also has addresses, check for address custom fields // Adapted from DAL3.Fields.php // see gh-253 if ($this->includesAddressFields()){ #} Retrieve $addrCustomFields = $zbs->DAL->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_ADDRESS)); #} Addresses if (is_array($addrCustomFields) && count($addrCustomFields) > 0){ $cfIndx = 1; foreach ($addrCustomFields as $fieldKey => $field){ // unpacks csv options and sets 'custom-field' attr $fieldO = zeroBSCRM_customFields_processCustomField($field); // splice them in to the end of the e.g. 'second address' group // Addr1 // for this specifically, we also add '[area]' $fieldO['area'] = 'Main Address'; // find index $mainAddrIndx = -1; $i = 0; foreach ($model as $k => $f) { if (isset($f['area']) && $f['area'] == 'Main Address') $mainAddrIndx = $i; $i++; } // splice $mainAddrIndx++; // req $model = array_merge( array_slice( $model, 0, $mainAddrIndx, true ), array( 'addr_'.$fieldKey => $fieldO ), array_slice( $model, $mainAddrIndx, null, true ) ); // Addr2 // change area $fieldO['area'] = 'Second Address'; // find index $secAddrIndx = -1; $i = 0; foreach ($model as $k => $f) { if (isset($f['area']) && $f['area'] == 'Second Address') $secAddrIndx = $i; $i++; } // splice $secAddrIndx++; // req $model = array_merge( array_slice( $model, 0, $secAddrIndx, true ), array( 'secaddr_'.$fieldKey => $fieldO ), array_slice( $model, $secAddrIndx, null, true ) ); } } } return $model; } /** * returns bool depending on whether object has custom fields setup * * * @return bool */ public function hasCustomFields($includeHidden=false){ global $zbs; $fieldsToHide = array(); // turn ZBS_TYPE_CONTACT (1) into "contact" $typeStr = $this->DAL()->objTypeKey($this->objectType); // any to hide? if (!$includeHidden){ $fieldHideOverrides = $zbs->settings->get('fieldhides'); if (isset($fieldHideOverrides[$typeStr])) $fieldsToHide = $fieldHideOverrides[$typeStr]; } // Direct retrieval v3+ if (!empty($typeStr)) { $customFields = $zbs->DAL->setting('customfields_'.$typeStr,array()); // got custom fields? if (isset($customFields) && is_array($customFields)){ // cycle through custom fields foreach ($customFields as $fieldKey => $field){ // hidden? if ($includeHidden || !in_array($fieldKey, $fieldsToHide)){ return true; } } } } return false; } /** * returns custom fields for an object * .. optionally excluding hidden (from fieldsort page) * * * @return array custom fields */ public function getCustomFields($includeHidden=false){ global $zbs; $returnCustomFields = array(); $fieldsToHide = array(); // turn ZBS_TYPE_CONTACT (1) into "contact" $typeStr = $this->DAL()->objTypeKey($this->objectType); // any to hide? if (!$includeHidden){ $fieldHideOverrides = $zbs->settings->get('fieldhides'); if (isset($fieldHideOverrides[$typeStr])) $fieldsToHide = $fieldHideOverrides[$typeStr]; } // Direct retrieval v3+ if (!empty($typeStr)) { $customFields = $zbs->DAL->setting('customfields_'.$typeStr,array()); // got custom fields? if (isset($customFields) && is_array($customFields)){ // cycle through custom fields foreach ($customFields as $fieldKey => $field){ // hidden? if ( $includeHidden || !$fieldsToHide || ( is_array( $fieldsToHide ) && ! in_array( $fieldKey, $fieldsToHide ) ) ) { // Unpacks csv options and sets 'custom-field' attr // Adds it to arr $returnCustomFields[$fieldKey] = $field; } } } } return $returnCustomFields; } public function includesAddressFields(){ if (isset($this->objectIncludesAddresses)) return true; return false; } public function DAL(){ // hmm this is reference to a kind of 'parent' but not parent class. not sure best reference here. // (to get back to $zbs->DAL) // ... this allows us to centralise the reference in all children classes, at least, but probs a more oop logical way to do this // is mostly helpers like buildWhere etc. but also other DAL funcs. global $zbs; return $zbs->DAL; } // internal sql helpers private function objFieldCSV(){ // assumes model wont change :) if ($this->objectFieldCSV == -1 || $this->objectFieldCSV == ''){ $x = ''; if (is_array($this->objectModel)) foreach ($this->objectModel as $k => $v) { if (!empty($x)) $x .= ','; $x .= $k; } $this->objectFieldCSV = $x; } return $this->objectFieldCSV; } // basic get any (first 10 paged) public function get($args=array()){ // hmm this is reference to a kind of 'parent' but not parent class. not sure best reference here. // (to get back to $zbs->DAL) global $zbs; #} =========== LOAD ARGS ============== $defaultArgs = array( 'sortByField' => 'ID', 'sortOrder' => 'ASC', 'page' => 0, 'perPage' => 10, ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= #} ========== CHECK FIELDS ============ // always ignore owner for now (settings global) $ignoreowner = true; #} ========= / CHECK FIELDS =========== global $ZBSCRM_t,$wpdb; $wheres = array('direct'=>array()); $whereStr = ''; $additionalWhere = ''; $params = array(); $res = array(); #} Build query $query = "SELECT ".$this->objFieldCSV." FROM ".$this->objectTableName; #} ============= WHERE ================ #} ============ / WHERE =============== #} Build out any WHERE clauses $wheresArr= $zbs->DAL2->buildWheres($wheres,$whereStr,$params); $whereStr = $wheresArr['where']; $params = $params + $wheresArr['params']; #} / Build WHERE #} Ownership v1.0 - the following adds SITE + TEAM checks, and (optionally), owner $params = array_merge($params,$zbs->DAL2->tools-->ownershipQueryVars($ignoreowner)); // merges in any req. $ownQ = $zbs->DAL2->ownershipSQL($ignoreowner); if (!empty($ownQ)) $additionalWhere = $zbs->DAL2->spaceAnd($additionalWhere).$ownQ; // adds str to query #} / Ownership #} Append to sql (this also automatically deals with sortby and paging) $query .= $zbs->DAL2->buildWhereStr($whereStr,$additionalWhere) . $zbs->DAL2->buildSort($sortByField,$sortOrder) . $zbs->DAL2->buildPaging($page,$perPage); try { #} Prep & run query $queryObj = $zbs->DAL2->prepare($query,$params); $potentialRes = $zbs->DAL2->get_results($queryObj, OBJECT); } catch (Exception $e){ #} General SQL Err $zbs->DAL2->catchSQLError($e); } #} Interpret results (Result Set - multi-row) if (isset($potentialRes) && is_array($potentialRes) && count($potentialRes) > 0) { #} Has results, tidy + return foreach ($potentialRes as $resDataLine) { // tidy (simple) $resArr = $this->tidy($resDataLine); $res[] = $resArr; } } return $res; } // takes $this->objectModel and converts any applicable fields // into old-form (legacy) $globalFieldArr (as used to be hard-typed in Fields.php Pre DAL3) #} #FIELDLOADING public function generateFieldsGlobalArr(){ if (isset($this->objectModel) && is_array($this->objectModel)){ // build it $retArr = array(); // cycle through fields foreach ($this->objectModel as $dal3key => $fieldModel){ // if they have 'input_type' then they're designed to be loaded into the global field var // .. if not, they're DB-only / loaded elsewhere stuff if (is_array($fieldModel) && isset($fieldModel['input_type'])){ // should be loaded. Build it. $retArr[$dal3key] = array(); // Old format as follows: /*'fname' => array( 'text', // input type __('First Name',"zero-bs-crm"), // label 'e.g. John', // placeholder // extra options: +- 'options'=>array('Mr', 'Mrs', 'Ms', 'Miss', 'Dr', 'Prof','Mr & Mrs'), 'essential' => true 'area'=>__('Main Address',"zero-bs-crm"), 'migrate'=>'addresses' 'opt'=>'secondaddress', ) */ // map them in // input type = [0] $retArr[$dal3key][0] = $fieldModel['input_type']; // input label = [1] $retArr[$dal3key][1] = ''; if ( isset( $fieldModel['label'] ) ) { $retArr[$dal3key][1] = __( $fieldModel['label'], 'zero-bs-crm' ); $second_address_label = zeroBSCRM_getSetting( 'secondaddresslabel' ); if ( empty( $second_address_label ) ) { $second_address_label = __( 'Second Address', 'zero-bs-crm' ); } if( !empty( $fieldModel['area'] ) && $fieldModel['area'] == 'Second Address' ) { $retArr[$dal3key][1] .= ' (' . esc_html( $second_address_label ) . ')'; } } // input placeholder = [2] $retArr[$dal3key][2] = (isset($fieldModel['placeholder'])) ? $fieldModel['placeholder'] : ''; // extra options (all key-referenced) //if (isset($fieldModel['options'])) $retArr[$dal3key]['options'] = $fieldModel['options']; // [options] == [3] in old global obj model world if (isset($fieldModel['options'])) $retArr[$dal3key][3] = $fieldModel['options']; if (isset($fieldModel['essential'])) $retArr[$dal3key]['essential'] = $fieldModel['essential']; if (isset($fieldModel['area'])) $retArr[$dal3key]['area'] = $fieldModel['area']; if (isset($fieldModel['migrate'])) $retArr[$dal3key]['migrate'] = $fieldModel['migrate']; if (isset($fieldModel['opt'])) $retArr[$dal3key]['opt'] = $fieldModel['opt']; if (isset($fieldModel['nocolumn'])) $retArr[$dal3key]['nocolumn'] = $fieldModel['nocolumn']; if (isset($fieldModel['default'])) $retArr[$dal3key]['default'] = $fieldModel['default']; // should all have (where different from dal3key): if (isset($fieldModel['dal1key'])) $retArr[$dal3key]['dal1key'] = $fieldModel['dal1key']; } } // / foreach field // return built fieldGlobalArr (should mimic old DAL1/2 Fields.php) return $retArr; } return array(); } // returns a translation matrix of DAL1key => DAL3key, where possible, using 'dal1key' attribute in data model public function getDAL1toDAL3ConversionMatrix(){ $ret = array(); if (isset($this->objectModel) && is_array($this->objectModel)){ //foreach ($arraySource as $k => $v){ foreach ($this->objectModel as $v3Key => $fieldObj){ if (isset($fieldObj['dal1key'])){ $ret[$fieldObj['dal1key']] = $v3Key; } } } return $ret; } // generic get X (by ID) // designed to be overriden by each child. public function getSingle($ID=-1){ return false; } /** * Helper to retrieve Custom Fields with Data for an object * * @return array summarised custom fields including values, for object */ public function getSingleCustomFields($ID=-1,$includeHidden=false){ global $zbs; if ($ID > 0){ // retrieve custom fields $customFields = $this->getCustomFields($includeHidden); // retrieve object data $objectData = $this->getSingle($ID); if (!is_array($objectData)) $objectData = array(); // Build return $return = array(); if (is_array($customFields)) foreach($customFields as $k => $v){ $return[] = array( 'id' => $v[3], 'name' => $v[1], 'value' => (isset($objectData[$v[3]]) ? $objectData[$v[3]] : ''), 'type' => $v[0] ); } return $return; } return false; } // generic get X (by IDs) // designed to be overriden by each child. public function getIDList($IDs=array()){ return false; } // generic get X (EVERYTHING) // designed to be overriden by each child. // expect heavy load! public function getAll($IDs=array()){ return false; } // generic get count of (EVERYTHING) // designed to be overriden by each child. public function getFullCount(){ return false; } // Ownership - simplistic GET owner of obj public function getOwner($objID=-1){ // check if ($objID < 1) return false; return $this->DAL()->getObjectOwner(array( 'objID' => $objID, 'objTypeID' => $this->objectType )); } // Ownership - simplistic SET owner of obj public function setOwner($objID=-1,$ownerID=-1){ // check if ($objID < 1 || $ownerID < 1) return false; // set owner return $this->DAL()->setObjectOwner(array( 'objID' => $objID, 'objTypeID' => $this->objectType, 'ownerID' => $ownerID )); } /** * Wrapper, use $this->updateMeta($objid,$key,$val) for easy update of obj meta :) * (Uses built in type) * * @param string key * @param string value * * @return bool result */ public function updateMeta($objid=-1,$key='',$val=''){ if (!empty($key) && isset($this->objectType) && $this->objectType > 0){ // && !empty($val) return $this->DAL()->addUpdateMeta(array( 'data' => array( 'objid' => $objid, 'objtype' => $this->objectType, 'key' => $key, 'val' => $val ) )); } return false; } /** * tidy's the object from wp db into clean array * ... also converts uts to local datetime etc. politely * * @param array $obj (DB obj) * * @return array (clean obj) */ public function tidy($obj=false){ global $zbs; $res = false; if (isset($obj->ID)){ // THESE must be standard :) $res = array(); $res['id'] = (int)$obj->ID; /* `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, */ $res['owner'] = (int)$obj->zbs_owner; // cycle through + pull in foreach ($this->objectModel as $dbkey => $val){ // if not already set if (!isset($res[$val['fieldname']])){ switch ($val['format']){ case 'int': $res[$val['fieldname']] = (int)$obj->$dbkey; break; case 'uts': // normal return $res[$val['fieldname']] = (int)$obj->$dbkey; // auto add locale str $res[$val['fieldname'].'_datestr'] = zeroBSCRM_locale_utsToDatetime($obj->$dbkey); break; default: $res[$val['fieldname']] = $obj->$dbkey; break; } } } } // if is obj id return $res; } /** * Offers generic custom field tidying, where an obj and it's cleaned version are passed * ... centralised here as all objects (which have custom fields) had this repeated * * @param int $objTypeID e.g. 1 = ZBS_TYPE_CONTACT * @param obj $obj (DB obj) * @param array $res (tidied DB obj) * @param bool $includeAddrCustomFields (whether or not to also probe + tidy custom fields for addrs (mainly contacts + company tidying)) * * @return array (clean obj) */ public function tidyAddCustomFields($objTypeID=ZBS_TYPE_CONTACT,$obj=false,$res=false,$includeAddrCustomFields=false){ // vague catch if ($obj == false || $res == false) return $res; #} Retrieve any cf $customFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>$objTypeID)); if (is_array($customFields)) foreach ($customFields as $cK => $cF){ // custom field (e.g. 'third name') it'll be passed here as 'third-name' // ... problem is mysql does not like that :) so we have to chage here: // in this case we REVERSE this: prepend cf's with cf_ and we switch - for _ // ... by using $cKey below, instead of cK $cKey = 'cf_'.str_replace('-','_',$cK); $res[$cK] = ''; // if normal if (isset($obj->$cK)) $res[$cK] = $this->stripSlashes($obj->$cK); // if cf if (isset($obj->$cKey)) $res[$cK] = $this->stripSlashes($obj->$cKey); // if date_type, format if ( isset($cF[0] ) && $cF[0] === 'date') { // make a _date field if ( '' === $res[$cK] ) { $res[$cK.'_cfdate'] = ''; } else { $res[$cK.'_cfdate'] = zeroBSCRM_date_i18n( -1, $res[$cK], false, true ); $res[$cK.'_datetime_str'] = jpcrm_uts_to_datetime_str( $res[$cK] ); $res[$cK.'_date_str'] = jpcrm_uts_to_date_str( $res[$cK] ); } } } #} Retrieve addr custfiedls $addrCustomFields = $this->DAL()->getActiveCustomFields(array('objtypeid'=>ZBS_TYPE_ADDRESS)); if (is_array($addrCustomFields)) foreach ($addrCustomFields as $cK => $cF){ // v2: //$cKN = (int)$cK+1; //$cKey = 'addr_cf'.$cKN; //$cKey2 = 'secaddr_cf'.$cKN; // v3: //$cKey = 'addr_'.$cK; //$cKey2 = 'secaddr_'.$cK; // v4: // These keys were causing alias collisions in mysql when keys ended up like 'addr_house-type' // ... where the sort couldn't be fired for that key due to the - character // ... so from 4.0.7+ we processed these adding a prefix `addrcf_` (and `secaddrcf_`) and replacing - for _ $cKey = 'addrcf_'.str_replace('-','_',$cK); $cKey2 = 'secaddrcf_'.str_replace('-','_',$cK); // Note we still want to return as `addr_house-type` not `addrcf_house_type` $res['addr_'.$cK] = ''; $res['secaddr_'.$cK] = ''; // retrieve if (isset($obj->$cKey)) $res['addr_'.$cK] = $this->stripSlashes($obj->$cKey); if (isset($obj->$cKey2)) $res['secaddr_'.$cK] = $this->stripSlashes($obj->$cKey2); // if date_type, format if (isset($cF[0]) && $cF[0] == 'date'){ // make a _date field if ( isset( $res['addr_' . $cK] ) ) { $res['addr_' . $cK . '_cfdate'] = zeroBSCRM_date_i18n( -1, $res['addr_' . $cK], false, true ); $res['addr_' . $cK . '_datetime_str'] = jpcrm_uts_to_datetime_str( $res['addr_' . $cK] ); $res['addr_' . $cK . '_date_str'] = jpcrm_uts_to_date_str( $res['addr_' . $cK] ); } if ( isset( $res['secaddr_' . $cK] ) ) { $res['secaddr_' . $cK . '_cfdate'] = zeroBSCRM_date_i18n( -1, $res['secaddr_' . $cK], false, true ); $res['secaddr_' . $cK . '_datetime_str'] = jpcrm_uts_to_datetime_str( $res['secaddr_' . $cK] ); $res['secaddr_' . $cK . '_date_str'] = jpcrm_uts_to_date_str( $res['secaddr_' . $cK] ); } } } return $res; } /** * this takes a dataArray passed for update/insert and works through * the fields, checking against the obj model for compliance * initially this only includes max_len checks as fix for gh-270 * * @param array $dataArr (pre-insert obj) * * @return bool */ public function wpdbChecks($dataArr=array()){ // req. global $zbs; $checksFailed = array(); if ($zbs->isDAL3() && $this->objectType > 0 && is_array($dataArr) && isset($this->objectDBPrefix)){ // new return $retArr = $dataArr; foreach ($dataArr as $key => $val){ // use $objectDBPrefix to retrieve the objmodel key // zbsi_id_override => id_override $fieldKey = str_replace($this->objectDBPrefix,'', $key); // max length check? if (!empty($fieldKey) && isset($this->objectModel[$fieldKey]) && isset($this->objectModel[$fieldKey]['max_len'])){ // check length if (strlen($val) > $this->objectModel[$fieldKey]['max_len']){ // > max_len // .. abbreviate $retArr[$key] = substr($val, 0, ($this->objectModel[$fieldKey]['max_len']-3)).'...'; // Add notice $label = $fieldKey; if (isset($this->objectModel[$fieldKey]['label'])) $label = $this->objectModel[$fieldKey]['label']; $msg = __('The value for the field:','zero-bs-crm').' "'.$label.'" '.__('was too long and has been abbreviated','zero-bs-crm'); $zbs->DAL->addError(305,$this->objectType,$msg,$fieldKey); } } } // return (possibly modified arr) return $retArr; } return $dataArr; } /** * this takes the current database insert/update or any object * and validates it against the dbmodel for that objtype for uniqueness * e.g. if a field in the dbmodel has force_unique, it's checked that that field is in fact unique, * returning false if so * Note: Blanks side-step this check if attribute 'can_be_blank', but are still are still subject to 'not_empty' check * ... (verifyNonEmptyValues) if that attribute is specified in the obj model * * This'll also add an error to the stack, if it can * * @param array $obj (clean obj) * * @return bool */ public function verifyUniqueValues($objArr=array(),$id=-1){ // req. global $zbs; $checksFailed = array(); if ($zbs->isDAL3() && $this->objectType > 0 && is_array($objArr)){ // DAL3+ we now have proper object models, so can check for 'force_unique' flags against field // get an obj model, if set // note: importantly, v2->v3 migration in v3.0 uses DAL2 objModel drop-in function here, so be aware this may be used during v2->v3 migration $potentialModel = $zbs->DAL->objModel($this->objectType); // will be objlayer model if set if (is_array($potentialModel)){ // cycle through each field verify where necessary foreach ($potentialModel as $fieldKey => $fieldDetail){ // there's a few we ignore :) if (in_array($fieldKey, array('ID','zbs_site','zbs_team','zbs_owner'))) continue; // verify unique fields are unique + unused // note. If 'can_be_blank' is also set against the field, blank doesn't get checked here if (isset($fieldDetail['force_unique']) && $fieldDetail['force_unique']){ if (isset($fieldDetail['can_be_blank']) && $fieldDetail['can_be_blank'] && empty($objArr[$fieldKey])){ // field is blank, and is allowed to be! } else { // needs to ensure field is unique. // get existing id, if set $whereArr = array(); // colname zbsc_email $whereArr['uniquecheck'] = array($fieldDetail['fieldname'],'=','%s',$objArr[$fieldKey]); $potentialID = $zbs->DAL->getFieldByWHERE(array( 'objtype' => $this->objectType, // ZBS_TYPE_CONTACT 'colname' => 'ID', 'where' => $whereArr, 'ignoreowner' => true)); // catch dupes (exists, but it's not this) if ($potentialID > 0 && $potentialID != $id){ // pass back the failed field. $checksFailed[$fieldKey] = $fieldDetail; } } } } // / foreach } // / if has model } // got any fails? if (count($checksFailed) > 0) { // can't update, some non-uniques. // set reason msg if ( is_array( $checksFailed ) ) { foreach ( $checksFailed as $fieldKey => $fieldDetail ) { $fk = $fieldKey; if ( isset( $fieldDetail['label'] ) ) { $fk = $fieldDetail['label']; } if( $fk === 'id_override' ) { $msg = __('Duplicated reference. The reference should be unique', 'zero-bs-crm'); } else { $msg = __('The value for the field:', 'zero-bs-crm') . ' "' . $fk . '" ' . __('was not unique (exists)', 'zero-bs-crm'); } $zbs->DAL->addError( 301, $this->objectType, $msg, $fieldKey ); } } // return fail return false; } // / fails unique field verify return true; } /** * this takes the current database insert/update or any object * and validates it against the dbmodel for that objtype for empties * e.g. if a field in the dbmodel has not_empty, it's checked that that field is in fact not empty * returning false if so * Note this is inverse to 'can_be_blank' flag * * This'll also add an error to the stack, if it can * * @param array $obj (clean obj) * * @return bool */ public function verifyNonEmptyValues($objArr=array()){ // req. global $zbs; $checksFailed = array(); if ($zbs->isDAL3() && $this->objectType > 0 && is_array($objArr)){ // DAL3+ we now have proper object models, so can check for 'force_unique' flags against field // get an obj model, if set // note: importantly, v2->v3 migration in v3.0 uses DAL2 objModel drop-in function here, so be aware this may be used during v2->v3 migration $potentialModel = $zbs->DAL->objModel($this->objectType); // will be objlayer model if set if (is_array($potentialModel)){ // cycle through each field verify where necessary foreach ($potentialModel as $fieldKey => $fieldDetail){ // verify fields are not empty // note. This ignores 'can_be_blank', if is somehow set despite setting not_empty if (isset($fieldDetail['not_empty']) && $fieldDetail['not_empty']){ // needs to ensure field is not empty if (empty($objArr[$fieldKey])){ // pass back the failed field. $checksFailed[$fieldKey] = $fieldDetail; } } } // / foreach } // / if has model } // got any fails? if (count($checksFailed) > 0){ // can't update, some empties. // set reason msg if (is_array($checksFailed)) foreach ($checksFailed as $fieldKey => $fieldDetail){ $fk = $fieldKey; if (isset($fieldDetail['label'])) $fk = $fieldDetail['label']; $msg = __('The field:','zero-bs-crm').' "'.$fk.'" '.__('is required','zero-bs-crm'); $zbs->DAL->addError(304,$this->objectType,$msg,$fieldKey); } // return fail return false; } // / fails non blank field verify return true; } /** * remove any non-db fields from the object * basically takes array like array('owner'=>1,'fname'=>'x','fullname'=>'x') * and returns array like array('owner'=>1,'fname'=>'x') * * @param array $obj (clean obj) * * @return array (db ready arr) */ public function db_ready_obj($obj=false){ global $zbs; // here it has to use the KEY which is without prefix (e.g. status, not zbsc_status) :) if (isset($this->objectModel) && is_array($this->objectModel)){ $ret = array(); if (is_array($obj)){ foreach ($this->objectModel as $fKey => $fObj){ if (isset($obj[$fKey])) $ret[$fKey] = $obj[$fKey]; } // gross backward compat - long may this die. if ($zbs->db2CompatabilitySupport) $ret['meta'] = $ret; } } return $ret; } /** * genericified link array of id's with this obj * Takes current area (e.g. EVENT) as first type, and assigns objlinks EVENT -> $toObjType * * @param int $objectID (int of this obj id) * @param array $objectIDsArr (array of ints (IDs)) - NOTE: can pass 'unset' as str to wipe links * @param int $toObjectType (int of obj link type) * * @return bool of action */ public function addUpdateObjectLinks($objectID=-1,$objectIDsArr=false,$toObjectType=false){ if ($toObjectType > 0 && $objectID > 0){ // GENERICIFIED OBJ LINKS if (isset($objectIDsArr) && is_array($objectIDsArr) && count($objectIDsArr) > 0){ // replace existing $this->DAL()->addUpdateObjLinks(array( 'objtypefrom' => $this->objectType, 'objtypeto' => $toObjectType, 'objfromid' => $objectID, 'objtoids' => $objectIDsArr, 'mode' => 'replace')); return true; } else if (isset($objectIDsArr) && $objectIDsArr == 'unset') { // wipe previous links $deleted = $this->DAL()->deleteObjLinks(array( 'objtypefrom' => $this->objectType, 'objtypeto' => $toObjectType, 'objfromid' => $objectID)); // where id = return true; } } return false; } // =============================================================================== // =========== DAL2 WRAPPERS ===================================================== // These are dumb, and pass back directly to parent $zbs->DAL equivilents, centralising them // ... this is so we can keep $this->lazyTable etc. usage which is simpler than $this->DAL()->lazyTable public function lazyTable($objType=-1){ // pass back to main $zbs->DAL return $this->DAL()->lazyTable($objType); } public function lazyTidy($objType=-1,$obj=false){ // pass back to main $zbs->DAL return $this->DAL()->lazyTidy($objType,$obj); } public function lazyTidyGeneric($obj=false){ // pass back to main $zbs->DAL return $this->DAL()->lazyTidyGeneric($obj); } public function space($str='',$pre=false){ // pass back to main $zbs->DAL return $this->DAL()->space($str,$pre); } public function spaceAnd($str=''){ // pass back to main $zbs->DAL return $this->DAL()->spaceAnd($str); } public function spaceWhere($str=''){ // pass back to main $zbs->DAL return $this->DAL()->spaceWhere($str); } public function delimiterIf($delimiter,$ifStr=''){ // pass back to main $zbs->DAL return $this->DAL()->delimiterIf($delimiter,$ifStr); } public function stripSlashes($obj=false){ return zeroBSCRM_stripSlashes( $obj ); } public function decodeIfJSON($str=''){ // pass back to main $zbs->DAL return $this->DAL()->decodeIfJSON($str); } public function build_csv($array=array()){ // pass back to main $zbs->DAL return $this->DAL()->build_csv($array); } public function buildWhereStr($whereStr='',$additionalWhere=''){ // pass back to main $zbs->DAL return $this->DAL()->buildWhereStr($whereStr,$additionalWhere); } public function buildWheres($wheres=array(),$whereStr='',$params=array(),$andOr='AND',$includeInitialWHERE=true){ // pass back to main $zbs->DAL return $this->DAL()->buildWheres($wheres,$whereStr,$params,$andOr,$includeInitialWHERE); } public function buildSort($sortByField='',$sortOrder='ASC'){ // pass back to main $zbs->DAL return $this->DAL()->buildSort($sortByField,$sortOrder); } public function buildPaging($page=-1,$perPage=-1){ // pass back to main $zbs->DAL return $this->DAL()->buildPaging($page,$perPage); } public function buildWPMetaQueryWhere($metaKey=-1,$metaVal=-1){ // pass back to main $zbs->DAL return $this->DAL()->buildWPMetaQueryWhere($metaKey,$metaVal); } public function getTypeStr($fieldKey=''){ // pass back to main $zbs->DAL return $this->DAL()->getTypeStr($fieldKey); } public function prepare($sql='',$params=array()){ // pass back to main $zbs->DAL return $this->DAL()->prepare($sql,$params); } public function catchSQLError($errObj=-1){ // pass back to main $zbs->DAL return $this->DAL()->catchSQLError($errObj); } // legacy signpost, this is now overwritten by DAL->contacts->fullname public function format_fullname($contactArr=array()){ // pass back to main $zbs->DAL return $this->DAL()->format_fullname($contactArr); } // legacy signpost, this is now overwritten by DAL->[contacts|companies]->format_name_etc public function format_name_etc($contactArr=array(),$args=array()){ // pass back to main $zbs->DAL return $this->DAL()->format_name_etc($contactArr,$args); } public function format_address($contactArr=array(),$args=array()){ // pass back to main $zbs->DAL return $this->DAL()->format_address($contactArr,$args); } public function makeSlug($string, $replace = array(), $delimiter = '-') { // pass back to main $zbs->DAL return $this->DAL()->makeSlug($string,$replace,$delimiter); } public function makeSlugCleanStr($string='', $delimiter='-'){ // pass back to main $zbs->DAL return $this->DAL()->makeSlugCleanStr($string,$delimiter); } public function ownershipQueryVars($ignoreOwner=false){ // pass back to main $zbs->DAL return $this->DAL()->ownershipQueryVars($ignoreOwner); } public function ownershipSQL($ignoreOwner=false,$table=''){ // pass back to main $zbs->DAL return $this->DAL()->ownershipSQL($ignoreOwner,$table); } public function addUpdateCustomField($args=array()){ // pass back to main $zbs->DAL return $this->DAL()->addUpdateCustomField($args); } // =========== / DAL2 WRAPPERS =================================================== // =============================================================================== } // / class
projects/plugins/crm/includes/ZeroBSCRM.Database.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V1.20 * * Copyright 2020 Automattic * * Date: 01/11/16 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== Table Creation ====================================================== */ global $wpdb, $ZBSCRM_t; // Table names $ZBSCRM_t['contacts'] = $wpdb->prefix . "zbs_contacts"; $ZBSCRM_t['customfields'] = $wpdb->prefix . "zbs_customfields"; $ZBSCRM_t['meta'] = $wpdb->prefix . "zbs_meta"; $ZBSCRM_t['tags'] = $wpdb->prefix . "zbs_tags"; $ZBSCRM_t['taglinks'] = $wpdb->prefix . "zbs_tags_links"; $ZBSCRM_t['settings'] = $wpdb->prefix . "zbs_settings"; $ZBSCRM_t['segments'] = $wpdb->prefix . "zbs_segments"; $ZBSCRM_t['segmentsconditions'] = $wpdb->prefix . "zbs_segments_conditions"; $ZBSCRM_t['adminlog'] = $wpdb->prefix . "zbs_admlog"; $ZBSCRM_t['temphash'] = $wpdb->prefix . "zbs_temphash"; $ZBSCRM_t['objlinks'] = $wpdb->prefix . "zbs_object_links"; $ZBSCRM_t['aka'] = $wpdb->prefix . "zbs_aka"; $ZBSCRM_t['externalsources'] = $wpdb->prefix . "zbs_externalsources"; $ZBSCRM_t['tracking'] = $wpdb->prefix . "zbs_tracking"; $ZBSCRM_t['logs'] = $wpdb->prefix . "zbs_logs"; $ZBSCRM_t['system_mail_templates'] = $wpdb->prefix . "zbs_sys_email"; $ZBSCRM_t['system_mail_hist'] = $wpdb->prefix . "zbs_sys_email_hist"; $ZBSCRM_t['cronmanagerlogs'] = $wpdb->prefix . "zbs_sys_cronmanagerlogs"; $ZBSCRM_t['dbmigrationbkmeta'] = $wpdb->prefix . "zbs_dbmigration_meta"; $ZBSCRM_t['dbmigrationbkposts'] = $wpdb->prefix . "zbs_dbmigration_posts"; $ZBSCRM_t['companies'] = $wpdb->prefix . "zbs_companies"; $ZBSCRM_t['quotes'] = $wpdb->prefix . "zbs_quotes"; $ZBSCRM_t['quotetemplates'] = $wpdb->prefix . "zbs_quotes_templates"; $ZBSCRM_t['invoices'] = $wpdb->prefix . "zbs_invoices"; $ZBSCRM_t['transactions'] = $wpdb->prefix . "zbs_transactions"; $ZBSCRM_t['lineitems'] = $wpdb->prefix . "zbs_lineitems"; $ZBSCRM_t['forms'] = $wpdb->prefix . "zbs_forms"; $ZBSCRM_t['events'] = $wpdb->prefix . "zbs_events"; $ZBSCRM_t['eventreminders'] = $wpdb->prefix . "zbs_event_reminders"; $ZBSCRM_t['tax'] = $wpdb->prefix . "zbs_tax_table"; $ZBSCRM_t['security_log'] = $wpdb->prefix . "zbs_security_log"; $ZBSCRM_t['automation-workflows'] = $wpdb->prefix . 'zbs_workflows'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, Universal.WhiteSpace.PrecisionAlignment.Found /** * Core-fired Database structure check * ... currently used to check tables exist */ function zeroBSCRM_database_check(){ #} Check + create zeroBSCRM_checkTablesExist(); } /** * creates the ZBS Database Tables * */ function zeroBSCRM_createTables(){ global $wpdb, $ZBSCRM_t; // Require upgrade.php so we can use dbDelta require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); // Where available we force InnoDB $storageEngineLine = ''; if (zeroBSCRM_DB_canInnoDB()) $storageEngineLine = 'ENGINE = InnoDB'; // Collation & Character Set $collation = 'utf8_general_ci'; $characterSet = 'utf8'; // We'll collect any errors as we go, exposing, if there are any, on system status page global $zbsDB_lastError,$zbsDB_creationErrors; // we log the last error before we start, in case another plugin has left an error in the buffer $zbsDB_lastError = ''; if (isset($wpdb->last_error)) $zbsDB_lastError = $wpdb->last_error; $zbsDB_creationErrors = array(); // Contacts $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['contacts'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, `zbsc_status` VARCHAR(100) NULL, `zbsc_email` VARCHAR(200) NULL, `zbsc_prefix` VARCHAR(30) NULL, `zbsc_fname` VARCHAR(100) NULL, `zbsc_lname` VARCHAR(100) NULL, `zbsc_addr1` VARCHAR(200) NULL, `zbsc_addr2` VARCHAR(200) NULL, `zbsc_city` VARCHAR(100) NULL, `zbsc_county` VARCHAR(200) NULL, `zbsc_country` VARCHAR(200) NULL, `zbsc_postcode` VARCHAR(50) NULL, `zbsc_secaddr1` VARCHAR(200) NULL, `zbsc_secaddr2` VARCHAR(200) NULL, `zbsc_seccity` VARCHAR(100) NULL, `zbsc_seccounty` VARCHAR(200) NULL, `zbsc_seccountry` VARCHAR(200) NULL, `zbsc_secpostcode` VARCHAR(50) NULL, `zbsc_hometel` VARCHAR(40) NULL, `zbsc_worktel` VARCHAR(40) NULL, `zbsc_mobtel` VARCHAR(40) NULL, `zbsc_wpid` INT NULL DEFAULT NULL, `zbsc_avatar` VARCHAR(300) NULL, `zbsc_tw` VARCHAR(100) NULL, `zbsc_li` VARCHAR(300) NULL, `zbsc_fb` VARCHAR(200) NULL, `zbsc_created` INT(14) NOT NULL, `zbsc_lastupdated` INT(14) NOT NULL, `zbsc_lastcontacted` INT(14) NULL DEFAULT NULL, PRIMARY KEY (`ID`), INDEX (`zbsc_email`, `zbsc_wpid`), KEY `zbsc_status` (`zbsc_status`) USING BTREE) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); // Custom Fields $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['customfields'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, `zbscf_objtype` INT(4) NOT NULL, `zbscf_objid` INT(32) NOT NULL, `zbscf_objkey` VARCHAR(100) NOT NULL, `zbscf_objval` VARCHAR(2000) NULL DEFAULT NULL, `zbscf_created` INT(14) NOT NULL, `zbscf_lastupdated` INT(14) NOT NULL, PRIMARY KEY (`ID`), INDEX `TYPEIDKEY` (`zbscf_objtype` ASC, `zbscf_objid` ASC, `zbscf_objkey` ASC)) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); // Tags $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['tags'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, `zbstag_objtype` INT NOT NULL, `zbstag_name` VARCHAR(200) NOT NULL, `zbstag_slug` VARCHAR(200) NOT NULL, `zbstag_created` INT(14) NOT NULL, `zbstag_lastupdated` INT(14) NOT NULL, PRIMARY KEY (`ID`)) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); // Tag Relationships (Links) $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['taglinks'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, `zbstl_objtype` INT(4) NOT NULL, `zbstl_objid` INT NOT NULL, `zbstl_tagid` INT NOT NULL, PRIMARY KEY (`ID`), INDEX (`zbstl_objid`), INDEX (`zbstl_tagid`), KEY `zbstl_tagid+zbstl_objtype` (`zbstl_tagid`,`zbstl_objtype`) USING BTREE) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); // Settings $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['settings'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, `zbsset_key` VARCHAR(100) NOT NULL DEFAULT -1, `zbsset_val` LONGTEXT NULL DEFAULT NULL, `zbsset_created` INT(14) NOT NULL, `zbsset_lastupdated` INT(14) NOT NULL, PRIMARY KEY (`ID`), INDEX `zbsset_key` (`zbsset_key`), INDEX (`zbs_owner`)) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); // Meta Key-Value pairs $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['meta'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, `zbsm_objtype` INT NOT NULL, `zbsm_objid` INT NOT NULL, `zbsm_key` VARCHAR(255) NOT NULL, `zbsm_val` LONGTEXT NULL DEFAULT NULL, `zbsm_created` INT(14) NOT NULL, `zbsm_lastupdated` INT(14) NOT NULL, PRIMARY KEY (`ID`), KEY `zbsm_objid+zbsm_key+zbsm_objtype` (`zbsm_objid`,`zbsm_key`,`zbsm_objtype`) USING BTREE) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); #} Segments $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['segments'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, `zbsseg_name` VARCHAR(120) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NOT NULL, `zbsseg_slug` VARCHAR(45) NOT NULL, `zbsseg_matchtype` VARCHAR(10) NOT NULL, `zbsseg_created` INT(14) NOT NULL, `zbsseg_lastupdated` INT(14) NOT NULL, `zbsseg_compilecount` INT NULL DEFAULT 0, `zbsseg_lastcompiled` INT(14) NOT NULL, PRIMARY KEY (`ID`)) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); // Segments: Conditions $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['segmentsconditions'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbscondition_segmentid` INT NOT NULL, `zbscondition_type` VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NOT NULL, `zbscondition_op` VARCHAR(50) NULL, `zbscondition_val` VARCHAR(250) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NULL, `zbscondition_val_secondary` VARCHAR(250) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NULL, PRIMARY KEY (`ID`)) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); // Admin Logs $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['adminlog'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, `zbsadmlog_status` INT(3) NOT NULL, `zbsadmlog_cat` VARCHAR(20) NULL DEFAULT NULL, `zbsadmlog_str` VARCHAR(500) NULL DEFAULT NULL, `zbsadmlog_time` INT(14) NULL DEFAULT NULL, PRIMARY KEY (`ID`)) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); // Temporary Hashes $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['temphash'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, `zbstemphash_status` INT NULL DEFAULT -1, `zbstemphash_objtype` VARCHAR(50) NOT NULL, `zbstemphash_objid` INT NULL DEFAULT NULL, `zbstemphash_objhash` VARCHAR(256) NULL DEFAULT NULL, `zbstemphash_created` INT(14) NOT NULL, `zbstemphash_lastupdated` INT(14) NOT NULL, `zbstemphash_expiry` INT(14) NOT NULL, PRIMARY KEY (`ID`)) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); // Object Relationships (Links) $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['objlinks'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, `zbsol_objtype_from` INT(4) NOT NULL, `zbsol_objtype_to` INT(4) NOT NULL, `zbsol_objid_from` INT NOT NULL, `zbsol_objid_to` INT NOT NULL, PRIMARY KEY (`ID`), INDEX (`zbsol_objid_from`), INDEX (`zbsol_objid_to`)) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); #} AKA (Aliases) $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['aka'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `aka_type` INT NULL, `aka_id` INT NOT NULL, `aka_alias` VARCHAR(200) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NOT NULL, `aka_created` INT(14) NULL, `aka_lastupdated` INT(14) NULL, PRIMARY KEY (`ID`), INDEX (`aka_id`, `aka_alias`)) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); #} External sources // NOTE:! Modified in 2.97.5 migration $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['externalsources'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, `zbss_objtype` INT(3) NOT NULL DEFAULT '-1', `zbss_objid` INT(32) NOT NULL, `zbss_source` VARCHAR(20) NOT NULL, `zbss_uid` VARCHAR(300) NOT NULL, `zbss_origin` VARCHAR(400) NULL DEFAULT NULL, `zbss_created` INT(14) NOT NULL, `zbss_lastupdated` INT(14) NOT NULL, PRIMARY KEY (`ID`), INDEX (`zbss_objid`), INDEX (`zbss_origin`), KEY `zbss_uid+zbss_source+zbss_objtype` (`zbss_uid`,`zbss_source`,`zbss_objtype`) USING BTREE) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); #} Tracking (web hit info) $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['tracking'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, `zbst_contactid` INT NOT NULL, `zbst_action` VARCHAR(50) NOT NULL, `zbst_action_detail` LONGTEXT NOT NULL, `zbst_referrer` VARCHAR(300) NOT NULL, `zbst_utm_source` VARCHAR(200) NOT NULL, `zbst_utm_medium` VARCHAR(200) NOT NULL, `zbst_utm_name` VARCHAR(200) NOT NULL, `zbst_utm_term` VARCHAR(200) NOT NULL, `zbst_utm_content` VARCHAR(200) NOT NULL, `zbst_created` INT(14) NOT NULL, `zbst_lastupdated` INT(14) NOT NULL, PRIMARY KEY (`ID`)) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); #} Logs $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['logs'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, `zbsl_objtype` INT NOT NULL, `zbsl_objid` INT NOT NULL, `zbsl_type` VARCHAR(200) NOT NULL, `zbsl_shortdesc` VARCHAR(300) NULL, `zbsl_longdesc` LONGTEXT NULL, `zbsl_pinned` INT(1) NULL, `zbsl_created` INT(14) NOT NULL, `zbsl_lastupdated` INT(14) NOT NULL, PRIMARY KEY (`ID`), INDEX (`zbsl_objid`), INDEX `zbsl_created` (`zbsl_created`) USING BTREE) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); // Migration BACKUP Post Meta Table // Note 2 additional columns in each (wpID,zbsID) store related ID's $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['dbmigrationbkmeta'] ."( `meta_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `wpID` bigint(20) unsigned NOT NULL, `zbsID` bigint(20) unsigned NOT NULL, `post_id` bigint(20) unsigned NOT NULL DEFAULT '0', `meta_key` varchar(255) COLLATE utf8_general_ci DEFAULT NULL, `meta_value` longtext COLLATE utf8_general_ci, PRIMARY KEY (`meta_id`), KEY `post_id` (`post_id`), KEY `meta_key` (`meta_key`)) ".$storageEngineLine." DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;"; zeroBSCRM_db_runDelta($sql); // Migration Backup Posts Tables $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['dbmigrationbkposts'] ."( `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `wpID` bigint(20) unsigned NOT NULL, `zbsID` bigint(20) unsigned NOT NULL, `post_author` bigint(20) unsigned NOT NULL DEFAULT '0', `post_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `post_date_gmt` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `post_content` longtext COLLATE utf8_general_ci NOT NULL, `post_title` text COLLATE utf8_general_ci NOT NULL, `post_excerpt` text COLLATE utf8_general_ci NOT NULL, `post_status` varchar(20) COLLATE utf8_general_ci NOT NULL DEFAULT 'publish', `comment_status` varchar(20) COLLATE utf8_general_ci NOT NULL DEFAULT 'open', `ping_status` varchar(20) COLLATE utf8_general_ci NOT NULL DEFAULT 'open', `post_password` varchar(255) COLLATE utf8_general_ci NOT NULL DEFAULT '', `post_name` varchar(200) COLLATE utf8_general_ci NOT NULL DEFAULT '', `to_ping` text COLLATE utf8_general_ci NOT NULL, `pinged` text COLLATE utf8_general_ci NOT NULL, `post_modified` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `post_modified_gmt` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `post_content_filtered` longtext COLLATE utf8_general_ci NOT NULL, `post_parent` bigint(20) unsigned NOT NULL DEFAULT '0', `guid` varchar(255) COLLATE utf8_general_ci NOT NULL DEFAULT '', `menu_order` int(11) NOT NULL DEFAULT '0', `post_type` varchar(20) COLLATE utf8_general_ci NOT NULL DEFAULT 'post', `post_mime_type` varchar(100) COLLATE utf8_general_ci NOT NULL DEFAULT '', `comment_count` bigint(20) NOT NULL DEFAULT '0', PRIMARY KEY (`ID`), KEY `post_name` (`post_name`), KEY `type_status_date` (`post_type`,`post_status`,`post_date`,`ID`), KEY `post_parent` (`post_parent`), KEY `post_author` (`post_author`)) ".$storageEngineLine." DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;"; zeroBSCRM_db_runDelta($sql); // System Email Templates $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['system_mail_templates'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, `zbsmail_active` INT NOT NULL, `zbsmail_id` INT NOT NULL, `zbsmail_deliverymethod` VARCHAR(200) NOT NULL, `zbsmail_fromname` VARCHAR(200) NULL, `zbsmail_fromaddress` VARCHAR(200) NULL, `zbsmail_replyto` VARCHAR(200) NULL, `zbsmail_ccto` VARCHAR(200) NULL, `zbsmail_bccto` VARCHAR(200) NULL, `zbsmail_subject` VARCHAR(200) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NULL DEFAULT NULL, `zbsmail_body` LONGTEXT NULL DEFAULT NULL, `zbsmail_created` INT(14) NOT NULL, `zbsmail_lastupdated` INT(14) NOT NULL, PRIMARY KEY (`ID`)) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); // System Email History $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['system_mail_hist'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` int(11) DEFAULT NULL, `zbs_team` int(11) DEFAULT NULL, `zbs_owner` int(11) NOT NULL, `zbsmail_type` int(11) NOT NULL, `zbsmail_sender_thread` int(11) NOT NULL, `zbsmail_sender_email` varchar(200) NOT NULL, `zbsmail_sender_wpid` int(11) NOT NULL, `zbsmail_sender_mailbox_id` int(11) NOT NULL, `zbsmail_sender_mailbox_name` varchar(200) DEFAULT NULL, `zbsmail_receiver_email` varchar(200) NOT NULL, `zbsmail_sent` int(11) NOT NULL, `zbsmail_target_objid` int(11) NOT NULL, `zbsmail_assoc_objid` int(11) NOT NULL, `zbsmail_subject` varchar(200) DEFAULT NULL, `zbsmail_content` longtext, `zbsmail_hash` varchar(128) DEFAULT NULL, `zbsmail_status` varchar(120) DEFAULT NULL, `zbsmail_sender_maildelivery_key` varchar(200) DEFAULT NULL, `zbsmail_starred` int(11) DEFAULT NULL, `zbsmail_opened` int(11) NOT NULL, `zbsmail_clicked` int(11) NOT NULL, `zbsmail_firstopened` int(14) NOT NULL, `zbsmail_lastopened` int(14) NOT NULL, `zbsmail_lastclicked` int(14) NOT NULL, `zbsmail_created` int(14) NOT NULL, PRIMARY KEY (`ID`), INDEX (`zbsmail_sender_wpid`), INDEX (`zbsmail_sender_mailbox_id`)) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); // cron Manager Logs $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['cronmanagerlogs'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` int(11) DEFAULT NULL, `zbs_team` int(11) DEFAULT NULL, `zbs_owner` int(11) NOT NULL, `job` VARCHAR(100) NOT NULL, `jobstatus` INT(3) NULL, `jobstarted` INT(14) NOT NULL, `jobfinished` INT(14) NOT NULL, `jobnotes` LONGTEXT NULL, PRIMARY KEY (`ID`)) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); // Tax Table $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['tax'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` int(11) DEFAULT NULL, `zbs_team` int(11) DEFAULT NULL, `zbs_owner` int(11) NOT NULL, `zbsc_tax_name` VARCHAR(100) NULL, `zbsc_rate` DECIMAL(18,2) NOT NULL DEFAULT 0.00, `zbsc_created` INT(14) NOT NULL, `zbsc_lastupdated` INT(14) NOT NULL, PRIMARY KEY (`ID`)) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); // Companies (DB3.0+) $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['companies'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, `zbsco_status` VARCHAR(50) NULL DEFAULT NULL, `zbsco_name` VARCHAR(100) NULL DEFAULT NULL, `zbsco_email` VARCHAR(200) NULL DEFAULT NULL, `zbsco_addr1` VARCHAR(200) NULL DEFAULT NULL, `zbsco_addr2` VARCHAR(200) NULL DEFAULT NULL, `zbsco_city` VARCHAR(100) NULL DEFAULT NULL, `zbsco_county` VARCHAR(200) NULL DEFAULT NULL, `zbsco_country` VARCHAR(200) NULL DEFAULT NULL, `zbsco_postcode` VARCHAR(50) NULL DEFAULT NULL, `zbsco_secaddr1` VARCHAR(200) NULL DEFAULT NULL, `zbsco_secaddr2` VARCHAR(200) NULL DEFAULT NULL, `zbsco_seccity` VARCHAR(100) NULL DEFAULT NULL, `zbsco_seccounty` VARCHAR(200) NULL DEFAULT NULL, `zbsco_seccountry` VARCHAR(200) NULL DEFAULT NULL, `zbsco_secpostcode` VARCHAR(50) NULL DEFAULT NULL, `zbsco_maintel` VARCHAR(40) NULL DEFAULT NULL, `zbsco_sectel` VARCHAR(40) NULL DEFAULT NULL, `zbsco_wpid` INT NULL DEFAULT NULL, `zbsco_avatar` VARCHAR(300) NULL DEFAULT NULL, `zbsco_tw` VARCHAR(100) NULL, `zbsco_li` VARCHAR(300) NULL, `zbsco_fb` VARCHAR(200) NULL, `zbsco_created` INT(14) NOT NULL, `zbsco_lastupdated` INT(14) NOT NULL, `zbsco_lastcontacted` INT(14) NULL DEFAULT NULL, PRIMARY KEY (`ID`), INDEX `wpid` (`zbsco_wpid` ASC), INDEX `name` (`zbsco_name` ASC), INDEX `email` (`zbsco_email` ASC), INDEX `created` (`zbsco_created` ASC)) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); // Tasks (DB3.0+) $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['events'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, `zbse_title` VARCHAR(255) NULL DEFAULT NULL, `zbse_desc` LONGTEXT NULL DEFAULT NULL, `zbse_start` INT(14) NOT NULL, `zbse_end` INT(14) NOT NULL, `zbse_complete` TINYINT(1) NOT NULL DEFAULT -1, `zbse_show_on_portal` TINYINT(1) NOT NULL DEFAULT -1, `zbse_show_on_cal` TINYINT(1) NOT NULL DEFAULT -1, `zbse_created` INT(14) NOT NULL, `zbse_lastupdated` INT(14) NULL DEFAULT NULL, PRIMARY KEY (`ID`), INDEX `title` (`zbse_title` ASC), INDEX `startint` (`zbse_start` ASC), INDEX `endint` (`zbse_end` ASC), INDEX `created` (`zbse_created` ASC)) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); // Task Reminders (DB3.0+) $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['eventreminders'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, `zbser_event` INT NOT NULL, `zbser_remind_at` INT NOT NULL DEFAULT -1, `zbser_sent` TINYINT NOT NULL DEFAULT -1, `zbser_created` INT(14) NOT NULL, `zbser_lastupdated` INT(14) NULL DEFAULT NULL, PRIMARY KEY (`ID`)) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); // Forms $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['forms'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, `zbsf_title` VARCHAR(200) NULL DEFAULT NULL, `zbsf_style` VARCHAR(20) NOT NULL, `zbsf_views` INT(10) NULL DEFAULT 0, `zbsf_conversions` INT(10) NULL DEFAULT 0, `zbsf_label_header` VARCHAR(200) NULL DEFAULT NULL, `zbsf_label_subheader` VARCHAR(200) NULL DEFAULT NULL, `zbsf_label_firstname` VARCHAR(200) NULL DEFAULT NULL, `zbsf_label_lastname` VARCHAR(200) NULL DEFAULT NULL, `zbsf_label_email` VARCHAR(200) NULL DEFAULT NULL, `zbsf_label_message` VARCHAR(200) NULL DEFAULT NULL, `zbsf_label_button` VARCHAR(200) NULL DEFAULT NULL, `zbsf_label_successmsg` VARCHAR(200) NULL DEFAULT NULL, `zbsf_label_spammsg` VARCHAR(200) NULL DEFAULT NULL, `zbsf_include_terms_check` TINYINT(1) NOT NULL DEFAULT -1, `zbsf_terms_url` VARCHAR(300) NULL DEFAULT NULL, `zbsf_redir_url` VARCHAR(300) NULL DEFAULT NULL, `zbsf_font` VARCHAR(100) NULL DEFAULT NULL, `zbsf_colour_bg` VARCHAR(100) NULL DEFAULT NULL, `zbsf_colour_font` VARCHAR(100) NULL DEFAULT NULL, `zbsf_colour_emphasis` VARCHAR(100) NULL DEFAULT NULL, `zbsf_created` INT(14) NOT NULL, `zbsf_lastupdated` INT(14) NOT NULL, PRIMARY KEY (`ID`), INDEX `title` (`zbsf_title` ASC), INDEX `created` (`zbsf_created` ASC)) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); // Invoices $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['invoices'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, `zbsi_id_override` VARCHAR(128) NULL DEFAULT NULL, `zbsi_parent` INT NULL DEFAULT NULL, `zbsi_status` VARCHAR(50) NOT NULL, `zbsi_hash` VARCHAR(64) NULL DEFAULT NULL, `zbsi_send_attachments` TINYINT(1) NOT NULL DEFAULT -1, `zbsi_pdf_template` VARCHAR(128) NULL DEFAULT NULL, `zbsi_portal_template` VARCHAR(128) NULL DEFAULT NULL, `zbsi_email_template` VARCHAR(128) NULL DEFAULT NULL, `zbsi_invoice_frequency` INT(4) NULL DEFAULT -1, `zbsi_currency` VARCHAR(4) NOT NULL DEFAULT -1, `zbsi_pay_via` INT(4) NULL DEFAULT NULL, `zbsi_logo_url` VARCHAR(300) NULL DEFAULT NULL, `zbsi_address_to_objtype` INT(2) NOT NULL DEFAULT -1, `zbsi_addressed_from` VARCHAR(600) NULL DEFAULT NULL, `zbsi_addressed_to` VARCHAR(600) NULL DEFAULT NULL, `zbsi_allow_partial` TINYINT(1) NOT NULL DEFAULT -1, `zbsi_allow_tip` TINYINT(1) NOT NULL DEFAULT -1, `zbsi_hours_or_quantity` TINYINT(1) NOT NULL DEFAULT 1, `zbsi_date` INT(14) NOT NULL, `zbsi_due_date` INT(14) NULL DEFAULT NULL, `zbsi_paid_date` INT(14) NULL DEFAULT -1, `zbsi_hash_viewed` INT(14) NULL DEFAULT -1, `zbsi_hash_viewed_count` INT(10) NULL DEFAULT 0, `zbsi_portal_viewed` INT(14) NULL DEFAULT -1, `zbsi_portal_viewed_count` INT(10) NULL DEFAULT 0, `zbsi_net` DECIMAL(18,2) NOT NULL DEFAULT 0.00, `zbsi_discount` DECIMAL(18,2) NULL DEFAULT 0.00, `zbsi_discount_type` VARCHAR(20) NULL DEFAULT NULL, `zbsi_shipping` DECIMAL(18,2) NULL DEFAULT 0.00, `zbsi_shipping_taxes` VARCHAR(40) NULL DEFAULT NULL, `zbsi_shipping_tax` DECIMAL(18,2) NULL DEFAULT 0.00, `zbsi_taxes` VARCHAR(40) NULL DEFAULT NULL, `zbsi_tax` DECIMAL(18,2) NULL DEFAULT 0.00, `zbsi_total` DECIMAL(18,2) NOT NULL DEFAULT 0.00, `zbsi_created` INT(14) NOT NULL, `zbsi_lastupdated` INT(14) NOT NULL, PRIMARY KEY (`ID`), INDEX `idoverride` (`zbsi_id_override` ASC), INDEX `parent` (`zbsi_parent` ASC), INDEX `status` (`zbsi_status` ASC), INDEX `hash` (`zbsi_hash` ASC), INDEX `created` (`zbsi_created` ASC)) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); // Line Items (DB3.0+) $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['lineitems'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, `zbsli_order` INT NULL DEFAULT NULL, `zbsli_title` VARCHAR(300) NULL DEFAULT NULL, `zbsli_desc` VARCHAR(300) NULL DEFAULT NULL, `zbsli_quantity` decimal(18,2) NULL DEFAULT NULL, `zbsli_price` DECIMAL(18,2) NOT NULL DEFAULT 0.00, `zbsli_currency` VARCHAR(4) NOT NULL DEFAULT -1, `zbsli_net` DECIMAL(18,2) NOT NULL DEFAULT 0.00, `zbsli_discount` DECIMAL(18,2) NULL DEFAULT 0.00, `zbsli_fee` DECIMAL(18,2) NULL DEFAULT 0.00, `zbsli_shipping` DECIMAL(18,2) NULL DEFAULT 0.00, `zbsli_shipping_taxes` VARCHAR(40) NULL DEFAULT NULL, `zbsli_shipping_tax` DECIMAL(18,2) NULL DEFAULT 0.00, `zbsli_taxes` VARCHAR(40) NULL DEFAULT NULL, `zbsli_tax` DECIMAL(18,2) NULL DEFAULT 0.00, `zbsli_total` DECIMAL(18,2) NOT NULL DEFAULT 0.00, `zbsli_created` INT(14) NOT NULL, `zbsli_lastupdated` INT(14) NOT NULL, PRIMARY KEY (`ID`), INDEX `order` (`zbsli_order` ASC), INDEX `created` (`zbsli_created` ASC)) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); // Quotes (DB3.0+) $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['quotes'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, `zbsq_id_override` VARCHAR(128) NULL DEFAULT NULL, `zbsq_title` VARCHAR(255) NULL DEFAULT NULL, `zbsq_currency` VARCHAR(4) NOT NULL DEFAULT -1, `zbsq_value` DECIMAL(18,2) NULL DEFAULT 0.00, `zbsq_date` INT(14) NOT NULL, `zbsq_template` VARCHAR(200) NULL DEFAULT NULL, `zbsq_content` LONGTEXT NULL DEFAULT NULL, `zbsq_notes` LONGTEXT NULL DEFAULT NULL, `zbsq_hash` VARCHAR(64) NULL DEFAULT NULL, `zbsq_send_attachments` TINYINT(1) NOT NULL DEFAULT -1, `zbsq_lastviewed` INT(14) NULL DEFAULT -1, `zbsq_viewed_count` INT(10) NULL DEFAULT 0, `zbsq_accepted` INT(14) NULL DEFAULT -1, `zbsq_acceptedsigned` VARCHAR(200) NULL DEFAULT NULL, `zbsq_acceptedip` VARCHAR(64) NULL DEFAULT NULL, `zbsq_created` INT(14) NOT NULL, `zbsq_lastupdated` INT(14) NOT NULL, PRIMARY KEY (`ID`), INDEX `title` (`zbsq_title` ASC), INDEX `dateint` (`zbsq_date` ASC), INDEX `hash` (`zbsq_hash` ASC), INDEX `created` (`zbsq_created` ASC), INDEX `accepted` (`zbsq_accepted` ASC)) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); // Quote Templates (DB3.0+) $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['quotetemplates'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, `zbsqt_title` VARCHAR(255) NULL DEFAULT NULL, `zbsqt_value` DECIMAL(18,2) NULL DEFAULT 0.00, `zbsqt_date_str` VARCHAR(20) NULL DEFAULT NULL, `zbsqt_date` INT(14) NULL DEFAULT NULL, `zbsqt_content` LONGTEXT NULL DEFAULT NULL, `zbsqt_notes` LONGTEXT NULL DEFAULT NULL, `zbsqt_currency` VARCHAR(4) NOT NULL DEFAULT -1, `zbsqt_created` INT(14) NOT NULL, `zbsqt_lastupdated` INT(14) NOT NULL, PRIMARY KEY (`ID`), INDEX `title` (`zbsqt_title` ASC), INDEX `created` (`zbsqt_created` ASC)) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); // Transactions (DB3.0+) $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['transactions'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, `zbst_status` VARCHAR(50) NOT NULL, `zbst_type` VARCHAR(50) DEFAULT NULL, `zbst_ref` VARCHAR(120) NOT NULL, `zbst_origin` VARCHAR(100) NULL DEFAULT NULL, `zbst_parent` INT NULL DEFAULT NULL, `zbst_hash` VARCHAR(64) NULL DEFAULT NULL, `zbst_title` VARCHAR(200) NULL DEFAULT NULL, `zbst_desc` VARCHAR(200) NULL DEFAULT NULL, `zbst_date` INT(14) NULL DEFAULT NULL, `zbst_customer_ip` VARCHAR(45) NULL DEFAULT NULL, `zbst_currency` VARCHAR(4) NOT NULL DEFAULT -1, `zbst_net` DECIMAL(18,2) NOT NULL DEFAULT 0.00, `zbst_fee` DECIMAL(18,2) NOT NULL DEFAULT 0.00, `zbst_discount` DECIMAL(18,2) NULL DEFAULT 0.00, `zbst_shipping` DECIMAL(18,2) NULL DEFAULT 0.00, `zbst_shipping_taxes` VARCHAR(40) NULL DEFAULT NULL, `zbst_shipping_tax` DECIMAL(18,2) NULL DEFAULT 0.00, `zbst_taxes` VARCHAR(40) NULL DEFAULT NULL, `zbst_tax` DECIMAL(18,2) NULL DEFAULT 0.00, `zbst_total` DECIMAL(18,2) NOT NULL DEFAULT 0.00, `zbst_date_paid` INT(14) NULL DEFAULT NULL, `zbst_date_completed` INT(14) NULL DEFAULT NULL, `zbst_created` INT(14) NOT NULL, `zbst_lastupdated` INT(14) NOT NULL, PRIMARY KEY (`ID`), INDEX `status` (`zbst_status` ASC), INDEX `ref` (`zbst_ref` ASC), INDEX `transtype` (`zbst_type` ASC), INDEX `transorigin` (`zbst_origin` ASC), INDEX `parent` (`zbst_parent` ASC), INDEX `hash` (`zbst_hash` ASC), INDEX `date` (`zbst_date` ASC), INDEX `title` (`zbst_title` ASC), INDEX `created` (`zbst_created` ASC)) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); // Security logs (used to stop repeat brute-forcing quote/inv hashes etc.) $sql = "CREATE TABLE IF NOT EXISTS ". $ZBSCRM_t['security_log'] ."( `ID` INT NOT NULL AUTO_INCREMENT, `zbs_site` INT NULL DEFAULT NULL, `zbs_team` INT NULL DEFAULT NULL, `zbs_owner` INT NOT NULL, `zbssl_reqtype` VARCHAR(20) NOT NULL, `zbssl_ip` VARCHAR(200) NULL DEFAULT NULL, `zbssl_reqhash` VARCHAR(128) NULL DEFAULT NULL, `zbssl_reqid` INT(11) NULL DEFAULT NULL, `zbssl_loggedin_id` INT(11) NULL DEFAULT NULL, `zbssl_reqstatus` INT(1) NULL DEFAULT NULL, `zbssl_reqtime` INT(14) NULL DEFAULT NULL, PRIMARY KEY (`ID`)) ".$storageEngineLine." DEFAULT CHARACTER SET = ".$characterSet." COLLATE = ".$collation.";"; zeroBSCRM_db_runDelta($sql); // Add table to store automation workflows. // phpcs:disable WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $sql = 'CREATE TABLE IF NOT EXISTS ' . $ZBSCRM_t['automation-workflows'] . '( `id` INT NOT NULL AUTO_INCREMENT, `zbs_site` INT NOT NULL, `zbs_team` INT NOT NULL, `zbs_owner` INT NOT NULL, `name` VARCHAR(255) NOT NULL, `description` VARCHAR(600) NULL DEFAULT NULL, `category` VARCHAR(255) NOT NULL, `triggers` LONGTEXT NOT NULL, `initial_step` VARCHAR(255) NOT NULL, `steps` LONGTEXT NOT NULL, `active` TINYINT(1) NOT NULL DEFAULT 0, `version` INT(14) NOT NULL DEFAULT 1, `created_at` INT(14) DEFAULT NULL, `updated_at` INT(14) DEFAULT NULL, PRIMARY KEY (`id`), INDEX `name` (`name` ASC), INDEX `active` (`active` ASC), INDEX `category` (`category` ASC), INDEX `created_at` (`created_at` ASC) ) ' . $storageEngineLine . ' DEFAULT CHARACTER SET = ' . $characterSet . ' COLLATE = ' . $collation . ';'; // phpcs:enable WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase zeroBSCRM_db_runDelta( $sql ); // As of v5.0, if we've created via the above SQL, we're at DAL3 :) // so on fresh installs, immitate the fact that we've 'completed' DAL1->DAL2->DAL3 Migration chain update_option( 'zbs_db_migration_253', array('completed'=>time(),'started'=>time()), false); update_option( 'zbs_db_migration_300', array('completed'=>time(),'started'=>time()), false); // if any errors, log to wp option (potentially can't save to our zbs settings table because may not exist) $errors = $zbsDB_creationErrors; if (is_array($errors)){ if (count($errors) > 0) update_option( 'zbs_db_creation_errors', array('lasttried' => time(),'errors' => $errors), false); else delete_option( 'zbs_db_creation_errors' ); // successful run kills the alert } // no longer needed unset($zbsDB_lastError,$zbsDB_creationErrors); // return any errors encountered return $errors; } #} Check existence & Create func #} WH NOTE: This could be more efficient (once we have a bunch of tabs) function zeroBSCRM_checkTablesExist(){ global $ZBSCRM_t, $wpdb; $create = false; // then we cycle through our tables :) - means all keys NEED to be kept up to date :) // No need to add to this ever now :) if ( ! $create ) { foreach ( $ZBSCRM_t as $tableKey => $tableName ) { $tablesExist = $wpdb->get_results( "SHOW TABLES LIKE '" . $tableName . "'" ); if ( count( $tablesExist ) < 1 ) { $create = true; break; } } } if ( $create ) { zeroBSCRM_createTables(); } // hooked in by extensions do_action( 'zbs_db_check' ); return $create; } /** * Attempts to run $sql through dbDelta, adding any errors to the stack as it encounters them * */ function zeroBSCRM_db_runDelta($sql=''){ global $wpdb,$zbsDB_lastError,$zbsDB_creationErrors; // enact dbDelta($sql); // catch any (new) errors if (isset($wpdb->last_error) && $wpdb->last_error !== $zbsDB_lastError) { // add to the stack $zbsDB_creationErrors[] = $wpdb->last_error; // clock it as latest error $zbsDB_lastError = $wpdb->last_error; } } /** * returns availability of InnoDB MySQL Storage Engine * * gh-470, some users on some installs did not have InnoDB * Used in table creation to force InnoDB use where possible, * ... and also used to expose availability via System Status UI * * @return bool (if InnoDB available) */ function zeroBSCRM_DB_canInnoDB(){ if ( jpcrm_database_engine() === 'sqlite' ) { return false; } global $wpdb; // attempt to cycle through MySQL's ENGINES & discern InnoDB $availableStorageEngines = $wpdb->get_results('SHOW ENGINES'); if (is_array($availableStorageEngines)) foreach ($availableStorageEngines as $engine){ if (is_object($engine) && isset($engine->Engine) && $engine->Engine == 'InnoDB') return true; } return false; } /** * Get info about the database engine. * * @param boolean $pretty Retrieve a user-friendly label instead of a slug. * * @return string */ function jpcrm_database_engine( $pretty = false ) { global $zbs; if ( $pretty ) { return $zbs->database_server_info['db_engine_label']; } return $zbs->database_server_info['db_engine']; } /** * Get the database version. * * @return string */ function zeroBSCRM_database_getVersion() { global $zbs; return $zbs->database_server_info['raw_version']; } function jpcrm_database_server_has_ability( $ability_name ) { global $zbs; $db_server_version = zeroBSCRM_database_getVersion(); $db_engine = $zbs->database_server_info['db_engine']; if ( $ability_name === 'fulltext_index' ) { if ( $db_engine === 'sqlite' ) { return false; } elseif ( $db_engine === 'mariadb' ) { // first stable 10.x release return version_compare( $db_server_version, '10.0.10', '>=' ); } else { // https://dev.mysql.com/doc/refman/5.6/en/mysql-nutshell.html return version_compare( $db_server_version, '5.6', '>=' ); } } return false; } /* ====================================================== / Table Creation ====================================================== */ /* ====================================================== Uninstall Funcs ====================================================== */ /** * dangerous, brutal, savage. * * This one removes all data except settings & migrations * see zeroBSCRM_database_nuke for the full show. * * @param bool $check_permissions (default true) whether to check current user can manage_options. * @return void */ function zeroBSCRM_database_reset( $check_permissions = true ) { if ( $check_permissions && ! current_user_can( 'manage_options' ) ) { return; } #} Brutal Reset of DB settings & removal of tables global $wpdb, $ZBSCRM_t; #} DAL 2.0 CPTs $post_types = array('zerobs_transaction', 'zerobs_customer', 'zerobs_invoice', 'zerobs_company', 'zerobs_event', 'zerobs_log', 'zerobs_quote', 'zerobs_ticket','zerobs_quo_template'); foreach ($post_types as $post_type) $wpdb->query("DELETE FROM $wpdb->posts WHERE `post_type` = '$post_type'"); #} DAL 2.0 Taxonomies $taxonomies = array('zerobscrm_tickettag', 'zerobscrm_transactiontag', 'zerobscrm_customertag','zerobscrm_worktag'); foreach ($taxonomies as $tax) $wpdb->query("DELETE FROM $wpdb->term_taxonomy WHERE `taxonomy` = '$tax'"); $wpdb->query("UPDATE $wpdb->term_taxonomy SET count = 0 WHERE `taxonomy` = 'zerobscrm_transactiontag'"); #} Floating Meta $post_meta = array('zbs_woo_unique_ID', 'zbs_paypal_unique_ID', 'zbs_woo_unique_inv_ID', 'zbs_stripe_unique_inv_ID', 'zbs_transaction_meta', 'zbs_customer_meta','zbs_customer_ext_str','zbs_customer_ext_woo','zbs_event_meta','zbs_event_actions'); foreach ($post_meta as $meta) $wpdb->query("DELETE FROM $wpdb->postmeta WHERE `meta_key` = '$meta'"); $wpdb->query("DELETE FROM $wpdb->postmeta WHERE `meta_key` LIKE 'zbs_obj_ext_%';"); #} WP Options - Not settings/migrations, just data related options $options = array( 'zbs_woo_first_import_complete', 'zbs_transaction_stripe_hist', 'zbs_transaction_paypal_hist', 'zbs_pp_latest','zbscrmcsvimpresumeerrors', 'zbs_stripe_last_charge_added','zbs_stripe_pages_imported','zbs_stripe_total_pages', ); foreach ($options as $option) $wpdb->query($wpdb->prepare("DELETE FROM $wpdb->options WHERE `option_name` = %s",array($option))); // phpcs:disable Generic.WhiteSpace.ScopeIndent.Incorrect,Generic.WhiteSpace.ScopeIndent.IncorrectExact,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching // DAL 3.0 tables. $ZBSCRM_t['totaltrans'] = $wpdb->prefix . 'zbs_global_total_trans'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase foreach ( $ZBSCRM_t as $k => $v ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // Do not truncate the settings. if ( $k !== 'settings' ) { // Copy how maybe_create_table() looks for existing tables. if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $v ) ) ) !== $v ) { continue; } $wpdb->query( 'TRUNCATE TABLE ' . $v ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared } } // phpcs:enable Generic.WhiteSpace.ScopeIndent.Incorrect,Generic.WhiteSpace.ScopeIndent.IncorrectExact,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching } // dangerous, brutal, savage removal of all ZBS signs /* ___________________ . , ; . (___________________|~~~~~X.;' . ' `" ' ` TNT */ function zeroBSCRM_database_nuke(){ if (current_user_can('manage_options')){ #} Brutal Reset of DB settings & removal of tables global $wpdb, $ZBSCRM_t; #} Deactivate Extensions zeroBSCRM_extensions_deactivateAll(); #} DAL 2.0 CPTs $post_types = array('zerobs_transaction', 'zerobs_customer', 'zerobs_invoice', 'zerobs_company', 'zerobs_event', 'zerobs_log', 'zerobs_quote', 'zerobs_ticket','zerobs_quo_template'); foreach ($post_types as $post_type) $wpdb->query("DELETE FROM $wpdb->posts WHERE `post_type` = '$post_type'"); #} DAL 2.0 Taxonomies $taxonomies = array('zerobscrm_tickettag', 'zerobscrm_transactiontag', 'zerobscrm_customertag','zerobscrm_worktag'); foreach ($taxonomies as $tax) $wpdb->query("DELETE FROM $wpdb->term_taxonomy WHERE `taxonomy` = '$tax'"); $wpdb->query("UPDATE $wpdb->term_taxonomy SET count = 0 WHERE `taxonomy` = 'zerobscrm_transactiontag'"); #} Floating Meta $post_meta = array('zbs_woo_unique_ID', 'zbs_paypal_unique_ID', 'zbs_woo_unique_inv_ID', 'zbs_stripe_unique_inv_ID', 'zbs_transaction_meta', 'zbs_customer_meta','zbs_customer_ext_str','zbs_customer_ext_woo','zbs_event_meta','zbs_event_actions'); foreach ($post_meta as $meta) $wpdb->query("DELETE FROM $wpdb->postmeta WHERE `meta_key` = '$meta'"); $wpdb->query("DELETE FROM $wpdb->postmeta WHERE `meta_key` LIKE 'zbs_obj_ext_%';"); #} WP Options - this tries to capture all, as from pre v3 we were not using formal naming conventions $options = array( 'zbs_woo_first_import_complete', 'zbs_transaction_stripe_hist', 'zbs_transaction_paypal_hist', 'zbs_pp_latest', 'zbsmigrations','zbs_teleactive','zbs_update_avail','zbscptautodraftclear','zbs_wizard_run','zbscrmcsvimpresumeerrors','zbs_crm_api_key','zbs_crm_api_secret','zbs-global-perf-test','zbsmc2indexes', 'zbs_stripe_last_charge_added','zbs_stripe_pages_imported','zbs_stripe_total_pages', 'widget_zbs_form_widget','zerobscrmsettings','zbsmigrationpreloadcatch','zbs_db_migration_253','zerobscrmsettings_bk', 'zbs_db_migration_300_pre_exts','zbs_db_migration_300_cftrans','zbs_db_migration_300_errstack','zbs_db_migration_300_cf','zbs_db_migration_300','zbs_children_processed','zbs_pp_latest',' _transient_timeout_zbs-nag-extension-update-now','_transient_zbs-nag-extension-update-now' ); foreach ($options as $option) $wpdb->query($wpdb->prepare("DELETE FROM $wpdb->options WHERE `option_name` = %s",array($option))); #} WP options - catchalls (be careful to only cull zbs settings here) $wpdb->query("DELETE FROM {$wpdb->options} WHERE `option_name` LIKE 'zbsmigration%'"); $wpdb->query("DELETE FROM {$wpdb->options} WHERE `option_name` LIKE '%zbs-db2%'"); $wpdb->query("DELETE FROM {$wpdb->options} WHERE `option_name` LIKE '%zbs-db3%'"); #} DROP all DAL 3.0 tables $ZBSCRM_t['totaltrans'] = $wpdb->prefix . "zbs_global_total_trans"; foreach ($ZBSCRM_t as $k => $v)$wpdb->query("DROP TABLE " . $v); } } /* ====================================================== / Uninstall Funcs ====================================================== */
projects/plugins/crm/includes/ZeroBSCRM.MetaBoxes3.Companies.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V3.0 * * Copyright 2020 Automattic * * Date: 20/02/2019 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== Init Func ====================================================== */ function zeroBSCRM_CompaniesMetaboxSetup(){ // main deets $zeroBS__Metabox_Company = new zeroBS__Metabox_Company( __FILE__ ); // Actions (Save + status) $zeroBS__Metabox_CompanyActions = new zeroBS__Metabox_CompanyActions( __FILE__ ); // contacts $zeroBS__Metabox_CompanyContacts = new zeroBS__Metabox_CompanyContacts( __FILE__ ); // Tags $zeroBS__Metabox_CompanyTags = new zeroBS__Metabox_CompanyTags( __FILE__ ); // files $zeroBS__Metabox_CompanyFiles = new zeroBS__Metabox_CompanyFiles( __FILE__ ); // external sources $zeroBS__Metabox_ExtSource = new zeroBS__Metabox_ExtSource( __FILE__, 'company','zbs-add-edit-company-edit'); #} Activity box on view page if(zeroBSCRM_is_company_view_page()){ $zeroBS__Metabox_Company_Activity = new zeroBS__Metabox_Company_Activity( __FILE__ ); } #} Ownership if (zeroBSCRM_getSetting('perusercustomers') == "1") $zeroBS__CoMetabox_Ownership = new zeroBS__Metabox_Ownership( __FILE__, ZBS_TYPE_COMPANY); } add_action( 'admin_init','zeroBSCRM_CompaniesMetaboxSetup'); /* ====================================================== / Init Func ====================================================== */ /* ====================================================== Company Metabox ====================================================== */ class zeroBS__Metabox_Company extends zeroBS__Metabox{ // this is for catching 'new' companys private $newRecordNeedsRedir = false; private $coOrgLabel = ''; public function __construct( $plugin_file ) { // oldschool. $this->coOrgLabel = jpcrm_label_company(); // set these $this->objType = 'company'; $this->metaboxID = 'zerobs-company-edit'; $this->metaboxTitle = $this->coOrgLabel.' '.__('Details','zero-bs-crm'); $this->metaboxScreen = 'zbs-add-edit-company-edit'; $this->metaboxArea = 'normal'; $this->metaboxLocation = 'high'; $this->saveOrder = 1; $this->capabilities = array( 'can_hide' => false, // can be hidden 'areas' => array('normal'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => true, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true, // can be minimised 'can_move' => true // can be moved ); // call this $this->initMetabox(); } public function html( $company, $metabox ) { global $zbs; // localise ID $companyID = -1; if (is_array($company) && isset($company['id'])) $companyID = (int)$company['id']; // PerfTest: zeroBSCRM_performanceTest_startTimer('custmetabox-dataget'); #} Rather than reload all the time :) global $zbsCompanyEditing; if (!isset($zbsCompanyEditing)){ $zbsCompany = zeroBS_getCompany($companyID,false); $zbsCompanyEditing = $zbsCompany; } else { $zbsCompany = $zbsCompanyEditing; } global $zbsCompanyFields; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $fields = $zbsCompanyFields; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $show_id = (int) $zbs->settings->get( 'showid' ); $fields_to_hide = $zbs->settings->get( 'fieldhides' ); $show_addresses = (int) $zbs->settings->get( 'showaddress' ); $show_second_address = (int) $zbs->settings->get( 'secondaddress' ); $show_country_fields = $zbs->settings->get( 'countries' ); $second_address_label = $zbs->settings->get( 'secondaddresslabel' ); if ( empty( $second_address_label ) ) { $second_address_label = __( 'Second Address', 'zero-bs-crm' ); } ?> <script type="text/javascript">var zbscrmjs_secToken = '<?php echo esc_js( wp_create_nonce( 'zbscrmjs-ajax-nonce' ) ); ?>';</script> <?php #} Pass this if it's a new customer (for internal automator) - note added this above with DEFINE for simpler. if (gettype($zbsCompany) != "array") echo '<input type="hidden" name="zbscrm_newcompany" value="1" />'; ?> <div> <div class="jpcrm-form-grid" id="wptbpMetaBoxMainItem"> <?php #} WH Hacky quick addition for MVP # ... further hacked if ( $show_id === 1 && $companyID > 0 ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?> <div class="jpcrm-form-group"> <label class="jpcrm-form-label"><?php echo esc_html( $this->coOrgLabel ) . ' '; esc_html_e( 'ID', 'zero-bs-crm' ); // phpcs:ignore Generic.Formatting.DisallowMultipleStatements.SameLine, WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase, Squiz.PHP.EmbeddedPhp.MultipleStatements ?>:</label> <b>#<?php echo isset( $companyID ) ? esc_html( $companyID ) : ''; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?></b> </div> <div class="jpcrm-form-group"> </div> <?php } ?> <?php global $zbsFieldsEnabled; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase if ( $show_second_address === 1 ) { $zbsFieldsEnabled['secondaddress'] = true; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } $field_group = ''; foreach ( $fields as $field_key => $field_value ) { $show_field = ! isset( $field_value['opt'] ) || isset( $zbsFieldsEnabled[ $field_value['opt'] ] ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $show_field = isset( $fields_to_hide['company'] ) && is_array( $fields_to_hide['company'] ) && in_array( $field_key, $fields_to_hide['company'] ) // phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict ? false : $show_field; $show_field = isset( $field_value[0] ) && 'selectcountry' === $field_value[0] && 0 === $show_country_fields ? false : $show_field; if ( isset( $field_value['area'] ) && $field_value['area'] !== '' ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase if ( $show_addresses !== 1 ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase continue; } elseif ( $field_group === '' ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase echo '<div class="jpcrm-form-grid" style="padding:0px;grid-template-columns: 1fr;">'; echo '<div class="jpcrm-form-group"><label>'; echo esc_html__( $field_value['area'], 'zero-bs-crm' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, WordPress.WP.I18n.NonSingularStringLiteralText echo '</label></div>'; } elseif ( $field_group !== $field_value['area'] ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase echo '</div>'; echo '<div class="jpcrm-form-grid" style="padding:0px;grid-template-columns: 1fr;">'; echo '<div class="jpcrm-form-group"><label>'; echo $show_field ? esc_html( $second_address_label ) : ''; echo '</label></div>'; } $field_group = $field_value['area']; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase, WordPress.WP.I18n.NonSingularStringLiteralText } if ( $field_group !== '' && ( ! isset( $field_value['area'] ) || $field_value['area'] === '' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $field_group = ''; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase echo '</div>'; echo '<div class="jpcrm-form-group jpcrm-form-group-span-2">&nbsp;</div>'; } if ( $show_field ) { if ( isset( $field_value[0] ) ) { if ( $field_group === 'Second Address' ) { $field_value[1] = str_replace( ' (' . $second_address_label . ')', '', $field_value[1] ); } zeroBSCRM_html_editField( $zbsCompany, $field_key, $field_value, 'zbsco_' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } } } ?> </div> </div> <script type="text/javascript"> jQuery(function(){ zbscrm_JS_bindFieldValidators(); }); </script><?php // PerfTest: zeroBSCRM_performanceTest_finishTimer('custmetabox-draw'); } public function save_data( $company_id, $company ) { if (!defined('ZBS_CO_SAVED')){ // debug if (get_current_user_id() == 12) echo 'FIRING<br>'; define('ZBS_CO_SAVED',1); // DAL3.0+ global $zbs; // check this if (empty($company_id) || $company_id < 1) $company_id = -1; // retrieve data in format //... by using zeroBS_buildCompanyMeta, custom fields are 'dealt with' automatically $dataArr = zeroBS_buildCompanyMeta($_POST); // Use the tag-class function to retrieve any tags so we can add inline. // Save tags against objid $dataArr['tags'] = zeroBSCRM_tags_retrieveFromPostBag(true,ZBS_TYPE_COMPANY); // owner - saved here now, rather than ownership box, to allow for pre-hook update. (as tags) $owner = -1; if (isset($_POST['zerobscrm-owner'])){ // should this have perms check to see if user can actually assign to? or should that be DAL? $potentialOwner = (int)sanitize_text_field( $_POST['zerobscrm-owner'] ); if ($potentialOwner > 0) $owner = $potentialOwner; } /* debug echo '_POST:<pre>'.print_r($_POST,1).'</pre>'; echo 'dataArr:<pre>'.print_r($dataArr,1).'</pre>'; exit(); */ // now we check whether a user with this email already exists (separate to this company id), so we can warn them // ... that it wont have changed the email if (isset($dataArr['email']) && !empty($dataArr['email'])){ $potentialID = zeroBS_getCompanyIDWithEmail($dataArr['email']); if (!empty($potentialID) && $potentialID != $company_id){ // no go. $this->updateEmailDupeMessage($potentialID); // unset email change (leave as was) $dataArr['email'] = zeroBS_companyEmail($company_id); } } #AVATARSAVE - save any avatar change if changed :) if (isset($_POST['zbs-company-avatar-custom-url']) && !empty($_POST['zbs-company-avatar-custom-url'])) $dataArr['avatar'] = sanitize_text_field( $_POST['zbs-company-avatar-custom-url'] ); // Stripslashes // This avoids us adding `O\'toole ltd' into the db. see #1107 // ...this is more sensitive than using zeroBSCRM_stripSlashesFromArr // in the long term it may make more sense to stripslashes pre insert/update in the DAL // in the case of companies, there are no core fields which will be broken by stripslashes at this time (4.0.11) $data_array = $dataArr; foreach ($dataArr as $key => $val){ // op strings $value = $val; if ( is_string( $value ) ) $value = stripslashes( $value ); // pass into final array $data_array[$key] = $value; } // add update directly $addUpdateReturn = $zbs->DAL->companies->addUpdateCompany(array( 'id' => $company_id, 'owner' => $owner, 'data' => $data_array, 'limitedFields' => -1, )); // Note: For NEW contacts, we make sure a global is set here, that other update funcs can catch // ... so it's essential this one runs first! // this is managed in the metabox Class :) if ($company_id == -1 && !empty($addUpdateReturn) && $addUpdateReturn != -1) { $company_id = $addUpdateReturn; global $zbsJustInsertedMetaboxID; $zbsJustInsertedMetaboxID = $company_id; // set this so it redirs $this->newRecordNeedsRedir = true; } // success? if ($addUpdateReturn != -1 && $addUpdateReturn > 0){ // Update Msg // this adds an update message which'll go out ahead of any content // This adds to metabox: $this->updateMessages['update'] = zeroBSCRM_UI2_messageHTML('info olive mini zbs-not-urgent',__('Contact Updated',"zero-bs-crm"),'','address book outline','contactUpdated'); // This adds to edit page $this->updateMessage( $this->newRecordNeedsRedir ); // catch any non-critical messages $nonCriticalMessages = $zbs->DAL->getErrors(ZBS_TYPE_COMPANY); if (is_array($nonCriticalMessages) && count($nonCriticalMessages) > 0) $this->dalNoticeMessage($nonCriticalMessages); } else { // fail somehow $failMessages = $zbs->DAL->getErrors(ZBS_TYPE_COMPANY); // show msg (retrieved from DAL err stack) if (is_array($failMessages) && count($failMessages) > 0) $this->dalErrorMessage($failMessages); else $this->dalErrorMessage(array(__('Insert/Update Failed with general error','zero-bs-crm'))); // pass the pre-fill: global $zbsObjDataPrefill; $zbsObjDataPrefill = $dataArr; } } return $company; } // This catches 'new' contacts + redirs to right url public function post_save_data($objID,$obj){ if ($this->newRecordNeedsRedir){ global $zbs, $zbsJustInsertedMetaboxID; if (!empty($zbsJustInsertedMetaboxID) && $zbsJustInsertedMetaboxID > 0){ // redir $zbs->new_record_edit_redirect( $this->objType, $zbsJustInsertedMetaboxID ); } } } public function updateMessage( $created = false ) { $message = $this->coOrgLabel . ' ' . ( $created ? __( 'Created', 'zero-bs-crm' ) : __( 'Updated', 'zero-bs-crm' ) ); // zbs-not-urgent means it'll auto hide after 1.5s $msg = zeroBSCRM_UI2_messageHTML('info olive mini zbs-not-urgent', $message,'','address book outline','companyUpdated'); // quick + dirty global $zbs; $zbs->pageMessages[] = $msg; } public function updateEmailDupeMessage($otherCompanyID=-1){ global $zbs; $viewHTML = ' <a href="'.jpcrm_esc_link('view',$otherCompanyID,$this->objType).'" target="_blank">'.__('View','zero-bs-crm').' '.$this->coOrgLabel.'</a>'; $msg = zeroBSCRM_UI2_messageHTML('info orange mini',__('Email could not be updated. (A record already exists with this email address).',"zero-bs-crm").$viewHTML,'','address book outline','companyNotUpdated'); $zbs->pageMessages[] = $msg; } } /* ====================================================== / Company Metabox ====================================================== */ /* ====================================================== "Contacts at Company" Metabox ====================================================== */ class zeroBS__Metabox_CompanyContacts extends zeroBS__Metabox{ private $coOrgLabel = ''; public function __construct( $plugin_file ) { // oldschool. $this->coOrgLabel = jpcrm_label_company(); $this->objType = 'company'; $this->metaboxID = 'zerobs-company-contacts'; $this->metaboxTitle = __('Associated Contacts',"zero-bs-crm"); $this->metaboxScreen = 'zbs-add-edit-company-edit'; //'zerobs_edit_contact'; // we can use anything here as is now using our func $this->metaboxArea = 'normal'; $this->metaboxLocation = 'high'; $this->headless = false; //$this->metaboxClasses = ''; $this->capabilities = array( 'can_hide' => false, // can be hidden 'areas' => array('normal'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => false, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => false, // can be minimised 'can_move' => false // can be moved ); // hide if "new" (not edit) - as can't yet add this way $isEdit = false; if (isset($_GET['action']) && $_GET['action'] == 'edit' && isset($_GET['zbsid']) && !empty($_GET['zbsid'])) $isEdit = true; if ($isEdit){ // call this $this->initMetabox(); } } public function html( $company, $metabox ) { global $zbs; $coID = -1; if (is_array($company) && isset($company['id'])) $coID = (int)$company['id']; //$contacts = zeroBS_getCustomers(true,1000,0,false,false,'',false,false,$coID); $contacts = array(); if ($coID > 0){ $contacts = $zbs->DAL->contacts->getContacts(array( 'inCompany' => $coID, 'sortByField' => 'ID', 'sortOrder' => 'ASC', 'page' => 0, 'perPage' => 200, 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership(ZBS_TYPE_CONTACT) )); } #} JUST OUTPUT ?><table class="form-table wh-metatab wptbp" id="wptbpMetaBoxMainItemContacts"> <tr class="wh-large"><th> <?php if (count($contacts) > 0){ echo '<div id="zbs-co-contacts" class="ui cards">'; foreach ($contacts as $contact){ #} new view link $contactUrl = jpcrm_esc_link('view',$contact['id'],'zerobs_customer'); #} Name $contactName = zeroBS_customerName($contact['id'],$contact,false,false); $contactFirstName = ''; if (isset($contact['fname'])) $contactFirstName = $contact['fname']; #} Description $contactDesc = '<i class="calendar alternate outline icon"></i>' . __('Contact since',"zero-bs-crm").' '.zeroBSCRM_date_i18n(zeroBSCRM_getDateFormat(), $contact['createduts'], true, false); if (isset($contact['email']) && !empty($contact['email'])) $contactDesc .= '<br /><a href="'.$contactUrl.'" target="_blank">'.$contact['email'].'</a>'; ?><div class="card"> <div class="content"> <div class="center aligned header"><?php echo '<a href="'.esc_attr($contactUrl).'">'.esc_html($contactName).'</a>'; ?></div> <?php if (!empty($contactDesc)){ ?> <div class="center aligned description"> <p><?php echo $contactDesc; ?></p> </div> <?php } ?> </div> <div class="extra content"> <div class="center aligned author"> <?php #} Img or ico echo zeroBS_getCustomerIcoHTML($contact['id'],'ui avatar image').' '. esc_html( $contactFirstName ); ?> </div> </div> </div><?php } echo '</div>'; } else { echo '<div style="margin-left:auto;margin-right:auto;display:inline-block">'; esc_html_e('No contacts found at',"zero-bs-crm"); echo ' ' . esc_html( $this->coOrgLabel ); echo '</div>'; } ?> </th></tr> </table> <script type="text/javascript"> jQuery(function(){ }); </script> <?php } public function save_data( $companyID, $company ) { // none as of yet return $company; } } /* ====================================================== / "Contacts at Company" Metabox ====================================================== */ /* ====================================================== Create Tags Box ====================================================== */ class zeroBS__Metabox_CompanyTags extends zeroBS__Metabox_Tags{ public function __construct( $plugin_file ) { $this->objTypeID = ZBS_TYPE_COMPANY; $this->objType = 'company'; $this->metaboxID = 'zerobs-company-tags'; $this->metaboxTitle = __(jpcrm_label_company().' Tags',"zero-bs-crm"); $this->metaboxScreen = 'zbs-add-edit-company-edit'; //'zerobs_edit_contact'; // we can use anything here as is now using our func $this->metaboxArea = 'side'; $this->metaboxLocation = 'high'; $this->showSuggestions = true; $this->capabilities = array( 'can_hide' => true, // can be hidden 'areas' => array('side'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => false, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true // can be minimised ); // call this $this->initMetabox(); } // html + save dealt with by parent class :) } /* ====================================================== / Create Tags Box ====================================================== */ /* ====================================================== Attach files to company metabox ====================================================== */ class zeroBS__Metabox_CompanyFiles extends zeroBS__Metabox{ public function __construct( $plugin_file ) { $this->objType = 'company'; $this->metaboxID = 'zerobs-company-files'; $this->metaboxTitle = __('Files',"zero-bs-crm"); $this->metaboxScreen = 'zbs-add-edit-company-edit'; //'zerobs_edit_contact'; // we can use anything here as is now using our func $this->metaboxArea = 'normal'; $this->metaboxLocation = 'low'; $this->capabilities = array( 'can_hide' => true, // can be hidden 'areas' => array('normal'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => true, // can/can't accept tabs onto it 'can_become_tab' => true, // can be added as tab 'can_minimise' => true // can be minimised ); // call this $this->initMetabox(); } public function html( $company, $metabox ) { global $zbs; $html = ''; $companyID = -1; if (is_array($company) && isset($company['id'])) $companyID = (int)$company['id']; $zbsFiles = zeroBSCRM_files_getFiles('company',$companyID); ?><table class="form-table wh-metatab wptbp" id="wptbpMetaBoxMainItemFiles"> <?php #} Whole file delete method could do with rewrite #} Also sort JS into something usable - should be ajax all this #} Any existing if (is_array($zbsFiles) && count($zbsFiles) > 0){ ?><tr class="wh-large zbsFileDetails"><th class="zbsFilesTitle"><label><?php echo '<span>'.count($zbsFiles).'</span> '.esc_html__('File(s)','zero-bs-crm').':'; ?></label></th> <td id="zbsFileWrapOther"> <table class="ui celled table" id="zbsFilesTable"> <thead> <tr> <th><?php esc_html_e("File", 'zero-bs-crm');?></th> <th class="collapsing center aligned"><?php esc_html_e("Actions", 'zero-bs-crm');?></th> </tr> </thead><tbody> <?php $fileLineIndx = 1; foreach($zbsFiles as $zbsFile){ /* $file = basename($zbsFile['file']); // if in privatised system, ignore first hash in name if (isset($zbsFile['priv'])){ $file = substr($file,strpos($file, '-')+1); } */ $file = zeroBSCRM_files_baseName($zbsFile['file'],isset($zbsFile['priv'])); $fileEditUrl = admin_url('admin.php?page='.$zbs->slugs['editfile']) . "&company=".$companyID."&fileid=" . ($fileLineIndx-1); echo '<tr class="zbsFileLineTR" id="zbsFileLineTRCustomer'.esc_attr($fileLineIndx).'">'; echo '<td><div class="zbsFileLine" id="zbsFileLineCustomer'.esc_attr($fileLineIndx).'"><a href="' . esc_url( $zbsFile['url'] ) . '" target="_blank">' . esc_html( $file ) . '</a></div>'; // if using portal.. state shown/hidden // this is also shown in each file slot :) if you change any of it change that too /*if(defined('ZBS_CLIENTPRO_TEMPLATES')){ if(isset($zbsFile['portal']) && $zbsFile['portal']){ echo "<p><i class='icon check circle green inverted'></i> ".__('Shown on Portal','zero-bs-crm').'</p>'; }else{ echo "<p><i class='icon ban inverted red'></i> ".__('Not shown on Portal','zero-bs-crm').'</p>'; } }*/ echo '</td>'; echo '<td class="collapsing center aligned"><span class="zbsDelFile ui button basic" data-delurl="' . esc_attr( $zbsFile['url'] ) . '"><i class="trash alternate icon"></i> '.esc_html__('Delete','zero-bs-crm').'</span></td></tr>'; // <a href="'.$fileEditUrl.'" target="_blank" class="ui button basic"><i class="edit icon"></i> '.__('Edit','zero-bs-crm').'</a> $fileLineIndx++; } ?> </tbody></table> </td></tr><?php } ?> <?php #adapted from http://code.tutsplus.com/articles/attaching-files-to-your-posts-using-wordpress-custom-meta-boxes-part-1--wp-22291 $html .= '<input type="file" id="zbs_file_attachment" name="zbs_file_attachment" size="25" class="zbs-dc">'; ?><tr class="wh-large"><th><label><?php esc_html_e('Add File',"zero-bs-crm");?>:</label><br />(<?php esc_html_e('Optional',"zero-bs-crm");?>)<br /><?php esc_html_e('Accepted File Types',"zero-bs-crm");?>:<br /><?php echo esc_html( zeroBS_acceptableFileTypeListStr() ); ?></th> <td><?php wp_nonce_field(plugin_basename(__FILE__), 'zbs_file_attachment_nonce'); echo $html; ?></td></tr> </table> <?php // PerfTest: zeroBSCRM_performanceTest_finishTimer('custmetabox'); // PerfTest: zeroBSCRM_performanceTest_debugOut(); ?> <script type="text/javascript"> var zbsCurrentlyDeleting = false; var zbsMetaboxFilesLang = { 'error': '<?php echo esc_html( zeroBSCRM_slashOut(__('Error','zero-bs-crm')) ); ?>', 'unabletodelete': '<?php echo esc_html( zeroBSCRM_slashOut(__('Unable to delete this file.','zero-bs-crm')) ); ?>' }; jQuery(function(){ jQuery('.zbsDelFile').on( 'click', function(){ if (!window.zbsCurrentlyDeleting){ // blocking window.zbsCurrentlyDeleting = true; var delUrl = jQuery(this).attr('data-delurl'); //var lineIDtoRemove = jQuery(this).closest('.zbsFileLine').attr('id'); var lineToRemove = jQuery(this).closest('tr'); if (typeof delUrl != "undefined" && delUrl != ''){ // postbag! var data = { 'action': 'delFile', 'zbsfType': '<?php echo esc_html( $this->objType ); ?>', 'zbsDel': delUrl, // could be csv, never used though 'zbsCID': <?php echo esc_html( $companyID ); ?>, 'sec': window.zbscrmjs_secToken }; // Send it Pat :D jQuery.ajax({ type: "POST", url: ajaxurl, // admin side is just ajaxurl not wptbpAJAX.ajaxurl, "data": data, dataType: 'json', timeout: 20000, success: function(response) { var localLineToRemove = lineToRemove, localDelURL = delUrl; // visually remove //jQuery(this).closest('.zbsFileLine').remove(); //jQuery('#' + lineIDtoRemove).remove(); jQuery(localLineToRemove).remove(); // update number var newNumber = jQuery('#zbsFilesTable tr').length-1; if (newNumber > 0) jQuery('#wptbpMetaBoxMainItemFiles .zbsFilesTitle span').html(); else jQuery('#wptbpMetaBoxMainItemFiles .zbsFileDetails').remove(); // remove any filled slots (with this file) jQuery('.zbsFileSlotTable').each(function(ind,ele){ if (jQuery(ele).attr('data-sloturl') == localDelURL){ jQuery('.zbsFileSlotWrap',jQuery(ele)).remove(); } }); // file deletion errors, show msg: if (typeof response.errors != "undefined" && response.errors.length > 0){ jQuery.each(response.errors,function(ind,ele){ jQuery('#zerobs-company-files-box').append('<div class="ui warning message" style="margin-top:10px;">' + ele + '</div>'); }); } }, error: function(response){ jQuery('#zerobs-company-files-box').append('<div class="ui warning message" style="margin-top:10px;"><strong>' + window.zbsMetaboxFilesLang.error + ':</strong> ' + window.zbsMetaboxFilesLang.unabletodelete + '</div>'); } }); } window.zbsCurrentlyDeleting = false; } // / blocking }); }); </script><?php // PerfTest: zeroBSCRM_performanceTest_finishTimer('other'); } public function save_data( $companyID, $company ) { global $zbs, $zbsc_justUploadedFile; if(!empty($_FILES['zbs_file_attachment']['name']) && (!isset($zbsc_justUploadedFile) || (isset($zbsc_justUploadedFile) && $zbsc_justUploadedFile != $_FILES['zbs_file_attachment']['name']) ) ) { /* --- security verification --- */ if(!wp_verify_nonce($_POST['zbs_file_attachment_nonce'], plugin_basename(__FILE__))) { return $id; } // end if if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $id; } // end if if (!zeroBSCRM_permsCustomers()){ return $companyID; } /* - end security verification - */ #} Blocking repeat-upload bug $zbsc_justUploadedFile = $_FILES['zbs_file_attachment']['name']; // verify file extension and mime type if ( jpcrm_file_check_mime_extension( $_FILES['zbs_file_attachment'] ) ){ $company_dir_info = jpcrm_storage_dir_info_for_company( $companyID ); $upload = jpcrm_save_admin_upload_to_folder( 'zbs_file_attachment', $company_dir_info['files'] ); if(isset($upload['error']) && $upload['error'] != 0) { wp_die('There was an error uploading your file. The error is: ' . esc_html( $upload['error'] )); } else { // w mod - adds to array :) $zbsCompanyFiles = zeroBSCRM_files_getFiles('company',$companyID);//zeroBSCRM_getCustomerFiles($companyID); if (is_array($zbsCompanyFiles)){ //add it $zbsCompanyFiles[] = $upload; } else { // first $zbsCompanyFiles = array($upload); } // update zeroBSCRM_files_updateFiles('company',$companyID,$zbsCompanyFiles); // Fire any 'post-upload-processing' (e.g. CPP makes thumbnails of pdf, jpg, etc.) do_action('zbs_post_upload_company',$upload); } } else { wp_die("The file type that you've uploaded is not an accepted file format."); } } return $company; } } /* ====================================================== / Attach files to company metabox ====================================================== */ /* ====================================================== Company Actions Metabox Metabox ====================================================== */ class zeroBS__Metabox_CompanyActions extends zeroBS__Metabox{ private $coOrgLabel = ''; public function __construct( $plugin_file ) { // oldschool. $this->coOrgLabel = jpcrm_label_company(); // set these $this->objType = 'company'; $this->metaboxID = 'zerobs-company-actions'; $this->metaboxTitle = jpcrm_label_company().' '.__('Actions','zero-bs-crm'); // will be headless anyhow $this->headless = true; $this->metaboxScreen = 'zbs-add-edit-company-edit'; $this->metaboxArea = 'side'; $this->metaboxLocation = 'high'; $this->saveOrder = 1; $this->capabilities = array( 'can_hide' => false, // can be hidden 'areas' => array('side'), // areas can be dragged to - normal side = only areas currently 'can_accept_tabs' => true, // can/can't accept tabs onto it 'can_become_tab' => false, // can be added as tab 'can_minimise' => true, // can be minimised 'can_move' => true // can be moved ); // call this $this->initMetabox(); } public function html( $company, $metabox ) { ?><div class="zbs-generic-save-wrap"> <div class="ui medium dividing header"><i class="save icon"></i> <?php echo esc_html( jpcrm_label_company() ); ?> <?php esc_html_e('Actions','zero-bs-crm'); ?></div> <?php // localise ID & content $companyID = -1; if (is_array($company) && isset($company['id'])) $companyID = (int)$company['id']; #} if a saved post... //if (isset($post->post_status) && $post->post_status != "auto-draft"){ if ($companyID > 0){ // existing ?> <div class="zbs-company-actions-bottom zbs-objedit-actions-bottom"> <button class="ui button black" type="button" id="zbs-edit-save"><?php esc_html_e( 'Update', 'zero-bs-crm' ); ?> <?php echo esc_html( $this->coOrgLabel ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase ?></button> <?php // delete? // for now just check if can modify, later better, granular perms. if ( zeroBSCRM_permsQuotes() ) { ?><div id="zbs-company-actions-delete" class="zbs-objedit-actions-delete"> <a class="submitdelete deletion" href="<?php echo jpcrm_esc_link( 'delete', $companyID, 'company' ); ?>"><?php esc_html_e('Delete Permanently', "zero-bs-crm"); ?></a> </div> <?php } // can delete ?> <div class='clear'></div> </div> <?php } else { // NEW quote ?> <div class="zbs-company-actions-bottom zbs-objedit-actions-bottom"> <button class="ui button black" type="button" id="zbs-edit-save"><?php esc_html_e( 'Save', 'zero-bs-crm' ); ?> <?php echo esc_html( $this->coOrgLabel ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase ?></button> </div> <?php } ?></div><?php // / .zbs-generic-save-wrap } // html // saved via main metabox } /* ====================================================== / Company Actions Metabox ====================================================== */ /* ====================================================== Company Activity Metabox ====================================================== */ class zeroBS__Metabox_Company_Activity extends zeroBS__Metabox { public function __construct( $plugin_file ) { $this->metaboxID = 'zbs-company-activity-metabox'; $this->metaboxTitle = __('Activity', 'zero-bs-crm'); $this->metaboxIcon = 'heartbeat'; $this->metaboxScreen = 'zerobs_view_company'; // we can use anything here as is now using our func $this->metaboxArea = 'side'; $this->metaboxLocation = 'high'; // call this $this->initMetabox(); } public function html( $obj, $metabox ) { global $zbs; $objid = -1; if (is_array($obj) && isset($obj['id'])) $objid = $obj['id']; // no need for this, $obj will already be same $zbsCustomer = zeroBS_getCustomer($objid, true,true,true); echo '<div class="zbs-activity">'; echo '<div class="">'; $zbsCompanyActivity = zeroBSCRM_getCompanyLogs($objid,true,100,0,'',false); zeroBSCRM_html_companyTimeline($objid,$zbsCompanyActivity,$obj); echo '</div>'; echo '</div>'; } // nothing to save here. public function save_data( $objID, $obj ) { return $obj; } } /* ====================================================== Company Activity Metabox ====================================================== */
projects/plugins/crm/includes/jpcrm-fonts.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * Logic concerned with installing and using different fonts, primarily in the creation of PDF files * */ // Require DOMPDF global $zbs; $zbs->libLoad('dompdf'); use FontLib\Font; defined( 'ZEROBSCRM_PATH' ) || exit; /* * Class encapsulating logic concerned with installing and using different fonts */ class JPCRM_Fonts { public function __construct( ) { } /* * Returns a list of fonts available via our CDN: * * @param: $cleaned_alphabetical bool - if true return the list with 'Noto' moved to back of string and re-ordered to be alphabetic * ... e.g. 'Noto Kufi Arabic' => 'Kufi Arabic (Noto)' */ public function list_all_available( $cleaned_alphabetical=false ){ // generated by WH 30/11/21 // while we can add: ,"NotoSansJP.zip":"Noto Sans JP" - unfortunately dompdf isn't supporting .otf files yet // TBD: adding Japanese, Korean, sadly CJK? // Removed, though present in gh repo: "Arimo.zip":"Arimo","Cousine.zip":"Cousine" $font_json = '{"Boku2.zip":"Boku2","NotoKufiArabic.zip":"Noto Kufi Arabic","NotoLoopedLao.zip":"Noto Looped Lao","NotoLoopedLaoUI.zip":"Noto Looped Lao UI","NotoLoopedThai.zip":"Noto Looped Thai","NotoLoopedThaiUI.zip":"Noto Looped Thai UI","NotoMusic.zip":"Noto Music","NotoNaskhArabic.zip":"Noto Naskh Arabic","NotoNaskhArabicUI.zip":"Noto Naskh Arabic UI","NotoNastaliqUrdu.zip":"Noto Nastaliq Urdu","NotoRashiHebrew.zip":"Noto Rashi Hebrew","NotoSansAdlam.zip":"Noto Sans Adlam","NotoSansAdlamUnjoined.zip":"Noto Sans Adlam Unjoined","NotoSansAnatolianHieroglyphs.zip":"Noto Sans Anatolian Hieroglyphs","NotoSansArabic.zip":"Noto Sans Arabic","NotoSansArabicUI.zip":"Noto Sans Arabic UI","NotoSansArmenian.zip":"Noto Sans Armenian","NotoSansAvestan.zip":"Noto Sans Avestan","NotoSansBalinese.zip":"Noto Sans Balinese","NotoSansBamum.zip":"Noto Sans Bamum","NotoSansBassaVah.zip":"Noto Sans Bassa Vah","NotoSansBatak.zip":"Noto Sans Batak","NotoSansBengali.zip":"Noto Sans Bengali","NotoSansBengaliUI.zip":"Noto Sans Bengali UI","NotoSansBhaiksuki.zip":"Noto Sans Bhaiksuki","NotoSansBrahmi.zip":"Noto Sans Brahmi","NotoSansBuginese.zip":"Noto Sans Buginese","NotoSansBuhid.zip":"Noto Sans Buhid","NotoSansCanadianAboriginal.zip":"Noto Sans Canadian Aboriginal","NotoSansCarian.zip":"Noto Sans Carian","NotoSansCaucasianAlbanian.zip":"Noto Sans Caucasian Albanian","NotoSansChakma.zip":"Noto Sans Chakma","NotoSansCham.zip":"Noto Sans Cham","NotoSansCherokee.zip":"Noto Sans Cherokee","NotoSansCoptic.zip":"Noto Sans Coptic","NotoSansCuneiform.zip":"Noto Sans Cuneiform","NotoSansCypriot.zip":"Noto Sans Cypriot","NotoSansDeseret.zip":"Noto Sans Deseret","NotoSansDevanagari.zip":"Noto Sans Devanagari","NotoSansDevanagariUI.zip":"Noto Sans Devanagari UI","NotoSansDisplay.zip":"Noto Sans Display","NotoSansDuployan.zip":"Noto Sans Duployan","NotoSansEgyptianHieroglyphs.zip":"Noto Sans Egyptian Hieroglyphs","NotoSansElbasan.zip":"Noto Sans Elbasan","NotoSansElymaic.zip":"Noto Sans Elymaic","NotoSansEthiopic.zip":"Noto Sans Ethiopic","NotoSansGeorgian.zip":"Noto Sans Georgian","NotoSansGlagolitic.zip":"Noto Sans Glagolitic","NotoSansGothic.zip":"Noto Sans Gothic","NotoSansGrantha.zip":"Noto Sans Grantha","NotoSansGujarati.zip":"Noto Sans Gujarati","NotoSansGujaratiUI.zip":"Noto Sans Gujarati UI","NotoSansGunjalaGondi.zip":"Noto Sans Gunjala Gondi","NotoSansGurmukhi.zip":"Noto Sans Gurmukhi","NotoSansGurmukhiUI.zip":"Noto Sans Gurmukhi UI","NotoSansHanifiRohingya.zip":"Noto Sans Hanifi Rohingya","NotoSansHanunoo.zip":"Noto Sans Hanunoo","NotoSansHatran.zip":"Noto Sans Hatran","NotoSansHebrew.zip":"Noto Sans Hebrew","NotoSansImperialAramaic.zip":"Noto Sans Imperial Aramaic","NotoSansIndicSiyaqNumbers.zip":"Noto Sans Indic Siyaq Numbers","NotoSansInscriptionalPahlavi.zip":"Noto Sans Inscriptional Pahlavi","NotoSansInscriptionalParthian.zip":"Noto Sans Inscriptional Parthian","NotoSansJavanese.zip":"Noto Sans Javanese","NotoSansKaithi.zip":"Noto Sans Kaithi","NotoSansKannada.zip":"Noto Sans Kannada","NotoSansKannadaUI.zip":"Noto Sans Kannada UI","NotoSansKayahLi.zip":"Noto Sans Kayah Li","NotoSansKharoshthi.zip":"Noto Sans Kharoshthi","NotoSansKhmer.zip":"Noto Sans Khmer","NotoSansKhmerUI.zip":"Noto Sans Khmer UI","NotoSansKhojki.zip":"Noto Sans Khojki","NotoSansKhudawadi.zip":"Noto Sans Khudawadi","NotoSansLao.zip":"Noto Sans Lao","NotoSansLaoUI.zip":"Noto Sans Lao UI","NotoSansLepcha.zip":"Noto Sans Lepcha","NotoSansLimbu.zip":"Noto Sans Limbu","NotoSansLinearA.zip":"Noto Sans Linear A","NotoSansLinearB.zip":"Noto Sans Linear B","NotoSansLisu.zip":"Noto Sans Lisu","NotoSansLycian.zip":"Noto Sans Lycian","NotoSansLydian.zip":"Noto Sans Lydian","NotoSansMahajani.zip":"Noto Sans Mahajani","NotoSansMalayalam.zip":"Noto Sans Malayalam","NotoSansMalayalamUI.zip":"Noto Sans Malayalam UI","NotoSansMandaic.zip":"Noto Sans Mandaic","NotoSansManichaean.zip":"Noto Sans Manichaean","NotoSansMarchen.zip":"Noto Sans Marchen","NotoSansMasaramGondi.zip":"Noto Sans Masaram Gondi","NotoSansMath.zip":"Noto Sans Math","NotoSansMayanNumerals.zip":"Noto Sans Mayan Numerals","NotoSansMedefaidrin.zip":"Noto Sans Medefaidrin","NotoSansMeeteiMayek.zip":"Noto Sans Meetei Mayek","NotoSansMendeKikakui.zip":"Noto Sans Mende Kikakui","NotoSansMeroitic.zip":"Noto Sans Meroitic","NotoSansMiao.zip":"Noto Sans Miao","NotoSansModi.zip":"Noto Sans Modi","NotoSansMongolian.zip":"Noto Sans Mongolian","NotoSansMono.zip":"Noto Sans Mono","NotoSansMro.zip":"Noto Sans Mro","NotoSansMultani.zip":"Noto Sans Multani","NotoSansMyanmar.zip":"Noto Sans Myanmar","NotoSansMyanmarUI.zip":"Noto Sans Myanmar UI","NotoSansNKo.zip":"Noto Sans N Ko","NotoSansNabataean.zip":"Noto Sans Nabataean","NotoSansNewTaiLue.zip":"Noto Sans New Tai Lue","NotoSansNewa.zip":"Noto Sans Newa","NotoSansNushu.zip":"Noto Sans Nushu","NotoSansOgham.zip":"Noto Sans Ogham","NotoSansOlChiki.zip":"Noto Sans Ol Chiki","NotoSansOldHungarian.zip":"Noto Sans Old Hungarian","NotoSansOldItalic.zip":"Noto Sans Old Italic","NotoSansOldNorthArabian.zip":"Noto Sans Old North Arabian","NotoSansOldPermic.zip":"Noto Sans Old Permic","NotoSansOldPersian.zip":"Noto Sans Old Persian","NotoSansOldSogdian.zip":"Noto Sans Old Sogdian","NotoSansOldSouthArabian.zip":"Noto Sans Old South Arabian","NotoSansOldTurkic.zip":"Noto Sans Old Turkic","NotoSansOriya.zip":"Noto Sans Oriya","NotoSansOriyaUI.zip":"Noto Sans Oriya UI","NotoSansOsage.zip":"Noto Sans Osage","NotoSansOsmanya.zip":"Noto Sans Osmanya","NotoSansPahawhHmong.zip":"Noto Sans Pahawh Hmong","NotoSansPalmyrene.zip":"Noto Sans Palmyrene","NotoSansPauCinHau.zip":"Noto Sans Pau Cin Hau","NotoSansPhagsPa.zip":"Noto Sans Phags Pa","NotoSansPhoenician.zip":"Noto Sans Phoenician","NotoSansPsalterPahlavi.zip":"Noto Sans Psalter Pahlavi","NotoSansRejang.zip":"Noto Sans Rejang","NotoSansRunic.zip":"Noto Sans Runic","NotoSansSamaritan.zip":"Noto Sans Samaritan","NotoSansSaurashtra.zip":"Noto Sans Saurashtra","NotoSansSharada.zip":"Noto Sans Sharada","NotoSansShavian.zip":"Noto Sans Shavian","NotoSansSiddham.zip":"Noto Sans Siddham","NotoSansSignWriting.zip":"Noto Sans Sign Writing","NotoSansSinhala.zip":"Noto Sans Sinhala","NotoSansSinhalaUI.zip":"Noto Sans Sinhala UI","NotoSansSogdian.zip":"Noto Sans Sogdian","NotoSansSoraSompeng.zip":"Noto Sans Sora Sompeng","NotoSansSoyombo.zip":"Noto Sans Soyombo","NotoSansSundanese.zip":"Noto Sans Sundanese","NotoSansSylotiNagri.zip":"Noto Sans Syloti Nagri","NotoSansSymbols.zip":"Noto Sans Symbols","NotoSansSymbols2.zip":"Noto Sans Symbols2","NotoSansSyriac.zip":"Noto Sans Syriac","NotoSansTagalog.zip":"Noto Sans Tagalog","NotoSansTagbanwa.zip":"Noto Sans Tagbanwa","NotoSansTaiLe.zip":"Noto Sans Tai Le","NotoSansTaiTham.zip":"Noto Sans Tai Tham","NotoSansTaiViet.zip":"Noto Sans Tai Viet","NotoSansTakri.zip":"Noto Sans Takri","NotoSansTamil.zip":"Noto Sans Tamil","NotoSansTamilSupplement.zip":"Noto Sans Tamil Supplement","NotoSansTamilUI.zip":"Noto Sans Tamil UI","NotoSansTelugu.zip":"Noto Sans Telugu","NotoSansTeluguUI.zip":"Noto Sans Telugu UI","NotoSansThaana.zip":"Noto Sans Thaana","NotoSansThai.zip":"Noto Sans Thai","NotoSansThaiUI.zip":"Noto Sans Thai UI","NotoSansTifinagh.zip":"Noto Sans Tifinagh","NotoSansTirhuta.zip":"Noto Sans Tirhuta","NotoSansUgaritic.zip":"Noto Sans Ugaritic","NotoSansVai.zip":"Noto Sans Vai","NotoSansWancho.zip":"Noto Sans Wancho","NotoSansWarangCiti.zip":"Noto Sans Warang Citi","NotoSansYi.zip":"Noto Sans Yi","NotoSansZanabazarSquare.zip":"Noto Sans Zanabazar Square","NotoSerifAhom.zip":"Noto Serif Ahom","NotoSerifArmenian.zip":"Noto Serif Armenian","NotoSerifBalinese.zip":"Noto Serif Balinese","NotoSerifBengali.zip":"Noto Serif Bengali","NotoSerifDevanagari.zip":"Noto Serif Devanagari","NotoSerifDisplay.zip":"Noto Serif Display","NotoSerifDogra.zip":"Noto Serif Dogra","NotoSerifEthiopic.zip":"Noto Serif Ethiopic","NotoSerifGeorgian.zip":"Noto Serif Georgian","NotoSerifGrantha.zip":"Noto Serif Grantha","NotoSerifGujarati.zip":"Noto Serif Gujarati","NotoSerifGurmukhi.zip":"Noto Serif Gurmukhi","NotoSerifHebrew.zip":"Noto Serif Hebrew","NotoSerifKannada.zip":"Noto Serif Kannada","NotoSerifKhmer.zip":"Noto Serif Khmer","NotoSerifKhojki.zip":"Noto Serif Khojki","NotoSerifLao.zip":"Noto Serif Lao","NotoSerifMalayalam.zip":"Noto Serif Malayalam","NotoSerifMyanmar.zip":"Noto Serif Myanmar","NotoSerifNyiakengPuachueHmong.zip":"Noto Serif Nyiakeng Puachue Hmong","NotoSerifOriya.zip":"Noto Serif Oriya","NotoSerifSinhala.zip":"Noto Serif Sinhala","NotoSerifTamil.zip":"Noto Serif Tamil","NotoSerifTamilSlanted.zip":"Noto Serif Tamil Slanted","NotoSerifTangut.zip":"Noto Serif Tangut","NotoSerifTelugu.zip":"Noto Serif Telugu","NotoSerifThai.zip":"Noto Serif Thai","NotoSerifTibetan.zip":"Noto Serif Tibetan","NotoSerifVithkuqi.zip":"Noto Serif Vithkuqi","NotoSerifYezidi.zip":"Noto Serif Yezidi","NotoTraditionalNushu.zip":"Noto Traditional Nushu"}'; $return_array = json_decode( $font_json, true ); if ( $cleaned_alphabetical ){ $cleaned_array = array(); foreach ( $return_array as $zip_name => $font_name ){ $cleaned_name = $font_name; if ( str_starts_with( $font_name, 'Noto Sans' ) ) { $cleaned_name = substr( $cleaned_name, 10 ) . ' (Noto Sans)'; } elseif ( str_starts_with( $font_name, 'Noto Serif' ) ) { $cleaned_name = substr( $cleaned_name, 11 ) . ' (Noto Serif)'; } // special cases here (lets us keep our font array clean but show more info in UI) switch ( $cleaned_name ){ case 'Boku2': $cleaned_name = 'Boku2 (JP)'; break; } $cleaned_array[ $font_name ] = $cleaned_name; } // sort alphabetically asort( $cleaned_array ); return $cleaned_array; } return $return_array; } /* * Converts a font-name to its zip filename */ public function zip_to_font_name( $zip_file_name='' ){ return str_replace( '.zip', '', jpcrm_string_split_at_caps( $zip_file_name ) ); } /* * Converts a font-name to its zip filename */ public function font_name_to_zip( $font_name='' ){ return str_replace( ' ', '', $font_name ) . '.zip'; } /* * Converts a font-name to its *-Regular.ttf filename */ public function font_name_to_regular_ttf_name( $font_name='' ){ return str_replace( ' ', '', $font_name ) . '-Regular.ttf'; } /* * Converts a font-name to its ultimate directory */ public function font_name_to_dir( $font_name='' ){ return str_replace( '.zip', '', $this->font_name_to_zip( $font_name ) ); } /* * Converts a slug to a font name */ public function font_slug_to_name( $font_slug='' ){ return ucwords( str_replace( '-', ' ', $font_slug ) ); } /* * Converts a font-name to a slug equivalent */ public function font_name_to_slug( $font_name='' ){ global $zbs; return $zbs->DAL->makeSlug( $font_name ); } /* * Checks a font is on our available list */ public function font_is_available( $font_name='' ){ $fonts = $this->list_all_available(); if ( isset( $fonts[ $this->font_name_to_zip( $font_name ) ] ) ) { return true; } return false; } /* * Checks a font is on our available list */ public function font_is_installed( $font_name='' ){ if ( $this->font_is_available( $font_name ) ){ // Available? if ( file_exists( ZEROBSCRM_INCLUDE_PATH . 'lib/dompdf-fonts/' . $this->font_name_to_dir( $font_name ) ) ){ // Installed? (check setting) $font_install_setting = zeroBSCRM_getSetting('pdf_extra_fonts_installed'); if ( !is_array( $font_install_setting ) ){ $font_install_setting = array(); } if ( array_key_exists( $this->font_name_to_slug( $font_name ), $font_install_setting ) ){ return true; } } } return false; // font doesn't exist or isn't installed } /* * Installs fonts (which have already been downloaded, but are not marked installed) */ public function install_font( $font_name='', $force_reinstall=false ) { // is available, and not installed (or $force_reinstall) if ( $this->font_is_available( $font_name ) && ( !$this->font_is_installed( $font_name ) || $force_reinstall ) ) { // get fonts dir $fonts_dir = jpcrm_storage_fonts_dir_path(); $working_dir = zeroBSCRM_privatisedDirCheckWorks(); // Check if temp dir is valid if ( empty( $working_dir['path'] ) || !$fonts_dir ) { return false; } $working_dir = $working_dir['path'] . '/'; $font_directory_name = $this->font_name_to_dir( $font_name ); // Discern available variations $font_regular_path = $working_dir . $this->font_name_to_regular_ttf_name( $font_name ); // 'NotoSans-Regular.ttf' - ALL variations have a `*-Regular.ttf` as at 01/12/21 $font_bold_path = null; $font_italic_path = null; $font_bolditalic_path = null; if ( file_exists( $working_dir . $font_directory_name . '-Bold.ttf' ) ){ $font_bold_path = $working_dir . $font_directory_name . '-Bold.ttf'; } if ( file_exists( $working_dir . $font_directory_name . '-Italic.ttf' ) ){ $font_italic_path = $working_dir . $font_directory_name . '-Italic.ttf'; } if ( file_exists( $working_dir . $font_directory_name . '-BoldItalic.ttf' ) ){ $font_bolditalic_path = $working_dir . $font_directory_name . '-BoldItalic.ttf'; } // Attempt to install if ($this->load_font( str_replace( ' ' ,'', $font_name ), // e.g. NotoSansJP $font_regular_path, $font_bold_path, $font_italic_path, $font_bolditalic_path )){ global $zbs; // Update setting $font_install_setting = $zbs->settings->get('pdf_extra_fonts_installed'); if ( !is_array( $font_install_setting ) ){ $font_install_setting = array(); } $font_install_setting[ $this->font_name_to_slug( $font_name ) ] = time(); $zbs->settings->update( 'pdf_extra_fonts_installed', $font_install_setting ); return true; } } return false; } /* * Installs default fonts (which are extracted, but are not marked installed) * can use $this->extract_and_install_default_fonts() if from scratch (extracts + installs) */ public function install_default_fonts( $force_reinstall = false ){ global $zbsExtensionInstallError; // get fonts dir $fonts_dir = jpcrm_storage_fonts_dir_path(); $working_dir = zeroBSCRM_privatisedDirCheckWorks(); // Check if temp dir is valid if ( empty( $working_dir['path'] ) || !$fonts_dir ) { $zbsExtensionInstallError = __( 'Jetpack CRM was not able to create the directories it needs in order to install fonts for the PDF Engine.', 'zero-bs-crm' ); return false; } $working_dir = $working_dir['path'] . '/'; // also install the font(s) if not already installed (if present) $fontsInstalled = zeroBSCRM_getSetting('pdf_fonts_installed'); if ( ( $fontsInstalled !== 1 && file_exists( $fonts_dir . 'fonts-info.txt' ) ) || ( !$this->default_fonts_installed() ) || $force_reinstall ) { // attempt to install if ( $this->load_font( 'NotoSansGlobal', $working_dir . 'NotoSans-Regular.ttf', $working_dir . 'NotoSans-Bold.ttf', $working_dir . 'NotoSans-Italic.ttf', $working_dir . 'NotoSans-BoldItalic.ttf' ) ) { // update setting global $zbs; $zbs->settings->update( 'pdf_fonts_installed', 1 ); } else { $zbsExtensionInstallError = __( 'Jetpack CRM was not able to install fonts for the PDF engine.', 'zero-bs-crm' ); return false; } } return true; } /** * Installs a new font family * This function maps a font-family name to a font. It tries to locate the * bold, italic, and bold italic versions of the font as well. Once the * files are located, ttf versions of the font are copied to the fonts * directory. Changes to the font lookup table are saved to the cache. * * This is an an adapted version of install_font_family() from https://github.com/dompdf/utils * * @param Dompdf $dompdf dompdf main object * @param string $fontname the font-family name * @param string $normal the filename of the normal face font subtype * @param string $bold the filename of the bold face font subtype * @param string $italic the filename of the italic face font subtype * @param string $bold_italic the filename of the bold italic face font subtype * * @throws Exception */ public function install_font_family($dompdf, $fontname, $normal, $bold = null, $italic = null, $bold_italic = null, $debug = false) { try { $fontMetrics = $dompdf->getFontMetrics(); // Check if the base filename is readable if ( !is_readable($normal) ) { throw new Exception("Unable to read '$normal'."); } $dir = dirname($normal); $basename = basename($normal); $last_dot = strrpos($basename, '.'); if ($last_dot !== false) { $file = substr($basename, 0, $last_dot); $ext = strtolower(substr($basename, $last_dot)); } else { $file = $basename; $ext = ''; } // dompdf will eventually support .otf, but for now limit to .ttf if ( !in_array($ext, array(".ttf")) ) { throw new Exception("Unable to process fonts of type '$ext'."); } // Try $file_Bold.$ext etc. $path = "$dir/$file"; $patterns = array( "bold" => array("_Bold", "b", "B", "bd", "BD"), "italic" => array("_Italic", "i", "I"), "bold_italic" => array("_Bold_Italic", "bi", "BI", "ib", "IB"), ); foreach ($patterns as $type => $_patterns) { if ( !isset($$type) || !is_readable($$type) ) { foreach($_patterns as $_pattern) { if ( is_readable("$path$_pattern$ext") ) { $$type = "$path$_pattern$ext"; break; } } if ( is_null($$type) ) if ($debug) echo ("Unable to find $type face file.\n"); } } $fonts = compact("normal", "bold", "italic", "bold_italic"); $entry = array(); // Copy the files to the font directory. foreach ($fonts as $var => $src) { if ( is_null($src) ) { $entry[$var] = $dompdf->getOptions()->get('fontDir') . '/' . mb_substr(basename($normal), 0, -4); continue; } // Verify that the fonts exist and are readable if ( !is_readable($src) ) { throw new Exception("Requested font '$src' is not readable"); } $dest = $dompdf->getOptions()->get('fontDir') . '/' . basename($src); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable, Generic.WhiteSpace.ScopeIndent.IncorrectExact -- TODO: Fix these. if ( ! is_writable( dirname( $dest ) ) ) { throw new Exception("Unable to write to destination '$dest'."); } if ($debug) echo "Copying $src to $dest...\n"; if ( !copy($src, $dest) ) { throw new Exception("Unable to copy '$src' to '$dest'"); } $entry_name = mb_substr($dest, 0, -4); if ($debug) echo "Generating Adobe Font Metrics for $entry_name...\n"; $font_obj = Font::load($dest); $font_obj->saveAdobeFontMetrics("$entry_name.ufm"); $font_obj->close(); $entry[$var] = $entry_name; unlink( $src ); } // Store the fonts in the lookup table $fontMetrics->setFontFamily($fontname, $entry); // Save the changes $fontMetrics->saveFontFamilies(); // Fini return true; } catch (Exception $e){ // nada } return false; } /* * Retrieves a font zip from our CDN and installs it locally */ public function retrieve_and_install_specific_font( $font_name='', $force_reinstall = false){ global $zbsExtensionInstallError; // font exists? if ( !$this->font_is_available( $font_name) ){ return false; } // font already installed? if ( $this->font_is_installed( $font_name ) && !$force_reinstall ){ return true; } // get fonts dir $fonts_dir = jpcrm_storage_fonts_dir_path(); $working_dir = zeroBSCRM_privatisedDirCheckWorks(); // Check if temp dir is valid if ( empty( $working_dir['path'] ) || !$fonts_dir ) { $zbsExtensionInstallError = __( 'Jetpack CRM was not able to create the directories it needs in order to install fonts for the PDF Engine.', 'zero-bs-crm' ); return false; } $working_dir = $working_dir['path'] . '/'; $font_file_name = $this->font_name_to_regular_ttf_name( $font_name ); // Already downloaded, so proceed to install if ( file_exists( $working_dir . $font_file_name) ) { return $this->install_font( $font_name ); } // Retrieve & install the font $remote_zip_name = $this->font_name_to_zip( $font_name ); $temp_path = tempnam( sys_get_temp_dir(), 'crmfont' ); // Retrieve zip global $zbs; if ( !zeroBSCRM_retrieveFile( $zbs->urls['extdlfonts'] . $remote_zip_name, $temp_path ) ) { // Something failed $zbsExtensionInstallError = __('Jetpack CRM was not able to download the fonts it needs for the PDF Engine.',"zero-bs-crm").' '.__('(fonts)','zero-bs-crm'); unlink( $temp_path ); return false; } // Extract zip to fonts dir $expanded = zeroBSCRM_expandArchive( $temp_path, $working_dir ); unlink( $temp_path ); // appears to have worked if ( !$expanded || !file_exists( $working_dir . $font_file_name ) ) { // Add error msg $zbsExtensionInstallError = __('CRM was not able to retrieve the requested font.',"zero-bs-crm") . ' ' . __('(Failed to install font.)',"zero-bs-crm"); ##WLREMOVE $zbsExtensionInstallError = __('Jetpack CRM was not able to retrieve the requested font.',"zero-bs-crm") . ' ' . __('(Failed to install font.)',"zero-bs-crm"); ##/WLREMOVE return false; } // install the font return $this->install_font( $font_name, true ); } /* * Extract (and install) default fonts which dompdf uses to provide global lang supp * This function is used if somebody were to delete these default fonts from jpcrm-storage. * Instead, use retrieve_and_install() to retrieve locale specific fonts (from v4.7.0) */ public function extract_and_install_default_fonts(){ global $zbsExtensionInstallError; // get fonts dir $fonts_dir = jpcrm_storage_fonts_dir_path(); $working_dir = zeroBSCRM_privatisedDirCheckWorks(); // Check if temp dir is valid if ( empty( $working_dir['path'] ) || !$fonts_dir ) { $zbsExtensionInstallError = __( 'Jetpack CRM was not able to create the directories it needs in order to install fonts for the PDF Engine.', 'zero-bs-crm' ); return false; } $working_dir = $working_dir['path'] . '/'; // Check if fonts are already downloaded if ( file_exists( $fonts_dir . 'fonts-info.txt' ) ) { // Proceed to installation return $this->install_default_fonts(); } // Extract zip to fonts dir $expanded = zeroBSCRM_expandArchive( ZEROBSCRM_PATH . 'data/pdffonts.zip', $working_dir ); // Check success? if ( !$expanded || !file_exists( $working_dir . 'fonts-info.txt' ) ) { // Add error msg $zbsExtensionInstallError = __('Jetpack CRM was not able to extract the fonts it needs for the PDF Engine.',"zero-bs-crm").' '.__('(fonts)','zero-bs-crm'); // Return fail return false; } rename( $working_dir . 'fonts-info.txt', $fonts_dir . 'fonts-info.txt' ); // install 'em return $this->install_default_fonts( true ); } /* * Loads a font file collection (.ttf's) onto the server for dompdf * only needs to fire once */ public function load_font( $font_name='', $normalFile='', $boldFile=null, $italicFile=null, $boldItalicFile=null ){ if ( zeroBSCRM_isZBSAdminOrAdmin() && !empty($font_name) && file_exists($normalFile) && ( file_exists($boldFile) || $boldFile == null ) && ( file_exists($italicFile) || $italicFile == null ) && ( file_exists($boldItalicFile) || $boldItalicFile == null ) ) { // PDF Install check (importantly skip the font check with false first param) zeroBSCRM_extension_checkinstall_pdfinv(false); global $zbs; $dompdf = $zbs->pdf_engine(); // Install the font(s) return $this->install_font_family( $dompdf, $font_name, $normalFile, $boldFile, $italicFile, $boldItalicFile ); } return false; } /* * Retrieves the font cache from dompdf and returns all loaded fonts */ public function loaded_fonts(){ $dompdf_font_cache_file = jpcrm_storage_fonts_dir_path() . 'installed-fonts.json'; if ( file_exists( $dompdf_font_cache_file ) ) { $cacheData = json_decode( file_get_contents( $dompdf_font_cache_file ) ); return $cacheData; } return array(); } /* * Returns bool whether or not our key font (Noto Sans global) is installed according to dompdf */ public function default_fonts_installed(){ $existing_fonts = $this->loaded_fonts(); if ( isset( $existing_fonts->notosansglobal ) ){ return true; } return false; } }
projects/plugins/crm/includes/ZeroBSCRM.Core.Localisation.php
<?php /* ! * Jetpack CRM * https://jetpackcrm.com * V2.0.6 * * Copyright 2020 Automattic * * Date: 24/05/2017 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) { exit; } /* ====================================================== / Breaking Checks ====================================================== */ // Globals... // } Cache of locale... if set (avoids multiple getting for each label) global $zeroBSCRM_locale; /* this isn't used! // } Temp mapping for 2.0.6: global $zeroBSCRM_localisationTextOverrides; $zeroBSCRM_localisationTextOverrides = array( 'en-US' => array( array('County','State'), array('Postcode','Zip Code'), array('Mobile Telephone','Cell') ) ); */ /* This func was built to centralise "workarounds" where the default WP date config conflicted with that of the jquery datepicker used. ... WH did so 27/2/19 ... ultimately this method is clearly flawed somewhere in the linkage though, ... as these keep cropping up. */ function zeroBSCRM_locale_wpConversionWorkarounds( $format = 'd/m/Y' ) { // allow for this funky thing here. (only if getting default format) if ( $format == 'F j, Y' ) { $format = 'm/d/Y'; } if ( $format == 'jS F Y' ) { $format = 'd/m/Y'; } if ( $format == 'j F, Y' ) { $format = 'd/m/Y'; } // added 27/2/19 JIRA-BS-792 if ( $format == 'j. F Y' ) { $format = 'd/m/Y'; } if ( $format == 'j F Y' ) { $format = 'd/m/Y'; } // added 11/03/19 JIRA-ZBS-817 if ( $format == 'F j, Y' ) { $format = 'm/d/Y'; } // Temporary workaround for gh-273, to be addressed in full under gh-313 if ( $format === 'Y. F j.' ) { $format = 'Y/d/m'; } return $format; } // https://codex.wordpress.org/Function_Reference/date_i18n function zeroBSCRM_locale_utsToDate( $unixTimestamp = -1 ) { if ( $unixTimestamp === -1 ) { $unixTimestamp = time(); } // return date_i18n( get_option( 'date_format' ), $unixTimestamp ); return zeroBSCRM_date_i18n( get_option( 'date_format' ), $unixTimestamp ); } // https://codex.wordpress.org/Function_Reference/date_i18n + 'Y-m-d H:i:s' function zeroBSCRM_locale_utsToDatetime( $unixTimestamp = -1 ) { if ( $unixTimestamp === -1 ) { $unixTimestamp = time(); } // return date_i18n( 'Y-m-d H:i:s', $unixTimestamp ); return zeroBSCRM_date_i18n( 'Y-m-d H:i:s', $unixTimestamp ); } // same as above but in WP chosen formats function zeroBSCRM_locale_utsToDatetimeWP( $unixTimestamp = -1 ) { if ( $unixTimestamp === -1 ) { $unixTimestamp = time(); } // return date_i18n( 'Y-m-d H:i:s', $unixTimestamp ); return zeroBSCRM_date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $unixTimestamp ); } // adapted from https://stackoverflow.com/questions/2891937/strtotime-doesnt-work-with-dd-mm-yyyy-format function zeroBSCRM_locale_dateToUTS( $dateInFormat = '', $withTime = false, $specificFormat = false ) { try { $format = zeroBSCRM_date_defaultFormat(); if ( $withTime ) { $format .= ' H:i'; // hacky catch of AM/PM + add to format end...? if ( str_contains( $dateInFormat, 'AM' ) || str_contains( $dateInFormat, 'PM' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $format .= ' A'; } } // if specificFormat, use that if ( $specificFormat !== false ) { $format = $specificFormat; } // debug echo 'from: '.$dateInFormat.' in format '.$format.':'; // requires php 5.3+ $dt = DateTime::createFromFormat( '!' . $format, $dateInFormat ); // debug echo 'DT Errors:<pre>'.print_r(DateTime::getLastErrors(),1).'</pre>'; /* can use this to check for errors: print_r(DateTime::getLastErrors()); e.g. Array ( [warning_count] => 0 [warnings] => Array ( ) [error_count] => 4 [errors] => Array ( [2] => Unexpected data found. [5] => Unexpected data found. ) ) */ // if was failed conversion, is set to false // if ($dt !== false) if ( $dt instanceof DateTime ) { return $dt->getTimestamp(); } else { // this only happens when people have $date in one format, but their settings match a diff setting // try this $dt = strtotime( $dateInFormat ); // debug // echo 'from: '.$dateInFormat.' in format '.$format.'... = '.$dt; if ( $dt !== false && $dt > 0 ) { return $dt; } return false; } } catch ( Exception $e ) { // debug echo 'error:'.$e->getMessage(); try { // try this $dt = strtotime( $dateInFormat ); // echo 'dt:'.$dateInFormat.'=>'; print_r($dt); echo '!'; if ( $dt !== false && $dt > 0 ) { return $dt; } } catch ( Exception $e ) { // really not a great date... // echo 'error2:'.$e->getMessage(); } } return false; } /* WH switched this for the above zeroBSCRM_locale_dateToUTS, which is just the next answer down on your original stack overflow link ... this was good, but that was a little more cleaner/all-encompassing. // function to convert date to time for ZBS use (since multile dates used) this was a bit of a pig // since when updating DB it needs Y-m-d H:i:s format. and strtotime does not work with UK date formats // hence the 1 Jan 1970 bug reported in the date picker from Paul (groove-85858971) function zeroBSCRM_strtotime($date = ''){ $the_format = get_option( 'date_format' ); if($the_format == 'd/m/Y' || $the_format = 'jS F Y' || $the_format = 'F j, Y'){ $date = str_replace('/', '-', $date); } $unixtime = strtotime($date); return $unixtime; } */ // wh added 9/8/18 - adds time to zeroBSCRM_date_i18n, basically // ... just appends H:i to format // ... had to use for .zbs-date-time datepicker function zeroBSCRM_date_i18n_plusTime( $format, $timestamp, $isUTC = false ) { // pass -1 to default to WP date if ( $format == -1 ) { $format = zeroBSCRM_date_defaultFormat(); } // add time $format .= ' H:i'; return zeroBSCRM_date_i18n( $format, $timestamp, false, $isUTC ); } // this is a modified version of 2x answer here, takinginto account +- gmt_offset // https://wordpress.stackexchange.com/questions/94755/converting-timestamps-to-local-time-with-date-l18n // fully testing + works as at 11/05/18 // WH: As of 16/8/18 - has extra var $isUTC - // this is a workaround for those peeps in non UTC // who, when converting dates, were getting back 'offset' dates (this is because we're using timestamps of midnight here) function zeroBSCRM_date_i18n( $format, $timestamp, $notused = true, $isUTC = false ) { // catch empty timestamps if ( ! is_numeric( $timestamp ) ) { $timestamp = time(); } // pass -1 to default to WP date if ( $format == -1 ) { $format = zeroBSCRM_date_defaultFormat(); } // Timezone Support // Default: $timezone_str = 'UTC'; // got a non-utc timestamp str? if ( ! $isUTC ) { $timezone_str = get_option( 'timezone_string' ); if ( empty( $timezone_str ) ) { // if offset, use that $offsetStr = get_option( 'gmt_offset' ); if ( ! empty( $offsetStr ) ) { $offset = $offsetStr * HOUR_IN_SECONDS; return date_i18n( $format, $timestamp + $offset, true ); } } } // if still no return, default: if ( empty( $timezone_str ) ) { $timezone_str = 'UTC'; } // proceed with timezone str: $timezone = new \DateTimeZone( $timezone_str ); // The date in the local timezone. $date = new \DateTime( 'now', $timezone ); $date->setTimestamp( $timestamp ); $date_str = $date->format( 'Y-m-d H:i:s' ); // Pretend the local date is UTC to get the timestamp // to pass to date_i18n(). $utc_timezone = new \DateTimeZone( 'UTC' ); $utc_date = new \DateTime( $date_str, $utc_timezone ); $timestamp = $utc_date->getTimestamp(); return date_i18n( $format, $timestamp, true ); } // gets format + returns format (with some mods) function zeroBSCRM_date_defaultFormat() { $format = get_option( 'date_format' ); // catch specific issues $format = zeroBSCRM_locale_wpConversionWorkarounds( $format ); return $format; } // https://stackoverflow.com/questions/16702398/convert-a-php-date-format-to-a-jqueryui-datepicker-date-format // further down // We need this to take WP locale -> datetimepicker // Note: WH added strtoupper, seems to be req. for datetimerangepicker /* * Matches each symbol of PHP date format standard * with jQuery equivalent codeword * @author Tristan Jahier */ function zeroBSCRM_date_PHPtoDatePicker( $format ) { // dd M yy static $assoc = array( 'Y' => 'yyyy', 'y' => 'yy', 'F' => 'MM', 'm' => 'mm', 'l' => 'DD', 'd' => 'dd', 'D' => 'D', 'j' => 'd', 'M' => 'M', 'n' => 'm', 'z' => 'o', 'N' => '', 'S' => 'd', 'w' => '', 'W' => '', 't' => '', 'L' => '', 'o' => '', 'a' => '', 'A' => '', 'B' => '', 'g' => '', 'G' => '', 'h' => '', 'H' => '', 'i' => '', 's' => '', 'u' => '', ); $keys = array_keys( $assoc ); $indeces = array_map( function ( $index ) { return '{{' . $index . '}}'; }, array_keys( $keys ) ); $format = str_replace( $keys, $indeces, $format ); // Note: WH added strtoupper, seems to be req. for datetimerangepicker return strtoupper( str_replace( $indeces, $assoc, $format ) ); } function zeroBSCRM_date_localeForDaterangePicker() { $dateTimePickerFormat = 'DD.MM.YYYY'; $wpDateFormat = get_option( 'date_format' ); if ( ! empty( $wpDateFormat ) ) { // catch specific issues $wpDateFormat = zeroBSCRM_locale_wpConversionWorkarounds( $wpDateFormat ); $dateTimePickerFormat = zeroBSCRM_date_PHPtoDatePicker( $wpDateFormat ); } return array( 'format' => $dateTimePickerFormat, 'applyLabel' => __( 'Apply', 'zero-bs-crm' ), 'cancelLabel' => __( 'Clear', 'zero-bs-crm' ), 'fromLabel' => __( 'From', 'zero-bs-crm' ), 'toLabel' => __( 'To', 'zero-bs-crm' ), 'customRangeLabel' => __( 'Custom', 'zero-bs-crm' ), 'separator' => ' - ', 'daysOfWeek' => array( __( 'Su', 'zero-bs-crm' ), __( 'Mo', 'zero-bs-crm' ), __( 'Tu', 'zero-bs-crm' ), __( 'We', 'zero-bs-crm' ), __( 'Th', 'zero-bs-crm' ), __( 'Fr', 'zero-bs-crm' ), __( 'Sa', 'zero-bs-crm' ), ), 'monthNames' => array( __( 'January', 'zero-bs-crm' ), __( 'February', 'zero-bs-crm' ), __( 'March', 'zero-bs-crm' ), __( 'April', 'zero-bs-crm' ), __( 'May', 'zero-bs-crm' ), __( 'June', 'zero-bs-crm' ), __( 'July', 'zero-bs-crm' ), __( 'August', 'zero-bs-crm' ), __( 'September', 'zero-bs-crm' ), __( 'October', 'zero-bs-crm' ), __( 'November', 'zero-bs-crm' ), __( 'December', 'zero-bs-crm' ), ), 'firstDay' => (int) get_option( 'start_of_week', 0 ), ); /* full possible settings "format": "MM/DD/YYYY", "separator": " - ", "applyLabel": "Apply", "cancelLabel": "Cancel", "fromLabel": "From", "toLabel": "To", "customRangeLabel": "Custom", "daysOfWeek": [ "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" ], "monthNames": [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], "firstDay": 1 */ } /* Removed 2.14 - opting for _e :) // } This simply dumps any 'overrides' into the __w function before returning (E.g. County -> State) function zeroBSCRM_localiseFieldLabel($labelStr=''){ global $zeroBSCRM_localisationTextOverrides; $locale = zeroBSCRM_getLocale(); #} Init just checks if set to en_US if (isset($locale) && !empty($locale) && isset($zeroBSCRM_localisationTextOverrides[$locale])){ #} locale present - replace any? $replacement = $labelStr; foreach ($zeroBSCRM_localisationTextOverrides[$locale] as $repArr){ if (isset($repArr[0]) && $repArr[0] == $labelStr) $replacement = $repArr[1]; } #} Return replacement or orig.. return $replacement; } return $labelStr; } */ // for JS there's a ver of this in admin.global called zeroBSCRMJS_formatCurrency function zeroBSCRM_formatCurrency( $amount ) { // see here: https://akrabat.com/using-phps-numberformatter-to-format-currencies/ // needs the international PHP extension (hence wrapped in if exists) /* You can check if you have the intl extension installed using php -m | grep intl and if you don't then you can install it with apt-get install php5-intl or yum install php-intl assuming you use your distro's stock PHP. (If you compile your own, then --enable-intl is the switch you need.) */ global $zbs; /* 'currency' => symbol 'currency_position' => 0, 'currency_format_thousand_separator' => ',', 'currency_format_decimal_separator' => '.', 'currency_format_number_of_decimals' => 2, */ // WH would be nice if we could get a GROUP of settings (i.e. just the ones above.. ) $settings = $zbs->settings->getAll(); // defaults declared elsewhere so do I need the below :declare: :bear: $zbscrm_currency_symbol = '$'; $zbscrm_currency_format_thousand_separator = ','; $zbscrm_currency_format_decimal_separator = '.'; $zbscrm_currency_format_number_of_decimals = 2; $zbscrm_currency_symbol = zeroBSCRM_getCurrencyChr(); $zbscrm_currency_position = $settings['currency_position']; $zbscrm_currency_format_thousand_separator = $settings['currency_format_thousand_separator']; $zbscrm_currency_format_decimal_separator = $settings['currency_format_decimal_separator']; $zbscrm_currency_format_number_of_decimals = $settings['currency_format_number_of_decimals']; // process the number $formatted_number = number_format( (float) $amount, $zbscrm_currency_format_number_of_decimals, $zbscrm_currency_format_decimal_separator, $zbscrm_currency_format_thousand_separator ); // add the currecy symbol switch ( $zbscrm_currency_position ) { case 0: // left $formatted_amount = $zbscrm_currency_symbol . $formatted_number; break; case 1: // right $formatted_amount = $formatted_number . $zbscrm_currency_symbol; break; case 2: // left with space $formatted_amount = $zbscrm_currency_symbol . ' ' . $formatted_number; break; case 3: // right with space $formatted_amount = $formatted_number . ' ' . $zbscrm_currency_symbol; break; default: // default to the left $formatted_amount = $zbscrm_currency_symbol . $formatted_number; break; } return $formatted_amount; /* AS OF v2.84+ we shunt everything through the settings rather than the below which seems unreliable $locale = zeroBSCRM_getLocale(true); if(class_exists('NumberFormatter')){ $formatter = new NumberFormatter($locale, NumberFormatter::CURRENCY); return $formatter->formatCurrency($amount, zeroBSCRM_getCurrencyStr()); } else{ // use wp default /// which needs this currency :) return zeroBSCRM_getCurrencyChr().number_format_i18n($amount); } */ } function zeroBSCRM_format_quantity( $quantity ) { return sprintf( '%g', $quantity ); } function zeroBSCRM_getLocale( $full = true ) { global $zeroBSCRM_locale; if ( isset( $zeroBSCRM_locale ) ) { return $zeroBSCRM_locale; } $zeroBSCRM_locale = get_bloginfo( 'language' ); if ( ! $full ) { $zeroBSCRM_locale = str_replace( '_', '-', $zeroBSCRM_locale ); // just in case en_GB? $langParts = explode( '-', $zeroBSCRM_locale ); $zeroBSCRM_locale = $langParts[0]; } return $zeroBSCRM_locale; } // getLocale wrapper function zeroBSCRM_locale_getServerLocale() { // https://stackoverflow.com/questions/29932843/php-get-current-locale // limited use, e.g. flywheel returns 'C' return setlocale( LC_ALL, 0 ); } /* =========================================== Helper functions (moved from dal 2.2) =========================================== */ // } Minified get currency func function zeroBSCRM_getCurrencyChr() { // } Curr $theCurrency = zeroBSCRM_getSetting( 'currency' ); $theCurrencyChar = '&pound;'; if ( isset( $theCurrency ) && isset( $theCurrency['chr'] ) ) { $theCurrencyChar = $theCurrency['chr']; } return $theCurrencyChar; } function zeroBSCRM_getCurrencyStr() { // } Curr $theCurrency = zeroBSCRM_getSetting( 'currency' ); $theCurrencyStr = 'GBP'; if ( isset( $theCurrency ) && isset( $theCurrency['chr'] ) ) { $theCurrencyStr = $theCurrency['strval']; } return $theCurrencyStr; } function zeroBSCRM_getTimezoneOffset() { return get_option( 'gmt_offset' ); } function zeroBSCRM_getCurrentTime() { return current_time(); } // } Date time formats // http://wordpress.stackexchange.com/questions/591/how-to-get-the-date-format-and-time-format-settings-for-use-in-my-template function zeroBSCRM_getDateFormat() { // } cache global $zeroBSCRM_dateFormat; if ( isset( $zeroBSCRM_dateFormat ) ) { return $zeroBSCRM_dateFormat; } $zeroBSCRM_dateFormat = get_option( 'date_format' ); return $zeroBSCRM_dateFormat; } function zeroBSCRM_getTimeFormat() { // } cache global $zeroBSCRM_timeFormat; if ( isset( $zeroBSCRM_timeFormat ) ) { return $zeroBSCRM_timeFormat; } $zeroBSCRM_timeFormat = get_option( 'time_format' ); return $zeroBSCRM_timeFormat; } // output locale stuff into header :) // actually left in main .php for now
projects/plugins/crm/includes/ZeroBSCRM.MetaBoxes3.TagManager.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V3.0 * * Copyright 2020 Automattic * * Date: 20/02/2019 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== Init Func ====================================================== */ function zeroBSCRM_TagManagerMetaboxSetup(){ // lazy page switch $typeInt = -1; if (zeroBSCRM_is_customertags_page()) $typeInt = ZBS_TYPE_CONTACT; if (zeroBSCRM_is_companytags_page()) $typeInt = ZBS_TYPE_COMPANY; if (zeroBSCRM_is_quotetags_page()) $typeInt = ZBS_TYPE_QUOTE; if (zeroBSCRM_is_invoicetags_page()) $typeInt = ZBS_TYPE_INVOICE; if (zeroBSCRM_is_transactiontags_page()) $typeInt = ZBS_TYPE_TRANSACTION; if (zeroBSCRM_is_formtags_page()) $typeInt = ZBS_TYPE_FORM; if (zeroBSCRM_is_tasktags_page()) $typeInt = ZBS_TYPE_TASK; if ($typeInt > 0){ // Tag List $zeroBS__Metabox_TagList = new zeroBS__Metabox_TagList( __FILE__, $typeInt ); // Add Tags $zeroBS__Metabox_TagAdd = new zeroBS__Metabox_TagAdd( __FILE__, $typeInt ); } } add_action( 'admin_init','zeroBSCRM_TagManagerMetaboxSetup'); /* ====================================================== / Init Func ====================================================== */ /* ====================================================== Declare Globals ====================================================== */ #} Used throughout // Don't know who added this, but GLOBALS are out of scope here //global $zbsCustomerFields,$zbsCustomerQuoteFields,$zbsCustomerInvoiceFields; /* ====================================================== / Declare Globals ====================================================== */ // PerfTest: zeroBSCRM_performanceTest_startTimer('custmetabox'); /* ====================================================== Tag List Metabox ====================================================== */ class zeroBS__Metabox_TagList extends zeroBS__Metabox{ /** * The legacy object name (e.g. 'zerobs_customer') * * @var string */ private $postType; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.PropertyNotSnakeCase public function __construct( $plugin_file, $typeInt = ZBS_TYPE_CONTACT ) { global $zbs; // set these $this->typeInt = $typeInt; $this->postType = $zbs->DAL->typeCPT($typeInt); $this->metaboxID = 'zerobs-'.$zbs->DAL->objTypeKey($typeInt).'-tags-edit'; $this->metaboxTitle = __($zbs->DAL->typeStr($typeInt).' Tags',"zero-bs-crm"); $this->metaboxScreen = 'zerobs_edit_tags'; // we can use anything here as is now using our func $this->metaboxArea = 'normal'; $this->metaboxLocation = 'high'; $this->saveOrder = 1; // headless! $this->headless = true; // call this $this->initMetabox(); } public function html( $contact, $metabox ) { global $zbs; // Get all tags $tags = $zbs->DAL->getTagsForObjType(array( 'objtypeid'=>$this->typeInt, 'excludeEmpty'=>false, 'withCount'=>true, 'ignoreowner' => true, // sort 'sortByField' => 'tagcount', 'sortOrder' => 'DESC' )); // pre-inject some potential js errors :) ?><div id="zbs-error-prep"><?php echo zeroBSCRM_UI2_messageHTML('info hidden',__('Tag Exists',"zero-bs-crm"),__('Cannot add a tag. A tag already exists with this text',"zero-bs-crm"),'','zbsTagAlreadyExists'); echo zeroBSCRM_UI2_messageHTML('info hidden',__('Tag Text Empty',"zero-bs-crm"),__('You cannot add empty tags',"zero-bs-crm"),'','zbsTagEmpty'); ?></div><?php // long term perhaps we need a list metabox type, for now, hardcoded: ?><table class="ui celled table" id="zbs-tag-manager" style="margin-top:0;"> <thead> <tr> <th><?php esc_html_e('Name',"zero-bs-crm"); ?></th> <th><?php esc_html_e('Slug',"zero-bs-crm"); ?></th> <?php /* this shows 1 date as DAL2 migration...<th><?php _e('First Used',"zero-bs-crm"); ?></th> */ ?> <th class="center aligned"><?php esc_html_e('Count',"zero-bs-crm"); ?></th> <th class="center aligned"><?php esc_html_e('Action','zero-bs-crm'); ?></th> </tr> </thead> <tbody> <?php if (count($tags) > 0){ foreach ($tags as $tag){ $link = jpcrm_esc_link('listtagged',-1,$this->postType,-1,$tag['id']); ?> <tr> <td><?php if ( isset( $tag['name'] ) ) echo '<a href="' . esc_url( $link ) . '" class="ui large label">' . esc_html( $tag['name'] ) . '</a>'; // phpcs:ignore Generic.ControlStructures.InlineControlStructure.NotAllowed ?></td> <td><?php if (isset($tag['slug'])) echo esc_html( $tag['slug'] ); ?></td> <?php /* this shows 1 date as DAL2 migration... <td><?php if (isset($tag['created']) && !empty($tag['created']) && $tag['created'] !== -1) echo zeroBSCRM_locale_utsToDate($tag['created']); ?></td> */ ?> <td class="center aligned"><?php if (isset($tag['count'])) echo '<a href="' . esc_url( $link ) . '">' . esc_html( zeroBSCRM_prettifyLongInts($tag['count']) ) . '</a>'; ?></td> <td class="center aligned"><button type="button" class="ui mini button black zbs-delete-tag" data-tagid="<?php echo esc_attr( $tag['id'] ); ?>"><i class="trash alternate icon"></i> <?php esc_html_e( 'Delete', 'zero-bs-crm' ); ?></button></td> </tr> <?php } } ?> </tbody> </table><?php if (count($tags) == 0) echo zeroBSCRM_UI2_messageHTML('info',__('No Tags Found',"zero-bs-crm"),__('There are no Tags here, create one using the box to the right.',"zero-bs-crm"),'disabled warning sign','zbsNoTagResults'); ?><script type="text/javascript"> <?php #} Nonce for AJAX echo "var zbscrmjs_secToken = '" . esc_js( wp_create_nonce( 'zbscrmjs-ajax-nonce' ) ) . "';"; ?> var zbsTagListLang = { 'delete': '<?php zeroBSCRM_slashOut(__('Delete',"zero-bs-crm")); ?>', 'deleteswaltitle': '<?php zeroBSCRM_slashOut(__('Are you sure?','zero-bs-crm')); ?>', 'deleteswaltext': '<?php zeroBSCRM_slashOut(__('This will delete the tag and remove it from any tagged '.__($zbs->DAL->typeStr($this->typeInt),'zero-bs-crm').'. This is irreversable.','zero-bs-crm')); ?>', 'deleteswalconfirm': '<?php zeroBSCRM_slashOut(__('Yes, delete the tag!','zero-bs-crm')); ?>', 'tagdeleted':'<?php zeroBSCRM_slashOut(__('Tag Deleted!','zero-bs-crm')); ?>', 'tagremoved':'<?php zeroBSCRM_slashOut(__('Your tag has been removed.','zero-bs-crm')); ?>', 'tagnotdeleted':'<?php zeroBSCRM_slashOut(__('Tag Not Deleted!','zero-bs-crm')); ?>', 'tagnotremoved':'<?php zeroBSCRM_slashOut(__('Your tag was not removed, please try again.','zero-bs-crm')); ?>', }; </script><?php } } /* ====================================================== / Tag List Metabox ====================================================== */ /* ====================================================== Create Tags Box ====================================================== */ class zeroBS__Metabox_TagAdd extends zeroBS__Metabox_Tags{ /** * The legacy object name (e.g. 'zerobs_customer') * * @var string */ private $postType; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.PropertyNotSnakeCase public function __construct( $plugin_file, $typeInt = ZBS_TYPE_CONTACT) { global $zbs; $this->typeInt = $typeInt; // until db2 ZBS_TYPE_CONTACT; $this->postType = $zbs->DAL->typeCPT($typeInt); $this->metaboxID = 'zerobs-'.$zbs->DAL->objTypeKey($typeInt).'-tags'; $this->metaboxTitle = __('Add '.$zbs->DAL->typeStr($typeInt).' Tags',"zero-bs-crm"); $this->metaboxScreen = 'zerobs_edit_tags'; // we can use anything here as is now using our func $this->metaboxArea = 'side'; $this->metaboxLocation = 'high'; // call this $this->initMetabox(); } // html + save dealt with by parent class :) } /* ====================================================== / Create Tags Box ====================================================== */
projects/plugins/crm/includes/wh.config.lib.php
<?php /*! * Jetpack CRM * http://www.zerobscrm.com * V1.0 * * Copyright 2020 Automattic * * Date: 26/05/16 */ class WHWPConfigLib { #} Main settings storage private $settings; private $settingsKey = false; private $settingsVer = false; private $settingsDefault = false; private $settingsPlugin = false; private $settingsPluginVer = false; private $settingsPluginDBVer = false; #} DMZ Settings private $settingsDMZRegister; private $settingsDMZKey = false; private $settingsDMZ; #} :) private $whlibVer = '2.0'; #} added "protected" list of setting keys that don't get reset when resetting to default private $settingsProtected = false; #} Constructor function __construct($config=array()) { #} localise any passed config if (is_array($config)){ if (isset($config['conf_key'])) $this->settingsKey = $config['conf_key']; if (isset($config['conf_ver'])) $this->settingsVer = $config['conf_ver']; if (isset($config['conf_defaults'])) $this->settingsDefault = $config['conf_defaults']; if (isset($config['conf_plugin'])) $this->settingsPlugin = $config['conf_plugin']; if (isset($config['conf_pluginver'])) $this->settingsPluginVer = $config['conf_pluginver']; if (isset($config['conf_plugindbver'])) $this->settingsPluginDBVer = $config['conf_plugindbver']; if (isset($config['conf_dmzkey'])) $this->settingsDMZKey = $config['conf_dmzkey']; if (isset($config['conf_protected'])) $this->settingsProtected = $config['conf_protected']; } else exit('WHConfigLib initiated incorrectly.'); #} define dmz settings key #} Set by passed config now $this->settingsDMZKey = $this->settingsKey . '_dmzregister'; #} Load direct $this->loadFromDB(); $this->loadDMZFromDB(); #} Fill any missing vars $this->validateAndUpdate(); #} If empty it's first run so init from defaults if (empty($this->settings)) $this->initCreate(); } #} Checks through defaults + existing and adds defaults where unset function validateAndUpdate(){ foreach ($this->settingsDefault as $key => $val){ if (!isset($this->settings[$key])) { $this->update($key,$val); } } } #} Initial Create function initCreate(){ #} If properly initialised! if ($settingsKey !== false && $settingsVer !== false && $settingsDefault !== false && $settingsPlugin !== false && $settingsPluginVer !== false){ #} Create + save initial from default #} Following have to be set out of props $defaultOptions = $this->settingsDefault; $defaultOptions['settingsID'] = $this->settingsVer; $defaultOptions['plugin'] = $this->settingsPlugin; $defaultOptions['version'] = $this->settingsPluginVer; $defaultOptions['db_version'] = $this->settingsPluginDBVer; #} Pass back to settings, and save $this->settings = $defaultOptions; $this->saveToDB(); #} else brutal exit! } else exit('WHConfigLib initiated incorrectly.'); } #} Reset to defaults function resetToDefaults(){ #} reset to default opts #} NOW with added protection :) any protected field keys wont get re-written #} Copy any protected keys over the new reset settings (if is set) $existingSettings = $this->settings; $newSettings = $this->settingsDefault; if (isset($this->settingsProtected) && is_array($this->settingsProtected)) foreach ($this->settingsProtected as $protectedKey){ #} If isset if (isset($existingSettings[$protectedKey])){ #} Pass it along $newSettings[$protectedKey] = $existingSettings[$protectedKey]; } } #} Save em down $this->settings = $newSettings; $this->saveToDB(); } #} Get all options as object function getAll($hardRefresh=false){ if ($hardRefresh) $this->loadFromDB(); return $this->settings; } #} Get single option function get($key,$freshFromDB=false){ if (empty($key) === true) return false; global $zbs; // db-loading way (ONLY WORKS DB2!) return $zbs->DAL->getSetting(array('key' => $key,'fullDetails' => false)); } #} Add/Update *brutally function update($key,$val=''){ if (empty($key) === true) return false; global $zbs; #} Don't even check existence as I guess it doesn't matter? $this->settings[$key] = $val; $zbs->DAL->updateSetting($key, $val); } #} Delete option function delete($key){ if (empty($key) === true) return false; // remove from settings unset( $this->settings[$key] ); // delete from db global $zbs; return $zbs->DAL->deleteSetting( array('key' => $key) ); } #} ================================== #} DMZ Config additions #} 2 layers: #} DMZConfig = whole object #} DMZConfigValue = object.value #} ================================== #} Get all DMZ (temp func for migration routine DB2, not to be generally used) function dmzGetMigrationSet(){ return array($this->settingsDMZKey,$this->settingsDMZRegister,$this->settingsDMZ); } #} Get single option function dmzGet($dmzKey,$confKey){ if (empty($dmzKey) === true || empty($confKey) === true) return false; #} Assumes it's loaded!? if (isset($this->settingsDMZ[$dmzKey])){ if (isset($this->settingsDMZ[$dmzKey][$confKey])) { return $this->settingsDMZ[$dmzKey][$confKey]; } } return false; } #} Delete option function dmzDelete($dmzKey,$confKey){ if (empty($dmzKey) === true || empty($confKey) === true) return false; $existingSettings = $this->dmzGetConfig($dmzKey); $newSettings = array(); if (isset($existingSettings) && is_array($existingSettings)) { foreach($existingSettings as $k => $v) { if ($k != $confKey) $newSettings[$k] = $v; } } #} Brutal $this->settingsDMZ[$dmzKey] = $newSettings; #} Save down $this->saveToDB(); } #} Add/Update *brutally function dmzUpdate($dmzKey,$confKey,$val=''){ if (empty($dmzKey) === true || empty($confKey) === true) return false; #} if not set, create if (!isset($this->settingsDMZ[$dmzKey])){ #} add to register $this->settingsDMZRegister[$dmzKey] = $dmzKey; #} Create as arr $this->settingsDMZ[$dmzKey] = array(); } #} Don't even check existence as I guess it doesn't matter? $this->settingsDMZ[$dmzKey][$confKey] = $val; #} Save down $this->saveToDB(); } #} Get alls option function dmzGetConfig($dmzKey){ if (empty($dmzKey) === true) return false; #} Assumes it's loaded!? if (isset($this->settingsDMZ[$dmzKey])){ return $this->settingsDMZ[$dmzKey]; } return false; } #} Delete Config function dmzDeleteConfig($dmzKey){ if (empty($dmzKey) === true) return false; #} Brutal unset($this->settingsDMZ[$dmzKey]); unset($this->settingsDMZRegister[$dmzKey]); #} Save down $this->saveToDB(); } #} Add/Update Config *brutally function dmzUpdateConfig($dmzKey,$config){ if (empty($dmzKey) === true || empty($config) === true) return false; #} if not set, create if (!isset($this->settingsDMZ[$dmzKey])){ #} add to register $this->settingsDMZRegister[$dmzKey] = $dmzKey; } // DEBUG echo 'type "'.$this->settingsDMZRegister.'" = "'.$dmzKey.'" ("'.gettype($this->settingsDMZRegister).'")<br>'; #} Just brutally override $this->settingsDMZ[$dmzKey] = $config; #} Save down $this->saveToDB(); } #} Load/Reload DMZ options from db function loadDMZFromDB(){ global $zbs; #} Load the register $this->settingsDMZRegister = $zbs->DAL->setting($this->settingsDMZKey,array()); // DEBUG echo 'loaded reg = "'; print_r($this->settingsDMZRegister); echo '"!'; #} This catches weirdo mis-saves?! if (!is_array($this->settingsDMZRegister)) $this->settingsDMZRegister = array(); #} Load anything logged in register if (is_array($this->settingsDMZRegister) && count($this->settingsDMZRegister) > 0) { foreach ($this->settingsDMZRegister as $regEntry){ #} Load it $this->settingsDMZ[$regEntry] = $zbs->DAL->setting($this->settingsDMZKey.'_'.$regEntry); } } return $this->settingsDMZ; } #} / DMZ Fields #} Save back to db function saveToDB(){ global $zbs; // DAL2 saves individually :) $u = array(); if (count($this->settings) > 0) foreach ($this->settings as $settingKey => $settingVal){ $u[] = $zbs->DAL->updateSetting($settingKey, $settingVal); } #} Also any DMZ's! (Brutal big saves - whole objs) #} save register $zbs->DAL->updateSetting($this->settingsDMZKey,$this->settingsDMZRegister); // DEBUG echo 'saved dmzregister:'; print_r($this->settingsDMZRegister); echo '!'; if (isset($this->settingsDMZRegister) && is_array($this->settingsDMZRegister)) foreach ($this->settingsDMZRegister as $dmzKey){ # => $dmzVal $u[] = $zbs->DAL->updateSetting($this->settingsDMZKey.'_'.$dmzKey, $this->settingsDMZ[$dmzKey]); } return $u; } #} Load/Reload from db function loadFromDB(){ global $zbs; $this->settings = $zbs->DAL->getSettings(array('autoloadOnly' => true,'fullDetails' => false)); return $this->settings; } #} Uninstall func - effectively creates a bk then removes its main setting function uninstall(){ #} Set uninstall flag $this->settings['uninstall'] = time(); #} Backup $this->createBackup('Pre-UnInstall Backup'); #} Blank it out $this->settings = NULL; // DAL2 // leave for now return true; } #} Backup existing settings obj (ripped from sgv2.0) function createBackup($backupLabel=''){ // Left this the same for DAL2 - is still storing backups in wp db $existingBK = get_option($this->settingsKey.'_bk'); if (!is_array($existingBK)) $existingBK = array(); $existingBK[time()] = array( 'main' => $this->settings, 'dmzreg' => $this->settingsDMZRegister, 'dmz' => $this->settingsDMZ ); if (!empty($backupLabel)) $existingBK[time()]['backupLabel'] = sanitize_text_field($backupLabel); #} For named settings bk update_option($this->settingsKey.'_bk',$existingBK, false); return $existingBK[time()]; } #} Kills all bks function killBackups(){ return delete_option($this->settingsKey.'_bk'); } #} Retrieve BKs function getBKs(){ $x = get_option($this->settingsKey.'_bk'); if (is_array($x)) return $x; else return array(); } #} Reload from BK (bkkey will be a timestamp, use getBKs to list these keys) function reloadFromBK($bkkey){ $backups = get_option($this->settingsKey.'_bk'); if (isset($backups[$bkkey])) if (is_array($backups[$bkkey])) { #} kill existing settings and use backed up ones $this->settings = $backups[$bkkey]; #} Save $this->saveToDB(); return true; } return false; } } #} This is a wrapper/factory class which simplifies using DMZ fields for extension plugins class WHWPConfigExtensionsLib { #} key holder private $extperma = false; private $settingsObj = false; private $existingSettings = false; #} Constructor function __construct($extperma='',$defaultConfig=array()) { if (!empty($extperma)){ #} store $this->extperma = 'ext_'.$extperma; #} initiate settings obj as a dmz set // WH move to $zbs->settings // ALSO now covered by // LEGACY SUPPORT (see ZeroBSCRM.php) global $zbs; if (isset($zbs->settings) && !empty($zbs->settings)){ $existingSettings = $zbs->settings->dmzGetConfig($this->extperma); } else { // legacy - older plugins not using new init hooks // pass back empty for now (will break them) // and notify $existingSettings = array(); // notify // can't do directly, as this is PRE INIT (no logged in user) // so delay... zeroBSCRM_notifyme_insert_notification(get_current_user_id(),-999,-1,'extension.update'); // weird this doesn't work either... day of it.add_action('before_zerobscrm_init', 'zeroBS_temp_ext_legacy_notice'); // gonna do this grossly: if (!defined('ZBSTEMPLEGACYNOTICE')) define('ZBSTEMPLEGACYNOTICE',1); // this is a hotfix 2.50.1 to work with // LEGACY SUPPORT // ... it'll add the setting to a pile to be reconstructed post init :) global $zbsLegacySupport; $zbsLegacySupport['extsettingspostinit'][$this->extperma] = $defaultConfig; } #} Create if not existing if (!is_array($existingSettings)){ #} init $zbs->settings->dmzUpdateConfig($this->extperma,$defaultConfig); } } else exit('WHConfigLib initiated incorrectly.'); } #} passthrough funcs function get($key){ //global $zbs; //return $zeroBSCRM_Settings->dmzGet($this->extperma,$key); // WH move to $zbs->settings global $zbs; return $zbs->settings->dmzGet($this->extperma,$key); } function delete($key){ //global $zbs; //return $zeroBSCRM_Settings->dmzDelete($this->extperma,$key); // WH move to $zbs->settings global $zbs; return $zbs->settings->dmzDelete($this->extperma,$key); } function update($key,$val=''){ //global $zbs; //return $zeroBSCRM_Settings->dmzUpdate($this->extperma,$key,$val); // WH move to $zbs->settings global $zbs; return $zbs->settings->dmzUpdate($this->extperma,$key,$val); } function getAll(){ //global $zbs; //return $zeroBSCRM_Settings->dmzGetConfig($this->extperma); // WH move to $zbs->settings global $zbs; return $zbs->settings->dmzGetConfig($this->extperma); } } function zeroBS_temp_ext_legacy_notice(){ // add one menu item, even if multiple ext. if (!defined('ZBSLEGACYSET')){ $o = get_option('zbs_temp_legacy_update_msg'); if ($o == false){ zeroBSCRM_notifyme_insert_notification(get_current_user_id(),-999,-1,'extension.update'); update_option('zbs_temp_legacy_update_msg',1, false); } define('ZBSLEGACYSET',1); } }
projects/plugins/crm/includes/ZeroBSCRM.CSVImporter.php
<?php /* ! * Jetpack CRM * https://jetpackcrm.com * V1.0 * * Copyright 2020 Automattic * * Date: 07/03/2017 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) { exit; } /* ====================================================== / Breaking Checks ====================================================== */ /* // } #coreintegration - MOVED to core.extensions // } Log with main core (Has to be here, outside of all funcs) // } Note, this function permacode (e.g. woo) needs to have a matching function for settings page named "zeroBSCRM_extensionhtml_settings_woo" (e.g.) global $zeroBSCRM_extensionsInstalledList; if (!is_array($zeroBSCRM_extensionsInstalledList)) $zeroBSCRM_extensionsInstalledList = array(); $zeroBSCRM_extensionsInstalledList[] = 'csvimporterlite'; #woo #pay #env // } Super simpz function to return this extensions name to core (for use on settings tabs etc.) function zeroBSCRM_extension_name_csvimporterlite(){ return 'CSV Importer LITE'; } */ // } IMPORTANT FOR SETTINGS EXTENSIONS MODEL! // } Unique str for each plugin extension, e.g. "mail" or "wooimporter" (lower case no numbers or spaces/special chars) $zeroBSCRM_CSVImporterconfigkey = 'csvimporterlite'; $zeroBSCRM_extensions[] = $zeroBSCRM_CSVImporterconfigkey; global $zeroBSCRM_CSVImporterLiteslugs; $zeroBSCRM_CSVImporterLiteslugs = array(); $zeroBSCRM_CSVImporterLiteslugs['app'] = 'zerobscrm-csvimporterlite-app'; // NOTE: this should now be ignored, use $zbs->slugs['csvlite'] as is WL friendly global $zeroBSCRM_CSVImporterLiteversion; $zeroBSCRM_CSVImporterLiteversion = '2.0'; /* No settings included in CSV Importer LITE - pro only :) // } If legit... #CORELOADORDER if (!defined('ZBSCRMCORELOADFAILURE')){ #} Should be safe as called from core #} Settings Model. req. > v1.1 #} Init settings model using your defaults set in the file above #} Note "zeroBSCRM_extension_extensionName_defaults" var below must match your var name in the config. global $zeroBSCRM_CSVImporterSettings, $zeroBSCRM_extension_extensionName_defaults; $zeroBSCRM_CSVImporterSettings = new WHWPConfigExtensionsLib($zeroBSCRM_CSVImporterconfigkey,$zeroBSCRM_extension_extensionName_defaults); } */ // CA: Block commented because the issue #1116 about a Woocommerce - JPCRM import conflict /* function zeroBSCRM_CSVImporterLite_extended_upload ( $mime_types =array() ) { //$mime_types['csv'] = "text/csv"; //wonder it actually this.. $mime_types['csv'] = "text/plain"; return $mime_types; } */ // add_filter('upload_mimes', 'zeroBSCRM_CSVImporterLite_extended_upload'); // } Add le admin menu function zeroBSCRM_CSVImporterLiteadmin_menu() { global $zbs,$zeroBSCRM_CSVImporterLiteslugs; // req wp_register_style( 'zerobscrm-csvimporter-admcss', ZEROBSCRM_URL . 'css/ZeroBSCRM.admin.csvimporter' . wp_scripts_get_suffix() . '.css', array(), $zbs->version ); $csv_admin_page = add_submenu_page( 'jpcrm-hidden', 'CSV Importer', 'CSV Importer', 'admin_zerobs_customers', $zbs->slugs['csvlite'], 'zeroBSCRM_CSVImporterLitepages_app', 1 ); // phpcs:ignore WordPress.WP.Capabilities.Unknown add_action( "admin_print_styles-{$csv_admin_page}", 'zeroBSCRM_CSVImporter_lite_admin_styles' ); add_action( "admin_print_styles-{$csv_admin_page}", 'zeroBSCRM_global_admin_styles' ); // } and this. } add_action( 'zerobs_admin_menu', 'zeroBSCRM_CSVImporterLiteadmin_menu' ); function zeroBSCRM_CSVImporter_lite_admin_styles() { wp_enqueue_style( 'zerobscrm-csvimporter-admcss' ); } // ================== Admin Pages // } Admin Page header function zeroBSCRM_CSVImporterLitepages_header( $subpage = '' ) { global $wpdb, $zbs, $zeroBSCRM_CSVImporterLiteversion; // } Req if ( ! current_user_can( 'admin_zerobs_customers' ) ) { wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'zero-bs-crm' ) ); } ?> <div id="sgpBody"> <div id="ZeroBSCRMAdminPage" class="ui segment"> <h1><?php echo ( empty( $subpage ) ? '' : esc_html( $subpage ) ); ?></h1> <?php // } Check for required upgrade // zeroBSCRM_CSVImportercheckForUpgrade(); } // } Admin Page footer function zeroBSCRM_CSVImporterLitepages_footer() { ?> </div> <?php } // } Main Uploader Page function zeroBSCRM_CSVImporterLitepages_app() { global $wpdb, $zbs, $zeroBSCRM_CSVImporterLiteversion; // } Req if ( ! current_user_can( 'admin_zerobs_customers' ) ) { wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'zero-bs-crm' ) ); } // } Homepage zeroBSCRM_CSVImporterLitehtml_app(); // } Footer zeroBSCRM_CSVImporterLitepages_footer(); ?> </div> <?php } // catch errors with nonce or other oddities function jpcrm_csvimporter_lite_preflight_checks( $stage ) { if ( ! isset( $_POST['zbscrmcsvimportnonce'] ) || ! wp_verify_nonce( $_POST['zbscrmcsvimportnonce'], 'zbscrm_csv_import' ) ) { // hard no zeroBSCRM_html_msg( -1, __( 'There was an error processing your CSV file. Please try again.', 'zero-bs-crm' ) ); exit(); } // eventually update this to use the zbscrm-store/_wip replacement // apparently sys_get_temp_dir() isn't consistent on whether it has a trailing slash $tmp_dir = untrailingslashit( sys_get_temp_dir() ); $tmp_dir = realpath( $tmp_dir ) . '/'; $field_map = array(); if ( $stage == 1 ) { if ( empty( $_FILES['zbscrmcsvfile'] ) || empty( $_FILES['zbscrmcsvfile']['name'] ) ) { throw new Exception( __( 'No CSV file was provided. Please choose the CSV file you want to upload.', 'zero-bs-crm' ) ); } $csv_file_data = $_FILES['zbscrmcsvfile']; // error uploading if ( $csv_file_data['error'] !== UPLOAD_ERR_OK ) { throw new Exception( __( 'There was an error processing your CSV file. Please try again.', 'zero-bs-crm' ) ); } // verify file extension and MIME if ( ! jpcrm_file_check_mime_extension( $csv_file_data, '.csv', array( 'text/csv', 'text/plain', 'application/csv' ) ) ) { throw new Exception( __( 'Your file is not a correctly-formatted CSV file. Please check your file format. If you continue to have issues please contact support.', 'zero-bs-crm' ) ); } /* The main goal below is to have a file that can be read in future steps, but also that is unreadable to the public. Things to be aware of: - If we don't move/rename the file, PHP automatically deletes it at the end of the process. - The hash/encryption is overkill at the moment but exists in case the destination folder is publicly available (see 2435-gh). - For now, we just rename the file and leave it in the system tmp folder, but eventually we can move it to the zbscrm-store replacement. */ $public_name = basename( $csv_file_data['tmp_name'] ); $hashed_filename = jpcrm_get_hashed_filename( $public_name, '.csv' ); $file_path = $tmp_dir . $hashed_filename; // try to move file to destination for future processing if ( ! move_uploaded_file( $csv_file_data['tmp_name'], $file_path ) ) { throw new Exception( __( 'Unable to upload CSV file.', 'zero-bs-crm' ) ); } } // Check stage 2 and 3 if ( $stage === 2 || $stage === 3 ) { // (carefully) check for file presence $public_name = ( isset( $_POST['zbscrmcsvimpf'] ) ? sanitize_file_name( $_POST['zbscrmcsvimpf'] ) : '' ); if ( empty( $public_name ) ) { throw new Exception( __( 'There was an error processing your CSV file. Please try again.', 'zero-bs-crm' ) ); } $hashed_filename = jpcrm_get_hashed_filename( $public_name, '.csv' ); $file_path = $tmp_dir . $hashed_filename; // Retrieve fields $field_map = array(); $mapped_field_count = 0; for ( $fieldI = 0; $fieldI <= 30; $fieldI++ ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // Default to ignore $map_to = 'ignorezbs'; // Map :) if ( ! empty( $_POST[ 'zbscrm-csv-fieldmap-' . $fieldI ] ) && $_POST[ 'zbscrm-csv-fieldmap-' . $fieldI ] !== -1 ) { $map_to = sanitize_text_field( $_POST[ 'zbscrm-csv-fieldmap-' . $fieldI ] ); // Count actual mapped fields if ( $map_to != 'ignorezbs' ) { ++$mapped_field_count; } // Pass it. $field_map[ $fieldI ] = $map_to; } } // no fields were mapped if ( $mapped_field_count === 0 ) { // delete the file unlink( $file_path ); throw new Exception( __( 'No fields were mapped. You cannot import contacts without at least one field mapped to a contact attribute.', 'zero-bs-crm' ) ); } } // Now that we only pass the filename via POST, and we encrypt+hash it, the following few lines are probably // no longer needed, but leaving for now $file_path = realpath( $file_path ); // This ensures that the provided file exists and is inside the upload folder or one of its subdirs (ie `/wp-content/uploads/*`) // and not somewhere else, also prevent traversal attacks, and usage of wrappers like phar:// etc if ( $file_path === false || ! str_starts_with( $file_path, $tmp_dir ) ) { // Traversal attempt, file does not exist, invalid wrapper throw new Exception( __( 'There was an error processing your CSV file. Please try again.', 'zero-bs-crm' ) ); } $csv_data = array(); $file = fopen( $file_path, 'r' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen while ( ! feof( $file ) ) { $csv_data[] = fgetcsv( $file ); } fclose( $file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose // no lines or empty first line if ( empty( $csv_data ) ) { // delete the file unlink( $file_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink throw new Exception( __( 'We did not find any usable lines in the provided file. If you are having continued problems please contact support.', 'zero-bs-crm' ) ); } // Count lines $num_lines = count( $csv_data ); $ignore_first_line = isset( $_POST['zbscrmcsvimpignorefirst'] ); if ( $ignore_first_line ) { --$num_lines; } $file_details = array( 'public_name' => $public_name, 'filename' => $hashed_filename, 'file_path' => $file_path, 'csv_data' => $csv_data, 'num_lines' => $num_lines, 'ignore_first_line' => $ignore_first_line, 'field_map' => $field_map, ); return $file_details; } // } HTML for main app function zeroBSCRM_CSVImporterLitehtml_app() { global $zbsCustomerFields, $zeroBSCRM_CSVImporterLiteslugs, $zbs;// ,$zeroBSCRM_CSVImporterSettings; // $settings = $zeroBSCRM_CSVImporterSettings->getAll(); $default_status = $zbs->settings->get( 'defaultstatus' ); $settings = array( 'savecopy' => false, 'defaultcustomerstatus' => $default_status ? $default_status : __( 'Customer', 'zero-bs-crm' ), ); $saveCopyOfCSVFile = false; // Not in LITE : ) if (isset($settings['savecopy'])) $saveCopyOfCSVFile = $settings['savecopy']; // } 3 stages: // } - Upload // } - Map // } - Complete (button) // } - Process $stage = 0; if ( ! empty( $_POST['zbscrmcsvimpstage'] ) ) { $stage = (int) $_POST['zbscrmcsvimpstage']; } if ( in_array( $stage, array( 1, 2, 3 ) ) ) { try { // check nonce and other things $file_details = jpcrm_csvimporter_lite_preflight_checks( $stage ); } catch ( Exception $e ) { // send back to beginning and show error $stage = 0; $stageError = $e->getMessage(); } } switch ( $stage ) { case 1: // } Title zeroBSCRM_CSVImporterLitepages_header( __( 'Step 2: Map Fields', 'zero-bs-crm' ) ); ?> <div class="zbscrm-csvimport-wrap"> <h2><?php esc_html_e( 'Map columns from your CSV to contact fields', 'zero-bs-crm' ); ?></h2> <?php if ( isset( $stageError ) && ! empty( $stageError ) ) { zeroBSCRM_html_msg( -1, $stageError ); } ?> <div class="zbscrm-csv-map"> <p class="zbscrm-csv-map-help"><?php esc_html_e( 'Your CSV file has been successfully uploaded. Please map your CSV columns to their corresponding CRM fields with the drop down options below.', 'zero-bs-crm' ); ?></p> <form method="post" class="zbscrm-csv-map-form"> <input type="hidden" id="zbscrmcsvimpstage" name="zbscrmcsvimpstage" value="2" /> <input type="hidden" id="zbscrmcsvimpf" name="zbscrmcsvimpf" value="<?php echo esc_attr( $file_details['public_name'] ); ?>" /> <?php wp_nonce_field( 'zbscrm_csv_import', 'zbscrmcsvimportnonce' ); ?> <hr /> <div class="zbscrm-csv-map-ignorefirst"> <input type="checkbox" id="zbscrmcsvimpignorefirst" name="zbscrmcsvimpignorefirst" value="1" /> <label for="zbscrmcsvimpignorefirst" ><?php echo esc_html__( 'Ignore first line of CSV file when running import.', 'zero-bs-crm' ) . '<br />' . esc_html__( 'Use this if you have a "header line" in your CSV file.', 'zero-bs-crm' ); ?></label> </div> <hr /> <?php // print_r($fileDetails); // } Cycle through each field and display a mapping option // } Using first line of import $first_line_parts = $file_details['csv_data'][0]; // } Retrieve possible map fields from fields model $possibleFields = array(); foreach ( $zbsCustomerFields as $fieldKey => $fieldDeets ) { // not custom-fields if ( ! isset( $fieldDeets['custom-field'] ) ) { $possibleFields[ $fieldKey ] = __( $fieldDeets[1], 'zero-bs-crm' ); } if ( in_array( $fieldKey, array( 'secaddr1', 'secaddr2', 'seccity', 'seccounty', 'seccountry', 'secpostcode' ) ) ) { $possibleFields[ $fieldKey ] .= ' (' . __( '2nd Address', 'zero-bs-crm' ) . ')'; } } // } Loop $indx = 1; foreach ( $first_line_parts as $userField ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // } Clean user field - "" if ( str_starts_with( $userField, '"' ) && str_ends_with( $userField, '"' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $userField = substr( $userField, 1, strlen( $userField ) - 2 ); } // } Clean user field - '' if ( str_starts_with( $userField, "'" ) && str_ends_with( $userField, "'" ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $userField = substr( $userField, 1, strlen( $userField ) - 2 ); } ?> <div class="zbscrm-csv-map-field"> <span><?php echo esc_html_x( 'Map', 'As in map CSV column to field', 'zero-bs-crm' ); ?>:</span> <div class="zbscrm-csv-map-user-field">"<?php echo esc_html( $userField ); ?>"</div><br /> <div class="zbscrm-csv-map-zbs-field"> <span class="to"><?php esc_html_e( 'To:', 'zero-bs-crm' ); ?></span> <select name="zbscrm-csv-fieldmap-<?php echo esc_attr( $indx ); ?>" id="zbscrm-csv-fieldmap-<?php echo esc_attr( $indx ); ?>"> <option value="-1" disabled="disabled"><?php esc_html_e( 'Select a field', 'zero-bs-crm' ); ?></option> <option value="-1" disabled="disabled">==============</option> <option value="ignorezbs" selected="selected"><?php esc_html_e( 'Ignore this field', 'zero-bs-crm' ); ?></option> <option value="-1" disabled="disabled">==============</option> <?php foreach ( $possibleFields as $fieldID => $fieldTitle ) { ?> <option value="<?php echo esc_attr( $fieldID ); ?>"><?php esc_html_e( $fieldTitle, 'zero-bs-crm' ); ?></option> <?php } ?> </select> </div> </div> <?php ++$indx; } ?> <hr /> <div style="text-align:center"> <button type="submit" name="csv-map-submit" id="csv-map-submit" class="ui button button-primary button-large green" type="submit"><?php esc_html_e( 'Continue', 'zero-bs-crm' ); ?></button> </div> </form> </div> </div> <?php break; case 2: // Title zeroBSCRM_CSVImporterLitepages_header( __( 'Step 3: Run Import', 'zero-bs-crm' ) ); // Stolen from plugin-install.php?tab=upload ?> <div class="zbscrm-csvimport-wrap"> <h2>Verify field mapping</h2> <?php if ( isset( $stageError ) && ! empty( $stageError ) ) { zeroBSCRM_html_msg( -1, $stageError ); } ?> <div class="zbscrm-confirmimport-csv"> <div> <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped echo zeroBSCRM_html_msg( 1, esc_html__( 'Note: There is no automatic way to undo a CSV import. To remove any contacts that have been added you will need to manually remove them.', 'zero-bs-crm' ) ); ?> <form method="post" enctype="multipart/form-data" class="zbscrm-csv-import-form"> <input type="hidden" id="zbscrmcsvimpstage" name="zbscrmcsvimpstage" value="3" /> <input type="hidden" id="zbscrmcsvimpf" name="zbscrmcsvimpf" value="<?php echo esc_attr( $file_details['public_name'] ); ?>" /> <?php wp_nonce_field( 'zbscrm_csv_import', 'zbscrmcsvimportnonce' ); ?> <h3>Import <?php echo esc_html( zeroBSCRM_prettifyLongInts( $file_details['num_lines'] ) ); ?> Contacts</h3> <hr /> <?php if ( $file_details['ignore_first_line'] ) { ?> <p style="font-size:16px;text-align:center;">Ignore first line of CSV <i class="fa fa-check"></i></p> <hr /> <input type="hidden" id="zbscrmcsvimpignorefirst" name="zbscrmcsvimpignorefirst" value="1" /> <?php } ?> <p style="font-size:16px;text-align:center;">Map the following fields:</p> <?php // Cycle through each field // Using first line of import $first_line_parts = $file_details['csv_data'][0]; foreach ( $file_details['field_map'] as $fieldID => $fieldTarget ) { $fieldTargetName = $fieldTarget; if ( isset( $zbsCustomerFields[ $fieldTarget ] ) && isset( $zbsCustomerFields[ $fieldTarget ][1] ) && ! empty( $zbsCustomerFields[ $fieldTarget ][1] ) ) { $fieldTargetName = __( $zbsCustomerFields[ $fieldTarget ][1], 'zero-bs-crm' ); } if ( in_array( $fieldTarget, array( 'secaddr1', 'secaddr2', 'seccity', 'seccounty', 'seccountry', 'secpostcode' ) ) ) { $fieldTargetName .= ' (' . __( '2nd Address', 'zero-bs-crm' ) . ')'; } $fromStr = ''; if ( isset( $first_line_parts[ $fieldID - 1 ] ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $fromStr = $first_line_parts[ $fieldID - 1 ]; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } // Clean user field - "" if ( str_starts_with( $fromStr, '"' ) && str_ends_with( $fromStr, '"' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $fromStr = substr( $fromStr, 1, strlen( $fromStr ) - 2 ); } // Clean user field - '' if ( str_starts_with( $fromStr, "'" ) && str_ends_with( $fromStr, "'" ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $fromStr = substr( $fromStr, 1, strlen( $fromStr ) - 2 ); } ?> <input type="hidden" id="zbscrm-csv-fieldmap-<?php echo esc_attr( $fieldID - 1 ); ?>" name="zbscrm-csv-fieldmap-<?php echo esc_attr( $fieldID - 1 ); ?>" value="<?php echo esc_attr( $fieldTarget ); ?>" /> <div class="zbscrm-impcsv-map"> <div class="zbscrm-impcsv-from"> <?php if ( ! empty( $fromStr ) ) { echo '"' . esc_html( $fromStr ) . '"'; } else { echo esc_html( sprintf( __( 'Field #%s', 'zero-bs-crm' ), $fieldID ) ); } ?> </div> <div class="zbscrm-impcsv-arrow"> <?php if ( $fieldTarget != 'ignorezbs' ) { echo '<i class="fa fa-long-arrow-right"></i>'; } else { echo '-'; } ?> </div> <div class="zbscrm-impcsv-to"> <?php if ( $fieldTarget != 'ignorezbs' ) { echo '"' . esc_html( $fieldTargetName ) . '"'; } else { esc_html_e( 'Ignore', 'zero-bs-crm' ); } ?> </div> </div> <?php } ?> <hr /> <div style="text-align:center"> <button type="submit" name="csv-map-submit" id="csv-map-submit" class="ui button button-primary button-large green" type="submit"><?php esc_html_e( 'Run import', 'zero-bs-crm' ); ?></button> </div> </form> </div> </div> <?php break; case 3: // } Title zeroBSCRM_CSVImporterLitepages_header( __( 'Step 4: Import', 'zero-bs-crm' ) ); ?> <div class="zbscrm-csvimport-wrap"> <h2 id="jpcrm_final_step_heading"><?php esc_html_e( 'Running import...', 'zero-bs-crm' ); ?></h2> <?php if ( isset( $stageError ) && ! empty( $stageError ) ) { zeroBSCRM_html_msg( -1, $stageError ); } ?> <div class="zbscrm-final-stage" style="text-align: center;"> <p>New contacts added: <span id="jpcrm_new_contact_count">0</span></p> <p>Existing contacts updated: <span id="jpcrm_update_contact_count">0</span></p> <button id="jpcrm_toggle_log_button" class="ui button grey"><?php esc_html_e( 'Toggle log', 'zero-bs-crm' ); ?></button> <a id="jpcrm_import_finish_button" href="<?php echo jpcrm_esc_link( $zbs->slugs['managecontacts'] ); /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped */ ?>" class="ui button green hidden"><?php esc_html_e( 'Finish', 'zero-bs-crm' ); ?></a> </div> <div id="jpcrm_import_log_div" class="zbscrm-import-log hidden"> <div class="zbscrm-import-log-line"><?php esc_html_e( 'Loading CSV File...', 'zero-bs-crm' ); ?> <i class="fa fa-check"></i></div> <div class="zbscrm-import-log-line"><?php esc_html_e( 'Parsing rows...', 'zero-bs-crm' ); ?> <i class="fa fa-check"></i></div> <div class="zbscrm-import-log-line"><?php echo esc_html( sprintf( __( 'Beginning Import of %s rows...', 'zero-bs-crm' ), zeroBSCRM_prettifyLongInts( $file_details['num_lines'] ) ) ); ?></div> <?php // } Cycle through $lineIndx = 0; $linesAdded = 0; $existingOverwrites = array(); $brStrs = array( '<br>', '<BR>', '<br />', '<BR />', '<br/>', '<BR/>' ); foreach ( $file_details['csv_data'] as $lineParts ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // } Check line if ( $lineIndx === 0 && $file_details['ignore_first_line'] ) { echo '<div class="zbscrm-import-log-line">' . esc_html__( 'Skipping header row...', 'zero-bs-crm' ) . '<i class="fa fa-check"></i></div>'; } else { // } build arr $customerFields = array(); // } Catch first if there foreach ( $file_details['field_map'] as $fieldID => $fieldTarget ) { // } id $fieldIndx = $fieldID; // } Anything to set? if ( // data in line isset( $lineParts[ $fieldIndx ] ) && ! empty( $lineParts[ $fieldIndx ] ) && // isn't ignore $fieldTarget != 'ignorezbs' ) { // for <br> passes, we convert them to nl $cleanUserField = str_replace( $brStrs, "\r\n", $lineParts[ $fieldIndx ] ); $cleanUserField = trim( $cleanUserField ); if ( $cleanUserField == 'NULL' ) { $cleanUserField = ''; } $cleanUserField = sanitize_text_field( $cleanUserField ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // } set customer fields $customerFields[ 'zbsc_' . $fieldTarget ] = $cleanUserField; } } // } Any legit fields? if ( count( $customerFields ) > 0 ) { // } Try and find a unique id for this user // adjusted for backward-compatibility, but this should be rewritten $userUniqueID = md5( implode( ',', $lineParts ) . '#' . $file_details['public_name'] ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // } 1st use email if there if ( isset( $customerFields['zbsc_email'] ) && ! empty( $customerFields['zbsc_email'] ) ) { $userUniqueID = $customerFields['zbsc_email']; } // } else use md5 of the line + Filename // } If no STATUS have to add one! $status_override_value = null; if ( ! isset( $customerFields['zbsc_status'] ) ) { // } Get from setting, if present if ( isset( $settings['defaultcustomerstatus'] ) && ! empty( $settings['defaultcustomerstatus'] ) ) { $status_override_value = $settings['defaultcustomerstatus']; } else { $status_override_value = 'Contact'; } } // } Already exists? (This is only used to find dupes $potentialCustomerID = zeroBS_getCustomerIDWithExternalSource( 'csv', $userUniqueID ); if ( ! empty( $potentialCustomerID ) && $potentialCustomerID > 0 ) { $thisDupeRef = '#' . $potentialCustomerID; if ( isset( $customerFields['zbsc_email'] ) && ! empty( $customerFields['zbsc_email'] ) ) { $thisDupeRef .= ' (' . $customerFields['zbsc_email'] . ')'; } $existingOverwrites[] = $thisDupeRef; } if ( ! empty( $potentialCustomerID ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // We could modify `zeroBS_integrations_addOrUpdateCustomer` // to touch only on the fields we are passing to the function, // but that function is used in other places and this could // result in unwanted side effects. // Instead we are passing all original fields // to the function, and overriding only the ones // we want. $original_contact = $zbs->DAL->contacts->getContact( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase $potentialCustomerID, // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase array( 'withCustomFields' => true, 'ignoreowner' => true, ) ); foreach ( $original_contact as $original_key => $original_value ) { // We need to prefix all fields coming from the above function, because // `zeroBS_integrations_addOrUpdateCustomer` expects the fields to be prefixed // (this is an older function). $original_contact[ 'zbsc_' . $original_key ] = $original_value; unset( $original_contact[ $original_key ] ); } $customerFields = array_merge( $original_contact, $customerFields ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } else { // We should override the status only when adding a new contact. $customerFields['zbsc_status'] = ! empty( $status_override_value ) ? $status_override_value : $customerFields['zbsc_status']; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } // } Add customer $newCustID = zeroBS_integrations_addOrUpdateCustomer( 'csv', $userUniqueID, $customerFields ); if ( ! empty( $newCustID ) && empty( $potentialCustomerID ) ) { ++$linesAdded; // } Line echo '<div class="zbscrm-import-log-line">' . sprintf( __( 'Successfully added contact #<a href="%1$s" target="_blank">%2$d</a>... <i class="fa fa-user"></i><span>+1</span>', 'zero-bs-crm' ), jpcrm_esc_link( 'edit', $newCustID, 'contact', false, false ), esc_html( $newCustID ) ) . '</div>'; } else { // dupe overriten? if ( ! empty( $potentialCustomerID ) ) { // } Line echo '<div class="zbscrm-import-log-line">' . esc_html__( 'Contact Already Exists!:', 'zero-bs-crm' ) . ' #' . esc_html( $newCustID ) . '... <i class="fa fa-user"></i><span>[' . esc_html__( 'Updated', 'zero-bs-crm' ) . ']</span></div>'; } } } else { echo '<div class="zbscrm-import-log-line">' . esc_html__( 'Skipping row (no usable fields)', 'zero-bs-crm' ) . '... <i class="fa fa-check"></i></div>'; } } ++$lineIndx; } // any of these? if ( count( $existingOverwrites ) > 0 ) { echo '<div class="zbscrm-import-log-line"><strong>' . esc_html__( 'The following contacts were already in your Jetpack CRM, and were updated:', 'zero-bs-crm' ) . '</strong></div>'; foreach ( $existingOverwrites as $l ) { echo '<div class="zbscrm-import-log-line">' . $l . '</div>'; } } if ( $file_details['file_path'] ) { unlink( $file_details['file_path'] ); } echo '<div class="zbscrm-import-log-line">' . esc_html__( 'CSV Upload File Deleted...', 'zero-bs-crm' ) . '<i class="fa fa-check"></i></div>'; ?> <hr /> </div> </div> <script> // these are some quick hacks for better usability until the importer rewrite function jpcrm_toggle_csv_log() { document.getElementById('jpcrm_import_log_div').classList.toggle('hidden'); } document.getElementById('jpcrm_toggle_log_button').addEventListener('click',jpcrm_toggle_csv_log); document.getElementById('jpcrm_final_step_heading').innerHTML = '<?php esc_html_e( 'Import complete!', 'zero-bs-crm' ); ?>'; document.getElementById('jpcrm_new_contact_count').innerHTML = <?php echo esc_html( $linesAdded ); /* phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase */ ?>; document.getElementById('jpcrm_update_contact_count').innerHTML = <?php echo esc_html( count( $existingOverwrites ) ); /* phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase */ ?>; document.getElementById('jpcrm_import_finish_button').classList.remove('hidden'); </script> <?php break; default: // } Also case 0 // } Title zeroBSCRM_CSVImporterLitepages_header( __( 'Step 1: Upload', 'zero-bs-crm' ) ); // } Stolen from plugin-install.php?tab=upload ?> <div class="zbscrm-csvimport-wrap"> <h2><?php esc_html_e( 'Import contacts from a CSV file', 'zero-bs-crm' ); ?></h2> <?php if ( isset( $stageError ) && ! empty( $stageError ) ) { zeroBSCRM_html_msg( -1, $stageError ); } ?> <div class="zbscrm-upload-csv"> <p class="zbscrm-csv-import-help"><?php esc_html_e( 'If you have a CSV file of contacts that you would like to import into Jetpack CRM, you can start the import wizard by uploading your .CSV file here.', 'zero-bs-crm' ); ?></p> <form method="post" enctype="multipart/form-data" class="zbscrm-csv-import-form"> <input type="hidden" id="zbscrmcsvimpstage" name="zbscrmcsvimpstage" value="1" /> <?php wp_nonce_field( 'zbscrm_csv_import', 'zbscrmcsvimportnonce' ); ?> <label class="screen-reader-text" for="zbscrmcsvfile"><?php esc_html_e( '.CSV file', 'zero-bs-crm' ); ?></label> <input type="file" id="zbscrmcsvfile" name="zbscrmcsvfile"> <div class="csv-import__start-btn"> <input type="submit" name="csv-file-submit" id="csv-file-submit" class="ui button black" value="<?php esc_attr_e( 'Upload CSV file', 'zero-bs-crm' ); ?>"> </div> </form> </div> </div> <?php // } Lite upsell (remove from rebrander) but also make it translation OK. ##WLREMOVE // WH added: Is now polite to License-key based settings like 'entrepreneur' doesn't try and upsell // this might be a bit easy to "hack out" hmmmm $bundle = false; if ( $zbs->hasEntrepreneurBundleMin() ) { $bundle = true; } if ( ! $bundle ) { ?> <hr style="margin-top:40px" /> <div class="zbscrm-lite-notice"> <h2><?php esc_html_e( 'CSV Importer: Lite Version', 'zero-bs-crm' ); ?></h2> <p><?php echo wp_kses( sprintf( __( 'If you would like to benefit from more features (such as logging your imports, automatically creating companies (B2B), and direct support) then please purchase a copy of our <a href="%s" target="_blank">CSV Importer PRO</a> extension.', 'zero-bs-crm' ), esc_url( $zbs->urls['extcsvimporterpro'] ) ), $zbs->acceptable_restricted_html ); ?><br /><br /><a href="<?php echo esc_url( $zbs->urls['extcsvimporterpro'] ); ?>" target="_blank" class="ui button blue large"><?php esc_html_e( 'Get CSV Importer PRO', 'zero-bs-crm' ); ?></a></p> </div> <?php } else { // has bundle should download + install ?> <hr style="margin-top:40px" /> <div class="zbscrm-lite-notice"> <h2><?php esc_html_e( 'CSV Importer: Lite Version', 'zero-bs-crm' ); ?></h2> <p><?php echo wp_kses( sprintf( __( 'You have the PRO version of CSV importer available as part of your bundle. Please download and install from <a href="%s" target="_blank">your account</a>.', 'zero-bs-crm' ), esc_url( $zbs->urls['account'] ) ), $zbs->acceptable_restricted_html ); ?></p> </div> <?php } ##/WLREMOVE break; } }
projects/plugins/crm/includes/ZeroBSCRM.List.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V1.0 * * Copyright 2020 Automattic * * Date: 26/05/16 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ class zeroBSCRM_list{ private $objType = false; private $objTypeID = false; // Will be set in v3.0+ - is autogenned from $objType ^^ private $singular = false; private $plural = false; private $tag = false; private $postType = false; private $postPage = false; private $langLabels = false; private $bulkActions = false; private $sortables = false; private $unsortables = false; private $extraBoxes = ''; private $extraJS = ''; private $messages = false; #} All messages need params to match this func: #} ... zeroBSCRM_UI2_messageHTML($msgClass='',$msgHeader='',$msg='',$iconClass='',$id='') /** * Construct function * * @param array $args Object construct args. */ public function __construct( $args = array() ) { $default_args = array( 'objType' => false, // transaction 'singular' => false, // Transaction 'plural' => false, // Transactions 'tag' => false, // zerobs_transactiontag 'postType' => false, // zerobs_transaction 'postPage' => false, // manage-transactions 'langLabels' => array( // bulk actions - general 'view' => __( 'View', 'zero-bs-crm' ), 'edit' => __( 'Edit', 'zero-bs-crm' ), 'deletestr' => __( 'Delete', 'zero-bs-crm' ), 'nocustomer' => __( 'Not Assigned', 'zero-bs-crm' ), 'areyousure' => __( 'Are you sure?', 'zero-bs-crm' ), 'acceptyesdoit' => __( 'Yes, accept', 'zero-bs-crm' ), 'yesproceed' => __( 'Yes, proceed', 'zero-bs-crm' ), 'changestatus' => __( 'Change Status', 'zero-bs-crm' ), 'yesupdate' => __( 'Yes, update', 'zero-bs-crm' ), // bulk actions - delete 'areyousurethese' => __( 'Are you sure you want to delete these?', 'zero-bs-crm' ), 'yesdelete' => __( 'Yes, delete!', 'zero-bs-crm' ), 'noleave' => __( 'No, leave them', 'zero-bs-crm' ), 'yesthose' => __( 'Yes, remove everything', 'zero-bs-crm' ), 'deleted' => __( 'Deleted', 'zero-bs-crm' ), 'notdeleted' => __( 'Could not delete!', 'zero-bs-crm' ), // tag related 'addtags' => __( 'Add tags', 'zero-bs-crm' ), 'removetags' => __( 'Remove tag(s)', 'zero-bs-crm' ), 'whichtags' => __( 'Which Tag(s)?', 'zero-bs-crm' ), 'whichtagsadd' => __( 'Which Tag(s) would you like to add?', 'zero-bs-crm' ), 'whichtagsremove' => __( 'Which Tag(s) would you like to remove?', 'zero-bs-crm' ), 'addthesetags' => __( 'Add Tags', 'zero-bs-crm' ), 'tagsadded' => __( 'Tags Added', 'zero-bs-crm' ), 'tagsaddeddesc' => __( 'Your tags have been successsfully added.', 'zero-bs-crm' ), 'tagsnotadded' => __( 'Tags Not Added', 'zero-bs-crm' ), 'tagsnotaddeddesc' => __( 'Your tags could not be added.', 'zero-bs-crm' ), 'tagsnotselected' => __( 'No Tags Selected', 'zero-bs-crm' ), 'tagsnotselecteddesc' => __( 'You did not select any tags.', 'zero-bs-crm' ), 'removethesetags' => __( 'Remove Tags', 'zero-bs-crm' ), 'tagsremoved' => __( 'Tags Removed', 'zero-bs-crm' ), 'tagsremoveddesc' => __( 'Your tags have been successsfully removed.', 'zero-bs-crm' ), 'tagsnotremoved' => __( 'Tags Not Removed', 'zero-bs-crm' ), 'tagsnotremoveddesc' => __( 'Your tags could not be removed.', 'zero-bs-crm' ), 'notags' => __( 'You do not have any tags', 'zero-bs-crm' ), // bulk actions - merge 2 records 'merged' => __( 'Merged', 'zero-bs-crm' ), 'notmerged' => __( 'Not Merged', 'zero-bs-crm' ), 'yesmerge' => __( 'Yes, merge them', 'zero-bs-crm' ), // error handling 'badperms' => __( 'Invalid permissions', 'zero-bs-crm' ), 'badperms_desc' => __( 'You do not have permissions to make this change.', 'zero-bs-crm' ), ), 'bulkActions' => array(), 'sortables' => array( 'id' ), 'unsortables' => array( 'tagged', 'editlink', 'phonelink', 'viewlink' ), 'extraBoxes' => '', // html for extra boxes e.g. upsells :) 'extraJS' => '', 'messages' => '', // not implemented 'hideSidebar' => false // ability to hard-hide sidebar ); // phpcs:disable foreach ($default_args as $argK => $argV){ $this->$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $this->$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$this->$argK = $newData;} else { $this->$argK = $args[$argK]; } } } // phpcs:enable global $zbs; if ( $this->objTypeID == false ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual,WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase $this->objTypeID = $zbs->DAL->objTypeID( $this->objType ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase } } public function drawListView(){ if (empty($this->objType) || empty($this->postType) || empty($this->postPage) || empty($this->singular) || empty($this->plural)){ return 'Error.'; } global $zbs; #} Retrieve all passed filters (tags, etc.) $listViewFilters = array(); if (isset($_GET['zbs_tag'])){ $possibleTag = (int)sanitize_text_field($_GET['zbs_tag']); $possibleTagObj = $zbs->DAL->getTag( $possibleTag, array( 'objtype' => $this->objTypeID ) ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase,WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase if ( isset( $possibleTagObj['id'] ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $listViewFilters['tags'] = array( $possibleTagObj ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } } if (isset($_GET['s']) && !empty($_GET['s'])){ $listViewFilters['s'] = sanitize_text_field($_GET['s']); } if (isset($_GET['quickfilters']) && !empty($_GET['quickfilters'])){ // set it whether legit? what'll this do on error urls people make up? // v2.2+ hone this + add multi-filter // v2.99.5 - ALWAYS lowercase :) $possible_quick_filters = sanitize_text_field( $_GET['quickfilters'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.MissingUnslash $listViewFilters['quickfilters'] = array( $possible_quick_filters ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } #} Paging $currentPage = 1; if (isset($_GET['paged'])) $currentPage = (int)sanitize_text_field($_GET['paged']); #} Sort $sort = false; if (isset($_GET['sort']) && !empty($_GET['sort'])) $sort = sanitize_text_field($_GET['sort']); $sortOrder = false; if (isset($_GET['sortdirection']) && ($_GET['sortdirection'] == 'asc' || $_GET['sortdirection'] == 'desc')) $sortOrder = sanitize_text_field($_GET['sortdirection']); # SCAFFOLDING - TO BE RE-ARRANGED :) #} NOTE SECOND FIELD IN THESE ARE NOW IGNORED!?!? (30/7) #} Centralised into ZeroBSCRM.List.Columns.php 30/7/17 $columnVar = 'zeroBSCRM_columns_'.$this->objType; //$zeroBSCRM_columns_transaction; $defaultColumns = $GLOBALS[ $columnVar ]['default']; $allColumns = $GLOBALS[ $columnVar ]['all']; global $zbs; $usingOwnership = $zbs->settings->get('perusercustomers'); #} Retrieve columns settings $customViews = $zbs->settings->get('customviews2'); $currentColumns = false; if (isset($customViews) && isset($customViews[$this->objType])) $currentColumns = $customViews[$this->objType]; if ($currentColumns == false) $currentColumns = $defaultColumns; // add all columns to sortables :) if ( is_array( $currentColumns ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase foreach ( $currentColumns as $col => $var ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase if ( ! in_array( $col, $this->unsortables, true ) && ! in_array( $col, $this->sortables, true ) ) { $this->sortables[] = $col; } } } $screen_opts = $zbs->global_screen_options(); if ( ! empty( $screen_opts['perpage'] ) && $screen_opts['perpage'] > 0 ) { $per_page = (int) $screen_opts['perpage']; } else { $per_page = 20; } #} Refresh 2 ?> <!-- title + edit ico --> <!-- col editor --> <div id="zbs-list-col-editor" class="hidden"> <h4 class="ui horizontal divider header"> <i class="list layout icon"></i> <?php echo esc_html( sprintf(__('%s List View Options',"zero-bs-crm"),$this->singular) ); ?> </h4> <?php if (zeroBSCRM_isZBSAdminOrAdmin()){ // only admin can manage columns (globally) ?> <div id="zbs-list-view-options-wrap" class="ui divided grid"> <div class="ui active inverted dimmer hidden" id="zbs-col-manager-loading" style="display:none"> <div class="ui text loader"><?php esc_html_e('Loading',"zero-bs-crm");?></div> </div> <div class="row"> <div class="ten wide column"> <h4><?php esc_html_e('Current Columns',"zero-bs-crm"); ?></h4> <div id="zbs-column-manager-current-cols" class="ui segment zbs-column-manager-connected"> <?php if (is_array($currentColumns)) foreach ($currentColumns as $colKey => $col){ ?><div id="zbs-column-manager-col-<?php echo esc_attr( $colKey ); ?>" class="ui compact tiny basic button zbs-column-manager-col" data-key="<?php echo esc_attr( $colKey ); ?>"><?php esc_html_e($col[0],"zero-bs-crm"); ?></div><?php } ?> </div> </div> <div class="six wide column"> <h4><?php esc_html_e('Available Columns',"zero-bs-crm"); ?></h4> <div id="zbs-column-manager-available-cols" class="ui segment"> <?php if (is_array($allColumns)) { // here we split them into groups, where there is. This allows a seperation of 'base fields' and compute fields (e.g. total value) $allColumnsSorted = array('basefields'=>array(),'other'=>array()); $hasMultiColumnGroups = 0; foreach ($allColumns as $colKey => $col){ if (!array_key_exists($colKey, $currentColumns)){ // split em up if (isset($col[2]) && $col[2] == 'basefield'){ $allColumnsSorted['basefields'][$colKey] = $col; $hasMultiColumnGroups = true; } else $allColumnsSorted['other'][$colKey] = $col; } } // now we put them out sequentially $colGroupCount = 0; foreach ($allColumnsSorted as $sortGroup => $columns){ if (is_array($columns) && count($columns) > 0){ // put out a grouper + title echo '<div>'; if ($hasMultiColumnGroups){ // header - <i class="list layout icon"></i> $title = ''; $extraStyles = ''; switch ($sortGroup){ case 'basefields': $title = __('Fields','zero-bs-crm'); break; default: $title = __('Extra Fields','zero-bs-crm'); break; } if ($colGroupCount > 0) $extraStyles = 'margin-top: 1em;'; if (!empty($title)) echo '<h4 class="ui horizontal divider header" style="'. esc_attr( $extraStyles ) .'">'. esc_html( $title ) .'</h4>'; } echo '<div class="zbs-column-manager-connected">'; foreach ($columns as $colKey => $col){ if (!array_key_exists($colKey, $currentColumns)){ ?><div id="zbs-column-manager-col-<?php echo esc_attr( $colKey ); ?>" class="ui compact tiny basic button zbs-column-manager-col" data-key="<?php echo esc_attr( $colKey ); ?>"><?php esc_html_e($col[0],"zero-bs-crm"); ?></div><?php } } echo '</div></div>'; $colGroupCount++; } } // if NONE output, we need to always have smt to drop to, so put empty: if ($colGroupCount == 0){ echo '<div class="zbs-column-manager-connected">'; echo '</div>'; } } ?> </div> </div> </div> </div> <div class="ui divider"></div> <?php } // if admin/can manage columns ?> <div id="zbs-list-options-base-wrap" class="ui grid"> <div class="two column clearing centered row"> <div class="column" style="max-width:364px;"> <div class="ui labeled input"> <div class="ui label"><i class="table icon"></i> <?php esc_html_e( 'Records per page:', 'zero-bs-crm' ); ?></div> <input type="text" style="width:70px;" class="intOnly" id="zbs-screenoptions-records-per-page" value="<?php echo esc_attr( $per_page ); ?>" /> </div> </div> </div> <div class="ui divider" style="margin-bottom:0;margin-top:0;"></div> <div class="two column clearing centered row"> <div class="column" style="max-width:364px;"> <button id="zbs-columnmanager-bottomsave" type="button" class="ui button black positive"> <i class="check square icon"></i> <?php esc_html_e( 'Save Options and Close', 'zero-bs-crm' ); ?> </button> </div> </div> </div> </div> <div class="jpcrm-listview"> <?php // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $this->draw_listview_header( $listViewFilters ); ?> <div class="jpcrm-listview-table-container"> <!-- Drawn by Javascript --> </div> <?php $this->draw_listview_footer(); ?> <div id="zbs-list-warnings-wrap"> <?php // Preloaded error messages // phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped,WordPress.WP.I18n.MissingTranslatorsComment,WordPress.WP.I18n.UnorderedPlaceholdersText echo zeroBSCRM_UI2_messageHTML( 'warning hidden', sprintf( __( 'Error retrieving %s', 'zero-bs-crm' ), $this->plural ), sprintf( __( 'There has been a problem retrieving your %s. If this issue persists, please contact support.', 'zero-bs-crm' ), $this->plural ), 'disabled warning sign', 'zbsCantLoadData' ); echo zeroBSCRM_UI2_messageHTML( 'warning hidden', sprintf( __( 'Error updating columns %s', 'zero-bs-crm' ), $this->plural ), __( 'There has been a problem saving your column configuration. If this issue persists, please contact support.', 'zero-bs-crm' ), 'disabled warning sign', 'zbsCantSaveCols' ); echo zeroBSCRM_UI2_messageHTML( 'warning hidden', sprintf( __( 'Error updating columns %s', 'zero-bs-crm' ), $this->plural ), __( 'There has been a problem saving your filter button configuration. If this issue persists, please contact support.', 'zero-bs-crm' ), 'disabled warning sign', 'zbsCantSaveButtons' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase echo zeroBSCRM_UI2_messageHTML( 'info hidden', sprintf( __( 'No %s Found', 'zero-bs-crm' ), $this->plural ), sprintf( __( 'There are no %s here. Do you want to <a href="%s">create one</a>?', 'zero-bs-crm' ), $this->plural, jpcrm_esc_link( 'create', -1, $this->postType ) ), 'disabled warning sign', 'zbsNoResults' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase // any additional messages? if ( isset( $this->messages ) && is_array( $this->messages ) && count( $this->messages ) > 0 ) { foreach ( $this->messages as $message ) { // $message needs to match this func :) echo zeroBSCRM_UI2_messageHTML( $message[0], $message[1], $message[2], $message[3], $message[4] ); } } // phpcs:enable WordPress.Security.EscapeOutput.OutputNotEscaped,WordPress.WP.I18n.MissingTranslatorsComment,WordPress.WP.I18n.UnorderedPlaceholdersText ?> </div> </div> <?php // If totals, show the wrapper. Currently only implemented in contacts if ( $zbs->settings->get( 'show_totals_table' ) === 1 && $this->objType === 'customer' ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase ?> <jpcrm-dashcount class="wide-cards"></jpcrm-dashcount> <?php } ##WLREMOVE // e.g. upsell boxes echo $this->extraBoxes; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase,WordPress.Security.EscapeOutput.OutputNotEscaped ##/WLREMOVE ?> <script type="text/javascript"> <?php // phpcs:disable Squiz.PHP.EmbeddedPhp.ContentBeforeOpen // phpcs:disable Squiz.PHP.EmbeddedPhp.ContentAfterEnd ?> // expose log types (For columns) var zbsLogTypes = <?php global $zeroBSCRM_logTypes; echo json_encode($zeroBSCRM_logTypes); ?>; <?php $allowinlineedits = ( zeroBSCRM_getSetting('allowinlineedits') == "1" ); $inlineEditStr = array(); $columns = array(); #} Current cols if ( is_array( $currentColumns ) ) { foreach ( $currentColumns as $colKey => $col ) { // set column title $column_title = __($col[0],"zero-bs-crm"); // overrides // Invoicing: Ref if ( $this->objType == 'invoice' && $colKey == 'ref' ) { $column_title = $zbs->settings->get('reflabel'); } // can column be inline edited? $inline = '-1'; if ( isset( $allColumns[$colKey] ) && isset( $allColumns[$colKey]['editinline'] ) && $allColumns[$colKey]['editinline'] ) { $inline = '1'; } $columns[] = array( 'namestr' => esc_html( zeroBSCRM_slashOut($column_title,true) ), 'fieldstr' => esc_html( zeroBSCRM_slashOut($colKey,true) ), 'inline' => (int) $inline, ); $inlineEditStr[ $colKey ] = (int) $inline; } } // build options objects $list_view_settings = array( 'objdbname' => $this->objType, 'search' => true, 'filters' => true, 'tags' => true, 'c2c' => true, 'editinline' => $allowinlineedits ); $list_view_parameters = array( 'listtype' => $this->objType, 'columns' => $columns, 'editinline' => $inlineEditStr, 'retrieved' => false, 'count' => (int)$per_page, 'pagination' => true, 'paged' => (int)$currentPage, // cast to object so an empty array is {} instead of [] when encoded as JSON 'filters' => (object) $listViewFilters, // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase 'sort' => ( !empty( $sort ) ? esc_html( $sort ) : false ), 'sortorder' => ( !empty( $sortOrder ) ? esc_html( $sortOrder ) : 'desc' ), // expose page key (used to retrieve data with screen opts - perpage) 'pagekey' => ( isset( $zbs->pageKey ) ? esc_html( $zbs->pageKey ) : '' ), ); ?> // General options for listview var zbsListViewSettings = <?php echo wp_json_encode( $list_view_settings ) ?>; // Vars for zbs list view drawer var zbsListViewParams = <?php echo wp_json_encode( $list_view_parameters ) ?>; var zbsSortables = [<?php $c = 0; if (count($this->sortables) > 0) foreach ($this->sortables as $sortableStr) { if ($c > 0) echo ','; echo "'". esc_html( $sortableStr ) ."'"; $c++; } ?>]; // for v2.2 this is only lot that will show sort, until we redo db this'll be hard var zbsBulkActions = [<?php $bulkCount = 0; if (count($this->bulkActions) > 0) foreach ($this->bulkActions as $bulkActionStr) { if ($bulkCount > 0) echo ','; echo "'". esc_html( $bulkActionStr ) ."'"; $bulkCount++; } ?>]; // :D var zbsListViewData = []; var zbsListViewCount = 0; var zbsDrawListViewBlocker = false; var zbsDrawListViewAJAXBlocker = false; var zbsDrawListViewColUpdateBlocker = false; var zbsDrawListViewColUpdateAJAXBlocker = false; var zbsObjectEmailLinkPrefix = '<?php // this assumes is contact for now, just sends to prefill - perhaps later add mailto: optional (wh wants lol) echo jpcrm_esc_link( 'email',-1,'zerobs_customer',true ); ?>'; var zbsObjectViewLinkPrefixCustomer = '<?php echo jpcrm_esc_link( 'view',-1,'zerobs_customer',true ); ?>'; var zbsObjectViewLinkPrefixCompany = '<?php echo jpcrm_esc_link( 'view',-1,'zerobs_company',true ); ?>'; var zbsObjectViewLinkPrefixQuote = '<?php echo jpcrm_esc_link( 'edit',-1,'zerobs_quote',true ); ?>'; var zbsObjectViewLinkPrefixInvoice = '<?php echo jpcrm_esc_link( 'edit',-1,'zerobs_invoice',true ); ?>'; var zbsObjectViewLinkPrefixTransaction = '<?php echo jpcrm_esc_link( 'edit',-1,'zerobs_transaction',true ); ?>'; var zbsObjectViewLinkPrefixForm = '<?php echo jpcrm_esc_link( 'edit',-1,ZBS_TYPE_FORM,true ); ?>'; var zbsObjectViewLinkPrefixSegment = '<?php echo jpcrm_esc_link( 'edit',-1,ZBS_TYPE_SEGMENT,true ); ?>'; var zbsObjectViewLinkPrefixTask = '<?php echo jpcrm_esc_link( 'edit', -1, ZBS_TYPE_TASK, true ); ?>'; var zbsObjectEditLinkPrefixCustomer = '<?php echo jpcrm_esc_link( 'edit',-1,'zerobs_customer',true ); ?>'; var zbsObjectEditLinkPrefixCompany = '<?php echo jpcrm_esc_link( 'edit',-1,'zerobs_company',true ); ?>'; var zbsObjectEditLinkPrefixQuote = '<?php echo jpcrm_esc_link( 'edit',-1,'zerobs_quote',true ); ?>'; var zbsObjectEditLinkPrefixQuoteTemplate = '<?php echo jpcrm_esc_link( 'edit',-1,'zerobs_quo_template',true ); ?>'; var zbsObjectEditLinkPrefixInvoice = '<?php echo jpcrm_esc_link( 'edit',-1,'zerobs_invoice',true ); ?>'; var zbsObjectEditLinkPrefixTransaction = '<?php echo jpcrm_esc_link( 'edit',-1,'zerobs_transaction',true ); ?>'; var zbsObjectEditLinkPrefixForm = '<?php echo jpcrm_esc_link( 'edit',-1,ZBS_TYPE_FORM,true ); ?>'; var zbsObjectEditLinkPrefixSegment = '<?php echo jpcrm_esc_link( 'edit',-1,ZBS_TYPE_SEGMENT,true ); ?>'; var jpcrm_segment_export_url_prefix = '<?php echo jpcrm_esc_link( $zbs->slugs['export-tools'] . '&segment-id=' ); ?>'; var zbsListViewLink = '<?php echo esc_url( admin_url( 'admin.php?page=' . $this->postPage ) ); /* phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase */ ?>'; var zbsExportPostURL = '<?php echo esc_url( zeroBSCRM_getAdminURL($zbs->slugs['export-tools']) ); ?>'; var zbsTagSkipLinkPrefix = zbsListViewLink + '&zbs_tag='; var zbsListViewObjName = '<?php switch ($this->postType){ case 'zerobs_customer': zeroBSCRM_slashOut(__('Contact',"zero-bs-crm")); break; case 'zerobs_company': zeroBSCRM_slashOut(jpcrm_label_company()); break; case 'zerobs_quote': zeroBSCRM_slashOut(__('Quote',"zero-bs-crm")); break; case 'zerobs_invoice': zeroBSCRM_slashOut(__('Invoice',"zero-bs-crm")); break; case 'zerobs_transaction': zeroBSCRM_slashOut(__('Transaction',"zero-bs-crm")); break; case 'zerobs_form': zeroBSCRM_slashOut(__('Form',"zero-bs-crm")); break; case 'zerobs_quotetemplate': zeroBSCRM_slashOut(__('Quote Template',"zero-bs-crm")); break; default: zeroBSCRM_slashOut(__('Item',"zero-bs-crm")); break; } ?>'; var zbsClick2CallType = parseInt('<?php echo esc_url( zeroBSCRM_getSetting('clicktocalltype') ); ?>'); <?php $jpcrm_listview_lang_labels = array(); // add any object-specific language labels if ( count( $this->langLabels ) > 0 ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase $jpcrm_listview_lang_labels = array_merge( $jpcrm_listview_lang_labels, $this->langLabels ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase } ?> var zbsListViewLangLabels = <?php echo wp_json_encode( $jpcrm_listview_lang_labels ); ?>; var zbsTagsForBulkActions = <?php // the linter was having issues with these indents, so disabling for this block // phpcs:disable Generic.WhiteSpace.ScopeIndent.IncorrectExact,Generic.WhiteSpace.ScopeIndent.Incorrect $tags = $zbs->DAL->getTagsForObjType( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase array( 'objtypeid' => $this->objTypeID, // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase 'withCount' => true, 'excludeEmpty' => false, 'ignoreowner' => true, ) ); // make simplified $simple_tags = array(); if ( is_array( $tags ) && count( $tags ) > 0 ) { foreach ( $tags as $t ) { $simple_tags[] = array( 'id' => $t['id'], 'name' => $t['name'], 'slug' => $t['slug'], ); } } $zbs_tags_for_bulk_actions = wp_json_encode( $simple_tags ); echo ( $zbs_tags_for_bulk_actions ? $zbs_tags_for_bulk_actions : '[]' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>; var zbsListViewIcos = {}; // gives data used by inline editor var zbsListViewInlineEdit = { // for now just put contacts in here customer: { statuses: <?php // MUST be a better way than this to get customer statuses... // phpcs:disable WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase global $zbsCustomerFields; if ( is_array( $zbsCustomerFields['status'][3] ) ) { echo wp_json_encode( $zbsCustomerFields['status'][3] ); } else { echo '[]'; } // phpcs:enable WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase ?> }, owners: <?php // hardcoded customer perms atm $possible_owners = zeroBS_getPossibleOwners( array( 'zerobs_admin', 'zerobs_customermgr' ), true ); if ( ! is_array( $possible_owners ) ) { echo wp_json_encode( array() ); } else { echo wp_json_encode( $possible_owners ); } ?> }; <?php // Nonce for AJAX echo 'var zbscrmjs_secToken = "' . esc_js( wp_create_nonce( 'zbscrmjs-ajax-nonce' ) ) . '";'; // any last JS? if ( isset( $this->extraJS ) && ! empty( $this->extraJS ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase echo $this->extraJS; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase,WordPress.Security.EscapeOutput.OutputNotEscaped } // phpcs:enable Generic.WhiteSpace.ScopeIndent.IncorrectExact,Generic.WhiteSpace.ScopeIndent.Incorrect ?> </script> <?php // phpcs:enable Squiz.PHP.EmbeddedPhp.ContentBeforeOpen // phpcs:enable Squiz.PHP.EmbeddedPhp.ContentAfterEnd } // /draw func /** * Draws listview header that contains search, bulk actions, and filter dropdowns * * @param array $listview_filters Array of current listview filters. */ public function draw_listview_header( $listview_filters ) { global $zbs; $all_quickfilters = array_key_exists( $this->objTypeID, $zbs->listview_filters ) ? $zbs->listview_filters[ $this->objTypeID ] : array(); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase $quickfilter_category_count = count( $all_quickfilters ); $quickfilter_categories = array( 'general' => __( 'General', 'zero-bs-crm' ), 'status' => __( 'Status', 'zero-bs-crm' ), 'segment' => __( 'Segment', 'zero-bs-crm' ), ); $all_tags = $zbs->DAL->getTagsForObjType( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase array( 'objtypeid' => $this->objTypeID, // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase 'excludeEmpty' => false, ) ); $current_quickfilter = ( ! empty( $listview_filters['quickfilters'][0] ) ? $listview_filters['quickfilters'][0] : '' ); $current_quickfilter_label = ''; if ( $quickfilter_category_count > 0 ) { $quickfilter_html = '<option disabled selected>' . esc_html__( 'Select filter', 'zero-bs-crm' ) . '</option>'; foreach ( $all_quickfilters as $category => $filters ) { if ( $quickfilter_category_count > 1 ) { $category_label = array_key_exists( $category, $quickfilter_categories ) ? $quickfilter_categories[ $category ] : $category; $quickfilter_html .= '<optgroup label="' . esc_attr( $category_label ) . '">'; } foreach ( $filters as $filter_slug => $filter_label ) { if ( $current_quickfilter === $filter_slug ) { $current_quickfilter_label = $filter_label; } $quickfilter_html .= '<option value="' . esc_attr( $filter_slug ) . '">' . esc_html( $filter_label ) . '</option>'; } if ( $quickfilter_category_count > 1 ) { $quickfilter_html .= '</optgroup>'; } } } $current_tag = ( ! empty( $listview_filters['tags'][0] ) ? $listview_filters['tags'][0]['name'] : '' ); $current_search = ( ! empty( $listview_filters['s'] ) ? $listview_filters['s'] : '' ); ?> <jpcrm-listview-header id="jpcrm-listview-header"> <header-item> <input type="search" value="<?php echo esc_attr( $current_search ); ?>" placeholder="<?php echo esc_attr__( 'Search...', 'zero-bs-crm' ); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>"/> <select class="bulk-actions-dropdown hidden"> <option><?php echo esc_html__( 'Bulk actions (no rows)', 'zero-bs-crm' ); ?></option> </select> </header-item> <header-item> <?php // add quickfilters filter if current object has quickfilters if ( $quickfilter_category_count > 0 ) { echo '<select class="filter-dropdown' . esc_attr( ! empty( $current_quickfilter_label ) ? ' hidden' : '' ) . '" data-filtertype="quickfilters">'; echo $quickfilter_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped echo '</select>'; echo '<div class="jpcrm-current-filter' . ( empty( $current_quickfilter_label ) ? ' hidden' : '' ) . '">'; echo '<button class="dashicons dashicons-remove" title="' . esc_attr__( 'Remove filter', 'zero-bs-crm' ) . '"></button>'; echo esc_html__( 'Filter', 'zero-bs-crm' ) . ': '; echo '<span>' . esc_html( $current_quickfilter_label ) . '</span>'; echo '</div>'; } // add tags filter if current object has tags if ( is_array( $all_tags ) && count( $all_tags ) > 0 ) { echo '<select class="filter-dropdown' . ( ! empty( $current_tag ) ? ' hidden' : '' ) . '" data-filtertype="tags">'; echo '<option disabled selected>' . esc_html__( 'Select tag', 'zero-bs-crm' ) . '</option>'; foreach ( $all_tags as $tag ) { echo '<option value="' . esc_attr( $tag['id'] ) . '">' . esc_html( $tag['name'] ) . '</option>'; } echo '</select>'; echo '<div class="jpcrm-current-filter' . ( empty( $current_tag ) ? ' hidden' : '' ) . '">'; echo '<button class="dashicons dashicons-remove" title="' . esc_attr__( 'Remove tag', 'zero-bs-crm' ) . '"></button>'; echo esc_html__( 'Tag', 'zero-bs-crm' ) . ': '; echo '<span>' . esc_html( $current_tag ) . '</span>'; echo '</div>'; } ?> </header-item> </jpcrm-listview-header> <?php } /** * Draws a listview footer and its containers for JS to use */ public function draw_listview_footer() { ?> <jpcrm-listview-footer> <footer-left> <div class= "jpcrm-listview-counts-container"> <!-- drawn by JS --> </div> </footer-left> <footer-right> <div class= "jpcrm-pagination-container"> <!-- drawn by JS --> </div> </footer-right> </jpcrm-listview-footer> <?php } } // class /** * Language labels for JS * * @param array $language_array Array of language labels. */ function jpcrm_listview_language_labels( $language_array ) { // phpcs:ignore Universal.Files.SeparateFunctionsFromOO.Mixed $jpcrm_listview_lang_labels = array( 'click_to_sort' => esc_html__( 'Click to sort', 'zero-bs-crm' ), /* translators: Placeholder is the number of selected rows. */ 'rows_selected_x' => esc_html__( 'Bulk actions (%s rows)', 'zero-bs-crm' ), 'rows_selected_1' => esc_html__( 'Bulk actions (1 row)', 'zero-bs-crm' ), 'rows_selected_0' => esc_html__( 'Bulk actions (no rows)', 'zero-bs-crm' ), 'zbs_edit' => esc_html__( 'Edit', 'zero-bs-crm' ), 'today' => esc_html__( 'Today', 'zero-bs-crm' ), 'daysago' => esc_html__( 'days ago', 'zero-bs-crm' ), 'notcontacted' => esc_html__( 'Not Contacted', 'zero-bs-crm' ), 'yesterday' => esc_html__( 'Yesterday', 'zero-bs-crm' ), 'couldntupdate' => esc_html__( 'Could not update', 'zero-bs-crm' ), 'couldntupdatedeets' => esc_html__( 'This record could not be updated. Please try again, if this persists please let admin know.', 'zero-bs-crm' ), /* translators: Placeholders are the range of the current record result and the total object count. */ 'listview_counts' => esc_html__( 'Showing %s of %s items', 'zero-bs-crm' ), // phpcs:ignore WordPress.WP.I18n.UnorderedPlaceholdersText ); return array_merge( $language_array, $jpcrm_listview_lang_labels ); } add_filter( 'zbs_globaljs_lang', 'jpcrm_listview_language_labels' );
projects/plugins/crm/includes/ZeroBSCRM.Delete.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V2.52+ * * Copyright 2020 Automattic * * Date: 26/02/18 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ class zeroBSCRM_Delete{ private $objID = false; private $objTypeID = false; // ZBS_TYPE_CONTACT - v3.0+ // following now FILLED OUT by objTypeID above, v3.0+ private $objType = false; // 'contact' private $singular = false; private $plural = false; private $listViewSlug = false; private $langLabels = false; private $stage = 1; // 1 = 'are you sure', 2 = 'deleted' private $canDelete = 1; // if no perms -1 // this only applies to contacts (v3.0) private $killChildren = false; function __construct($args=array()) { #} =========== LOAD ARGS ============== $defaultArgs = array( 'objID' => false, 'objTypeID' => false, //5 // these are now retrieved from DAL centralised vars by objTypeID above, v3.0+ // ... unless hard typed here. 'objType' => false, //transaction 'singular' => false, //Transaction 'plural' => false, //Transactions 'listViewSlug' => false, //manage-transactions 'langLabels' => array( ) ); foreach ($defaultArgs as $argK => $argV){ $this->$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $this->$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$this->$argK = $newData;} else { $this->$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= // NOTE: here these vars are passed like: // $this->objID // .. NOT // $objID global $zbs; // we load from DAL defaults, if objTypeID passed (overriding anything passed, if empty/false) if (isset($this->objTypeID)){ //$zbs->isDAL3() && $objTypeID = (int)$this->objTypeID; if ($objTypeID > 0){ // obj type (contact) $objTypeStr = $zbs->DAL->objTypeKey($objTypeID); if ((!isset($this->objType) || $this->objType == false) && !empty($objTypeStr)) $this->objType = $objTypeStr; // singular $objSingular = $zbs->DAL->typeStr($objTypeID); if ((!isset($this->singular) || $this->singular == false) && !empty($objSingular)) $this->singular = $objSingular; // plural $objPlural = $zbs->DAL->typeStr($objTypeID,true); if ((!isset($this->plural) || $this->plural == false) && !empty($objPlural)) $this->plural = $objPlural; // listViewSlug $objSlug = $zbs->DAL->listViewSlugFromObjID($objTypeID); if ((!isset($this->listViewSlug) || $this->listViewSlug == false) && !empty($objSlug)) $this->listViewSlug = $objSlug; } //echo 'loading from '.$this->objTypeID.':<pre>'.print_r(array($objTypeStr,$objSingular,$objPlural,$objSlug),1).'</pre>'; exit(); } // if objid - load $post $this->loadObject(); // check perms if (!zeroBSCRM_permsObjType($this->objTypeID)) $this->canDelete = false; // check if it actually exists if (!is_array($this->obj) || !isset($this->obj['id'])) $this->canDelete = false; // anything to save? if ($this->canDelete) $this->catchPost(); } // automatically, generically, loads the single obj public function loadObject(){ // if objid - load $post if (isset($this->objID) && !empty($this->objID) && $this->objID > 0) { global $zbs; // DAL3 we can use generic getSingle if ($zbs->isDAL3() && $this->objTypeID > 0){ // this gets $zbs->DAL->contacts->getSingle() $this->obj = $zbs->DAL->getObjectLayerByType($this->objTypeID)->getSingle($this->objID); } else { // DAL2 // customer currently only $this->obj = zeroBS_getCustomer($this->objID); } } } public function catchPost(){ // If post, fire do_action // DAL3 this gets postType switched to objType if (isset($_POST['zbs-delete-form-master']) && $_POST['zbs-delete-form-master'] == $this->objTypeID){ // CHECK NONCE if ( wp_verify_nonce( $_POST['zbs-delete-nonce'], 'delete-nonce' ) ) { // got any extras? e.g. kill children? if (isset($_POST['zbs-delete-kill-children'])){ if ($_POST['zbs-delete-kill-children'] == 'no') $this->killChildren = false; if ($_POST['zbs-delete-kill-children'] == 'yes') $this->killChildren = true; } // verify + delete if (isset($_POST['zbs-delete-id']) && $_POST['zbs-delete-id'] == $this->objID){ global $zbs; // got orphans? $saveOrphans = true; if ($this->killChildren) $saveOrphans = false; // legit, delete switch ($this->objTypeID){ case ZBS_TYPE_CONTACT: // delete $deleted = $zbs->DAL->contacts->deleteContact(array( 'id' => $this->objID, 'saveOrphans' => $saveOrphans )); break; case ZBS_TYPE_COMPANY: // delete $deleted = $zbs->DAL->companies->deleteCompany(array( 'id' => $this->objID, 'saveOrphans' => $saveOrphans )); break; case ZBS_TYPE_QUOTE: // delete $deleted = $zbs->DAL->quotes->deleteQuote(array( 'id' => $this->objID, 'saveOrphans' => $saveOrphans )); break; case ZBS_TYPE_INVOICE: // delete $deleted = $zbs->DAL->invoices->deleteInvoice(array( 'id' => $this->objID, 'saveOrphans' => $saveOrphans )); break; case ZBS_TYPE_TRANSACTION: // delete $deleted = $zbs->DAL->transactions->deleteTransaction(array( 'id' => $this->objID, 'saveOrphans' => $saveOrphans )); break; case ZBS_TYPE_FORM: // delete $deleted = $zbs->DAL->forms->deleteForm(array( 'id' => $this->objID, 'saveOrphans' => $saveOrphans )); break; case ZBS_TYPE_TASK: // for now always kill links $saveOrphans = false; // delete $deleted = $zbs->DAL->events->deleteEvent(array( 'id' => $this->objID, 'saveOrphans' => $saveOrphans )); break; case ZBS_TYPE_QUOTETEMPLATE: // delete $deleted = $zbs->DAL->quotetemplates->deleteQuotetemplate(array( 'id' => $this->objID, 'saveOrphans' => $saveOrphans )); break; } // fire it do_action('zerobs_delete_'.$this->objType, $this->objID, $this->obj); // set $stage +1 (as only get here if posted ^) $this->stage = 2; } } } } public function drawView(){ // check if (empty($this->objType) || empty($this->listViewSlug) || empty($this->singular) || empty($this->plural)){ return 'Error.'; } global $zbs; ?><div id="zbs-delete-master-wrap"> <form method="post" id="zbs-delete-form"> <div id="zbs-edit-warnings-wrap"> <?php #} Pre-loaded msgs, because I wrote the helpers in php first... should move helpers to js and fly these echo zeroBSCRM_UI2_messageHTML('warning hidden','Error Retrieving '.$this->plural,'There has been a problem retrieving your '.$this->singular.', if this issue persists, please ask your administrator to reach out to Jetpack CRM.','disabled warning sign','zbsCantLoadData'); echo zeroBSCRM_UI2_messageHTML('warning hidden','Error Retrieving '.$this->singular,'There has been a problem retrieving your '.$this->singular.', if this issue persists, please ask your administrator to reach out to Jetpack CRM.','disabled warning sign','zbsCantLoadDataSingle'); ?> </div> <!-- main view: list + sidebar --> <div id="zbs-edit-wrap" class="ui grid" style="padding-top:5em"> <?php if (count($zbs->pageMessages) > 0){ #} Updated Msgs // was doing like this, but need control over styling // do_action( 'zerobs_updatemsg_contact'); // so for now just using global :) echo '<div class="row" style="padding-bottom: 0 !important;"><div class="sixteen wide column" id="zbs-edit-notification-wrap">'; foreach ($zbs->pageMessages as $msg){ // for now these can be any html :) echo $msg; } echo '</div></div>'; } ?> <div class="row"> <?php if (!$this->canDelete){ // no perms msg ?> <div class="two wide column"></div> <div class="twelve wide column"> <?php echo zeroBSCRM_UI2_messageHTML('warning','Restricted','You cannot delete this '.$this->singular.'.','disabled warning sign','zbsCantDelete'); ?> </div> <div class="two wide column"></div> <?php } else { // switch based on stage switch ($this->stage){ case 2: // deleted ?> <div class="two wide column"></div> <div class="twelve wide column"> <div class="ui icon big message"> <i class="trash icon"></i> <div class="content"> <div class="header"> <?php esc_html_e('Deleted',"zero-bs-crm"); ?> </div> <p><?php echo esc_html( $this->singular ).' '. esc_html__('was successfully deleted.',"zero-bs-crm"); ?></p> <p><?php // delete / back buttons $backUrl = jpcrm_esc_link('list',-1,$this->objTypeID); // output echo '<a href="'.esc_url( $backUrl ).'" class="ui green button right floated">'. esc_html__('Back to','zero-bs-crm').' '. esc_html( $this->plural ).'</a>'; ?></p> </div> </div> </div> <div class="two wide column"></div> <?php break; case 1: // are you sure? ?> <div class="two wide column"></div> <div class="twelve wide column"> <input type="hidden" name="zbs-delete-id" value="<?php echo esc_attr( $this->objID ); ?>" /> <input type="hidden" name="zbs-delete-form-master" value="<?php echo esc_attr( $this->objTypeID ); ?>" /> <div class="ui icon big warning message"> <i class="trash icon"></i> <div class="content"> <div class="header"> <?php esc_html_e('Are you sure?',"zero-bs-crm"); ?> </div> <p><?php echo esc_html__('Are you sure you want to delete this',"zero-bs-crm").' '. esc_html( $this->singular ).'?'; ?></p> <?php $objectTypesWithChildren = array( ZBS_TYPE_CONTACT, ZBS_TYPE_COMPANY ); // contact needs extra check: if (in_array($this->objTypeID,$objectTypesWithChildren)){ // ouput explanation (what children will go) switch ($this->objTypeID){ case ZBS_TYPE_CONTACT: case ZBS_TYPE_COMPANY: ?> <?php echo '<p>'; esc_html_e( 'Shall I also delete the associated Contacts, Invoices, Quotes, Transactions, and Tasks?', 'zero-bs-crm' ); echo '<br>'; esc_html_e( '(This cannot be undone!)', 'zero-bs-crm' ); echo '</p>'; break; } ?> <p> <select name="zbs-delete-kill-children"> <option value="no"><?php esc_html_e('No, leave them',"zero-bs-crm"); ?></option> <option value="yes"><?php esc_html_e('Yes, remove everything',"zero-bs-crm"); ?></option> </select> </p><?php } ?> <p><?php // delete / back buttons $backUrl = jpcrm_esc_link('edit',$this->objID,$this->objTypeID); // output echo '<button type="submit" class="ui orange button right floated"><i class="trash alternate icon"></i> '. esc_html__('Delete','zero-bs-crm').' '. esc_html( $this->singular ) .'</button>'; echo '<a href="'. esc_url( $backUrl ) .'" class="ui green button right floated"><i class="angle double left icon"></i> '. esc_html__('Back to','zero-bs-crm').' '. esc_html( $this->singular ).' ('. esc_html__('Cancel','zero-bs-crm').')</a>'; ?></p> </div> </div> </div> <div class="two wide column"></div> <?php break; default: // smt broken! echo 'Error!'; break; } } // / can delete ?> </div> <!-- could use this for mobile variant?) <div class="two column mobile only row" style="display:none"></div> --> </div> <!-- / mainlistview wrap --> <input type="hidden" name="zbs-delete-nonce" value="<?php echo esc_attr( wp_create_nonce( "delete-nonce" ) ); ?>" /> </form></div> <script type="text/javascript"> jQuery(function($){ console.log("======= DELETE VIEW UI ========="); }); // General options for edit page var zbsDeleteSettings = { objid: <?php echo esc_html( $this->objID ); ?>, objdbname: '<?php echo esc_html( $this->objType ); ?>' }; var zbsObjectViewLinkPrefixCustomer = '<?php echo jpcrm_esc_link( 'view', -1, 'zerobs_customer', true ); ?>'; var zbsObjectEditLinkPrefixCustomer = '<?php echo jpcrm_esc_link( 'edit', -1, 'zerobs_customer', true ); ?>'; var zbsObjectViewLinkPrefixCompany = '<?php echo jpcrm_esc_link( 'view', -1, 'zerobs_company', true ); ?>'; var zbsListViewLink = '<?php echo jpcrm_esc_link($this->listViewSlug ); ?>'; var zbsClick2CallType = parseInt('<?php echo esc_html( zeroBSCRM_getSetting('clicktocalltype') ); ?>'); var zbsEditViewLangLabels = { 'today': '<?php echo esc_html( zeroBSCRM_slashOut(__('Today',"zero-bs-crm")) ); ?>', <?php $labelCount = 0; if (count($this->langLabels) > 0) foreach ($this->langLabels as $labelK => $labelV){ if ($labelCount > 0) echo ','; echo esc_html( $labelK ).":'". esc_html( zeroBSCRM_slashOut($labelV) )."'"; $labelCount++; } ?> }; <?php #} Nonce for AJAX echo "var zbscrmjs_secToken = '" . esc_js( wp_create_nonce( 'zbscrmjs-ajax-nonce' ) ) . "';"; ?></script><?php } // /draw func } // class
projects/plugins/crm/includes/ZeroBSCRM.TagManager.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * V2.52+ * * Copyright 2020 Automattic * * Date: 19/03/18 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /* ====================================================== / Breaking Checks ====================================================== */ class zeroBSCRM_TagManager{ private $objTypeID = false; // following all set by objTypeID pass, v3.0+ private $objType = false; private $singular = false; private $plural = false; // v3.0 this was removed private $postType = false; // set in child class 'zerobs_customer' // ONLY USED IN save funcs etc. maybe, potentially just legacy now. // renamed 'listViewSlug' v3.0+ private $postPage = false; private $listViewSlug = false; // except these: private $langLabels = false; private $extraBoxes = ''; function __construct($args=array()) { #} =========== LOAD ARGS ============== $defaultArgs = array( 'objTypeID' => false, //5 (v3.0+) 'objType' => false, //transaction 'singular' => false, //Transaction 'plural' => false, //Transactions //'postType' => false, //zerobs_transaction - removed v3.0 + // renamed 'listViewSlug' v3.0+ 'postPage' => false, //manage-transactions-tags 'listViewSlug' => false, 'langLabels' => array( ), 'extraBoxes' => '' // html for extra boxes e.g. upsells :) ); foreach ($defaultArgs as $argK => $argV){ $$argK = $argV; if (is_array($args) && isset($args[$argK])) { if (is_array($args[$argK])){ $newData = $$argK; if (!is_array($newData)) $newData = array(); foreach ($args[$argK] as $subK => $subV){ $newData[$subK] = $subV; }$$argK = $newData;} else { $$argK = $args[$argK]; } } } #} =========== / LOAD ARGS ============= global $zbs; // we load from DAL defaults, if objType passed (overriding anything passed, if empty/false) if ($zbs->isDAL3() && isset($objTypeID)){ $objTypeID = (int)$objTypeID; if ($objTypeID > 0){ // obj type (contact) $objTypeStr = $zbs->DAL->objTypeKey($objTypeID); if ((!isset($this->objType) || $this->objType == false) && !empty($objTypeStr)) $this->objType = $objTypeStr; // singular $objSingular = $zbs->DAL->typeStr($objTypeID); if ((!isset($this->singular) || $this->singular == false) && !empty($objSingular)) $this->singular = $objSingular; // plural $objPlural = $zbs->DAL->typeStr($objTypeID,true); if ((!isset($this->plural) || $this->plural == false) && !empty($objPlural)) $this->plural = $objPlural; // listViewSlug $objSlug = $zbs->DAL->listViewSlugFromObjID($objTypeID); if ((!isset($this->listViewSlug) || $this->listViewSlug == false) && !empty($objSlug)) $this->listViewSlug = $objSlug; } } // anything to save? $this->catchPost(); } public function catchPost(){ // If post, fire do_action if (isset($_POST['zbs-tag-form-master']) && $_POST['zbs-tag-form-master'] == $this->objType){ // fire it do_action('zerobs_save_'.$this->objType.'_tags', $this->objID, $this->obj); } } public function drawTagView(){ if (empty($this->objType) || empty($this->listViewSlug) || empty($this->singular) || empty($this->plural)){ return 'Error.'; } global $zbs; ?><div id="zbs-edit-master-wrap"><form method="post" id="zbs-edit-form" enctype="multipart/form-data"><input type="hidden" name="zbs-edit-form-master" value="<?php echo esc_attr( $this->objType ); ?>" /> <style> </style> <?php // left in for later :) $currentFields = array(); $allFields = array(); ?> <!-- field editor --> <div id="zbs-edit-field-editor" class="ui segment secondary hidden"> <?php if (current_user_can('administrator')){ ?> <h4 class="ui horizontal divider header"> <i class="list layout icon"></i> <?php echo esc_html( $this->singular ) .' '. esc_html__('Field Manager',"zero-bs-crm"); ?> </h4> <div id="zbs-edit-field-wrap" class="ui divided grid"> <div class="ui active inverted dimmer hidden" id="zbs-field-manager-loading" style="display:none"> <div class="ui text loader"><?php esc_html_e('Loading',"zero-bs-crm");?></div> </div> <div class="row"> <div class="twelve wide column"> <h4><?php esc_html_e('Current Fields',"zero-bs-crm"); ?></h4> <div id="zbs-column-manager-current-fields" class="ui segment zbs-column-manager-connected"> <?php if (is_array($currentFields)) foreach ($currentFields as $colKey => $col){ ?><div id="zbs-column-manager-field-<?php echo esc_attr( $colKey ); ?>" class="ui basic button zbs-column-manager-field" data-key="<?php echo esc_attr( $colKey ); ?>"><?php esc_html_e($col[0],"zero-bs-crm"); ?></div><?php } ?> </div> </div> <div class="four wide column"> <h4><?php esc_html_e('Available Fields',"zero-bs-crm"); ?></h4> <div id="zbs-column-manager-available-fields" class="ui segment zbs-column-manager-connected"> <?php if (is_array($allFields)) foreach ($allFields as $colKey => $col){ if (!array_key_exists($colKey, $currentColumns)){ ?><div id="zbs-column-manager-field-<?php echo esc_attr( $colKey ); ?>" class="ui basic button zbs-column-manager-field" data-key="<?php echo esc_attr( $colKey ); ?>"><?php esc_html_e($col[0],"zero-bs-crm"); ?></div><?php } } ?> </div> </div> </div> </div> <?php } // / can admin ?> </div> <!-- field manager --> <div id="zbs-edit-warnings-wrap"> <?php #} Pre-loaded msgs, because I wrote the helpers in php first... should move helpers to js and fly these echo zeroBSCRM_UI2_messageHTML('warning hidden','Error Retrieving '.$this->plural,'There has been a problem retrieving your '.$this->singular.', if this issue persists, please contact support.','disabled warning sign','zbsCantLoadData'); ?> </div> <!-- main view: list + sidebar --> <div id="zbs-edit-wrap" class="ui divided grid"> <?php if (count($zbs->pageMessages) > 0){ #} Updated Msgs // was doing like this, but need control over styling // do_action( 'zerobs_updatemsg_contact'); // so for now just using global :) echo '<div class="row" style="padding-bottom: 0 !important;"><div class="sixteen wide column" id="zbs-edit-notification-wrap">'; foreach ($zbs->pageMessages as $msg){ // for now these can be any html :) echo $msg; } echo '</div></div>'; } ?> <div class="row"> <!-- record list --> <div class="twelve wide column" id="zbs-edit-table-wrap"> <?php #} Main Metaboxes zeroBSCRM_do_meta_boxes( 'zerobs_edit_tags', 'normal', $this->objType ); ?> </div> <!-- side bar --> <div class="four wide column" id="zbs-edit-sidebar-wrap"> <?php #} Sidebar metaboxes zeroBSCRM_do_meta_boxes( 'zerobs_edit_tags', 'side', $this->objType ); ?> <?php ##WLREMOVE ?> <?php echo $this->extraBoxes; ?> <?php ##/WLREMOVE ?> </div> </div> <!-- could use this for mobile variant?) <div class="two column mobile only row" style="display:none"></div> --> </div> <!-- / mainlistview wrap --> </form></div> <script type="text/javascript"> <?php // make simpler $tags = $zbs->DAL->getTagsForObjType(array( 'objtypeid'=>$zbs->DAL->objTypeID($this->objType),//ZBS_TYPE_CONTACT in place of 'contact'=>1, 'transaction'=> etc. 'excludeEmpty'=>false, 'withCount'=>false, 'ignoreowner' => true )); $tagsArr = array(); if (is_array($tags) && count($tags) > 0) foreach ($tags as $t){ $tagsArr[] = $t['name']; } $tags = $tagsArr; ?> // this forces firing of our custom init in admin.tags.metabox.js var zbsCustomTagInitFunc = 'zbsJS_bindTagManagerInit'; var zbsDontDrawTags = true; // don't draw em in edit box // and this OVERRIDES the tag metabox list: var zbsCRMJS_currentTags = <?php echo json_encode($tags); ?>; jQuery(function($){ console.log("======= TAG MANAGER VIEW UI ========="); }); // General options for listview var zbsEditSettings = { <?php /*objid: <?php echo $this->objID; ?>,*/ ?> objdbname: '<?php echo esc_html( $this->objType ); ?>' }; var zbsDrawEditViewBlocker = false; var zbsDrawEditAJAXBlocker = false; var zbsObjectViewLinkPrefixCustomer = '<?php echo jpcrm_esc_link( 'view', -1, 'zerobs_customer', true ); ?>'; var zbsObjectEditLinkPrefixCustomer = '<?php echo jpcrm_esc_link( 'edit', -1, 'zerobs_customer', true ); ?>'; var zbsObjectViewLinkPrefixCompany = '<?php echo jpcrm_esc_link( 'view', -1, 'zerobs_company', true ); ?>'; var zbsListViewLink = '<?php echo jpcrm_esc_link( $this->listViewSlug ); ?>'; var zbsClick2CallType = parseInt('<?php echo esc_html( zeroBSCRM_getSetting('clicktocalltype') ); ?>'); var zbsEditViewLangLabels = { 'today': '<?php echo esc_html( zeroBSCRM_slashOut(__('Today',"zero-bs-crm")) ); ?>', <?php $labelCount = 0; if (is_array($this->langLabels) && count($this->langLabels) > 0) foreach ($this->langLabels as $labelK => $labelV){ if ($labelCount > 0) echo ','; echo esc_html( $labelK ).":'".esc_html( zeroBSCRM_slashOut($labelV) )."'"; $labelCount++; } ?> }; <?php #} Nonce for AJAX echo "var zbscrmjs_secToken = '" . esc_js( wp_create_nonce( 'zbscrmjs-ajax-nonce' ) ) . "';"; ?></script><?php } // /draw func } // class
projects/plugins/crm/includes/ZeroBSCRM.Core.Page.Controller.php
<?php /* ! * Jetpack CRM * https://jetpackcrm.com * V2.5 * * Copyright 2020 Automattic * * Date: 09/01/18 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) { exit; } /* ====================================================== / Breaking Checks ====================================================== */ /* ====================================================== Page Controllers ====================================================== */ /* * Sets $zbs-pageKey based on $_GET parameters * e.g. `admin.php?page=zbs-add-edit&action=edit&zbstype=contact&zbsid=101` * sets `$zbs->pageKey` to `zbs-add-edit-contact-edit` */ function jpcrm_pages_admin_addedit_set_pagekey() { global $zbs; // defaults // retrieve vars $zbsid = $zbs->zbsvar( 'zbsid' ); $type = $zbs->zbsvar( 'zbstype' ); if ( $type == -1 ) { $type = 'contact'; } $action = $zbs->zbsvar( 'action' ); // note here we append type + action to pageKey, if they're here (so we can differentiate between them for screenoptions) // This overrides the setting of pageKey in CoreMenusLearn $pageKey = $zbs->slugs['addedit']; // makes it zbs-add-edit $pageKey .= '-' . $type . '-' . $action; $zbs->pageKey = $pageKey; } /* * Translates $_GET variables into zeroBSCRM_pages_admin_addedit_page call */ function zeroBSCRM_pages_admin_addedit() { global $zbs; zeroBSCRM_pages_admin_addedit_page( ( $zbs->zbsvar( 'zbstype' ) == -1 ) ? 'contact' : $zbs->zbsvar( 'zbstype' ), $zbs->zbsvar( 'action' ), $zbs->zbsvar( 'zbsid' ) ); } // } This is a slow general move to new UI (and new DB) and moving away from the custom post add / edit links function zeroBSCRM_pages_admin_addedit_page( $type = 'contact', $action = 'new', $id = -1 ) { global $zbs; $obj_type_id = $zbs->DAL->objTypeID( $type ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase switch ( $obj_type_id ) { case ZBS_TYPE_CONTACT: // pass them this way.. zeroBSCRM_pages_admin_addedit_page_contact( $id, $action ); break; case ZBS_TYPE_COMPANY: zeroBSCRM_pages_admin_addedit_page_company( $id, $action ); break; case ZBS_TYPE_SEGMENT: zeroBSCRM_pages_admin_addedit_page_segment( $id, $action ); break; // DAL3.0 + the rest can be fired via zeroBSCRM_pages_admin_addedit_page_generic case ZBS_TYPE_QUOTE: case ZBS_TYPE_INVOICE: case ZBS_TYPE_TRANSACTION: case ZBS_TYPE_TASK: case ZBS_TYPE_FORM: case ZBS_TYPE_QUOTETEMPLATE: if ( zeroBSCRM_permsObjType( $obj_type_id ) ) { zeroBSCRM_pages_admin_addedit_page_generic( $id, $action ); } else { echo '<div style="margin-left: 20px">'; echo esc_html( sprintf( __( 'You do not have permission to edit this %s.', 'zero-bs-crm' ), $zbs->DAL->typeStr( $obj_type_id ) ) ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase,WordPress.WP.I18n.MissingTranslatorsComment echo '</div>'; } break; } } // } This function runs before any HTML has been output (after admin_init) // } ... it catches add_edit pages + initiates the right edit class, if needed // } ... This allows us to SAVE DATA before HTML has been output + therefor redirect with http headers // } e.g. New contact -> added -> redir to /..&zbsid=1 // } Edit view is added to a global var, so draw can be called in page func :) function zeroBSCRM_prehtml_pages_admin_addedit() { global $zbs; // get from zbsvar - so long as pre admin_init, this is fine to do. (This func is called a few funcs after globalise_vars() in Core, so is legit) $zbsid = $zbs->zbsvar( 'zbsid' ); $action = $zbs->zbsvar( 'action' ); $type = $zbs->zbsvar( 'zbstype' ); if ( empty( $type ) || $type == -1 ) { $type = 'contact'; } // set the pageKey var jpcrm_pages_admin_addedit_set_pagekey(); // proceed to class factory if ( $action == 'edit' ) { global $zbsEditView; switch ( $type ) { case 'contact': // } sell smt? $upsellBoxHTML = ''; $zbsEditView = new zeroBSCRM_Edit( array( 'objID' => $zbsid, 'objTypeID' => ZBS_TYPE_CONTACT, /* all of this was centralised via objTypeID^^ based on DAL from DAL3+ 'objType' => 'contact', 'singular' => $lang[0], // Contact 'plural' => $lang[1], // Contacts 'tag' => 'zerobscrm_customertag', 'postType' => 'zerobs_customer', 'postPage' => 'manage-customers', */ 'langLabels' => array( // labels // 'what' => __('WHAT',"zero-bs-crm"), ), 'extraBoxes' => $upsellBoxHTML, ) ); break; case 'company': $upsellBoxHTML = ''; $zbsEditView = new zeroBSCRM_Edit( array( 'objID' => $zbsid, 'objTypeID' => ZBS_TYPE_COMPANY, 'langLabels' => array(), 'extraBoxes' => $upsellBoxHTML, ) ); break; case 'quote': $upsellBoxHTML = ''; $zbsEditView = new zeroBSCRM_Edit( array( 'objID' => $zbsid, 'objTypeID' => ZBS_TYPE_QUOTE, 'langLabels' => array( // send email modal 'send_email' => __( 'Email Quote', 'zero-bs-crm' ), 'sendthisemail' => __( 'Send this quote via email:', 'zero-bs-crm' ), 'toemail' => __( 'To Email:', 'zero-bs-crm' ), 'toemailplaceholder' => __( 'e.g. mike@example.com', 'zero-bs-crm' ), 'attachassoc' => __( 'Attach associated files', 'zero-bs-crm' ), 'attachpdf' => __( 'Attach as PDF', 'zero-bs-crm' ), 'sendthemail' => __( 'Send', 'zero-bs-crm' ), 'sendneedsassignment' => __( 'To send an email, this quote needs to be assigned to a contact or company with a valid email address', 'zero-bs-crm' ), 'sendingemail' => __( 'Sending Email...', 'zero-bs-crm' ), 'senttitle' => __( 'Quote Sent', 'zero-bs-crm' ), 'sent' => __( 'Your quote has been sent by Email', 'zero-bs-crm' ), 'senderrortitle' => __( 'Error Sending', 'zero-bs-crm' ), 'senderror' => __( 'There was an error sending this quote via email.', 'zero-bs-crm' ), ), 'extraBoxes' => $upsellBoxHTML, ) ); break; case 'invoice': $upsellBoxHTML = ''; $zbsEditView = new zeroBSCRM_Edit( array( 'objID' => $zbsid, 'objTypeID' => ZBS_TYPE_INVOICE, 'langLabels' => array(), 'extraBoxes' => $upsellBoxHTML, ) ); break; case 'transaction': $upsellBoxHTML = ''; $zbsEditView = new zeroBSCRM_Edit( array( 'objID' => $zbsid, 'objTypeID' => ZBS_TYPE_TRANSACTION, 'langLabels' => array(), 'extraBoxes' => $upsellBoxHTML, ) ); break; case 'form': $upsellBoxHTML = ''; $zbsEditView = new zeroBSCRM_Edit( array( 'objID' => $zbsid, 'objTypeID' => ZBS_TYPE_FORM, 'langLabels' => array(), 'extraBoxes' => $upsellBoxHTML, ) ); break; case 'event': $upsellBoxHTML = ''; $zbsEditView = new zeroBSCRM_Edit( array( 'objID' => $zbsid, 'objTypeID' => ZBS_TYPE_TASK, 'langLabels' => array(), 'extraBoxes' => $upsellBoxHTML, ) ); break; case 'quotetemplate': $upsellBoxHTML = ''; $zbsEditView = new zeroBSCRM_Edit( array( 'objID' => $zbsid, 'objTypeID' => ZBS_TYPE_QUOTETEMPLATE, 'langLabels' => array(), 'extraBoxes' => $upsellBoxHTML, ) ); break; } } elseif ( $action == 'delete' ) { global $zbsDeleteView; switch ( $type ) { case 'contact': $zbsDeleteView = new zeroBSCRM_Delete( array( 'objID' => $zbsid, 'objTypeID' => ZBS_TYPE_CONTACT, 'langLabels' => array(), ) ); break; case 'company': $zbsDeleteView = new zeroBSCRM_Delete( array( 'objID' => $zbsid, 'objTypeID' => ZBS_TYPE_COMPANY, 'langLabels' => array(), ) ); break; case 'quote': $zbsDeleteView = new zeroBSCRM_Delete( array( 'objID' => $zbsid, 'objTypeID' => ZBS_TYPE_QUOTE, 'langLabels' => array(), ) ); break; case 'invoice': $zbsDeleteView = new zeroBSCRM_Delete( array( 'objID' => $zbsid, 'objTypeID' => ZBS_TYPE_INVOICE, 'langLabels' => array(), ) ); break; case 'transaction': $zbsDeleteView = new zeroBSCRM_Delete( array( 'objID' => $zbsid, 'objTypeID' => ZBS_TYPE_TRANSACTION, 'langLabels' => array(), ) ); break; case 'form': $zbsDeleteView = new zeroBSCRM_Delete( array( 'objID' => $zbsid, 'objTypeID' => ZBS_TYPE_FORM, 'langLabels' => array(), ) ); break; case 'event': $zbsDeleteView = new zeroBSCRM_Delete( array( 'objID' => $zbsid, 'objTypeID' => ZBS_TYPE_TASK, 'langLabels' => array(), ) ); break; case 'quotetemplate': $zbsDeleteView = new zeroBSCRM_Delete( array( 'objID' => $zbsid, 'objTypeID' => ZBS_TYPE_QUOTETEMPLATE, 'langLabels' => array(), ) ); break; } } } function zeroBSCRM_pages_admin_addedit_page_contact( $id = -1, $action = 'new' ) { global $zbs; if ( $action == 'view' ) { // return view page zeroBSCRM_pages_admin_view_page_contact( $id ); } elseif ( $action == 'edit' ) { /* ================================================================================ =============================== EDIT OBJECT ==================================== */ global $zbs,$zbsEditView; /* Edit Class now initiated above (in zeroBSCRM_prehtml_pages_admin_addedit) for pre-html saving .. so we can just draw here :) */ $zbsEditView->drawEditView(); /* ============================== / EDIT OBJECT ==================================== ================================================================================ */ } elseif ( $action == 'delete' ) { /* ================================================================================ ================================ DEL OBJECT ==================================== */ global $zbsDeleteView; /* Delete Class now initiated above (in zeroBSCRM_prehtml_pages_admin_addedit) for pre-html saving .. so we can just draw here :) */ $zbsDeleteView->drawView(); /* ============================== / DEL OBJECT ==================================== ================================================================================ */ } } function zeroBSCRM_pages_admin_addedit_page_company( $id = -1, $action = 'new' ) { global $zbs; if ( $action == 'view' ) { // return view page zeroBSCRM_pages_admin_view_page_company( $id ); } elseif ( $action == 'edit' ) { // super simple draw, as class would have been initiated into global, here: zeroBSCRM_prehtml_pages_admin_addedit global $zbsEditView; $zbsEditView->drawEditView(); } elseif ( $action == 'delete' ) { /* ================================================================================ ================================ DEL OBJECT ==================================== */ global $zbsDeleteView; /* Delete Class now initiated above (in zeroBSCRM_prehtml_pages_admin_addedit) for pre-html saving .. so we can just draw here :) */ $zbsDeleteView->drawView(); /* ============================== / DEL OBJECT ==================================== ================================================================================ */ } } function zeroBSCRM_pages_admin_addedit_page_segment( $id, $action = '' ) { if ( $action == 'view' ) { // return view page // for now, none // zeroBSCRM_pages_addEditSegment($id); } elseif ( $action == 'edit' ) { // edit page zeroBSCRM_pages_addEditSegment( $id ); } elseif ( $action == 'delete' ) { /* ================================================================================ ================================ DEL OBJECT ==================================== */ global $zbsDeleteView; /* Delete Class now initiated above (in zeroBSCRM_prehtml_pages_admin_addedit) for pre-html saving .. so we can just draw here :) */ $zbsDeleteView->drawView(); /* ============================== / DEL OBJECT ==================================== ================================================================================ */ } } function zeroBSCRM_pages_admin_addedit_page_generic( $id = -1, $action = 'new' ) { global $zbs; if ( $action == 'view' ) { // return view page // Generic objs (quotes, invs, trans etc.) echo zeroBSCRM_UI2_messageHTML( 'warning', __( 'Error #101', 'zero-bs-crm' ), __( 'This page does not exist.', 'zero-bs-crm' ) ); } elseif ( $action == 'edit' ) { // super simple draw, as class would have been initiated into global, here: zeroBSCRM_prehtml_pages_admin_addedit global $zbsEditView; $zbsEditView->drawEditView(); } elseif ( $action == 'delete' ) { /* ================================================================================ ================================ DEL OBJECT ==================================== */ global $zbsDeleteView; /* Delete Class now initiated above (in zeroBSCRM_prehtml_pages_admin_addedit) for pre-html saving .. so we can just draw here :) */ $zbsDeleteView->drawView(); /* ============================== / DEL OBJECT ==================================== ================================================================================ */ } } /* ====================================================== / Page Controllers ====================================================== */ /* ====================================================== Page Titles (for our custom pages e.g. edit contact) ====================================================== */ add_filter( 'admin_title', 'zeroBSCRM_pages_titleModifier', 999, 2 ); function zeroBSCRM_pages_titleModifier( $admin_title, $title ) { return apply_filters( 'zbs_admin_title_modifier', $admin_title, $title ); } /* this is hooked into in page setup add_filter( 'zbs_admin_title_modifier' , 'cut_the_boasting',10,2); function cut_the_boasting($admin_title,$title) { return 'ZBS'.$title.' AND '.$admin_title; } */ /* ====================================================== / Page Titles (for our custom pages e.g. edit contact) ====================================================== */
projects/plugins/crm/includes/jpcrm-learn-menu-legacy-functions.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * Legacy Learn menu functions * This file contains function-based learn menu rendering, where generically rendered learn menus * were moved into the new class (`Learn_Menu`), these will need modernising individually */ /* * Wrapper for newly formed Learn_Menu evolution * This provides backward compatibility for extensions using this function. * ... but is really deprecated */ function zeroBS_genericLearnMenu( $page_title = '', $left_buttons = '', $right_buttons = '', $show_learn = true, $learn_title = '', $learn_content = '', $learn_more_url = '', $learn_image_url = '', $learn_video_url = '', $extra_js = '', $popup_extra_css = '', $learn_video_title = '' ) { global $zbs; // render generic learn menu with content $zbs->learn_menu->render_generic_learn_menu( $page_title, $left_buttons, $right_buttons, $show_learn, $learn_title, $learn_content, $learn_more_url, $zbs->learn_menu->get_image_url( $learn_image_url ), $learn_video_url, $extra_js, $popup_extra_css, $learn_video_title ); } /** * Extend contact listview learn menu. * * @param array $learn_menu Learn menu array. * * @return array */ function jpcrm_contactlist_learn_menu( $learn_menu ) { $learn_menu['right_buttons'] = get_jpcrm_table_options_button(); if ( zeroBSCRM_permsCustomers() ) { $learn_menu['right_buttons'] .= '<a href="' . jpcrm_esc_link( 'create', -1, 'zerobs_customer', false ) . '" class="jpcrm-button font-14px">' . __( 'Add new contact', 'zero-bs-crm' ) . '</a>'; } return $learn_menu; } /** * Extend contact view learn menu. * * @param array $learn_menu Learn menu array. * * @return array */ function jpcrm_viewcontact_learn_menu( $learn_menu ) { $contact_id = ( empty( $_GET['zbsid'] ) ? -1 : (int) $_GET['zbsid'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended $learn_menu['right_buttons'] = zeroBSCRM_getObjNav( $contact_id, 'view', ZBS_TYPE_CONTACT ); return $learn_menu; } /** * Extend company view learn menu. * * @param array $learn_menu Learn menu array. * * @return array */ function jpcrm_viewcompany_learn_menu( $learn_menu ) { $company_id = ( empty( $_GET['zbsid'] ) ? -1 : (int) $_GET['zbsid'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended // page options likely are meant to configure object tab columns in the view profile, but they don't currently work // $learn_menu['left_buttons'] = '<button class="jpcrm-button transparent-bg font-14px" type="button" id="jpcrm_page_options">' . esc_html__( 'Page options', 'zero-bs-crm' ) . '&nbsp;<i class="fa fa-cog"></i></button>'; $learn_menu['right_buttons'] = zeroBSCRM_getObjNav( $company_id, 'view', ZBS_TYPE_COMPANY ); return $learn_menu; } /** * Extend contact edit learn menu. * * @param array $learn_menu Learn menu array. * * @return array */ function jpcrm_contactedit_learn_menu( $learn_menu ) { $contact_id = ( empty( $_GET['zbsid'] ) ? -1 : (int) $_GET['zbsid'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended $learn_menu['left_buttons'] = '<button class="jpcrm-button transparent-bg font-14px" type="button" id="jpcrm_page_options">' . esc_html__( 'Page options', 'zero-bs-crm' ) . '&nbsp;<i class="fa fa-cog"></i></button>'; $learn_menu['right_buttons'] = zeroBSCRM_getObjNav( $contact_id, 'edit', ZBS_TYPE_CONTACT ); return $learn_menu; } /** * Extend form listview learn menu. * * @param array $learn_menu Learn menu array. * * @return array */ function jpcrm_formlist_learn_menu( $learn_menu ) { $learn_menu['right_buttons'] = get_jpcrm_table_options_button(); if ( zeroBSCRM_isZBSAdminOrAdmin() ) { // Settings link global $zbs; $setting_link = zeroBSCRM_getAdminURL( $zbs->slugs['settings'] ) . '&tab=forms'; $learn_menu['right_buttons'] .= '<a href="' . esc_url( $setting_link ) . '" class="jpcrm-button white-bg font-14px" title="' . esc_attr__( 'Forms settings', 'zero-bs-crm' ) . '">' . esc_html__( 'Forms settings', 'zero-bs-crm' ) . '</a>'; } if ( zeroBSCRM_permsForms() ) { $learn_menu['right_buttons'] .= ' <a href="' . jpcrm_esc_link( 'create', -1, 'zerobs_form', false ) . '" class="jpcrm-button font-14px">' . __( 'Add new form', 'zero-bs-crm' ) . '</a>'; } return $learn_menu; } /** * Extend task edit learn menu. * * @param array $learn_menu Learn menu array. * * @return array */ function jpcrm_taskedit_learn_menu( $learn_menu ) { global $zbs; $learn_menu['left_buttons'] = '<div id="jpcrm-task-learn-nav"></div>'; $learn_menu['left_buttons'] .= ' <a href="' . jpcrm_esc_link( $zbs->slugs['manage-tasks'] ) . '" class="jpcrm-button white-bg font-14px">' . __( 'View calendar', 'zero-bs-crm' ) . '</a>'; $learn_menu['left_buttons'] .= ' <a href="' . jpcrm_esc_link( $zbs->slugs['manage-tasks-list'] ) . '" class="jpcrm-button white-bg font-14px">' . __( 'View list', 'zero-bs-crm' ) . '</a>'; return $learn_menu; } /** * Extend task listview learn menu. * * @param array $learn_menu Learn menu array. * * @return array */ function jpcrm_tasklistview_learn_menu( $learn_menu ) { global $zbs; $learn_menu['right_buttons'] = get_jpcrm_table_options_button(); $learn_menu['right_buttons'] .= ' <a href="' . jpcrm_esc_link( $zbs->slugs['manage-tasks'] ) . '" class="jpcrm-button white-bg font-14px">' . __( 'View Calendar', 'zero-bs-crm' ) . '</a>'; if ( zeroBSCRM_perms_tasks() ) { $learn_menu['right_buttons'] .= ' <a href="' . jpcrm_esc_link( 'create', -1, 'zerobs_event', false ) . '" class="jpcrm-button font-14px">' . __( 'Add new task', 'zero-bs-crm' ) . '</a>'; } return $learn_menu; } /** * Extend new task learn menu. * * @param array $learn_menu Learn menu array. * * @return array */ function jpcrm_tasknew_learn_menu( $learn_menu ) { global $zbs; $learn_menu['left_buttons'] = '<div id="jpcrm-task-learn-nav"></div>'; $learn_menu['left_buttons'] .= ' <a href="' . jpcrm_esc_link( $zbs->slugs['manage-tasks'] ) . '" class="jpcrm-button white-bg font-14px">' . __( 'View calendar', 'zero-bs-crm' ) . '</a>'; $learn_menu['left_buttons'] .= ' <a href="' . jpcrm_esc_link( $zbs->slugs['manage-tasks-list'] ) . '" class="jpcrm-button white-bg font-14px">' . __( 'View list', 'zero-bs-crm' ) . '</a>'; return $learn_menu; } /** * Extend quote listview learn menu. * * @param array $learn_menu Learn menu array. * * @return array */ function jpcrm_quotelist_learn_menu( $learn_menu ) { $learn_menu['right_buttons'] = get_jpcrm_table_options_button(); if ( zeroBSCRM_isZBSAdminOrAdmin() ) { // Settings link global $zbs; $setting_link = zeroBSCRM_getAdminURL( $zbs->slugs['settings'] ) . '&tab=quotebuilder'; $learn_menu['right_buttons'] .= '<a href="' . esc_url( $setting_link ) . '" class="jpcrm-button white-bg font-14px" title="' . esc_attr__( 'Quotes settings', 'zero-bs-crm' ) . '">' . esc_html__( 'Quotes settings', 'zero-bs-crm' ) . '</a>'; } if ( zeroBSCRM_permsCustomers() ) { $learn_menu['right_buttons'] .= ' <a href="' . jpcrm_esc_link( 'create', -1, 'zerobs_quote', false ) . '" class="jpcrm-button font-14px">' . __( 'Add new quote', 'zero-bs-crm' ) . '</a>'; } return $learn_menu; } /** * Extend transaction listview learn menu. * * @param array $learn_menu Learn menu array. * * @return array */ function jpcrm_transactionlist_learn_menu( $learn_menu ) { $learn_menu['right_buttons'] = get_jpcrm_table_options_button(); if ( zeroBSCRM_isZBSAdminOrAdmin() ) { // Settings link global $zbs; $setting_link = zeroBSCRM_getAdminURL( $zbs->slugs['settings'] ) . '&tab=transactions'; $learn_menu['right_buttons'] .= '<a href="' . esc_url( $setting_link ) . '" class="jpcrm-button white-bg font-14px" title="' . esc_attr__( 'Transaction settings', 'zero-bs-crm' ) . '">' . esc_html__( 'Transaction settings', 'zero-bs-crm' ) . '</a>'; } if ( zeroBSCRM_permsTransactions() ) { $learn_menu['right_buttons'] .= ' <a href="' . jpcrm_esc_link( 'create', -1, 'zerobs_transaction', false ) . '" class="jpcrm-button font-14px">' . __( 'Add new transaction', 'zero-bs-crm' ) . '</a>'; } return $learn_menu; } /** * Extend invoice listview learn menu. * * @param array $learn_menu Learn menu array. * * @return array */ function jpcrm_invoicelist_learn_menu( $learn_menu ) { $learn_menu['right_buttons'] = get_jpcrm_table_options_button(); if ( zeroBSCRM_isZBSAdminOrAdmin() ) { // Settings link global $zbs; $setting_link = zeroBSCRM_getAdminURL( $zbs->slugs['settings'] ) . '&tab=invbuilder'; $learn_menu['right_buttons'] .= '<a href="' . esc_url( $setting_link ) . '" class="jpcrm-button white-bg font-14px" title="' . esc_attr__( 'Invoice settings', 'zero-bs-crm' ) . '">' . esc_html__( 'Invoice settings', 'zero-bs-crm' ) . '</a>'; } if ( zeroBSCRM_permsInvoices() ) { $learn_menu['right_buttons'] .= '<a href="' . jpcrm_esc_link( 'create', -1, 'zerobs_invoice', false ) . '" class="jpcrm-button font-14px">' . __( 'Add new invoice', 'zero-bs-crm' ) . '</a>'; } return $learn_menu; } /** * Extend new invoice learn menu. * * @param array $learn_menu Learn menu array. * * @return array */ function jpcrm_invoicenew_learn_menu( $learn_menu ) { global $zbs; if ( zeroBSCRM_isZBSAdminOrAdmin() ) { $learn_menu['right_buttons'] .= '<a href="' . esc_url( admin_url( 'admin.php?page=' . $zbs->slugs['settings'] ) . '&tab=invbuilder' ) . '" class="jpcrm-button white-bg font-14px" title="' . esc_attr__( 'Invoice settings', 'zero-bs-crm' ) . '">' . esc_html__( 'Invoice settings', 'zero-bs-crm' ) . '</a>'; $learn_menu['right_buttons'] .= '<a href="' . esc_url( admin_url( 'admin.php?page=' . $zbs->slugs['settings'] ) . '&tab=bizinfo' ) . '" class="jpcrm-button white-bg font-14px" title="' . esc_attr__( 'Business settings', 'zero-bs-crm' ) . '">' . esc_html__( 'Business settings', 'zero-bs-crm' ) . '</a>'; } return $learn_menu; } /** * Extend invoice edit learn menu. * * @param array $learn_menu Learn menu array. * * @return array */ function jpcrm_invoiceedit_learn_menu( $learn_menu ) { global $zbs; if ( zeroBSCRM_isZBSAdminOrAdmin() ) { $learn_menu['right_buttons'] .= '<a href="' . esc_url( admin_url( 'admin.php?page=' . $zbs->slugs['settings'] ) . '&tab=invbuilder' ) . '" class="jpcrm-button white-bg font-14px" title="' . esc_attr__( 'Invoice settings', 'zero-bs-crm' ) . '">' . esc_html__( 'Invoice settings', 'zero-bs-crm' ) . '</a>'; $learn_menu['right_buttons'] .= '<a href="' . esc_url( admin_url( 'admin.php?page=' . $zbs->slugs['settings'] ) . '&tab=bizinfo' ) . '" class="jpcrm-button white-bg font-14px" title="' . esc_attr__( 'Business settings', 'zero-bs-crm' ) . '">' . esc_html__( 'Business settings', 'zero-bs-crm' ) . '</a>'; } return $learn_menu; } /** * Extend company listview learn menu. * * @param array $learn_menu Learn menu array. * * @return array */ function jpcrm_companylist_learn_menu( $learn_menu ) { $learn_menu['right_buttons'] = get_jpcrm_table_options_button(); if ( zeroBSCRM_isZBSAdminOrAdmin() ) { // Settings link global $zbs; $setting_link = zeroBSCRM_getAdminURL( $zbs->slugs['settings'] ) . '&tab=companies'; $learn_menu['right_buttons'] .= '<a href="' . esc_url( $setting_link ) . '" class="jpcrm-button white-bg font-14px" title="' . esc_attr__( 'Settings', 'zero-bs-crm' ) . '">' . esc_html( sprintf( __( '%s settings', 'zero-bs-crm' ), jpcrm_label_company() ) ) . '</a>'; // phpcs:ignore WordPress.WP.I18n.MissingTranslatorsComment } if ( zeroBSCRM_permsCustomers() ) { $learn_menu['right_buttons'] .= '<a href="' . jpcrm_esc_link( 'create', -1, 'zerobs_company', false ) . '" class="jpcrm-button font-14px">' . sprintf( __( 'Add new %s', 'zero-bs-crm' ), jpcrm_label_company() ) . '</a>'; // phpcs:ignore WordPress.WP.I18n.MissingTranslatorsComment } return $learn_menu; } /** * Extend company edit learn menu. * * @param array $learn_menu Learn menu array. * * @return array */ function jpcrm_companyedit_learn_menu( $learn_menu ) { $company_id = ( empty( $_GET['zbsid'] ) ? -1 : (int) $_GET['zbsid'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended $learn_menu['right_buttons'] = zeroBSCRM_getObjNav( $company_id, 'edit', ZBS_TYPE_COMPANY ); return $learn_menu; } /** * Extend task calendar learn menu. * * @param array $learn_menu Learn menu array. * * @return array */ function jpcrm_taskcalendar_learn_menu( $learn_menu ) { global $zbs; // show "who's calendar" top right $selected_user_id = ( empty( $_GET['zbsowner'] ) ? -1 : (int) $_GET['zbsowner'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended $task_users = zeroBS_getPossibleCustomerOwners(); $task_users_html = ''; if ( count( $task_users ) > 0 && zeroBSCRM_isZBSAdminOrAdmin() ) { $task_users_html .= '<select id="zerobscrm-owner">'; $task_users_html .= '<option value="-1">' . __( 'All Users', 'zero-bs-crm' ) . '</option>'; foreach ( $task_users as $user ) { $task_users_html .= '<option value="' . esc_attr( $user->ID ) . '"' . ( $user->ID === $selected_user_id ? ' selected' : '' ) . '>' . esc_html( $user->display_name ) . '</option>'; } $task_users_html .= '</select>'; $url_base = jpcrm_esc_link( $zbs->slugs['manage-tasks'] ); $task_users_html .= <<<EOF <script type="text/javascript"> var jpcrm_existing_tasks_user_id = $selected_user_id; jQuery('#zerobscrm-owner').on('change',function(){ var v = jQuery(this).val(); if (v != '' && v != window.jpcrm_existing_tasks_user_id){ var newURL = '$url_base'; if (v != -1) newURL += '&zbsowner=' + jQuery(this).val(); window.location = newURL; } }); </script> EOF; } $learn_menu['right_buttons'] = $task_users_html; $learn_menu['right_buttons'] .= ' <a href="' . jpcrm_esc_link( $zbs->slugs['manage-tasks-list'] ) . '" class="jpcrm-button white-bg font-14px">' . __( 'List view', 'zero-bs-crm' ) . '</a>'; if ( zeroBSCRM_perms_tasks() ) { $learn_menu['right_buttons'] .= ' <a href="' . jpcrm_esc_link( 'create', -1, 'zerobs_event', false ) . '" class="jpcrm-button font-14px">' . __( 'Add new task', 'zero-bs-crm' ) . '</a>'; } return $learn_menu; } /** * Extend segment listview learn menu. * * @param array $learn_menu Learn menu array. * * @return array */ function jpcrm_segmentlist_learn_menu( $learn_menu ) { $learn_menu['right_buttons'] = get_jpcrm_table_options_button(); if ( zeroBSCRM_permsCustomers() ) { $learn_menu['right_buttons'] .= ' <a href="' . jpcrm_esc_link( 'create', -1, 'segment', false ) . '" class="jpcrm-button font-14px">' . esc_html__( 'Add new segment', 'zero-bs-crm' ) . '</a>'; } return $learn_menu; } /** * Extend segment new and edit learn menu. * * @param array $learn_menu Learn menu array. * * @return array */ function jpcrm_segmentedit_learn_menu( $learn_menu ) { $is_new_segment = ( empty( $_GET['zbsid'] ) || (int) $_GET['zbsid'] <= 0 ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended if ( $is_new_segment ) { $learn_menu['title'] = __( 'New Segment', 'zero-bs-crm' ); } else { $learn_menu['right_buttons'] = '<button class="jpcrm-button font-14px" type="button" id="zbs-segment-edit-act-save">' . __( 'Save Segment', 'zero-bs-crm' ) . '</button>'; } return $learn_menu; } /** * Extend settings learn menu. * * @param array $learn_menu Learn menu array. * * @return array */ function jpcrm_settings_learn_menu( $learn_menu ) { global $zbs; if ( current_user_can( 'admin_zerobs_manage_options' ) ) { // phpcs:ignore WordPress.WP.Capabilities.Unknown $learn_menu['right_buttons'] = ' <a href="' . zeroBSCRM_getAdminURL( $zbs->slugs['modules'] ) . '" class="jpcrm-button white-bg font-14px" id="manage-features">' . __( 'Manage modules', 'zero-bs-crm' ) . '</a>'; } $learn_menu['extra_js'] = 'if (typeof hopscotch != "undefined" && (hopscotch.getState() === "zbs-welcome-tour:10" || hopscotch.getState() === "zbs-welcome-tour:10:5")) { hopscotch.startTour(window.zbsTour);}'; return $learn_menu; } /** * Extend emails learn menu. * * @param array $learn_menu Learn menu array. * * @return array */ function jpcrm_emails_learn_menu( $learn_menu ) { $learn_menu['right_buttons'] = '<a href="' . admin_url( 'admin.php?page=zerobscrm-send-email' ) . '" class="jpcrm-button font-14px zbs-inbox-compose-email">' . __( 'Compose Mail', 'zero-bs-crm' ) . '</a>'; return $learn_menu; } /** * Render object delete menu * * Likely not used anywhere. */ function jpcrm_delete_learn_menu() { global $zbs; $title = __( 'Delete', 'zero-bs-crm' ); $content = $zbs->learn_menu->get_content_body( 'delete' ); $links = $zbs->learn_menu->get_content_urls( 'delete' ); $zbstype = -1; if ( ! empty( $_GET['zbstype'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended // type specific :) $zbstype = sanitize_text_field( $_GET['zbstype'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended,WordPress.Security.ValidatedSanitizedInput.MissingUnslash // try a conversion $obj_type_id = $zbs->DAL->objTypeID( $zbstype ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase if ( $obj_type_id > 0 ) { // got a type :D $singular = $zbs->DAL->typeStr( $obj_type_id ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase $title = __( 'Delete', 'zero-bs-crm' ) . ' ' . $singular; $content = $zbs->learn_menu->get_content_body( $zbstype . 'delete' ); // e.g. contactdelete $links = $zbs->learn_menu->get_content_urls( $zbstype . 'delete' ); } } $show_learn = false; // output $zbs->learn_menu->render_generic_learn_menu( $title, '', '', $show_learn, $title, $content, $links['learn'], $links['img'], $links['vid'], '' ); } /** * Extend notifications learn menu. * * @param array $learn_menu Learn menu array. * * @return array */ function jpcrm_notifications_learn_menu( $learn_menu ) { $learn_menu['extra_js'] = 'if (typeof hopscotch != "undefined" && hopscotch.getState() === "zbs-welcome-tour:4") { hopscotch.startTour(window.zbsTour);}'; return $learn_menu; } /** * Extend extensions learn menu. * * @param array $learn_menu Learn menu array. * * @return array */ function jpcrm_extensions_learn_menu( $learn_menu ) { $learn_menu['extra_js'] = 'if (hopscotch && (hopscotch.getState() === "zbs-welcome-tour:9" || hopscotch.getState() === "zbs-welcome-tour:9:5")) { hopscotch.startTour(window.zbsTour);}'; return $learn_menu; } /** * Extend CSV Lite learn menu. * * @param array $learn_menu Learn menu array. * * @return array */ function jpcrm_csvlite_learn_menu( $learn_menu ) { global $zbs; $html = '<p>'; $html .= esc_html__( 'If you have contacts you need to import to Jetpack CRM, doing so via a CSV is common way to get your data in.', 'zero-bs-crm' ); $html .= '</p>'; ##WLREMOVE $html .= '<p>'; $html .= '<strong>' . esc_html__( 'Note', 'zero-bs-crm' ) . ':</strong> ' . sprintf( __( 'It is important that you format your CSV file correctly for the upload. We have written a detailed guide on how to do this <a href="%s" target="_blank">here</a>.', 'zero-bs-crm' ), esc_url( $zbs->urls['kbcsvformat'] ) ); // phpcs:ignore WordPress.WP.I18n.MissingTranslatorsComment $html .= '</p>'; if ( ! empty( $zbs->urls['extcsvimporterpro'] ) ) { $html .= '<p>'; $html .= esc_html__( 'Want to import companies as well as keep a record of your imports?', 'zero-bs-crm' ); $html .= ' <a href="' . esc_url( $zbs->urls['extcsvimporterpro'] ) . '" target="_blank">' . esc_html__( 'CSV importer PRO is the perfect tool.', 'zero-bs-crm' ) . '</a>'; $html .= '</p>'; $learn_menu['right_buttons'] = '<a href="' . esc_url( $zbs->urls['extcsvimporterpro'] ) . '" target="_blank" class="jpcrm-button font-14px">' . esc_html__( 'Get CSV Importer Pro', 'zero-bs-crm' ) . '</a>'; } ##/WLREMOVE $learn_menu['content'] = $html; return $learn_menu; }
projects/plugins/crm/includes/class-endpoint-listener.php
<?php /** * Jetpack CRM Endpoint Listener Class * Provides support for generic verified endpoint call captures * e.g. OAuth return calls of webhooks * * Endpoint example: * https://example.com?jpcrm_listen={hash}&jpcrm_action={action} * https://example.com?jpcrm_listen=1234&jpcrm_action=oauth_gmail */ namespace Automattic\JetpackCRM; // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; /** * Endpoint Listener class. */ class Endpoint_Listener { /** * Callback url base (url which will be listened for) */ private $callback_url_base = false; /** * Callback actions * An array of acceptable actions */ private $actions = array(); /** * Listened state (have we caught a request) */ private $listened_state = false; /** * Init */ public function __construct() { // verify & set callback_url $this->establish_callback_url(); } /* * Catch listener requests * Fired on load, catches any listener responses inbound * */ public function catch_listener_request() { // has hit our hook parameter with a valid key, only needs to fire once. if ( $this->is_listener_request() && !$this->listened_state ){ // split by action $action = sanitize_text_field( $_GET['jpcrm_action'] ); if ( $this->legitimate_action( $action ) ){ // call wp action do_action( 'jpcrm_listener_' . $action ); $this->listened_state = true; } } } /* * Verify and set callback url (frontend) */ public function establish_callback_url(){ // Set url $this->callback_url_base = site_url() . '?jpcrm_listen=' . $this->get_listener_key(); } /* * Retrieve a callback url with secondary endpoint (action) affixed */ public function get_callback_url( $action ){ if ( $this->legitimate_action( $action ) ){ return $this->callback_url_base . '&jpcrm_action=' . $action; } return false; } /* * Is this request to our listener? */ public function is_listener_request(){ // check for an oauth request & valid key if ( isset( $_GET['jpcrm_listen'] ) && $this->verify_listener_key() ) { return true; } return false; } /* * Verify listener key against the setting */ public function verify_listener_key( $key='' ){ // if key isn't passed, seek for it in _GET if ( !isset( $key ) || empty( $key ) ){ $potential_key = sanitize_text_field( $_GET['jpcrm_listen'] ); if ( empty( $potential_key ) ){ return false; } else { $key = $potential_key; } } if ( $key == $this->get_listener_key() ){ return true; } return false; } /* * Get listener key */ public function get_listener_key(){ global $zbs; // retrieve $key = $zbs->settings->get( 'global_listener_key', false ); // check it if ( empty( $key ) ){ // generate new one return $this->create_listener_key(); } return $key; } /* * Create/reset listener key */ public function create_listener_key(){ global $zbs; // generate a key $new_key = zeroBSCRM_generateHash( 20 ); // set it $zbs->settings->update( 'global_listener_key', $new_key ); // re-verify & set callback_url $this->establish_callback_url(); // return it return $new_key; } /* * Get actions */ public function get_actions() { return apply_filters( 'jpcrm_listener_actions', $this->actions ); } /* * Add action */ public function add_action( $action ) { if ( !in_array( $action, $this->actions ) ){ $this->actions[] = $action; } return $this->actions; } /* * Checks if a action is on the list */ public function legitimate_action( $action ){ if ( !empty( $action ) && in_array( $action, $this->get_actions() ) ){ return true; } return false; } }
projects/plugins/crm/includes/jpcrm-dependency-checker.php
<?php if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /** * * The JPCRMDependencyChecker class provides various functions that * can be used to verify dependencies for features and extensions * */ class JPCRM_DependencyChecker { /** * An array of plugins installed. * * @var array */ public $all_plugins = array(); /** * The current version of core. * * @var string */ protected $core_ver; /** * The current version of DAL. * * @var string */ protected $dal_ver; /** * Build DependencyChecker class */ public function __construct() { if ( ! function_exists( 'get_plugins' ) ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; } global $zbs; $this->all_plugins = get_plugins(); $this->core_ver = $zbs->version ?? ''; $this->dal_ver = $zbs->dal_version ?? ''; } /** * * Checks if a feature's dependency requirements are met * * @param str $feature_name public-facing feature name * @param arr $core_reqs array with core req_core_ver and req_DAL_ver * @param arr $plugin_reqs array of required plugins (each with a slug and req_ver) * @param bool $is_silent determine whether to show notices to the end user or not * * @return bool * */ public function check_all_reqs( $feature_name='', $core_reqs=array() , $plugin_reqs=array(), $is_silent=false ) { $meets_core_reqs = $this->check_core_reqs($feature_name, $core_reqs, $is_silent); $meets_plug_reqs = $this->check_plugin_reqs($feature_name, $plugin_reqs, $is_silent); // everything checks out if ( $meets_core_reqs && $meets_plug_reqs ) return true; // something didn't pass return false; } /** * * Checks if feature meets core dependency requirements * If it doesn't, it will trigger an admin notice * * @param str $feature_name public-facing feature name * @param arr $core_reqs details required for feature (req_core_ver and req_DAL_ver) * @param bool $is_silent determine whether to show notices to the end user or not * * @return bool * */ public function check_core_reqs( $feature_name='', $args=array(), $is_silent=false ) { $req_core_ver = !empty( $args['req_core_ver'] ) ? $args['req_core_ver'] : 1e6; //high version number $is_good_core_ver = version_compare( $this->core_ver, $req_core_ver, '>=' ); $req_DAL_ver = !empty( $args['req_DAL_ver'] ) ? $args['req_DAL_ver'] : false; $is_good_DAL_ver = version_compare( $this->dal_ver, $req_DAL_ver, '>=' ); // return true if everything checks out if ( $is_good_core_ver && $is_good_DAL_ver) { return true; } // return false if silent check elseif ($is_silent) { return false; } global $zbs; // otherwise, proceed to trigger an admin notice $feature_name = !empty( $feature_name ) ? $feature_name : __( 'CRM feature', 'zero-bs-crm' ); if ( empty( $this->core_ver ) || empty( $this->dal_ver ) ) { $error_msg = __( 'Your CRM install appears to have issues. Please verify the CRM is fully installed and any notices are properly handled before trying again.', 'zero-bs-crm' ); ##WLREMOVE $error_msg = __( 'Your Jetpack CRM install appears to have issues. Please verify the CRM is fully installed and any notices are properly handled before trying again.', 'zero-bs-crm' ); ##/WLREMOVE } elseif ( ! $is_good_core_ver ) { $error_msg = sprintf( __( '%s requires CRM version %s or greater, but version %s is currently installed. Please update your CRM to use this feature.', 'zero-bs-crm' ), $feature_name, $req_core_ver, $this->core_ver ); ##WLREMOVE $error_msg = sprintf( __( '%s requires Jetpack CRM version %s or greater, but version %s is currently installed. Please update Jetpack CRM to use this feature.', 'zero-bs-crm' ), $feature_name, $req_core_ver, $this->core_ver ); ##/WLREMOVE } else if ( !$is_good_DAL_ver ) { $error_msg = sprintf( __( '%s requires your CRM database to be updated. Please visit <a href="%s">your CRM dashboard</a> for more information.', 'zero-bs-crm' ), $feature_name, zeroBSCRM_getAdminURL( $zbs->slugs['dash'] ) ); } $error_fn = function() use( $error_msg ) { $this->show_dependency_error( $error_msg ); }; add_action( 'admin_notices', $error_fn ); return false; } /** * * Checks if a plugin is installed * * @param str $slug plugin slug * * @return bool * */ private function is_plugin_installed( $slug='' ){ if ( array_key_exists( $slug, $this->all_plugins ) ) { return true; } return false; } /** * Gets plugin version * * @param str $slug plugin slug * * @return str plugin version * @return bool false if slug is not found * */ private function get_plugin_version( $slug='' ) { if ( $this->is_plugin_installed( $slug ) ) { return $this->all_plugins[$slug]['Version']; } return false; } /** * * Checks if feature's plugin dependency requirements are met * If it doesn't, it will trigger an admin notice * * @param arr $plugins array of required plugins (each with an array of name, slug, and req_ver) * @param bool $is_silent determine whether to show notices to the end user or not * @param str $error_msg custom failure message (optional) * * @return bool * */ public function check_plugin_reqs( $feature_name='', $plugins=array(), $is_silent=false, $error_msg='' ) { $everything_is_fine = true; $feature_name = !empty( $feature_name ) ? $feature_name : __( 'CRM feature', 'zero-bs-crm' ); // if we don't have an array of arrays (e.g. only one plugin is passed), make one if ( !isset( $plugins[0] ) ) { $plugins = array( $plugins ); } foreach ( $plugins as $args ) { $slug = !empty( $args['slug'] ) ? $args['slug'] : ''; $cur_ver = $this->get_plugin_version( $slug ); $req_ver = !empty( $args['req_ver'] ) ? $args['req_ver'] : 1e6; //high version number $is_good_ver = version_compare($cur_ver, $req_ver, '>='); $is_active = is_plugin_active( $slug ); // move to next plugin check if everything checks out if ( $is_active && $is_good_ver ) { continue; } $everything_is_fine = false; // short-circuit if silent check if ( $is_silent || ! current_user_can( 'activate_plugins' ) ) { break; } // otherwise, proceed to trigger an admin notice $plugin_name = !empty( $args['name'] ) ? $args['name'] : $slug; //use slug if no name $plugin_link = !empty( $args['link'] ) ? $args['link'] : false; $is_installed = $this->is_plugin_installed( $slug ); if ( empty( $slug ) ) { $error_msg = __( 'A CRM feature has an unknown missing dependency. Please contact support!' ); ##WLREMOVE $error_msg = __( 'A Jetpack CRM feature has an unknown missing dependency. Please contact support!' ); ##/WLREMOVE } else if ( empty( $error_msg ) ) { if ( !$is_installed ) { $error_msg = sprintf( __( '%s requires %s version %s or greater. Please install and activate %s to use this feature.', 'zero-bs-crm' ), $feature_name, $plugin_link?'<a target="_blank" href="'.$plugin_link.'">'.$plugin_name.'</a>':$plugin_name, $req_ver, $plugin_name ); } else if ( $is_installed && !$is_good_ver ) { $error_msg = sprintf( __( '%s requires %s version %s or greater, but version %s is currently installed. Please update %s to use this feature.', 'zero-bs-crm' ), $feature_name, $plugin_name, $req_ver, $cur_ver, $plugin_name ); } else if ( !$is_active ) { $error_msg = sprintf( __( '%s requires the %s plugin to be active. Please activate %s to use this feature.', 'zero-bs-crm' ), $feature_name, $plugin_name, $plugin_name ); ##WLREMOVE if ( !empty( $args['kb_link'] ) ) { $error_msg .= '<br><br>'; $error_msg .= sprintf( __( 'To learn more about how this feature works, click <a href="%s" target="_blank">here</a>.', 'zero-bs-crm' ), $args['kb_link'] ); } ##/WLREMOVE } } $error_fn = function() use( $error_msg ) { $this->show_dependency_error( $error_msg ); }; add_action( 'admin_notices', $error_fn ); } return $everything_is_fine; } /** * * Show error message if feature's dependency requirements are not met * * @param str $error_msg * */ private function show_dependency_error( $error_msg ) { if ( zeroBSCRM_isAdminPage() ) { ?> <div class="ui segment jpcrm-error"> <div class="content"> <b><?php esc_html_e( 'CRM dependency error', 'zero-bs-crm' ) ?></b><br> <p><?php echo $error_msg; ?></p> </div> </div> <?php } else { ?> <div class="error"><p><?php echo $error_msg; ?></p></div> <?php } } }
projects/plugins/crm/includes/jpcrm-rewrite-rules.php
<?php /** * Handle rewrite rules for Jetpack CRM * * @package automattic/jetpack-crm */ // prevent direct access if ( ! defined( 'ZEROBSCRM_PATH' ) ) { exit; } /** * Flush rewrite rules if flagged to do so */ function jpcrm_do_flush_rewrite() { $flush_rewrite_option = get_option( 'jpcrm_flush_rewrite_flag', 0 ); // no need for flush/rewrite if ( $flush_rewrite_option <= 0 ) { return; } flush_rewrite_rules(); delete_option( 'jpcrm_flush_rewrite_flag' ); } add_action( 'init', 'jpcrm_do_flush_rewrite' ); /** * Add flag to flush rewrite rules */ function jpcrm_flag_for_flush_rewrite() { update_option( 'jpcrm_flush_rewrite_flag', time(), false ); }
projects/plugins/crm/includes/ZeroBSCRM.DAL3.Fields.php
<?php /* ! * Jetpack CRM * https://jetpackcrm.com * V1.1.19 * * Copyright 2020 Automattic * * Date: 18/10/16 */ /* ====================================================== Breaking Checks ( stops direct access ) ====================================================== */ if ( ! defined( 'ZEROBSCRM_PATH' ) ) { exit; } /* ====================================================== / Breaking Checks ====================================================== */ global $zbsFieldsEnabled,$zbsFieldSorts,$zbsAddressFields; $zbsFieldsEnabled = array(); // } ALSO added 'opt' field #} if this is set it'll be checked whether $zbsFieldsEnabled['optname'] global is true/false $zbsFieldSorts = array(); $zbsAddressFields = array(); // these are all DAL3 Object Loaded via zeroBSCRM_fields_initialise(): global $zbsCustomerFields,$zbsCompanyFields,$zbsCustomerQuoteFields,$zbsCustomerInvoiceFields,$zbsTransactionFields,$zbsFormFields; $zbsCustomerFields = array(); $zbsCompanyFields = array(); $zbsCustomerQuoteFields = array(); $zbsCustomerInvoiceFields = array(); $zbsTransactionFields = array(); $zbsFormFields = array(); // This takes all the DAL3 object models and builds out fieldGlobalArrays // ... as was hard-typed in < v3.0 // ... Addresses still hard typed as 3.0, but rest model-generated // This gets run in Core.php after initialising zbsDAL class function zeroBSCRM_fields_initialise() { global $zbs,$zbsFieldsEnabled,$zbsFieldSorts,$zbsAddressFields; global $zbsCustomerFields,$zbsCompanyFields,$zbsCustomerQuoteFields,$zbsCustomerInvoiceFields,$zbsTransactionFields,$zbsFormFields; /* ====================================================== Legacy / Unchanged ====================================================== */ $zbsAddressFields = array( 'addr1' => array( 'text', __( 'Address Line 1', 'zero-bs-crm' ), '', 'area' => 'Main Address', ), 'addr2' => array( 'text', __( 'Address Line 2', 'zero-bs-crm' ), '', 'area' => 'Main Address', ), 'city' => array( 'text', __( 'City', 'zero-bs-crm' ), 'e.g. New York', 'area' => 'Main Address', ), 'county' => array( 'text', __( 'County', 'zero-bs-crm' ), 'e.g. Kings County', 'area' => 'Main Address', ), 'postcode' => array( 'text', __( 'Postcode', 'zero-bs-crm' ), 'e.g. 10019', 'area' => 'Main Address', ), 'country' => array( 'text', __( 'Country', 'zero-bs-crm' ), 'e.g. UK', 'area' => 'Main Address', ), ); // } Global Default sort for all "addresses" (to be used for all address outputs) $zbsFieldSorts['address'] = array( // } Default order 'default' => array( 'addr1', 'addr2', 'city', 'county', 'postcode', 'country', ), ); /* ====================================================== / Legacy / Unchanged ====================================================== */ /* ====================================================== Contacts ====================================================== */ // Load from object model :) $zbsCustomerFields = $zbs->DAL->contacts->generateFieldsGlobalArr(); // } Default sort (still hard-typed for now) $zbsFieldSorts['customer'] = array( // } Default order 'default' => array( 'status', 'prefix', 'fname', 'lname', /* addresses subordinated to global "address" field sort 'addr1', 'addr2', 'city', 'county', 'postcode', */ 'addresses', // } This indicates addresses 'hometel', 'worktel', 'mobtel', 'email', 'notes', ), ); /* ====================================================== / Contacts ====================================================== */ /* ====================================================== Companies ====================================================== */ // Load from object model :) $zbsCompanyFields = $zbs->DAL->companies->generateFieldsGlobalArr(); // } Default sort (still hard-typed for now) $zbsFieldSorts['company'] = array( // } Default order 'default' => array( 'status', 'name', // coname /* addresses subordinated to global "address" field sort 'addr1', 'addr2', 'city', 'county', 'postcode', */ 'addresses', // } This indicates addresses 'maintel', 'sectel', 'mobtel', 'email', 'notes', ), ); /* ====================================================== / Companies ====================================================== */ /* ====================================================== Quotes ====================================================== */ // Load from object model :) $zbsCustomerQuoteFields = $zbs->DAL->quotes->generateFieldsGlobalArr(); // } Default sort (still hard-typed for now) $zbsFieldSorts['quote'] = array( // } Default order 'default' => array( 'title', // name 'value', // val 'date', 'notes', ), ); /* ====================================================== / Quotes ====================================================== */ /* ====================================================== Invoices ====================================================== */ /* NOTE: $zbsCustomerInvoiceFields Removed as of v3.0, invoice builder is very custom, UI wise, .. and as the model can deal with saving + custom fields WITHOUT the global, there's no need (whereas other objects input views are directed by these globals, Invs is separate, way MS made it) // Load from object model :) $zbsCustomerInvoiceFields = $zbs->DAL->invoices->generateFieldsGlobalArr(); #} Default sort (still hard-typed for now) $zbsFieldSorts['invoice'] = array( #} Default order 'default' => array( 'status', 'no', 'date', 'notes', 'ref', 'due', 'logo', 'bill', 'ccbill' ) ); */ /* ====================================================== / Invoices ====================================================== */ /* ====================================================== Transactions ====================================================== */ // Load from object model :) $zbsTransactionFields = $zbs->DAL->transactions->generateFieldsGlobalArr(); // } Default sort (still hard-typed for now) /* not used, yet? $zbsFieldSorts['transactions'] = array( #} Default order 'default' => array( ) ); */ /* ====================================================== / Transactions ====================================================== */ /* ====================================================== Forms ====================================================== */ // Load from object model :) $zbsFormFields = $zbs->DAL->forms->generateFieldsGlobalArr(); // } Default sort (still hard-typed for now) $zbsFieldSorts['form'] = array( // } Default order 'default' => array( 'header', 'subheader', 'fname', 'lname', 'email', 'notes', 'submit', 'spam', 'success', ), ); /* ====================================================== / Forms ====================================================== */ } /* ====================================================== Hard Coded Fields + Sorts (Defaults which can be overriden by custom fields + field sorts) ====================================================== */ // } Below are HARD CODED fields :) // } NOTE: // } Added an additional field to each field 'area' // } adding this (any text) will group these into a "subset" with title of 'area' // } they MUST (currently) be in sequential order!!! /* DAL3 Notes: #globalfieldobjsdal3 This ultimately becomes #legacy. This global $fields var collection was written way back at the beginning when we were doing all kinds of rough dev. Now, these are kind of derelict technical debt, really replaced by DAL obj models. To defer the work in this cycle, I've left these here (as doing DAL3 translation) because to remove them at this point is like peeling off a symbiote. ... so, for near future, let's see how they play out. DAL3 Obj models + legacy $fields globals. I suppose the field globals are kind of "UI visible" variants of obj models... that's how they operate, for now, at least. // interesting use: DAL2 core, func: ->objModel($type=1) WH 12/2/19 TBC ... yeah this was legacy. I split this from ZeroBSCRM.Fields.php into it's own DAL3 drop-in replacement because the old way was far too clunky when we have proper models now. But rather than being model-based here ... I've opted for a second layer (maintain existing, just tweak the names where they've changed) ... e.g. Quote "name" => "title" WH 22/3/19 */ /* ====================================================== Field & Sort Functions (These build out custom field arrs by working on defaults from above) ====================================================== */ // } Currently this is just "add countries" or dont function zeroBSCRM_internalAddressFieldMods() { global $zbs; $addCountries = $zbs->settings->get( 'countries' ); if ( isset( $addCountries ) && $addCountries ) { // } add it global $zbsAddressFields, $zbsFieldSorts; $zbsAddressFields['country'] = array( 'selectcountry', __( 'Country', 'zero-bs-crm' ), 'e.g. United Kingdom', 'area' => 'Main Address', ); // } add to sort $zbsFieldSorts['address']['default'][] = 'country'; } } // } Unpack any custom fields + add function zeroBSCRM_unpackCustomFields() { // } Jammed for now, adds country if set! zeroBSCRM_internalAddressFieldMods(); global $zbs,$zbsAddressFields,$zbsFieldSorts; $customfields = $zbs->settings->get( 'customfields' ); $keyDrivenCustomFields = array( // these get DAL3 Custom fields 'customers' => ZBS_TYPE_CONTACT, 'companies' => ZBS_TYPE_COMPANY, 'quotes' => ZBS_TYPE_QUOTE, 'transactions' => ZBS_TYPE_TRANSACTION, 'invoices' => ZBS_TYPE_INVOICE, 'addresses' => ZBS_TYPE_ADDRESS, ); // Following overloading code is also replicated in AdminPages.php (settings page), search #FIELDOVERLOADINGDAL2+ // DAL3 ver (all objs in $keyDrivenCustomFields above) if ( $zbs->isDAL3() ) { foreach ( $keyDrivenCustomFields as $key => $objTypeID ) { if ( isset( $customfields ) && isset( $customfields[ $key ] ) ) { // turn ZBS_TYPE_CONTACT (1) into "contact" $typeStr = $zbs->DAL->objTypeKey( $objTypeID ); if ( ! empty( $typeStr ) ) { $customfields[ $key ] = $zbs->DAL->setting( 'customfields_' . $typeStr, array() ); } } } } // / field overloading if ( isset( $customfields ) && is_array( $customfields ) ) { // v3rc2, this doesn't appear to be needed, already loaded above? // left in as fallback if ( isset( $customfields['addresses'] ) && is_array( $customfields['addresses'] ) && count( $customfields['addresses'] ) > 0 ) { $addrCustomFields = $customfields['addresses']; } else { $addrCustomFields = $zbs->DAL->getActiveCustomFields( array( 'objtypeid' => ZBS_TYPE_ADDRESS ) ); } // } Addresses if ( is_array( $addrCustomFields ) && count( $addrCustomFields ) > 0 ) { $cfIndx = 1; foreach ( $addrCustomFields as $fieldKey => $field ) { // unpacks csv options and sets 'custom-field' attr $fieldO = zeroBSCRM_customFields_processCustomField( $field ); // } Add it to arr // v2 method $zbsAddressFields['cf'.$cfIndx] = $fieldO; // v3: $zbsAddressFields[ 'addr_' . $fieldKey ] = $fieldO; // } increment ++$cfIndx; // } Also add it to the list of "default sort" at end $zbsFieldSorts['address']['default'][] = 'addr_' . $fieldKey; } } // } Customers $customfields = zeroBSCRM_customFields_applyFieldToGlobal( $customfields, 'customers', 'customer', 'zbsCustomerFields' ); // } Companies $customfields = zeroBSCRM_customFields_applyFieldToGlobal( $customfields, 'companies', 'company', 'zbsCompanyFields' ); // } Quotes $customfields = zeroBSCRM_customFields_applyFieldToGlobal( $customfields, 'quotes', 'quote', 'zbsCustomerQuoteFields' ); // } Invoices $customfields = zeroBSCRM_customFields_applyFieldToGlobal( $customfields, 'invoices', 'invoice', 'zbsCustomerInvoiceFields' ); // } Transactions $customfields = zeroBSCRM_customFields_applyFieldToGlobal( $customfields, 'transactions', 'transaction', 'zbsTransactionFields' ); } // if isset + is array } // this takes the custom fields from DB storage (passed) and translate them into the globals (e.g. $zbsCompanyFields) // ... a lot of the linkages here are DAL1 legacy stuff, probably need rethinking v3+ // $customFields = settings['customfields'] // $key = 'companies' (< DAL2 customFields key) // $keyFieldSorts = 'company' (proper DAL2 key used for field sorts) // $globalVarName = 'zbsCompanyFields' (the global storing the field obj) function zeroBSCRM_customFields_applyFieldToGlobal( $customFields, $key, $keyFieldSorts, $globalVarName ) { if ( ! empty( $globalVarName ) && is_array( $customFields ) && ! empty( $key ) && isset( $customFields[ $key ] ) && is_array( $customFields[ $key ] ) && count( $customFields[ $key ] ) > 0 ) { // globalise, e.g. global $zbsCompanyFields; global $zbs, $zbsFieldSorts; $cfIndx = 1; if ( is_array( $customFields[ $key ] ) ) { foreach ( $customFields[ $key ] as $fieldKey => $field ) { // unpacks csv options and sets 'custom-field' attr $fieldO = zeroBSCRM_customFields_processCustomField( $field ); // } Add it to arr $GLOBALS[ $globalVarName ][ $fieldKey ] = $fieldO; // } increment ++$cfIndx; // } Also add it to the list of "default sort" at end $zbsFieldSorts[ $keyFieldSorts ]['default'][] = $fieldKey; unset( $fieldKey ); } // foreach field } // if custom fields is array } // if issets return $customFields; } // } Retrieves any potential tweaks from options obj function zeroBSCRM_unpackCustomisationsToFields() { global $zbs; $customisedfields = $zbs->settings->get( 'customisedfields' ); $allowedCustomisation = array( 'customers' => array( 'status', 'prefix', ), 'companies' => array( 'status', ), 'quotes' => array(), 'invoices' => array(), 'transactions' => array(), 'addresses' => array(), ); if ( isset( $customisedfields ) && is_array( $customisedfields ) ) { foreach ( $allowedCustomisation as $allowKey => $allowFields ) { if ( is_array( $allowFields ) && count( $allowFields ) ) { foreach ( $allowFields as $field ) { // } Corresponding option? if ( isset( $customisedfields ) && isset( $customisedfields[ $allowKey ] ) && isset( $customisedfields[ $allowKey ][ $field ] ) ) { // } $customisedfields[$allowKey][$field][0] will be (as of yet unused) show/hide flag // } $customisedfields[$allowKey][$field][1] will be new optionval // } option override present :) // } Brutal, needs reworking switch ( $allowKey ) { case 'customers': global $zbsCustomerFields; if ( $field == 'status' && isset( $zbsCustomerFields['status'] ) ) { // } Rebuild options ($arr[3]) $opts = explode( ',', $customisedfields[ $allowKey ][ $field ][1] ); $zbsCustomerFields['status'][3] = $opts; } if ( $field == 'prefix' && isset( $zbsCustomerFields['prefix'] ) ) { // } Rebuild options ($arr[3]) $opts = explode( ',', $customisedfields[ $allowKey ][ $field ][1] ); $zbsCustomerFields['prefix'][3] = $opts; } break; case 'companies': global $zbsCompanyFields; if ( $field == 'status' && isset( $zbsCompanyFields['status'] ) ) { // } Rebuild options ($arr[3]) $opts = explode( ',', $customisedfields[ $allowKey ][ $field ][1] ); $zbsCompanyFields['status'][3] = $opts; } break; case 'quotes': // Nothing yet break; case 'invoices': // Nothing yet break; } } } } } // / foreach } // / isset } // } field sorts function zeroBSCRM_applyFieldSorts() { // } localise global $zbs, $zbsFieldSorts, $zbsCustomerFields, $zbsFieldsEnabled, $zbsCompanyFields, $zbsCustomerQuoteFields, $zbsCustomerInvoiceFields, $zbsFormFields, $zbsAddressFields; // } Work through diff zones + rearrange field arrays // } Does so by: 1) using any overrides stored in "fieldsorts" in settings, then 2) defaults where no overrides $fieldSortOverrides = $zbs->settings->get( 'fieldsorts' ); // quick add: Field hides // no actually, don't do hide at this level... $fieldHideOverrides = $zbs->settings->get('fieldhides'); // } Exclusions $exclusions = array( 'addresses' ); // } ================================================================================= // } Addresses (global) // } ================================================================================= $addressDefaultsPresent = false; if ( isset( $zbsFieldSorts['address'] ) && isset( $zbsFieldSorts['address']['default'] ) && is_array( $zbsFieldSorts['address']['default'] ) && count( $zbsFieldSorts['address']['default'] ) > 0 ) { // } Use defaults or overrides? $addressFieldSortSource = $zbsFieldSorts['address']['default']; // NOTE IN THIS INSTANCE THIS IS USED A LOT BELOW! if ( isset( $fieldSortOverrides['address'] ) && is_array( $fieldSortOverrides['address'] ) && count( $fieldSortOverrides['address'] ) > 0 ) { $addressFieldSortSource = $fieldSortOverrides['address']; } // } new arr $newAddressFieldsArr = array(); // } Cycle through defaults/overrides first... and pull through in correct order foreach ( $addressFieldSortSource as $key ) { // } if exists, add to newcustomerfieldsarr if ( ! in_array( $key, $exclusions ) && isset( $zbsAddressFields[ $key ] ) ) { // } just copy it through $newAddressFieldsArr[ $key ] = $zbsAddressFields[ $key ]; } else { // if doesn't exist, that's weird, or it's an exclusion (address fields are clumped together) // nothing here as in addresses (global) } } // } Then cycle through original obj and add any that got missed by defaults list... foreach ( $zbsAddressFields as $key => $field ) { if ( ! array_key_exists( $key, $newAddressFieldsArr ) ) { // } Add it to the end $newAddressFieldsArr[ $key ] = $field; } } // } Copy over arr :) $zbsAddressFields = $newAddressFieldsArr; $addressDefaultsPresent = true; } // } NOTES ON ADDRESSES: #NOTESONADDRESS /* at this point the addressfields obj is a global "template" for how users want addresses to show up. ... for now we'll just add the fields from here (x2 with second having prefix secaddr_) in place of "addresses" but needs adjustment/refactoring */ // } ================================================================================= // } Customers // } ================================================================================= if ( isset( $zbsFieldSorts['customer'] ) && isset( $zbsFieldSorts['customer']['default'] ) && is_array( $zbsFieldSorts['customer']['default'] ) && count( $zbsFieldSorts['customer']['default'] ) > 0 ) { // } Use defaults or overrides? $customerFieldSortSource = $zbsFieldSorts['customer']['default']; if ( isset( $fieldSortOverrides['customer'] ) && is_array( $fieldSortOverrides['customer'] ) && count( $fieldSortOverrides['customer'] ) > 0 ) { $customerFieldSortSource = $fieldSortOverrides['customer']; } // } new arr $newCustomerFieldsArr = array(); // } Cycle through defaults first... and pull through in correct order foreach ( $customerFieldSortSource as $key ) { // } if exists, add to newcustomerfieldsarr if ( ! in_array( $key, $exclusions ) && isset( $zbsCustomerFields[ $key ] ) ) { // } just copy it through // unless it's a hide! $newCustomerFieldsArr[ $key ] = $zbsCustomerFields[ $key ]; /* no actually, don't do hide at this level... if (isset($fieldHideOverrides['customer']) && is_array($fieldHideOverrides['customer'])){ if (in_array($key, $fieldHideOverrides['customer'])){ // hide } else { // show $newCustomerFieldsArr[$key] = $zbsCustomerFields[$key]; } } */ } else { // if doesn't exist, that's weird, or it's an exclusion (address fields are clumped together) if ( $key == 'addresses' ) { // } Add all fields here for now... not ideal, but okay. // } Uses Address field sort tho :) // } Customers have 2 addresses: if ( $addressDefaultsPresent ) { // } Quick design to use address as template, see #NOTESONADDRESS // } Add addr 1 fields foreach ( $addressFieldSortSource as $addrFieldKey ) { // } If we've left attr on obj (legacy), use that field, otherwise copy a new field in from $zbsAddressFields obj // } e.g. addr1 etc. but if user added cf1 to addresses... // } adadpt key :/ (to stop conflicts from cf1 - this makes this addr_cf1) $adaptedFieldKey = $addrFieldKey; if ( str_starts_with( $addrFieldKey, 'cf' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $adaptedFieldKey = 'addr_' . $addrFieldKey; } if ( isset( $zbsCustomerFields[ $adaptedFieldKey ] ) ) { // } copy it through as next in line $newCustomerFieldsArr[ $adaptedFieldKey ] = $zbsCustomerFields[ $adaptedFieldKey ]; } else { // } copy field inc features, from address fields (as template) // } added 1.1.19: don't copy if not set in zbsaddressfields (modified custom fields) if ( isset( $zbsAddressFields[ $addrFieldKey ] ) ) { $newCustomerFieldsArr[ $adaptedFieldKey ] = $zbsAddressFields[ $addrFieldKey ]; } } // }... and hacky... but .... // } main address objs also need these:,'area'=>'Main Address' if ( ! isset( $newCustomerFieldsArr[ $adaptedFieldKey ]['area'] ) ) { $newCustomerFieldsArr[ $adaptedFieldKey ]['area'] = 'Main Address'; } } $secAddrPrefix = 'sec'; // <DAL3 $secAddrPrefix = 'secaddr_'; // } Add addr 2 fields foreach ( $addressFieldSortSource as $addrFieldKey ) { // } If we've left attr on obj (legacy), use that field, otherwise copy a new field in from $zbsAddressFields obj // } e.g. addr1 etc. but if user added cf1 to addresses... if ( isset( $zbsCustomerFields[ $secAddrPrefix . $addrFieldKey ] ) ) { // } copy it through as next in line $newCustomerFieldsArr[ $secAddrPrefix . $addrFieldKey ] = $zbsCustomerFields[ $secAddrPrefix . $addrFieldKey ]; } else { // } added 1.1.19: don't copy if not set in zbsaddressfields (modified custom fields) if ( isset( $zbsAddressFields[ $addrFieldKey ] ) ) { // } copy field inc features, from address fields (as template) $newCustomerFieldsArr[ $secAddrPrefix . $addrFieldKey ] = $zbsAddressFields[ $addrFieldKey ]; // }... and hacky... but .... // } second address objs also need these:,'area'=>'Second Address','opt'=>'secondaddress' $newCustomerFieldsArr[ $secAddrPrefix . $addrFieldKey ]['area'] = 'Second Address'; $newCustomerFieldsArr[ $secAddrPrefix . $addrFieldKey ]['opt'] = 'secondaddress'; } } } } } } } // } Then cycle through original obj and add any that got missed by defaults list... foreach ( $zbsCustomerFields as $key => $field ) { if ( ! array_key_exists( $key, $newCustomerFieldsArr ) ) { // } Add it to the end $newCustomerFieldsArr[ $key ] = $field; } } // } Copy over arr :) $zbsCustomerFields = $newCustomerFieldsArr; } // } ================================================================================= // } Company // } ================================================================================= if ( isset( $zbsFieldSorts['company'] ) && isset( $zbsFieldSorts['company']['default'] ) && is_array( $zbsFieldSorts['company']['default'] ) && count( $zbsFieldSorts['company']['default'] ) > 0 ) { // } Use defaults or overrides? $companyFieldSortSource = $zbsFieldSorts['company']['default']; if ( isset( $fieldSortOverrides['company'] ) && is_array( $fieldSortOverrides['company'] ) && count( $fieldSortOverrides['company'] ) > 0 ) { $companyFieldSortSource = $fieldSortOverrides['company']; } // } new arr $newCompanyFieldsArr = array(); // } Cycle through defaults first... and pull through in correct order foreach ( $companyFieldSortSource as $key ) { // } if exists, add to newCompanyFieldsArr if ( ! in_array( $key, $exclusions ) && isset( $zbsCompanyFields[ $key ] ) ) { // } just copy it through $newCompanyFieldsArr[ $key ] = $zbsCompanyFields[ $key ]; } else { // if doesn't exist, that's weird, or it's an exclusion (address fields are clumped together) if ( $key == 'addresses' ) { // } Add all fields here for now... not ideal, but okay. // } Uses Address field sort tho :) // } Companies have 2 addresses: if ( $addressDefaultsPresent ) { // } Quick design to use address as template, see #NOTESONADDRESS // } Add addr 1 fields foreach ( $addressFieldSortSource as $addrFieldKey ) { // } If we've left attr on obj (legacy), use that field, otherwise copy a new field in from $zbsAddressFields obj // } e.g. addr1 etc. but if user added cf1 to addresses... // } adadpt key :/ (to stop conflicts from cf1 - this makes this addr_cf1) $adaptedFieldKey = $addrFieldKey; if ( str_starts_with( $addrFieldKey, 'cf' ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $adaptedFieldKey = 'addr_' . $addrFieldKey; } if ( isset( $zbsCompanyFields[ $adaptedFieldKey ] ) ) { // } copy it through as next in line $newCompanyFieldsArr[ $adaptedFieldKey ] = $zbsCompanyFields[ $adaptedFieldKey ]; } else { // } copy field inc features, from address fields (as template) // } added 1.1.19: don't copy if not set in zbsaddressfields (modified custom fields) if ( isset( $zbsAddressFields[ $addrFieldKey ] ) ) { $newCompanyFieldsArr[ $adaptedFieldKey ] = $zbsAddressFields[ $addrFieldKey ]; } } // }... and hacky... but .... // } main address objs also need these:,'area'=>'Main Address' if ( ! isset( $newCompanyFieldsArr[ $adaptedFieldKey ]['area'] ) ) { $newCompanyFieldsArr[ $adaptedFieldKey ]['area'] = 'Main Address'; } } $secAddrPrefix = 'sec'; // <DAL3 $secAddrPrefix = 'secaddr_'; // } Add addr 2 fields foreach ( $addressFieldSortSource as $addrFieldKey ) { // } If we've left attr on obj (legacy), use that field, otherwise copy a new field in from $zbsAddressFields obj // } e.g. addr1 etc. but if user added cf1 to addresses... if ( isset( $zbsCompanyFields[ $secAddrPrefix . $addrFieldKey ] ) ) { // } copy it through as next in line $newCompanyFieldsArr[ $secAddrPrefix . $addrFieldKey ] = $zbsCompanyFields[ $secAddrPrefix . $addrFieldKey ]; } else { // } added 1.1.19: don't copy if not set in zbsaddressfields (modified custom fields) if ( isset( $zbsAddressFields[ $addrFieldKey ] ) ) { // } copy field inc features, from address fields (as template) $newCompanyFieldsArr[ $secAddrPrefix . $addrFieldKey ] = $zbsAddressFields[ $addrFieldKey ]; // }... and hacky... but .... // } second address objs also need these:,'area'=>'Second Address','opt'=>'secondaddress' $newCompanyFieldsArr[ $secAddrPrefix . $addrFieldKey ]['area'] = 'Second Address'; $newCompanyFieldsArr[ $secAddrPrefix . $addrFieldKey ]['opt'] = 'secondaddress'; } } } } } } } // } Then cycle through original obj and add any that got missed by defaults list... foreach ( $zbsCompanyFields as $key => $field ) { if ( ! array_key_exists( $key, $newCompanyFieldsArr ) ) { // } Add it to the end $newCompanyFieldsArr[ $key ] = $field; } } // } Copy over arr :) $zbsCompanyFields = $newCompanyFieldsArr; } // } ================================================================================= // } Quote // } ================================================================================= if ( isset( $zbsFieldSorts['quote'] ) && isset( $zbsFieldSorts['quote']['default'] ) && is_array( $zbsFieldSorts['quote']['default'] ) && count( $zbsFieldSorts['quote']['default'] ) > 0 ) { // } Use defaults or overrides? $quoteFieldSortSource = $zbsFieldSorts['quote']['default']; if ( isset( $fieldSortOverrides['quote'] ) && is_array( $fieldSortOverrides['quote'] ) && count( $fieldSortOverrides['quote'] ) > 0 ) { $quoteFieldSortSource = $fieldSortOverrides['quote']; } // } new arr $newQuoteFieldsArr = array(); // } Cycle through defaults first... and pull through in correct order foreach ( $quoteFieldSortSource as $key ) { // } if exists, add to newQuoteFieldsArr if ( ! in_array( $key, $exclusions ) && isset( $zbsCustomerQuoteFields[ $key ] ) ) { // } just copy it through $newQuoteFieldsArr[ $key ] = $zbsCustomerQuoteFields[ $key ]; } else { // if doesn't exist, that's weird, or it's an exclusion (address fields are clumped together) if ( $key == 'addresses' ) { // } Quotes have none. } } } // } Then cycle through original obj and add any that got missed by defaults list... foreach ( $zbsCustomerQuoteFields as $key => $field ) { if ( ! array_key_exists( $key, $newQuoteFieldsArr ) ) { // } Add it to the end $newQuoteFieldsArr[ $key ] = $field; } } // } Copy over arr :) $zbsCustomerQuoteFields = $newQuoteFieldsArr; } // } ================================================================================= // } Invoice // } ================================================================================= if ( isset( $zbsFieldSorts['invoice'] ) && isset( $zbsFieldSorts['invoice']['default'] ) && is_array( $zbsFieldSorts['invoice']['default'] ) && count( $zbsFieldSorts['invoice']['default'] ) > 0 ) { // } Use defaults or overrides? $invoiceFieldSortSource = $zbsFieldSorts['invoice']['default']; if ( isset( $fieldSortOverrides['invoice'] ) && is_array( $fieldSortOverrides['invoice'] ) && count( $fieldSortOverrides['invoice'] ) > 0 ) { $invoiceFieldSortSource = $fieldSortOverrides['invoice']; } // } new arr $newInvoiceFieldsArr = array(); // } Cycle through defaults first... and pull through in correct order foreach ( $invoiceFieldSortSource as $key ) { // } if exists, add to newInvoiceFieldsArr if ( ! in_array( $key, $exclusions ) && isset( $zbsCustomerInvoiceFields[ $key ] ) ) { // } just copy it through $newInvoiceFieldsArr[ $key ] = $zbsCustomerInvoiceFields[ $key ]; } else { // if doesn't exist, that's weird, or it's an exclusion (address fields are clumped together) if ( $key == 'addresses' ) { // } Invs have none. } } } // } Then cycle through original obj and add any that got missed by defaults list... foreach ( $zbsCustomerInvoiceFields as $key => $field ) { if ( ! array_key_exists( $key, $newInvoiceFieldsArr ) ) { // } Add it to the end $newInvoiceFieldsArr[ $key ] = $field; } } // } Copy over arr :) $zbsCustomerInvoiceFields = $newInvoiceFieldsArr; } // } ================================================================================= // } Forms // } ================================================================================= if ( isset( $zbsFieldSorts['form'] ) && isset( $zbsFieldSorts['form']['default'] ) && is_array( $zbsFieldSorts['form']['default'] ) && count( $zbsFieldSorts['form']['default'] ) > 0 ) { // } Use defaults or overrides? $formFieldSortSource = $zbsFieldSorts['form']['default']; if ( isset( $fieldSortOverrides['form'] ) && is_array( $fieldSortOverrides['form'] ) && count( $fieldSortOverrides['form'] ) > 0 ) { $formFieldSortSource = $fieldSortOverrides['form']; } // } new arr $newFormFieldsArr = array(); // } Cycle through defaults first... and pull through in correct order foreach ( $formFieldSortSource as $key ) { // } if exists, add to newFormFieldsArr if ( ! in_array( $key, $exclusions ) && isset( $zbsFormFields[ $key ] ) ) { // } just copy it through $newFormFieldsArr[ $key ] = $zbsFormFields[ $key ]; } else { // if doesn't exist, that's weird, or it's an exclusion (address fields are clumped together) if ( $key == 'addresses' ) { // } Invs have none. } } } // } Then cycle through original obj and add any that got missed by defaults list... foreach ( $zbsFormFields as $key => $field ) { if ( ! array_key_exists( $key, $newFormFieldsArr ) ) { // } Add it to the end $newFormFieldsArr[ $key ] = $field; } } // } Copy over arr :) $zbsFormFields = $newFormFieldsArr; } } /* ====================================================== / Field & Sort Functions ====================================================== */ /* ====================================================== Field Helper funcs ====================================================== */ // mikes, WH took from automations v0.1 // from Export file and customer meta .. functionised.. function zeroBSCRM_customerFields_select( $form_id, $form_name ) { global $zbsCustomerFields; $fields = $zbsCustomerFields; $useSecondAddr = zeroBSCRM_getSetting( 'secondaddress' ); global $zbsFieldsEnabled; if ( $useSecondAddr == '1' ) { $zbsFieldsEnabled['secondaddress'] = true; } $output = "<select id='" . $form_id . "' name='" . $form_name . "'>"; foreach ( $fields as $fieldK => $fieldV ) { $showField = true; // } Check if not hard-hidden by opt override (on off for second address, mostly) if ( isset( $fieldV['opt'] ) && ( ! isset( $zbsFieldsEnabled[ $fieldV['opt'] ] ) || ! $zbsFieldsEnabled[ $fieldV['opt'] ] ) ) { $showField = false; } // or is hidden by checkbox? if ( isset( $fieldHideOverrides['company'] ) && is_array( $fieldHideOverrides['company'] ) ) { if ( in_array( $fieldK, $fieldHideOverrides['company'] ) ) { $showField = false; } } // } If show... if ( $showField ) { $output .= '<option value="' . $fieldK . '" /> ' . $fieldV[1] . '<br />'; } // } / if show } $output .= '</select>'; return $output; } // WH: Made simple "get customer fields array simple" for mc2 function zeroBSCRM_customerFields_getSimpleArr() { // taken mostly from the customer metabox global $zeroBSCRM_Settings; // Get field Hides... $fieldHideOverrides = $zeroBSCRM_Settings->get( 'fieldhides' ); global $zbsCustomerFields; $fields = $zbsCustomerFields; // } Using second address? $useSecondAddr = zeroBSCRM_getSetting( 'secondaddress' ); $showCountries = zeroBSCRM_getSetting( 'countries' ); // } Hiding address inputs? $showAddr = zeroBSCRM_getSetting( 'showaddress' ); // code to build arr $retArr = array(); // } This global holds "enabled/disabled" for specific fields... ignore unless you're WH or ask global $zbsFieldsEnabled; if ( $useSecondAddr == '1' ) { $zbsFieldsEnabled['secondaddress'] = true; } // } This is the grouping :) $zbsFieldGroup = ''; $zbsOpenGroup = false; foreach ( $fields as $fieldK => $fieldV ) { $showField = true; // } Check if not hard-hidden by opt override (on off for second address, mostly) if ( isset( $fieldV['opt'] ) && ( ! isset( $zbsFieldsEnabled[ $fieldV['opt'] ] ) || ! $zbsFieldsEnabled[ $fieldV['opt'] ] ) ) { $showField = false; } // or is hidden by checkbox? if ( isset( $fieldHideOverrides['customer'] ) && is_array( $fieldHideOverrides['customer'] ) ) { if ( in_array( $fieldK, $fieldHideOverrides['customer'] ) ) { $showField = false; } } // if show field :) add if ( $showField ) { $retArr[ $fieldK ] = $fieldV; } } return $retArr; } // builds a detail array from post from form // the SAVE end to zeroBSCRM_html_editFields // centralisd/genericified 20/7/18 wh 2.91+ // WH NOTE: This should be replaced/merged with buildObjArr function zeroBSCRM_save_fields( $fieldArr = array(), $postKey = 'zbscq_', $skipFields = array() ) { $res = array(); foreach ( $fieldArr as $fK => $fV ) { $res[ $fK ] = ''; if ( isset( $_POST[ $postKey . $fK ] ) ) { switch ( $fV[0] ) { case 'tel': // validate tel? $res[ $fK ] = sanitize_text_field( $_POST[ $postKey . $fK ] ); preg_replace( '/[^0-9 ]/', '', $res[ $fK ] ); break; case 'price': case 'numberfloat': // validate price/float? $res[ $fK ] = sanitize_text_field( $_POST[ $postKey . $fK ] ); $res[ $fK ] = preg_replace( '@[^0-9\.]+@i', '-', $res[ $fK ] ); $res[ $fK ] = floatval( $res[ $fK ] ); break; case 'numberint': // validate price? $res[ $fK ] = sanitize_text_field( $_POST[ $postKey . $fK ] ); $res[ $fK ] = preg_replace( '@[^0-9]+@i', '-', $res[ $fK ] ); $res[ $fK ] = floatval( $res[ $fK ] ); break; case 'textarea': $res[ $fK ] = zeroBSCRM_textProcess( $_POST[ $postKey . $fK ] ); break; default: $res[ $fK ] = sanitize_text_field( $_POST[ $postKey . $fK ] ); break; } } } return $res; } /* zeroBSCRM_customFields_getSlugOrCreate This function will get the slug for a custom field, based on a label, if it exists ... if it doesn't exist, it'll add it as a default text field type params: $objectTypeStr='customers' | customersfiles | quotes | companies etc. $fieldLabel='Promotion URL' - NOTE: only tested with 'customers' type - debug with others before production use NOTE: Not sure how early in the load-stack you can successfully use this.. to be tested NOTE: All custom field stuff should be centralised/refactored, this has got messy */ function zeroBSCRM_customFields_getSlugOrCreate( $fieldLabel = '', $objectTypeStr = 'customers' ) { // taken from admin pages custom fields: // standard custom fields processing (not files/any that need special treatment) // genericified 20/07/19 2.91 $customFieldsToProcess = array( 'addresses' => 'zbsAddressFields', 'customers' => 'zbsCustomerFields', 'companies' => 'zbsCompanyFields', 'quotes' => 'zbsCustomerQuoteFields', 'transactions' => 'zbsTransactionFields', ); // acceptable types $acceptableCFTypes = zeroBSCRM_customfields_acceptableCFTypes(); // block ID here too if ( ! empty( $fieldLabel ) && ! empty( $objectTypeStr ) && $fieldLabel != 'ID' && isset( $customFieldsToProcess[ $objectTypeStr ] ) ) { global $wDB,$zbs; $customFieldsArr = $zbs->settings->get( 'customfields' ); if ( ( isset( $customFieldsArr[ $objectTypeStr ] ) && ! is_array( $customFieldsArr[ $objectTypeStr ] ) ) || ( ! isset( $customFieldsArr[ $objectTypeStr ] ) ) ) { // set it (no real risk here, except for slap-handed-typos in $objectTypeStr) $customFieldsArr[ $objectTypeStr ] = array(); } // make slug $possSlug = $zbs->DAL->makeSlug( $fieldLabel ); // block ID here too if ( $possSlug !== 'id' ) { // ====== TAKEN from adminpages custom fields saving // ... and modified a bit $globalVarName = $customFieldsToProcess[ $objectTypeStr ]; // 2.96.7+ CHECK against existing fields + add -1 -2 etc. if already in there // if exists, just return it :) if ( isset( $GLOBALS[ $globalVarName ][ $possSlug ] ) ) { return $possSlug; } else { // doesn't exist, so add :) // make default vars $possType = 'text'; $possName = $fieldLabel; $possPlaceholder = ''; if ( in_array( $possType, $acceptableCFTypes ) ) { // } Add it $customFieldsArr[ $objectTypeStr ][] = array( $possType, $possName, $possPlaceholder, $possSlug ); // NOW SAVE DOWN // update DAL 2 custom fields :) if ( $zbs->isDAL2() ) { if ( isset( $customFieldsArr['customers'] ) && is_array( $customFieldsArr['customers'] ) ) { // slight array reconfig $db2CustomFields = array(); foreach ( $customFieldsArr['customers'] as $cfArr ) { $db2CustomFields[ $zbs->DAL->makeSlug( $cfArr[1] ) ] = $cfArr; } // simple maintain DAL2 (needs to also) $zbs->DAL->updateActiveCustomFields( array( 'objtypeid' => 1, 'fields' => $db2CustomFields, ) ); } } // } Brutal update $zbs->settings->update( 'customfields', $customFieldsArr ); // update the fields/sorts so is reloaded in zeroBSCRM_applyFieldSorts(); return $possSlug; } } } // / is id } return false; } function zeroBSCRM_customfields_acceptableCFTypes() { return array( // all avail pre 2.98.5 'text', 'textarea', 'date', 'select', 'tel', 'price', 'numberfloat', 'numberint', 'email', // 2.98.5 'radio', 'checkbox', 'autonumber', // Removed encrypted (for now), see JIRA-ZBS-738 // 'encrypted' ); } // takes Strings from autonumber settings for prefix/suffix and parses some common replacements: function zeroBSCRM_customFields_parseAutoNumberStr( $str = '' ) { global $zbs; // CURRENT DATE (on creation): // YYYY = 2019 // YY = 19 // MMMM = 01 - 12 // MM = Jan - Dec // MONTH = January - December // WW = 01 - 52 // DD = 01 - 31 // DOY = 01 - 365 // AGENT who's editing (on creation): // USEREMAIL = woody@gmail.com // USERID = 1 // USERNAME = woodyhayday // USERINITIALS = WH // USERFULLNAME = Woody Hayday // USERFIRSTNAME = Woody // USERLASTNAME = Hayday $x = str_replace( 'YYYY', date( 'Y' ), $str ); $x = str_replace( 'YY', date( 'y' ), $x ); $x = str_replace( 'MMMM', date( 'm' ), $x ); $x = str_replace( 'MM', date( 'M' ), $x ); $x = str_replace( 'MONTH', date( 'F' ), $x ); $x = str_replace( 'WW', date( 'W' ), $x ); $x = str_replace( 'DD', date( 'd' ), $x ); $x = str_replace( 'DOY', date( 'z' ), $x ); // User Prefix $userID = $zbs->user(); if ( $userID > 0 ) { $user_info = get_userdata( $zbs->user() ); $x = str_replace( 'USEREMAIL', $user_info->user_email, $x ); $x = str_replace( 'USERID', $userID, $x ); $x = str_replace( 'USERNAME', $user_info->user_login, $x ); $initials = ''; if ( isset( $user_info->first_name ) && ! empty( $user_info->first_name ) ) { $initials .= substr( trim( $user_info->first_name ), 0, 1 ); } if ( isset( $user_info->last_name ) && ! empty( $user_info->last_name ) ) { $initials .= substr( trim( $user_info->last_name ), 0, 1 ); } $x = str_replace( 'USERINITIALS', strtoupper( $initials ), $x ); $x = str_replace( 'USERFULLNAME', $user_info->first_name . ' ' . $user_info->last_name, $x ); $x = str_replace( 'USERFIRSTNAME', $user_info->first_name, $x ); $x = str_replace( 'USERLASTNAME', $user_info->last_name, $x ); } else { // replace for those where no username etc. (API) $x = str_replace( 'USEREMAIL', '', $x ); $x = str_replace( 'USERID', '', $x ); $x = str_replace( 'USERNAME', '', $x ); $x = str_replace( 'USERINITIALS', '', $x ); $x = str_replace( 'USERFULLNAME', '', $x ); $x = str_replace( 'USERFIRSTNAME', '', $x ); $x = str_replace( 'USERLASTNAME', '', $x ); } return $x; } // retrieves a number from current custom field setting (autonumber) // ... returns it + ups the number in the custom field setting // this may be called several times if updating many, but tiny unperformant bit should be worth it // ... for the safety of double checking function zeroBSCRM_customFields_getAutoNumber( $objTypeID = -1, $fK = '' ) { global $zbs; // needs at least this if ( ! $zbs->isDAL2() ) { return false; } // def $return = false; // see if exists (get custom fields for obj) $customFields = $zbs->DAL->getActiveCustomFields( array( 'objtypeid' => $objTypeID ) ); // we have to do this in a way which feels very dangerous. // we take the custom field setting to bits and rebuild with incremented autonumber. // these should be moved to their own safer system/table, I think. v3.1? if ( is_array( $customFields ) && count( $customFields ) > 0 ) { // this'll be replaced by all array items, with the autonumber upped, all being well // legacy pain. $newCustomFields = array(); $changed = false; // eeeeish these aren't even array keyed. legacy pain. foreach ( $customFields as $f ) { $added = false; // f3 = slug if ( is_array( $f ) && isset( $f[3] ) && $f[3] == $fK && $f[0] == 'autonumber' ) { // this is our autonumber. // split it $autonumber = explode( '#', $f[2] ); if ( count( $autonumber ) == 3 ) { // all seems well, will be prefix,number,suffix $no = (int) trim( $autonumber[1] ); if ( $no > -1 ) { // great, got a number of at least 0 // set return $return = $no; // increment ++$no; // add back in, with incremented autonumber $newCustomField = $f; $newCustomField[2] = $autonumber[0] . '#' . $no . '#' . $autonumber[2]; $newCustomFields[] = $newCustomField; $added = true; $changed = true; } } } // not added by above? if ( ! $added ) { // just make sure still in array $newCustomFields[] = $f; } } // save down (if changed) if ( $changed ) { if ( is_array( $newCustomFields ) ) { // slight array reconfig $db2CustomFields = array(); foreach ( $newCustomFields as $cfArr ) { $db2CustomFields[ $zbs->DAL->makeSlug( $cfArr[1] ) ] = $cfArr; } // simple maintain DAL2 (needs to also) $zbs->DAL->updateActiveCustomFields( array( 'objtypeid' => $objTypeID, 'fields' => $db2CustomFields, ) ); } } } // / if custom fields return $return; } // unpacks csv options and sets 'custom-field' attr // (used in several places so unifying) function zeroBSCRM_customFields_processCustomField( $fieldOrig = false ) { // split $fieldO = $fieldOrig; if ( is_array( $fieldO ) ) { // } unpack csv if ( $fieldO[0] == 'select' || $fieldO[0] == 'checkbox' || $fieldO[0] == 'radio' ) { // } Legacy shiz? needed post dal2? // } This gives empty placeholder and exploded original str if ( isset( $fieldO[3] ) && ! is_array( $fieldO[3] ) ) { $fieldO[2] = ''; $fieldO[3] = explode( ',', $fieldOrig[2] ); } } // here we set a flag that defines them as custom fields $fieldO['custom-field'] = true; return $fieldO; } return false; } /* example: getActiveCustomFields "customers": [ ["text", "filename", "Filename", "filename"], ["date", "dddd", "", "dddd"], ["select", "selecter", "a,b,c", "selecter"], ["radio", "radioz", "rad1,rad2,rad3,rad4,rad5,rad6,rad7,rad89,another option,andmore,and this,oh and don\\'t forget", "radioz"], ["checkbox", "check boz", "checkbox,afeafhte,another check,last one!", "check-boz"], ["autonumber", "autonumbz", "zzAAAX#12343#zzXXXX", "autonumbz"], ["numberint", "forced numeric", "999", "forced-numeric"], ["radio", "empty radio", "", "empty-radio"], ["checkbox", "empty check", "", "empty-check"], ["select", "empty select", "", "empty-select"] ], */ /* ====================================================== / Field Helper funcs ====================================================== */