filename
stringlengths
11
137
content
stringlengths
6
292k
projects/plugins/crm/modules/mailpoet/includes/class-mailpoet-segment-conditions.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * MailPoet: Segment Conditions * */ namespace Automattic\JetpackCRM; // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; /** * MailPoet Segment Conditions class */ class Mailpoet_Segment_Conditions { /** * An array of our segment condition class instances */ public $conditions = array(); /** * The single instance of the class. */ protected static $_instance = null; /** * Setup Segment conditions */ public function __construct( ) { // Require segment conditions when jpcrm is ready add_action( 'jpcrm_post_init', array( $this, 'require_segment_conditions'), 1 ); } /** * Main Class Instance. * * Ensures only one instance of Mailpoet_Segment_Conditions is loaded or can be loaded. * * @since 2.0 * @static * @see * @return Mailpoet_Segment_Conditions main instance */ public static function instance() { if ( is_null( self::$_instance ) ) { self::$_instance = new self(); } return self::$_instance; } /** * Require segment conditions */ public function require_segment_conditions(){ // is mailpoet subscriber require_once( JPCRM_MAILPOET_ROOT_PATH . 'includes/segment-conditions/class-segment-condition-mailpoet-subscriber.php' ); $this->conditions['is_mailpoet_customer'] = new \Segment_Condition_Mailpoet_Subscriber(); } }
projects/plugins/crm/modules/mailpoet/includes/class-mailpoet-background-sync.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * MailPoet Sync: Background Sync * */ namespace Automattic\JetpackCRM; // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; /** * MailPoet Background Sync class */ class Mailpoet_Background_Sync { /** * If set to true this will echo progress of a sync job. */ public $debug = false; /** * Future proofing multi-connections */ public $mode = JPCRM_MAILPOET_MODE_LOCAL; /** * The single instance of the class. */ protected static $_instance = null; /** * Setup MailPoet Background Sync */ public function __construct( ) { // load job class require_once JPCRM_MAILPOET_ROOT_PATH. 'includes/class-mailpoet-background-sync-job.php'; // Initialise Hooks $this->init_hooks(); // Schedule cron $this->schedule_cron(); } /** * Main Class Instance. * * Ensures only one instance of Mailpoet_Background_Sync is loaded or can be loaded. * * @since 2.0 * @static * @see * @return Mailpoet_Background_Sync main instance */ public static function instance() { if ( is_null( self::$_instance ) ) { self::$_instance = new self(); } return self::$_instance; } /** * Returns main class instance */ public function mailpoet(){ global $zbs; return $zbs->modules->mailpoet; } /** * If $this->debug is true, outputs passed string * * @param string - Debug string */ private function debug( $str ){ if ( $this->debug ){ echo '[' . zeroBSCRM_locale_utsToDatetime( time() ) . '] ' . $str . '<br>'; } } /** * Initialise Hooks */ private function init_hooks( ) { // cron add_action( 'jpcrm_mailpoet_sync', array( $this, 'cron_job' ) ); // Syncing based on MailPoet hooks: // Subscriber edits/changes: add_action( 'mailpoet_subscriber_created', array( $this, 'add_update_subscriber_by_id' ), 1, 1 ); add_action( 'mailpoet_subscriber_updated', array( $this, 'add_update_subscriber_by_id' ), 1, 1 ); add_action( 'mailpoet_subscriber_deleted', array( $this, 'delete_subscriber_by_id' ), 1, 1 ); add_action( 'mailpoet_multiple_subscribers_created', array( $this, 'add_update_subscribers_by_id' ), 1, 1 ); add_action( 'mailpoet_multiple_subscribers_updated', array( $this, 'add_update_subscribers_by_id' ), 1, 1 ); add_action( 'mailpoet_multiple_subscribers_deleted', array( $this, 'delete_subscribers_by_id' ), 1, 1 ); // add our cron task to the core crm cron monitor list add_filter( 'jpcrm_cron_to_monitor', array( $this, 'add_cron_monitor' ) ); } /** * Setup cron schedule */ private function schedule_cron( ) { // schedule it if ( ! wp_next_scheduled( 'jpcrm_mailpoet_sync' ) ) { wp_schedule_event( time(), '5min', 'jpcrm_mailpoet_sync' ); } } /** * Run cron job */ public function cron_job(){ // define global to mark this as a cron call define( 'jpcrm_mailpoet_cron_running', 1 ); // fire job $this->sync_subscribers(); } /** * Returns bool as to whether or not the current call was made via cron */ private function is_cron(){ return defined( 'jpcrm_mailpoet_cron_running' ); } /** * Filter call to add the cron zbssendbot to the watcher system * * @param array $crons * @return array */ function add_cron_monitor( $crons ) { if ( is_array( $crons ) ) { $crons[ 'jpcrm_mailpoet_sync' ] = '5min'; } return $crons; } /** * Main job function: this will retrieve and import subscribers from MailPoet * This can be called in three 'modes' * - via cron (as defined by `jpcrm_mailpoet_cron_running`) * - via AJAX (if not via cron and not in debug mode) * - for debug (if $this->debug is set) This is designed to be called inline and will output progress of sync job * * @param bool $silent - if true no output will be returned (for use where we call after `add_update_subscribers_by_id()`) * * @return mixed (int|json) * - if cron originated: a count of orers imported is returned * - if not cron originated (assumes AJAX): * - if completed sync: JSON summary info is output and then exit() is called * - else count of subscribers imported is returned */ public function sync_subscribers( $silent = false ){ global $zbs; $this->debug( 'Fired `sync_subscribers()`.' ); // check not currently running if ( defined( 'jpcrm_mailpoet_running' ) ) { $this->debug( 'Attempted to run `sync_subscribers()` when job already in progress.' ); // return blocker error return array( 'status' => 'job_in_progress' ); } $this->debug( 'Commencing syncing...' ); // prep silos $total_remaining_pages = 0; $total_pages = 0; $errors = array(); $subscribers_synced = 0; // blocker if ( !defined( 'jpcrm_mailpoet_running' ) ) { define( 'jpcrm_mailpoet_running', 1 ); } // init class $sync_job = new Mailpoet_Background_Sync_Job( $this->debug ); // start sync job $sync_result = $sync_job->run_sync(); $this->debug( 'Sync Result:<pre>' . print_r( $sync_result, 1 ) . '</pre>' ); /* will be false or array( 'total_pages' => $total_pages, 'total_remaining_pages' => $total_remaining_pages, 'errors' => $errors, );*/ if ( is_array( $sync_result ) && isset( $sync_result['total_pages'] ) && isset( $sync_result['total_remaining_pages'] ) ){ // maintain overall % counts later used to provide a summary % across sync site connections $total_pages += (int)$sync_result['total_pages']; $total_remaining_pages += $sync_result['total_remaining_pages']; $subscribers_synced = (int)$sync_result['subscribers_synced']; } // discern completeness // either maxxed pages, or more likely x no = y no if ( $total_remaining_pages == 0 || $this->mailpoet()->get_all_mailpoet_subscribers_count() <= $this->mailpoet()->get_crm_mailpoet_contact_count() ){ $sync_status = 'sync_completed'; $overall_percentage = 100; $status_short_text = __( 'Sync Completed', 'zero-bs-crm' ); $status_long_text = __( 'MailPoet Sync has imported all existing subscribers and will continue to import future subscribers.', 'zero-bs-crm' ); } else { $sync_status = 'sync_part_complete'; $overall_percentage = (int)( ( $total_pages - $total_remaining_pages ) / $total_pages * 100 ); $status_short_text = __( 'Syncing subscribers from MailPoet...', 'zero-bs-crm' ); $status_long_text = ''; } // if cron, we just return count if ( $this->is_cron() || $silent ) { return array( 'status' => $sync_status, // sync_completed sync_part_complete job_in_progress error 'status_short_text' => $status_short_text, 'percentage_completed' => $overall_percentage, ); } else { $this->debug( 'Completed Subscriber Sync Job: ' . $sync_status ); $mailpoetsync_status_array = array( 'status' => $sync_status, 'status_short_text' => $status_short_text, 'status_long_text' => $status_long_text, 'page_no' => ( $total_pages - $total_remaining_pages ), 'subscribers_synced' => $subscribers_synced, 'percentage_completed' => $overall_percentage, 'total_crm_contacts_from_mailpoet' => $this->mailpoet()->get_crm_mailpoet_contact_count() ); $mailpoet_latest_stats = $this->mailpoet()->get_jpcrm_mailpoet_latest_stats(); echo json_encode( array_merge( $mailpoet_latest_stats, $mailpoetsync_status_array ) ); exit(); } } /** * Set's a completion status for MailPoet Subscriber imports * * @param string|bool $status = 'yes|no' (#legacy) or 'true|false' * * @return bool $status */ public function set_first_import_status( $status ){ $status_bool = false; if ( $status == 'yes' || $status === true ){ $status_bool = true; } // set it $this->mailpoet()->settings->update( 'first_import_complete', $status_bool ); return $status_bool; } /** * Returns a completion status for MailPoet Subscriber imports * * @return bool $status */ public function first_import_completed(){ $status_bool = false; // get $first_import_complete = $this->mailpoet()->settings->get( 'first_import_complete', false ); if ( $first_import_complete == 'yes' || $first_import_complete === true || $first_import_complete == 1 ){ $status_bool = true; } return $status_bool; } /** * Sets current working page index (to resume from) * * @return int $page */ public function set_resume_from_page( $page_no ){ $this->mailpoet()->settings->update( 'resume_from_page', $page_no ); return $page_no; } /** * Return current working page index (to resume from) * * @return int $page */ public function resume_from_page(){ return $this->mailpoet()->settings->get( 'resume_from_page', 0 ); } /** * Returns 'local' or 'api' * (whichever mode is selected in settings) */ public function import_mode( $str_mode = false ){ // import mode $mode = (int)$this->mode; // debug/string mode if ( $str_mode ) { if ( $mode === 0 ) { return 'JPCRM_MAILPOET_MODE_LOCAL'; } else { return 'JPCRM_MAILPOET_MODE_API'; } } return $mode; } /** * Add or Update subscriber * Fired by hooks: mailpoet_subscriber_created, mailpoet_subscriber_updated, mailpoet_subscriber_deleted * Changes caught here: * - first, last names * - email * - doens't seem to fire on: change of newsletter, change of tags */ public function add_update_subscriber_by_id( int $subscriberId ){ global $zbs; // should we log changes via contact note? $autolog_changes = $this->mailpoet()->settings->get( 'autolog_changes', false ); // retrieve records $potential_subscriber = $this->mailpoet()->get_mailpoet_subscriber_by_subscriber_id( $subscriberId ); $potential_contact = $zbs->DAL->contacts->getContact( -1, array( 'externalSource' => 'mailpoet', 'externalSourceUID' => $subscriberId, )); // got records? if ( is_array( $potential_subscriber ) && isset( $potential_subscriber['email'] ) ){ // Update: if ( is_array( $potential_contact ) && isset( $potential_contact['id'] ) ){ // note changes $previous_data = $potential_contact; $contact_changes = array(); // email (will always be the same until https://github.com/Automattic/zero-bs-crm/issues/2565) // ... in fact this next block is defunct as it stands because getSubscriber above gets the subscriber // ... AFTER email change. if ( $potential_subscriber['email'] != $potential_contact['email'] ){ $contact_changes['email'] = $potential_subscriber->data->email; // if email changed, add old as an alias // for that we need the old alias list to append to $contact_aliases = is_array( $potential_contact['aliases'] ) ? $potential_contact['aliases'] : array(); if ( !in_array( $previous_data['email'], $contact_aliases ) ){ $contact_aliases[] = $previous_data['email']; } } // first name if ( $potential_subscriber['first_name'] != $potential_contact['fname'] ){ $contact_changes['fname'] = $potential_subscriber['first_name']; } // last name if ( $potential_subscriber['last_name'] != $potential_contact['lname'] ){ $contact_changes['lname'] = $potential_subscriber['last_name']; } // enact changes if ( count( $contact_changes ) > 0 ){ // we split this into field + contact_aliases changes, because then we can use limitedFields support // build limited fields: $contact_changes_as_limited_fields = array(); foreach ( $contact_changes as $key => $value ){ $contact_changes_as_limited_fields[] = array( 'key' => 'zbsc_' . $key, 'val' => $value, 'type' => '%s' // all are strings here ); } // enact $zbs->DAL->contacts->addUpdateContact( array( 'id' => $potential_contact['id'], 'limitedFields' => $contact_changes_as_limited_fields )); // any aliases to add? if ( isset( $contact_aliases ) && count( $contact_aliases ) ){ foreach ( $contact_aliases as $alias ){ zeroBS_addObjAlias( ZBS_TYPE_CONTACT, $potential_contact['id'], $alias ); } } // do we add logs? if ( $autolog_changes == "1" ){ // build log $object_change_str = ''; if ( isset( $contact_changes['email'] ) ){ $object_change_str .= sprintf ( '%s: <code>%s</code> → <code>%s</code><br>', __( 'Email', 'zero-bs-crm' ), $previous_data['email'], $contact_changes['email'] ); } if ( isset( $contact_changes['fname'] ) ){ $object_change_str .= sprintf ( '%s: <code>%s</code> → <code>%s</code><br>', __( 'First name', 'zero-bs-crm' ), $previous_data['fname'], $contact_changes['fname'] ); } if ( isset( $contact_changes['lname'] ) ){ $object_change_str .= sprintf ( '%s: <code>%s</code> → <code>%s</code><br>', __( 'Last name', 'zero-bs-crm' ), $previous_data['lname'], $contact_changes['lname'] ); } // add log if ( !empty( $object_change_str ) ){ zeroBS_addUpdateLog( $potential_contact['id'], -1, -1, array( 'type' => __( 'Contact Changed via MailPoet', 'zero-bs-crm' ), 'shortdesc' => __( 'Contact details changed via connected MailPoet subscriber', 'zero-bs-crm' ), 'longdesc' => $object_change_str, ), 'zerobs_customer' ); } } } return; } else { // New addition // Note we can't act on this hook because currently the only thing passed is the // MailPoet ID, from which the user can't currently (via MailPoet API) be retrieved // ... so when they add that we can use $this->mailpoet()->get_mailpoet_subscriber_by_subscriber_id // in it's real sense and write logic here to import the addition. // For now we hack around this below using their GetSubscribers endpoint with a filter of `minUpdatedAt` // ... though that's not a sure bet by any means. // see #temporary-workaround // gh-2565 } } // Temporary workaround for lack of accessibility to getSubscriberByID in MP API // in the instance of newly added subs // #temporary-workaround // Attempts to grab the last inserted sub. This will be hit and miss, but will work smoothly for // small, infrequently updated lists $last_updated_guess_timestamp = time() + jpcrm_get_wp_timezone_offset_in_seconds() - 1; $potential_subscribers = $this->mailpoet()->get_mailpoet_subscribers( false, false, $last_updated_guess_timestamp, 1, 0, false, true, true ); if ( is_array( $potential_subscribers ) && count( $potential_subscribers ) > 0 ){ // push this sub through our sync import function: // init class $sync_job = new Mailpoet_Background_Sync_Job( false ); $sync_job->import_subscriber( $potential_subscribers[0] ); } } /** * Delete subscriber * Fired by hooks: mailpoet_subscriber_created, mailpoet_subscriber_updated, mailpoet_subscriber_deleted */ public function delete_subscriber_by_id( int $subscriberId ){ global $zbs; // what's the delete action? $delete_action = $this->mailpoet()->settings->get( 'delete_action', 'none' ); // shall we delete the related crm contact? if ( $delete_action == 'delete' || $delete_action == 'delete_save_related_objects' ){ // retrieve record $potential_contact_id = $zbs->DAL->contacts->getContact( -1, array( 'externalSource' => 'mailpoet', 'externalSourceUID' => $subscriberId, 'onlyID' => true, )); // got record? if ( $potential_contact_id ){ $save_orphans = false; if ( $delete_action == 'delete_save_related_objects' ) { $save_orphans = true; } // delete the contact $zbs->DAL->contacts->deleteContact( array( 'id' => $potential_contact_id, 'saveOrphans' => $save_orphans, )); } } elseif ( $delete_action == 'add_note' ) { // if it was deleted in MailPoet but user has 'add_note' selected as delete action, we add a log to contact // retrieve record $potential_contact_id = $zbs->DAL->contacts->getContact( -1, array( 'externalSource' => 'mailpoet', 'externalSourceUID' => $subscriberId, 'onlyID' => true, )); // got record? if ( $potential_contact_id ){ zeroBS_addUpdateLog( $potential_contact_id, -1, -1, array( 'type' => __( 'Subscriber deleted in MailPoet', 'zero-bs-crm' ), 'shortdesc' => __( 'Associated MailPoet subscriber was deleted in MailPoet', 'zero-bs-crm' ), 'longdesc' => '' ), 'zerobs_customer' ); } } // if we're not deleting the contact, we need to remove the external source record // for the contact, because there's no link any more. // ... actually if we leave it in tact it still records useful info (the fact the source was MP) } /** * Add or Update subscribers * Fired by hooks: mailpoet_multiple_subscribers_created, mailpoet_multiple_subscribers_updated */ public function add_update_subscribers_by_id( int $minActionTimestamp ){ // catch these via sync $this->sync_subscribers( true ); } /** * Delete subscribers * Fired by hook: mailpoet_multiple_subscribers_deleted */ public function delete_subscribers_by_id( array $subscriberIds ){ // here we rely on our other function `delete_subscriber_by_id()` // which has all of the settings-based delete actions if ( count( $subscriberIds ) > 0 ){ foreach ( $subscriberIds as $subscriber_id ){ $this->delete_subscriber_by_id( $subscriber_id ); } } } }
projects/plugins/crm/modules/mailpoet/includes/segment-conditions/class-segment-condition-mailpoet-subscriber.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * MailPoet Sync: Segment Condition: Is MailPoet Subscriber * */ // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; /** * MailPoet Sync: Segment Condition: Is MailPoet Subscriber class */ class Segment_Condition_Mailpoet_Subscriber extends zeroBSCRM_segmentCondition { public $key = 'imported_mailpoet_subscriber'; public $condition = array( 'category' => 'MailPoet', 'priority' => 1, 'operators' => array( 'istrue', 'isfalse' ), 'fieldname' =>'imported_mailpoet_subscriber' ); /** * init, here just used to set translated attributes. */ public function __construct( $constructionArgs = array() ) { // set translations $this->condition['name'] = __( 'Imported from MailPoet', 'zero-bs-crm' ); $this->condition['description'] = __( 'Select contacts which were imported from MailPoet via MailPoet Sync', 'zero-bs-crm' ); // fire main class init $this->init( $constructionArgs ); } public function conditionArg( $startingArg=false, $condition=false, $conditionKeySuffix=false ){ global $zbs, $ZBSCRM_t; if ( $condition['operator'] == 'istrue' ) return array('additionalWhereArr'=> array( 'is_mailpoet_subscriber' . $conditionKeySuffix => array( 'ID','IN', '(SELECT DISTINCT zbss_objid FROM ' . $ZBSCRM_t['externalsources'] . " WHERE zbss_objtype = ".ZBS_TYPE_CONTACT." AND zbss_source = %s)", array( 'mailpoet' ) ) ) ); if ( $condition['operator'] == 'isfalse' ) return array('additionalWhereArr'=> array( 'is_mailpoet_subscriber' . $conditionKeySuffix => array( 'ID','NOT IN', '(SELECT DISTINCT zbss_objid FROM ' . $ZBSCRM_t['externalsources'] . " WHERE zbss_objtype = ".ZBS_TYPE_CONTACT." AND zbss_source = %s)", array( 'mailpoet' ) ) ) ); return $startingArg; } }
projects/plugins/crm/modules/mailpoet/admin/settings/router.page.php
<?php /** * Jetpack CRM * https://jetpackcrm.com * * MailPoet Sync: Admin: Settings page */ namespace Automattic\JetpackCRM; // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; /** * Page: MailPoet Sync Settings */ function jpcrm_settings_page_html_mailpoet() { global $zbs; $page = $_GET['tab']; $current_tab = 'main'; if ( isset( $_GET['subtab'] ) ) { $current_tab = sanitize_text_field ( $_GET['subtab'] ); } $zbs->modules->mailpoet->load_admin_page("settings/{$current_tab}"); call_user_func( "Automattic\JetpackCRM\jpcrm_settings_page_html_{$page}_{$current_tab}"); }
projects/plugins/crm/modules/mailpoet/admin/settings/main.page.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * MailPoet Sync: Admin: Settings page * */ namespace Automattic\JetpackCRM; // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; /** * Page: MailPoet Sync Settings */ function jpcrm_settings_page_html_mailpoet_main(){ global $zbs; $settings = $zbs->modules->mailpoet->settings->getAll(); $delete_action_options = array( 'delete' => __( 'Delete CRM contact and associated objects', 'zero-bs-crm' ), 'delete_save_related_objects' => __( 'Delete CRM contact but leave associated objects', 'zero-bs-crm' ), 'add_note' => __( 'Add a note to the CRM contact', 'zero-bs-crm' ), 'none' => __( 'No action', 'zero-bs-crm' ), ); // Act on any edits! if (isset($_POST['editwplf'])){ // Retrieve $updatedSettings = array(); // tag object settings $updatedSettings['tag_with_list'] = ( isset( $_POST['jpcrm_tag_with_list'] ) && !empty( $_POST['jpcrm_tag_with_list'] ) ? 1 : 0 ); $updatedSettings['tag_with_tags'] = ( isset( $_POST['jpcrm_tag_with_tags'] ) && !empty( $_POST['jpcrm_tag_with_tags'] ) ? 1 : 0 ); $updatedSettings['tag_list_prefix'] = ( isset( $_POST['jpcrm_tag_list_prefix'] ) ? jpcrm_sanitize_text_field_allow_whitespace( $_POST['jpcrm_tag_list_prefix'] ) : 'MailPoet List: ' ); $updatedSettings['tag_tag_prefix'] = ( isset( $_POST['jpcrm_tag_tag_prefix'] ) ? jpcrm_sanitize_text_field_allow_whitespace( $_POST['jpcrm_tag_tag_prefix'] ) : 'MailPoet Tag: ' ); // autolog changes $updatedSettings['autolog_changes'] = ( isset( $_POST['jpcrm_autolog_changes'] ) && !empty( $_POST['jpcrm_autolog_changes'] ) ? 1 : 0 ); // delete action $updatedSettings['delete_action'] = ( isset( $_POST['jpcrm_delete_action'] ) && in_array( $_POST['jpcrm_delete_action'], array_keys( $delete_action_options ) ) ? sanitize_text_field( $_POST['jpcrm_delete_action'] ) : 'none' ); #} Brutal update foreach ($updatedSettings as $k => $v){ $zbs->modules->mailpoet->settings->update($k,$v); } // $msg out! $sbupdated = true; // Reload $settings = $zbs->modules->mailpoet->settings->getAll(); } // Show Title jpcrm_render_setting_title( 'MailPoet Sync Settings', '' ); ?> <p style="padding-top: 18px; text-align:center;margin:1em"> <?php printf( '<a href="%s" class="ui basic positive button" style="margin-top:1em"><i class="users icon"></i> %s</a>', jpcrm_esc_link( $zbs->slugs['mailpoet'] ), esc_html__( 'MailPoet Sync Hub', 'zero-bs-crm' ) ); ?> </p> <p id="sbDesc"><?php esc_html_e( 'Here you can configure the global settings for MailPoet Sync.', 'zero-bs-crm' ); ?></p> <?php if (isset($sbupdated)) if ($sbupdated) { echo '<div class="ui message success">'. esc_html__( 'Settings Updated', 'zero-bs-crm' ) . '</div>'; } ?> <div id="sbA"> <form method="post"> <input type="hidden" name="editwplf" id="editwplf" value="1" /> <table class="table table-bordered table-striped wtab"> <thead> <tr> <th colspan="2" class="wmid"><?php esc_html_e('MailPoet Sync Settings','zero-bs-crm'); ?>:</th> </tr> </thead> <tbody> <tr> <td class="wfieldname"><label for="jpcrm_tag_with_list"><?php esc_html_e( 'Tag Contact with MailPoet List(s)', 'zero-bs-crm' ); ?>:</label><br /><?php esc_html_e('Tick to tag your contact with any MailPoet lists they are present on.','zero-bs-crm'); ?></td> <td style="width:540px"><input type="checkbox" class="winput form-control" name="jpcrm_tag_with_list" id="jpcrm_tag_with_list" value="1"<?php if ( isset( $settings['tag_with_list'] ) && $settings['tag_with_list'] == "1" ) echo ' checked="checked"'; ?> /></td> </tr> <tr> <td class="wfieldname"><label for="jpcrm_tag_list_prefix"><?php esc_html_e( 'List tag prefix','zero-bs-crm'); ?>:</label><br /><?php esc_html_e('Enter a tag prefix for List tags (e.g. MailPoet List: )', 'zero-bs-crm' ); ?></td> <td style='width:540px'><input type="text" class="winput form-control" name="jpcrm_tag_list_prefix" id="jpcrm_tag_list_prefix" value="<?php if ( isset( $settings['tag_list_prefix']) && !empty( $settings['tag_list_prefix'] ) ) echo esc_attr( $settings['tag_list_prefix'] ); ?>" placeholder="<?php esc_html_e( "e.g. 'MailPoet List: '", 'zero-bs-crm' ); ?>" /></td> </tr> <?php # We don't have tag retrieval yet as it's a new feature to MailPoet :) ?> <tr> <td class="wfieldname"><label for="jpcrm_tag_with_tags"><?php esc_html_e( 'Tag Contact with MailPoet Tag(s)', 'zero-bs-crm' ); ?>:</label><br /><?php esc_html_e( 'Tick to tag your contact with any MailPoet tags they are tagged with.', 'zero-bs-crm' ); ?></td> <td style="width:540px"><input type="checkbox" class="winput form-control" name="jpcrm_tag_with_tags" id="jpcrm_tag_with_tags" value="1"<?php if ( isset( $settings['tag_with_tags'] ) && $settings['tag_with_tags'] == "1" ) echo ' checked="checked"'; ?> /></td> </tr> <tr> <td class="wfieldname"><label for="jpcrm_tag_tag_prefix"><?php esc_html_e( 'List tag prefix','zero-bs-crm'); ?>:</label><br /><?php esc_html_e('Enter a tag prefix for Subscriber tags (e.g. MailPoet Tag: )', 'zero-bs-crm' ); ?></td> <td style='width:540px'><input type="text" class="winput form-control" name="jpcrm_tag_tag_prefix" id="jpcrm_tag_tag_prefix" value="<?php if ( isset( $settings['tag_tag_prefix']) && !empty( $settings['tag_tag_prefix'] ) ) echo esc_attr( $settings['tag_tag_prefix'] ); ?>" placeholder="<?php esc_attr_e( "e.g. 'MailPoet Tag: '", 'zero-bs-crm' ); ?>" /></td> </tr> <tr> <td class="wfieldname"><label for="jpcrm_autolog_changes"><?php esc_html_e( 'Autolog changes to subscribers', 'zero-bs-crm' ); ?>:</label><br /><?php esc_html_e( 'Tick to add a note to a contact each time changes made in MailPoet subscribers are reflected in CRM contacts', 'zero-bs-crm' ); ?></td> <td style="width:540px"><input type="checkbox" class="winput form-control" name="jpcrm_autolog_changes" id="jpcrm_autolog_changes" value="1"<?php if ( isset( $settings['autolog_changes'] ) && $settings['autolog_changes'] == "1" ) echo ' checked="checked"'; ?> /></td> </tr> <tr> <td class="wfieldname"><label for="jpcrm_delete_action"><?php esc_html_e( 'Subscriber deleted action', 'zero-bs-crm' ); ?>:</label><br /><?php esc_html_e( 'Choose what should happen to CRM contacts when a MailPoet subscriber is deleted in MailPoet.', 'zero-bs-crm' ); ?></td> <td style="width:540px"> <select class="winput form-control" name="jpcrm_delete_action" id="jpcrm_delete_action"> <?php foreach ( $delete_action_options as $value => $label ){ ?><option value="<?php echo esc_attr( $value ); ?>"<?php if ( isset( $settings['delete_action'] ) && $settings['delete_action'] == $value ){ echo ' selected="selected"'; } ?>><?php echo esc_html( $label ); ?></option><?php } ?> </select> </td> </tr> </tbody> </table> <table class="table table-bordered table-striped wtab"> <tbody> <tr> <td class="wmid"><button type="submit" class="button button-primary button-large"><?php esc_html_e( 'Save Settings', 'zero-bs-crm' ); ?></button></td> </tr> </tbody> </table> </form> </div> <?php }
projects/plugins/crm/modules/mailpoet/admin/mailpoet-hub/main.page.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * MailPoet Sync: Admin: Hub page * */ // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; /** * Page: MailPoet Sync Hub */ function jpcrm_mailpoet_render_hub_page() { global $zbs; // any messages to output $general_notices = array(); $error_notices = array(); // intercept for attempting restart of initial sync if ( isset( $_GET['restart_sync'] ) ) { // Show message: are you sure? $html = '<p>' . __( 'This will restart syncing your MailPoet subscribers from scratch, using your current settings.', 'zero-bs-crm' ) . '</p>'; $html .= '<p>' . __( 'This will not remove any existing subscribers or data, but it will update objects if they are reimported and have since changed.', 'zero-bs-crm' ) . '</p>'; $html .= '<p><a href="' . jpcrm_esc_link( $zbs->modules->mailpoet->slugs['hub'] . '&definitely_restart_sync=1' ) . '" class="ui button teal">' . __( 'Yes, do a full resync', 'zero-bs-crm' ) . '</a>&nbsp;&nbsp;<a href="' . jpcrm_esc_link( $zbs->modules->mailpoet->slugs['hub'] ) . '" class="ui button red">' . __( 'No, cancel and go back to hub', 'zero-bs-crm' ) . '</a></p>'; echo zeroBSCRM_UI2_messageHTML( 'warning', __( 'Want to restart your sync?', 'zero-bs-crm' ), $html, 'info' ); exit(); } // intercept for actual restart of initial sync if ( isset( $_GET['definitely_restart_sync'] ) ) { // restart! $zbs->modules->mailpoet->background_sync->set_first_import_status( false ); $zbs->modules->mailpoet->background_sync->set_resume_from_page( 0 ); // notice $general_notices[] = zeroBSCRM_UI2_messageHTML( 'info', __( 'Sync restarted', 'zero-bs-crm' ), __( 'The MailPoet Sync import has been restarted. This will start running in the background from the beginning.', 'zero-bs-crm' ) ); } // intercept for debug, if we have $_GET['debug_sync'], call that if ( isset( $_GET['debug_sync'] ) ){ // render debug mode sync page jpcrm_mailpoet_render_hub_page_debug_mode(); exit(); } $settings = $zbs->modules->mailpoet->settings->getAll(); $settings_page_url = jpcrm_esc_link( $zbs->slugs['settings'] . '&tab=' . $zbs->modules->mailpoet->slugs['settings'] ); // retrieve current counts $jpcrm_mailpoet_latest_stats = $zbs->modules->mailpoet->get_jpcrm_mailpoet_latest_stats(); // various states: if ( !$zbs->mailpoet_is_active() ){ $error_notices[] = zeroBSCRM_UI2_messageHTML( 'warning', '', __( 'You do not currently have the MailPoet plugin installed. You\'ll need to install MailPoet to use MailPoet Sync', 'zero-bs-crm' ) ) ; $no_mailpoet_found = true; } // shorthand $settings_cog_html = '<a href="' . $settings_page_url . '" title="' . __( 'Change Settings', 'zero-bs-crm' ) . '" target="_blank"><i class="cog icon"></i></a>'; $settings_cog_button_html = '<a href="' . $settings_page_url . '" title="' . __( 'Change Settings', 'zero-bs-crm' ) . '" target="_blank" class="ui right floated jpcrm-mailpoet-settings-button"><i class="cog icon"></i>' . __( 'MailPoet Sync Settings', 'zero-bs-crm' ) . '</a>'; ?> <div id="jpcrm-mailpoet-hub-page"> <div id="jpcrm-mailpoet-logo"> <img id="jpcrm-mailpoet-jpcrm-logo" src="<?php echo esc_url( ZEROBSCRM_URL ); ?>i/jpcrm-logo-horizontal-black.png" alt="CRM" /> <i class="plus icon"></i> <img id="jpcrm-mailpoet-mailpoet-logo" src="<?php echo esc_url( ZEROBSCRM_URL ); ?>i/mailpoet-logo.svg" alt="MailPoet" /> </div> <?php // any notices? if ( count( $general_notices ) > 0 ){ ?> <div id="jpcrm-mailpoet-messages"> <?php foreach ( $general_notices as $notice_html ){ echo $notice_html; } ?> </div> <?php } ?> <div class="ui segment" id="jpcrm-mailpoet-page-body"> <div> <div class="jpcrm-mailpoet-stats-header"></div> <?php // show any detected error messages if possible foreach ( $error_notices as $error_notice ) { echo $error_notice; } ?> </div> <?php if ( isset( $no_mailpoet_found ) ){ // No MailPoet ?> <h2 class="ui header"> <i id="jpcrm-mailpoet-status-icon" class="icon hourglass half green"></i> <div class="content"> <?php echo esc_html__( 'Status: ', 'zero-bs-crm' ) . esc_html__( 'Not yet connected', 'zero-bs-crm' ); ?> <div class="sub header"> <p class="jpcrm-mailpoet-recap"> <?php echo esc_html__( 'Setup Type: ', 'zero-bs-crm' ) . esc_html__( 'No connection', 'zero-bs-crm' ); ?> </p> <br> <span id="jpcrm-mailpoet-status-long-text"><?php echo wp_kses( sprintf( __( 'To get started with MailPoet Sync please make sure <a href="%s">MailPoet is installed</a>.', 'zero-bs-crm' ), esc_url( $zbs->modules->mailpoet->urls['install_mailpoet'] ) ), $zbs->acceptable_restricted_html ); ?></span> <i style="display:none" id="jpcrm_failed_ajax" class="grey exclamation circle icon"></i> <script> var jpcrm_mailpoet_initiate_ajax_sync = false; var jpcrm_mailpoet_nonce = '<?php echo esc_js( wp_create_nonce( 'jpcrm_mailpoet_hubsync' ) ); ?>'; </script> </div> </div> </h2> <?php } else { // Has plugin ?> <h2 class="ui header"> <i id="jpcrm-mailpoet-status-icon" class="icon hourglass half green"></i> <div class="content"> <?php esc_html_e( 'Status: ', 'zero-bs-crm' ); ?> <span id="jpcrm-mailpoet-status-short-text" class="status green"><?php esc_html_e( 'Syncing content from MailPoet...', 'zero-bs-crm' ); ?></span> <div class="sub header"> <p class="jpcrm-mailpoet-recap"> <?php esc_html_e( 'Setup Type:', 'zero-bs-crm' ); ?> <?php esc_html_e( 'Local', 'zero-bs-crm' ); ?><br /> <?php echo '<span id="jpcrm-mailpoet-stat-contacts-synced">' . esc_html( $jpcrm_mailpoet_latest_stats['subscribers_synced'] ) . '</span> ' . esc_html__( 'Subscribers Synced', 'zero-bs-crm' ); ?> <a href="<?php echo jpcrm_esc_link( 'manage-customers&quickfilters=mailpoet_subscriber' ); ?>" id="jpcrm-mailpoet-recap-link-to-contacts" class="ui tiny black button<?php if ( $jpcrm_mailpoet_latest_stats['subscribers_synced'] <= 0 ) { echo ' hidden'; } ?>" style="margin-left:10px"><?php esc_html_e( 'View Subscribers in CRM', 'zero-bs-crm' ); // phpcs:ignore Squiz.ControlStructures.ControlSignature.NewlineAfterOpenBrace ?></a> </p> <br> <span id="jpcrm-mailpoet-status-long-text"><?php esc_html_e( 'MailPoet Sync is importing subscribers...', 'zero-bs-crm' ); ?></span> <i style="display:none" id="jpcrm_failed_ajax" class="grey exclamation circle icon"></i> <script> var jpcrm_mailpoet_initiate_ajax_sync = true; var jpcrm_mailpoet_nonce = '<?php echo esc_js( wp_create_nonce( 'jpcrm_mailpoet_hubsync' ) ); ?>'; </script> <div class="ui inline loader" id="jpcrm_firing_ajax" title="<?php esc_attr_e( 'Keeping this page open will improve the background sync speed.', 'zero-bs-crm' ); ?>"></div> </div> </div> </h2> <?php } ?> <div id="jpcrm-mailpoet-stats" class="ui"> <?php if ( $jpcrm_mailpoet_latest_stats['subscribers_synced'] < 1 ) { ?> <div id="jpcrm-mailpoet-stats-nothing-yet" class="ui active dimmer"> <div> <p><?php esc_html_e( "You don't have any data synced from MailPoet yet.", 'zero-bs-crm' ); ?></p> <p> <a href="<?php echo esc_url( $settings_page_url ); ?>" target="_blank" class="ui small button"> <i class="cog icon"></i> <?php esc_html_e( 'Change Settings', 'zero-bs-crm' ); ?> </a> <?php ##WLREMOVE ?> <a href="<?php echo esc_url( $zbs->urls['kb-mailpoet'] ); ?>" target="_blank" class="ui small blue button"> <i class="file text outline icon"></i> <?php esc_html_e( 'Visit Setup Guide', 'zero-bs-crm' ); ?> </a> <?php ##/WLREMOVE ?> </p> </div> </div> <?php } ?> </div> </div> <div id="jpcrm-mailpoet-quiet-restart-link"> <?php esc_html_e( 'Admin Tools:', 'zero-bs-crm' ); // settings link if ( zeroBSCRM_isZBSAdminOrAdmin() ) { ?> <a href="<?php echo esc_url( $settings_page_url ); ?>"><?php esc_html_e( 'MailPoet Sync Settings', 'zero-bs-crm' ); ?></a> <?php } ?> | <a href="<?php echo jpcrm_esc_link( $zbs->modules->mailpoet->slugs['hub'] . '&restart_sync=1' ); ?>"><?php esc_html_e( 'Restart Sync', 'zero-bs-crm' ); ?></a> | <a href="<?php echo jpcrm_esc_link( $zbs->modules->mailpoet->slugs['hub'] . '&debug_sync=1' ); ?>"><?php esc_html_e( 'Run Sync debug', 'zero-bs-crm' ); ?></a> </div> </div> <?php // output language labels jpcrm_mailpoet_output_language_labels(); } /* * Output <script> JS to pass language labels to JS * * @param $additional_labels - array; any key/value pairs here will be expressed in the JS label var */ function jpcrm_mailpoet_output_language_labels( $additional_labels = array() ){ // specify default (generic) labels $language_labels = array_merge( array( 'ajax_fail' => __( 'Failed retrieving data.', 'zero-bs-crm' ), 'complete' => __( 'Completed Sync.', 'zero-bs-crm' ), 'remaining_pages' => __( '{0} remaining pages.', 'zero-bs-crm' ), 'caught_mid_job' => __( 'Import job is running in the back end. If this message is still shown after some time, please contact support.', 'zero-bs-crm' ), 'server_error' => __( 'There was a general server error.', 'zero-bs-crm' ), 'incomplete_nextpage' => __( 'Completed page. Next: page {0} of {1} pages. ({2})', 'zero-bs-crm' ), 'complete_lastpage' => __( 'Completed last page, (page {0} of {1} pages)', 'zero-bs-crm' ), 'debug_return' => __( 'Return: {0}', 'zero-bs-crm' ), 'retrieving_page' => __( 'Retrieving page {0}', 'zero-bs-crm' ), ), $additional_labels ); ?><script>var jpcrm_mailpoet_language_labels = <?php echo json_encode( $language_labels ); ?></script><?php } /** * Styles and scripts for hub page */ function jpcrm_mailpoet_hub_page_styles_scripts(){ global $zbs; wp_enqueue_script( 'jpcrm-mailpoet', plugins_url( '/js/jpcrm-mailpoet-hub-page'.wp_scripts_get_suffix().'.js', JPCRM_MAILPOET_ROOT_FILE ), array( 'jquery' ), $zbs->version ); wp_enqueue_style( 'jpcrm-mailpoet-hub-page', plugins_url( '/css/jpcrm-mailpoet-hub-page'.wp_scripts_get_suffix().'.css', JPCRM_MAILPOET_ROOT_FILE ) ); zeroBSCRM_global_admin_styles(); } /** * Run a sync in debug mode: */ function jpcrm_mailpoet_render_hub_page_debug_mode(){ global $zbs; ?><div id="jpcrm-mailpoet-hub-page"> <div id="jpcrm-mailpoet-logo"> <img id="jpcrm-mailpoet-jpcrm-logo" src="<?php echo esc_url( ZEROBSCRM_URL ); ?>i/jpcrm-logo-horizontal-black.png" alt="" /> <i class="plus icon"></i> <img id="jpcrm-mailpoet-mailpoet-logo" src="<?php echo esc_url( ZEROBSCRM_URL ); ?>i/mailpoet-logo.svg" alt="MailPoet" /> </div> <div class="ui segment" id="jpcrm-mailpoet-page-body"> <h2>Debug Mode:</h2> <div id="jpcrm-mailpoet-debug-output"> <?php // set debug $zbs->modules->mailpoet->background_sync->debug = true; // call job function $zbs->modules->mailpoet->background_sync->sync_subscribers(); ?></div> </div> <p style="text-align: center;margin-top:2em"><a href="<?php echo jpcrm_esc_link( $zbs->modules->mailpoet->slugs['hub'] ) ?>" class="ui button green"><?php esc_html_e( 'Go back to MailPoet Sync Hub', 'zero-bs-crm' ); ?></a> </div><?php }
projects/plugins/crm/modules/mailpoet/admin/mailpoet-hub/main.page.ajax.php
<?php /** * Fired by AJAX on hub page (where still contacts to import, checks nonce and initiates sync) */ function jpcrm_mailpoet_ajax_import_subscribers( ){ global $zbs; // verify nonce check_ajax_referer( 'jpcrm_mailpoet_hubsync', 'sec' ); // init $return = $zbs->modules->mailpoet->background_sync->sync_subscribers(); // if something's returned, output via AJAX // (Mostly `background_sync->sync_subscribers()` will do this automatically) echo json_encode( $return ); exit(); } // import subscribers AJAX add_action( 'wp_ajax_jpcrm_mailpoet_fire_sync_job', 'jpcrm_mailpoet_ajax_import_subscribers' );
projects/plugins/crm/modules/portal/class-client-portal-endpoint.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * Client Portal Endpoint * */ namespace Automattic\JetpackCRM; defined( 'ZEROBSCRM_PATH' ) || exit; /** * * This class represents a single Client Portal endpoint (e.g. Quotes) * */ #[\AllowDynamicProperties] abstract class Client_Portal_Endpoint { public $portal = null; public $template_name = null; public $should_check_user_permission = true; public $slug = null; public $name = null; public $icon = null; public $hide_from_menu = null; public $hide_from_settings_page = false; public $add_rewrite_endpoint = null; public $menu_order = null; public $template_args = array(); public $template_path = ''; public $default_template_path = ''; /** * Option param value used by some endpoints * @var string */ public $param_value; abstract public static function register_endpoint( $endpoints, $client_portal ); public function __construct( $portal ) { $this->portal = $portal; } /** * This function will perform all actions from this endpoint, including * the permission check. */ public function perform_endpoint_action() { // Some endpoints from the Client Portal bypass user permissions and // allow users that are not logged in to see the content. // e.g. Invoices with easy links. if ( $this->should_check_user_permission ) { if ( ! is_user_logged_in() ) { return $this->portal->get_template('login.php'); } if ( ! $this->portal->is_user_enabled() ) { return $this->portal->get_template('disabled.php'); } } $this->pre_content_action(); $this->output_html(); $this->post_content_action(); } public function output_html() { if ($this->template_name != '') { $this->portal->get_template( $this->template_name, $this->template_args, $this->template_path, $this->default_template_path ); } } /** * This action gets called before any action (even permission checks) * are performed by this endpoint. */ public function before_endpoint_actions() { // Do nothing. Should be overwritten by child classes if needed. } /** * This action gets called before any rendering is made by the endpoint. */ public function pre_content_action() { // Do nothing. Should be overwritten by child classes if needed. } /** * This action gets called after all rendering is finished. */ public function post_content_action() { // Do nothing. Should be overwritten by child classes if needed. } }
projects/plugins/crm/modules/portal/class-client-portal-render-helper.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * Client Portal Render Helper * */ namespace Automattic\JetpackCRM; defined( 'ZEROBSCRM_PATH' ) || exit; /** * * Client Portal class that helps rendering the Client Portal HTML. * */ class Client_Portal_Render_Helper { public $parent_portal; public function __construct($parent) { $this->parent_portal = $parent; } /** * Shows an object load error and dies. */ function show_single_obj_error_and_die() { $err = '<center>'; $err .= '<h3>'.__('Error loading object','zero-bs-crm').'</h3>'; $err .= __('Either this object does not exist or you do not have permission to view it.', 'zero-bs-crm'); $err .= '</center>'; echo $err; die(); } #} MS - can you make this work with templates, couldn't so dumped (dumbly) here for now: function portal_footer() { // won't return ours :/ ##WLREMOVE global $zbs; $showpoweredby_public = $zbs->settings->get( 'showpoweredby_public' ) === 1 ? true : false; if ( $showpoweredby_public ) { ?> <div class="zerobs-portal-poweredby" style="font-size:11px;position:absolute;bottom:25px;right:50px;font-size:12px;"> <?php echo wp_kses( sprintf( __( 'Client Portal by <a href="%s" target="_blank">Jetpack CRM</a>', 'zero-bs-crm' ), esc_url( $zbs->urls['home'] ) ), $zbs->acceptable_restricted_html ); ?> </div> <?php } ##/WLREMOVE } /* * Outputs html which shows 'you are viewing this as an admin' dialog on portal pages */ function portal_viewing_as_admin_banner( $admin_message = '' ) { global $zbs; ?> <div class="jpcrm-client-portal-admin-banner"> <div class="alert alert-info"> <strong><?php esc_html_e( 'You are viewing the Client Portal as an admin.', 'zero-bs-crm' ); ?></strong> <?php if ( ! empty( $admin_message ) ) { ?> <p class="admin-message"><?php echo esc_html( $admin_message ); ?></p> <?php } ?> <?php ##WLREMOVE ?> <p> <a href="<?php echo esc_url( $zbs->urls['kbclientportal'] ); ?>" target="_blank"><?php esc_html_e( 'Learn more about the Client Portal', 'zero-bs-crm' ); ?></a> </p> <?php ##/WLREMOVE ?> </div> <?php $this->admin_message(); ?> </div> <?php } // upsell shown to admins across whole portal as they view as admin function admin_message(){ global $zbs; // temp fix if (current_user_can( 'admin_zerobs_manage_options' ) && !function_exists('zeroBSCRM_cpp_register_endpoints')){// !zeroBSCRM_isExtensionInstalled('clientportalpro')){ ##WLREMOVE ?> <script type="text/javascript"> jQuery(function(){ jQuery('#zbs-close-cpp-note').on( 'click', function(){ jQuery('.zbs-client-portal-pro-note').remove(); }); }); </script> <?php ##/WLREMOVE } return ''; } function portal_nav( $selected_item = 'dashboard', $do_echo = true ) { global $wp_query; $nav_html = ''; $zbsWarn = ''; $dash_link = zeroBS_portal_link('dash'); $portal_root_url = \jpcrm_get_client_portal_root_url(); $nav_html .= ' <ul id="zbs-nav-tabs">'; foreach ( $this->parent_portal->endpoints as $endpoint ) { if ( $endpoint->hide_from_menu ) { continue; } $link = $endpoint->slug == 'dashboard' ? esc_url( $portal_root_url ) : esc_url( $portal_root_url . $endpoint->slug ); $class = $endpoint->slug == $selected_item ? 'active' : ''; //produce the menu from the array of menu items (easier to extend :-) ). // WH: this assumes icon, otehrwise it'll break! :o $nav_html .= "<li class='" . $class . "'><a href='" . $link . "'><i class='fa " . $endpoint->icon . "'></i>" . $endpoint->name . "</a></li>"; } $zbs_logout_text = __('Log out',"zero-bs-crm"); $zbs_logout_text = apply_filters('zbs_portal_logout_text', $zbs_logout_text); $zbs_logout_icon = 'fa-sign-out'; $zbs_logout_icon = apply_filters('zbs_portal_logout_icon', $zbs_logout_icon); $nav_html .= "<li><a href='". wp_logout_url( $dash_link ) . "'><i class='fa ".$zbs_logout_icon."' aria-hidden='true'></i>" . $zbs_logout_text . "</a></li>"; $nav_html .= '</ul>'; // echo or return nav HTML depending on flag; defaults to echo (legacy support) if ( $do_echo ) { echo $nav_html; } else { return $nav_html; } } }
projects/plugins/crm/modules/portal/jpcrm-compatibility-functions.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * This file was intended to provide a 'proxy' for all the functions that were * brutally chopped during the Client Portal refactor. * But for now it seems like just displaying a notice to update the * version of core is a good option. * */ defined( 'ZEROBSCRM_PATH' ) || exit; if ( ! function_exists( 'zeroBSCRM_portal_plainPermaCheck' ) ) { function zeroBSCRM_portal_plainPermaCheck() { // Not needed anymore. // TODO: Clean all unneeded functions. } }
projects/plugins/crm/modules/portal/class-client-portal.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * Client Portal Module * */ namespace Automattic\JetpackCRM; defined( 'ZEROBSCRM_PATH' ) || exit; require_once plugin_dir_path( __FILE__ ) . 'class-client-portal-endpoint.php'; /** * * Client Portal Module class for Jetpack CRM. * To add a new endpoint use one of the existing endpoints located inside the * './endpoints' folder. */ class Client_Portal { public $router = null; public $render = null; public $endpoints = null; /** * The class constructor initializes the attribbutes and calls an init function. * */ public function __construct() { require_once plugin_dir_path( __FILE__ ) . 'class-client-portal-render-helper.php'; require_once plugin_dir_path( __FILE__ ) . 'class-client-portal-router.php'; $this->router = new Client_Portal_Router(); $this->render = new Client_Portal_Render_Helper( $this ); // Initializes it later. Priority 10 add_action( 'init', array( $this, 'init' ) ); } /** * Initializes the Client Portal Module. * Mainly sets ups all needed hooks. * */ function init() { // Adding the shortcode function for the Client Portal. add_shortcode( 'jetpackcrm_clientportal', array( $this, 'client_portal_shortcode' ) ); add_shortcode( 'zerobscrm_clientportal', array( $this, 'client_portal_shortcode' ) ); // Basic theme support (here for now, probs needs option). add_filter( 'body_class', array( $this, 'portal_theme_support' ) ); // Fixes a bug when the Client Portal is set to the homepage (more info: gh-15). add_filter( 'redirect_canonical', array( $this, 'redirect_fix_portal_as_homepage' ), 10, 2 ); // Hook used by our custom rewrite rules. add_filter( 'query_vars', array( $this, 'get_portal_query_vars' ), 0 ); // Styles needed by the Client Portal. add_action( 'zbs_enqueue_scripts_and_styles', array( $this, 'portal_enqueue_scripts_and_styles' ) ); // Custom login redirect hook (this one is in our $router). add_action( 'login_redirect', array( $this->router, 'redirect_contacts_upon_login' ), 10, 3 ); // Initializes all endpoints (including the ones from external plugins). $this->init_endpoints(); // this catches failed logins, checks if from our page, then redirs // From mr pippin https://pippinsplugins.com/redirect-to-custom-login-page-on-failed-login/ add_action( 'wp_login_failed', array( $this, 'portal_login_fail_redirect' ) ); // hook failed login } /** * */ public function add_endpoint_class_folder( $endpoint_folder_path ) { $endpoint_directory = glob( $endpoint_folder_path . '/class*endpoint.php' ); foreach ( $endpoint_directory as $endpoint_file ) { require_once $endpoint_file; // Gets the filename without the ';php' suffix. e.g. 'class-single-invoice-endpoint'. $base_filename = basename( $endpoint_file, '.php' ); // Turns the snake case filename into pascal case separated by '_'. e.g. 'Class_Single_Invoice_Endpoint' $pascal_case_filename = str_replace('-', '_', ucwords($base_filename, '-')); // Removes the 'Class' prefix and adds the hardcoded namespace. e.g. 'Automattic\JetpackCRM\SingleInvoiceEndpoint' $endpoint_class = 'Automattic\JetpackCRM\\' . str_replace('Class_', '', $pascal_case_filename); // Registers the endpoint $this->endpoints = $endpoint_class::register_endpoint($this->endpoints, $this); } } public function sort_endpoints_by_menu_order() { // Sort all endpoints by their order usort ( $this->endpoints, function( $endpoint_a, $endpoint_b ) { if ( $endpoint_a->menu_order == $endpoint_b->menu_order ) { return 0; } else { return ( $endpoint_a->menu_order < $endpoint_b->menu_order ) ? -1 : 1; } } ); } /** * Initializes all the endpoints for the Client Portal */ public function init_endpoints() { // Since this is the init function, we should start with an empty array. $this->endpoints = array(); // By default we load all classes in the endpoints folder. $this->add_endpoint_class_folder( plugin_dir_path( __FILE__ ) . 'endpoints' ); // Allowing plugins to declare their endpoint classes. do_action( 'jpcrm_client_portal_register_endpoint', $this ); do_action( 'jpcrm_client_portal_post_init_endpoints', $this ); $this->sort_endpoints_by_menu_order(); $this->add_all_rewrite_endpoints(); } /** * Sorts out the stylesheet includes. * */ function portal_enqueue_scripts_and_styles() { global $zbs; wp_enqueue_style( 'zbs-portal', plugins_url( '/css/jpcrm-public-portal' . wp_scripts_get_suffix() . '.css', __FILE__ ), array(), $zbs->version ); wp_enqueue_style('zbs-fa', ZEROBSCRM_URL . 'css/font-awesome.min.css', array(), $zbs->version ); // This do_action call was left here for compatibility purposes (legacy). do_action('zbs_enqueue_portal', 'zeroBS_portal_enqueue_stuff'); // This new action should be used for newer implementations. do_action('jpcrm_enqueue_client_portal_styles'); } /** * Function used to offer css support for some themes. */ function portal_theme_support( $classes = array() ) { $theme_slug = get_stylesheet(); switch( $theme_slug ) { case 'twentyseventeen': $classes[] ='zbs-theme-support-2017'; break; case 'twentynineteen': $classes[] = 'zbs-theme-support-2019'; break; case 'twentytwenty': $classes[] = 'zbs-theme-support-2020'; break; case 'twentytwentyone': $classes[] = 'zbs-theme-support-2021'; break; case 'twentytwentytwo': $classes[] = 'zbs-theme-support-2022'; break; } return $classes; } /** * Locate template. * * Locate the called template. * Search Order: * 1. /themes/theme/zerobscrm-plugin-templates/$template_name * 2. /themes/theme/$template_name * 3. /plugins/portal/v3/templates/$template_name. * * @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 locate_template( $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/'; endif; // Set default plugin templates path. if ( ! $default_path ) : $default_path = ZEROBSCRM_PATH . 'modules/portal/templates/'; // Path to the template folder endif; // 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; endif; return apply_filters( 'locate_template', $template, $template_name, $template_path, $default_path ); } /** * Get template. * * Search for the template and include the file. * * @since 1.2.7 * * @see 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 get_template( $template_name, $args = array(), $tempate_path = '', $default_path = '' ) { if ( is_array( $args ) && isset( $args ) ) : extract( $args ); endif; $template_file = $this->locate_template( $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; endif; include_once $template_file; } // this handles contact detail updates via $_POST from the client portal // this is a #backward-compatibility landmine; proceed with caution (see gh-1642) function jpcrm_portal_update_details_from_post($cID=-1 ){ global $zbs, $zbsCustomerFields; /** * This gets fields hidden in Client Portal settings. * Eventually we should expand this to preprocess and filter * the following fields altogether if disabled: * - countries: zeroBSCRM_getSetting('countries') * - second addresses: zeroBSCRM_getSetting('secondaddress') * - all addresses: zeroBSCRM_getSetting('showaddress') * - not sure what this is: $zbs->settings->get('fieldhides') */ $hidden_fields = $zbs->settings->get( 'portal_hidefields' ); $hidden_fields = !empty( $hidden_fields ) ? explode( ',', $hidden_fields ) : array(); $read_only_fields = $zbs->settings->get( 'portal_readonlyfields' ); $read_only_fields = !empty( $read_only_fields ) ? explode( ',', $read_only_fields ) : array(); // get existing contact data $old_contact_data = $zbs->DAL->contacts->getContact( $cID ); // downgrade to old-style second address keys so that field names match the object generated by zeroBS_buildCustomerMeta() $key_map = array( 'secaddr_addr1' => 'secaddr1', 'secaddr_addr2' => 'secaddr2', 'secaddr_city' => 'seccity', 'secaddr_county' => 'seccounty', 'secaddr_country' => 'seccountry', 'secaddr_postcode' => 'secpostcode' ); foreach ( $key_map as $newstyle_key => $oldstyle_key ) { if ( isset( $old_contact_data[$newstyle_key] ) ){ $old_contact_data[$oldstyle_key] = $old_contact_data[$newstyle_key]; unset($old_contact_data[$newstyle_key]); } } // create new (sanitised) contact data from $_POST $new_contact_data = zeroBS_buildCustomerMeta($_POST, $old_contact_data); // process fields $fields_to_change = array(); foreach ( $new_contact_data as $key => $value ) { // check for hidden or read only field groups $is_hidden_or_readonly_field_group = false; if ( isset( $zbsCustomerFields[$key] ) && isset( $zbsCustomerFields[$key]['area'] ) ) { $area_key = ( $zbsCustomerFields[$key]['area'] == "Main Address" ) ? 'jpcrm-main-address' : ''; $area_key = ( $zbsCustomerFields[$key]['area'] == "Second Address" ) ? 'jpcrm-main-address' : $area_key; if ( in_array( $area_key, $hidden_fields ) || in_array( $area_key, $read_only_fields ) ) { $is_hidden_or_readonly_field_group = true; } } // if invalid or unauthorised field, keep old value if ( !isset( $zbsCustomerFields[$key] ) || in_array( $key, $hidden_fields ) || in_array( $key, $read_only_fields) || $is_hidden_or_readonly_field_group ) { $new_contact_data[$key] = $old_contact_data[$key]; } // collect fields that changed elseif ( $old_contact_data[$key] != $value ) { $fields_to_change[] = $key; } } // update contact if fields changed if ( count( $fields_to_change ) > 0 ) { $cID = $zbs->DAL->contacts->addUpdateContact( array( 'id' => $cID, 'data' => $new_contact_data, 'do_not_update_blanks' => false ) ); // update log if contact update was successful if ( $cID ){ // build long description string for log $longDesc = ''; foreach ( $fields_to_change as $field ) { if ( !empty( $longDesc ) ) { $longDesc .= '<br>'; } $longDesc .= sprintf( '%s: <code>%s</code> → <code>%s</code>', $field, $old_contact_data[$field], $new_contact_data[$field]); } zeroBS_addUpdateLog( $cID, -1, -1, array( 'type' => __( 'Details updated via Client Portal', 'zero-bs-crm' ), 'shortdesc' => __( 'Contact changed some of their details via the Client Portal', 'zero-bs-crm' ), 'longdesc' => $longDesc, ), 'zerobs_customer' ); echo "<div class='zbs_alert'>" . esc_html__( 'Details updated.', 'zero-bs-crm') . "</div>"; } else { echo "<div class='zbs-alert-danger'>" . esc_html__( 'Error updating details!', 'zero-bs-crm' ) . "</div>"; } } return $cID; } /** * Checks if a user has "enabled" or "disabled" access. * * @return bool True if the user is enabled in the Client Portal. */ function is_user_enabled() { // cached? if (defined('ZBS_CURRENT_USER_DISABLED')) return false; global $wpdb; $uid = get_current_user_id(); $cID = zeroBS_getCustomerIDFromWPID($uid); // these ones definitely work $uinfo = get_userdata( $uid ); $potentialEmail = ''; if (isset($uinfo->user_email)) $potentialEmail = $uinfo->user_email; $cID = zeroBS_getCustomerIDWithEmail($potentialEmail); $disabled = zeroBSCRM_isCustomerPortalDisabled($cID); if (!$disabled) return true; // cache to avoid multi-check define('ZBS_CURRENT_USER_DISABLED',true); return false; } /** * Fixes a bug when the Client Portal is set to the homepage. */ function redirect_fix_portal_as_homepage( $redirect_url, $requested_url ) { // When the Client Portal is set to the homepage we have to allow the slug // to be used for the child pages. We have to do this because WordPress will // redirect child pages to the root (e.g. '/clients/invoices' to '/invoices') // when the Client Portal is set to the homepage. This will fix it. if ( $this->is_a_client_portal_endpoint() ) { return $requested_url; } return $redirect_url; } function add_all_rewrite_endpoints() { foreach ( $this->endpoints as $endpoint ) { if ( $endpoint->add_rewrite_endpoint ) { $slug = $endpoint->slug; // TODO: remove reliance on Client Portal Pro from Core if ( function_exists( 'zeroBSCRM_clientPortalgetEndpoint' ) ) { $slug = zeroBSCRM_clientPortalgetEndpoint( $slug ); } add_rewrite_endpoint( $slug, EP_ROOT | EP_PAGES ); } } jpcrm_client_portal_flush_rewrite_rules_if_needed(); } /** * Returns the query vars associated with the Client Portal. * * @return array The list of the query vars associated with the Client Portal. */ function get_portal_query_vars( $vars ) { foreach ( $this->endpoints as $endpoint ) { if ( $endpoint->add_rewrite_endpoint ) { $slug = $endpoint->slug; // TODO: remove reliance on Client Portal Pro from Core if ( function_exists( 'zeroBSCRM_clientPortalgetEndpoint' ) ) { $slug = zeroBSCRM_clientPortalgetEndpoint( $slug ); } $vars[] = $slug; } } return $vars; } /** * Lets us check early on in the action stack to see if page is ours. * Only works after 'wp' in action order (needs wp_query->query_var) * Is also used by zeroBSCRM_isClientPortalPage in Admin Checks * (which affects force redirect to dash, so be careful). * * @return bool Returns true if the current page is a portal page. */ function is_portal_page() { return ! is_admin() && $this->is_a_client_portal_endpoint(); } /** * Checks if is a child, or a child of a child, of the client portal main page. * * @return bool Returns true if is a child, or a child of a child, of the client portal main page. */ function is_child_of_portal_page() { global $post; if (!is_admin() && function_exists('zeroBSCRM_getSetting') && zeroBSCRM_isExtensionInstalled('portal')){ $portalPage = (int)zeroBSCRM_getSetting('portalpage'); if ($portalPage > 0 && isset($post) && is_object($post)){ if ( is_page() && ($post->post_parent == $portalPage) ) { return true; } else { // check 1 level deeper if ($post->post_parent > 0){ $parentsParentID = (int)wp_get_post_parent_id($post->post_parent); if ($parentsParentID > 0 && ($parentsParentID == $portalPage) ) return true; } return false; } } } return false; } /** * Only works after 'wp' in action order (needs $wp_query->post). * * @return bool If current page loaded has an endpoint that matches ours returns true. False otherwise. */ function is_a_client_portal_endpoint() { global $wp_query; // We get the post id (which will be the page id) + compare to our setting. $portalPage = zeroBSCRM_getSetting('portalpage'); if ( ! empty( $portalPage ) && $portalPage > 0 && isset( $wp_query->post ) && gettype( $wp_query->post ) == 'object' && isset( $wp_query->post->ID ) && $wp_query->post->ID == $portalPage ) { return true; } else { return $this->is_child_of_portal_page(); } } /** * This is the shortcode function for the Client Portal. * */ function client_portal_shortcode() { // This function is being called by a shortcode (add_shortcode) and should never return any output (e.g. echo). // The implementation is old and removing all the output requires a lot of work. This is a quick workaround to fix it. ob_start(); // this checks that we're on the front-end // ... a necessary step, because the editor (wp) now runs the shortcode on loading (probs gutenberg) // ... and because this should RETURN, instead it ECHO's directly // ... it should not run on admin side, because that means is probs an edit page! if ( !is_admin() ) { global $wp_query; // Setting the default endpoint to be the dashboard. // This could be customizable by the user if we want to. $endpoints_slug_array_column = array_column($this->endpoints, null, 'slug'); // Let the default endpoint to be overriden by plugins. $default_endpoint_slug = apply_filters( 'jpcrm_client_portal_default_endpoint_slug', 'dashboard', $this ); $endpoint = $endpoints_slug_array_column[$default_endpoint_slug]; $portal_query_vars = $this->get_portal_query_vars( $wp_query->query_vars ); foreach( $portal_query_vars as $var_key => $var_value ) { foreach ( $this->endpoints as $endpoint_search ) { if ( $endpoint_search->slug === $var_key ) { $endpoint = $endpoint_search; $endpoint->param_value = $var_value; break 2; // Breaks this loop and the outer loop, hence 2. } } } // allows one to tweak endpoint properties as needed before running endpoint actions $endpoint->before_endpoint_actions(); $endpoint->perform_endpoint_action(); } $result = ob_get_contents(); ob_end_clean(); return $result; } /** * This catches failed logins, checks if from our page, then redirs * From mr pippin https://pippinsplugins.com/redirect-to-custom-login-page-on-failed-login/ * */ function portal_login_fail_redirect( $username ) { $referrer = ''; if(array_key_exists('HTTP_REFERER', $_SERVER)){ $referrer = $_SERVER['HTTP_REFERER']; // where did the post submission come from? } // if there's a valid referrer, and it's not the default log-in screen + it's got our post if ( !empty($referrer) && !strstr($referrer,'wp-login') && !strstr($referrer,'wp-admin') && isset($_POST['fromzbslogin'])) { wp_redirect(zeroBS_portal_link('dash') . '?login=failed' ); // let's append some information (login=failed) to the URL for the theme to use exit; } } /** * Gets client portal endpoint name for a given object type. * * @param int $obj_type_id object type ID * * @return str * @return bool false if endpoint is not supported */ function get_endpoint( $obj_type_id ) { return $this->router->get_endpoint( $obj_type_id ); } /** * Returns bool if current portal access is provided via easy-access hash * * @return bool - true if current access is via hash */ function access_is_via_hash( $obj_type_id ){ return $this->router->access_is_via_hash( $obj_type_id ); } /** * Gets current object ID based on portal page URL. * * @param int $obj_type_id object type ID * * @return int * @return false if invalid object, bad permissions, or any other failure */ function get_obj_id_from_current_portal_page_url( $obj_type_id ) { return $this->router->get_obj_id_from_current_portal_page_url( $obj_type_id ); } }
projects/plugins/crm/modules/portal/class-client-portal-router.php
<?php /** * Jetpack CRM * https://jetpackcrm.com * * Client Portal Router * * @package automattic/jetpack-crm */ namespace Automattic\JetpackCRM; defined( 'ZEROBSCRM_PATH' ) || exit; /** * Client Portal class that takes care of all the routing */ class Client_Portal_Router { /** * Redirect CRM contacts to Client Portal after login. * * @param string $redirect_to The redirect destination URL. * @param int $request The requested redirect destination URL passed as a parameter. * @param WP_User $wp_user WP_User object if login was successful, WP_Error object otherwise. * * @return str $redirect_to */ public function redirect_contacts_upon_login( $redirect_to, $request, $wp_user ) { if ( isset( $wp_user->roles ) && in_array( 'zerobs_customer', $wp_user->roles, true ) ) { $redirect_to = zeroBS_portal_link(); } return $redirect_to; } /** * Gets client portal endpoint name for a given object type. * * @param int $obj_type_id object type ID. * * @return string | bool false if endpoint is not supported */ public function get_endpoint( $obj_type_id ) { $endpoint = ''; // determine which endpoint we are on switch ( $obj_type_id ) { case ZBS_TYPE_INVOICE: $endpoint = 'invoices'; break; case ZBS_TYPE_QUOTE: $endpoint = 'quote'; break; default: $endpoint = false; } // fail if endpoint is not supported if ( ! $endpoint ) { return false; } // support custom endpoints if enabled in Client Portal Pro if ( function_exists( 'zeroBSCRM_clientPortalgetEndpoint' ) ) { $endpoint = zeroBSCRM_clientPortalgetEndpoint( $endpoint ); } return $endpoint; } /** * Determines if the string is an easy-access hash or not. * * @param string $obj_id_or_hash Object ID or hash. * * @return bool */ public function jpcrm_is_easy_access_hash( $obj_id_or_hash = '' ) { return str_starts_with( $obj_id_or_hash, 'zh-' ); } /** * Gets current objid or hash from query parameters * For use on singles, which are potentially easy-access calls * * @param int $obj_type_id Object type ID. * * @return string - object id or easy-access hash, or '' */ public function jpcrm_get_portal_single_objid_or_hash( $obj_type_id ) { $endpoint = $this->get_endpoint( $obj_type_id ); // fail if bad endpoint if ( ! $endpoint ) { return ''; } return sanitize_text_field( get_query_var( $endpoint ) ); } /** * Returns bool if current portal access is provided via easy-access hash * * @param int $obj_type_id Object type ID. * @return bool - true if current access is via hash */ public function access_is_via_hash( $obj_type_id ) { return $this->jpcrm_is_easy_access_hash( $this->jpcrm_get_portal_single_objid_or_hash( $obj_type_id ) ); } /** * Gets current object ID based on portal page URL. * * @param int $obj_type_id Object type ID. * * @return int | false if invalid object, bad permissions, or any other failure */ public function get_obj_id_from_current_portal_page_url( $obj_type_id ) { // get object ID from URL $obj_id_or_hash = $this->jpcrm_get_portal_single_objid_or_hash( $obj_type_id ); // valid obj id or hash? if ( empty( $obj_id_or_hash ) ) { return false; } // if a hash... if ( $this->jpcrm_is_easy_access_hash( $obj_id_or_hash ) ) { // fail if access via hash is not allowed if ( ! jpcrm_can_access_portal_via_hash( $obj_type_id ) ) { return false; } // retrieve obj ID by hash $obj_id = $this->jpcrm_get_obj_id_by_hash( $obj_id_or_hash, $obj_type_id ); // was an invalid hash if ( ! $obj_id ) { return false; } } else { // not a hash, so cast to int $obj_id = (int) $obj_id_or_hash; // fail if current user isn't allowed if ( ! jpcrm_can_current_wp_user_view_object( $obj_id, $obj_type_id ) ) { return false; } } return $obj_id; } /** * Returns security request name by object type. * * @param string $raw_obj_hash Raw object hash. * @param int $obj_type_id Object type ID. * * @return int id | bool false if no match */ public function jpcrm_get_obj_id_by_hash( $raw_obj_hash, $obj_type_id ) { // remove 'zh-' prefix $obj_hash = substr( $raw_obj_hash, 3 ); $security_request_name = jpcrm_get_easy_access_security_request_name_by_obj_type( $obj_type_id ); // log request $request_id = zeroBSCRM_security_logRequest( $security_request_name, $obj_hash ); // check hash $obj = zeroBSCRM_hashes_GetObjFromHash( $obj_hash, -1, $obj_type_id ); // bad hash if ( ! $obj['success'] ) { return false; } $obj_id = (int) $obj['data']['ID']; // clear request zeroBSCRM_security_finiRequest( $request_id ); return $obj_id; } }
projects/plugins/crm/modules/portal/jpcrm-portal-init.php
<?php if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /** * This function inits everything needed. * This is the only function directly called by this php file. */ function jpcrm_portal_init() { add_filter( 'jpcrm_register_free_extensions', 'jpcrm_register_free_extension_portal' ); add_action( 'jpcrm_load_modules', 'jpcrm_load_portal' ); jpcrm_portal_init_add_portal_to_complete_list(); jpcrm_portal_init_add_portal_to_setting_map(); require_once 'jpcrm-compatibility-functions.php'; } jpcrm_portal_init(); // Inits everything. function jpcrm_load_portal() { global $zbs; if ( zeroBSCRM_isExtensionInstalled( 'portal' ) ) { require_once JPCRM_MODULES_PATH . 'portal/class-client-portal.php'; $zbs->modules->load_module( 'portal', 'Client_Portal' ); } } function jpcrm_register_free_extension_portal( $exts ) { $exts['portal'] = array( 'name' => __( 'Client Portal', 'zero-bs-crm' ), 'i' => 'cpp.png', 'short_desc' => __( 'Adds a client area to your CRM install so they can see their documents.', 'zero-bs-crm' ), ); return $exts; } function jpcrm_portal_init_add_portal_to_complete_list() { global $zeroBSCRM_extensionsCompleteList; $zeroBSCRM_extensionsCompleteList['portal'] = array( 'fallbackname' => 'Client Portal', 'imgstr' => '<i class="fa fa-users" aria-hidden="true"></i>', 'desc' => __( 'Add a client area to your website.', 'zero-bs-crm' ), 'url' => 'https://jetpackcrm.com/feature/client-portal/', 'colour' => '#833a3a', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/client-portal/', 'shortName' => 'Portal' ); } /** * This function is using the prefix 'zeroBSCRM_' because core needs this * prefix to call the function. This should not be renamed. */ function zeroBSCRM_extension_name_portal() { return __('Client Portal',"zero-bs-crm"); } function jpcrm_portal_init_add_portal_to_setting_map() { global $jpcrm_core_extension_setting_map; $jpcrm_core_extension_setting_map['portal'] = 'feat_portal'; } /** * This function starts with the old prefix because the CRM uses the prefix * to dinamically call the function. * e.g.: * call_user_func( 'zeroBSCRM_extension_install_' . $safe_function_string ); */ function zeroBSCRM_extension_install_portal() { $result = jpcrm_install_core_extension( 'portal' ); if ( $result ) { // Create the page if it's not there. zeroBSCRM_portal_checkCreatePage(); } // Mark the rewrite rules as changed since they just got added now. jpcrm_client_portal_set_rewrite_rules_changed(); return $result; } /** * This function starts with the old prefix because the CRM uses the prefix * to dinamically call the function. * e.g.: * call_user_func( 'zeroBSCRM_extension_uninstall_' . $safe_function_string ); */ function zeroBSCRM_extension_uninstall_portal() { return jpcrm_uninstall_core_extension( 'portal' ); } /** * Marks the rewrite rules as changed so the Client Portal can flush them. */ function jpcrm_client_portal_set_rewrite_rules_changed() { update_option('jpcrm_client_portal_rewrite_rules_changed', 1, false); } /* * Flushes the rewrite rules if needed. */ function jpcrm_client_portal_flush_rewrite_rules_if_needed() { $rules_changed_option = get_option( 'jpcrm_client_portal_rewrite_rules_changed' ); if ($rules_changed_option == 1) { flush_rewrite_rules(); delete_option( 'jpcrm_client_portal_rewrite_rules_changed' ); } } /* * Checks if an incompatible (old) version of client portal pro is activated and * deactivates it if needed. This function is added to the init hook. */ function jpcrm_intercept_incompatible_client_portal_pro() { if ( is_admin() && defined('ZBS_CLIENTPORTALPRO_ROOTFILE') ) { $portal_pro_data = get_file_data( ZBS_CLIENTPORTALPRO_ROOTFILE, [ 'Version' => 'Version', ], 'plugin' ); if ( version_compare($portal_pro_data[ 'Version' ], '2.0', '<') ) { // Deactivates and adds a notice and transient if successful if ( jpcrm_extensions_deactivate_by_key( 'clientportalpro' ) ) { // check not fired within past day $existing_transient = get_transient( 'clientportalpro.incompatible.version.deactivated' ); if ( !$existing_transient ) { zeroBSCRM_notifyme_insert_notification( get_current_user_id(), -999, -1, 'clientportalpro.incompatible.version.deactivated', '' ); set_transient( 'clientportalpro.incompatible.version.deactivated', 'clientportalpro.incompatible.version.deactivated', HOUR_IN_SECONDS * 24 ); } // If the plugin was just activated, this keeps it from saying "plugin activated". if ( isset( $_GET['activate'] ) ) { unset( $_GET['activate'] ); } } } } } add_action( 'init', 'jpcrm_intercept_incompatible_client_portal_pro' );
projects/plugins/crm/modules/portal/endpoints/class-invoices-endpoint.php
<?php namespace Automattic\JetpackCRM; if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; class Invoices_Endpoint extends Client_Portal_Endpoint { public static function register_endpoint( $endpoints, $client_portal ) { if ( zeroBSCRM_getSetting( 'feat_invs' ) > 0 ) { $new_endpoint = new Invoices_Endpoint( $client_portal ); $new_endpoint->portal = $client_portal; $new_endpoint->slug = $client_portal->get_endpoint( ZBS_TYPE_INVOICE ); $new_endpoint->name = __('Invoices', 'zero-bs-crm'); $new_endpoint->hide_from_menu = false; $new_endpoint->menu_order = 2; $new_endpoint->icon = 'fa-file-text-o'; $new_endpoint->add_rewrite_endpoint = true; $endpoints[] = $new_endpoint; } return $endpoints; } // Handle dual-mode endpoint properties invoices vs. single invoice public function before_endpoint_actions() { // We should call invoices if no param is given, single invoice otherwise if ( empty( $this->param_value ) ) { $this->template_name = 'invoices.php'; $this->should_check_user_permission = true; } else { global $zbs; $this->template_name = 'single-invoice.php'; $this->should_check_user_permission = $zbs->settings->get( 'easyaccesslinks' ) === 0; } } /** * Single Endpoint rendering function */ function single_invoice_html_output( $invoice_id = -1, $invoice_hash = '' ) { echo zeroBSCRM_invoice_generatePortalInvoiceHTML( $invoice_id, $invoice_hash ); } #} New functions here. Used as NAMED in WooSync. Please do not rename and not tell me as need to update WooSync if so #} 1. The invoice list function /** * * @param $link and $endpoint as they will differ between Portal and WooCommerce My Account * */ function list_invoices_html_output($link = '', $endpoint = ''){ global $wpdb; $uid = get_current_user_id(); $uinfo = get_userdata( $uid ); $cID = zeroBS_getCustomerIDWithEmail($uinfo->user_email); $is_invoice_admin = $uinfo->has_cap( 'admin_zerobs_invoices' ); // if the current is a valid contact or a WP user with permissions to view invoices... if( $cID > 0 || $is_invoice_admin ){ // this allows the current admin to see all invoices even if they're a contact if ( $is_invoice_admin ) { $cID = -1; $this->portal->render->portal_viewing_as_admin_banner( __( 'Admins will see all invoices below, but clients will only see invoices assigned to them.', 'zero-bs-crm' ) ); } // get invoices $customer_invoices = zeroBS_getInvoicesForCustomer($cID,true,100,0,false); // if there are more than zero invoices... if(count($customer_invoices) > 0){ global $zbs; ?><?php // capture output buffer: this isn't ideal but since other extensions modify this table with existing hooks, it's the best we can do. ob_start(); foreach($customer_invoices as $cinv){ //invstatus check $inv_status = $cinv['status']; // id $idStr = '#'.$cinv['id']; if (isset($cinv['id_override']) && !empty($cinv['id_override'])) $idStr = $cinv['id_override']; // skip drafts if not an admin with invoice access if ( $inv_status === 'Draft' && ! $is_invoice_admin ) { // phpcs:ignore Generic.WhiteSpace.ScopeIndent.IncorrectExact continue; } if (!isset($cinv['due_date']) || empty($cinv['due_date']) || $cinv['due_date'] == -1) //no due date; $due_date_str = __("No due date", "zero-bs-crm"); else $due_date_str = $cinv['due_date_date']; // view on portal (hashed?) $invoiceURL = zeroBSCRM_portal_linkObj($cinv['id'],ZBS_TYPE_INVOICE); //zeroBS_portal_link('invoices',$invoiceID); $idLinkStart = ''; $idLinkEnd = ''; if (!empty($invoiceURL)){ $idLinkStart = '<a href="'. $invoiceURL .'">'; $idLinkEnd = '</a>'; } echo '<tr>'; echo '<td data-title="' . esc_attr( $zbs->settings->get('reflabel') ) . '">'. $idLinkStart . esc_html( $idStr ) . ' '. esc_html__('(view)', 'zero-bs-crm') . $idLinkEnd.'</td>'; echo '<td data-title="' . esc_attr__('Date',"zero-bs-crm") . '">' . esc_html( $cinv['date_date'] ) . '</td>'; echo '<td data-title="' . esc_attr__('Due date',"zero-bs-crm") . '">' . esc_html( $due_date_str ) . '</td>'; echo '<td data-title="' . esc_attr__('Total',"zero-bs-crm") . '">' . esc_html( zeroBSCRM_formatCurrency($cinv['total']) ) . '</td>'; echo '<td data-title="' . esc_attr__('Status',"zero-bs-crm") . '"><span class="status '. esc_attr( $inv_status ) .'">' . esc_html( $cinv['status'] ) . '</span></td>'; do_action('zbs-extra-invoice-body-table', $cinv['id']); // echo '<td class="tools"><a href="account/invoices/274119/pdf" class="pdf_download" target="_blank"><i class="fa fa-file-pdf-o"></i></a></td>'; echo '</tr>'; } $invoices_to_show = ob_get_contents(); ob_end_clean(); if ( !empty( $invoices_to_show ) ) { // there are invoices to show to this user, so build table echo '<table class="table zbs-invoice-list">'; echo '<thead>'; echo '<th>' . esc_html( $zbs->settings->get('reflabel') ) . '</th>'; echo '<th>' . esc_html__('Date','zero-bs-crm') . '</th>'; echo '<th>' . esc_html__('Due date','zero-bs-crm') . '</th>'; echo '<th>' . esc_html__('Total','zero-bs-crm') . '</th>'; echo '<th>' . esc_html__('Status','zero-bs-crm') . '</th>'; do_action('zbs-extra-invoice-header-table'); echo '</thead>'; echo $invoices_to_show; echo '</table>'; } else { // no invoices to show...might have drafts but no admin perms esc_html_e( 'You do not have any invoices yet.', 'zero-bs-crm' ); } }else{ // invoice object count for current user is 0 esc_html_e( 'You do not have any invoices yet.', 'zero-bs-crm' ); } }else{ // not a valid contact or invoice admin user esc_html_e( 'You do not have any invoices yet.', 'zero-bs-crm' ); } } }
projects/plugins/crm/modules/portal/endpoints/class-details-endpoint.php
<?php namespace Automattic\JetpackCRM; if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; class Details_Endpoint extends Client_Portal_Endpoint { public static function register_endpoint( $endpoints, $client_portal ) { $new_endpoint = new Details_Endpoint( $client_portal ); $new_endpoint->portal = $client_portal; $new_endpoint->slug = 'details'; $new_endpoint->name = __('Your Details', 'zero-bs-crm'); $new_endpoint->hide_from_menu = false; $new_endpoint->menu_order = 1; $new_endpoint->icon = 'fa-user'; $new_endpoint->template_name = 'details.php'; $new_endpoint->add_rewrite_endpoint = true; $new_endpoint->should_check_user_permission = true; $endpoints[] = $new_endpoint; return $endpoints; } function render_admin_notice() { $admin_message = __( 'This is the Client Portal contact details page. This will show the contact their details and allow them change information in the fields below. You can hide fields from this page in Settings → Client Portal → Fields.', 'zero-bs-crm' ); $this->portal->render->portal_viewing_as_admin_banner( $admin_message ); } // Functions that were in the template file function save_details() { if( $_POST['save'] == 1 && isset( $_POST['_wpnonce'] ) && wp_verify_nonce( $_POST['_wpnonce'], 'jpcrm-update-client-details' ) ) { $uid = get_current_user_id(); $uinfo = get_userdata( $uid ); $cID = zeroBS_getCustomerIDWithEmail($uinfo->user_email); // added !empty check - because if logged in as admin, saved deets, it made a new contact for them if((int)$_POST['customer_id'] == $cID && !empty($cID)){ // handle the password fields, if set. if(isset($_POST['password']) && !empty($_POST['password']) && isset($_POST['password2']) && !empty($_POST['password2']) ){ if($_POST['password'] != $_POST['password2']){ echo "<div class='zbs_alert danger'>" . esc_html__("Passwords do not match","zero-bs-crm") . "</div>"; } else { // update password wp_set_password( sanitize_text_field($_POST['password']), $uid); // log password change zeroBS_addUpdateLog( $cID, -1, -1, array( 'type' => __( 'Password updated via Client Portal', 'zero-bs-crm' ), 'shortdesc' => __( 'Contact changed their password via the Client Portal', 'zero-bs-crm' ), 'longdesc' => '', ), 'zerobs_customer' ); // display message echo "<div class='zbs_alert'>" . esc_html__( 'Password updated.', 'zero-bs-crm' ) . "</div>"; // update any details as well $this->portal->jpcrm_portal_update_details_from_post($cID); } } else { // update any details as well $this->portal->jpcrm_portal_update_details_from_post($cID); } do_action('jpcrm_client_portal_after_save_details'); } } } function get_value( $fieldK, $zbsCustomer ) { // get a value (this allows field-irrelevant global tweaks, like the addr catch below...) $value = ''; if (isset($zbsCustomer[$fieldK])) $value = $zbsCustomer[$fieldK]; // #backward-compatibility // 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 ($fieldK){ case 'secaddr1': if (isset($zbsCustomer['secaddr_addr1'])) $value = $zbsCustomer['secaddr_addr1']; break; case 'secaddr2': if (isset($zbsCustomer['secaddr_addr2'])) $value = $zbsCustomer['secaddr_addr2']; break; case 'seccity': if (isset($zbsCustomer['secaddr_city'])) $value = $zbsCustomer['secaddr_city']; break; case 'seccounty': if (isset($zbsCustomer['secaddr_county'])) $value = $zbsCustomer['secaddr_county']; break; case 'seccountry': if (isset($zbsCustomer['secaddr_country'])) $value = $zbsCustomer['secaddr_country']; break; case 'secpostcode': if (isset($zbsCustomer['secaddr_postcode'])) $value = $zbsCustomer['secaddr_postcode']; break; } return $value; } function render_text_field( $fieldK, $fieldV, $value ) { $extra_attributes = ""; if ( isset( $fieldV[ 'read_only' ] ) && $fieldV[ 'read_only' ] ) { $extra_attributes .= ' readonly disabled '; } ?> <p> <label class='label' for="<?php echo esc_attr( $fieldK ); ?>"><?php esc_html_e( $fieldV[1], 'zero-bs-crm' ); ?>:</label> <input <?php echo esc_attr( $extra_attributes ); ?> type="text" name="zbsc_<?php echo esc_attr( $fieldK ); ?>" id="<?php echo esc_attr( $fieldK ); ?>" class="form-control widetext" placeholder="<?php echo esc_attr( isset( $fieldV[2] ) ? $fieldV[2] : '' ); ?>" value="<?php echo ! empty( $value ) ? esc_attr( $value ) : ''; ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); /* phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase */ ?>" /> </p> <?php } function render_price_field($fieldK, $fieldV, $value){ $extra_attributes = ""; if ( isset( $fieldV[ 'read_only' ] ) && $fieldV[ 'read_only' ] ) { $extra_attributes .= ' readonly disabled '; } ?><p> <label for="<?php echo esc_attr( $fieldK ); ?>"><?php esc_html_e($fieldV[1],"zero-bs-crm"); ?>:</label> <?php echo esc_html( zeroBSCRM_getCurrencyChr() ); ?> <input <?php echo esc_attr( $extra_attributes ); ?> style="width: 130px;display: inline-block;;" type="text" name="zbsc_<?php echo esc_attr( $fieldK ); ?>" id="<?php echo esc_attr( $fieldK ); ?>" class="form-control numbersOnly" placeholder="<?php echo esc_attr( isset( $fieldV[2] ) ? $fieldV[2] : '' ); ?>" value="<?php echo ! empty( $value ) ? esc_attr( $value ) : ''; ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); /* phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase */ ?>" /> </p><?php } /** * Renders the HTML of a numeric field identified by $field_key with value $value. * * @param string $field_key The key associated with this field, used (for example) in the input name. * @param object $field_settings Row from the meta table that needs to be updated. * @param object $value Row from the meta table that needs to be updated. * * @return void */ private function render_numeric_field( $field_key, $field_settings, $value ) { $extra_attributes = ''; if ( isset( $field_settings['read_only'] ) && $field_settings['read_only'] ) { $extra_attributes .= ' readonly disabled '; } ?> <p> <label for="<?php echo esc_attr( $field_key ); ?>"><?php echo esc_html( $field_settings[1] ); ?>:</label> <input <?php echo esc_attr( $extra_attributes ); ?> style="width: 130px;display: inline-block;;" type="text" name="zbsc_<?php echo esc_attr( $field_key ); ?>" id="<?php echo esc_attr( $field_key ); ?>" class="form-control numbersOnly" placeholder="<?php echo isset( $field_settings[2] ) ? esc_attr( $field_settings[2] ) : ''; ?>" value="<?php echo ! empty( $value ) ? esc_attr( $value ) : ''; ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>" /> </p> <?php } function render_date_field( $field_key, $field_value, $value ) { $extra_attributes = ''; if ( isset( $field_value[ 'read_only' ] ) && $field_value[ 'read_only' ] ) { $extra_attributes .= ' readonly disabled'; } $date_value = ''; if ( ! empty( $value ) && $value !== -99) { $date_value = jpcrm_uts_to_date_str( $value, 'Y-m-d', true ); } ?> <p> <label class='label' for="<?php echo esc_attr( $field_key ); ?>"> <?php esc_html_e( $field_value[1], 'zero-bs-crm' ); ?>: </label> <input<?php echo esc_attr( $extra_attributes ); ?> type="date" name="zbsc_<?php echo esc_attr( $field_key ); ?>" id="zbsc_<?php echo esc_attr( $field_key ); ?>" placeholder="yyyy-mm-dd" value="<?php echo esc_attr( $date_value ); ?>"/> </p> <?php } function render_select_field($fieldK, $fieldV, $value){ $extra_attributes = ""; if ( isset( $fieldV[ 'read_only' ] ) && $fieldV[ 'read_only' ] ) { $extra_attributes .= ' readonly disabled '; } ?> <p> <label class='label' for="<?php echo esc_attr( $fieldK ); ?>"><?php esc_html_e($fieldV[1],"zero-bs-crm"); ?>:</label> <select <?php echo esc_attr( $extra_attributes ); ?> name="zbsc_<?php echo esc_attr( $fieldK ); ?>" id="<?php echo esc_attr( $fieldK ); ?>" class="form-control zbs-watch-input" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); /* phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase */ ?>"> <?php // pre DAL 2 = $fieldV[3], DAL2 = $fieldV[2] $options = array(); if (isset($fieldV[3]) && is_array($fieldV[3])) { $options = $fieldV[3]; } else { // DAL2 these don't seem to be auto-decompiled? // doing here for quick fix, maybe fix up the chain later. if (isset($fieldV[2])) $options = explode(',', $fieldV[2]); } if (isset($options) && count($options) > 0){ //catcher echo '<option value="" disabled="disabled"'; if ( empty( $value ) ) echo ' selected="selected"'; echo '>'.esc_html__('Select',"zero-bs-crm").'</option>'; foreach ($options as $opt){ echo '<option value="' . esc_attr( $opt ) .'"'; if (isset($value) && strtolower($value) == strtolower($opt)) echo ' selected="selected"'; // __ here so that things like country lists can be translated echo '>' . esc_html( __( $opt, 'zero-bs-crm' ) ) .'</option>'; } } else echo '<option value="">'.esc_html__('No Options',"zero-bs-crm").'!</option>'; ?> </select> <input type="hidden" name="zbsc_<?php echo esc_attr( $fieldK ); ?>_dirtyflag" id="zbsc_<?php echo esc_attr( $fieldK ); ?>_dirtyflag" value="0" /> </p> <?php } function render_telephone_field($fieldK, $fieldV, $value, $zbsCustomer) { $extra_attributes = ""; if ( isset( $fieldV[ 'read_only' ] ) && $fieldV[ 'read_only' ] ) { $extra_attributes .= ' readonly disabled '; } $click2call = 0; ?><p> <label for="<?php echo esc_attr( $fieldK ); ?>"><?php esc_html_e($fieldV[1],"zero-bs-crm");?>:</label> <input <?php echo esc_attr( $extra_attributes ); ?> type="text" name="zbsc_<?php echo esc_attr( $fieldK ); ?>" id="<?php echo esc_attr( $fieldK ); ?>" class="form-control zbs-tel" placeholder="<?php echo esc_attr( isset( $fieldV[2] ) ? $fieldV[2] : '' ); ?>" value="<?php echo ! empty( $value ) ? esc_attr( $value ) : ''; ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); /* phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase */ ?>" /> <?php if ($click2call == "1" && isset($zbsCustomer[$fieldK]) && !empty($zbsCustomer[$fieldK])) echo '<a href="' . esc_attr( zeroBSCRM_clickToCallPrefix().$zbsCustomer[$fieldK] ) . '" class="button"><i class="fa fa-phone"></i> ' . esc_html( $zbsCustomer[$fieldK] ) . '</a>'; ?> <?php if ($fieldK == 'mobtel'){ $sms_class = 'send-sms-none'; $sms_class = apply_filters('zbs_twilio_sms', $sms_class); do_action('zbs_twilio_nonce'); $customerMob = ''; if (is_array($zbsCustomer) && isset($zbsCustomer[$fieldK]) && isset($contact['id'])) $customerMob = zeroBS_customerMobile($contact['id'],$zbsCustomer); 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>'; } ?> </p> <?php } function render_email_field($fieldK, $fieldV, $value){ $extra_attributes = ""; if ( isset( $fieldV[ 'read_only' ] ) && $fieldV[ 'read_only' ] ) { $extra_attributes .= ' readonly disabled '; } ?><p> <label for="<?php echo esc_attr( $fieldK ); ?>"><?php esc_html_e($fieldV[1],"zero-bs-crm"); ?>:</label> <div class="<?php echo esc_attr( $fieldK ); ?>"> <input <?php echo esc_attr( $extra_attributes ); ?> type="text" name="zbsc_<?php echo esc_attr( $fieldK ); ?>" id="<?php echo esc_attr( $fieldK ); ?>" class="form-control zbs-email" placeholder="<?php echo esc_attr( isset( $fieldV[2] ) ? $fieldV[2] : '' ); ?>" value="<?php echo ! empty( $value ) ? esc_attr( $value ) : ''; ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); /* phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase */ ?>" /> </div> </p><?php } /** * Renders the HTML of a textarea identified by $field_key with value $value. * * @param string $field_key The key associated with this field, used (for example) in the input name. * @param object $field_settings Row from the meta table that needs to be updated. * @param object $value Row from the meta table that needs to be updated. * * @return void */ private function render_text_area_field( $field_key, $field_settings, $value ) { $extra_attributes = ""; if ( isset( $field_settings['read_only'] ) && $field_settings['read_only'] ) { $extra_attributes .= ' readonly disabled '; } ?><p> <label for="<?php echo esc_attr( $field_key ); ?>"><?php echo esc_html( $field_settings[1] ); ?>:</label> <textarea <?php echo esc_attr( $extra_attributes ); ?> name="zbsc_<?php echo esc_attr( $field_key ); ?>" id="<?php echo esc_attr( $field_key ); ?>" class="form-control" placeholder="<?php echo isset( $field_settings[2] ) ? esc_attr( $field_settings[2] ) : ''; ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>"><?php echo ! empty( $value ) ? esc_attr( $value ) : ''; ?></textarea> </p><?php } function render_country_list_field($fieldK, $fieldV, $value, $showCountryFields) { $extra_attributes = ""; if ( isset( $fieldV[ 'read_only' ] ) && $fieldV[ 'read_only' ] ) { $extra_attributes .= ' readonly disabled '; } $countries = zeroBSCRM_loadCountryList(); if ($showCountryFields == "1"){ ?><p> <label for="<?php echo esc_attr( $fieldK ); ?>"><?php esc_html_e($fieldV[1],"zero-bs-crm"); ?>:</label> <select <?php echo esc_attr( $extra_attributes ); ?> name="zbsc_<?php echo esc_attr( $fieldK ); ?>" id="<?php echo esc_attr( $fieldK ); ?>" class="form-control" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); /* phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase */ ?>"> <?php if (isset($countries) && count($countries) > 0){ //catcher echo '<option value="" disabled="disabled"'; if ( 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 (isset($value) && ( 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> </p><?php } } function render_radio_field($fieldK, $fieldV, $value, $postPrefix) { $extra_attributes = ""; if ( isset( $fieldV[ 'read_only' ] ) && $fieldV[ 'read_only' ] ) { $extra_attributes .= ' readonly disabled '; } ?><p> <label for="<?php echo esc_attr( $fieldK ); ?>"><?php esc_html_e($fieldV[1],"zero-bs-crm"); ?>:</label> <div class="zbs-field-radio-wrap"> <?php // pre DAL 2 = $fieldV[3], DAL2 = $fieldV[2] $options = false; if (isset($fieldV[3]) && is_array($fieldV[3])) { $options = $fieldV[3]; } else { // DAL2 these don't seem to be auto-decompiled? // doing here for quick fix, maybe fix up the chain later. if (isset($fieldV[2])) $options = explode(',', $fieldV[2]); } if (isset($options) && is_array($options) && count($options) > 0 && $options[0] != ''){ $optIndex = 0; foreach ($options as $opt){ // <label><input type="radio" name="group1" id="x" /> <span>Label text x</span></label> echo '<div class="zbs-radio">'; echo '<label for="'.esc_attr( $fieldK ).'-'.esc_attr( $optIndex ).'"><input ' . esc_attr( $extra_attributes ) . ' type="radio" name="' . esc_attr( $postPrefix.$fieldK ) . '" id="'. esc_attr( $fieldK ) . '-' . esc_attr( $optIndex ) . '" value="' . esc_attr( $opt ) . '"'; if (isset($value) && $value == $opt) echo ' checked="checked"'; echo ' /> <span>' . esc_html( $opt ) . '</span></label></div>'; $optIndex++; } } else echo '-'; ?> </div> </p><?php } function render_checkbox_field($fieldK, $fieldV, $value, $postPrefix) { $extra_attributes = apply_filters( 'jpcrm_client_portal_detail_field_extra_attributes', $fieldK, $fieldV ); if ( isset( $fieldV[ 'read_only' ] ) && $fieldV[ 'read_only' ] ) { $extra_attributes .= ' readonly disabled '; } ?><p> <label for="<?php echo esc_attr( $fieldK ); ?>"><?php esc_html_e($fieldV[1],"zero-bs-crm"); ?>:</label> <div class="zbs-field-checkbox-wrap"> <?php // pre DAL 2 = $fieldV[3], DAL2 = $fieldV[2] $options = false; if (isset($fieldV[3]) && is_array($fieldV[3])) { $options = $fieldV[3]; } else { // DAL2 these don't seem to be auto-decompiled? // doing here for quick fix, maybe fix up the chain later. if (isset($fieldV[2])) $options = explode(',', $fieldV[2]); } // split fields (multi select) $dataOpts = array(); if ( !empty( $value ) ) { $dataOpts = explode(',', $value); } if (isset($options) && is_array($options) && count($options) > 0 && $options[0] != ''){ $optIndex = 0; foreach ($options as $opt){ echo '<div class="zbs-cf-checkbox">'; echo '<label for="' . esc_attr( $fieldK ) . '-' . esc_attr( $optIndex ) . '"><input ' . esc_attr( $extra_attributes ) . ' type="checkbox" name="' . esc_attr( $postPrefix . $fieldK ) . '-' . esc_attr( $optIndex ) . '" id="' . esc_attr( $fieldK ) . '-' . esc_attr( $optIndex ) . '" value="' . esc_attr( $opt ) . '"'; if (in_array($opt, $dataOpts)) echo ' checked="checked"'; echo ' /> <span>' . esc_html( $opt ) . '</span></label></div>'; $optIndex++; } } else echo '-'; ?> </div> </p><?php } function render_field_by_type( $type, $fieldK, $fieldV, $value, $postPrefix, $showCountryFields, $zbsCustomer ) { switch ( $type ) { case 'text': $this->render_text_field( $fieldK, $fieldV, $value ); break; case 'price': $this->render_price_field( $fieldK, $fieldV, $value ); break; case 'date': $this->render_date_field( $fieldK, $fieldV, $value ); break; case 'select': $this->render_select_field( $fieldK, $fieldV, $value ); break; case 'tel': $this->render_telephone_field( $fieldK, $fieldV, $value, $zbsCustomer ); break; case 'email': $this->render_email_field( $fieldK, $fieldV, $value ); break; case 'textarea': $this->render_text_area_field( $fieldK, $fieldV, $value ); break; // Added 1.1.19 case 'selectcountry': $this->render_country_list_field( $fieldK, $fieldV, $value, $showCountryFields ); break; // 2.98.5 added autonumber, checkbox, radio case 'autonumber': // NOT SHOWN on portal :) break; // radio case 'radio': $this->render_radio_field( $fieldK, $fieldV, $value, $postPrefix ); break; case 'checkbox': $this->render_checkbox_field( $fieldK, $fieldV, $value, $postPrefix ); break; case 'numberint': case 'numberfloat': $this->render_numeric_field( $fieldK, $fieldV, $value ); //phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase break; default: do_action( 'jpcrm_client_portal_detail_render_field_by_type', $type, $fieldK, $fieldV, $value, $postPrefix, $showCountryFields, $zbsCustomer ); break; } } }
projects/plugins/crm/modules/portal/endpoints/class-transactions-endpoint.php
<?php namespace Automattic\JetpackCRM; if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; class Transactions_Endpoint extends Client_Portal_Endpoint { public static function register_endpoint( $endpoints, $client_portal ) { if ( zeroBSCRM_getSetting( 'feat_transactions' ) > 0 ) { $new_endpoint = new Transactions_Endpoint( $client_portal ); $new_endpoint->portal = $client_portal; $new_endpoint->slug = 'transactions'; $new_endpoint->name = __('Transactions', 'zero-bs-crm'); $new_endpoint->hide_from_menu = false; $new_endpoint->menu_order = 4; $new_endpoint->icon = 'fa-shopping-cart'; $new_endpoint->template_name = 'transactions.php'; $new_endpoint->add_rewrite_endpoint = true; $new_endpoint->should_check_user_permission = true; $endpoints[] = $new_endpoint; } return $endpoints; } }
projects/plugins/crm/modules/portal/endpoints/class-dashboard-endpoint.php
<?php namespace Automattic\JetpackCRM; if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; class Dashboard_Endpoint extends Client_Portal_Endpoint { public static function register_endpoint( $endpoints, $client_portal ) { $new_endpoint = new Dashboard_Endpoint( $client_portal ); $new_endpoint->portal = $client_portal; $new_endpoint->slug = 'dashboard'; $new_endpoint->name = __('Dashboard', 'zero-bs-crm'); $new_endpoint->hide_from_menu = false; $new_endpoint->menu_order = 0; $new_endpoint->icon = 'fa-dashboard'; $new_endpoint->template_name = 'dashboard.php'; $new_endpoint->add_rewrite_endpoint = true; $new_endpoint->should_check_user_permission = true; $endpoints[] = $new_endpoint; return $endpoints; } }
projects/plugins/crm/modules/portal/endpoints/class-payments-endpoint.php
<?php namespace Automattic\JetpackCRM; if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; class Payments_Endpoint extends Client_Portal_Endpoint { public static function register_endpoint( $endpoints, $client_portal ) { $new_endpoint = new Payments_Endpoint( $client_portal ); $new_endpoint->portal = $client_portal; $new_endpoint->slug = 'pn'; $new_endpoint->name = __('Payments', 'zero-bs-crm'); $new_endpoint->hide_from_menu = true; $new_endpoint->add_rewrite_endpoint = true; $new_endpoint->should_check_user_permission = true; $new_endpoint->hide_from_settings_page = true; $endpoints[] = $new_endpoint; return $endpoints; } public function pre_content_action() { // Tnis is the legacy name. do_action('zerobscrm_portal_pn'); // And adding the new name as post-action (this one should be used with new payments. do_action('jpcrm_portal_payment'); } }
projects/plugins/crm/modules/portal/endpoints/class-thanks-endpoint.php
<?php namespace Automattic\JetpackCRM; if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; class Thanks_Endpoint extends Client_Portal_Endpoint { public static function register_endpoint( $endpoints, $client_portal ) { $new_endpoint = new Thanks_Endpoint( $client_portal ); $new_endpoint->portal = $client_portal; $new_endpoint->slug = 'thanks'; $new_endpoint->name = __('Thank you', 'zero-bs-crm'); $new_endpoint->hide_from_menu = true; $new_endpoint->template_name = 'thank-you.php'; $new_endpoint->add_rewrite_endpoint = true; $new_endpoint->should_check_user_permission = false; $new_endpoint->hide_from_settings_page = true; $endpoints[] = $new_endpoint; return $endpoints; } }
projects/plugins/crm/modules/portal/endpoints/class-cancel-endpoint.php
<?php namespace Automattic\JetpackCRM; if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; class Cancel_Endpoint extends Client_Portal_Endpoint { public static function register_endpoint( $endpoints, $client_portal ) { $new_endpoint = new Cancel_Endpoint( $client_portal ); $new_endpoint->portal = $client_portal; $new_endpoint->slug = 'cancel'; $new_endpoint->name = __('Payment Cancelled', 'zero-bs-crm'); $new_endpoint->hide_from_menu = true; $new_endpoint->template_name = 'cancelled.php'; $new_endpoint->add_rewrite_endpoint = true; $new_endpoint->should_check_user_permission = false; $new_endpoint->hide_from_settings_page = true; $endpoints[] = $new_endpoint; return $endpoints; } }
projects/plugins/crm/modules/portal/endpoints/class-single-quote-endpoint.php
<?php namespace Automattic\JetpackCRM; if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; class Single_Quote_Endpoint extends Client_Portal_Endpoint { public static function register_endpoint( $endpoints, $client_portal ) { global $zbs; if ( zeroBSCRM_getSetting( 'feat_quotes' ) > 0 ) { $new_endpoint = new Single_Quote_Endpoint( $client_portal ); $new_endpoint->portal = $client_portal; $new_endpoint->slug = $client_portal->get_endpoint( ZBS_TYPE_QUOTE ); $new_endpoint->hide_from_menu = true; $new_endpoint->template_name = 'single-quote.php'; $new_endpoint->add_rewrite_endpoint = true; $new_endpoint->should_check_user_permission = $zbs->settings->get( 'easyaccesslinks' ) === "0"; $new_endpoint->hide_from_settings_page = true; $endpoints[] = $new_endpoint; } return $endpoints; } /* * Generates HTML for portal single email * * Previously called zeroBSCRM_quote_generatePortalQuoteHTML */ function single_quote_html_output( $quote_id = -1, $quote_hash='' ) { global $post, $zbs; $quote_data = zeroBS_getQuote( $quote_id, true ); $quote_content = ''; $acceptable = false; if ( !$quote_data ) { // something is wrong...abort! $this->show_single_obj_error_and_die(); } // content if ( isset( $quote_data['content'] ) ) { $placeholder_templating = $zbs->get_templating(); // get initial replacements arr $replacements = $placeholder_templating->get_generic_replacements(); $replacements['quote-url'] = zeroBSCRM_portal_linkObj( $quote_id, ZBS_TYPE_QUOTE ); $quote_content = $placeholder_templating->replace_placeholders( array( 'global', 'quote' ), $quote_data['content'], $replacements, array( ZBS_TYPE_QUOTE => $quote_data ) ); } // hash (if not passed) if ( isset( $quote_data['hash'] ) ) { $quote_hash = $quote_data['hash']; } // acceptable? if ( empty( $quote_data['accepted'] ) ) { $acceptable = true; } else { // setting this shows it at base of quote, when accepted if ( $quote_data['accepted'] > 0 ) { $acceptedDate = $quote_data['accepted_date']; } } ?> <div id="zerobs-proposal-<?php echo esc_attr( $quote_id ); ?> main" class="zerobs-proposal entry-content hentry" style="margin-bottom:50px;margin-top:0px;"> <div class="zerobs-proposal-body"><?php echo wp_kses( wpautop( $quote_content ), $zbs->acceptable_html ); ?></div> <?php if ( $acceptable ) { // js-exposed success/failure messages ?> <div id="zbs-quote-accepted-<?php echo esc_attr( $quote_id ) ?>" class="alert alert-success" style="display:none;margin-bottom:5em;"> <?php esc_html_e( 'Quote accepted. Thank you!', 'zero-bs-crm' ); ?> </div> <div id="zbs-quote-failed-<?php echo esc_attr( $quote_id ) ?>" class="alert alert-warning" style="display:none;margin-bottom:5em;"> <?php esc_html_e( 'Quote could not be accepted at this time.', 'zero-bs-crm' ); ?> </div> <div class="zerobs-proposal-actions" id="zerobs-proposal-actions-<?php echo esc_attr( $quote_id ); ?>"> <h3><?php esc_html_e( 'Accept Quote?', 'zero-bs-crm' ); ?></h3> <button id="zbs-proposal-accept" class="button btn btn-large btn-success button-success" type="button"><?php esc_html_e( 'Accept', 'zero-bs-crm' ); ?></button> <?php } if ( isset( $acceptedDate ) ) { ?> <div class="zerobs-proposal-actions" id="zerobs-proposal-actions-<?php echo esc_attr( $quote_id ); ?>"> <h3><?php esc_html_e( 'Accepted', 'zero-bs-crm' ); ?> <?php echo esc_html( $acceptedDate ); ?></h3> </div> <?php } ?> </div> <div style="clear:both"></div> <script type="text/javascript"> var jpcrm_proposal_data = { 'quote_id': '<?php echo esc_js( $quote_id ); ?>', 'quote_hash': '<?php echo esc_js( $quote_hash ); ?>', 'proposal_nonce': '<?php echo esc_js( wp_create_nonce( 'zbscrmquo-nonce' ) );?>', 'ajax_url': '<?php echo esc_url( admin_url( 'admin-ajax.php') ); ?>' }; </script> <?php wp_enqueue_script('jpcrm_public_proposal_js', plugins_url('/js/ZeroBSCRM.public.proposals'.wp_scripts_get_suffix().'.js',ZBS_ROOTFILE), array( 'jquery' ), $zbs->version); } }
projects/plugins/crm/modules/portal/endpoints/class-quotes-endpoint.php
<?php namespace Automattic\JetpackCRM; if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; class Quotes_Endpoint extends Client_Portal_Endpoint { public static function register_endpoint( $endpoints, $client_portal ) { if ( zeroBSCRM_getSetting( 'feat_quotes' ) > 0 ) { $new_endpoint = new Quotes_Endpoint( $client_portal ); $new_endpoint->portal = $client_portal; $new_endpoint->slug = 'quotes'; $new_endpoint->name = __('Quotes', 'zero-bs-crm'); $new_endpoint->hide_from_menu = false; $new_endpoint->menu_order = 3; $new_endpoint->icon = 'fa-clipboard'; $new_endpoint->template_name = 'quotes.php'; $new_endpoint->add_rewrite_endpoint = true; $new_endpoint->should_check_user_permission = true; $endpoints[] = $new_endpoint; } return $endpoints; } }
projects/plugins/crm/modules/portal/templates/transactions.php
<?php /** * Transaction List * * The list of transactions made by a user (all statuses) * * @author ZeroBSCRM * @package Templates/Portal/Transactions * @see https://jetpackcrm.com/kb/ * @version 3.0 * */ if ( ! defined( 'ABSPATH' ) ) exit; // Don't allow direct access global $zbs; $portal = $zbs->modules->portal; $settings = $zbs->settings->getAll(); $show_transaction_status = ( isset( $settings['portal_transactions_show_status'] ) && $settings['portal_transactions_show_status'] == '1' ); #} changed to this, so if people want to re-style then can remove_action do_action( 'zbs_enqueue_scripts_and_styles' ); ?> <div class="alignwide zbs-site-main zbs-portal-grid"> <nav class="zbs-portal-nav"> <?php if( function_exists( 'zeroBSCRM_clientPortalgetEndpoint' ) ) { $tran_endpoint = zeroBSCRM_clientPortalgetEndpoint( 'transactions' ); } else { $tran_endpoint = 'transactions'; } $portal->render->portal_nav( $tran_endpoint ); ?> </nav> <div class='zbs-portal-content'> <?php global $zbs; $uid = get_current_user_id(); $uinfo = get_userdata( $uid ); $cID = zeroBS_getCustomerIDWithEmail($uinfo->user_email); if ( $cID > 0 || $uinfo->has_cap( 'admin_zerobs_transactions' ) ) { // TODO: use pagination while getting from the db. $customer_transactions = $zbs->DAL->transactions->getTransactions( array( 'assignedContact' => $cID, 'withAssigned' => false, 'sortByField' => 'date', 'sortOrder' => 'DESC', 'page' => 0, 'perPage' => 100, 'ignoreowner' => true, ) ); // admin msg (upsell cpp) (checks perms itself, safe to run) $portal->render->admin_message(); if ( is_array( $customer_transactions ) && count( $customer_transactions ) > 0 ) { // titled v3.0 ?><h2><?php esc_html_e( 'Transactions', 'zero-bs-crm' ); ?></h2> <div class='zbs-entry-content zbs-responsive-table' style="position:relative;"> <?php echo '<table class="table">'; echo '<thead>'; echo '<th>' . esc_html__( 'Transaction', 'zero-bs-crm' ) . '</th>'; echo '<th>' . esc_html__( 'Transaction Date', 'zero-bs-crm' ) . '</th>'; echo '<th>' . esc_html__( 'Title', 'zero-bs-crm' ) . '</th>'; echo '<th>' . esc_html__( 'Total', 'zero-bs-crm' ) . '</th>'; if ($show_transaction_status) { echo '<th>' . esc_html__('Status', 'zero-bs-crm') . '</th>'; } echo '</thead>'; foreach( $customer_transactions as $transaction ) { // Transaction Date $transaction_date = __( 'No date', 'zero-bs-crm' ); if ( isset( $transaction['date_date'] ) && ! empty ( $transaction['date_date'] ) ) { $transaction_date = $transaction['date_date']; } // Transaction Ref $transaction_ref = ''; if ( isset($transaction['ref'] ) && ! empty( $transaction['ref'] ) ) { $transaction_ref = $transaction['ref']; } // transactionTitle Title // Default value is set to '&nbsp;' to force rendering the cell. The css "empty-cells: show;" doesn't work in this type of table $transaction_title = '&nbsp;'; if ( isset( $transaction['title'] ) && ! empty( $transaction['title'] ) ) { $transaction_title = $transaction['title']; } // Transaction Value $transaction_value = ''; if ( isset( $transaction['total'] ) && ! empty( $transaction['total'] ) ) { $transaction_value = zeroBSCRM_formatCurrency( $transaction['total'] ); } // Transaction Status $transaction_status = ''; if ( isset( $transaction['status'] ) && ! empty( $transaction['status'] ) ) { $transaction_status = $transaction['status']; } echo '<tr>'; echo '<td data-title="' . esc_attr__( 'Transaction', 'zero-bs-crm' ) . '">' . esc_html( $transaction_ref ) . '</td>'; echo '<td data-title="' . esc_attr__( 'Transaction Date', 'zero-bs-crm' ) . '">' . esc_html( $transaction_date ) . '</td>'; echo '<td data-title="' . esc_attr__( 'Title', 'zero-bs-crm' ) . '"><span class="name">' . esc_html( $transaction_title ) . '</span></td>'; echo '<td data-title="' . esc_attr__( 'Total', 'zero-bs-crm' ) . '">' . esc_html( $transaction_value ) . '</td>'; if ($show_transaction_status) { echo '<td data-title="' . esc_attr__( 'Status', 'zero-bs-crm') . '">' . esc_html( $transaction_status ) . '</td>'; } echo '</tr>'; } echo '</table>'; } else { esc_html_e( 'You do not have any transactions yet.', 'zero-bs-crm'); } } ?></div> </div> <div class="zbs-portal-grid-footer"><?php $portal->render->portal_footer(); ?></div> </div>
projects/plugins/crm/modules/portal/templates/login.php
<?php /** * Login Template * * This is the login page for the Portal * * @author ZeroBSCRM * @package Templates/Portal/Login * @see https://jetpackcrm.com/kb/ * @version 3.0 * */ if ( ! defined( 'ABSPATH' ) ) exit; global $zbs; $portal = $zbs->modules->portal; do_action( 'zbs_enqueue_scripts_and_styles' ); $portalPage = zeroBSCRM_getSetting('portalpage'); $portalLink = get_page_link($portalPage); ?> <div id="zbs-main" class="alignwide zbs-site-main"> <div class="zbs-client-portal-wrap main site-main zbs-post zbs-hentry"> <?php $args = array( 'echo' => true, 'remember' => true, 'redirect' => $portalLink, 'form_id' => 'loginform', 'id_username' => 'user_login', 'id_password' => 'user_pass', 'id_remember' => 'rememberme', 'id_submit' => 'wp-submit', 'label_username' => __( 'Email Address', 'zero-bs-crm' ), 'label_password' => __( 'Password', 'zero-bs-crm' ), 'label_remember' => __( 'Remember Me', 'zero-bs-crm' ), 'label_log_in' => __( 'Log In', 'zero-bs-crm' ), 'value_username' => '', 'value_remember' => false ); // add a filter for now, which adds a hidden field, which lets our redir catcher catch failed logins + bringback add_filter( 'login_form_bottom', 'zeroBSCRM_portal_loginFooter'); function zeroBSCRM_portal_loginFooter($prev=''){ return $prev.'<input type="hidden" name="fromzbslogin" value="1" />'; } // catch fails if (isset($_GET['login']) && $_GET['login'] == 'failed'){ echo '<div class="alert alert-info">'.esc_html__('Your username or password was incorrect. Please try again','zero-bs-crm').'</div>'; } echo '<div class="container zbs-portal-login" style="margin-top:20px;text-align:center;">'; ?> <h2><?php esc_html_e(apply_filters('zbs_portal_login_title', __('Welcome to your Client Portal',"zero-bs-crm")),'zero-bs-crm'); ?></h2> <p><?php esc_html_e(apply_filters('zbs_portal_login_content', __("Please login to your Client Portal to be able to view your documents","zero-bs-crm"),'zero-bs-crm')); ?></p> <div class="login-form"> <?php wp_login_form( $args ); do_action('login_form'); ?> <a href="<?php echo esc_url( wp_lostpassword_url( get_permalink() ) ); ?>" alt="<?php esc_attr_e( 'Lost Password', 'zero-bs-crm' ); ?>"><?php esc_html_e( 'Lost Password', 'zero-bs-crm' ); ?></a> </div> <?php echo '</div>'; ?> <?php $portal->render->portal_footer(); ?> </div> </div>
projects/plugins/crm/modules/portal/templates/dashboard.php
<?php /** * Portal Dashboard Page * * This is used as the main dashboard page of the portal * * @author ZeroBSCRM * @package Templates/Portal/Dashboard * @see https://jetpackcrm.com/kb/ * @version 3.0 * */ if ( ! defined( 'ABSPATH' ) ) exit; // Don't allow direct access global $zbs; $portal = $zbs->modules->portal; do_action( 'zbs_enqueue_scripts_and_styles' ); $uid = get_current_user_id(); $uinfo = get_userdata( $uid ); $cID = zeroBS_getCustomerIDWithEmail($uinfo->user_email); ?> <div class="alignwide zbs-site-main zbs-portal-grid"> <nav class="zbs-portal-nav"> <?php $portal->render->portal_nav('dashboard'); ?> </nav> <div class="zbs-portal-content"> <?php // admin msg (upsell cpp) (checks perms itself, safe to run) $portal->render->admin_message(); $page_title = __("Welcome to your Dashboard","zero-bs-crm"); $page_title = apply_filters('zbs_portal_dashboard_title', $page_title); ?> <h2><?php echo esc_html( $page_title ); ?></h2> <div class='zbs-entry-content' style="position:relative;"> <p> <?php //add actions for additional content do_action('zbs_pre_dashboard_content'); $dashboard = __("Welcome to your Client Portal dashboard. From here you can view your information using the portal navigation bar.", "zero-bs-crm"); //added so this can be modified, with a shortcode too $dashboard = apply_filters('zbs_portal_dashboard_content' , $dashboard); echo $dashboard; do_action('zbs_post_dashboard_content'); ?> </p> </div> </div> <div class="zbs-portal-grid-footer"><?php $portal->render->portal_footer(); ?></div> </div>
projects/plugins/crm/modules/portal/templates/details.php
<?php /** * Your Details Page * * This displays the users details for editing * * @author ZeroBSCRM * @package Templates/Portal/Details * @see https://kb.jetpackcrm.com/ * @version 3.0 * */ if ( ! defined( 'ABSPATH' ) ) exit; // Don't allow direct access global $zbs; $portal = $zbs->modules->portal; $details_endpoint = new Automattic\JetpackCRM\Details_Endpoint( $portal ); do_action( 'zbs_enqueue_scripts_and_styles' ); global $zbs, $wpdb, $zbsCustomerFields; // handle the saving of the details. if(array_key_exists('save', $_POST)){ $details_endpoint->save_details(); } $uid = get_current_user_id(); $uinfo = get_userdata( $uid ); $cID = zeroBS_getCustomerIDWithEmail($uinfo->user_email); ?> <div class="alignwide zbs-site-main zbs-portal-grid"> <nav class="zbs-portal-nav"> <?php // define $details_slug = 'details'; //moved into func if(function_exists('zeroBSCRM_clientPortalgetEndpoint')){ $details_slug = zeroBSCRM_clientPortalgetEndpoint('details'); } $portal->render->portal_nav($details_slug); ?> </nav> <div class='zbs-portal-content'> <?php $page_title = __("Your Details","zero-bs-crm"); $page_title = apply_filters('zbs_portal_details_title', $page_title); ?> <h2><?php echo esc_html( $page_title ); ?></h2> <?php // if admin, explain if ( current_user_can( 'admin_zerobs_manage_options' ) && empty( $cID ) ) { // phpcs:ignore WordPress.WP.Capabilities.Unknown,WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $details_endpoint->render_admin_notice(); } ?> <div class='zbs-entry-content' style="position:relative;"> <form enctype="multipart/form-data" action="#" name="zbs-update-deets" method="POST" style="padding-bottom:50px;" class="form-horizontal form-inline"> <?php wp_nonce_field( 'jpcrm-update-client-details' ); $fields = $zbsCustomerFields; $fields = apply_filters( 'jpcrm_client_portal_detail_fields', $fields ); // Get field Hides... $fieldHideOverrides = $zbs->settings->get('fieldhides'); $zbsCustomer = zeroBS_getCustomerMeta($cID); $zbsOpenGroup = false; $showAddr = true; // Fields to hide for front-end situations (Portal) $fields_to_hide_on_portal = $zbs->DAL->fields_to_hide_on_frontend( ZBS_TYPE_CONTACT ); $potentialNotToShow = $zbs->settings->get('portal_hidefields'); if (isset($potentialNotToShow)){ $potentialNotToShow = explode(',',$potentialNotToShow); } if (is_array($potentialNotToShow)) $fields_to_hide_on_portal = $potentialNotToShow; ?> <input type="hidden" name="customer_id" id="customer_id" value="<?php echo esc_attr( $cID ); ?>" /> <div class="form-table wh-metatab wptbp" id="wptbpMetaBoxMainItem"> <?php // Address settings $showAddresses = zeroBSCRM_getSetting('showaddress'); $showSecondAddress = zeroBSCRM_getSetting('secondaddress'); $showCountryFields = zeroBSCRM_getSetting('countries'); // This global holds "enabled/disabled" for specific fields... ignore unless you're WH or ask global $zbsFieldsEnabled; if ($showSecondAddress == "1"){ $zbsFieldsEnabled['secondaddress'] = true; } $second_address_label = zeroBSCRM_getSetting( 'secondaddresslabel' ); if ( empty( $second_address_label ) ) { $second_address_label = __( 'Second Address', 'zero-bs-crm' ); } $postPrefix = 'zbsc_'; $zbsFieldGroup = ''; $address_areas = array( 'Main Address' => 'jpcrm-main-address', 'Second Address' => 'jpcrm-second-address' ); $zbsWasOpenMultiGroupWrap = false; foreach ($fields as $fieldK => $fieldV){ // WH hard-not-showing some fields if (in_array($fieldK, $fields_to_hide_on_portal)) { continue; } // Hide address fields by group if ( isset( $fieldV['area'] ) && isset( $address_areas[ $fieldV['area'] ] ) && in_array( $address_areas[ $fieldV['area'] ], $fields_to_hide_on_portal ) ) { continue; } $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; } } // ================================================================================== // Following grouping code needed moving out of ifShown loop: // Whatever prev field group was, if this is diff, close (post group) if ( $zbsOpenGroup && // diff group ( (isset($fieldV['area']) && $fieldV['area'] != $zbsFieldGroup) || // No group !isset($fieldV['area']) && $zbsFieldGroup != '' ) ){ echo '</div>'; $zbsOpenGroup = false; } // Any groupings? if (isset($fieldV['area'])){ if (!$zbsWasOpenMultiGroupWrap) { echo "<div class='zbs-multi-group-wrap'>"; $zbsWasOpenMultiGroupWrap = true; } // First in a grouping? (assumes in sequential grouped order) if ($zbsFieldGroup != $fieldV['area']){ // set it $zbsFieldGroup = $fieldV['area']; $fieldGroupLabel = str_replace(' ','_',$zbsFieldGroup); $fieldGroupLabel = strtolower($fieldGroupLabel); if ($showSecondAddress != "1") { $fieldGroupLabel .= "_100w"; } if ($showAddresses == "0") { $fieldGroupLabel .= " zbs-hide"; } // Make class for hiding address (this form output is weird) <-- classic mike saying my code is weird when it works fully. Ask if you don't know! // DR Still Weird? $zbsShouldHideOrNotClass = ''; // if addresses turned off, hide the lot if (($showAddresses != "1") || ($zbsFieldGroup == 'Second Address' && $showSecondAddress != "1")) { $zbsShouldHideOrNotClass = 'zbs-hide'; } if ( $fieldV['area'] == 'Second Address' ) { echo '<div class="zbs-multi-group-item '. esc_attr( $zbsShouldHideOrNotClass ) .'"><label class="zbs-field-group-label">'. esc_html( $second_address_label ) .'</label>'; } else { echo '<div class="zbs-multi-group-item '. esc_attr( $zbsShouldHideOrNotClass ) .'"><label class="zbs-field-group-label">'. esc_html__($fieldV['area'],"zero-bs-crm").'</label>'; } // Set this (need to close) $zbsOpenGroup = true; } } else { // No groupings! $zbsFieldGroup = ''; } // Grouping // ================================================================================== // close opened wrap of groups if (!array_key_exists('area', $fieldV) && $zbsWasOpenMultiGroupWrap) { echo "</div>"; $zbsWasOpenMultiGroupWrap = false; } // If show... if ($showField) { // This whole output is LEGACY // v3.0 + this is resolved in core via zeroBSCRM_html_editFields() and zeroBSCRM_html_editField() // ... in FormatHelpers. // ... this could do with re-writing to match that. $value = $details_endpoint->get_value($fieldK, $zbsCustomer); if (isset($fieldV[0])) { if ($zbsFieldGroup == 'Second Address') { $fieldV[1] = str_replace( ' (' . $second_address_label . ')', '', $fieldV[1] ); } $details_endpoint->render_field_by_type($fieldV[0], $fieldK, $fieldV, $value, $postPrefix, $showCountryFields, $zbsCustomer); } } } // foreach field // closes any groups/tabs that are still open if ($zbsWasOpenMultiGroupWrap) { echo "</div>"; } if ($zbsOpenGroup) { echo "</div>"; } ?> <p> <label style="margin-top:2em;"><?php esc_html_e("Change your password (or leave blank to keep the same)", "zero-bs-crm"); ?></label> <input class="form-control" type="password" id="password" name="password" value=""/> </p> <p> <label><?php esc_html_e("Re-enter password", "zero-bs-crm"); ?></label> <input class="form-control" type="password" id="password2" name="password2" value=""/> </p> <p> <input type="hidden" id="save" name="save" value="1"/> <input type="submit" id="submit" value="<?php esc_attr_e('Submit',"zero-bs-crm");?>"/> </p> </div> </form> </div> </div> <div class="zbs-portal-grid-footer"><?php $portal->render->portal_footer(); ?></div> </div>
projects/plugins/crm/modules/portal/templates/thank-you.php
<?php /** * Payment Thank You * * This is used as a 'Payment Confirmation' when payment success * * @author ZeroBSCRM * @package Templates/Portal/Thanks * @see https://jetpackcrm.com/kb/ * @version 3.0 * */ if ( ! defined( 'ABSPATH' ) ) exit; // Don't allow direct access global $zbs; $portal = $zbs->modules->portal; do_action( 'zbs_enqueue_scripts_and_styles' ); $uid = get_current_user_id(); $cID = -1; if ( $uid !== 0) { $uinfo = get_userdata( $uid ); $cID = zeroBS_getCustomerIDWithEmail( $uinfo->user_email ); } $show_nav = ( ( $uid !== 0 ) && $portal->is_user_enabled() ) ; ?> <div class="alignwide zbs-site-main zbs-portal-grid<?php echo $show_nav?'':' no-nav' ?>"> <?php if ( $show_nav ) : ?> <nav class="zbs-portal-nav"> <?php $portal->render->portal_nav('dashboard'); ?> </nav> <?php endif; ?> <div class="zbs-portal-content"> <?php // admin msg (upsell cpp) (checks perms itself, safe to run) $portal->render->admin_message(); ?> <h2><?php esc_html_e("Thank You", "zero-bs-crm"); ?></h2> <div class='zbs-entry-content' style="position:relative;"> <p> <?php esc_html_e("Thank you for your payment.", "zero-bs-crm"); ?> </p> </div> </div> <div class="zbs-portal-grid-footer"><?php $portal->render->portal_footer(); ?></div> </div>
projects/plugins/crm/modules/portal/templates/cancelled.php
<?php /** * Payment Cancelled Page * * This is used as a 'Payment Cancelled' page following a cancelled payment * * @author ZeroBSCRM * @package Templates/Portal/Cancelled * @see https://jetpackcrm.com/kb/ * @version 3.0 * */ if ( ! defined( 'ABSPATH' ) ) exit; // Don't allow direct access global $zbs; $portal = $zbs->modules->portal; $uid = get_current_user_id(); $show_nav = ( ( $uid !== 0 ) && $portal->is_user_enabled() ) ; do_action( 'zbs_enqueue_scripts_and_styles' ); ?> <div class="alignwide zbs-site-main zbs-portal-grid<?php echo $show_nav?'':' no-nav' ?>"> <?php if ( $show_nav ) : ?> <nav class="zbs-portal-nav"> <?php //moved into func $portal->render->portal_nav('dashboard'); ?> </nav> <?php endif; ?> <div class="zbs-portal-content"> <h2><?php esc_html_e("Payment Cancelled", "zero-bs-crm"); ?></h2> <div class='zbs-entry-content' style="position:relative;"> <p> <?php esc_html_e("Your payment was cancelled.", "zero-bs-crm"); ?> </p> </div> </div> <div class="zbs-portal-grid-footer"><?php $portal->render->portal_footer(); ?></div> </div>
projects/plugins/crm/modules/portal/templates/single-quote.php
<?php /** * Single Quote Template * * The Single Quote Portal Page * * @author ZeroBSCRM * @package Templates/Portal/Quote * @see https://kb.jetpackcrm.com/ * @version 3.0 * */ // Don't allow direct access if ( ! defined( 'ABSPATH' ) ) exit; global $zbs; $portal = $zbs->modules->portal; $single_quote_endpoint = new Automattic\JetpackCRM\Single_Quote_Endpoint( $portal ); // Enqueuement do_action( 'zbs_enqueue_scripts_and_styles' ); // get raw id or hash from URL $obj_id = $portal->get_obj_id_from_current_portal_page_url( ZBS_TYPE_QUOTE ); // fail if invalid object or no permissions to view it if ( !$obj_id ) { $portal->render->show_single_obj_error_and_die(); } $show_nav = ( $portal->is_user_enabled() || !$portal->access_is_via_hash( ZBS_TYPE_QUOTE ) ) ; ?> <style> .zerobs-proposal-body{ font-size: 16px; box-shadow: 0px 1px 2px 0 rgba(34,36,38,0.15); margin: 1rem 0em; padding: 20px; border-radius: 0.28571429rem; border: 1px solid rgba(34,36,38,0.15); margin-top: -32px; } .zerobs-proposal-body li, .zerobs-proposal-body li span{ padding:5px; line-height: 18px; } .zerobs-proposal-body table td, table tbody th { border: 1px solid #ddd; padding: 8px; font-size: 16px; } .zerobs-proposal-body ul{ padding-left:20px; } </style> <div class="alignwide zbs-site-main zbs-portal-grid<?php echo $show_nav?'':' no-nav' ?>"> <?php if ( $show_nav ) { ?> <nav class="zbs-portal-nav"><?php echo $portal->render->portal_nav( $portal->get_endpoint( ZBS_TYPE_QUOTE ), false ); ?></nav> <?php } ?> <div class="zbs-portal-content zbs-portal-quote-single"> <?php $single_quote_endpoint->single_quote_html_output( $obj_id, true ); ?> </div> <div class="zbs-portal-grid-footer"><?php $portal->render->portal_footer(); ?></div> </div>
projects/plugins/crm/modules/portal/templates/quotes.php
<?php /** * Quote List Page * * This list of Quotes for the Portal * * @author ZeroBSCRM * @package Templates/Portal/Quotes * @see https://jetpackcrm.com/kb/ * @version 3.0 * */ if ( ! defined( 'ABSPATH' ) ) exit; global $zbs; $portal = $zbs->modules->portal; $ZBSuseQuotes = zeroBSCRM_getSetting( 'feat_quotes' ); do_action( 'zbs_enqueue_scripts_and_styles' ); $portalLink = zeroBS_portal_link(); if ( $ZBSuseQuotes < 0 ) { status_header( 404 ); nocache_headers(); include get_query_template( '404' ); die(); } add_action( 'wp_enqueue_scripts', array( $portal, 'portal_enqueue_scripts_and_styles' ) ); ?> <div class="alignwide zbs-site-main zbs-portal-grid"> <nav class="zbs-portal-nav"> <?php //moved into func if(function_exists('zeroBSCRM_clientPortalgetEndpoint')){ $quote_endpoint = zeroBSCRM_clientPortalgetEndpoint('quotes'); }else{ $quote_endpoint = 'quotes'; } $portal->render->portal_nav( $quote_endpoint ); ?> </nav> <div class="zbs-portal-content"> <h2><?php esc_html_e('Quotes','zero-bs-crm'); ?></h2> <?php global $wpdb; $uid = get_current_user_id(); $uinfo = get_userdata( $uid ); $cID = zeroBS_getCustomerIDWithEmail($uinfo->user_email); $is_quote_admin = $uinfo->has_cap( 'admin_zerobs_quotes' ); // if the current is a valid contact or a WP user with permissions to view quotes... if( $cID > 0 || $is_quote_admin ){ $currencyChar = zeroBSCRM_getCurrencyChr(); // this allows the current admin to see all quotes even if they're a contact if ( $is_quote_admin ) { $cID = -1; $portal->render->portal_viewing_as_admin_banner( __( 'Admins will see all quotes below, but clients will only see quotes assigned to them.', 'zero-bs-crm' ) ); } // get quotes $customer_quotes = zeroBS_getQuotesForCustomer($cID,true,100,0,false); ?> <div class='zbs-entry-content zbs-responsive-table' style="position:relative;"> <?php // if there are more than zero quotes... if(count($customer_quotes) > 0){ $quotes_to_show = ''; foreach($customer_quotes as $cquo){ // skip drafts if not an admin with quote access if ( $cquo['status'] == -1 && !$is_quote_admin ) { continue; } // Quote Date $quote_date = __("No date", "zero-bs-crm"); if (isset($cquo['date_date']) && !empty($cquo['date_date'])) { $quote_date = $cquo['date_date']; } // Quote Status $quote_stat = zeroBS_getQuoteStatus($cquo); // Quote Value $quote_value = ''; if (isset($cquo['value']) && !empty($cquo['value'])){ $quote_value = zeroBSCRM_formatCurrency($cquo['value']); } // view on portal (hashed?) $quote_url = zeroBSCRM_portal_linkObj($cquo['id'],ZBS_TYPE_QUOTE); // Quote Title // Default value is set to '&nbsp;' to force rendering the cell. The css "empty-cells: show;" doesn't work in this type of table $quote_title = '&nbsp;'; if (isset($cquo['title']) && !empty($cquo['title'])){ $quote_title = $cquo['title']; } $quotes_to_show .= '<tr>'; $quotes_to_show .= '<td data-title="' . __('#',"zero-bs-crm") . '"><a href="'. $quote_url .'">#'. $cquo['id'] .' '. __('(view)','zero-bs-crm') . '</a></td>'; $quotes_to_show .= '<td data-title="' . __('Date',"zero-bs-crm") . '">' . $quote_date . '</td>'; $quotes_to_show .= '<td data-title="' . __('Title',"zero-bs-crm") . '"><span class="name">'.$quote_title.'</span></td>'; $quotes_to_show .= '<td data-title="' . __('Total',"zero-bs-crm") . '">' . $quote_value . '</td>'; $quotes_to_show .= '<td data-title="' . __('Status',"zero-bs-crm") . '"><span class="status">'.$quote_stat.'</span></td>'; $quotes_to_show .= '</tr>'; } if ( !empty( $quotes_to_show ) ) { // there are quotes to show to this user, so build table echo '<table class="table">'; echo '<thead>'; echo '<th>' . esc_html__('#',"zero-bs-crm") . '</th>'; echo '<th>' . esc_html__('Date',"zero-bs-crm") . '</th>'; echo '<th>' . esc_html__('Title',"zero-bs-crm") . '</th>'; echo '<th>' . esc_html__('Total',"zero-bs-crm") . '</th>'; echo '<th>' . esc_html__('Status',"zero-bs-crm") . '</th>'; echo '</thead>'; echo $quotes_to_show; echo '</table>'; } else { // no quotes to show...might have drafts but no admin perms esc_html_e('You do not have any quotes yet.',"zero-bs-crm"); } }else{ // quote object count for current user is 0 esc_html_e('You do not have any quotes yet.',"zero-bs-crm"); } }else{ // not a valid contact or quote admin user esc_html_e( 'You do not have any quotes yet.', 'zero-bs-crm' ); } ?> </div> </div> <div class="zbs-portal-grid-footer"><?php $portal->render->portal_footer(); ?></div> </div>
projects/plugins/crm/modules/portal/templates/disabled.php
<?php /** * Account Disabled * * This is shown if a users Portal access is disabled * * @author ZeroBSCRM * @package Templates/Portal/Disabled * @see https://jetpackcrm.com/kb/ * @version 3.0 * */ if ( ! defined( 'ABSPATH' ) ) exit; // Don't allow direct access global $zbs; $portal = $zbs->modules->portal; do_action( 'zbs_enqueue_scripts_and_styles' ); ?> <div class="alignwide zbs-site-main"> <div class="zbs-portal-content"> <h2><?php esc_html_e("Access Disabled", "zero-bs-crm"); ?></h2> <div class='zbs-entry-content' style="position:relative;"> <p> <?php esc_html_e("Currently your client portal access is disabled.", "zero-bs-crm"); ?> </p> </div> </div> <div class="zbs-portal-grid-footer"><?php $portal->render->portal_footer(); ?></div> </div>
projects/plugins/crm/modules/portal/templates/footer.php
<?php /** * Footer template? * * Is this actually used anywhere? If so, the reference is pretty well hidden. * * @author ZeroBSCRM * @package Templates/Portal/Footer * @see https://jetpackcrm.com/kb/ */
projects/plugins/crm/modules/portal/templates/invoices.php
<?php /** * Invoice List Page * * The list of Invoices for the Portal * * @author ZeroBSCRM * @package Templates/Portal/Invoices * @see https://jetpackcrm.com/kb/ * @version 3.0 * */ if ( ! defined( 'ABSPATH' ) ) exit; // Don't allow direct access global $zbs; $portal = $zbs->modules->portal; do_action( 'zbs_enqueue_scripts_and_styles' ); $ZBSuseInvoices = zeroBSCRM_getSetting('feat_invs'); if($ZBSuseInvoices < 0){ status_header( 404 ); nocache_headers(); include get_query_template( '404' ); die(); } $portalLink = zeroBS_portal_link(); $invoice_endpoint = $portal->get_endpoint( ZBS_TYPE_INVOICE ); ?> <style> .zbs-portal-invoices-list .paid { background: green; color: white; font-weight: 700; line-height: 35px; border-radius: 0px !important; } </style> <div class="alignwide zbs-site-main zbs-portal-grid"> <nav class="zbs-portal-nav"> <?php $portal->render->portal_nav($invoice_endpoint); ?> </nav> <div class='zbs-portal-content zbs-portal-invoices-list'> <h2><?php esc_html_e('Invoices','zero-bs-crm'); ?></h2> <div class='zbs-entry-content zbs-responsive-table' style="position:relative;"> <?php $invoices_endpoint = new Automattic\JetpackCRM\Invoices_Endpoint( $portal ); $invoices_endpoint->list_invoices_html_output(); ?> </div> </div> <div class="zbs-portal-grid-footer"><?php $portal->render->portal_footer(); ?></div> </div>
projects/plugins/crm/modules/portal/templates/single-invoice.php
<?php /** * Single Invoice Template * * The single invoice template * * @author ZeroBSCRM * @package Templates/Portal/Invoice * @see https://kb.jetpackcrm.com/ * @version 3.0 * */ if ( ! defined( 'ABSPATH' ) ) exit; // Don't allow direct access global $zbs; $portal = $zbs->modules->portal; $single_invoice_endpoint = new Automattic\JetpackCRM\Invoices_Endpoint( $portal ); // Enqueuement do_action( 'zbs_enqueue_scripts_and_styles' ); // get raw id or hash from URL $obj_id = $portal->get_obj_id_from_current_portal_page_url( ZBS_TYPE_INVOICE ); // fail if invalid object or no permissions to view it if ( !$obj_id ) { $portal->render->show_single_obj_error_and_die(); } $show_nav = ( $portal->is_user_enabled() || ! $portal->access_is_via_hash( ZBS_TYPE_INVOICE ) ) ; ?> <style> .stripe-button-el{ background: none !important; border: 0px !important; box-shadow: none !important; } .zbs-back-to-invoices a:hover{ text-decoration:none; } </style> <div class="alignwide zbs-site-main zbs-portal-grid<?php echo $show_nav?'':' no-nav' ?>"> <?php if ( $show_nav ) { ?> <nav class="zbs-portal-nav"><?php echo $portal->render->portal_nav( $portal->get_endpoint( ZBS_TYPE_INVOICE ), false ); ?></nav> <?php } ?> <div class='zbs-portal-content zbs-portal-invoices-list'> <div class='zbs-entry-content zbs-single-invoice-portal' style="position:relative;"> <?php $single_invoice_endpoint->single_invoice_html_output( $obj_id, true ); ?> </div> </div> <div class="zbs-portal-grid-footer"><?php $portal->render->portal_footer(); ?></div> </div>
projects/plugins/crm/modules/woo-sync/jpcrm-woo-sync-init.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * WooSync Module initialisation * */ // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; // Add to $zeroBSCRM_extensionsCompleteList global // (Legacy way of maintaining an extensions list) global $zbs, $zeroBSCRM_extensionsCompleteList; $zeroBSCRM_extensionsCompleteList['woo-sync'] = array( 'fallbackname' => 'WooSync', 'imgstr' => '<i class="fa fa-keyboard-o" aria-hidden="true"></i>', 'desc' => __( 'Automatically import WooCommerce data into your CRM.', 'zero-bs-crm' ), 'url' => $zbs->urls['woosync'], 'colour' => 'rgb(127 85 178)', 'helpurl' => 'https://kb.jetpackcrm.com/article-categories/woocommerce-sync/', 'shortname' => 'WooSync', ); global $jpcrm_core_extension_setting_map; $jpcrm_core_extension_setting_map['woo-sync'] = 'feat_woosync'; // registers WooSync as a core extension, and adds to $zeroBSCRM_extensionsCompleteList global function jpcrm_register_free_extension_woosync( $exts ) { // append our module $exts['woo-sync'] = array( 'name' => 'WooCommerce Sync', 'i' => 'ext/woocommerce.png', 'short_desc' => __( 'Automatically import WooCommerce data into your CRM.', 'zero-bs-crm' ) ); return $exts; } add_filter( 'jpcrm_register_free_extensions', 'jpcrm_register_free_extension_woosync' ); // load the Woo_Sync class if feature is enabled function jpcrm_load_woo_sync() { global $zbs; // Check whether old WooSync is installed, if so, deactivate in favour of core module jpcrm_intercept_old_woosync(); // load if ( zeroBSCRM_isExtensionInstalled( 'woo-sync' ) ) { require_once( JPCRM_MODULES_PATH . 'woo-sync/includes/class-woo-sync.php' ); $zbs->modules->load_module( 'woosync', 'Woo_Sync' ); } } add_action( 'jpcrm_load_modules', 'jpcrm_load_woo_sync' ); /* * Where WooSync is installed as an extension, deactivate it */ function jpcrm_intercept_old_woosync( ){ // here we check if the old extension exists by its name function // ... if this didn't catch all situations, use zeroBSCRM_installedProExt if ( function_exists( 'zeroBSCRM_extension_name_woosync' ) ) { // deactivate if ( jpcrm_extensions_deactivate_by_key( 'woosync' ) ) { // Activate the module in its place zeroBSCRM_extension_install_woo_sync(); // remove obsolete cron wp_clear_scheduled_hook( 'zerobscrm_woosync_hourly_sync' ); // check not fired within past day $existing_transient = get_transient( 'woosync.conflict.deactivated' ); if ( !$existing_transient ) { // add notice & transient zeroBSCRM_notifyme_insert_notification( get_current_user_id(), -999, -1, 'woosync.conflict.deactivated', '' ); set_transient( 'woosync.conflict.deactivated', 'woosync.conflict.deactivated', HOUR_IN_SECONDS * 24 ); } } } } /** * Add a warning message on the plugin list. * * @param array $actions List of actions. * @param string $plugin_file Plugin file name. * @return array */ function jpcrm_warning_message_woosync_ext( $actions, $plugin_file = '', $plugin_data = array() ) { $woosync_ext_files = array( 'ZeroBSCRM_WooCommerce.php', '-ext-woo-connect.php', ); $is_woosyc_ext_installed = false; foreach ( $woosync_ext_files as $ext_file ) { $is_woosyc_ext_installed = ( str_contains( $plugin_file, $ext_file ) ); if ( $is_woosyc_ext_installed ) { break; } } if ( $is_woosyc_ext_installed ) { $delete_link = ''; if ( array_key_exists( 'delete', $actions ) ) { $delete_link = $actions['delete']; } $modified_actions = array( 'warning' => __( 'As of <b>CRM v5</b> this extension is no longer needed.', 'zero-bs-crm' ) . '<br><span style="color:#000;">' . $delete_link . '</span>', ); ##WLREMOVE $modified_actions = array( 'warning' => __( 'As of <b>Jetpack CRM v5</b> this extension is no longer needed.', 'zero-bs-crm' ) . '<br><span style="color:#000;">' . $delete_link . '</span>', ); ##/WLREMOVE return $modified_actions; } return $actions; } add_filter( 'plugin_action_links', 'jpcrm_warning_message_woosync_ext', 10, 3); // Install function function zeroBSCRM_extension_install_woo_sync() { return jpcrm_install_core_extension( 'woo-sync' ); } // Uninstall function function zeroBSCRM_extension_uninstall_woo_sync() { // remove cron wp_clear_scheduled_hook( 'jpcrm_woosync_sync' ); return jpcrm_uninstall_core_extension( 'woo-sync' ); } // Sniffs for WooCommerce, and puts out notification when we have woo but no woosync function jpcrm_sniff_feature_woosync() { global $zbs; // where we've not got WooSync active.. if ( !zeroBSCRM_isExtensionInstalled( 'woo-sync' ) ) { // check if WooCommerce _is_ active & prompt $zbs->feature_sniffer->sniff_for_plugin( array( 'feature_slug' => 'woocommerce', 'plugin_slug' => 'woocommerce/woocommerce.php', 'more_info_link' => $zbs->urls['kb-woosync-home'], 'is_module' => true, ) ); } } add_action( 'jpcrm_sniff_features', 'jpcrm_sniff_feature_woosync' ); // add jobs to system assistant function jpcrm_add_woo_jobs_to_system_assistant( $job_list ) { global $zbs; if ( $zbs->woocommerce_is_active() ) { // enable the Woo module if WooCommerce plugin is enabled $job_list['enable_woo_module'] = array( 'title' => __( 'Enable WooSync', 'zero-bs-crm' ), 'icon' => 'dollar sign', 'desc_incomplete' => __( 'You have the WooCommerce plugin installed, but the CRM module is not yet enabled. In order to sync your WooCommerce data to the CRM, you first need to enable the module.', 'zero-bs-crm' ), 'desc_complete' => __( 'The WooSync module is active.', 'zero-bs-crm' ), 'button_url' => jpcrm_esc_link( $zbs->slugs['modules'] ), 'button_txt' => __( 'Check module state', 'zero-bs-crm' ), 'state' => zeroBSCRM_isExtensionInstalled( 'woo-sync' ), ); // Get Woo data if no Woo transactions exist if ( zeroBSCRM_isExtensionInstalled( 'woo-sync' ) ) { $job_list['get_woo_data'] = array( 'title' => __( 'Sync WooCommerce data', 'zero-bs-crm' ), 'icon' => 'sync alternate', 'desc_incomplete' => __( 'No orders have been imported yet. Please verify that the module is properly configured.', 'zero-bs-crm' ), 'desc_complete' => __( 'Order data has been imported.', 'zero-bs-crm' ), 'button_url' => jpcrm_esc_link( $zbs->modules->woosync->slugs['hub'] ), 'button_txt' => __( 'Check sync status', 'zero-bs-crm' ), 'state' => $zbs->modules->woosync->get_crm_woo_transaction_count() > 0, ); } } return $job_list; } add_filter( 'jpcrm_system_assistant_jobs', 'jpcrm_add_woo_jobs_to_system_assistant' ); /** * Check if HPOS is enabled. * * The feature was enabled in WooCommerce 7.1. * * For new stores created on or after 10 October 2023, this is enabled by default. * https://woo.com/posts/platform-update-high-performance-order-storage-for-woocommerce/ * * @return bool Defaults to false. */ function jpcrm_woosync_is_hpos_enabled() { if ( class_exists( '\Automattic\WooCommerce\Utilities\OrderUtil' ) ) { return \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled(); } return false; } // Extension legacy definitions if ( ! defined( 'JPCRM_WOO_SYNC_ROOT_FILE' ) ) { define( 'JPCRM_WOO_SYNC_ROOT_FILE', __FILE__ ); define( 'JPCRM_WOO_SYNC_ROOT_PATH', plugin_dir_path( __FILE__ ) ); define( 'JPCRM_WOO_SYNC_IMAGE_URL', plugin_dir_url( JPCRM_WOO_SYNC_ROOT_FILE ) . 'i/' ); }
projects/plugins/crm/modules/woo-sync/includes/class-woo-sync-my-account-integration.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * WooSync: WooCommerce My Account integration * */ namespace Automattic\JetpackCRM; // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; /** * WooSync My Account integration class */ class Woo_Sync_My_Account_Integration { /** * The single instance of the class. */ protected static $_instance = null; /** * Setup WooSync * Note: This will effectively fire after core settings and modules loaded * ... effectively on tail end of `init` */ public function __construct( ) { // Initialise Hooks $this->init_hooks(); // Styles and scripts $this->register_styles_scripts(); } /** * Main Class Instance. * * Ensures only one instance of Woo_Sync_My_Account_Integration is loaded or can be loaded. * * @since 2.0 * @static * @see * @return Woo_Sync_My_Account_Integration main instance */ public static function instance() { if ( is_null( self::$_instance ) ) { self::$_instance = new self(); } return self::$_instance; } /** * Initialise Hooks */ private function init_hooks( ) { // Add menu item to Woo My Account add_filter( 'woocommerce_account_menu_items', array( $this, 'append_items_to_woo_menu' ), 99, 1 ); // Expose invoice content: add_action( 'woocommerce_account_invoices_endpoint', array( $this, 'render_invoice_list' ) ); // Enqueue styles and scripts add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_styles_scripts' ) ); // Expose CRM fields for editing on My Account (where specified in `wcport` setting) add_action( 'woocommerce_edit_account_form', array( $this, 'render_additional_crm_fields_on_my_account' ), 10, 0 ); // Save any changes to CRM fields as submitted from My Account page (where used `$this->render_additional_crm_fields_on_my_account`) add_action( 'woocommerce_save_account_details', array( $this, 'save_my_account_crm_field_changes'), 10, 1 ); // See also $zbs->wordpress_user_integration->wordpress_profile_update (catches woo my account + wp profile update changes) } /** * Get Invoice List */ public function render_invoice_list(){ global $zbs; $settings = $zbs->modules->woosync->settings->getAll(); if ( array_key_exists( 'wcacc', $settings) && $settings['wcacc'] && property_exists( $zbs->modules, 'portal' ) ){ if ( $this->check_customer_has_invoices() ) { $invoices_endpoint = new \Automattic\JetpackCRM\Invoices_Endpoint( $zbs->modules->portal ); $invoices_endpoint->list_invoices_html_output(); } else { echo esc_html__( 'No invoices available.', 'zero-bs-crm' ); } } else { echo esc_html__( 'This feature is disabled.', 'zero-bs-crm' ); } } /** * Does the current logged in customer have invoices? * * @return bool */ private function check_customer_has_invoices(){ $wordpress_user_id = get_current_user_id(); $uinfo = get_userdata( $wordpress_user_id ); $contact_id = zeroBS_getCustomerIDWithEmail( $uinfo->user_email ); if ( $contact_id > 0 ){ $customer_invoices = zeroBS_getInvoicesForCustomer( $contact_id, true, 100, 0, false ); if ( count( $customer_invoices ) > 0){ return true; } } return false; } /** * Appends our menu items (e.g. `Your Invoices`) to the Woo menu stack * To be fired via hook: `woocommerce_account_menu_items` */ public function append_items_to_woo_menu( $items ){ global $zbs; $my_account_invoices_enabled = zeroBSCRM_getSetting( 'feat_invs' ) > 0; $wc_settings = $zbs->modules->woosync->settings->getAll(); if ( $my_account_invoices_enabled && $wc_settings['wcacc'] ){ $modified_items = array( 'invoices' => __( 'Your Invoices', 'zero-bs-crm' ) ); $modified_items = array_slice( $items, 0, 2, true ) + $modified_items + array_slice( $items, 2, count( $items ), true ); $items = $modified_items; } return $items; } /** * Register styles and scripts */ public function register_styles_scripts() { global $zbs; wp_register_style( 'jpcrm-woo-sync-my-account', plugins_url( '/css/jpcrm-woo-sync-my-account'.wp_scripts_get_suffix().'.css', JPCRM_WOO_SYNC_ROOT_FILE ) ); wp_register_style( 'jpcrm-woo-sync-fa', plugins_url( '/css/font-awesome.min.css', ZBS_ROOTFILE ) ); } /** * Enqueue styles and scripts */ public function enqueue_styles_scripts(){ $account_page_id = get_option('woocommerce_myaccount_page_id'); if ( is_page( $account_page_id ) ) { wp_enqueue_style( 'jpcrm-woo-sync-my-account' ); wp_enqueue_style( 'jpcrm-woo-sync-fa' ); } } /** * Render CRM fields for editing on My Account (where specified in `wcport` setting) * WH note: This could make use of a central functions for a chunk of it (e.g. shared with portal/front-end exposed fields?) */ public function render_additional_crm_fields_on_my_account() { // make action magic happen here... global $zbs, $zbsCustomerFields, $zbsFieldsEnabled; $settings = $zbs->modules->woosync->settings->getAll(); if ( array_key_exists( 'wcport', $settings ) ){ // Retrieve current user data $wordpress_user_id = get_current_user_id(); $uinfo = get_userdata( $wordpress_user_id ); $contact_id = zeroBS_getCustomerIDWithEmail($uinfo->user_email); $crm_contact = zeroBS_getCustomerMeta($contact_id); // Field models/settings // Fields pulled from contact model $fields = $zbsCustomerFields; // Retireve fields show/hide statuses $fields_to_show = $settings['wcport']; $fields_to_hide = $zbs->settings->get('fieldhides'); $fields_to_show_on_woo_my_account = explode(",", $fields_to_show); // Fields to hide for front-end situations (Portal) $fields_to_hide_on_portal = $zbs->DAL->fields_to_hide_on_frontend( ZBS_TYPE_CONTACT ); // Portal hide field setting (overrides global setting ^) $portal_hide_fields_setting = $zbs->settings->get('portal_hidefields'); if ( isset( $portal_hide_fields_setting ) ){ $portal_hide_fields_setting_array = explode( ',', $portal_hide_fields_setting ); if ( is_array( $portal_hide_fields_setting_array ) ){ $fields_to_hide_on_portal = $portal_hide_fields_setting_array; } } // Address/contact settings $show_addresses = zeroBSCRM_getSetting('showaddress'); $show_second_address = zeroBSCRM_getSetting('secondaddress'); $show_address_country_field = zeroBSCRM_getSetting('countries'); $click2call = false; // Legacy: This global holds "enabled/disabled" for specific fields... ignore unless you're WH or ask if ( $show_second_address == "1" ) { $zbsFieldsEnabled['secondaddress'] = true; } // Track group element state $open_field_group = false; $field_group_key = ''; ?> <input type="hidden" name="zbs_customer_id" id="zbs_customer_id" value="<?php echo esc_attr( $contact_id ); ?>" /> <?php // Cycle through fields and op foreach ( $fields as $field_key => $field_value ){ // Hard global front-end & specific Woo My Account blocking of some fields if ( // Global block !in_array( $field_key, $fields_to_hide_on_portal ) && // Woo My Account settings specific block in_array( $field_key, $fields_to_show_on_woo_my_account ) && // Hard-hidden by opt override (on off for second address, mostly) !( isset( $field_value['opt'] ) && ( !isset( $zbsFieldsEnabled[ $field_value['opt'] ] ) || !$zbsFieldsEnabled[ $field_value['opt']] ) ) && // or is hidden by checkbox? !( isset( $fields_to_hide['customer'] ) && is_array( $fields_to_hide['customer'] ) && in_array( $field_key, $fields_to_hide['customer'] ) ) ){ // Output all fields with a field format type if ( isset( $field_value[0] ) ){ // Output Fields in Woo matching format (<p> per line) ?><p class="form-row"><?php // Split by field format switch ( $field_value[0] ){ case 'text': ?> <label for="<?php echo esc_attr( $field_key ); ?>"><?php esc_html_e( $field_value[1], "zero-bs-crm" ); ?></label> <input type="text" name="zbsc_<?php echo esc_attr( $field_key ); ?>" id="<?php echo esc_attr( $field_key ); ?>" class="input-text" style="width: 100%;padding: 15px;margin-bottom: 18px;" placeholder="<?php echo ( isset( $field_value[2] ) ? esc_attr__( $field_value[2], 'zero-bs-crm' ) : '' ); /* phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText */ ?>" value="<?php echo esc_attr( isset( $crm_contact[ $field_key ] ) ? $crm_contact[ $field_key ] : '' ); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>" /> <?php break; case 'price': ?><label for="<?php echo esc_attr( $field_key ); ?>"><?php esc_html_e($field_value[1],"zero-bs-crm"); ?></label> <?php echo esc_html( zeroBSCRM_getCurrencyChr() ); ?> <input style="width: 130px;display: inline-block;" type="text" name="zbsc_<?php echo esc_attr( $field_key ); ?>" id="<?php echo esc_attr( $field_key ); ?>" class="form-control numbersOnly" placeholder="<?php echo ( isset( $field_value[2] ) ? esc_attr__( $field_value[2], 'zero-bs-crm' ) : '' ); /* phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText */ ?>" value="<?php echo esc_attr( isset( $crm_contact[ $field_key ] ) ? $crm_contact[ $field_key ] : '' ); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>" /> <?php break; case 'date': $value = (isset($crm_contact[$field_key])) ? $crm_contact[$field_key] : null; $date_value = ''; if ( ! empty( $value ) && $value !== -99) { $date_value = jpcrm_uts_to_date_str( $value, 'Y-m-d', true ); } ?> <p> <label class='label' for="<?php echo esc_attr( $field_key ); ?>"> <?php esc_html_e( $field_value[1], 'zero-bs-crm' ); ?>: </label> <input type="date" name="zbsc_<?php echo esc_attr( $field_key ); ?>" id="zbsc_<?php echo esc_attr( $field_key ); ?>" placeholder="yyyy-mm-dd" value="<?php echo esc_attr( $date_value ); ?>"/> </p> <?php break; case 'select': ?><label for="<?php echo esc_attr( $field_key ); ?>"><?php esc_html_e($field_value[1],"zero-bs-crm"); ?></label> <select name="zbsc_<?php echo esc_attr( $field_key ); ?>" id="<?php echo esc_attr( $field_key ); ?>" class="form-control zbs-watch-input" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>"> <?php // pre DAL 2 = $field_value[3], DAL2 = $field_value[2] $options = array(); if (isset($field_value[3])) { $options = $field_value[3]; } else { // DAL2 these don't seem to be auto-decompiled if ( isset( $field_value[2] ) ) { $options = explode( ',', $field_value[2] ); } } if (isset($options) && count($options) > 0){ echo '<option value="" disabled="disabled"'; if ( !isset( $crm_contact[$field_key] ) || ( isset( $crm_contact[$field_key] ) && empty( $crm_contact[$field_key] ) ) ) { echo ' selected="selected"'; } echo '>' . esc_html__( 'Select', "zero-bs-crm" ) . '</option>'; foreach ($options as $opt){ echo '<option value="' . esc_attr( $opt ) . '"'; if ( isset( $crm_contact[$field_key] ) && strtolower( $crm_contact[$field_key] ) == strtolower( $opt ) ){ echo ' selected="selected"'; } // __ here so that things like country lists can be translated echo '>' . esc_html__( $opt, "zero-bs-crm" ) . '</option>'; } } else echo '<option value="">' . esc_html__( 'No Options', "zero-bs-crm" ) . '!</option>'; ?> </select> <?php break; case 'tel': ?><label for="<?php echo esc_attr( $field_key ); ?>"><?php esc_html_e($field_value[1],"zero-bs-crm");?></label> <input type="text" name="zbsc_<?php echo esc_attr( $field_key ); ?>" id="<?php echo esc_attr( $field_key ); ?>" class="form-control zbs-tel" placeholder="<?php echo ( isset( $field_value[2] ) ? esc_attr__( $field_value[2], 'zero-bs-crm' ) : '' ); /* phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText */ ?>" value="<?php echo esc_attr( isset( $crm_contact[ $field_key ] ) ? $crm_contact[ $field_key ] : '' ); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>" /> <?php if ( $click2call == "1" && isset( $crm_contact[$field_key] ) && !empty( $crm_contact[$field_key] ) ) { echo '<a href="' . esc_attr( zeroBSCRM_clickToCallPrefix() . $crm_contact[$field_key] ) . '" class="button"><i class="fa fa-phone"></i> ' . esc_html( $crm_contact[$field_key] ) . '</a>'; } if ( $field_key == 'mobtel' ){ // Twilio hook-in do_action( 'zbs_twilio_nonce' ); // Twilio filtering for css classes $sms_class = 'send-sms-none'; $sms_class = apply_filters( 'zbs_twilio_sms', $sms_class ); ; $contact_mobile = ''; if ( is_array( $crm_contact ) && isset( $crm_contact[$field_key] ) && isset( $contact['id'] ) ){ $contact_mobile = zeroBS_customerMobile( $contact['id'], $crm_contact ); } if ( !empty( $contact_mobile) ){ echo '<a class="' . esc_attr( $sms_class ) . ' button" data-smsnum="' . esc_attr( $contact_mobile ) .'"><i class="mobile alternate icon"></i> ' . esc_html__( 'SMS', 'zero-bs-crm' ) . ': ' . esc_html( $contact_mobile ) . '</a>'; } } ?> <?php break; case 'email': ?><label for="<?php echo esc_attr( $field_key ); ?>"><?php esc_html_e( $field_value[1], "zero-bs-crm" ); ?>:</label> <input type="text" name="zbsc_<?php echo esc_attr( $field_key ); ?>" id="<?php echo esc_attr( $field_key ); ?>" class="form-control zbs-email" placeholder="<?php echo esc_attr( isset( $field_value[2] ) ? __( $field_value[2], 'zero-bs-crm' ) : '' ); /* phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText */ ?>" value="<?php echo esc_attr( isset( $crm_contact[ $field_key ] ) ? $crm_contact[ $field_key ] : '' ); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>" /> <?php break; case 'textarea': ?><label for="<?php echo esc_attr( $field_key ); ?>"><?php esc_html_e( $field_value[1], "zero-bs-crm" ); ?>:</label> <textarea name="zbsc_<?php echo esc_attr( $field_key ); ?>" id="<?php echo esc_attr( $field_key ); ?>" class="form-control" placeholder="<?php echo esc_attr( isset( $field_value[2] ) ? __( $field_value[2], 'zero-bs-crm' ) : '' ); /* phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText */ ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>"><?php echo esc_textarea( isset( $crm_contact[ $field_key ] ) ? $crm_contact[ $field_key ] : '' ); ?></textarea> <?php break; #} Added 1.1.19 case 'selectcountry': $countries = zeroBSCRM_loadCountryList(); if ( $show_address_country_field == "1" ){ ?><label for="<?php echo esc_attr( $field_key ); ?>"><?php esc_html_e( $field_value[1], "zero-bs-crm" ); ?></label> <select name="zbsc_<?php echo esc_attr( $field_key ); ?>" id="<?php echo esc_attr( $field_key ); ?>" class="form-control" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>"> <?php // got countries? if ( isset( $countries ) && count( $countries ) > 0 ){ echo '<option value="" disabled="disabled"'; if ( !isset( $crm_contact[$field_key] ) || ( isset( $crm_contact[$field_key] ) && empty( $crm_contact[$field_key] ) ) ){ 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 ( isset( $crm_contact[$field_key] ) && ( strtolower( $crm_contact[$field_key] ) == strtolower( $country ) || strtolower( $crm_contact[$field_key] ) == strtolower( $countryKey ) ) ){ echo ' selected="selected"'; } echo '>' . esc_html( $country ) . '</option>'; } } else echo '<option value="">' . esc_html__( 'No Countries Loaded', "zero-bs-crm" ) . '!</option>'; ?> </select><?php } break; // auto number - can't actually edit autonumbers, so its just outputting :) case 'autonumber': ?> <label for="<?php echo esc_attr( $field_key ); ?>"><?php esc_html_e( $field_value[1], "zero-bs-crm" ); ?></label> <?php // output any saved autonumber for this obj $value = $field_value[2]; $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 ); } break; case 'numberint': $value = isset( $crm_contact[$field_key] ) ? $crm_contact[$field_key] : -99; ?> <label for="<?php echo esc_attr( $field_key ); ?>"><?php esc_html_e( $field_value[1], 'zero-bs-crm' ); /* phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText */ ?></label> <input style="width: 130px;display: inline-block;" type="text" name="zbsc_<?php echo esc_attr( $field_key ); ?>" id="<?php echo esc_attr( $field_key ); ?>" class="form-control intOnly zbs-dc zbs-custom-field" placeholder="<?php echo esc_attr( isset( $field_value[2] ) ? __( $field_value[2], 'zero-bs-crm' ) : '' ); /* phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText */ ?>" value="<?php echo esc_attr( $value !== -99 ? $value : '' ); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>" /> <?php break; case 'numberfloat': $value = isset( $crm_contact[$field_key] ) ? $crm_contact[$field_key] : -99; ?> <label for="<?php echo esc_attr( $field_key ); ?>"><?php esc_html_e( $field_value[1], 'zero-bs-crm' ); /* phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText */ ?></label> <input style="width: 130px;display: inline-block;" type="text" name="zbsc_<?php echo esc_attr( $field_key ); ?>" id="<?php echo esc_attr( $field_key ); ?>" class="form-control numbersOnly zbs-dc zbs-custom-field" placeholder="<?php echo esc_attr( isset( $field_value[2] ) ? __( $field_value[2], 'zero-bs-crm' ) : '' ); /* phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText */ ?>" value="<?php echo esc_attr( $value !== -99 ? $value : '' ); ?>" autocomplete="<?php echo esc_attr( jpcrm_disable_browser_autocomplete() ); ?>" /> <?php break; case 'checkbox': $value = isset( $crm_contact[$field_key] ) ? $crm_contact[$field_key] : -99; ?> <label for="<?php echo esc_attr( $field_key ); ?>"><?php esc_html_e( $field_value[1], "zero-bs-crm" ); ?></label> <?php // pre DAL 2 = $fieldV[3], DAL2 = $fieldV[2] $options = false; if ( isset( $field_value[3] ) && is_array( $field_value[3] ) ) { $options = $field_value[3]; } else if ( isset( $field_value[2] ) ) { // DAL2 these don't seem to be auto-decompiled? // doing here for quick fix, maybe fix up the chain later. $options = explode( ',', $field_value[2] ); } // split fields (multi select) $data_options = array(); if ( $value !== -99 && ! empty( $value ) ) { $data_options = explode(',', $value); } if ( isset( $options ) && is_array( $options ) && count( $options ) > 0 && $options[0] != '' ) { $option_index = 0; foreach ( $options as $opt ) { echo '<div class="ui checkbox"><input type="checkbox" name="zbsc_' . esc_attr( $field_key . '-' . $option_index ) . '" id="' . esc_attr( $field_key . '-' . $option_index ) . '" value="' . esc_attr( $opt ) . '"'; if ( in_array( $opt, $data_options ) ) { echo ' checked="checked"'; } echo ' /><label for="' . esc_attr( $field_key . '-' . $option_index ) . '">' . esc_html( $opt ) . '</label></div>'; $option_index++; } } else { echo '<label for="' . esc_attr( $field_key ) . '-0">' . esc_html__( 'No Options', 'zero-bs-crm' ) . '!</label>'; } ?> <input type="hidden" name="zbsc_<?php echo esc_attr( $field_key ); ?>_dirtyflag" id="zbsc_<?php echo esc_attr( $field_key ); ?>_dirtyflag" value="0" /> <?php break; case 'radio': $value = isset( $crm_contact[$field_key] ) ? $crm_contact[$field_key] : -99; ?> <label for="<?php echo esc_attr( $field_key ); ?>"><?php esc_html_e( $field_value[1], "zero-bs-crm" ); ?></label> <div class="zbs-field-radio-wrap"> <?php // pre DAL 2 = $fieldV[3], DAL2 = $fieldV[2] $options = false; if ( isset( $field_value[3] ) && is_array( $field_value[3] ) ) { $options = $field_value[3]; } else if ( isset( $field_value[2] ) ) { // DAL2 these don't seem to be auto-decompiled? // doing here for quick fix, maybe fix up the chain later. $options = explode( ',', $field_value[2] ); } if ( isset( $options ) && is_array( $options ) && count( $options ) > 0 && $options[0] != '' ) { $option_index = 0; foreach ( $options as $opt ) { echo '<div class="zbs-radio"><input type="radio" name="zbsc_' . esc_attr( $field_key ) . '" id="' . esc_attr( $field_key . '-' . $option_index ) . '" value="' . esc_attr( $opt ) . '"'; if ($value !== -99 && $value == $opt) echo ' checked="checked"'; echo ' /> <label for="' . esc_attr( $field_key . '-' . $option_index ) . '">' . esc_html( $opt ) . '</label></div>'; $option_index++; } } else { echo '<label for="' . esc_attr( $field_key ) . '-0">' . esc_html__( 'No Options', 'zero-bs-crm' ) . '!</label>'; } ?> </div> <input type="hidden" name="zbsc_<?php echo esc_attr( $field_key ); ?>_dirtyflag" id="zbsc_<?php echo esc_attr( $field_key ); ?>_dirtyflag" value="0" /> <?php break; } } ?></p><?php } // / not in 'hard do not show' list } // foreach field } // if array key does not exist } /** * Save any changes made from extra field additions on My Account page (via `$this->render_additional_crm_fields_on_my_account`) * * @param int $wordpress_user_id */ public function save_my_account_crm_field_changes( $wordpress_user_id ) { global $zbs, $zbsCustomerFields; $contact_id = zeroBS_getCustomerIDFromWPID( $wordpress_user_id ); $old_contact_data = $zbs->DAL->contacts->getContact( $contact_id ); $new_contact_data = zeroBS_buildCustomerMeta($_POST, $old_contact_data); // Here we check for fields already updated via core WordPress User integration if ( defined( 'JPCRM_PROFILE_UPDATE_CHANGES' ) ){ $do_not_update = JPCRM_PROFILE_UPDATE_CHANGES; } else { $do_not_update = array(); } if ( $contact_id > 0 ) { // First thing we have to do is to get some fields from WooCommerce // and 'translate' their key names into our CRM key names. $woo_field_to_crm_field = array( 'account_first_name' => 'fname', 'account_last_name' => 'lname', 'account_email' => 'email', ); foreach ( $_POST as $post_key => $post_value ) { if ( ! isset( $woo_field_to_crm_field[ $post_key ] ) ) { continue; } $crm_field = $woo_field_to_crm_field[ $post_key ]; if ( ! in_array( $crm_field, $do_not_update ) ) { $new_contact_data[ $crm_field ] = $post_value; } } // TODO: This is the same code from Client Portal. This should be centralised somehow. // process fields $fields_to_change = array(); foreach ( $new_contact_data as $key => $value ) { if ( !isset( $zbsCustomerFields[$key] ) || in_array( $key, $do_not_update ) ) { $new_contact_data[$key] = $old_contact_data[$key]; } // collect fields that changed elseif ( isset($old_contact_data[$key]) && $old_contact_data[$key] != $value ) { $fields_to_change[] = $key; } } // update contact if fields changed if ( count( $fields_to_change ) > 0 ) { $contact_id = $zbs->DAL->contacts->addUpdateContact( array( 'id' => $contact_id, 'data' => $new_contact_data, 'do_not_update_blanks' => false ) ); // update log if contact update was successful if ( $contact_id ) { // build long description string for log $longDesc = ''; foreach ( $fields_to_change as $field ) { if ( !empty( $longDesc ) ) { $longDesc .= '<br>'; } $longDesc .= sprintf( '%s: <code>%s</code> → <code>%s</code>', $field, $old_contact_data[$field], $new_contact_data[$field]); } zeroBS_addUpdateLog( $contact_id, -1, -1, array( 'type' => __( 'Details updated via WooCommerce My Account', 'zero-bs-crm' ), 'shortdesc' => __( 'Contact changed some of their details via WooCommerce My Account', 'zero-bs-crm' ), 'longdesc' => $longDesc, ), 'zerobs_customer' ); } } } } }
projects/plugins/crm/modules/woo-sync/includes/jpcrm-woo-sync-default-settings.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * WooSync: Default Settings * */ return array( // Once multi-site syncing we store a stack of these in here: 'sync_sites' => array(), // 0 = no, 1 = yes 'wccopyship' => '0', 'wctagcust' => '1', // tag contacts with item 'wctagtransaction' => '1', // tag transaction with item 'wctaginvoice' => '1', // tag invoice with item 'wctagcoupon' => '1', // Include any passed coupon code as a tag (dependent on above 3 settings) 'wctagproductprefix' => 'Product: ', 'wctagcouponprefix' => 'Coupon: ', 'wcinv' => '0', 'wcprod' => '0', 'wcacc' => '1', // autodeletion 'auto_trash' => 'change_status', // do_nothing | change_status | hard_delete_and_log 'auto_delete' => 'change_status', // do_nothing | change_status | hard_delete_and_log 'enable_woo_status_mapping' => 1, );
projects/plugins/crm/modules/woo-sync/includes/class-woo-sync-woo-admin-integration.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * WooSync: Woo Admin class * Collects CRM additions to the WooCommerce backend UI */ namespace Automattic\JetpackCRM; // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; /** * WooSync Woo Admin class */ class Woo_Sync_Woo_Admin_Integration { /** * The single instance of the class. */ protected static $_instance = null; /** * Setup WooSync * Note: This will effectively fire after core settings and modules loaded * ... effectively on tail end of `init` */ public function __construct() { // Initialise Hooks $this->init_hooks(); } /** * Main Class Instance. * * Ensures only one instance of Woo_Sync_Woo_Admin_Integration is loaded or can be loaded. * * @since 2.0 * @static * @return Woo_Sync_Woo_Admin_Integration main instance */ public static function instance() { if ( is_null( self::$_instance ) ) { self::$_instance = new self(); } return self::$_instance; } /** * Initialise Hooks */ private function init_hooks() { global $zbs; // Abort if Woo isn't active. if ( ! $zbs->woocommerce_is_active() ) { return; } // Hook into Woo orders listview. if ( jpcrm_woosync_is_hpos_enabled() ) { // These hooks are available as of Woo 7.3.0 and are required for HPOS. add_filter( 'woocommerce_shop_order_list_table_columns', array( $this, 'append_orders_column' ) ); add_action( 'woocommerce_shop_order_list_table_custom_column', array( $this, 'render_orders_column_content' ), 20, 2 ); } else { add_filter( 'manage_edit-shop_order_columns', array( $this, 'append_orders_column' ) ); add_action( 'manage_shop_order_posts_custom_column', array( $this, 'render_orders_column_content' ), 20, 2 ); } // Add CRM contact to Woo order page. add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) ); } /** * Add CRM contact column to Woo orders listview. * * @param array $columns Listview columns. */ public function append_orders_column( $columns ) { $rebuilt_columns = array(); // Inserting columns to a specific location foreach ( $columns as $key => $column ) { $rebuilt_columns[ $key ] = $column; if ( $key === 'order_status' ) { // Inserting after "Status" column $rebuilt_columns['jpcrm_contact'] = __( 'CRM Contact', 'zero-bs-crm' ); } } return $rebuilt_columns; } /** * HTML rendering of our custom orders view column content * * @param string $column Column slug. * @param int $order_or_post_id Order post ID. */ public function render_orders_column_content( $column, $order_or_post_id ) { global $zbs; switch ( $column ) { case 'jpcrm_contact': if ( jpcrm_woosync_is_hpos_enabled() ) { $order = $order_or_post_id; } else { $order = wc_get_order( $order_or_post_id ); } $email = $order->get_billing_email(); if ( empty( $email ) ) { return; } $contact_id = zeroBS_getCustomerIDWithEmail( $email ); if ( $contact_id > 0 ) { $url = jpcrm_esc_link( 'view', $contact_id, 'zerobs_customer' ); $label = __( 'View Contact', 'zero-bs-crm' ); $class = 'primary'; } else { $url = admin_url( 'admin.php?page=' . $zbs->modules->woosync->slugs['hub'] ); $label = __( 'Add Contact', 'zero-bs-crm' ); $class = 'secondary'; } ?> <div class="zbs-actions"> <a class="button button-<?php echo esc_attr( $class ); ?>" href="<?php echo esc_url( $url ); ?>"><?php echo esc_html( $label ); ?></a> </div> <?php break; } } /** * Add CRM meta boxes to Woo pages */ public function add_meta_boxes() { // Gather Woo screens where we'll want to add metaboxes. $screens_to_use = array(); $woo_screens = array( 'shop_order', 'shop_subscription' ); foreach ( $woo_screens as $woo_screen ) { $potential_screen = wc_get_page_screen_id( $woo_screen ); if ( ! empty( $potential_screen ) ) { $screens_to_use[] = $potential_screen; } } // Currently if Woo is active we should at least have the orders page, but that could change. if ( ! empty( $screens_to_use ) ) { add_meta_box( 'zbs_crm_contact', __( 'CRM Contact', 'zero-bs-crm' ), array( $this, 'render_woo_order_page_contact_box' ), $screens_to_use, 'side', 'core' ); } } /** * Renders HTML for contact metabox on Woo pages * * @param WC_Order|\WP_POST $order_or_post Order or post. */ public function render_woo_order_page_contact_box( $order_or_post ) { // phpcs:disable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase global $zbs; if ( jpcrm_woosync_is_hpos_enabled() ) { $order = $order_or_post; } else { $order = wc_get_order( $order_or_post->ID ); } $this->render_metabox_styles(); // the customer information pane $email = $order->get_billing_email(); // No billing email found, so render message and return. if ( empty( $email ) ) { ?> <div class="jpcrm-contact-metabox"> <div class="no-crm-contact"> <p style="margin-top:20px;"> <?php esc_html_e( 'Once you save your order to a customer with a billing email, the CRM contact card will display here.', 'zero-bs-crm' ); ?> </p> </div> </div> <?php return; } // retrieve contact id $contact_id = zeroBS_getCustomerIDWithEmail( $email ); // Can't find a contact under that email, so return. if ( $contact_id <= 0 ) { return; } // retrieve contact $crm_contact = $zbs->DAL->contacts->getContact( $contact_id ); $contact_name = $zbs->DAL->contacts->getContactFullNameEtc( $contact_id, $crm_contact, array( false, false ) ); $contact_transaction_count = $zbs->DAL->specific_obj_type_count_for_assignee( $contact_id, ZBS_TYPE_TRANSACTION, ZBS_TYPE_CONTACT ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase // check avatar mode $avatar = ''; $avatar_mode = zeroBSCRM_getSetting( 'avatarmode' ); if ( $avatar_mode !== 3 ) { $avatar = zeroBS_customerAvatarHTML( $contact_id, $crm_contact, 100, 'ui small image centered' ); } ?> <div class="jpcrm-contact-metabox"> <?php echo $avatar; /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped */ ?> <div id="panel-name"><span class="jpcrm-name"><?php echo esc_html( $contact_name ); ?></span></div> <div id="panel-status" class="ui label status <?php echo esc_attr( strtolower( $crm_contact['status'] ) ); ?>"> <?php echo esc_html( $crm_contact['status'] ); ?> </div> <div> <?php echo esc_html( zeroBSCRM_prettifyLongInts( $contact_transaction_count ) . ' ' . ( $contact_transaction_count > 1 ? __( 'Transactions', 'zero-bs-crm' ) : __( 'Transaction', 'zero-bs-crm' ) ) ); ?> </div> <div class="panel-left-info cust-email"> <i class="ui icon envelope outline"></i> <span class="panel-customer-email"><?php echo esc_html( $email ); ?></span> </div> <div class="panel-edit-contact"> <a class="view-contact-link button button-primary" href="<?php echo esc_url( jpcrm_esc_link( 'view', $contact_id, 'zerobs_customer' ) ); ?>"><?php echo esc_html__( 'View Contact', 'zero-bs-crm' ); ?></a> </div> </div> <?php // phpcs:enable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase } /** * Renders metabox styles. * * It'd be better to move this to its own file, but putting it here for now. */ public function render_metabox_styles() { ?> <style> .jpcrm-contact-metabox{ margin: 20px 0; text-align:center; } .zbs-custom-avatar{ border-radius: 50% !important; max-width:80px; text-align:center; padding:10px; } .view-contact-link{ margin-top:10px; } .cust-email{ padding-bottom:10px; padding-top:10px; color: black; font-weight:700; } .jpcrm-name{ font-weight:900; } .status{ margin-left: 0; padding: 0.3em 0.78571429em; display: inline-block; border-radius: 5px; margin-top: 3px; margin-bottom: 3px; font-size: 12px !important; font-weight: 500; background-color: #ccc; } .customer{ background-color: #21BA45 !important; border-color: #21BA45 !important; color: #FFFFFF !important; } </style> <?php } }
projects/plugins/crm/modules/woo-sync/includes/class-woo-sync-segment-conditions.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * WooSync: Segment Conditions * */ namespace Automattic\JetpackCRM; // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; /** * WooSync Segment Conditions class */ class Woo_Sync_Segment_Conditions { /** * An array of our segment condition class instances */ public $conditions = array(); /** * The single instance of the class. */ protected static $_instance = null; /** * Setup Segment conditions */ public function __construct( ) { // Require segment conditions when jpcrm is ready add_action( 'jpcrm_post_init', array( $this, 'require_segment_conditions'), 1 ); } /** * Main Class Instance. * * Ensures only one instance of Woo_Sync_Segment_Conditions is loaded or can be loaded. * * @since 2.0 * @static * @see * @return Woo_Sync_Segment_Conditions main instance */ public static function instance() { if ( is_null( self::$_instance ) ) { self::$_instance = new self(); } return self::$_instance; } /** * Require segment conditions */ public function require_segment_conditions(){ // is woo customer require_once( JPCRM_WOO_SYNC_ROOT_PATH . 'includes/segment-conditions/class-segment-condition-woo-customer.php' ); $this->conditions['is_woo_customer'] = new \Segment_Condition_Woo_Customer(); // woo order count require_once( JPCRM_WOO_SYNC_ROOT_PATH . 'includes/segment-conditions/class-segment-condition-woo-order-count.php' ); $this->conditions['woo_order_count'] = new \Segment_Condition_Woo_Order_Count(); } }
projects/plugins/crm/modules/woo-sync/includes/class-woo-sync.php
<?php // phpcs:disable /*! * Jetpack CRM * https://jetpackcrm.com * * WooSync * */ namespace Automattic\JetpackCRM; // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; #} the WooCommerce API use Automattic\WooCommerce\Client; use Automattic\WooCommerce\HttpClient\HttpClientException; /** * WooSync class */ class Woo_Sync { /** * Extension version. * * @var string */ public $version = '5.0'; /** * Extension settings key * * @var string */ public $config_key = 'woosync'; /** * Extension name. * * @var string */ public $ext_name = 'WooSync'; /** * Maximum number of WooCommerce products to retrieve into CRM product index * * @var int */ public $max_woo_product_index = 100; /** * Settings object * * @var \WHWPConfigExtensionsLib | null */ public $settings = null; /** * Show extension settings tab * * @var string */ public $settings_tab = true; /** * Feature class object: Background Sync * * @var Woo_Sync_Background_Sync | null */ public $background_sync = null; /** * Feature class object: Contact Tabs * * @var Woo_Sync_Contact_Tabs | null */ public $contact_tabs = null; /** * Feature class object: My Account Integration * * @var Woo_Sync_My_Account_Integration | null */ public $my_account = null; /** * Feature class object: Woo Admin UI modifications * * @var Woo_Sync_Woo_Admin_Integration | null */ public $woo_ui = null; /** * Feature class object: WooSync Segment Conditions * * @var Woo_Sync_Segment_Conditions | null */ public $segment_conditions = null; /** * Where true get_active_sync_sites() won't automatically try to add a local site when there isn't one already (e.g. on migration 5.2) */ public $skip_local_woo_check = false; /** * The single instance of the class. */ protected static $_instance = null; /** * Slugs for internal pages * * @var array() */ public $slugs = array( 'hub' => 'woo-sync-hub', 'settings' => 'woosync', 'settings_connections' => 'connections', 'settings_connection_edit' => 'connection_edit', ); /** * URLs that the Woo module uses * * @var array() */ public $urls = array( 'kb-woo-api-keys' => 'https://kb.jetpackcrm.com/knowledge-base/getting-your-woocommerce-api-key-and-secret/', 'kb-woo-map-status' => 'https://kb.jetpackcrm.com/knowledge-base/woosync-imported-all-customers-as-lead-status/', ); /** * Setup WooSync * Note: This will effectively fire after core settings and modules loaded * ... effectively on tail end of `init` */ public function __construct( ) { // Definitions $this->definitions(); // Initialise endpoints $this->init_endpoints(); // Initialise Settings $this->init_settings(); // Initialise Features $this->init_features(); // Run migrations (if any) $this->run_migrations(); // Initialise Hooks $this->init_hooks(); // Autoload page AJAX $this->load_ajax(); // Register frontend/backend styles and scripts $this->register_styles_scripts(); } /** * Main Class Instance. * * Ensures only one instance of Woo_Sync is loaded or can be loaded. * * @since 2.0 * @static * @see * @return Woo_Sync main instance */ public static function instance() { if ( is_null( self::$_instance ) ) { self::$_instance = new self(); } return self::$_instance; } /** * Define any key vars. */ private function definitions(){ define( 'JPCRM_WOO_SYNC_MODE_LOCAL', 0 ); define( 'JPCRM_WOO_SYNC_MODE_API', 1 ); } /** * Initialise endpoints * (previously on `init`) */ private function init_endpoints( ) { add_rewrite_endpoint('invoices', EP_PAGES ); } /** * Initialise Settings */ private function init_settings( ) { $this->settings = new \WHWPConfigExtensionsLib( $this->config_key, $this->default_settings() ); } /** * Retrieve Settings */ public function get_settings() { return $this->settings->getAll(); } /** * Retrieve WooCommerce Order statuses */ public function get_woo_order_statuses() { $woo_order_statuses = array( 'pending' => __( 'Pending', 'zero-bs-crm' ), 'processing' => __( 'Processing', 'zero-bs-crm' ), 'on-hold' => __( 'On hold', 'zero-bs-crm' ), 'completed' => __( 'Completed', 'zero-bs-crm' ), 'cancelled' => __( 'Cancelled', 'zero-bs-crm' ), 'refunded' => __( 'Refunded', 'zero-bs-crm' ), 'failed' => __( 'Failed', 'zero-bs-crm' ), 'checkout-draft' => __( 'Draft', 'zero-bs-crm' ), ); return apply_filters( 'zbs-woo-additional-status', $woo_order_statuses ); } /** * Retrieve default mapped order status for a given object type * * @param int $obj_type_id Object type (e.g. ZBS_TYPE_CONTACT, ZBS_TYPE_INVOICE, or ZBS_TYPE_TRANSACTION). * @param str $order_status Woo order status. * * @return str|bool Status string to use for object */ public function get_default_status_for_order_obj( $obj_type_id, $order_status ) { global $zbs; $status = false; if ( $obj_type_id === ZBS_TYPE_CONTACT ) { // default contact status is configured in CRM settings $status = $zbs->settings->get( 'defaultstatus' ); } elseif ( $obj_type_id === ZBS_TYPE_INVOICE ) { // reasonable default paid mapping based on Woo status descriptions: // https://woocommerce.com/document/managing-orders/#order-statuses $paid_statuses = array( 'completed', 'processing', ); if ( in_array( $order_status, $paid_statuses, true ) ) { $status = 'Paid'; } elseif ( $order_status === 'checkout-draft' ) { $status = 'Draft'; } else { $status = 'Unpaid'; } } elseif ( $obj_type_id === ZBS_TYPE_TRANSACTION ) { // note that transaction statuses aren't translated, as they're user-configurable if ( $order_status === 'on-hold' ) { // weird legacy mapping fix $status = 'Hold'; } elseif ( $order_status === 'checkout-draft' ) { // for lack of a better status $status = 'Draft'; } else { // default transaction status is the same as the Woo order status $status = ucfirst( $order_status ); } } return $status; } /** * Retrieve available WooCommerce Order mapping to different CRM fields. * This mapping is stored in the settings in the settings, more specifically * in $settings[ $type_prefix . $woo_order_status_key ]. * * @return array Array with mapping types for contacts, invoices and transactions. */ public function get_woo_order_mapping_types() { $contact_statuses = zeroBSCRM_getCustomerStatuses( true ); $invoice_statuses = zeroBSCRM_getInvoicesStatuses(); $transaction_statuses = zeroBSCRM_getTransactionsStatuses( true ); return array( 'contact' => array( 'label' => __( 'Contact status', 'zero-bs-crm' ), 'prefix' => 'order_contact_map_', 'statuses' => $contact_statuses, ), 'invoice' => array( 'label' => __( 'Invoice status', 'zero-bs-crm' ), 'prefix' => 'order_invoice_map_', 'statuses' => $invoice_statuses, ), 'transaction' => array( 'label' => __( 'Transaction status', 'zero-bs-crm' ), 'prefix' => 'order_transaction_map_', 'statuses' => $transaction_statuses, ), ); } /** * Initialise Hooks */ private function init_hooks( ) { // Add settings tab add_filter( 'zbs_settings_tabs', array( $this, 'add_settings_tab' ) ); // Menus: // Adds Tools menu subitem add_filter( 'zbs-tools-menu', array( $this, 'add_tools_menu_sub_item_link' ) ); // Learn menu add_action( 'wp_after_admin_bar_render', array( $this, 'render_learn_menu'), 12 ); // Admin menu add_filter( 'zbs_menu_wpmenu', array( $this, 'add_wp_pages' ), 10, 1 ); // JPCRM effecting: // Add Woo related info to CRM external source infobox add_filter( 'zbs_external_source_infobox_line', array( $this, 'override_crm_external_source_infobox' ), 10, 2 ); // Pay invoice via WooCommerce checkout button add_filter( 'zbs_woo_pay_invoice', array( $this, 'render_pay_via_woo_checkout_button' ), 20 ); // Add listview filters. add_filter( 'jpcrm_listview_filters', array( $this, 'add_listview_filters' ) ); // Hook in to Contact, Invoice, and Transaction query generation to support quickfilter add_filter( 'jpcrm_contact_query_quickfilter', array( $this, 'contact_query_quickfilter_addition' ), 10, 2 ); add_filter( 'jpcrm_invoice_query_quickfilter', array( $this, 'invoice_query_quickfilter_addition' ), 10, 2 ); add_filter( 'jpcrm_transaction_query_quickfilter', array( $this, 'transaction_query_quickfilter_addition' ), 10, 2 ); // Hook in to new contact log creation and add string manipulation add_filter( 'jpcrm_new_contact_log', array( $this, 'new_contact_log_override' ), 10, 3 ); // Product index // #follow-on-refinements // add_filter( 'zbs_invpro_productindex', array( $this, 'append_woo_products_to_crm_product_index' ), 10, 1 ); // Add our action to the stack (for OAuth like connecting to Woo external stores) add_filter( 'jpcrm_listener_actions', array( $this, 'add_listener_action' ), 1 ); // set action for endpoint listener to fire, so we can catch oauth requests (if any) add_action( 'jpcrm_listener_woosync_add_store', array( $this, 'catch_add_store_auth'), 10 ); // add webhook actions add_filter( 'jpcrm_api_valid_webhook_actions', array( $this, 'add_webhook_actions' ) ); // add a position to the WooSync segment condition category positions array add_filter( 'jpcrm_segment_condition_category_positions', array( $this, 'add_segments_condition_category_positions' ) ); } /** * Initialise Features */ private function init_features( ) { // Contact Tabs if ( zeroBSCRM_is_customer_view_page() ) { require_once JPCRM_WOO_SYNC_ROOT_PATH . 'includes/jpcrm-woo-sync-contact-tabs.php'; $this->contact_tabs = Woo_Sync_Contact_Tabs::instance(); wp_enqueue_style( 'jpcrm-woo-sync-contact-tabs', plugins_url( '/css/jpcrm-woo-sync-contact-tabs.css', JPCRM_WOO_SYNC_ROOT_FILE ) ); } // Settings page if ( jpcrm_is_settings_page() ) { $this->load_admin_page( 'settings/router' ); } // Hub page if ( $this->is_hub_page() ) { $this->load_admin_page( 'woo-sync-hub/main' ); } // Background sync require_once JPCRM_WOO_SYNC_ROOT_PATH . 'includes/class-woo-sync-background-sync.php'; $this->background_sync = Woo_Sync_Background_Sync::instance(); // My account require_once JPCRM_WOO_SYNC_ROOT_PATH . 'includes/class-woo-sync-my-account-integration.php'; $this->my_account = Woo_Sync_My_Account_Integration::instance(); // WooCommerce UI additions require_once JPCRM_WOO_SYNC_ROOT_PATH . 'includes/class-woo-sync-woo-admin-integration.php'; $this->woo_ui = Woo_Sync_Woo_Admin_Integration::instance(); // Segment conditions require_once( JPCRM_WOO_SYNC_ROOT_PATH . 'includes/class-woo-sync-segment-conditions.php' ); $this->segment_conditions = Woo_Sync_Segment_Conditions::instance(); } /** * Autoload page AJAX */ private function load_ajax( ) { $admin_page_directories = jpcrm_get_directories( JPCRM_WOO_SYNC_ROOT_PATH . 'admin' ); if ( is_array( $admin_page_directories ) ){ foreach ( $admin_page_directories as $directory ){ $files = scandir( JPCRM_WOO_SYNC_ROOT_PATH . 'admin/' . $directory ); if ( is_array( $files ) ){ foreach ( $files as $file ){ // find files `*.ajax.*` if ( strrpos( $file, '.ajax.' ) > 0 ){ // load it require_once( JPCRM_WOO_SYNC_ROOT_PATH . 'admin/' . $directory . '/' . $file ); } } } } } } /** * Include WooCommerce REST API (well, in fact, autoload /vendor) */ public function include_woocommerce_rest_api(){ require_once ZEROBSCRM_PATH . 'vendor/autoload.php'; } /** * Adds items to listview filter using `jpcrm_listview_filters` hook. * * @param array $listview_filters Listview filters. */ public function add_listview_filters( $listview_filters ) { $listview_filters[ZBS_TYPE_CONTACT]['general']['woo_customer'] = __( 'WooCommerce', 'zero-bs-crm' ); $listview_filters[ZBS_TYPE_TRANSACTION]['general']['woo_transaction'] = __( 'WooCommerce', 'zero-bs-crm' ); $listview_filters[ZBS_TYPE_INVOICE]['general']['woo_invoice'] = __( 'WooCommerce', 'zero-bs-crm' ); return $listview_filters; } /** * Hook in to Contact query generation and add the quickfilter * (Hooked into `jpcrm_contact_query_quickfilter`) */ public function contact_query_quickfilter_addition( $wheres, $quick_filter_key ) { global $ZBSCRM_t; // is a Woo customer? (Could be copied/generalised for other ext sources) if ( $quick_filter_key == 'woo_customer' ){ $wheres['is_woo_customer'] = array( 'ID','IN', '(SELECT DISTINCT zbss_objid FROM ' . $ZBSCRM_t['externalsources'] . " WHERE zbss_objtype = " . ZBS_TYPE_CONTACT . " AND zbss_source = %s)", array( 'woo' ) ); } return $wheres; } /** * Hook in to Invoice query generation and add the quickfilter * (Hooked into `jpcrm_invoice_query_quickfilter`) */ public function invoice_query_quickfilter_addition( $wheres, $quick_filter_key ) { global $ZBSCRM_t; // is a Woo customer? (Could be copied/generalised for other ext sources) if ( $quick_filter_key == 'woo_invoice' ){ $wheres['is_woo_invoice'] = array( 'ID','IN', '(SELECT DISTINCT zbss_objid FROM ' . $ZBSCRM_t['externalsources'] . " WHERE zbss_objtype = " . ZBS_TYPE_INVOICE . " AND zbss_source = %s)", array( 'woo' ) ); } return $wheres; } /** * Hook in to Transaction query generation and add the quickfilter * (Hooked into `jpcrm_transaction_query_quickfilter`) */ public function transaction_query_quickfilter_addition( $wheres, $quick_filter_key ) { global $ZBSCRM_t; // is a Woo customer? (Could be copied/generalised for other ext sources) if ( $quick_filter_key == 'woo_transaction' ){ $wheres['is_woo_transaction'] = array( 'ID','IN', '(SELECT DISTINCT zbss_objid FROM ' . $ZBSCRM_t['externalsources'] . " WHERE zbss_objtype = " . ZBS_TYPE_TRANSACTION . " AND zbss_source = %s)", array( 'woo' ) ); } return $wheres; } /** * Hook in to new contact log creation and add string manipulation * (Hooked into `jpcrm_new_contact_log`) */ public function new_contact_log_override( $note_long_description, $source_key, $uid ) { if ( $source_key == 'woo' ){ if ( !empty( $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>'; } } return $note_long_description; } /** * Register styles & scripts * (previously on `init`) */ public function register_styles_scripts() { // WooCommerce My Account wp_register_style( 'jpcrm-woo-sync-my-account', plugins_url( '/css/jpcrm-woo-sync-my-account'.wp_scripts_get_suffix().'.css', JPCRM_WOO_SYNC_ROOT_FILE ) ); wp_register_style( 'jpcrm-woo-sync-fa', plugins_url( '/css/font-awesome.min.css', ZBS_ROOTFILE ) ); } /** * Filter settings tabs, adding this extension * (previously `load_settings_tab`) * * @param array $tabs */ public function add_settings_tab( $tabs ){ // Append our tab if enabled if ( $this->settings_tab ) { $main_tab = $this->slugs['settings']; $connection_tab = $this->slugs['settings_connections']; $tabs[ $main_tab ] = array( 'name' => $this->ext_name, 'ico' => '', 'submenu' => array( "{$main_tab}&subtab={$connection_tab}" => array( 'name' => __( 'Store Connections', 'zero-bs-crm'), 'ico' => '', ), ), ); } return $tabs; } /** * Return default settings */ public function default_settings() { return require( JPCRM_WOO_SYNC_ROOT_PATH . 'includes/jpcrm-woo-sync-default-settings.php' ); } /** * Main page addition */ function add_wp_pages( $menu_array=array() ) { // add a submenu item to main CRM menu $menu_array['jpcrm']['subitems']['woosync'] = array( 'title' => 'WooSync', 'url' => $this->slugs['hub'], 'perms' => 'admin_zerobs_manage_options', 'order' => 10, 'wpposition' => 10, 'callback' => 'jpcrm_woosync_render_hub_page', 'stylefuncs' => array( 'zeroBSCRM_global_admin_styles', 'jpcrm_woosync_hub_page_styles_scripts' ), ); return $menu_array; } /** * Adds Tools menu sub item */ public function add_tools_menu_sub_item_link( $menu_items ) { global $zbs; $menu_items[] = '<a href="' . zeroBSCRM_getAdminURL( $this->slugs['hub'] ) . '" class="item"><i class="shopping cart icon"></i> WooSync</a>'; return $menu_items; } /** * Output learn menu */ public function render_learn_menu(){ if ( $this->is_hub_page() ){ global $zbs; $learn_content = '<p>' . __( "Here you can import your WooCommerce data. It's important that you have setup the extension correctly, including setting the order statuses to map to contact statuses.", 'zerobscrm' ) . '</p>'; $learn_content .= '<p>' . __( "If you do not set this up, all WooCommerce orders will be imported as contacts with default status (Lead). Hit import to get started or learn more about how to setup the extension.", 'zero-bs-crm' ) . '</p>'; $image_url = JPCRM_WOO_SYNC_IMAGE_URL . 'learn/learn-woo-sync.png'; // output $zbs->learn_menu->render_generic_learn_menu( 'WooCommerce Sync', '', '', true, __( "Import WooCommerce History", "zerobscrm" ), $learn_content, $zbs->urls['kb-woosync-home'], $image_url, false, '' ); } } /** * Load the file for a given page * * @param string $page_name (e.g. `settings/main`) */ public function load_admin_page( $page_name ){ jpcrm_load_admin_page( $page_name, JPCRM_WOO_SYNC_ROOT_PATH ); } /** * Append/override Woo related info to CRM external source infobox * (previously `transaction_to_order_link`) * * @param string $html * @param array $external_source */ public function override_crm_external_source_infobox( $html, $external_source ) { global $zbs; if ( $external_source['source'] == 'woo' ){ // retrieve origin info (where available) $origin_str = ''; $origin_detail = $zbs->DAL->hydrate_origin( $external_source['origin'] ); if ( is_array( $origin_detail ) && isset( $origin_detail['origin_type'] ) && $origin_detail['origin_type'] == 'domain' ){ // clean the domain (at this point strip protocols) $clean_domain = $zbs->DAL->clean_external_source_domain_string( $origin_detail['origin'] ); $origin_str = __( ' from ', 'zero-bs-crm' ) . '<span class="jpcrm-ext-source-domain">' . $clean_domain . '</span>'; } $woo_order_link = admin_url( 'post.php?post=' . $external_source['unique_id'] . '&action=edit' ); // get label, which is usually the order ID but may be a custom order number $woo_order_link_label = $this->get_order_number_from_object_meta( $external_source['objtype'], $external_source['objid'], $external_source['unique_id'] ); switch ( $external_source['objtype'] ){ case ZBS_TYPE_INVOICE: case ZBS_TYPE_TRANSACTION: // local (can show order link) or external (can't show order link) if ( $this->is_order_from_local_by_external_source( $external_source ) ){ $html = '<div class="jpcrm-ext-source-woo-order">' . __( "Order", 'zero-bs-crm' ) . ' <span class="jpcrm-ext-source-uid">#' . $woo_order_link_label . '</span><a class="compact ui mini button right floated" href="' . esc_url( $woo_order_link ) . '" target="_blank">' . __( 'View Order', 'zero-bs-crm' ) . '</a></div>'; } else { $html = '<div class="jpcrm-ext-source-woo-order">' . __( "Order", 'zero-bs-crm' ) . ' <span class="jpcrm-ext-source-uid">#' . $woo_order_link_label . '</span>' . $origin_str . '</div>'; } break; case ZBS_TYPE_CONTACT: case ZBS_TYPE_COMPANY: // local (can show order link) or external (can't show order link) if ( $this->is_order_from_local_by_external_source( $external_source ) ){ $html = '<div class="jpcrm-ext-source-woo-order">' . __( "Order", 'zero-bs-crm' ) . ' <span class="jpcrm-ext-source-uid">#' . $woo_order_link_label . '</span><a class="compact ui mini button right floated" href="' . esc_url( $woo_order_link ) . '" target="_blank">' . __( 'View Order', 'zero-bs-crm' ) . '</a></div>'; } else { $html = '<div class="jpcrm-ext-source-woo-order">' . __( "Order", 'zero-bs-crm' ) . ' <span class="jpcrm-ext-source-uid">#' . $woo_order_link_label . '</span>' . $origin_str . '</div>'; } break; } } return $html; } /** * This checks an external source for 'origin', and if that matches local site url, returns true * ... if origin is not recorded, this falls back to current setup mode (for users data pre refactor with origin (~v5)) * * @param array $external_source */ public function is_order_from_local_by_external_source( $external_source ) { global $zbs; if ( is_array( $external_source ) && isset( $external_source['origin'] ) ){ $origin_detail = $zbs->DAL->hydrate_origin( $external_source['origin'] ); if ( $origin_detail['origin_type'] == 'domain' ){ if ( $origin_detail['origin'] == site_url() ){ return true; } } } else { // no origin, must be a pre-v5 recorded order } return false; } /** * Return object number retrieved from an object meta (which can be different from an object ID) * * @param int $obj_type_id * @param int $obj_id * @param int $order_post_id */ public function get_order_number_from_object_meta( $obj_type_id, $obj_id, $order_post_id ) { global $zbs; $order_num = $zbs->DAL->meta( $obj_type_id, $obj_id, 'extra_order_num' ); if ( !$order_num ) { $order_num = $order_post_id; } return $order_num; } /** * Pay for invoice via WooCommerce checkout * Intercepts pay button logic and adds pay via woo button * Does not do so for API-imported orders * * @param int $invoice_id */ public function render_pay_via_woo_checkout_button( $invoice_id = -1 ) { global $zbs; // We can't generate a Woo payment button if WooCommerce isn't active if ( ! $zbs->woocommerce_is_active() ) { // show an error if an invoice admin if ( zeroBSCRM_permsInvoices() ) { $admin_alert = '<b>' . esc_html__( 'Admin note', 'zero-bs-crm' ) . ':</b> '; $admin_alert .= esc_html__( 'Please enable WooCommerce to show the payment link here.', 'zero-bs-crm' ); return $admin_alert; } else { return false; } } // blatantly wrong invoice ID if ( $invoice_id <= 0 ) { return false; } $api = $this->get_invoice_meta( $invoice_id, 'api' ); $order_post_id = $this->get_invoice_meta( $invoice_id, 'order_post_id' ); // intercept pay button and set to pay via woo checkout if ( empty( $api ) && ! empty( $order_post_id ) ) { remove_filter( 'invoicing_pro_paypal_button', 'zeroBSCRM_paypalbutton', 1 ); remove_filter( 'invoicing_pro_stripe_button', 'zeroBSCRM_stripebutton', 1 ); $order = wc_get_order( $order_post_id ); // Order no longer exists (probably deleted). if ( ! $order ) { // show an error if an invoice admin if ( zeroBSCRM_permsInvoices() ) { $admin_alert = '<b>' . esc_html__( 'Admin note', 'zero-bs-crm' ) . ':</b> '; $admin_alert .= esc_html__( 'WooCommerce order no longer exists, so unable to generate payment link.', 'zero-bs-crm' ); return $admin_alert; } else { return false; } } $payment_page = $order->get_checkout_payment_url(); $res = '<h3>' . __( 'Pay Invoice', 'zero-bs-crm' ) . '</h3>'; $res .= '<a href="' . esc_url( $payment_page ) . '" class="ui button btn">' . __( 'Pay Now', 'zero-bs-crm' ) . '</a>'; return $res; } return $invoice_id; } /** * Append WooCommerce products to CRM product index (used on invoice editor) * Applied via filter `zbs_invpro_productindex` * * This is not HPOS-friendly and will need a rework prior to enabling. * * @param array $crm_product_index */ public function append_woo_products_to_crm_product_index( $crm_product_index ){ // Get Sync sites, and cycle through them $sync_sites = $this->get_active_sync_sites(); foreach ( $sync_sites as $site_key => $site_info ){ if ( $site_info['mode'] == JPCRM_WOO_SYNC_MODE_LOCAL ){ // Local store $woo_product_index = $this->get_product_list_via_local_store(); } else { // From API-derived store $woo_product_index = $this->get_product_list_via_api(); } // append to array if ( is_array( $woo_product_index ) && count( $woo_product_index ) > 0 ){ $crm_product_index = array_merge( $woo_product_index, $crm_product_index ); } } return $crm_product_index; } /** * Retrieve WooCommerce product list via API * * @param string site connection key * */ public function get_product_list_via_api( $site_key ){ $woo_product_index = array(); try { // use Woo client library $woocommerce = $this->get_woocommerce_client( $site_key ); // Set params $params = array( 'per_page' => $this->max_woo_product_index ); $params = apply_filters( 'zbs-woo-product-list', $params ); $product_list = $woocommerce->get( 'products', $params ); // cycle through & simplify to match product index foreach ( $product_list as $product_data ){ $index_line = new \stdClass; $index_line->ID = $product_data->id; $index_line->zbsprod_name = $product_data->name; $index_line->zbsprod_desc = wp_strip_all_tags($product_data->short_description); $index_line->zbsprod_price = $product_data->price; $woo_product_index[] = $index_line; } } catch ( HttpClientException $e ) { echo "<div class='ui message red'><i class='ui icon exclamation circle'></i> WooCommerce Client Error: " . print_r( $e->getMessage(), true ) . "</div>"; } return $woo_product_index; } /** * Retrieve WooCommerce product list via Local store */ public function get_product_list_via_local_store(){ $woo_product_index = array(); if ( class_exists( 'WC_Product_Query' ) ){ $products = wc_get_products( array( 'limit' => $this->max_woo_product_index, )); foreach( $products as $product ){ // retrieve variations $args = array( 'post_type' => 'product_variation', 'post_status' => array( 'private', 'publish' ), 'numberposts' => -1, 'orderby' => 'menu_order', 'order' => 'asc', 'post_parent' => $product->get_id() ); $variations = get_posts( $args ); foreach ( $variations as $variation ) { $variable_product = wc_get_product( $variation->ID ); // add variation $index_line = new \stdClass; $index_line->ID = $variation->ID; $index_line->zbsprod_name = $variable_product->get_name(); $index_line->zbsprod_desc = wp_strip_all_tags( $variable_product->get_short_description() ); $index_line->zbsprod_price = $variable_product->get_price(); $woo_product_index[] = $index_line; } // Add main product $index_line = new \stdClass; $index_line->ID = $product->get_id(); $index_line->zbsprod_name = $product->get_name(); $index_line->zbsprod_desc = wp_strip_all_tags($product->get_short_description()); $index_line->zbsprod_price = $product->get_price(); $woo_product_index[] = $index_line; } } return $woo_product_index; } /** * Returns total order count for local store */ public function get_order_count_via_local_store() { // retrieve generic page of orders to get total $args = array( 'limit' => 1, 'paged' => 1, 'paginate' => true, ); $orders = wc_get_orders( $args ); return $orders->total; } /** * Returns the total number of woosync imported contacts present in CRM */ public function get_crm_woo_contact_count() { global $zbs; return $zbs->DAL->contacts->getContacts( array( 'externalSource' => 'woo', 'count' => true, 'ignoreowner' => true, ) ); } /** * Returns the total number of woosync imported transactions present in CRM */ public function get_crm_woo_transaction_count() { global $zbs; return $zbs->DAL->transactions->getTransactions( array( 'externalSource' => 'woo', 'count' => true, 'ignoreowner' => true, ) ); } /** * Returns the total value of woosync imported transactions present in CRM */ public function get_crm_woo_transaction_total() { global $zbs; return $zbs->DAL->transactions->getTransactions( array( // this may need status filtering. For now left as total total (MVP) 'externalSource' => 'woo', 'total' => true, 'ignoreowner' => true, ) ); } /** * Returns the most recent woo order crm transaction */ public function get_crm_woo_latest_woo_transaction() { global $zbs; $orders = $zbs->DAL->transactions->getTransactions( array( 'externalSource' => 'woo', 'sortByField' => 'date', 'sortOrder' => 'DESC', 'page' => 0, 'perPage' => 1, 'ignoreowner' => true, ) ); if ( is_array( $orders ) && isset( $orders[0] ) && is_array( $orders[0] ) ) { return $orders[0]; } return false; } /** * Returns the a string based on the most recent woo order crm transaction */ public function get_crm_woo_latest_woo_transaction_string() { global $zbs; $latest_synced_transaction = $this->get_crm_woo_latest_woo_transaction(); $latest_synced_transaction_text = ''; if ( is_array( $latest_synced_transaction ) ) { $latest_synced_transaction_text .= '<br />'; // build a 'latest order' string $latest_synced_transaction_text .= __( 'Latest import:', 'zero-bs-crm' ) . ' <a href="' . jpcrm_esc_link( 'edit', $latest_synced_transaction['id'], ZBS_TYPE_TRANSACTION ) . '" target="_blank">' . $latest_synced_transaction['ref'] . '</a> '; if ( !empty( $latest_synced_transaction['title'] ) ) { $latest_synced_transaction_text .= '- ' . $latest_synced_transaction['title'] . ' '; } if ( !empty( $latest_synced_transaction['date_date'] ) ) { $latest_synced_transaction_text .= '(' . $latest_synced_transaction['date_date'] . ') '; } /* skip origin string for now, as we currently only support one origin at a time */ // $origin_str = ''; // $external_sources = $zbs->DAL->getExternalSources( // -1, // array( // 'objectID' => $latest_synced_transaction['id'], // 'objectType' => ZBS_TYPE_TRANSACTION, // 'grouped_by_source' => true, // 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership( ZBS_TYPE_CONTACT ), // ) // ); // if ( isset( $external_sources['woo'] ) ) { // $origin_detail = $zbs->DAL->hydrate_origin( $external_sources['woo'][0]['origin'] ); // $clean_domain = $zbs->DAL->clean_external_source_domain_string( $origin_detail['origin'] ); // $origin_str = __( ' from ', 'zero-bs-crm' ) . $clean_domain; // } // $latest_synced_transaction_text .= $origin_str; } return $latest_synced_transaction_text; } /** * Returns the latest WooSync stats */ public function get_jpcrm_woo_latest_stats() { $last_order_synced = $this->get_crm_woo_latest_woo_transaction_string(); $contacts_synced = zeroBSCRM_prettifyLongInts( $this->get_crm_woo_contact_count() ); $transactions_synced = zeroBSCRM_prettifyLongInts( $this->get_crm_woo_transaction_count() ); $transaction_total = zeroBSCRM_formatCurrency( $this->get_crm_woo_transaction_total( ) ); return array( 'last_order_synced' => $last_order_synced, 'contacts_synced' => $contacts_synced, 'transactions_synced' => $transactions_synced, 'transaction_total' => $transaction_total, ); } /** * Returns a crm transaction based on order num|origin */ public function get_transaction_from_order_num( $order_num, $origin='', $only_id=false ){ global $zbs; $source_args = array( 'externalSource' => 'woo', 'externalSourceUID' => $order_num, 'origin' => $origin, ); if ( $only_id ){ $source_args['onlyID'] = true; } return $zbs->DAL->transactions->getTransaction( -1, $source_args); } /** * Returns settings-saved order prefix * * @param string site connection key * * @return string Order Prefix */ public function get_prefix( $site_key ){ $sync_site = $this->get_active_sync_site( $site_key ); return $sync_site['prefix']; } /** * Returns bool: is the loading page, our hub page * * @return bool hub page */ public function is_hub_page(){ $page = ''; if ( isset( $_GET['page'] ) ){ $page = sanitize_text_field( $_GET['page'] ); } if ( $page == $this->slugs['hub'] ){ return true; } return false; } /** * Processes an error string to make it more user friendly (#legacy) * * @return string $error */ public function process_error( $error ){ // number 1: Invalid JSON = endpoint incorrect... if ( str_contains( $error, 'Invalid JSON returned for' ) ) { return __( 'Error. Your WooCommerce endpoint may be incorrect!', 'zero-bs-crm' ); } return $error; } /** * Returns CRM Invoice meta with a specified key * * @param int $invoice_id * @param string $key * * @return mixed $meta value */ public function get_invoice_meta( $invoice_id, $key = '' ){ global $zbs; return $zbs->DAL->invoices->getInvoiceMeta( $invoice_id, 'extra_' . $key ); } /** * Returns future WooCommerce Bookings against a contact/object * * @param int $objid * * @return array WC Booking objects */ public function get_future_woo_bookings_for_object( $objid = -1 ){ $bookings = array(); if ( class_exists( 'WC_Booking_Data_Store' ) ){ $wp_id = zeroBS_getCustomerWPID( $objid ); if ( $wp_id > 0 ){ $bookings = \WC_Booking_Data_Store::get_bookings_for_user( $wp_id, array( 'orderby' => 'start_date', 'order' => 'ASC', 'date_after' => current_datetime()->setTime( 0, 0, 0, 0 )->getTimestamp() + current_datetime()->getOffset(), // gets the start of the day, respecting the current timezone (getOffset()). ) ); } } return $bookings; } /** * Returns URL to hop to local WooCommerce wp-admin * * @return string URL */ public function get_local_woo_admin_url( ){ return site_url( '/wp-admin/admin.php?page=wc-admin' ); } /** * Returns URL to hop to external WooCommerce wp-admin * * @param string Site URL * @return string URL */ public function get_external_woo_admin_url( $site_url = '' ){ if ( empty( $site_url ) ){ return '#woo-url-error'; } // dumb hard-typed for now, is there a smarter way? return trailingslashit( $site_url ) . 'wp-admin/admin.php?page=wc-admin'; } /** * Returns query string for URL to auth external WooCommerce wp-admin * https://woocommerce.github.io/woocommerce-rest-api-docs/#rest-api-keys * * @param string $domain * * @return string URL query string */ public function get_external_woo_url_for_oauth( $domain='' ){ global $zbs; if ( empty( $domain ) ){ return '#woo-url-error'; } $app_name = sprintf( __( 'CRM: %s', 'zero-bs-crm' ), site_url() ); $return_url = jpcrm_esc_link( $zbs->slugs['settings'] . '&tab=' . $zbs->modules->woosync->slugs['settings'] . '&subtab=' . $this->slugs['settings_connections'] ); ##WLREMOVE $app_name = sprintf( __( 'Jetpack CRM: %s', 'zero-bs-crm' ), site_url() ); ##/WLREMOVE // user_id - we use this with a transient to provide catching service tallying, // given that the credentials sent back to the callback url from woo do not hold the domain $user_id = get_current_user_id(); set_transient( 'jpcrm_woo_connect_token_' . $user_id, $domain, 600 ); // load listener if it's not already loaded $zbs->load_listener(); // build callback url $callback_url = $zbs->listener->get_callback_url( 'woosync_add_store' ); $params = [ 'app_name' => $app_name, 'scope' => 'read', 'user_id' => $user_id, 'return_url' => $return_url, 'callback_url' => $callback_url ]; $query_string = http_build_query( $params ); return $domain . '/wc-auth/v1/authorize?' . $query_string; } /* * Add our listener action to the stack * */ public function add_listener_action( $actions = array() ) { $actions[] = 'woosync_add_store'; return $actions; } /* * Add a catch for our endpoint listener action * Catches Woo site authentications via endpoint listener * */ public function catch_add_store_auth() { // at this point its basically authenticated via endpoint listener $log = array(); $request = file_get_contents('php://input'); $log[] = 'req:'.$request; // should be in json, is it? $params = json_decode( $request ); $log[] = 'params:'.gettype($params); if ( is_object( $params ) && isset( $params->user_id ) ){ $log[] = 'got params'; // could be legit /* e.g. { "key_id": 2, "user_id": "1", "consumer_key": "ck_65bff54d05b71c762bef6c99125fc1ea8570622c", "consumer_secret": "cs_f71faa8a0p0fe014c05fee0eed463cbb10fb61e9", "key_permissions": "read" } */ if ( isset( $params->user_id ) && isset( $params->consumer_key ) && isset( $params->consumer_secret ) && isset( $params->key_permissions ) ){ // basic validation $key = sanitize_text_field( $params->consumer_key ); $secret = sanitize_text_field( $params->consumer_secret ); // no need to check permissions? `read` $log[] = 'got key:'.$key; $log[] = 'got secret:'.$secret; // got keys? if ( !empty( $key ) && !empty( $secret ) ){ $log[] = 'validated'; // see if we have a transient to match this $transient_check_domain = get_transient( 'jpcrm_woo_connect_token_' . $params->user_id ); $log[] = 'transient '.$transient_check_domain . ' (jpcrm_woo_connect_token_' . $params->user_id . ')'; if ( !empty( $transient_check_domain ) ){ $log[] = 'transient checks out '.$transient_check_domain; // run a test on connection (make a function in backgroudn sync?) if ( $this->verify_api_connection( false, $transient_check_domain, $key, $secret ) ){ $log[] = 'connection verified'; // if legit, add as site $new_sync_site = $this->add_sync_site( array( 'mode' => JPCRM_WOO_SYNC_MODE_API, 'domain' => $transient_check_domain, 'key' => $key, 'secret' => $secret, 'prefix' => '', ) ); // add option to flag newly added to UI if ( $new_sync_site ) { set_transient( 'jpcrm_woo_newly_authenticated', $new_sync_site['site_key'], 600 ); } } else { // failed to verify? What to do. $log[] = 'connection NOT verified'; } } } } } $log[] = 'fini'; //update_option('wlogtemp', $log, false); exit(); } /** * Translates a WooCommerce order status to the equivalent settings key * * @param string $obj_type_id Object type ID. * * @return array The associated settings key array [ $order_status => $settings_key ] */ public function woo_order_status_mapping( $obj_type_id ) { global $zbs; // convert to key for use in legacy setting name $obj_type_key = $zbs->DAL->objTypeKey( $obj_type_id ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase $setting_prefix = $this->get_woo_order_mapping_types()[ $obj_type_key ]['prefix']; return array( 'completed' => $setting_prefix . 'wccompleted', 'on-hold' => $setting_prefix . 'wconhold', 'cancelled' => $setting_prefix . 'wccancelled', 'processing' => $setting_prefix . 'wcprocessing', 'refunded' => $setting_prefix . 'wcrefunded', 'failed' => $setting_prefix . 'wcfailed', 'pending' => $setting_prefix . 'wcpending', 'checkout-draft' => $setting_prefix . 'wccheckoutdraft', ); } /** * Translates a WooCommerce order status to a CRM contact resultant status * previously `apply_status` * * @param string $obj_type_id Object type ID. * @param string $order_status Status from WooCommerce order (e.g. 'processing'). * * @return string contact status */ public function translate_order_status_to_obj_status( $obj_type_id, $order_status ) { global $zbs; $settings = $this->get_settings(); // get default object status for given Woo order status $default_status = $this->get_default_status_for_order_obj( $obj_type_id, $order_status ); // if status mapping is disabled, return default status $is_status_mapping_enabled = ( isset( $settings['enable_woo_status_mapping'] ) ? ( (int) $settings['enable_woo_status_mapping'] === 1 ) : true ); if ( ! $is_status_mapping_enabled ) { return $default_status; } // mappings $woo_order_status_mapping = $this->woo_order_status_mapping( $obj_type_id ); if ( ! empty( $settings[ $woo_order_status_mapping[ $order_status ] ] ) && $zbs->DAL->is_valid_obj_status( $obj_type_id, $settings[ $woo_order_status_mapping[ $order_status ] ] ) // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase ) { // there's a valid mapping in settings, so use that return $settings[ $woo_order_status_mapping[ $order_status ] ]; } elseif ( $default_status ) { // there's a default object mapping for this order status, so use that return $default_status; } // use provided order status as fallback status return $order_status; } // =============================================================================== // =========== Connections DAL ================================================ /** * Attempts to retrieve products to validate connection settings * * @param $site_key * * or * * @param $domain * @param $api_key * @param $api_secret * */ public function verify_api_connection( $site_key, $domain='', $api_key='', $api_secret='' ){ // site key or creds? if ( !empty( $site_key ) ){ // retrieve site $sync_site = $this->get_active_sync_site( $site_key ); // remote site? if ( is_array( $sync_site ) && $sync_site['mode'] == JPCRM_WOO_SYNC_MODE_API ){ // Woo client library $woocommerce_client = $this->get_woocommerce_client( $site_key ); } } elseif ( !empty( $domain ) && !empty( $api_key ) && !empty( $api_secret ) ) { // attempt with creds $woocommerce_client = $this->get_woocommerce_client( false, $domain, $api_key, $api_secret ); } // got a client? if ( isset( $woocommerce_client ) ){ try { // Set params $product_list = $woocommerce_client->get( 'products', array( 'per_page' => 1 ) ); // success if no exceptions thrown! if ( is_array( $product_list ) ){ return true; } } catch ( HttpClientException $e ) { //echo "<div class='ui message red'><i class='ui icon exclamation circle'></i> WooCommerce Client Error: " . print_r( $e->getMessage(), true ) . "</div>"; return false; } } return false; } /** * Returns an array of active sites which need syncing ordered by longest since sync * Note: This ignores `paused` state, which should be checked for within these records via the attribute `paused` * * @param string $order_by * */ public function get_active_sync_sites( $order_by = 'last_sync' ){ global $zbs; // retrieve existing $sync_sites = $this->settings->get( 'sync_sites' ); if ( !is_array( $sync_sites ) ){ $sync_sites = array(); } // Add local if present // Catches when a user now has Woo installed but they didn't before, and then adds a sync site for it if ( !$this->skip_local_woo_check && $zbs->woocommerce_is_active() ){ // does it already have a stored record? if ( !isset( $sync_sites['local'] ) ){ // build local sync record $this->add_sync_site( array( 'site_key' => 'local', 'mode' => JPCRM_WOO_SYNC_MODE_LOCAL, 'domain' => site_url(), 'key' => '', 'secret' => '', 'prefix' => '', 'paused' => false, // default to enabled )); // reload sync sites $sync_sites = $this->settings->get( 'sync_sites' ); } } // sorts switch ( $order_by ){ case 'last_sync': uasort( $sync_sites, array( $this, 'compare_sync_sites_for_order_last_sync' ) ); break; } return $sync_sites; } /** * Sort compare function to help order sync_sites */ private function compare_sync_sites_for_order_last_sync( $a, $b ){ return $this->compare_sync_sites_for_order( $a, $b, 'last_sync' ); } /** * Sort compare function to help order sync_sites */ private function compare_sync_sites_for_order( $a, $b, $attribute_key ){ $x = ( isset( $a[ $attribute_key ] ) ? $a[ $attribute_key ] : false ); $y = ( isset( $b[ $attribute_key ] ) ? $b[ $attribute_key ] : false ); return strcmp( $x, $y ); } /** * Retrieve single sync site via key */ public function get_active_sync_site( $site_key = '' ){ // get existing $sync_sites = $this->get_active_sync_sites( 'default' ); if ( isset( $sync_sites[ $site_key ] ) ){ return $sync_sites[ $site_key ]; } return false; } /** * Takes an URL and makes a unique site key slug from it, testing against existing */ public function generate_site_key( $site_url ){ $attempts = 0; $max_attempts = 20; while ( $attempts < $max_attempts ){ $new_key = $this->generate_site_key_string( $site_url ); // seems to exist, append if ( $attempts > 0 ){ $new_key .= '_' . $attempts; } // exists? if ( $this->get_active_sync_site( $new_key ) === false ){ return $new_key; } $attempts++; } return false; } /** * Takes an URL and makes a site key slug from it */ private function generate_site_key_string( $site_url ){ global $zbs; // simplistic replacements $site_url = str_replace( array( 'https', 'http' ), '', $site_url ); $site_url = str_replace( array( '/', '.' ), '_', $site_url ); $site_url = str_replace( '__', '_', $site_url ); // use DAL finally $site_url = $zbs->DAL->makeSlug( $site_url, array(), '_' ); return $site_url; } /** * Add a new Sync Site record */ public function add_sync_site( $args=array() ){ // ============ LOAD ARGS =============== $defaultArgs = array( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase 'site_key' => '', // if none is passed, domain will be used to generate 'mode' => -1, 'domain' => '', 'key' => '', 'secret' => '', 'prefix' => '', 'paused' => false, // if set to non-false site will not sync (typically pass timestamp of time paused) ); 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]; } } } // phpcs:ignore // ============ / LOAD ARGS ============= // get existing (but side-step the woo local check because that can cause an infinite loop) $pre_state = $this->skip_local_woo_check; $this->skip_local_woo_check = true; $this->skip_local_woo_check = $pre_state; // phpcs:disable VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable // basic validation if ( ! in_array( $mode, array( JPCRM_WOO_SYNC_MODE_LOCAL, JPCRM_WOO_SYNC_MODE_API ), true ) ) { return false; } // if no site key, attempt to generate one: if ( empty( $site_key ) ) { if ( $mode === JPCRM_WOO_SYNC_MODE_LOCAL ) { $site_key = 'local'; } elseif ( ! empty( $domain ) ) { $site_key = $this->generate_site_key( $domain ); } else { // external site setup without a domain ¯\_(ツ)_/¯ $site_key = $this->generate_site_key( 'no_domain' ); } $sync_sites = $this->get_active_sync_sites( 'default' ); if ( // error generating key empty( $site_key ) // site key already exists || isset( $sync_sites[ $site_key ] ) // domain already exists || in_array( $domain, array_column( $sync_sites, 'domain' ), true ) ) { return false; } } // add $sync_sites[ $site_key ] = array( 'mode' => $mode, 'domain' => $domain, 'key' => $key, 'secret' => $secret, 'prefix' => $prefix, // tracking 'last_sync_fired' => -1, 'resume_from_page' => 1, 'total_order_count' => 0, 'total_customer_count' => 0, 'first_import_complete' => false, ); // pause, if present if ( $paused ) { $sync_sites[ $site_key ]['paused'] = $paused; } // phpcs:enable VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable // save $this->settings->update( 'sync_sites', $sync_sites ); // add the sitekey (which may have been autogenerated above) and return $sync_sites[ $site_key ]['site_key'] = $site_key; return $sync_sites[ $site_key ]; } /** * Update sync site record */ public function update_sync_site( $args = array() ){ // ============ LOAD ARGS =============== $defaultArgs = array( 'site_key' => '', 'mode' => -1, 'domain' => '', 'key' => '', 'secret' => '', 'prefix' => '', 'last_sync_fired' => -1, 'resume_from_page' => 1, 'total_order_count' => 0, 'total_customer_count' => 0, 'first_import_complete' => false, 'paused' => false, // if set to non-false site will not sync (typically pass timestamp of time paused) // meta 'site_connection_errors' => 0, // counts how many connection errors since last good connection (allows for pausing on 3x errors) ); 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 ============= // get existing $sync_sites = $this->get_active_sync_sites( 'default' ); // basic validation if ( empty( $site_key ) ){ return false; } if ( !in_array( $mode, array( JPCRM_WOO_SYNC_MODE_LOCAL, JPCRM_WOO_SYNC_MODE_API )) ){ return false; } // override $sync_sites[ $site_key ] = array( 'mode' => $mode, 'domain' => $domain, 'key' => $key, 'secret' => $secret, 'prefix' => $prefix, // tracking 'last_sync_fired' => $last_sync_fired, 'resume_from_page' => $resume_from_page, 'total_order_count' => $total_order_count, 'total_customer_count' => $total_customer_count, 'first_import_complete' => $first_import_complete, 'site_connection_errors' => $site_connection_errors, ); // pause, if present if ( $paused ){ $sync_sites[ $site_key ][ 'paused' ] = $paused; } // save $this->settings->update( 'sync_sites', $sync_sites ); // return return $sync_sites[ $site_key ]; } /** * Set a specific attribute against a sync site */ public function set_sync_site_attribute( $site_key, $attribute_key, $value ){ // get existing $sync_site = $this->get_active_sync_site( $site_key ); // set $sync_site[ $attribute_key ] = $value; // save $data = $sync_site; $data['site_key'] = $site_key; return $this->update_sync_site( $data ); } /** * Get a specific attribute from a sync site */ public function get_sync_site_attribute( $site_key, $attribute_key, $fallback_value=false ){ // get existing $sync_site = $this->get_active_sync_site( $site_key ); if ( isset( $sync_site[ $attribute_key ] ) ){ return $sync_site[ $attribute_key ]; } return $fallback_value; } /** * Increment a count against a sync site */ public function increment_sync_site_count( $site_key, $attribute_key, $increment_by = 1 ){ // get existing $sync_site = $this->get_active_sync_site( $site_key ); // set? if ( !isset( $sync_site[ $attribute_key ] ) ){ $sync_site[ $attribute_key ] = 0; } // increment $sync_site[ $attribute_key ] = (int)$sync_site[ $attribute_key ]; $sync_site[ $attribute_key ] = $sync_site[ $attribute_key ] + $increment_by; // save $data = $sync_site; $data['site_key'] = $site_key; return $this->update_sync_site( $data ); } /** * Remove a Sync Site from the connection stack */ public function remove_sync_site( $site_key = '' ){ // get existing $sync_sites = $this->get_active_sync_sites( 'default' ); // basic validation if ( empty( $site_key ) || !isset( $sync_sites[ $site_key ] ) ){ return false; } // remove it unset( $sync_sites[ $site_key ] ); // save $this->settings->update( 'sync_sites', $sync_sites ); // return return true; } /** * Pause a sync site */ public function pause_sync_site( $site_key ){ return $this->set_sync_site_attribute( $site_key, 'paused', time() ); } /** * Resume a sync site */ public function resume_sync_site( $site_key ){ // get existing $sync_site = $this->get_active_sync_site( $site_key ); // unset unset( $sync_site[ 'paused' ] ); // save $data = $sync_site; $data['site_key'] = $site_key; return $this->update_sync_site( $data ); } /** * Returns WooCommerce Client instance * built using settings based keys etc. * * @param $domain * @param $key * @param $secret * */ public function get_woocommerce_client( $site_key = '', $domain='', $key='', $secret='' ){ // load via site key if ( !empty( $site_key ) ){ $site_info = $this->get_active_sync_site( $site_key ); // got sync site? if ( !is_array( $site_info ) ){ return false; } $domain = $site_info['domain']; $key = $site_info['key']; $secret = $site_info['secret']; } // got creds? if ( !empty( $key ) && !empty( $secret ) && !empty( $domain ) ){ // include the rest API files $this->include_woocommerce_rest_api(); return new Client( $domain, $key, $secret, [ // https://github.com/woocommerce/wc-api-php 'version' => 'wc/v3', // https://stackoverflow.com/questions/42186757/woocommerce-woocommerce-rest-cannot-view-status-401 'query_string_auth' => true, ] ); } else { $missing = array(); if ( empty( $key ) ){ $missing[] = 'key'; } if ( empty( $secret ) ){ $missing[] = 'secret'; } if ( empty( $domain ) ){ $missing[] = 'domain'; } throw new Missing_Settings_Exception( 101, 'Failed to load WooCommerce API Library', array( 'missing' => $missing ) ); } return false; } // =========== / Connections DAL ================================================ // =============================================================================== // =============================================================================== // =========== WooSync Specific Migrations ====================================== /* * Migrations */ private function run_migrations(){ // 5.2 - Migrate any WooSync site connections from 1:many setup $this->migrate_52(); } /* * Migration 5.2 - Migrate any WooSync site connections from 1:many setup * Should only really need to run once */ private function migrate_52(){ // retrieve current settings $settings = $this->get_settings(); // completed already? $migration_status = get_option( 'jpcrm_woosync_52_mig' ); if ( !$migration_status ){ // do we have settings even? if ( is_array( $settings ) && isset( $settings['wcsetuptype'] ) && in_array( $settings['wcsetuptype'], array( JPCRM_WOO_SYNC_MODE_LOCAL, JPCRM_WOO_SYNC_MODE_API ) ) ){ // It's important we set this before we migrate because otherwise if local install exists it'll catch itself in a loop attempting to make it on the fly $this->skip_local_woo_check = true; // looks like it. // only if we're not in local, pass the domain and keys. // (we don't want to pass them if local because of the situation where a user may have previously // had an external site and then we'd end up with a local sync site record with remote domain) if ( $settings['wcsetuptype'] == JPCRM_WOO_SYNC_MODE_LOCAL ){ $data = array( 'site_key' => 'local', 'mode' => JPCRM_WOO_SYNC_MODE_LOCAL, 'domain' => site_url(), 'key' => '', 'secret' => '', 'prefix' => '' ); } else if ( $settings['wcsetuptype'] == JPCRM_WOO_SYNC_MODE_API ){ $data = array( 'site_key' => '', // let woosync generate it 'mode' => JPCRM_WOO_SYNC_MODE_API, 'domain' => $settings['wcdomain'], 'key' => $settings['wckey'], 'secret' => $settings['wcsecret'], 'prefix' => $settings['wcprefix'], ); } // add as new sync site record $new_sync_site = $this->add_sync_site( $data ); // verify if ( is_array( $new_sync_site ) && !empty( $new_sync_site['site_key'] ) && $this->get_active_sync_site( $new_sync_site['site_key'], true ) ){ // backup and remove old settings update_option( 'jpcrm_woosync_52_mig_backup', $settings, false ); $this->settings->delete('wcsetuptype'); $this->settings->delete('wcdomain'); $this->settings->delete('wckey'); $this->settings->delete('wcsecret'); $this->settings->delete('wcprefix'); // mark migrated update_option( 'jpcrm_woosync_52_mig', time(), false ); } else { // failed migration... will keep trying to run ? // insert notification zeroBSCRM_notifyme_insert_notification( get_current_user_id(), -999, -1, 'woosync.5.2.migration', 'failed_importing_sync_site' ); } } else { // no settings, fresh install with no past, simple. update_option( 'jpcrm_woosync_52_mig', time(), false ); } } } // =========== / WooSync Specific Migrations ==================================== // =============================================================================== /** * Register WooSync webhook actions with the CRM API * * @param array $valid_webhook_actions * * @return array $valid_webhook_actions **/ public function add_webhook_actions( $valid_webhook_actions ) { $valid_webhook_actions[] = 'woosync_do_something'; add_action( 'jpcrm_webhook_woosync_do_something', array( $this, 'webhook_process_some_data' ) ); return $valid_webhook_actions; } /** * Example function when `woosync_do_something` webhook action is called * * @param array $data **/ public function webhook_process_some_data( $data ) { // do stuff with data, e.g. // wp_send_json_success( $data ); } /* * Adds segment condition category positions (to effect the display order) */ public function add_segments_condition_category_positions( $positions = array() ) { global $zbs; $positions['woosync'] = 10; return $positions; } }
projects/plugins/crm/modules/woo-sync/includes/class-woo-sync-background-sync-job.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * WooSync: Background Sync Job (per run, site connection) * */ namespace Automattic\JetpackCRM; // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; #} the WooCommerce API use Automattic\WooCommerce\Client; use Automattic\WooCommerce\HttpClient\HttpClientException; use Automattic\JetpackCRM\Missing_Settings_Exception; /** * WooSync Background Sync Job class */ class Woo_Sync_Background_Sync_Job { /** * Site Key */ private $site_key = false; /** * Site Info */ private $site_info = false; /** * Paused state */ private $paused = false; /** * Number of orders to process per job */ private $orders_per_page = 50; private $pages_per_job = 1; /** * Current page the job is working on */ private $current_page = 1; /** * Number of pages in Woo */ private $woo_total_pages = 0; /** * Number of orders in Woo */ private $woo_total_orders = 0; /** * If set to true this will echo progress of a sync job. */ public $debug = false; /** * Setup WooSync Background Sync * Note: This will effectively fire after core settings and modules loaded * ... effectively on tail end of `init` */ public function __construct( $site_key = '', $site_info = false, $debug = false, $orders_per_page = 50, $pages_per_job = 1 ) { // requires key if ( empty( $site_key ) ){ // fail. return false; } // set vars $this->site_key = $site_key; $this->site_info = $site_info; $this->debug = $debug; $this->orders_per_page = $orders_per_page; $this->pages_per_job = $pages_per_job; // load where not passed if ( !is_array( $this->site_info ) ){ $this->site_info = $this->woosync()->get_active_sync_site( $this->site_key ); } // promote paused state if ( isset( $this->site_info['paused'] ) && $this->site_info['paused'] ){ $this->paused = true; } // good to go? if ( empty( $this->site_key ) || !is_array( $this->site_info ) ){ return false; } } /** * Returns main class instance */ public function woosync(){ global $zbs; return $zbs->modules->woosync; } /** * Returns full settings array from main settings class */ public function settings(){ return $this->woosync()->settings->getAll(); } /** * Returns 'local' or 'api' * (whichever mode is selected in settings) */ public function import_mode( $str_mode = false ){ // import mode $mode = (int)$this->site_info['mode']; // debug/string mode if ( $str_mode ) { if ( $mode === 0 ) { return 'JPCRM_WOO_SYNC_MODE_LOCAL'; } else { return 'JPCRM_WOO_SYNC_MODE_API'; } } return $mode; } /** * If $this->debug is true, outputs passed string * * @param string - Debug string */ private function debug( $str ){ if ( $this->debug ){ echo '[' . zeroBSCRM_locale_utsToDatetime( time() ) . '] ' . $str . '<br>'; } } /** * Main job function: this will retrieve and import orders from WooCommerce into CRM. * for a given sync site * * @return mixed (int|json) * - if cron originated: a count of orders imported is returned * - if not cron originated (assumes AJAX): * - if completed sync: JSON summary info is output and then exit() is called * - else count of orders imported is returned */ public function run_sync(){ global $zbs; $this->debug( 'Fired `sync_orders()` for `' . $this->site_key . '`.<pre>' . print_r( $this->site_info, 1 ) . '</pre>' ); if ( !is_array( $this->site_info ) ){ // debug $this->debug( 'Failed to retrieve site to sync! ' ); return false; } // prep vars $run_sync_job = true; $total_remaining_pages = 0; $total_pages = 0; $errors = array(); // check not marked 'paused' if ( $this->paused ){ // skip it $this->debug( 'Skipping Sync for ' . $this->site_info['domain'] . ' (mode: ' . $this->site_info['mode'] . ') - Paused' ); $run_sync_job = false; } $this->debug( 'Starting Sync for ' . $this->site_info['domain'] . ' (mode: ' . $this->site_info['mode'] . ')' ); // switch by mode if ( $this->site_info['mode'] == JPCRM_WOO_SYNC_MODE_API ) { // vars $domain = $this->site_info['domain']; $key = $this->site_info['key']; $secret = $this->site_info['secret']; $prefix = $this->site_info['prefix']; // confirm settings if ( empty( $domain ) || empty( $key ) || empty( $secret ) ) { $status_short_text = __( 'Setup required', 'zero-bs-crm' ); $this->debug( $status_short_text ); $errors[] = array( 'status' => 'error', 'status_short_text' => $status_short_text, 'status_long_text' => sprintf( __( 'WooSync will start importing data when you have updated your settings. Your site connection <code>%s</code> needs more information to connect.', 'zero-bs-crm' ), $this->site_info['domain'] ), 'error' => 'external_no_settings', ); // skip this site connection $run_sync_job = false; } } elseif ( $this->site_info['mode'] == JPCRM_WOO_SYNC_MODE_LOCAL ) { // local install // verify woo installed if ( !$zbs->woocommerce_is_active() ) { $status_short_text = __( 'Missing WooCommerce', 'zero-bs-crm' ); $this->debug( $status_short_text ); $errors[] = array( 'status' => 'error', 'status_short_text' => $status_short_text, 'status_long_text' => __( 'WooSync will start importing data when you have installed WooCommerce.', 'zero-bs-crm' ), 'error' => 'local_no_woocommerce', ); // skip this site connection $run_sync_job = false; } } else { // no mode, or a faulty one! $this->debug( 'Mode unacceptable' ); $errors[] = array( 'status' => 'error', 'status_short_text' => $status_short_text, 'status_long_text' => __( 'WooSync could not sync because one of your store connections is in an unacceptable mode.', 'zero-bs-crm' ), 'error' => 'local_no_woocommerce', ); // skip this site connection $run_sync_job = false; } if ( $run_sync_job ){ $this->debug( 'Running Import of ' . $this->pages_per_job . ' pages' ); // do x pages for ( $i = 0; $i < $this->pages_per_job; $i++ ) { // get last working position $page_to_retrieve = $this->resume_from_page(); // ... if for some reason we've got a negative, start from scratch. if ( $page_to_retrieve < 1 ) { $page_to_retrieve = 1; } $this->current_page = $page_to_retrieve; // import the page of orders // This always returns the count of imported orders, // unless 100% sync is reached, at which point it will exit (if called via AJAX) // for now, we don't need to track the return $this->import_page_of_orders( $page_to_retrieve ); } // mark the pass $this->woosync()->set_sync_site_attribute( $this->site_key, 'last_sync_fired', time() ); $this->debug( 'Sync Job finished for ' . $this->site_info['domain'] . ' with percentage complete: ' . $this->percentage_completed( false ) . '% complete.' ); } // return overall % counts later used to provide a summary % across sync site connections $percentage_counts = $this->percentage_completed( true ); if ( is_array( $percentage_counts ) ){ $total_pages = (int)$percentage_counts['total_pages']; $total_remaining_pages = $percentage_counts['total_pages'] - $percentage_counts['page_no']; } // We should never have less than zero here // (seems to happen when site connections error out) if ( $total_remaining_pages < 0 ){ $total_remaining_pages = 0; } return array( 'total_pages' => $total_pages, 'total_remaining_pages' => $total_remaining_pages, 'errors' => $errors, ); } /** * Retrieve and process 1 page of WooCommerce orders via API or from local store * * @param int $page_no - the page number to start from * * @return mixed (int|json) * - if cron originated: a count of orders imported is returned * - if not cron originated (assumes AJAX): * - if completed sync: JSON summary info is output and then exit() is called * - else count of orders imported is returned */ private function import_page_of_orders( $page_no ) { $this->debug( 'Fired `import_page_of_orders( ' . $page_no . ' )`, importing from ' . $this->import_mode( true ) . ' on site ' . $this->site_key .'.' ); // store/api switch if ( $this->import_mode() === JPCRM_WOO_SYNC_MODE_API ) { // API return $this->import_orders_from_api( $page_no ); } else { return $this->import_orders_from_store( $page_no ); } } /** * Retrieve and process a page of WooCommerce orders from local store * Previously `get_orders_from_store` * * @param int $page_no * * @return mixed (int|json) * - if cron originated: a count of orders imported is returned * - if not cron originated (assumes AJAX): * - if completed sync: JSON summary info is output and then exit() is called * - else count of orders imported is returned */ public function import_orders_from_store( $page_no = -1 ) { // Where we're trying to run without WooCommerce, fail. // In theory we shouldn't ever hit this, as we catch it earlier. global $zbs; if ( !$zbs->woocommerce_is_active() ) { $this->debug( 'Unable to import as it appears WooCommerce is not installed.' ); return false; } // retrieve orders $orders = wc_get_orders( array( 'limit' => $this->orders_per_page, 'paged' => $page_no, 'paginate' => true, 'order' => 'ASC', 'orderby' => 'ID', )); // count the pages and break if we have nothing to import if ( $orders->max_num_pages == 0 ) { // we're at 100%, mark sync complete $this->set_first_import_status( true ); // return count return 0; } // cache values $this->woo_total_pages = $orders->max_num_pages; $this->woo_total_orders = $orders->total; // we have some pages to process, so proceed $orders_imported = 0; // cycle through orders from store and import foreach ( $orders->orders as $order ) { // We previously used the wp cpt ID, see #1982 // In case we hit issues where a user sees dupes from this, we'll store any != in an extra meta $order_post_id = $order->get_id(); // Get order number if there is one; for example refunds don't have 'get_order_number' if ( method_exists( $order, 'get_order_number' ) ) { $order_num = $order->get_order_number(); } else { // order number by default is the same as the order post ID $order_num = $order_post_id; } if ( !empty( $order_post_id ) ) { $this->debug( 'Importing order: ' . $order_num . '(' . $order_post_id . ')' ); // this seems perhaps unperformant given we have the `order` object // ... and this function re-get's the order object, but it's centralised and useful (and #legacy) $this->add_update_from_woo_order( $order_post_id ); // this will include orders updated... $orders_imported++; } } // check for completion if ( $page_no >= $orders->max_num_pages ) { // we're at 100%, mark sync complete $this->set_first_import_status( true ); // set pointer to last page $this->set_resume_from_page( $orders->max_num_pages ); // return count return $orders_imported; } // There's still pages to go then: // increase pointer by one $this->set_resume_from_page( $page_no + 1 ); // return the count return $orders_imported; } /** * Retrieve and process a page of WooCommerce orders via API * Previously `get_orders_from_api` * * @param int $page_no * * @return mixed (int|json) * - if cron originated: a count of orders imported is returned * - if not cron originated (assumes AJAX): * - if completed sync: JSON summary info is output and then exit() is called * - else count of orders imported is returned */ public function import_orders_from_api( $page_no = -1 ) { global $zbs; try { // get client $woocommerce = $this->woosync()->get_woocommerce_client( $this->site_key ); $this->debug( 'Got WooCommerce Client...' ); // clock origin $origin = ''; $domain = $this->site_info['domain']; if ( !empty( $domain ) ) { // if Domain if ( $domain ) { $origin = $zbs->DAL->add_origin_prefix( $domain, 'domain' ); } } // retrieve orders // http://woocommerce.github.io/woocommerce-rest-api-docs/#orders $orders = $woocommerce->get( 'orders', array( 'page' => $page_no, 'per_page' => $this->orders_per_page, 'order' => 'asc', 'orderby' => 'id', ) ); // retrieve page count from headers: $last_response = $woocommerce->http->getResponse(); $response_headers = $last_response->getHeaders(); $lc_response_headers = array_change_key_case( $response_headers, CASE_LOWER ); // error if X-WP-TotalPages header doesn't exist if ( !isset( $lc_response_headers['x-wp-totalpages'] ) ) { echo json_encode( array( 'status' => 'error', 'status_short_text' => 'woo_api_missing_headers', 'status_long_text' => __( 'Missing headers in API response. It seems that WooCommerce has not responded in a standard way.', 'zero-bs-crm' ), 'page_no' => $page_no, 'orders_imported' => 0, 'percentage_completed' => 0, ) ); exit; } // cache values $this->woo_total_pages = (int)$lc_response_headers['x-wp-totalpages']; $this->woo_total_orders = (int)$lc_response_headers['x-wp-total']; $total_pages = (int)$lc_response_headers['x-wp-totalpages']; $this->debug( 'API Response:<pre>' . var_export( array( 'orders_retrieved' => count( $orders ), // 'last_response' => $last_response, // 'response_headers' => $response_headers, // 'lc_response_headers' => $lc_response_headers, 'total_pages' => $this->woo_total_pages, ), true ) . '</pre>' ); // count the pages and break if we have nothing to import if ( $this->woo_total_pages === 0 ) { // we're at 100%, mark sync complete $this->set_first_import_status( true ); // return count return 0; } // we have some pages to process, so proceed $orders_imported = 0; // cycle through orders foreach ( $orders as $order ) { $this->debug( 'Importing order: ' . $order->number . ' (becoming: ' . $this->woosync()->get_prefix( $this->site_key ) . $order->number . ')' ); // prefix ID and number $order->number = $this->woosync()->get_prefix( $this->site_key ) . $order->number; $order->id = $this->woosync()->get_prefix( $this->site_key ) . $order->id; // translate order data to crm objects $crm_objects = $this->woocommerce_api_order_to_crm_objects( $order, $origin ); // import crm objects $this->import_crm_object_data( $crm_objects ); $orders_imported++; } // check for completion if ( $page_no >= $this->woo_total_pages ) { // we're at 100%, mark sync complete $this->set_first_import_status( true ); // set pointer to last page $this->set_resume_from_page( $this->woo_total_pages ); } else { // There's still pages to go then: // increase pointer by one $this->set_resume_from_page( $page_no + 1 ); } // connection worked, so reset any errors: $this->woosync()->set_sync_site_attribute( $this->site_key, 'site_connection_errors', 0 ); // return count return $orders_imported; } catch ( HttpClientException $e ) { $this->debug( 'Sync Failed in `import_orders_from_api()`, WooCommerce REST API error: ' . $e->getMessage() ); /* echo json_encode( array( 'status' => 'error', 'status_short_text' => 'woo_client_error', 'status_long_text' => $this->woosync()->process_error( $e->getMessage() ), 'page_no' => $page_no, 'orders_imported' => 0, 'percentage_completed' => 0, ) ); */ // log connection error (3x = auto-pause) $this->log_connection_error(); return 'error'; } catch ( Missing_Settings_Exception $e ) { // missing settings means couldn't load lib. // compile string of what's missing $missing_string = ''; $missing_data = $e->get_error_data(); if ( is_array( $missing_data ) && isset( $missing_data['missing'] ) ) { $missing_string = '<br>' . __( 'Missing:', 'zero-bs-crm' ) . ' ' . implode( ', ', $missing_data['missing'] ); } $this->debug( 'Sync Failed in `import_orders_from_api()` due to missing settings against `' . $this->site_key . '` (could not, therefore, load WooCommerce API Connection): ' . $e->getMessage() . $missing_string ); /* echo json_encode( array( 'status' => 'error', 'status_short_text' => 'woo_client_error', 'status_long_text' => $this->woosync()->process_error( $e->getMessage() ), 'page_no' => $page_no, 'orders_imported' => 0, 'percentage_completed' => 0, ) ); */ // log connection error (3x = auto-pause) $this->log_connection_error(); return 'error'; } } /** * Add or Update an order from WooCommerce * (previously `add_order_from_id`) * * @param int $order_post_id Order post id from WooCommerce (may be different than $order_num) */ public function add_update_from_woo_order( $order_post_id ) { global $zbs; // This is only fired from local store calls, so let's retrieve the local domain as origin $origin = ''; $domain = site_url(); if ( $domain ) { $origin = $zbs->DAL->add_origin_prefix( $domain, 'domain' ); } // get order data $order = wc_get_order( $order_post_id ); // return if order doesn't exist if ( ! $order ) { return false; } $extra_meta = array(); // Get order number if there is one; for example: // * refunds don't have 'get_order_number' // * some plugins like Sequential Order Numbers Pro set a custom order number if ( method_exists( $order, 'get_order_number' ) ) { $order_num = $order->get_order_number(); // store the order number for future reference $extra_meta['order_num'] = $order_num; } else { // order number by default is the same as the order post ID $order_num = $order_post_id; } $raw_order_data = $order->get_data(); // consolidate data $tidy_order_data = $this->woocommerce_order_to_crm_objects( $raw_order_data, $order, $order_post_id, $order_num, '', '', false, array(), $origin, $extra_meta ); // import data $this->import_crm_object_data( $tidy_order_data ); } /** * Set's a completion status for woo order imports * * @param string|bool $status = 'yes|no' (#legacy) or 'true|false' * * @return bool $status */ public function set_first_import_status( $status ){ $status_bool = false; if ( $status == 'yes' || $status === true ){ $status_bool = true; } // set it $this->woosync()->set_sync_site_attribute( $this->site_key, 'first_import_complete', $status_bool ); return $status_bool; } /** * Returns a completion status for woo order imports * * @return bool $status */ public function first_import_completed(){ $status_bool = false; // get $sync_site = $this->woosync()->get_active_sync_site( $this->site_key ); if ( $sync_site['first_import_complete'] == 'yes' || $sync_site['first_import_complete'] === true || $sync_site['first_import_complete'] == 1 ){ $status_bool = true; } return $status_bool; } /** * Sets current working page index (to resume from) * * @return int $page */ public function set_resume_from_page( $page_no ){ //update_option( 'zbs_woo_resume_sync_' . $this->site_key, $page_no ); $this->woosync()->set_sync_site_attribute( $this->site_key, 'resume_from_page', $page_no ); return $page_no; } /** * Return current working page index (to resume from) * * @return int $page */ public function resume_from_page(){ return $this->woosync()->get_sync_site_attribute( $this->site_key, 'resume_from_page', 1 ); } /** * Adds or updates crm objects related to a processed woocommerce order * (requires that the $order_data has been passed through `woocommerce_order_to_crm_objects`) * Previously `import_woocommerce_order_from_order_data` * * @param array $crm_object_data (Woo Order data passed through `woocommerce_order_to_crm_objects`) * * @return int $transaction_id * */ public function import_crm_object_data( $crm_object_data ) { global $zbs; $settings = $this->settings(); // Add/update contact from cleaned order data, (previously `add_or_update_contact_from_order_data`) $contact_id = -1; if ( isset( $crm_object_data['contact'] ) && isset( $crm_object_data['contact']['email'] ) ) { // Add the contact $contact_id = $zbs->DAL->contacts->addUpdateContact( array( 'data' => $crm_object_data['contact'], 'extraMeta' => $crm_object_data['contact_extra_meta'], 'do_not_update_blanks' => true ) ); } // if contact: add logs, contact id relations to objects, and addupdate company if ( $contact_id > 0 ) { $this->debug( 'Contact added/updated #' . $contact_id ); $zbs->DAL->contacts->addUpdateContactTags( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase array( 'id' => $contact_id, 'tag_input' => $crm_object_data['contact']['tags'], 'mode' => 'append', ) ); // contact logs if ( is_array( $crm_object_data['contact_logs'] ) ) { foreach ( $crm_object_data['contact_logs'] as $log ) { // add log $log_id = $zbs->DAL->logs->addUpdateLog( array( 'id' => -1, 'owner' => -1, 'ignore_if_existing_desc_type' => true, 'ignore_if_meta_matching' => array( 'key' => 'from_woo_order', 'value' => $crm_object_data['order_post_id'] ), // fields (directly) 'data' => array( 'objtype' => ZBS_TYPE_CONTACT, 'objid' => $contact_id, 'type' => $log['type'], 'shortdesc' => $log['shortdesc'], 'longdesc' => $log['longdesc'], 'meta' => array( 'from_woo_order' => $crm_object_data['order_post_id'] ), 'created' => -1 ), ) ); } } // add contact ID relationship to the related objects $crm_object_data['transaction']['contacts'] = array( $contact_id ); $crm_object_data['invoice']['contacts'] = array( $contact_id ); // Add/update company (if using b2b mode, and successfully added/updated contact): $b2b_mode = zeroBSCRM_getSetting( 'companylevelcustomers' ); if ( $b2b_mode && isset( $crm_object_data['company']['name'] ) && !empty( $crm_object_data['company']['name'] ) ) { /** * Note: we use existing company ID if we can find it by name; otherwise we create it * * WooCommerce orders only has one company field that we can use (company name). As such, * we can't rely on more accurate searches (e.g. by email) */ $potential_company = $zbs->DAL->companies->getCompany( -1, array( 'name' => $crm_object_data['company']['name'] ) ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase if ( $potential_company ) { $company_id = $potential_company['id']; } else { // Add the company $company_id = $zbs->DAL->companies->addUpdateCompany( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase array( 'data' => $crm_object_data['company'], ) ); } if ( $company_id > 0 ) { $this->debug( 'Company added/updated #' . $company_id ); // inject into transaction data too $crm_object_data['transaction']['companies'] = array( $company_id ); $zbs->DAL->contacts->addUpdateContactCompanies( array( 'id' => $contact_id, 'companyIDs' => array( $company_id ), ) ); } else { $this->debug( 'Company import failed: <code>' . json_encode( $crm_object_data['company'] ) . '</code>' ); } } } else { // failed to add contact? $this->debug( 'Contact import failed, or there was no contact to import. Contact Data: <code>' . json_encode( $crm_object_data['contact'] ) . '</code>' ); } // Add/update invoice (if enabled) (previously `add_or_update_invoice`) if ( $settings['wcinv'] == 1 ) { // retrieve existing invoice // note this is substituting $crm_object_data['invoice']['existence_check_args'] for what should be $args, but it works $invoice_id = $zbs->DAL->invoices->getInvoice( -1, $crm_object_data['invoice']['existence_check_args'] ); // add logo if invoice doesn't exist yet if ( !$invoice_id ) { $crm_object_data['invoice']['logo_url'] = jpcrm_business_logo_url(); } else { // if this is an update, let's not overwrite existing hash and logo $old_invoice_data = $zbs->DAL->invoices->getInvoice( $invoice_id ); $crm_object_data['invoice']['logo_url'] = $old_invoice_data['logo_url']; $crm_object_data['invoice']['hash'] = $old_invoice_data['hash']; } // add/update invoice $invoice_id = $zbs->DAL->invoices->addUpdateInvoice( array( 'id' => $invoice_id, 'data' => $crm_object_data['invoice'], 'extraMeta' => ( isset( $crm_object_data['invoice']['extra_meta'] ) ? $crm_object_data['invoice']['extra_meta'] : -1 ), 'calculate_totals' => true, ) ); // link the transaction to the invoice if ( !empty( $invoice_id ) ) { $this->debug( 'Added invoice #' . $invoice_id ); $crm_object_data['transaction']['invoice_id'] = $invoice_id; } else { $this->debug( 'invoice import failed: <code>' . json_encode( $crm_object_data['invoice'] ) . '</code>' ); } } // Add/update transaction (previously `add_or_update_transaction`) // note this is substituting $crm_object_data['invoice']['existence_check_args'] for what should be $args, but it works $existing_transaction_id = $zbs->DAL->transactions->getTransaction( -1, $crm_object_data['transaction']['existence_check_args'] ); if ( !empty( $existing_transaction_id ) ) { $this->debug( 'Existing transaction #' . $existing_transaction_id ); } $args = array( 'id' => $existing_transaction_id, 'owner' => -1, 'data' => $crm_object_data['transaction'], ); // got any extra meta? if ( isset( $crm_object_data['transaction_extra_meta'] ) && is_array( $crm_object_data['transaction_extra_meta'] ) ) { $args['extraMeta'] = $crm_object_data['transaction_extra_meta']; } // This parameter (do_not_mark_invoices) makes sure invoice status are not changed. $args[ 'do_not_mark_invoices' ] = true; $transaction_id = $zbs->DAL->transactions->addUpdateTransaction( $args ); if ( !empty( $transaction_id ) ) { // if we have success here, but we didn't have a previous id, then it's a successful new order addition if ( empty( $existing_transaction_id ) ){ // increment connection order import count $this->woosync()->increment_sync_site_count( $this->site_key, 'total_order_count' ); $this->debug( 'Added transaction #' . $transaction_id ); } else { $this->debug( 'Updated transaction #' . $transaction_id ); } } else { $this->debug( 'Transaction import failed: <code>' . json_encode( $crm_object_data['transaction'] ) . '</code>' ); } // Secondary transactions (Refunds) if ( is_array( $crm_object_data['secondary_transactions'] ) ) { foreach ( $crm_object_data['secondary_transactions'] as $sub_transaction ) { // slightly modified version of above transaction insert logic. $existing_transaction_id = $zbs->DAL->transactions->getTransaction( -1, $sub_transaction['existence_check_args'] ); // debug if ( !empty( $existing_transaction_id ) ){ $this->debug( 'Sub transaction: Existing transaction #' . $existing_transaction_id ); } // build arguments $args = array( 'id' => $existing_transaction_id, 'owner' => -1, 'data' => $sub_transaction, ); // if we have transaction id, also inject it as a parent (this gets caught by the UI to give a link back) if ( isset( $transaction_id ) && !empty( $contact_id ) ) { $args['data']['parent'] = $transaction_id; } // if we have contact id, also inject it if ( isset( $contact_id ) && !empty( $contact_id ) ) { $args['data']['contacts'] = array( $contact_id ); } // if we have company id, also inject it if ( isset( $company_id ) && !empty( $company_id ) ) { $args['data']['companies'] = array( $company_id ); } // if we have invoice_id, inject it // ... this makes our double entry invoices work. if ( isset( $invoice_id ) && !empty( $invoice_id ) ) { $args['data']['invoice_id'] = $invoice_id; } // pass any extra meta along if ( isset( $sub_transaction['extra_meta'] ) && is_array( $sub_transaction['extra_meta'] ) ) { $args['extraMeta'] = $sub_transaction['extra_meta']; unset( $args['data']['extra_meta'] ); } $sub_transaction_id = $zbs->DAL->transactions->addUpdateTransaction( $args ); $this->debug( 'Added/Updated Sub-transaction (Refund) #' . $sub_transaction_id ); } } return $transaction_id; } /** * Translates a local store order into an import-ready crm objects array * previously `tidy_order_from_store` * * @param $order_data * @param $order * @param $order_num * @param $order_items * @param $api * @param $order_tags * @param $origin * @param $extra_meta * * @return array of various objects (contact|company|transaction|invoice) */ public function woocommerce_order_to_crm_objects( $order_data, $order, $order_post_id, $order_num, $order_items = '', $item_title = '', $from_api = false, $order_tags = array(), $origin = '', $extra_meta = array() ) { global $zbs; // get settings $settings = $this->settings(); // build arrays $data = array( 'contact' => array(), 'contact_extra_meta' => array(), 'contact_logs' => array(), 'company' => false, 'invoice' => false, 'transaction' => false, 'secondary_transactions' => array(), 'lineitems' => array(), 'order_post_id' => $order_post_id, ); // Below we sometimes need to do some type-conversion, (e.g. dates), so here we retrieve our // crm contact custom fields to use the types... $custom_fields = $zbs->DAL->getActiveCustomFields( array( 'objtypeid' => ZBS_TYPE_CONTACT ) ); $is_status_mapping_enabled = ( isset( $settings['enable_woo_status_mapping'] ) ? ( (int) $settings['enable_woo_status_mapping'] === 1 ) : true ); $contact_statuses = zeroBSCRM_getCustomerStatuses( true ); // initialise dates $contact_creation_date = -1; $contact_creation_date_uts = -1; $transaction_creation_date_uts = -1; $invoice_creation_date_uts = -1; // Tag customer setting i.e. do we want to tag with every product name // Will be useful to be able to filter Sales Dashboard by Product name eventually $tag_contact_with_item = false; $tag_transaction_with_item = false; $tag_invoice_with_item = false; $tag_with_coupon = false; $tag_product_prefix = ( isset( $settings['wctagproductprefix'] ) ) ? zeroBSCRM_textExpose( $settings['wctagproductprefix'] ) : ''; $tag_coupon_prefix = ( isset( $settings['wctagcouponprefix'] ) ) ? zeroBSCRM_textExpose( $settings['wctagcouponprefix'] ) : ''; if ( isset( $settings['wctagcust'] ) && $settings['wctagcust'] == 1 ) { $tag_contact_with_item = true; } if ( isset( $settings['wctagtransaction'] ) && $settings['wctagtransaction'] == 1 ) { $tag_transaction_with_item = true; } if ( isset( $settings['wctaginvoice'] ) && $settings['wctaginvoice'] == 1 ) { $tag_invoice_with_item = true; } if ( isset( $settings['wctagcoupon'] ) && $settings['wctagcoupon'] == 1 ) { $tag_with_coupon = true; } // pre-processing from the $order_data $order_status = $order_data['status']; $order_currency = $order_data['currency']; // Add external source $data['source'] = array( 'externalSource' => 'woo', 'externalSourceUID' => $order_post_id, 'origin' => $origin, 'onlyID' => true ); // Dates: if ( !$from_api ) { // from local store if ( isset( $order_data['date_created'] ) && !empty( $order_data['date_created'] ) ) { $contact_creation_date = $order_data['date_created']->date("Y-m-d h:m:s"); $contact_creation_date_uts = $order_data['date_created']->date("U"); $transaction_creation_date_uts = $order_data['date_created']->date("U"); $invoice_creation_date_uts = $order_data['date_created']->date("U"); } } else { // from API // dates are strings in API. $contact_creation_date = $order_data['date_created']; $contact_creation_date_uts = strtotime($order_data['date_created']); $transaction_creation_date_uts = strtotime($order_data['date_created']); $invoice_creation_date_uts = strtotime($order_data['date_created']); } // ==== Tax Rates (on local stores only) if ( !$from_api ) { // Force Woo order totals recalculation to ensure taxes were applied correctly // Only force recalculation if the order is not paid yet if ( $order->get_status() === 'pending' || $order->get_status() === 'on-hold' ) { try { $order->calculate_totals(); $order->save(); } catch ( \TypeError $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch /* This is a Woo bug with empty fees: https://github.com/woocommerce/woocommerce/issues/44859 For now we'll just ignore it and carry on. */ } } $order_data = $order->get_data(); // retrieve tax table to feed in tax links $tax_rates_table = $this->woosync()->background_sync->get_tax_rates_table(); // Add/update any tax rates used in this order $tax_rate_changes = false; foreach ( $order->get_items('tax') as $item ){ $tax_rate_id = $item->get_rate_id(); // Tax rate ID $tax_label = $item->get_label(); // Tax label name $tax_percent = \WC_Tax::get_rate_percent( $tax_rate_id ); // Tax percentage $tax_rate = str_replace('%', '', $tax_percent); // Tax rate /* $tax_rate_code = $item->get_rate_code(); // Tax code $tax_name = $item->get_(); // Tax name $tax_total = $item->get_tax_total(); // Tax Total $tax_ship_total = $item->get_shipping_tax_total(); // Tax shipping total $tax_compound = $item->get_compound(); // Tax compound */ // check if tax rate exists already $tax_rate_exists = false; foreach ( $tax_rates_table as $tax_rate_id => $tax_rate_detail ){ if ( // name sprintf( __( '%s (From WooCommerce)', 'zero-bs-crm' ), $tax_label ) == $tax_rate_detail['name'] && // rate $tax_rate == $tax_rate_detail['rate'] ){ $tax_rate_exists = true; break; } } // add/update it if it doesn't exist or has changed rate if ( !$tax_rate_exists ){ // add/update $added_rate_id = zeroBSCRM_taxRates_addUpdateTaxRate( array( //'id' => -1, 'data' => array( 'name' => sprintf( __( '%s (From WooCommerce)', 'zero-bs-crm' ), $tax_label ), 'rate' => (float)$tax_rate, ), ) ); // mark as table changed $tax_rate_changes = true; } }; // reload tax rate table if changes actioned if ( $tax_rate_changes ){ $tax_rates_table = $this->woosync()->background_sync->get_tax_rates_table( true ); } } // /=== Tax // ==== Contact // Always use contact email, not billing email: // We've hit issues based on adding a Jetpack CRM contact based on billing email if they have a WP user attached // with a different email. The $order_data['customer_id'] will = 0 for guest or +tive for users. This way we will always // store the contact against the contact email (and not the billing email) $contact_email = ''; $billing_email = ''; if ( isset( $order_data['customer_id']) && $order_data['customer_id'] > 0 ) { // then we have an existing user. Get the WP email $user = get_user_by( 'id', $order_data['customer_id'] ); $contact_email = $user->user_email; if ( isset($order_data['billing']['email'] ) ) { $billing_email = $order_data['billing']['email']; } // pass WP ID to contact $data['contact']['wpid'] = $order_data['customer_id']; } else { if ( isset( $order_data['billing']['email'] ) ) { $billing_email = $order_data['billing']['email']; $contact_email = $billing_email; } } // we only add a contact whom has an email if ( !empty( $contact_email ) ) { if ( $is_status_mapping_enabled ) { $contact_id = zeroBS_getCustomerIDWithEmail( $contact_email ); // If this is a new contact or the current status equals the first status (CRM's default value is 'Lead'), we are allowed to change it. if ( empty( $contact_id ) || $zbs->DAL->contacts->getContactStatus( $contact_id ) === $contact_statuses[0] ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase $data['contact']['status'] = $this->woosync()->translate_order_status_to_obj_status( ZBS_TYPE_CONTACT, $order_status ); } } $data['contact']['created'] = $contact_creation_date_uts; $data['contact']['email'] = $contact_email; $data['contact']['externalSources'] = array( array( 'source' => 'woo', 'uid' => $order_post_id, 'origin' => $origin, 'owner' => 0, // for now we hard-type no owner to avoid ownership issues. As we roll out fuller ownership we may want to adapt this. ), ); if ( isset( $order_data['billing']['first_name'] ) ) { $data['contact']['fname'] = $order_data['billing']['first_name']; } if ( isset( $order_data['billing']['last_name'] ) ) { $data['contact']['lname'] = $order_data['billing']['last_name']; } // if we've not got any fname/lname and we do have 'customer_id' attribute (wp user id) // ... check the wp user to see if they have a display name we can use. if ( isset( $order_data['customer_id'] ) && $order_data['customer_id'] > 0 ) { // retrieve wp user $woo_customer_meta = get_user_meta( $order_data['customer_id'] ); // fname if ( isset( $woo_customer_meta['first_name'] ) && ( !isset( $data['contact']['fname'] ) || empty( $data['contact']['fname'] ) ) ) { $data['contact']['fname'] = $woo_customer_meta['first_name'][0]; } // lname if ( isset( $woo_customer_meta['last_name'] ) && ( !isset( $data['contact']['lname'] ) || empty( $data['contact']['lname'] ) ) ) { $data['contact']['lname'] = $woo_customer_meta['last_name'][0]; } } if ( isset( $order_data['billing']['address_1'] ) ) { $data['contact']['addr1'] = $order_data['billing']['address_1']; } if ( isset( $order_data['billing']['address_2'] ) ) { $data['contact']['addr2'] = $order_data['billing']['address_2']; } if ( isset( $order_data['billing']['city'] ) ) { $data['contact']['city'] = $order_data['billing']['city']; } if ( isset( $order_data['billing']['state'] ) ) { $data['contact']['county'] = $order_data['billing']['state']; } if ( isset( $order_data['billing']['postcode'] ) ) { $data['contact']['postcode'] = $order_data['billing']['postcode']; } if ( isset( $order_data['billing']['country'] ) ) { $data['contact']['country'] = $order_data['billing']['country']; } if ( isset( $order_data['billing']['phone'] ) ) { $data['contact']['hometel'] = $order_data['billing']['phone']; } // if setting: copy shipping address if ( $settings['wccopyship'] ) { if ( isset( $order_data['shipping']['address_1'] ) ) { $data['contact']['secaddr1'] = $order_data['shipping']['address_1']; } if ( isset( $order_data['shipping']['address_2'] ) ) { $data['contact']['secaddr2'] = $order_data['shipping']['address_2']; } if ( isset( $order_data['shipping']['city'] ) ) { $data['contact']['seccity'] = $order_data['shipping']['city']; } if ( isset( $order_data['shipping']['state'] ) ) { $data['contact']['seccounty'] = $order_data['shipping']['state']; } if ( isset( $order_data['shipping']['postcode'] ) ) { $data['contact']['secpostcode'] = $order_data['shipping']['postcode']; } if ( isset( $order_data['shipping']['country'] ) ) { $data['contact']['seccountry'] = $order_data['shipping']['country']; } } // Store the billing email as an alias, and as an extraMeta (for later potential origin work) if ( !empty( $billing_email ) ) { $data['contact_extra_meta']['billingemail'] = $billing_email; // we only need to add the alias if it's different to the $contact_email if ( $billing_email !== $contact_email ) { $data['contact']['aliases'] = array( $billing_email ); } } // Store any customer notes if ( isset( $order_data['customer_note'] ) && !empty( $order_data['customer_note'] ) ) { // Previously `notes` field, refactor into core moved this into log addition $data['contact_logs'][] = array( 'type' => 'note', 'shortdesc' => __( 'WooCommerce Customer notes', 'zero-bs-crm' ), 'longdesc' => __( 'WooCommerce Customer notes:', 'zero-bs-crm' ) . ' ' . $order_data['customer_note'] . '<br>' . sprintf( __( 'From order: #%s', 'zero-bs-crm' ), $order_post_id ), ); } // Retrieve any WooCommerce Checkout metadata & try to store it against contact if match custom fields // Returns array of WC_Meta_Data objects https://woocommerce.github.io/code-reference/classes/WC-Meta-Data.html // Filters to support WooCommerce Checkout Field Editor, Field editor Pro etc. /* [1] => WC_Meta_Data Object ( [current_data:protected] => Array ( [id] => 864 [key] => tax-id [value] => 12345 ) [data:protected] => Array ( [id] => 864 [key] => tax-id [value] => 12345 ) ) */ if ( isset( $order_data['meta_data'] ) && is_array( $order_data['meta_data'] ) ) { // Cycle through them and pick out matching fields foreach ( $order_data['meta_data'] as $wc_meta_data_object ) { // retrieve data $meta_data = $wc_meta_data_object->get_data(); if ( is_array( $meta_data ) ) { // process it, only adding if not already set (to avoid custom checkout overriding base fields) $key = $zbs->DAL->makeSlug( $meta_data['key'] ); if ( !empty( $key ) && !isset( $data['contact'][ $key ] ) ) { $value = $meta_data['value']; // see if we have a matching custom field to infer type conversions from: if ( isset( $custom_fields[ $key ] ) ) { // switch on type switch ( $custom_fields[ $key ][0] ) { case 'date': // May 29, 2022 => UTS $value = strtotime( $value ); break; } } // simplistic add $data['contact'][ $key ] = $value; // filter through any mods $data['contact'] = $this->filter_checkout_contact_fields( $key, $value, $data['contact'], $order, $custom_fields ); } } } } // WooCommerce Checkout Add-ons fields support, where installed $data['contact'] = $this->checkout_add_ons_add_field_values( $order_post_id, $data['contact'], $custom_fields ); } // ==== Company (where available) if ( isset( $order_data['billing'] ) && isset( $order_data['billing']['company'] ) ) { /** * Build fields for company in case it doesn't exist * * WooCommerce only gives us one company field (company name), and we can't infer other fields * from customer info since multiple customers might put the same company */ $data['company'] = array( 'status' => __( 'Customer', 'zero-bs-crm' ), 'name' => $order_data['billing']['company'], 'created' => $contact_creation_date_uts, 'externalSources' => array( array( 'source' => 'woo', 'uid' => $order_post_id, 'origin' => $origin, 'owner' => 0, // for now we hard-type no owner to avoid ownership issues. As we roll out fuller ownership we may want to adapt this. ), ), ); } // ==== Transaction // prep dates $transaction_paid_date_uts = null; $transaction_completed_date_uts = null; if ( array_key_exists( 'date_paid', $order_data ) && !empty( $order_data['date_paid'] ) ) { $transaction_paid_date_uts = $order_data['date_paid']->date( 'U' ); } $invoice_status = $this->woosync()->translate_order_status_to_obj_status( ZBS_TYPE_INVOICE, $order_status ); // retrieve completed date, where available if ( array_key_exists( 'date_completed', $order_data ) && !empty( $order_data['date_completed'] ) ) { $transaction_completed_date_uts = $order_data['date_completed']->date( 'U' ); } // Retrieve and process order line items if ( !$from_api ) { $item_title = ''; $order_items = $order->get_items(); // Retrieve order-used tax rates $tax_items_labels = array(); foreach ( $order->get_items('tax') as $tax_item ) { $rate_id = $tax_item->get_rate_id(); $tax_items_labels[ $rate_id ] = $tax_item->get_label(); if ( isset( $tax_items_labels[ $rate_id ] ) && ! empty( $tax_item->get_shipping_tax_total() ) ) { $tax_label = $tax_items_labels[ $rate_id ]; foreach ( $tax_rates_table as $tax_rate_id => $tax_rate_detail ) { // Translators: %s = tax rate name if ( sprintf( __( '%s (From WooCommerce)', 'zero-bs-crm' ), $tax_label ) === $tax_rate_detail['name'] ) { $shipping_tax_id = $tax_rate_id; break; } } } } $order_data['subtotal'] = 0.0; // cycle through order items to create crm line items foreach ( $order_items as $item_key => $item ) { // first item gets item name if ( empty( $item_title ) ) { $item_title = $item->get_name(); } else { $item_title = __( 'Multiple Items', 'zero-bs-crm' ); } // retrieve item data $item_data = $item->get_data(); // catch cases where quantity is 0; see gh-2190 $price = empty( $item_data['quantity'] ) ? 0 : $item_data['subtotal'] / $item_data['quantity']; $order_data['subtotal'] += $price; // translate Woo taxes to CRM taxes $item_woo_taxes = $item->get_taxes(); $tax_label = ''; $item_tax_rate_ids = array(); // collect taxes foreach ( $item_woo_taxes['subtotal'] as $rate_id => $tax ){ if ( isset( $tax_items_labels[ $rate_id ] ) ){ $tax_label = $tax_items_labels[ $rate_id ]; // match tax label to tax in our crm tax table (should have been added by the logic above here, even if new) foreach ( $tax_rates_table as $tax_rate_id => $tax_rate_detail ){ if ( sprintf( __( '%s (From WooCommerce)', 'zero-bs-crm' ), $tax_label ) == $tax_rate_detail['name'] ){ // this tax is applied to this line item $item_tax_rate_ids[] = $tax_rate_id; } } } } // attributes not yet translatable but originally referenced: `variation_id|tax_class|subtotal_tax` $new_line_item = array( 'order' => $order_post_id, // passed as parameter to this function 'currency' => $order_currency, 'quantity' => $item_data['quantity'], 'price' => $price, 'total' => $item_data['total'], 'title' => $item_data['name'], 'desc' => $item_data['name'] . ' (#' . $item_data['product_id'] . ')', 'tax' => $item_data['total_tax'], 'shipping' => 0, ); // add taxes, where present if ( is_array( $item_tax_rate_ids ) && count( $item_tax_rate_ids ) > 0 ) { $new_line_item['taxes'] = implode( ',', $item_tax_rate_ids ); } // Add order item line $data['lineitems'][] = $new_line_item; // add to tags where not alreday present if ( !in_array( $item_data['name'], $order_tags ) ) { $order_tags[] = $tag_product_prefix . $item_data['name']; } } // --- Process any present fee in the order --- // $fees = $order->get_fees(); if ( is_array( $fees ) && count( $fees ) > 0 ) { foreach ( $fees as $fee ) { if ( $fee instanceof \WC_Order_Item_Fee ) { $value = $fee->get_amount( false ); // Woo allows a fee's value to be an empty string, so account for that to prevent a PHP fatal. if ( empty( $value ) ) { $value = 0; } $new_line_item = array( 'order' => $order_post_id, // passed as parameter to this function 'currency' => $order_currency, 'quantity' => 1, 'price' => $value, 'fee' => $value, 'total' => $value, 'title' => esc_html__( 'Fee', 'zero-bs-crm' ), 'desc' => $fee->get_name(), 'tax' => $fee->get_total_tax(), 'taxes' => -1, 'shipping' => 0.0, ); // Apply the same tax if ( is_array( $item_tax_rate_ids ) && count( $item_tax_rate_ids ) > 0 ) { $new_line_item['taxes'] = implode( ',', $item_tax_rate_ids ); } $order_data['subtotal'] += $new_line_item['price']; // Add fee as an item to the invoice $data['lineitems'][] = $new_line_item; } } } // if the order has a coupon. Tag the contact with that coupon too, but only if from same store. if ( $tag_with_coupon ) { foreach ( $order->get_coupon_codes() as $coupon_code ) { $order_tags[] = $tag_coupon_prefix . $coupon_code; } } } else { // API response returns these differently $data['lineitems'] = $order_items; } // tags (contact) if ( $tag_contact_with_item ) { $data['contact']['tags'] = $order_tags; } $transaction_status = $this->woosync()->translate_order_status_to_obj_status( ZBS_TYPE_TRANSACTION, $order_status ); // fill out transaction header (object) $data['transaction'] = array( 'ref' => $order_num, 'type' => __( 'Sale', 'zero-bs-crm' ), 'title' => $item_title, 'status' => $transaction_status, 'total' => $order_data['total'], 'date' => $transaction_creation_date_uts, 'created' => $transaction_creation_date_uts, 'date_completed' => $transaction_completed_date_uts, 'date_paid' => $transaction_paid_date_uts, 'externalSources' => array( array( 'source' => 'woo', 'uid' => $order_post_id, 'origin' => $origin, 'owner' => 0, // for now we hard-type no owner to avoid ownership issues. As we roll out fuller ownership we may want to adapt this. ), ), 'currency' => $order_currency, 'net' => ( (float)$order_data['total'] - (float)$order_data['discount_total'] - (float)$order_data['total_tax'] - (float)$order_data['shipping_total'] ), 'tax' => $order_data['total_tax'], 'fee' => 0, 'discount' => $order_data['discount_total'], 'shipping' => $order_data['shipping_total'], 'existence_check_args' => $data['source'], 'lineitems' => $data['lineitems'], ); // tags (transaction) if ( $tag_transaction_with_item ) { $data['transaction']['tags'] = $order_tags; $data['transaction']['tag_mode'] = 'append'; } // any extra meta? if ( is_array( $extra_meta ) && count( $extra_meta ) > 0 ) { $data['transaction_extra_meta'] = $extra_meta; } // Sub-transactions (refunds) if ( method_exists( $order, 'get_refunds' ) ) { // process refunds $refunds = $order->get_refunds(); if ( is_array( $refunds ) ) { // cycle through and add as secondary transactions foreach ( $refunds as $refund ) { // retrieve refund data $refund_data = $refund->get_data(); // process the refund as a secondary transaction // This mimicks the main transaction, taking from the refund object where sensible $refund_id = $refund->get_id(); $refund_title = sprintf( __( 'Refund against transaction #%s', 'zero-bs-crm' ), $order_num ); $refund_description = $refund_title . "\r\n" . __( 'Reason: ', 'zero-bs-crm' ) . $refund_data['reason']; $refund_date_uts = strtotime( $refund_data['date_created']->__toString() ); if ( isset( $refund_data['currency'] ) && !empty( $refund_data['currency'] ) ) { $refund_currency = $refund_data['currency']; } else { $refund_currency = $order_currency; } $refund_transaction = array( 'ref' => $refund_id, 'type' => __( 'Refund', 'zero-bs-crm' ), 'title' => $refund_title, 'status' => __( 'Refunded', 'zero-bs-crm' ), 'total' => -$refund_data['total'], 'desc' => $refund_description, 'date' => $refund_date_uts, 'created' => $refund_date_uts, 'date_completed' => $transaction_completed_date_uts, 'date_paid' => $transaction_paid_date_uts, 'externalSources' => array( array( 'source' => 'woo', 'uid' => $refund_id, // rather than order_num, here we use the refund item id 'origin' => $origin, 'owner' => 0, // for now we hard-type no owner to avoid ownership issues. As we roll out fuller ownership we may want to adapt this. ), ), 'currency' => $refund_currency, 'net' => -( (float)$refund_data['total'] - (float)$refund_data['discount_total'] - (float)$refund_data['total_tax'] - (float)$refund_data['shipping_total'] ), 'tax' => $refund_data['total_tax'], 'fee' => 0, 'discount' => $refund_data['discount_total'], 'shipping' => $refund_data['shipping_total'], 'existence_check_args' => array( 'externalSource' => 'woo', 'externalSourceUID' => $refund_id, 'origin' => $origin, 'onlyID' => true, ), 'lineitems' => array( // here we roll a single refund line item array( 'order' => $refund_id, 'currency' => $refund_currency, 'quantity' => 1, 'price' => -$refund_data['total'], 'total' => -$refund_data['total'], 'title' => $refund_title, 'desc' => $refund_description, 'tax' => $refund_data['total_tax'], 'shipping' => 0, ), ), 'extra_meta' => array(), // this is caught to insert as extraMeta ); // Add any extra meta we can glean in case future useful: $refund_transaction['extra_meta']['order_num'] = $order_num; // backtrace if ( isset( $refund_data['refunded_by'] ) && !empty( $refund_data['refunded_by'] ) ) { $refund_transaction['extra_meta']['refunded_by'] = $refund_data['refunded_by']; } if ( isset( $refund_data['refunded_payment'] ) && !empty( $refund_data['refunded_payment'] ) ) { $refund_transaction['extra_meta']['refunded_payment'] = $refund_data['refunded_payment']; } // add it to the stack $data['secondary_transactions'][] = $refund_transaction; } } } // ==== Invoice $data['invoice'] = array(); if ( $settings['wcinv'] == 1 ) { $data['invoice'] = array( 'id_override' => 'woo-' . $order_num, // we have to add a prefix here otherwise woo order #123 wouldn't insert if invoice with id #123 already exists 'status' => $invoice_status, 'currency' => $order_currency, 'date' => $invoice_creation_date_uts, 'due_date' => $invoice_creation_date_uts, 'net' => $order_data['subtotal'], 'total' => $order_data['total'], 'discount' => $order_data['discount_total'], 'discount_type' => 'm', 'shipping' => $order_data['shipping_total'], 'shipping_tax' => $order_data['shipping_tax'], 'tax' => $order_data['total_tax'], 'ref' => $item_title, 'hours_or_quantity' => 1, 'lineitems' => $data['lineitems'], 'created' => $invoice_creation_date_uts, 'externalSources' => array( array( 'source' => 'woo', 'uid' => $order_post_id, 'origin' => $origin, 'owner' => 0, // for now we hard-type no owner to avoid ownership issues. As we roll out fuller ownership we may want to adapt this. ), ), 'existence_check_args' => $data['source'], 'extra_meta' => array( 'order_post_id' => $order_post_id, 'api' => $from_api, ), ); if ( isset( $shipping_tax_id ) && ! empty( $shipping_tax_id ) ) { $data['invoice']['shipping_taxes'] = $shipping_tax_id; } if ( isset( $data['tax'] ) && isset( $order_data['discount_tax'] ) ) { $data['tax'] -= $order_data['discount_tax']; } if ( is_array( $extra_meta ) && count( $extra_meta ) > 0 ) { $data['invoice']['extra_meta'] = array_merge( $extra_meta, $data['invoice']['extra_meta'] ); } // tags (invoice) if ( $tag_invoice_with_item ) { $data['invoice']['tags'] = $order_tags; $data['invoice']['tag_mode'] = 'append'; } } // Let third parties modify the data array before it's stored as a CRM Object. // This will allow totals to be updated when WooSync pulls data from a store in a different currency. return apply_filters( 'jpcrm_woo_sync_order_data', $data ); } /** * Translates an API order into an import-ready crm objects array * previously `tidy_order_from_api` * * @param $order * * @return array of various objects (contact|company|transaction|invoice) */ public function woocommerce_api_order_to_crm_objects( $order, $origin = '' ){ // $order_status is the WooCommerce order status $settings = $this->settings(); $tag_with_coupon = false; $tag_product_prefix = ( isset( $settings['wctagproductprefix'] ) ) ? zeroBSCRM_textExpose( $settings['wctagproductprefix'] ) : ''; $tag_coupon_prefix = zeroBSCRM_textExpose( $settings['wctagcouponprefix'] ); if ( $settings['wctagcoupon'] == 1 ) { $tag_with_coupon = true; } // Translate API order into local order equivalent $order_data = array( 'status' => $order->status, 'currency' => $order->currency, 'date_created' => $order->date_created_gmt, 'customer_id' => 0, // will be 0 from the API. 'billing' => array( 'company' => $order->billing->company, 'email' => $order->billing->email, 'first_name' => $order->billing->first_name, 'last_name' => $order->billing->last_name, 'address_1' => $order->billing->address_1, 'address_2' => $order->billing->address_2, 'city' => $order->billing->city, 'state' => $order->billing->state, 'postcode' => $order->billing->postcode, 'country' => $order->billing->country, 'phone' => $order->billing->phone, ), 'shipping' => array( 'address_1' => $order->shipping->address_1, 'address_2' => $order->shipping->address_2, 'city' => $order->shipping->city, 'state' => $order->shipping->state, 'postcode' => $order->shipping->postcode, 'country' => $order->shipping->country, ), 'total' => $order->total, 'discount_total' => $order->discount_total, 'shipping_total' => $order->shipping_total, 'shipping_tax' => $order->shipping_tax, 'total_tax' => $order->total_tax, ); $order_line_items = array(); $order_tags = array(); $item_title = ''; // cycle through line items and process foreach ( $order->line_items as $line_item_key => $line_item ) { if ( empty( $item_title ) ) { $item_title = $line_item->name; } else { $item_title = __( 'Multiple Items', 'zero-bs-crm' ); } $order_line_items[] = array( 'order' => $order->id, 'quantity' => $line_item->quantity, 'price' => $line_item->price, 'currency' => $order_data['currency'], 'total' => $line_item->subtotal, 'title' => $line_item->name, 'desc' => $line_item->name . ' (#' . $line_item->product_id . ')', 'tax' => $line_item->total_tax, 'shipping' => 0, ); if ( !in_array( $line_item->name, $order_tags ) ){ $order_tags[] = $tag_product_prefix . $line_item->name; } } // catch coupon_lines and tag if tagging // http://woocommerce.github.io/woocommerce-rest-api-docs/#coupon-properties if ( $tag_with_coupon && isset( $order->coupon_lines ) ) { foreach ( $order->coupon_lines as $coupon_line ) { $order_tags[] = $tag_coupon_prefix . $coupon_line->code; } } // store the order post ID for future reference $extra_meta = array( 'order_num' => $order->number, ); // Finally translate through `woocommerce_order_to_crm_objects` with the argument `$from_api = true` so it skips local store parts of the process return $this->woocommerce_order_to_crm_objects( $order_data, $order, $order->id, $order->number, $order_line_items, $item_title, true, $order_tags, $origin, $extra_meta ); } /** * Attempts to return the percentage completed of a sync * * @param bool $return_counts - Return counts (if true returns an array inc % completed, x of y pages) * @param bool $use_cache - use values cached in object instead of retrieving them directly from Woo * * @return int|bool - percentage completed, or false if not attainable */ public function percentage_completed( $return_counts = false, $use_cache = true ) { // if not using cache, retrieve values from Woo if ( !$use_cache ) { // could probably abstract the retrieval of orders for more nesting. For now it's fairly DRY as only in 2 places. // store/api switch if ( $this->import_mode( $this->site_key ) == JPCRM_WOO_SYNC_MODE_API ) { // API try { // get client $woocommerce = $this->woosync()->get_woocommerce_client( $this->site_key ); // retrieve orders // https://woocommerce.github.io/woocommerce-rest-api-docs/v3.html?php#parameters $orders = $woocommerce->get( 'orders', array( 'page' => 1, 'per_page' => 1, ) ); // retrieve page count from headers: $last_response = $woocommerce->http->getResponse(); $response_headers = $last_response->getHeaders(); $lc_response_headers = array_change_key_case( $response_headers, CASE_LOWER ); if ( !isset( $lc_response_headers['x-wp-totalpages'] ) ) { return false; } $this->woo_total_orders = (int)$lc_response_headers['x-wp-total']; // we can't rely on the X-WP-TotalPages header here, as we're only retrieving one order for speed $this->woo_total_pages = ceil( $this->woo_total_orders / $this->orders_per_page ); } catch ( HttpClientException $e ) { // failed to connect return false; } catch ( Missing_Settings_Exception $e ) { // missing settings means couldn't load lib. return false; } } else { // Local store // Where we're trying to run without WooCommerce, fail. if ( !function_exists( 'wc_get_orders' ) ) { $this->debug( 'Unable to return percentage completed as it appears WooCommerce is not installed.' ); return false; } else { // retrieve orders (just to get total page count (≖_≖ )) $orders = wc_get_orders( array( 'limit' => 1, // no need to retrieve more than one order here 'paged' => 1, 'paginate' => true, ) ); $this->woo_total_orders = $orders->total; // we can't rely on $orders->max_num_pages here, as we're only retrieving one order for speed $this->woo_total_pages = ceil( $this->woo_total_orders / $this->orders_per_page ); } } } // calculate completeness if ( $this->woo_total_pages === 0 ) { // no orders to sync, so complete $percentage_completed = 100; } else { $percentage_completed = $this->current_page / $this->woo_total_pages * 100; } $this->debug( 'Percentage completed: ' . $percentage_completed . '%' ); $this->debug( 'Pages completed: ' . $this->current_page . ' / ' . $this->woo_total_pages ); $this->debug( 'Orders completed: ' . min( $this->current_page * $this->orders_per_page, $this->woo_total_orders ) . ' / ' . $this->woo_total_orders ); $this->debug( 'Percentage completed: ' . $percentage_completed . '%' ); if ( $return_counts ){ return array( 'page_no' => $this->current_page, 'total_pages' => $this->woo_total_pages, 'percentage_completed' => $percentage_completed ); } // return if ( $percentage_completed >= 0 ) { return $percentage_completed; } return false; } /** * Filter contact data passed through the woo checkout * .. allows us to hook in support for things like WooCommerce Checkout Field Editor * * @param array $field_key * @param array $field_value * @param array $contact_data * @param array $order - WooCommerce order object passed down * @param array $custom_fields - CRM Contact custom fields details * * @return array ($contact_data potentially modified) */ private function filter_checkout_contact_fields( $field_key, $field_value, $contact_data, $order, $custom_fields ) { // Checkout Field Editor custom fields support, (where installed) // https://woocommerce.com/products/woocommerce-checkout-field-editor/ if ( function_exists( 'wc_get_custom_checkout_fields' ) ) { $contact_data = $this->checkout_field_editor_filter_field( $field_key, $field_value, $contact_data, $order, $custom_fields ); } // Checkout Field Editor Pro custom fields support, (where installed) // https://wordpress.org/plugins/woo-checkout-field-editor-pro/ if ( class_exists( 'THWCFD' ) ) { $contact_data = $this->checkout_field_editor_pro_filter_field( $field_key, $field_value, $contact_data, $order, $custom_fields ); } return $contact_data; } /** * Filter to add Checkout Field Editor custom fields support, where installed * https://woocommerce.com/products/woocommerce-checkout-field-editor/ * * @param array $field_key * @param array $field_value * @param array $contact_data * @param array $order - WooCommerce order object passed down * @param array $custom_fields - CRM Contact custom fields details * * @return array ($contact_data potentially modified) */ private function checkout_field_editor_filter_field( $field_key, $field_value, $contact_data, $order, $custom_fields ) { // Checkout Field Editor custom fields support, (where installed) if ( function_exists( 'wc_get_custom_checkout_fields' ) ) { // get full fields $fields_info = wc_get_custom_checkout_fields( $order ); // catch specific cases if ( isset( $fields_info[ $field_key ] ) ){ // format info from Checkout Field Editor $field_info = $fields_info[ $field_key ]; switch ( $field_info['type'] ){ // multiselect case 'multiselect': // here the value will be a csv with extra padding (spaces we don't store) $contact_data[ $field_key ] = str_replace( ', ', ',', $field_value ); break; // checkbox, singular case 'checkbox': // here the value will be 1 if it's checked, // but in CRM we only have 'checkboxes' plural, so here we convert '1' to a checked matching box // Here if checked, we'll check the first available checkbox if ( $field_value == 1 ){ // get value if ( isset( $custom_fields[ $field_key ] ) ){ $fields_csv = $custom_fields[ $field_key ][2]; if ( strpos( $fields_csv, ',' ) ){ $field_value = substr( $fields_csv, 0, strpos( $fields_csv, ',' ) ); } else { $field_value = $fields_csv; } } $contact_data[ $field_key ] = $field_value; } break; } } } return $contact_data; } /** * Filter to add Checkout Field Editor Pro (Checkout Manager) for WooCommerce support, where installed * https://wordpress.org/plugins/woo-checkout-field-editor-pro/ * * @param array $field_key * @param array $field_value * @param array $contact_data * @param array $order - WooCommerce order object passed down * @param array $custom_fields - CRM Contact custom fields details * * @return array ($contact_data potentially modified) */ private function checkout_field_editor_pro_filter_field( $field_key, $field_value, $contact_data, $order, $custom_fields ) { // Checkout Field Editor custom fields support, (where installed) if ( class_exists( 'THWCFD' ) ) { // see if we have a matching custom field to infer type conversions from: if ( isset( $custom_fields[ $field_key ] ) ){ // switch on type switch ( $custom_fields[ $field_key ][0] ){ // checkbox, singular case 'checkbox': // here the value will be 1 if it's checked, // but in CRM we only have 'checkboxes' plural, so here we convert '1' to a checked matching box // Here if checked, we'll check the first available checkbox if ( $field_value == 1 ){ // get value if ( isset( $custom_fields[ $field_key ] ) ){ $fields_csv = $custom_fields[ $field_key ][2]; if ( strpos( $fields_csv, ',' ) ){ $field_value = substr( $fields_csv, 0, strpos( $fields_csv, ',' ) ); } else { $field_value = $fields_csv; } } $contact_data[ $field_key ] = $field_value; } break; } } } return $contact_data; } /** * Filter to add WooCommerce Checkout Add-ons fields support, where installed * https://woocommerce.com/products/woocommerce-checkout-add-ons/ * * @param array $order_post_id - WooCommerce order id * @param array $contact_data * @param array $custom_fields - CRM Contact custom fields details * * @return array ($contact_data potentially modified) */ private function checkout_add_ons_add_field_values( $order_post_id, $contact_data, $custom_fields ) { global $zbs; // WooCommerce Checkout Add-ons fields support, where installed if ( function_exists( 'wc_checkout_add_ons' ) ) { $checkout_addons_instance = wc_checkout_add_ons(); $field_values = $checkout_addons_instance->get_order_add_ons( $order_post_id ); // Add any fields we have saved in Checkout Add-ons, // note this overrides any existing values, if conflicting if ( is_array( $field_values ) ){ /* Example Array( [de22a81] => Array ( [name] => tax-id-2 [checkout_label] => tax-id-2 [value] => 999 [normalized_value] => 999 [total] => 0 [total_tax] => 0 [fee_id] => 103 ) ) */ foreach ( $field_values as $checkout_addon_key => $checkout_addon_field ){ $field_key = $zbs->DAL->makeSlug( $checkout_addon_field['name'] ); // brutal addition/override of any fields passed $contact_data[ $field_key ] = $checkout_addon_field['value']; // all array-type values (multi-select etc.) can be imploded for our storage: // multiselect, multicheckbox if ( is_array( $contact_data[ $field_key ] ) ){ // note we used `normalized_value` not `value`, because that matches our custom field storage // ... e.g. "Blue" = `normalized_value`, "blue" = value (but we store case) $contact_data[ $field_key ] = implode( ',', $checkout_addon_field['normalized_value'] ); } // see if we have a matching custom field to infer type conversions from: if ( isset( $custom_fields[ $field_key ] ) ){ // switch on type switch ( $custom_fields[ $field_key ][0] ){ // Select, radio case 'select': case 'radio': // note we used `normalized_value` not `value`, because that matches our custom field storage // ... e.g. "Blue" = `normalized_value`, "blue" = value (but we store case) $contact_data[ $field_key ] = $checkout_addon_field['normalized_value']; break; // checkbox, singular case 'checkbox': // here the value will be 1 if it's checked, // but in CRM we only have 'checkboxes' plural, so here we convert '1' to a checked matching box // Here if checked, we'll check the first available checkbox if ( $contact_data[ $field_key ] == 1 ){ // get value if ( isset( $custom_fields[ $field_key ] ) ){ $fields_csv = $custom_fields[ $field_key ][2]; if ( strpos( $fields_csv, ',' ) ){ $contact_data[ $field_key ] = substr( $fields_csv, 0, strpos( $fields_csv, ',' ) ); } else { $contact_data[ $field_key ] = $fields_csv; } } } break; } } } } } return $contact_data; } /* * Catch site sync connection errors (and log count per site) */ private function log_connection_error() { // increment connection error count $this->woosync()->increment_sync_site_count( $this->site_key, 'site_connection_errors' ); // how many? $error_count = $this->woosync()->get_sync_site_attribute( $this->site_key, 'site_connection_errors', 0 ); $this->debug( 'External store connection error detected (' . $error_count . ')' ); if ( $error_count >= 3 ){ $this->pause_site_due_to_connection_error(); } } /* * Fired when a remote site errors out 3 times, pauses site and adds notification to admin area */ private function pause_site_due_to_connection_error() { $this->debug( 'External store connection error count exceeds maximum ... Pausing site connection' ); // pause $this->woosync()->pause_sync_site( $this->site_key ); // set notification // check not fired within past day $existing_transient = get_transient( 'woosync.syncsite.paused.errors' ); if ( !$existing_transient ) { global $zbs; // add notice & transient $reference = strtotime( 'today midnight' ); $connections_page_url = jpcrm_esc_link( $zbs->slugs['settings'] ) . '&tab=' . $zbs->modules->woosync->slugs['settings'] . '&subtab=' . $zbs->modules->woosync->slugs['settings_connections']; zeroBSCRM_notifyme_insert_notification( get_current_user_id(), -999, -1, 'woosync.syncsite.paused', $connections_page_url, $reference ); set_transient( 'woosync.syncsite.paused.errors', 'woosync.syncsite.paused.errors', HOUR_IN_SECONDS * 24 ); } } }
projects/plugins/crm/modules/woo-sync/includes/class-woo-sync-background-sync.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * WooSync: Background Sync * */ namespace Automattic\JetpackCRM; // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; /** * WooSync Background Sync class */ class Woo_Sync_Background_Sync { /** * Ready Mode, * No syncing will run unless this is set to true. * This is designed to allow for migrations to run on update, before collision-likely sync runs. */ private $ready_mode = false; /** * If set to true this will echo progress of a sync job. */ public $debug = false; /* * Tax rates table storage */ private $tax_rates_table = false; /** * The single instance of the class. */ protected static $_instance = null; /** * Setup WooSync Background Sync * Note: This will effectively fire after core settings and modules loaded * ... effectively on tail end of `init` */ public function __construct( ) { // check we're good to go $this->verify_ready_mode(); if ( $this->ready_mode ){ // load job class require_once JPCRM_WOO_SYNC_ROOT_PATH. 'includes/class-woo-sync-background-sync-job.php'; // Initialise Hooks $this->init_hooks(); // Schedule cron $this->schedule_cron(); } } /** * Main Class Instance. * * Ensures only one instance of Woo_Sync_Background_Sync is loaded or can be loaded. * * @since 2.0 * @static * @see * @return Woo_Sync_Background_Sync main instance */ public static function instance() { if ( is_null( self::$_instance ) ) { self::$_instance = new self(); } return self::$_instance; } /** * Returns main class instance */ public function woosync(){ global $zbs; return $zbs->modules->woosync; } /** * Checks that all 'pre-ready' conditions are met before enabling sync * (Critical migrations when we moved from 1 to many site syncing) */ public function verify_ready_mode( ){ // check for critical migration when we moved from 1 to many site syncing $migration_status = get_option( 'jpcrm_woosync_52_mig' ); if ( $migration_status ){ $this->ready_mode = true; } return $this->ready_mode; } /** * If $this->debug is true, outputs passed string * * @param string - Debug string */ private function debug( $str ){ if ( $this->debug ){ echo '[' . zeroBSCRM_locale_utsToDatetime( time() ) . '] ' . $str . '<br>'; } } /** * Initialise Hooks */ private function init_hooks() { // cron add_action( 'jpcrm_woosync_sync', array( $this, 'cron_job' ) ); // add our cron task to the core crm cron monitor list add_filter( 'jpcrm_cron_to_monitor', array( $this, 'add_cron_monitor' ) ); global $zbs; // Abort if Woo isn't active. if ( ! $zbs->woocommerce_is_active() ) { return; } // Order changes: add_action( 'woocommerce_order_status_changed', array( $this, 'add_update_from_woo_order' ), 1, 1 ); add_action( 'woocommerce_process_shop_order_meta', array( $this, 'add_update_from_woo_order' ), 100, 1 ); add_action( 'woocommerce_deposits_create_order', array( $this, 'add_update_from_woo_order' ), 100, 1 ); if ( jpcrm_woosync_is_hpos_enabled() ) { // These hooks are available as of Woo 7.1.0 and are required for HPOS. add_action( 'woocommerce_before_trash_order', array( $this, 'woocommerce_order_trashed' ), 10, 1 ); add_action( 'woocommerce_before_delete_order', array( $this, 'woocommerce_order_deleted' ), 10, 1 ); } else { add_action( 'wp_trash_post', array( $this, 'woocommerce_order_trashed' ), 10, 1 ); add_action( 'before_delete_post', array( $this, 'woocommerce_order_deleted' ), 10, 1 ); } // Catch WooCommerce customer address changes and update contact: add_action( 'woocommerce_customer_save_address', array( $this, 'update_contact_address_from_wp_user' ), 10, 3 ); } /** * Setup cron schedule */ private function schedule_cron( ) { // schedule it if ( ! wp_next_scheduled( 'jpcrm_woosync_sync' ) ) { wp_schedule_event( time(), '5min', 'jpcrm_woosync_sync' ); } } /** * Run cron job */ public function cron_job(){ // define global to mark this as a cron call define( 'jpcrm_woosync_cron_running', 1 ); // fire job $this->sync_orders(); } /** * Returns bool as to whether or not the current call was made via cron */ private function is_cron(){ return defined( 'jpcrm_woosync_cron_running' ); } /** * Filter call to add the cron zbssendbot to the watcher system * * @param array $crons * @return array */ function add_cron_monitor( $crons ) { if ( is_array( $crons ) ) { $crons[ 'jpcrm_woosync_sync' ] = '5min'; //'hourly'; } return $crons; } /** * Main job function: using established settings, this will retrieve and import orders * from WooCommerce into CRM. This can be called in three 'modes' * - via cron (as defined by `jpcrm_woosync_cron_running`) * - via AJAX (if not via cron and not in debug mode) * - for debug (if $this->debug is set) This is designed to be called inline and will output progress of sync job * * * @return mixed (int|json) * - if cron originated: a count of orers imported is returned * - if not cron originated (assumes AJAX): * - if completed sync: JSON summary info is output and then exit() is called * - else count of orders imported is returned */ public function sync_orders(){ global $zbs; $this->debug( 'Fired `sync_orders()`.' ); if ( !$this->ready_mode ){ $this->debug( 'Blocked by !ready_mode.' ); // return blocker error return array( 'status' => 'not_in_ready_mode', 'status_short_text' => __( 'Unable to complete migration 5.2', 'zero-bs-crm' ), 'status_long_text' => __( 'WooSync was unable to complete a necessary migration and therefore cannot yet sync.', 'zero-bs-crm' ), ); } $sync_sites = $this->woosync()->get_active_sync_sites(); $this->debug( 'Sync Sites:<pre>' . print_r( $sync_sites, 1 ) . '</pre>' ); if ( !is_array( $sync_sites ) ){ $this->debug( 'Failed to retrieve sites to sync! ' ); } // check not currently running if ( defined( 'jpcrm_woosync_running' ) ) { $this->debug( 'Attempted to run `sync_orders()` when job already in progress.' ); // return blocker error return array( 'status' => 'job_in_progress' ); } $this->debug( 'Commencing syncing ' . count( $sync_sites ) . ' sites.' ); // prep silos $total_remaining_pages = 0; $total_pages = 0; $total_active_connections = 0; $total_paused_connections = 0; $errors = array(); // cycle through each sync site and attempt sync foreach ( $sync_sites as $site_key => $site_info ){ // check not marked 'paused' if ( isset( $site_info['paused'] ) && $site_info['paused'] ){ // skip it $total_paused_connections++; $this->debug( 'Skipping Sync for ' . $site_info['domain'] . ' (mode: ' . $site_info['mode'] . ') - Paused' ); continue; } $this->debug( 'Starting Sync for ' . $site_info['domain'] . ' (mode: ' . $site_info['mode'] . ')' ); $total_active_connections++; // blocker if ( !defined( 'jpcrm_woosync_running' ) ) { define( 'jpcrm_woosync_running', 1 ); } // init class $sync_job = new Woo_Sync_Background_Sync_Job( $site_key, $site_info, $this->debug ); // start sync job $sync_result = $sync_job->run_sync(); $this->debug( 'Sync Result:<pre>' . print_r( $sync_result, 1 ) . '</pre>' ); /* will be false or array( 'total_pages' => $total_pages, 'total_remaining_pages' => $total_remaining_pages, 'errors' => $errors, );*/ if ( is_array( $sync_result ) && isset( $sync_result['total_pages'] ) && isset( $sync_result['total_remaining_pages'] ) ){ // maintain overall % counts later used to provide a summary % across sync site connections $total_pages += (int)$sync_result['total_pages']; $total_remaining_pages += $sync_result['total_remaining_pages']; } } // discern completeness if ( $total_active_connections > 0 ){ if ( $total_paused_connections === 0 ){ // no paused connections if ( $total_remaining_pages == 0 ){ $sync_status = 'sync_completed'; $overall_percentage = 100; $status_short_text = __( 'Sync Completed', 'zero-bs-crm' ); $status_long_text = __( 'WooSync has imported all existing orders and will continue to import future orders.', 'zero-bs-crm' ); } else { $sync_status = 'sync_part_complete'; $overall_percentage = (int)( ( $total_pages - $total_remaining_pages ) / $total_pages * 100 ); $status_short_text = __( 'Syncing content from WooCommerce...', 'zero-bs-crm' ); $status_long_text = ''; } } else { // has some paused connections if ( $total_remaining_pages == 0 ){ $sync_status = 'sync_completed'; $overall_percentage = 100; $status_short_text = __( 'Sync Completed for active connections', 'zero-bs-crm' ); $status_long_text = __( 'WooSync has imported existing orders for sites with active connections, but could not import from paused site connections.', 'zero-bs-crm' ); } else { $sync_status = 'sync_part_complete'; $overall_percentage = (int)( ( $total_pages - $total_remaining_pages ) / $total_pages * 100 ); $status_short_text = __( 'Syncing content from WooCommerce...', 'zero-bs-crm' ); $status_long_text = ''; } } } else { if ( $total_remaining_pages == 0 ){ $sync_status = 'sync_completed'; $overall_percentage = 100; $status_short_text = __( 'Sync Previously Completed', 'zero-bs-crm' ); $status_long_text = __( 'WooSync imported orders previously, but is not currently actively syncing due to paused connections.', 'zero-bs-crm' ); } else { $sync_status = 'sync_part_complete'; $overall_percentage = (int)( ( $total_pages - $total_remaining_pages ) / $total_pages * 100 ); $status_short_text = __( 'WooSync is trying to sync, but cannot retrieve all orders due to paused connections.', 'zero-bs-crm' ); $status_long_text = ''; } } // if cron, we just return count if ( $this->is_cron() ) { return array( 'status' => $sync_status, // sync_completed sync_part_complete job_in_progress error 'status_short_text' => $status_short_text, 'percentage_completed' => $overall_percentage, ); } else { $this->debug( 'Completed multi-site sync job: ' . $sync_status ); $woosync_status_array = array( 'status' => $sync_status, 'status_short_text' => $status_short_text, 'status_long_text' => $status_long_text, 'page_no' => ( $total_pages - $total_remaining_pages ), 'orders_imported' => 0, 'percentage_completed' => $overall_percentage, ); $woosync_latest_stats = $this->woosync()->get_jpcrm_woo_latest_stats(); echo json_encode( array_merge( $woosync_latest_stats, $woosync_status_array ) ); exit(); } } /** * Update contact address of a wp user (likely WooCommerce user) * * @param int $user_id (WordPress user id) * @param string $address_type (e.g. `billing`) */ public function update_contact_address_from_wp_user( $user_id = -1, $address_type = 'billing' ){ global $zbs; // retrieve contact ID from WP user ID $contact_id = $zbs->DAL->contacts->getContact(array( 'WPID' => $user_id, 'onlyID' => true )); if ( $contact_id > 0 ){ // retrieve customer data from WP user ID $woo_customer_meta = get_user_meta( $user_id ); if ( $address_type == 'billing' ){ $data = array( 'addr1' => $woo_customer_meta['billing_address_1'][0], 'addr2' => $woo_customer_meta['billing_address_2'][0], 'city' => $woo_customer_meta['billing_city'][0], 'county' => $woo_customer_meta['billing_state'][0], 'country' => $woo_customer_meta['billing_country'][0], 'postcode' => $woo_customer_meta['billing_postcode'][0], ); } else { $data = array( 'secaddr1' => $woo_customer_meta['shipping_address_1'][0], 'secaddr2' => $woo_customer_meta['shipping_address_2'][0], 'seccity' => $woo_customer_meta['shipping_city'][0], 'seccounty' => $woo_customer_meta['shipping_state'][0], 'seccountry' => $woo_customer_meta['shipping_country'][0], 'secpostcode' => $woo_customer_meta['shipping_postcode'][0], ); } // addUpdate as limited fields $limited_fields_array = array(); foreach ( $data as $k => $v ){ $limited_fields_array[] = array( 'key' => 'zbsc_' .$k, 'val' => $v, 'type'=> '%s' ); } // then addUpdate $zbs->DAL->contacts->addUpdateContact(array( 'id' => $contact_id, 'limitedFields' => $limited_fields_array )); } } /** * Catches trashing of WooCommerce orders and (optionally) removes transactions from CRM * * @param int $order_post_id */ public function woocommerce_order_trashed( $order_post_id ) { // retrieve action $delete_action = $this->woosync()->settings->get( 'auto_trash', false ); // action? if ( $delete_action === 'do_nothing' ) { return; } // act $this->woocommerce_order_removed( $order_post_id, $delete_action ); } /** * Catches deletion of WooCommerce orders and (optionally) removes transactions from CRM * * @param int $order_post_id */ public function woocommerce_order_deleted( $order_post_id ) { // retrieve action $delete_action = $this->woosync()->settings->get( 'auto_delete', false ); // action? if ( $delete_action === 'do_nothing' ) { return; } // act $this->woocommerce_order_removed( $order_post_id, $delete_action ); } /** * Catches deletion of WooCommerce orders and (optionally) removes transactions from CRM * * @param int $order_post_id * @param str $delete_action */ private function woocommerce_order_removed( $order_post_id, $delete_action ) { global $zbs; if ( ! jpcrm_woosync_is_hpos_enabled() ) { // was it an order that was deleted? $post_type = get_post_type( $order_post_id ); if ( $post_type !== 'shop_order' ) { return; } } // catch default if ( empty( $delete_action ) ) { $delete_action = 'change_status'; } // retrieve order $order = wc_get_order( $order_post_id ); // Sometimes there's a custom order number... if ( method_exists( $order, 'get_order_number' ) ) { $order_num = $order->get_order_number(); } else { // order number by default is the same as the order post ID $order_num = $order_post_id; } // get transaction $transaction_id = $this->woosync()->get_transaction_from_order_num( $order_num, '', true ); if ( $transaction_id > 0 ) { // retrieve any associated invoices $invoice_id = $zbs->DAL->transactions->get_transaction_invoice_id( $transaction_id ); // act switch ( $delete_action ) { // change the transaction (and invoice) status to 'Deleted' case 'change_status': // set status $zbs->DAL->transactions->setTransactionStatus( $transaction_id, __( 'Deleted', 'zero-bs-crm' ) ); // Also change the status on any woo-created associated invoice if ( $invoice_id > 0 ) { $zbs->DAL->invoices->setInvoiceStatus( $invoice_id, __( 'Deleted', 'zero-bs-crm' ) ); } break; // Delete the transaction (and invoice) and add log to contact case 'hard_delete_and_log': // delete transaction $zbs->DAL->transactions->deleteTransaction( array( 'id' => $transaction_id )); // Also delete any woo-created associated invoice if ( $invoice_id > 0 ) { $zbs->DAL->invoices->deleteInvoice( array( 'id' => $invoice_id, 'saveOrphans' => false )); } // get contact(s) to add log to // only 1:1 via ui currently, but is support for many in DAL $contacts = $zbs->DAL->transactions->get_transaction_contacts( $transaction_id ); if ( is_array( $contacts ) ) { foreach ( $contacts as $contact ) { // add log $zbs->DAL->logs->addUpdateLog( array( 'data' => array( 'objtype' => ZBS_TYPE_CONTACT, 'objid' => $contact['id'], 'type' => 'transaction_deleted', 'shortdesc' => __( 'WooCommerce Order Deleted', 'zero-bs-crm' ), 'longdesc' => sprintf( __( 'Transaction #%s was removed from your CRM after the related WooCommerce order #%s was deleted.', 'zero-bs-crm' ), $transaction_id, $order_num ) ), )); } } break; } } } /** * Add or update an order from local WooCommerce (passthru to sync job) * * @param int $order_id - Order id from WooCommerce (may be different than $order_num) */ public function add_update_from_woo_order( $order_id ) { $sync_sites = $this->woosync()->settings->get( 'sync_sites' ); // if there's a local site and if it's not paused if ( isset( $sync_sites['local'] ) && empty( $sync_sites['local']['paused'] ) ) { $local_site_info = $sync_sites['local']; $local_sync_job = new Woo_Sync_Background_Sync_Job( 'local', $local_site_info, $this->debug ); $local_sync_job->add_update_from_woo_order( $order_id ); } } /** * Get tax rates table (cached) */ public function get_tax_rates_table( $refresh_from_db = false ) { if ( !is_array( $this->tax_rates_table ) || $refresh_from_db ){ // retrieve tax table to feed in tax links $this->tax_rates_table = zeroBSCRM_taxRates_getTaxTableArr( true ); } return $this->tax_rates_table; } }
projects/plugins/crm/modules/woo-sync/includes/jpcrm-woo-sync-contact-tabs.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * WooSync: Contact Tabs * Adds extra tabs to contact single view: vitals tab set */ namespace Automattic\JetpackCRM; // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; /** * WooSync Contact Tabs class */ class Woo_Sync_Contact_Tabs { /** * The single instance of the class. */ protected static $_instance = null; /** * Setup WooSync Contact Tabs * Note: This will effectively fire after core settings and modules loaded * ... effectively on tail end of `init` */ public function __construct( ) { // Initialise Hooks $this->init_hooks(); } /** * Main Class Instance. * * Ensures only one instance of Woo_Sync_Contact_Tabs is loaded or can be loaded. * * @since 2.0 * @static * @see * @return Woo_Sync_Contact_Tabs main instance */ public static function instance(){ if ( is_null( self::$_instance ) ) { self::$_instance = new self(); } return self::$_instance; } /** * Initialise Hooks */ private function init_hooks( ){ // add in tabs add_filter( 'jetpack-crm-contact-vital-tabs', array( $this, 'append_info_tabs' ) , 10, 2 ); } /** * Wire in ant applicable tabs (subs, memberships, bookings) */ public function append_info_tabs( $array, $id ) { if ( !is_array($array) ){ $array = array(); } // Woo Subscriptions if ( function_exists( 'wcs_get_users_subscriptions' ) ){ $array[] = array( 'id' => 'woocommerce-subscriptions-tab', 'name' => __( 'Subscriptions', 'zero-bs-crm' ), 'content' => $this->generate_subscriptions_tab_html( $id ), ); } // Woo Memberships if ( function_exists( 'wc_memberships_get_user_memberships' ) ){ $array[] = array( 'id' => 'woocommerce-memberships-tab', 'name' => __('Memberships', 'zero-bs-crm'), 'content' => $this->generate_memberships_tab_html( $id ) ); } // Woo Bookings if ( class_exists( 'WC_Bookings_Controller' ) ){ $array[] = array( 'id' => 'woocommerce-bookings-tab', 'name' => __('Upcoming Bookings', 'zero-bs-crm'), 'content' => $this->generate_bookings_tab_html( $id ) ); } return $array; } /** * Draw the Woo Bookings Contact Vitals tab */ private function generate_bookings_tab_html( $object_id = -1 ){ global $zbs; // return html $html = ''; // retrieve bookings $bookings = $zbs->modules->woosync->get_future_woo_bookings_for_object( $object_id ); if ( count( $bookings ) > 0 ){ $html .= '<div class="table-wrap woo-sync-book">'; $html .= '<table class="ui single line table">'; $html .= '<thead>'; $html .= '<tr>'; $html .= '<th scope="col" class="booking-id">' . __( 'ID', 'woocommerce-bookings' ) . '</th>'; $html .= '<th scope="col" class="booked-product">' . __( 'Booked', 'woocommerce-bookings' ) . '</th>'; $html .= '<th scope="col" class="booking-start-date">' . __( 'Start Date', 'woocommerce-bookings') . '</th>'; $html .= '<th scope="col" class="booking-end-date">' . __( 'End Date', 'woocommerce-bookings' ) . '</th>'; $html .= '<th scope="col" class="booking-status">' . __( 'Status', 'woocommerce-bookings' ) . '</th>'; $html .= '</tr>'; $html .= '</thead>'; $html .= '<tbody>'; foreach ( $bookings as $booking ){ $html .= '<tr>'; $html .= '<td class="booking-id">' . esc_html( $booking->get_id() ) . '</td>'; $html .= '<td class="booked-product">'; if ( $booking->get_product() && $booking->get_product()->is_type( 'booking' ) ) : $html .= '<a href="' . esc_url( get_permalink( $booking->get_product()->get_id() ) ) . '">'; $html .= esc_html( $booking->get_product()->get_title() ); $html .= '</a>'; endif; $html .= '</td>'; $status = esc_html( wc_bookings_get_status_label( $booking->get_status() ) ); $html .= '<td class="booking-start-date">' . esc_html( $booking->get_start_date() ) . '</td>'; $html .= '<td class="booking-end-date">' . esc_html( $booking->get_end_date() ) . '</td>'; $html .= '<td><span class="ui label ' . strtolower( $status ) . '">'.$status.'</span></td>'; $html .= '</tr>'; } $html .= '</tbody>'; $html .= '</table>'; $html .= '</div>'; } else { $html .= '<div class="ui message info blue"><i class="ui icon info circle"></i>' . __( "This contact does not have any upcoming WooCommerce Bookings.", 'zero-bs-crm' ) . '</div>'; } return $html; } /** * Returns HTML that can be used to render the Subscriptions Table. * When no WordPress user is found a <div> is returned with an info message. * When no subscriptions are found a <div> is returned with an info message. * * @param integer $object_id Contact ID. * @return string HTML that can be used to render the Subscriptions Table. */ private function generate_subscriptions_tab_html( $object_id = -1 ) { $subscriptions = array(); if ( zeroBSCRM_getClientPortalUserID( $object_id ) > 0 ) { // Retrieve any subs against the main email or aliases. $subscriptions = $this->get_contact_subscriptions( $object_id ); } if ( count( $subscriptions ) === 0 ) { return '<div class="ui message info blue"><i class="ui icon info circle"></i>' . __( 'This contact does not have any WooCommerce Subscriptions yet.', 'zero-bs-crm' ) . '</div>'; } $html = ''; $html .= '<div class="table-wrap woo-sync-subs">'; $html .= '<table class="ui single line table">'; $html .= '<thead><tr>'; $html .= '<th>' . __( 'Subscription', 'zero-bs-crm' ) . '</th>'; $html .= '<th>' . __( 'Status', 'zero-bs-crm' ) . '</th>'; $html .= '<th>' . __( 'Amount', 'zero-bs-crm' ) . '</th>'; $html .= '<th>' . __( 'Start', 'zero-bs-crm' ) . '</th>'; $html .= '<th>' . __( 'Renews', 'zero-bs-crm' ) . '</th>'; $html .= '</tr></thead>'; $html .= '<tbody>'; foreach ( $subscriptions as $order_id ) { $order = wc_get_order( $order_id ); $status = $order->get_status(); $date_created = $order->get_date_created(); $date_renew = $order->get_date( 'next_payment_date' ); $price = $order->get_formatted_order_total(); $name = ''; $sub_link = admin_url( "post.php?post={$order_id}&action=edit" ); $created = jpcrm_uts_to_date_str( strtotime( $date_created ) ); $next = jpcrm_uts_to_date_str( strtotime( $date_renew ) ); $html .= '<tr>'; $html .= '<td><a href="' . esc_url( $sub_link ) . '">' . $name . __( ' Subscription #', 'zero-bs-crm' ) . $order_id . '</a></td>'; $html .= '<td><span class="ui label ' . $status . '">' . $status . '</span></td>'; $html .= '<td>' . $price . '</td>'; $html .= '<td>' . $created . '</td>'; $html .= '<td>' . $next . '</td>'; $html .= '</tr>'; } $html .= '</tbody>'; $html .= '</table>'; $html .= '</div>'; return $html; } /** * Generate HTML for memberships contact vitals tab */ private function generate_memberships_tab_html( $object_id = -1 ) { $data = $this->get_contact_memberships( $object_id ); if ( $data['message'] === 'notfound' || count( $data['memberships'] ) <= 0 ) { return '<div class="ui message info blue"><i class="ui icon info circle"></i>' . __( 'This contact does not have any WooCommerce Memberships yet.', 'zero-bs-crm' ) . '</div>'; } $memberships = $data['memberships']; $html = ''; $html .= '<div class="table-wrap woo-sync-mem">'; $html .= '<table class="ui single line table">'; $html .= '<thead><tr>'; $html .= '<th>' . __( 'Membership', 'zero-bs-crm' ) . '</th>'; $html .= '<th>' . __( 'Status', 'zero-bs-crm' ) . '</th>'; $html .= '<th>' . __( 'Name', 'zero-bs-crm' ) . '</th>'; $html .= '<th>' . __( 'Start', 'zero-bs-crm' ) . '</th>'; $html .= '<th>' . __( 'Expires', 'zero-bs-crm' ) . '</th>'; $html .= '</tr></thead>'; $html .= '<tbody>'; foreach ( $memberships as $membership ) { // populate fields $member_id = $membership->id; $status = $this->display_membership_status( $membership->get_status() ); $name = $membership->plan->name; $date_expires = $membership->get_end_date( 'Y-m-d H:i:s' ); $date_created = $membership->get_start_date(); $created = jpcrm_uts_to_date_str( strtotime( $date_created ) ); if ( empty( $date_expires ) ) { $expires = __( 'Never', 'zero-bs-crm' ); } else { $expires = jpcrm_uts_to_date_str( strtotime( $date_expires ) ); } $membership_link = admin_url( 'post.php?post=' . $membership->id . '&action=edit' ); $html .= '<tr>'; $html .= '<td><a href="' . esc_url( $membership_link ) . '">' . sprintf( __( ' Membership #%s', 'zero-bs-crm' ), $member_id ) . '</a></td>'; $html .= '<td><span class="ui label ' . $status . '">' . $status . '</span></td>'; $html .= '<td>' . $name . '</td>'; $html .= '<td>' . $created . '</td>'; $html .= '<td>' . $expires . '</td>'; $html .= '</tr>'; } $html .= '</tbody>'; $html .= '</table>'; $html .= '</div>'; return $html; } /** * Helper to display membership statuses */ private function display_membership_status( $status = '' ){ $woocommerce_statuses = array( 'wcm-active' => __('active', 'zero-bs-crm'), 'wcm-complimentary' => __('complimentary', 'zero-bs-crm'), 'wcm-pending' => __('pending', 'zero-bs-crm'), 'wcm-delayed' => __('delayed', 'zero-bs-crm'), 'wcm-pending-cancelletion' => __('pending cancellation', 'zero-bs-crm'), 'wcm-paused' => __('paused', 'zero-bs-crm'), 'wcm-expired' => __('expired', 'zero-bs-crm'), 'wcm-cancelled' => __('cancelled', 'zero-bs-crm') ); $display_status = $status; if ( array_key_exists( $status, $woocommerce_statuses ) ){ $display_status = $woocommerce_statuses[$status]; } return $display_status; } /** * Retrieves memberships for a contact */ private function get_contact_memberships( $object_id = -1 ){ $wp_id = zeroBS_getCustomerWPID( $object_id ); if ( $wp_id > 0 ){ return array( 'message' => 'success', 'memberships' => wc_memberships_get_user_memberships( $wp_id ) ); } else { return array( 'message' => 'notfound', 'memberships' => array() ); } } /** * Retrieves any Woo Subscriptions against a contact * * @param int $object_id Contact ID. */ private function get_contact_subscriptions( $object_id = -1 ) { $all_sub_statuses = array_keys( wcs_get_subscription_statuses() ); $subscription_ids = array(); if ( $object_id > 0 ) { // 1 - get the subscription IDs for the attached wp user $user_id = zeroBS_getCustomerWPID( $object_id ); if ( $user_id > 0 ) { $args = array( 'customer_id' => $user_id, 'status' => $all_sub_statuses, 'type' => 'shop_subscription', 'return' => 'ids', ); $subscription_ids = wc_get_orders( $args ); } // 2 - find subs for all emails (inc aliases) $emails = zeroBS_customerEmails( $object_id ); if ( is_array( $emails ) ) { foreach ( $emails as $email ) { if ( empty( $email ) ) { continue; } $args = array( 'billing_email' => $email, 'status' => $all_sub_statuses, 'type' => 'shop_subscription', 'return' => 'ids', ); $subscription_ids_by_email = wc_get_orders( $args ); $subscription_ids = array_merge( $subscription_ids, $subscription_ids_by_email ); } } // 3 - remove any duplicate IDs between array_1 and array_2 $subscription_ids = array_unique( $subscription_ids, SORT_REGULAR ); } return $subscription_ids; } }
projects/plugins/crm/modules/woo-sync/includes/segment-conditions/class-segment-condition-woo-order-count.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * WooSync: Segment Condition: Order Count * */ // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; /** * WooSync: Segment Condition: Order Count class */ class Segment_Condition_Woo_Order_Count extends zeroBSCRM_segmentCondition { public $key = 'woo_order_count'; public $condition = array( 'category' => 'WooSync', 'position' => 2, 'operators' => array( 'equal', 'notequal', 'larger', 'less', 'intrange', 'largerequal', 'lessequal' ), 'fieldname' => 'woo_order_count', 'inputmask' => 'int' ); /** * init, here just used to set translated attributes. */ public function __construct( $constructionArgs = array() ) { // set translations $this->condition['name'] = __( 'WooCommerce Order Count', 'zero-bs-crm' ); $this->condition['description'] = __( 'Select contacts who match WooCommerce customers with specific order counts', 'zero-bs-crm' ); // fire main class init $this->init( $constructionArgs ); } public function conditionArg( $startingArg=false, $condition=false, $conditionKeySuffix=false ){ global $zbs, $ZBSCRM_t; // here we just count objlinks, which has the vulnerability that if there are orphan links created it'll show wrong count, but for now is 'enough' // Note this also ignores ownership :O $order_count_query = "SELECT COUNT(DISTINCT(obj_links.zbsol_objid_from)) FROM " . $ZBSCRM_t['objlinks'] . " obj_links" . " INNER JOIN " . $ZBSCRM_t['externalsources'] . " ext_sources" . " ON obj_links.zbsol_objid_from = ext_sources.zbss_objid" . " WHERE obj_links.zbsol_objtype_from = " . ZBS_TYPE_TRANSACTION . " AND obj_links.zbsol_objtype_to = " . ZBS_TYPE_CONTACT . " AND obj_links.zbsol_objid_to = contact.ID" . " AND ext_sources.zbss_objtype = " . ZBS_TYPE_TRANSACTION; /* example: SELECT * FROM wp_zbs_object_links obj_links INNER JOIN wp_zbs_externalsources ext_sources ON obj_links.zbsol_objid_from = ext_sources.zbss_objid WHERE obj_links.zbsol_objtype_from = 5 AND obj_links.zbsol_objtype_to = 1 AND obj_links.zbsol_objid_to = {CONTACTID} AND ext_sources.zbss_objtype = 5 */ if ( $condition['operator'] == 'equal' ) return array('additionalWhereArr'=> array( 'woo_order_count_equal' . $conditionKeySuffix => array( "(" . $order_count_query . ")", '=', '%d', $condition['value'] ) ) ); else if ( $condition['operator'] == 'notequal' ) return array('additionalWhereArr'=> array( 'woo_order_count_notequal' . $conditionKeySuffix => array( "(" . $order_count_query . ")", '<>', '%d', $condition['value'] ) ) ); else if ( $condition['operator'] == 'larger' ) return array('additionalWhereArr'=> array( 'woo_order_count_larger' . $conditionKeySuffix => array( "(" . $order_count_query . ")", '>', '%d', $condition['value'] ) ) ); else if ( $condition['operator'] == 'largerequal' ) return array('additionalWhereArr'=> array( 'woo_order_count_larger_equal' . $conditionKeySuffix => array( "(" . $order_count_query . ")", '>=', '%d', $condition['value'] ) ) ); else if ( $condition['operator'] == 'less' ) return array('additionalWhereArr'=> array( 'woo_order_count_smaller' . $conditionKeySuffix => array( "(" . $order_count_query . ")", '<', '%d', $condition['value'] ) ) ); else if ( $condition['operator'] == 'lessequal' ) return array('additionalWhereArr'=> array( 'woo_order_count_smaller_equal' . $conditionKeySuffix => array( "(" . $order_count_query . ")", '<=', '%d', $condition['value'] ) ) ); else if ( $condition['operator'] == 'intrange' ) return array('additionalWhereArr'=> array( 'woo_order_count_larger' . $conditionKeySuffix => array( "(" . $order_count_query . ")", '>=', '%d', $condition['value'] ), 'woo_order_count_smaller' . $conditionKeySuffix => array( "(" . $order_count_query . ")", '<=', '%d', $condition['value2'] ) ) ); return $startingArg; } }
projects/plugins/crm/modules/woo-sync/includes/segment-conditions/class-segment-condition-woo-customer.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * WooSync: Segment Condition: Is WooCommerce Customer * */ // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; /** * WooSync: Segment Condition: Is WooCommerce Customer class */ class Segment_Condition_Woo_Customer extends zeroBSCRM_segmentCondition { public $key = 'is_woo_customer'; public $condition = array( 'position' => 1, 'category' => 'WooSync', 'operators' => array( 'istrue', 'isfalse' ), 'fieldname' =>'is_woo_customer' ); /** * init, here just used to set translated attributes. */ public function __construct( $constructionArgs = array() ) { // set translations $this->condition['name'] = __( 'WooCommerce Customer', 'zero-bs-crm' ); $this->condition['description'] = __( 'Select contacts who are or are not also WooCommerce customers', 'zero-bs-crm' ); // fire main class init $this->init( $constructionArgs ); } public function conditionArg( $startingArg=false, $condition=false, $conditionKeySuffix=false ){ global $zbs, $ZBSCRM_t; if ( $condition['operator'] == 'istrue' ) return array('additionalWhereArr'=> array( 'is_woo_customer' . $conditionKeySuffix => array( 'ID','IN', '(SELECT DISTINCT zbss_objid FROM ' . $ZBSCRM_t['externalsources'] . " WHERE zbss_objtype = ".ZBS_TYPE_CONTACT." AND zbss_source = %s)", array( 'woo' ) ) ) ); if ( $condition['operator'] == 'isfalse' ) return array('additionalWhereArr'=> array( 'is_woo_customer' . $conditionKeySuffix => array( 'ID','NOT IN', '(SELECT DISTINCT zbss_objid FROM ' . $ZBSCRM_t['externalsources'] . " WHERE zbss_objtype = ".ZBS_TYPE_CONTACT." AND zbss_source = %s)", array( 'woo' ) ) ) ); return $startingArg; } }
projects/plugins/crm/modules/woo-sync/admin/settings/connections.page.ajax.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * WooSync: Admin: Connections page AJAX * */ // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; /** * Language labels for JS */ function jpcrm_woosync_connections_js_language_labels( $language_array = array() ){ // add our labels // connections page $language_array['connect-woo'] = __( 'Connect WooCommerce Store', 'zero-bs-crm' ); $language_array['connect-woo-site-url'] = __( 'Enter your Store URL:', 'zero-bs-crm' ); $language_array['connect-woo-site-placeholder'] = __( 'e.g. https://examplestore.com', 'zero-bs-crm' ); $language_array['connect-woo-go'] = __( 'Connect Store', 'zero-bs-crm' ); $language_array['connect-woo-invalid-url'] = __( 'Invalid URL', 'zero-bs-crm' ); $language_array['connect-woo-invalid-url-empty'] = __( 'Please enter your store URL!', 'zero-bs-crm' ); $language_array['connect-woo-invalid-url-detail'] = __( 'This doesn\'t look like a valid URL. If this is not correct, please contact support.', 'zero-bs-crm' ); $language_array['connect-woo-invalid-url-http'] = __( 'Invalid URL - Store URL must use HTTPS', 'zero-bs-crm' ); $language_array['connect-woo-invalid-url-duplicate'] = __( 'This Store URL already exists!', 'zero-bs-crm' ); $language_array['connect-woo-ajax-error'] = __( 'AJAX Error', 'zero-bs-crm' ); return $language_array; } add_filter( 'zbs_globaljs_lang', 'jpcrm_woosync_connections_js_language_labels' ); /** * JS Vars (get added to jpcrm_root var stack) */ function jpcrm_woosync_connections_js_vars( $var_array = array() ){ global $zbs; // add our vars // now retrieved via AJAX - $var_array['connect_woo_querystring'] = $this->get_external_woo_url_for_oauth_query_string(); $var_array['woosync_token'] = wp_create_nonce( "jpcrm-woosync-ajax-nonce" ); // add array of sync sites $sync_sites = $zbs->modules->woosync->settings->get( 'sync_sites' ); $woosync_connections = array(); foreach ( $sync_sites as $site ) { $woosync_connections[] = rtrim( $site['domain'], '/' ); } $var_array['woosync_connections'] = $woosync_connections; return $var_array; } add_filter( 'zbs_globaljs_vars', 'jpcrm_woosync_connections_js_vars' ); // Send a quote via email add_action( 'wp_ajax_jpcrm_woosync_get_auth_url', 'jpcrm_woosync_ajax_get_auth_url' ); function jpcrm_woosync_ajax_get_auth_url(){ // Check nonce check_ajax_referer( 'jpcrm-woosync-ajax-nonce', 'sec' ); // Check perms if ( !zeroBSCRM_isZBSAdminOrAdmin() ) { zeroBSCRM_sendJSONError(array()); } // retrieve params if ( isset( $_POST['site_url'] ) ){ $site_url = sanitize_text_field( $_POST['site_url'] ); if ( !empty( $site_url ) ){ global $zbs; zeroBSCRM_sendJSONSuccess( array( 'target_url' => $zbs->modules->woosync->get_external_woo_url_for_oauth( $site_url ) )); } } zeroBSCRM_sendJSONError(array()); }
projects/plugins/crm/modules/woo-sync/admin/settings/router.page.php
<?php /** * Jetpack CRM * https://jetpackcrm.com * * WooSync: Admin: Settings page */ namespace Automattic\JetpackCRM; // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; /** * Page: WooSync Settings */ function jpcrm_settings_page_html_woosync() { global $zbs; $page = $_GET['tab']; $current_tab = 'main'; if ( isset( $_GET['subtab'] ) ) { $current_tab = sanitize_text_field ( $_GET['subtab'] ); } $zbs->modules->woosync->load_admin_page("settings/{$current_tab}"); call_user_func( "Automattic\JetpackCRM\jpcrm_settings_page_html_{$page}_{$current_tab}"); // enqueue settings styles if ( function_exists( 'Automattic\JetpackCRM\jpcrm_woosync_connections_styles_scripts' ) ){ jpcrm_woosync_connections_styles_scripts(); } }
projects/plugins/crm/modules/woo-sync/admin/settings/main.page.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * WooSync: Admin: Settings page * */ namespace Automattic\JetpackCRM; // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; /** * Page: WooSync Settings */ function jpcrm_settings_page_html_woosync_main() { global $zbs; $settings = $zbs->modules->woosync->get_settings(); $woo_order_statuses = $zbs->modules->woosync->get_woo_order_statuses(); $woo_order_mapping_types = $zbs->modules->woosync->get_woo_order_mapping_types(); $auto_deletion_options = array( 'do_nothing' => __( 'Do nothing', 'zero-bs-crm' ), 'change_status' => sprintf( __( 'Change transaction/invoice status to `%s`', 'zero-bs-crm' ), __( 'Deleted', 'zero-bs-crm' ) ), 'hard_delete_and_log' => __( 'Delete transaction/invoice, and add log to contact', 'zero-bs-crm' ), ); // Act on any edits! if ( isset( $_POST['editwplf'] ) ) { // Retrieve $updatedSettings = array(); // enable order mapping $updatedSettings['enable_woo_status_mapping'] = empty( $_POST['jpcrm_enable_woo_status_mapping'] ) ? 0 : 1; foreach ( $woo_order_mapping_types as $map_type_value ) { foreach ( $woo_order_statuses as $woo_order_status => $woo_order_status_value ) { $mapping_key = $map_type_value['prefix'] . 'wc' . str_replace( '-', '', $woo_order_status ); $updatedSettings[ $mapping_key ] = ! empty( $_POST[ $mapping_key ] ) ? sanitize_text_field( $_POST[ $mapping_key ] ) : ''; } } //copy shipping address into second address $updatedSettings['wccopyship'] = ! empty( $_POST['wpzbscrm_wccopyship'] ); // tag objects with item name|coupon $updatedSettings['wctagcust'] = ! empty( $_POST['wpzbscrm_wctagcust'] ); $updatedSettings['wctagtransaction'] = ! empty( $_POST['wpzbscrm_wctagtransaction'] ); $updatedSettings['wctaginvoice'] = ! empty( $_POST['wpzbscrm_wctaginvoice'] ); $updatedSettings['wctagcoupon'] = ! empty( $_POST['wpzbscrm_wctagcoupon'] ); $updatedSettings['wctagcouponprefix'] = ! empty( $_POST['wctagcouponprefix'] ) ? zeroBSCRM_textProcess( $_POST['wctagcouponprefix'] ) : ''; $updatedSettings['wctagproductprefix'] = ! empty( $_POST['wctagproductprefix'] ) ? zeroBSCRM_textProcess( $_POST['wctagproductprefix'] ) : ''; // switches $updatedSettings['wcinv'] = ! empty( $_POST['wpzbscrm_wcinv'] ); $updatedSettings['wcprod'] = ! empty( $_POST['wpzbscrm_wcprod'] ); $updatedSettings['wcport'] = ! empty( $_POST['wpzbscrm_wcport'] ) ? preg_replace( '/\s*,\s*/', ',', sanitize_text_field( $_POST['wpzbscrm_wcport'] ) ) : ''; $updatedSettings['wcacc'] = ! empty( $_POST['wpzbscrm_wcacc'] ); // trash/delete action $updatedSettings['auto_trash'] = 'change_status'; if ( isset( $_POST['jpcrm_woosync_auto_trash'] ) && in_array( $_POST['jpcrm_woosync_auto_trash'], array_keys( $auto_deletion_options ), true ) ) { $updatedSettings['auto_trash'] = sanitize_text_field( $_POST['jpcrm_woosync_auto_trash'] ); } $updatedSettings['auto_delete'] = 'change_status'; if ( isset( $_POST['jpcrm_woosync_auto_delete'] ) && in_array( $_POST['jpcrm_woosync_auto_delete'], array_keys( $auto_deletion_options ), true ) ) { $updatedSettings['auto_delete'] = sanitize_text_field( $_POST['jpcrm_woosync_auto_delete'] ); } #} Brutal update foreach ( $updatedSettings as $k => $v ) { $zbs->modules->woosync->settings->update( $k, $v ); } // $msg out! $sbupdated = true; // Reload $settings = $zbs->modules->woosync->get_settings(); } // Show Title jpcrm_render_setting_title( 'WooSync Settings', '' ); ?> <p style="padding-top: 18px; text-align:center;margin:1em"> <?php echo sprintf( '<a href="%s&tab=%s&subtab=%s" class="ui button green"><i class="plug icon"></i> %s</a>', jpcrm_esc_link( $zbs->slugs['settings'] ), esc_attr( $zbs->modules->woosync->slugs['settings'] ), esc_attr( $zbs->modules->woosync->slugs['settings_connections'] ), esc_html__( 'Manage WooSync Connections', 'zero-bs-crm' ) ) . sprintf( '<a href="%s" class="ui basic positive button" style="margin-top:1em"><i class="shopping cart icon"></i> %s</a>', jpcrm_esc_link( $zbs->slugs['woosync'] ), esc_html__( 'WooSync Hub', 'zero-bs-crm' ) ); ?> </p> <p id="sbDesc"><?php esc_html_e( 'Here you can configure the global settings for WooSync.', 'zero-bs-crm' ); ?></p> <?php if ( ! empty( $sbupdated ) ) { echo '<div class="ui message success">' . esc_html__( 'Settings Updated', 'zero-bs-crm' ) . '</div>'; } ?> <div id="sbA"> <form method="post"> <input type="hidden" name="editwplf" id="editwplf" value="1" /> <table class="table table-bordered table-striped wtab"> <thead> <tr> <th colspan="2" class="wmid"><?php esc_html_e( 'WooSync Settings', 'zero-bs-crm' ); ?>:</th> </tr> </thead> <tbody> <tr> <td class="wfieldname"> <label for="wpzbscrm_wccopyship"><?php esc_html_e( 'Add Shipping Address', 'zero-bs-crm' ); ?>:</label><br /> <?php esc_html_e( 'Tick to store shipping address as contacts second address', 'zero-bs-crm' ); ?> </td> <td style="width:540px"> <input type="checkbox" class="winput form-control" name="wpzbscrm_wccopyship" id="wpzbscrm_wccopyship" value="1"<?php echo ( ! empty( $settings['wccopyship'] ) ? ' checked="checked"' : '' ); ?> /> </td> </tr> <tr> <td class="wfieldname"> <label for="wpzbscrm_wctagcust"><?php esc_html_e( 'Tag Contact', 'zero-bs-crm' ); ?>:</label><br /> <?php esc_html_e( 'Tick to tag your contact with their item name', 'zero-bs-crm' ); ?> </td> <td style="width:540px"> <input type="checkbox" class="winput form-control" name="wpzbscrm_wctagcust" id="wpzbscrm_wctagcust" value="1"<?php echo ( ! empty( $settings['wctagcust'] ) ? ' checked="checked"' : '' ); ?> /> </td> </tr> <tr> <td class="wfieldname"> <label for="wpzbscrm_wctagtransaction"><?php esc_html_e( 'Tag Transaction', 'zero-bs-crm' ); ?>:</label><br /> <?php esc_html_e( 'Tick to tag your transaction with the item name', 'zero-bs-crm' ); ?> </td> <td style="width:540px"> <input type="checkbox" class="winput form-control" name="wpzbscrm_wctagtransaction" id="wpzbscrm_wctagtransaction" value="1"<?php echo ( ! empty( $settings['wctagtransaction'] ) ? ' checked="checked"' : '' ); ?> /> </td> </tr> <tr> <td class="wfieldname"> <label for="wpzbscrm_wctaginvoice"><?php esc_html_e( 'Tag Invoice', 'zero-bs-crm' ); ?>:</label><br /> <?php esc_html_e( 'Tick to tag your invoice with the item name', 'zero-bs-crm' ); ?> </td> <td style="width:540px"> <input type="checkbox" class="winput form-control" name="wpzbscrm_wctaginvoice" id="wpzbscrm_wctaginvoice" value="1"<?php echo ( ! empty( $settings['wctaginvoice'] ) ? ' checked="checked"' : '' ); ?> /> </td> </tr> <tr> <td class="wfieldname"> <label for="jpcrm_woosync_auto_trash"><?php esc_html_e( 'Order Trash action', 'zero-bs-crm' ); ?>:</label><br /> <?php esc_html_e( 'Choose what should happen when an order is trashed in WooCommerce', 'zero-bs-crm' ); ?> </td> <td style="width:540px"> <select id="jpcrm_woosync_auto_trash" name="jpcrm_woosync_auto_trash" class="winput form-control"> <?php $current_auto_trash_setting = ! empty( $settings['auto_trash'] ) ? $settings['auto_trash'] : 'change_status'; foreach ( $auto_deletion_options as $option_key => $option_label ) { ?> <option value="<?php echo esc_attr( $option_key ); ?>"<?php echo ( $option_key === $current_auto_trash_setting ? ' selected="selected"' : '' ); ?>> <?php echo esc_html( $option_label ); ?> </option> <?php } ?> </select> </td> </tr> <tr> <td class="wfieldname"> <label for="jpcrm_woosync_auto_delete"><?php esc_html_e( 'Order Delete action', 'zero-bs-crm' ); ?>:</label><br /> <?php esc_html_e( 'Choose what should happen when an order is deleted in WooCommerce', 'zero-bs-crm' ); ?> </td> <td style="width:540px"> <select id="jpcrm_woosync_auto_delete" name="jpcrm_woosync_auto_delete" class="winput form-control"> <?php $current_auto_delete_setting = ! empty( $settings['auto_delete'] ) ? $settings['auto_delete'] : 'change_status'; foreach ( $auto_deletion_options as $option_key => $option_label ) { ?> <option value="<?php echo esc_attr( $option_key ); ?>"<?php echo ( $option_key === $current_auto_delete_setting ? ' selected="selected"' : '' ); ?>> <?php echo esc_html( $option_label ); ?> </option> <?php } ?> </select> </td> </tr> <tr> <td class="wfieldname"> <label for="wpzbscrm_wctagcoupon"><?php esc_html_e( 'Include Coupon as tag', 'zero-bs-crm' ); ?>:</label><br /> <?php esc_html_e( 'Tick to include any used WooCommerce coupon codes as tags (depends on above settings)', 'zero-bs-crm' ); ?> </td> <td style="width:540px"> <input type="checkbox" class="winput form-control" name="wpzbscrm_wctagcoupon" id="wpzbscrm_wctagcoupon" value="1"<?php echo ( ! empty( $settings['wctagcoupon'] ) ? ' checked="checked"' : '' ); ?> /> </td> </tr> <tr> <td class="wfieldname"> <label for="wpzbscrm_wcinv"><?php esc_html_e( 'Create Invoices from WooCommerce Orders', 'zero-bs-crm' ); ?>:</label><br /> <?php esc_html_e( 'Tick to create invoices from your WooCommerce orders', 'zero-bs-crm' ); ?> </td> <td style="width:540px"> <input type="checkbox" class="winput form-control" name="wpzbscrm_wcinv" id="wpzbscrm_wcinv" value="1"<?php echo ( ! empty( $settings['wcinv'] ) ? ' checked="checked"' : '' ); ?> /> </td> </tr> <tr> <td class="wfieldname"> <label for="wpzbscrm_wcacc"><?php esc_html_e( 'Show Invoices on My Account', 'zero-bs-crm' ); ?>:</label><br /> <?php esc_html_e( 'Tick to show a Jetpack CRM Invoices menu item under WooCommerce My Account', 'zero-bs-crm' ); ?> </td> <td style="width:540px"> <input type="checkbox" class="winput form-control" name="wpzbscrm_wcacc" id="wpzbscrm_wcacc" value="1"<?php echo ( ! empty( $settings['wcacc'] ) ? ' checked="checked"' : '' ); ?> /> <?php $invoices_enabled = zeroBSCRM_getSetting( 'feat_invs' ) > 0; if ( !$invoices_enabled ) { ?> <br /> <small><?php esc_html_e( 'Warning: Invoicing module is currently disabled.', 'zero-bs-crm' ); ?></small> <?php } ?> </td> </tr> <tr> <td class="wfieldname"> <label for="wctagproductprefix"><?php esc_html_e( 'Product tag prefix', 'zero-bs-crm' ); ?>:</label><br /> <?php esc_html_e( 'Enter a tag prefix for product tags (e.g. Product: )', 'zero-bs-crm' ); ?> </td> <td style='width:540px'> <input type="text" class="winput form-control" name="wctagproductprefix" id="wctagproductprefix" value="<?php echo ( ! empty( $settings['wctagproductprefix'] ) ? esc_attr( $settings['wctagproductprefix'] ) : '' ); ?>" placeholder="<?php esc_attr_e( "e.g. 'Product: '", 'zero-bs-crm' ); ?>" /> </td> </tr> <tr> <td class="wfieldname"> <label for="wctagcouponprefix"><?php esc_html_e( 'Coupon tag prefix', 'zero-bs-crm' ); ?>:</label><br /> <?php esc_html_e( 'Enter a tag prefix for coupon tags (e.g. Coupon: )', 'zero-bs-crm' ); ?> </td> <td style='width:540px'> <input type="text" class="winput form-control" name="wctagcouponprefix" id="wctagcouponprefix" value="<?php echo ( ! empty( $settings['wctagcouponprefix'] ) ? esc_attr( $settings['wctagcouponprefix'] ) : '' ); ?>" placeholder="<?php esc_attr_e( "e.g. 'Coupon: '", 'zero-bs-crm' ); ?>" /> </td> </tr> <!-- #follow-on-refinements commented out for now as we need to review how product index works now we have accessible line items in v3.0 <tr> <td class="wfieldname"> <label for="wpzbscrm_wcprod"><?php // _e( 'Use Product Index', 'zero-bs-crm' ); ?>:</label><br /> <?php // _e( 'Tick to allow Product Index on Invoices. Makes creating invoices easier', 'zero-bs-crm' ); ?></td> <td style="width:540px"> <input type="checkbox" class="winput form-control" name="wpzbscrm_wcprod" id="wpzbscrm_wcprod" value="1"<?php // echo ( ! empty( $settings['wcprod'] ) ? ' checked="checked"' : '' ); ?> /> </td> </tr> --> <tr> <td class="wfieldname"> <?php ##WLREMOVE ?> <div class="ui teal label right floated"><i class="circle info icon link"></i> <a href="<?php echo esc_url( $zbs->urls['kb-contact-fields'] ); ?>" target="_blank"><?php esc_html_e( 'Read more', 'zero-bs-crm' ); ?></a></div> <?php ##/WLREMOVE ?> <label for="wpzbscrm_port"><?php esc_html_e( 'WooCommerce My Account', 'zero-bs-crm' ); ?>:</label><br /> <?php esc_html_e( 'Enter a comma-separated list of Jetpack CRM contact fields to let customers edit these via WooCommerce My Account.', 'zero-bs-crm' ); ?> </td> <td style="width:540px"> <input type="text" class="winput form-control" name="wpzbscrm_wcport" id="wpzbscrm_port" value="<?php echo ( ! empty( $settings['wcport'] ) ? esc_attr( $settings['wcport'] ) : '' ); ?>" placeholder="e.g. addr1,custom-field-1" /> </td> </tr> <tr> <td class="wfieldname"> <label for="jpcrm_enable_woo_status_mapping"><?php esc_html_e( 'Enable order status mapping', 'zero-bs-crm' ); ?>:</label><br /> <?php esc_html_e( 'Tick here if you want WooCommerce order status changes to automatically change contact statuses', 'zero-bs-crm' ); ?> </td> <td style="width:540px"><input type="checkbox" class="winput form-control" name="jpcrm_enable_woo_status_mapping" id="jpcrm_enable_woo_status_mapping" value="1"<?php echo isset( $settings['enable_woo_status_mapping'] ) && (int)$settings['enable_woo_status_mapping'] === 0 ? '' : ' checked="checked"'; ?> /> </td> </tr> <tr> <td class="wfieldname" colspan="2"> <label><?php esc_html_e( 'Order status map', 'zero-bs-crm' ); ?>:</label><br /> <?php esc_html_e( 'Here you can choose how you want to map WooCommerce order statuses to CRM statuses (if the above setting is enabled)', 'zero-bs-crm' ); ?> <div style="margin-top:10px;"> <a style="margin-top:10px;" href="<?php echo esc_url( $zbs->urls['woomanagingorders'] ); ?>" target="_blank"><?php esc_html_e( 'Learn more about the WooCommerce order statuses', 'zero-bs-crm' ); ?><img class="jpcrm-external-link-icon" style="margin-bottom:2px" src="<?php echo esc_url( ZEROBSCRM_URL ); ?>i/external-link.svg" /></a> </div> <br/> <table style="width:100%;border-spacing: 0 15px;border-collapse: separate;table-layout: fixed;"> <tr> <th><?php esc_html_e( 'Order status', 'zero-bs-crm' ); ?></th> <?php foreach ( $woo_order_mapping_types as $map_type_value ) : ?> <th><?php echo esc_html( $map_type_value['label'] ); ?></th> <?php endforeach; ?> </tr> <?php foreach ( $woo_order_statuses as $woo_order_status => $woo_order_value ) { ?> <tr class="jpcrm_woosync_order_status_map"> <td><?php echo esc_html( $woo_order_value ); ?></td> <?php foreach ( $woo_order_mapping_types as $obj_type => $map_type_value ) : $selected = ''; $mapping_key = $map_type_value['prefix'] . 'wc' . str_replace( '-', '', $woo_order_status ); $obj_type_id = $zbs->DAL->objTypeID( $obj_type ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase if ( ! isset( $settings[ $mapping_key ] ) || $settings[ $mapping_key ] === '-1' ) { // use default mapping as fallback $selected = $zbs->modules->woosync->get_default_status_for_order_obj( $obj_type_id, $woo_order_status ); } else { // select mapping from settings $selected = $settings[ $mapping_key ]; } if ( ! $zbs->DAL->is_valid_obj_status( $obj_type_id, $selected ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase $selected = false; } ?> <td> <select class="winput" style="width: 90%;" name="<?php echo esc_attr( $mapping_key ); ?>" id="<?php echo esc_attr( $mapping_key ); ?>"> <?php // if there's no default match, make user select one if ( ! $selected ) { ?> <option value="-1" selected disabled>-- <?php esc_html_e( 'Select mapped status', 'zero-bs-crm' ); ?> --</option> <?php } ?> <?php foreach ( $map_type_value['statuses'] as $status ) { printf( '<option value="%s" %s>%s</option>', esc_attr( $status ), ( $selected === $status ? 'selected' : '' ), esc_html( $obj_type_id === ZBS_TYPE_INVOICE ? __( $status, 'zero-bs-crm' ) : $status ) ); // phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText } ?> </select> </td> <?php endforeach; ?> </tr> <?php } ?> </table> </td> </tr> </tbody> </table> <table class="table table-bordered table-striped wtab"> <tbody> <tr> <td class="wmid"><button type="submit" class="button button-primary button-large"><?php esc_html_e( 'Save Settings', 'zero-bs-crm' ); ?></button></td> </tr> </tbody> </table> </form> </div> <?php wp_enqueue_style( 'jpcrm-woo-sync-settings-main', plugins_url( '/css/jpcrm-woo-sync-settings-main' . wp_scripts_get_suffix() . '.css', JPCRM_WOO_SYNC_ROOT_FILE ) ); }
projects/plugins/crm/modules/woo-sync/admin/settings/connection_edit.page.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * WooSync: Admin: Connection edit page * */ namespace Automattic\JetpackCRM; // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; /** * Page: Connection edit page */ function jpcrm_settings_page_html_woosync_connection_edit() { global $zbs; $settings = $zbs->modules->woosync->settings->getAll(); if ( isset( $_GET['site_key'] ) ){ $site_key = sanitize_text_field( $_GET['site_key'] ); // retrieve connected store $sync_site = $zbs->modules->woosync->get_active_sync_site( $site_key ); } if ( !isset( $sync_site ) || !is_array( $sync_site ) ){ // fail echo zeroBSCRM_UI2_messageHTML( 'warning', '', __( 'No such connection exists.', 'zero-bs-crm' ), 'info' ); } else { // process any updates if ( isset( $_POST['edit_connection'] ) ){ // check nonce check_admin_referer( 'woosync-connection-edit' ); // process data $sync_site['key'] = ( isset( $_POST['woosync_key'] ) ? sanitize_text_field( $_POST['woosync_key'] ) : '' ); $sync_site['secret'] = ( isset( $_POST['woosync_secret'] ) ? sanitize_text_field( $_POST['woosync_secret'] ) : '' ); $sync_site['prefix'] = ( isset( $_POST['woosync_prefix'] ) ? sanitize_text_field( $_POST['woosync_prefix'] ) : '' ); // verify (ideally we'd say 'these connection settings don't work, are you sure', but for now let's keep it simple) $verified_change = $zbs->modules->woosync->verify_api_connection( '', $sync_site['domain'],$sync_site['key'], $sync_site['secret'] ); // update $sync_site['site_key'] = $site_key; $zbs->modules->woosync->update_sync_site( $sync_site ); $connection_updated = true; // reload connected store $sync_site = $zbs->modules->woosync->get_active_sync_site( $site_key ); } // normal page switch ( $sync_site['mode'] ){ case JPCRM_WOO_SYNC_MODE_LOCAL: $site_title = __( 'Local', 'zero-bs-crm' ); break; case JPCRM_WOO_SYNC_MODE_API: $site_title = __( 'External', 'zero-bs-crm' ); break; } ?> <p><?php echo wp_kses( sprintf( __( 'From this page you can edit connection details for a connection between Jetpack CRM and one or more WooCommerce stores. <a href="%s" target="_blank">Read more about connecting Jetpack CRM to WooCommerce</a>.', 'zero-bs-crm' ), esc_url( $zbs->urls['connect-multi-woo'] ) ), $zbs->acceptable_restricted_html ); ?></p> <h3 style="text-align: center;" class="ui blue header"><?php echo sprintf( esc_html__( 'Edit %s WooCommerce Connection', 'zero-bs-crm' ), esc_html( $site_title ) ); ?></h3> <?php if ( isset( $connection_updated ) ){ $connection_message = __( 'Your connection settings have been updated. Your new connection settings have been verified.', 'zero-bs-crm' ); if ( !$verified_change ){ $connection_message = __( 'Your connection settings have been updated with one Warning: Your new connection settings could not be verified.', 'zero-bs-crm' ); } echo zeroBSCRM_UI2_messageHTML( 'info', __( 'Connection Updated', 'zero-bs-crm' ), $connection_message ); } ?> <form method="post"> <input type="hidden" name="edit_connection" id="edit_connection" value="1" /> <?php // add nonce wp_nonce_field( 'woosync-connection-edit'); ?> <table class="table table-striped wtab"> <tbody> <tr> <td class="wfieldname"><label for="woosync_mode"><?php esc_html_e( 'Mode','zero-bs-crm' ); ?>:</label></td> <td style="width:540px"><?php switch ( $sync_site['mode'] ){ case JPCRM_WOO_SYNC_MODE_LOCAL: echo '<span class="ui label teal"><i class="home icon"></i> ' . esc_html__( 'Local', 'zero-bs-crm' ) . '</span>'; break; case JPCRM_WOO_SYNC_MODE_API: echo '<span class="ui label blue"><i class="plug icon"></i> ' . esc_html__( 'External', 'zero-bs-crm' ) . '</span>'; break; } ?></td> </tr> <tr> <td class="wfieldname"><label for="woosync_domain"><?php esc_html_e( 'Store domain', 'zero-bs-crm' ); ?>:</label></td> <td style="width:540px"><?php echo esc_html( $sync_site['domain'] ); ?></td> </tr><?php switch ( $sync_site['mode'] ){ case JPCRM_WOO_SYNC_MODE_LOCAL: // Local sites, no editing of the key/secret ?> <tr style="display:none"> <td colspan="2"> <input type="hidden" name="woosync_key" id="woosync_key" value="<?php if (isset($sync_site['key']) && !empty($sync_site['key'])) echo esc_attr( $sync_site['key'] ); ?>" /> <input type="hidden" name="woosync_secret" id="woosync_secret" value="<?php if (isset($sync_site['secret']) && !empty($sync_site['secret'])) echo esc_attr( $sync_site['secret'] ); ?>" /> </td> </tr> <?php break; case JPCRM_WOO_SYNC_MODE_API: // External sites can edit the key and secret ?> <tr> <td class="wfieldname"><label for="woosync_key"><?php esc_html_e( 'API Key', 'zero-bs-crm' ); ?>:</label></td> <td style="width:540px"><input type="text" class="winput form-control" name="woosync_key" id="woosync_key" value="<?php if (isset($sync_site['key']) && !empty($sync_site['key'])) echo esc_attr( $sync_site['key'] ); ?>" placeholder="e.g. ck_99966f77a8e9ace9efb689a6fa7f5334ac9ea645" /></td> </tr> <tr> <td class="wfieldname"><label for="woosync_secret"><?php esc_html_e( 'API Secret', 'zero-bs-crm' ); ?>:</label></td> <td style="width:540px"><input type="text" class="winput form-control" name="woosync_secret" id="woosync_secret" value="<?php if (isset($sync_site['secret']) && !empty($sync_site['secret'])) echo esc_attr( $sync_site['secret'] ); ?>" placeholder="e.g. cs_9994bcfb20e188073b609650487736196d841015" /></td> </tr> <?php break; } ?> <tr> <td class="wfieldname"><label for="woosync_prefix"><?php esc_html_e('Order Prefix','zero-bs-crm'); ?>:</label></td> <td style="width:540px"><input type="text" class="winput form-control" name="woosync_prefix" id="woosync_prefix" value="<?php if (isset($sync_site['prefix']) && !empty($sync_site['prefix'])) echo esc_attr( $sync_site['prefix'] ); ?>" placeholder="e.g. example_" /></td> </tr> </tbody> <tfoot> <tr> <td colspan="2" class="wmid" style="padding-top:1.5em"> <button class="ui blue button" id="jpcrm-woosync-save-connection-details" type="submit"><?php esc_html_e( 'Update Connection', 'zero-bs-crm' ); ?></button> <?php echo sprintf( '<a href="%s&tab=%s&subtab=%s" class="ui basic button" style="margin-top:1em">%s</a>', jpcrm_esc_link( $zbs->slugs['settings'] ), esc_attr( $zbs->modules->woosync->slugs['settings'] ), esc_attr( $zbs->modules->woosync->slugs['settings_connections'] ), esc_html__( 'Back to Store Connections', 'zero-bs-crm' ) ); ?> </td> </tr> </tfoot> </table> </form> <script type="text/javascript"> jQuery(document).ready(function(){ }); </script> <?php } // / normal page load }
projects/plugins/crm/modules/woo-sync/admin/settings/connections.page.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * WooSync: Admin: Connections page * */ namespace Automattic\JetpackCRM; // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; /** * Page: WooSync Connections */ function jpcrm_settings_page_html_woosync_connections() { global $zbs; $show_disconnect_prompt = false; $settings = $zbs->modules->woosync->settings->getAll(); // retrieve connected store(s) $sync_sites = $zbs->modules->woosync->get_active_sync_sites( 'default', true ); // did we just authenticate? if ( isset( $_GET['success'] ) ){ $success_value = (int)sanitize_text_field( $_GET['success'] ); if ( $success_value == 1 ){ echo zeroBSCRM_UI2_messageHTML( 'success', '', __( 'Successfully authenticated remote store.', 'zero-bs-crm' ), 'info' ); } else { echo zeroBSCRM_UI2_messageHTML( 'warning', '', __( 'Attempt to authenticate remote store failed.', 'zero-bs-crm' ), 'info' ); } } $nonce_str = ( isset( $_GET['_wpnonce'] ) ? $_GET['_wpnonce'] : '' ); // catch disconnect requests if ( isset( $_GET['disconnect'] ) && zeroBSCRM_isZBSAdminOrAdmin() ) { $site_key_to_disconnect = sanitize_text_field( $_GET['disconnect'] ); if ( !empty( $site_key_to_disconnect ) && isset( $sync_sites[ $site_key_to_disconnect ] ) ) { // show warning or act if ( !isset( $_GET['definitely_disconnect'] ) ){ // warning prompt $show_disconnect_prompt = true; } else { // act $nonceVerified = wp_verify_nonce( $nonce_str, 'disconnect_woosync_site_connection_' . $site_key_to_disconnect ); if ( $nonceVerified ){ // disconnect/delete site if ( $zbs->modules->woosync->remove_sync_site( $site_key_to_disconnect ) ) { // success message zeroBSCRM_html_msg( 0, __( 'Successfully disconnected connection:', 'zero-bs-crm' ) . ' ' . $sync_sites[ $site_key_to_disconnect ]['domain'] ); // re-retrieve connected store(s) $sync_sites = $zbs->modules->woosync->get_active_sync_sites( 'default', true ); } } else { zeroBSCRM_html_msg( 1, __( 'Unable to disconnect connection:', 'zero-bs-crm' ) . ' ' . $sync_sites[ $site_key_to_disconnect ]['domain'] ); } } } } // catch pause request else if ( isset( $_GET['pause'] ) && zeroBSCRM_isZBSAdminOrAdmin() ) { $did_resume = false; $site_key_to_pause = sanitize_text_field( $_GET['pause'] ); $nonceVerified = wp_verify_nonce( $nonce_str, 'pause_woosync_site_connection_' . $site_key_to_pause ); if ( $nonceVerified ) { $site_info = $zbs->modules->woosync->pause_sync_site( $site_key_to_pause ); if ( !empty( $site_info['paused'] ) ) { $did_resume = true; // re-retrieve connected store(s) $sync_sites = $zbs->modules->woosync->get_active_sync_sites( 'default', true ); } } // output message if ( $did_resume ) { zeroBSCRM_html_msg( 0, __( 'Successfully paused sync for connection:', 'zero-bs-crm' ) . ' ' . $sync_sites[ $site_key_to_pause ]['domain'] ); } else { zeroBSCRM_html_msg( 1, __( 'Unable to pause sync for connection:', 'zero-bs-crm' ) . ' ' . $sync_sites[ $site_key_to_pause ]['domain'] ); } } // catch resume request else if ( isset( $_GET['resume'] ) && zeroBSCRM_isZBSAdminOrAdmin() ) { $did_pause = false; $site_key_to_resume = sanitize_text_field( $_GET['resume'] ); $nonceVerified = wp_verify_nonce( $nonce_str, 'resume_woosync_site_connection_' . $site_key_to_resume ); if ( $nonceVerified ) { $site_info = $zbs->modules->woosync->resume_sync_site( $site_key_to_resume ); if ( empty( $site_info['paused'] ) ) { $did_pause = true; // re-retrieve connected store(s) $sync_sites = $zbs->modules->woosync->get_active_sync_sites( 'default', true ); } } // output message if ( $did_pause ) { zeroBSCRM_html_msg( 0, __( 'Successfully resumed sync for connection:', 'zero-bs-crm' ) . ' ' . $sync_sites[ $site_key_to_resume ]['domain'] ); } else { zeroBSCRM_html_msg( 1, __( 'Unable to resume sync for connection:', 'zero-bs-crm' ) . ' ' . $sync_sites[ $site_key_to_resume ]['domain'] ); } } if ( $show_disconnect_prompt ) { ?> <div class="ui icon big warning message"> <i class="times circle outline icon"></i> <div class="content"> <div class="header"> <?php _e('Are you sure?',"zero-bs-crm"); ?> </div> <p><?php echo sprintf( __( 'Are you sure you want to disconnect the connection to the store at <br><code>%s</code>?', 'zero-bs-crm' ), $sync_sites[ $site_key_to_disconnect ]['domain'] ); ?></p> <p><?php esc_html_e( 'This will permanently remove this connection. No new data will be synchronised from this external store unless you add a new connection to it at a later date. This will not remove any existing data.', 'zero-bs-crm' ); ?></p> <p><?php // actions echo '<a href="' . esc_url( wp_nonce_url( '?page=' . $zbs->slugs['settings'] . '&tab=' . $zbs->modules->woosync->slugs['settings'] . '&subtab=' . $zbs->modules->woosync->slugs['settings_connections'] . '&disconnect=' . $site_key_to_disconnect . '&definitely_disconnect=1', 'disconnect_woosync_site_connection_' . $site_key_to_disconnect ) ) . '" class="ui orange button right floated"><i class="trash alternate icon"></i> ' . esc_html__( 'Disconnect Store Connection', 'zero-bs-crm' ) . '</a>'; echo '<a href="' . jpcrm_esc_link( $zbs->slugs['settings'] . '&tab=' . $zbs->modules->woosync->slugs['settings'] . '&subtab=' . $zbs->modules->woosync->slugs['settings_connections'] ) . '" class="ui green button right floated"><i class="angle double left icon"></i> ' . esc_html__('Back to Connections', 'zero-bs-crm' ) . '</a>'; ?></p> </div> </div> <?php } else { // normal page load ?> <p><?php echo wp_kses( sprintf( __( 'From this page you can manage connections between Jetpack CRM and one or more WooCommerce stores. <a href="%s" target="_blank">Read more about connecting Jetpack CRM to WooCommerce</a>.', 'zero-bs-crm' ), esc_url( $zbs->urls['connect-multi-woo'] ) ), $zbs->acceptable_restricted_html ); ?></p> <h3 style="text-align: center;" class="ui blue header"><?php esc_html_e( 'WooCommerce Connections', 'zero-bs-crm'); ?></h3> <table class="table table-striped wtab"> <tbody> <td> <?php // first up we want to pick any local connections out of the stack if ( isset( $sync_sites['local'] ) ) { // draw it jpcrm_woosync_connections_page_single_connection( 'local', $sync_sites['local'] ); } foreach ( $sync_sites as $site_key => $site_info ) { // skip local as dealt with above if ( $site_key === 'local' ) { continue; } // draw it jpcrm_woosync_connections_page_single_connection( $site_key, $site_info ); } // if no connections show message: if ( count( $sync_sites ) === 0 ) { echo zeroBSCRM_UI2_messageHTML( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped 'info', __( 'No WooCommerce connections', 'zero-bs-crm' ), __( 'Connect to an external WooCommerce store or install WooCommerce to get started.', 'zero-bs-crm' ), '', 'jpcrm-no-woo-connections-notice' ); } ?> </td> </tbody> <tfoot> <tr> <td colspan="2" class="wmid" style="padding-top:1.5em"> <button class="ui blue button" id="jpcrm-woosync-connect-to-store"><i class="plug icon"></i> <?php if ( count( $sync_sites ) == 0 ){ esc_html_e( 'Connect a Store', 'zero-bs-crm' ); } else { esc_html_e( 'Connect another Store', 'zero-bs-crm' ); } ?></button> <?php echo sprintf( '<a href="%s" class="ui basic positive button" style="margin-top:1em"><i class="shopping cart icon"></i> %s</a>', jpcrm_esc_link( $zbs->slugs['woosync'] ), esc_html__( 'WooSync Hub', 'zero-bs-crm' ) ); ?> </td> </tr> </tfoot> </table> <script type="text/javascript"> jQuery(document).ready(function(){ }); </script> <?php } // / normal page load } /* * Draws html for a WooCommerce connection */ function jpcrm_woosync_connections_page_single_connection( $site_key, $site_info ){ global $zbs; if ( !is_array( $site_info ) ){ return ''; } // connected? switch ( $site_info['mode'] ){ case JPCRM_WOO_SYNC_MODE_LOCAL: // always connected, as long as Woo is here if ( $zbs->woocommerce_is_active() ){ $connection_status = true; $connection_explainer_str = ''; } else { $connection_status = false; $connection_explainer_str = __( 'Cannot find WooCommerce', 'zero-bs-crm' ); } break; case JPCRM_WOO_SYNC_MODE_API: // verify creds: if ( $zbs->modules->woosync->verify_api_connection( $site_key ) ){ $connection_status = true; $connection_explainer_str = ''; // clear connection error count $zbs->modules->woosync->set_sync_site_attribute( $site_key, 'site_connection_errors', 0 ); } else { $connection_status = false; $connection_explainer_str = __( 'Could not connect to WooCommerce', 'zero-bs-crm' ); // increment connection error count $zbs->modules->woosync->increment_sync_site_count( $site_key, 'site_connection_errors' ); } break; } ?><div class="jpcrm-woocommerce-connection ui segment" id="jpcrm-woocommerce-connection-<?php echo esc_attr( $site_key ); ?>"> <div class="ui grid"> <div class="twelve wide column"> <div class="jpcrm-woocommerce-site"> <?php $additional_button_html = ''; if ( $connection_status ) { $label_color = 'green'; $label_str = __( 'Connected', 'zero-bs-crm' ); // pause/resume if ( !isset( $site_info['paused'] ) || !$site_info['paused'] ){ // pause $additional_button_html = sprintf( '<a href="%s&tab=%s&subtab=%s&pause=%s&_wpnonce=%s" class="ui small basic fluid button" style="margin-top:1em"><i class="pause icon"></i> %s</a>', jpcrm_esc_link($zbs->slugs['settings']), $zbs->modules->woosync->slugs['settings'], $zbs->modules->woosync->slugs['settings_connections'], $site_key, wp_create_nonce( 'pause_woosync_site_connection_' . $site_key ), __( 'Pause Sync', 'zero-bs-crm' ) ); } else { // resume $additional_button_html = sprintf( '<a href="%s&tab=%s&subtab=%s&resume=%s&_wpnonce=%s" class="ui small basic orange fluid button" style="margin-top:1em"><i class="play icon"></i> %s</a>', jpcrm_esc_link($zbs->slugs['settings']), $zbs->modules->woosync->slugs['settings'], $zbs->modules->woosync->slugs['settings_connections'], $site_key, wp_create_nonce( 'resume_woosync_site_connection_' . $site_key ), __( 'Resume Sync', 'zero-bs-crm' ) ); } } else { $label_color = 'grey'; $label_str = __( 'Not connected', 'zero-bs-crm' ); } echo '<span class="ui right floated large label jpcrm-woocommerce-connection-state ' . esc_attr( $label_color ) . '">' . esc_html( $label_str ) . '</span>'; switch ( $site_info['mode'] ){ case JPCRM_WOO_SYNC_MODE_LOCAL: echo '<span class="ui large label teal"><i class="home icon"></i> ' . esc_html__( 'Local', 'zero-bs-crm' ) . '</span>'; break; case JPCRM_WOO_SYNC_MODE_API: echo '<span class="ui large label blue"><i class="plug icon"></i> ' . esc_html__( 'External', 'zero-bs-crm' ) . '</span>'; break; } echo '<span class="jpcrm-woocommerce-site-url">' . esc_html( $site_info['domain'] ) . '</span>'; ?> </div> <?php // extra detail? if ( $site_info['last_sync_fired'] != -1 || isset( $site_info['total_order_count'] ) ){ ?><div class="jpcrm-woocommerce-connection-details"><?php // last synced if ( $site_info['last_sync_fired'] != -1 ) { echo '<div class="jpcrm-woocommerce-last-synced jpcrm-woocommerce-connection-detail">' . esc_html( sprintf( __( 'Last Synced Data: %s', 'zero-bs-crm' ), zeroBSCRM_locale_utsToDatetime( $site_info['last_sync_fired'] ) ) ) . '</div>'; } if ( isset( $site_info['total_order_count'] ) ){ echo '<div class="jpcrm-woocommerce-total-order-count jpcrm-woocommerce-connection-detail">' . esc_html( sprintf( __( 'Total Orders Imported: %s', 'zero-bs-crm' ), zeroBSCRM_prettifyLongInts( $site_info['total_order_count'] ) ) ) . '</div>'; } ?></div><?php } ?> </div> <div class="four wide column jpcrm-woocommerce-connection-column"> <?php // edit $edit_button = sprintf( '<a href="%s&tab=%s&subtab=%s&site_key=%s" class="ui small basic fluid button" style="margin-top:1em"><i class="pencil alternate icon"></i> %s</a>', jpcrm_esc_link( $zbs->slugs['settings'] ), esc_attr( $zbs->modules->woosync->slugs['settings'] ), esc_attr( $zbs->modules->woosync->slugs['settings_connection_edit'] ), esc_attr( $site_key ), esc_html__( 'Edit', 'zero-bs-crm' ) ); // actions switch ( $site_info['mode'] ){ case JPCRM_WOO_SYNC_MODE_LOCAL: if ( $connection_status ){ // All Okay // visit store echo '<a href="' . esc_url( $zbs->modules->woosync->get_local_woo_admin_url() ) . '" target="_blank" class="ui small blue fluid button"><i class="building alternate icon"></i> ' . esc_html__( 'WooCommerce Admin', 'zero-bs-crm' ) . '</a>'; // edit echo $edit_button; // any extras? (pause) echo $additional_button_html; } else { // Some issue with connection, could be lack of WooCommerce (was active, isn't now) esc_html_e( 'There was an error connecting to your local WooCommerce store. Please make sure WooCommerce is active, after which if this error message persists, please contact support.', 'zero-bs-crm' ); } break; case JPCRM_WOO_SYNC_MODE_API: if ( $connection_status ){ // already connected, nothing to do // visit store echo '<a href="' . esc_url( $zbs->modules->woosync->get_external_woo_admin_url( $site_info['domain'] ) ) . '" target="_blank" class="ui small blue fluid button"><i class="external square alternate icon"></i> ' . esc_html__( 'WooCommerce Admin', 'zero-bs-crm' ) . '</a>'; // edit echo $edit_button; // any extras? (pause) echo $additional_button_html; // delete echo sprintf( '<a href="%s&tab=%s&subtab=%s&disconnect=%s" class="ui small basic negative fluid button" style="margin-top:1em"><i class="times circle outline icon"></i> %s</a>', jpcrm_esc_link( $zbs->slugs['settings'] ), esc_attr( $zbs->modules->woosync->slugs['settings'] ), esc_attr( $zbs->modules->woosync->slugs['settings_connections'] ), esc_attr( $site_key ), esc_html__( 'Delete Connection', 'zero-bs-crm' ) ); } else { // edit echo $edit_button; // delete echo sprintf( '<a href="%s&tab=%s&subtab=%s&disconnect=%s" class="ui small basic negative fluid button" style="margin-top:1em"><i class="times circle outline icon"></i> %s</a>', jpcrm_esc_link( $zbs->slugs['settings'] ), esc_attr( $zbs->modules->woosync->slugs['settings'] ), esc_attr( $zbs->modules->woosync->slugs['settings_connections'] ), esc_attr( $site_key ), esc_html__( 'Delete Connection', 'zero-bs-crm' ) ); } break; } // explainer? if ( !empty( $connection_explainer_str ) ) { echo '<br>' . esc_html( $connection_explainer_str ); } ?></div> </div> </div><?php } /** * Styles and scripts for connections */ function jpcrm_woosync_connections_styles_scripts(){ global $zbs; wp_enqueue_script( 'jpcrm-woo-sync-connections-page', plugins_url( '/js/jpcrm-woo-sync-settings-connections'.wp_scripts_get_suffix().'.js', JPCRM_WOO_SYNC_ROOT_FILE ), array( 'jquery' ), $zbs->modules->woosync->version ); wp_enqueue_style( 'jpcrm-woo-sync-connections-page', plugins_url( '/css/jpcrm-woo-sync-settings-connections'.wp_scripts_get_suffix().'.css', JPCRM_WOO_SYNC_ROOT_FILE ) ); }
projects/plugins/crm/modules/woo-sync/admin/woo-sync-hub/main.page.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * WooSync: Admin: Hub page * */ // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; /** * Page: WooSync Hub */ function jpcrm_woosync_render_hub_page() { global $zbs; // any messages to output $general_notices = array(); $error_notices = array(); // from 5.2 we have multi-site syncing $sync_sites = $zbs->modules->woosync->get_active_sync_sites(); // intercept for attempting restart of initial sync if ( isset( $_GET['restart_sync'] ) ) { // Show message: are you sure? $html = '<p>' . __( 'This will restart syncing your WooCommerce orders from scratch, using your current settings.', 'zero-bs-crm' ) . '</p>'; $html .= '<p>' . __( 'This will not remove any existing orders or data, but it will update objects if they are reimported and have since changed.', 'zero-bs-crm' ) . '</p>'; $html .= '<p><a href="' . jpcrm_esc_link( $zbs->modules->woosync->slugs['hub'] . '&definitely_restart_sync=1' ) . '" class="ui button teal">' . __( 'Yes, do a full resync', 'zero-bs-crm' ) . '</a>&nbsp;&nbsp;<a href="' . jpcrm_esc_link( $zbs->modules->woosync->slugs['hub'] ) . '" class="ui button red">' . __( 'No, cancel and go back to hub', 'zero-bs-crm' ) . '</a></p>'; echo zeroBSCRM_UI2_messageHTML( 'warning', __( 'Want to restart your sync?', 'zero-bs-crm' ), $html, 'info' ); exit(); } // intercept for actual restart of initial sync if ( isset( $_GET['definitely_restart_sync'] ) ) { // restart all! if ( is_array( $sync_sites ) ){ foreach ( $sync_sites as $site_key => $site_info ){ // mark that we've 'not completed first import' $zbs->modules->woosync->set_sync_site_attribute( $site_key, 'first_import_complete', false); $zbs->modules->woosync->set_sync_site_attribute( $site_key, 'resume_from_page', 1); } } // notice $general_notices[] = zeroBSCRM_UI2_messageHTML( 'info', __( 'Sync restarted', 'zero-bs-crm' ), __( 'The WooSync import has been restarted. This will start running in the background from the beginning.', 'zero-bs-crm' ) ); } // intercept for debug, if we have $_GET['debug_sync'], call that if ( isset( $_GET['debug_sync'] ) ){ // render debug mode sync page jpcrm_woosync_render_hub_page_debug_mode(); exit(); } $settings = $zbs->modules->woosync->settings->getAll(); $settings_page_url = jpcrm_esc_link( $zbs->slugs['settings'] . '&tab=' . $zbs->modules->woosync->slugs['settings'] ); $connections_page_url = jpcrm_esc_link( $zbs->slugs['settings'] . '&tab=' . $zbs->modules->woosync->slugs['settings'] . '&subtab=' . $zbs->modules->woosync->slugs['settings_connections'] ); // retrieve current counts $jpcrm_woo_latest_stats = $zbs->modules->woosync->get_jpcrm_woo_latest_stats(); // from 5.2 we have multi-site syncing (that user may potentially be using) $active_connection_stack = array( 'external' => array(), 'local' => array(), ); $total_active_connections = 0; // this counts active connections (not paused) $total_paused_connections = 0; $site_connection_errors = 0; foreach ( $sync_sites as $site_key => $site_info ){ // external if ( $site_info['mode'] == JPCRM_WOO_SYNC_MODE_API ) { // vars $domain = $site_info['domain']; $key = $site_info['key']; $secret = $site_info['secret']; $prefix = $site_info['prefix']; $wc_setup_type_text = __( 'External site', 'zero-bs-crm' ); // if domain setting, show site if ( ! empty( $domain ) ) { $wc_setup_type_text .= ' - ' . __( 'Domain: ', 'zero-bs-crm' ) . $domain; } else { $wc_setup_type_text .= ' (' . __( 'No domain specified!', 'zero-bs-crm' ) . ')'; } // confirm settings if ( empty( $domain ) || empty( $key ) || empty( $secret ) ) { $error_notices[] = zeroBSCRM_UI2_messageHTML( 'warning', '', sprintf( __( 'You have not setup your WooCommerce API details for one of your connections. Please fill in your API details on the <a href="%s" target="_blank">connections page</a>.', 'zero-bs-crm' ), $connections_page_url ) ); // if no prefix, alert // really we could move this out of this block, but it would // get messy if they've already started an import if ( empty( $prefix ) ) { $error_notices[] = zeroBSCRM_UI2_messageHTML( 'info', '', sprintf( __( 'You are set up to import from an external site, but you have not set an order prefix. This is recommended so that orders from external sites do not clash with local/other site orders. Please add a prefix for the connection on the <a href="%s" target="_blank">connections page</a>.', 'zero-bs-crm' ), $connections_page_url ) ); } } else { $active_connection_stack['external'][] = $domain; // if not paused if ( !isset( $site_info['paused'] ) || empty( $site_info['paused'] ) ){ $total_active_connections++; } else { $total_paused_connections++; } // if any recorded errors: if ( isset( $site_info['site_connection_errors'] ) && $site_info['site_connection_errors'] > 0 ){ $site_connection_errors++; } } } else { // local install $wc_setup_type_text = __( 'Same site (local WooCommerce store)', 'zero-bs-crm' ); // verify woo installed if ( !$zbs->woocommerce_is_active() ) { $error_notices[] = zeroBSCRM_UI2_messageHTML( 'warning', '', __( 'You do not have WooCommerce installed. Please first install WooCommerce if you want to sync local store data.', 'zero-bs-crm' ) ); } else { $active_connection_stack['local'][] = site_url(); // if not paused if ( !isset( $site_info['paused'] ) || empty( $site_info['paused'] ) ){ $total_active_connections++; } else { $total_paused_connections++; } } } } // / per site connection // if we're using multiple connections if ( count( $sync_sites ) > 1 ){ $wc_setup_type_text = __( 'Multiple Site Connections', 'zero-bs-crm' ); // count them $wc_setup_type_text .= sprintf( __( ' (%d active and %d paused)', 'zero-bs-crm' ), $total_active_connections, count( $sync_sites ) - $total_active_connections ); } // catch zero connections active if ( $total_active_connections === 0 ){ $general_notices[] = zeroBSCRM_UI2_messageHTML( 'info', __( 'No Active Store Connections', 'zero-bs-crm' ), sprintf( __( 'You do not have any active store connections. WooSync is not currently syncing any order data. Please <a href="%s">connect a store</a>.', 'zero-bs-crm' ), $connections_page_url ) ); } elseif ( $total_paused_connections > 0 ) { // some active, some paused! $general_notices[] = zeroBSCRM_UI2_messageHTML( 'info', __( 'Paused Store Connections', 'zero-bs-crm' ), sprintf( __( 'One or more of your store connections are paused. WooSync will not currently sync any order data from these sites. Please <a href="%s">connect a store</a>.', 'zero-bs-crm' ), $connections_page_url ) ); } // catch site connection errors if ( $site_connection_errors > 0 ){ $general_notices[] = zeroBSCRM_UI2_messageHTML( 'info', __( 'Store Connection Error', 'zero-bs-crm' ), sprintf( __( 'A Store Connection is having trouble connecting. Please double check your <a href="%s">Store Connections</a>.', 'zero-bs-crm' ), $connections_page_url ) ); } $has_woosync_errors = count( $error_notices ) > 0; // shorthand $settings_cog_html = '<a href="' . $settings_page_url . '" title="' . __( 'Change Settings', 'zero-bs-crm' ) . '" target="_blank"><i class="cog icon"></i></a>'; $settings_cog_button_html = '<a href="' . $settings_page_url . '" title="' . __( 'Change Settings', 'zero-bs-crm' ) . '" target="_blank" class="ui right floated jpcrm-woosync-settings-button"><i class="cog icon"></i>' . __( 'WooSync Settings', 'zero-bs-crm' ) . '</a>'; ?> <div id="jpcrm-woosync-hub-page"> <div id="jpcrm-woo-logo"> <img id="jpcrm-woosync-jpcrm-logo" src="<?php echo esc_url( ZEROBSCRM_URL ); ?>i/jpcrm-logo-horizontal-black.png" alt="" /> <i class="plus icon"></i> <img id="jpcrm-woosync-woo-logo" src="<?php echo esc_url( ZEROBSCRM_URL ); ?>i/woocommerce-logo-color-black@2x.png" alt="" /> </div> <?php // any notices? if ( count( $general_notices ) > 0 ){ ?> <div id="jpcrm-woosync-messages"> <?php foreach ( $general_notices as $notice_html ){ echo $notice_html; } ?> </div> <?php } ?> <div class="ui segment" id="jpcrm-woosync-page-body"> <div> <div class="jpcrm-woosync-stats-header"></div> <?php // show any detected error messages if possible foreach ( $error_notices as $error_notice ) { echo $error_notice; } ?> </div> <?php if ( count( $sync_sites ) == 0 ){ // No connection ?> <h2 class="ui header"> <i id="jpcrm-woosync-status-icon" class="icon hourglass half green"></i> <div class="content"> <?php echo esc_html__( 'Status: ', 'zero-bs-crm' ) . esc_html__( 'Not yet connected', 'zero-bs-crm' ); ?> <div class="sub header"> <p class="jpcrm-woosync-recap"> <?php echo esc_html__( 'Setup Type: ', 'zero-bs-crm' ) . esc_html__( 'No connection', 'zero-bs-crm' ); ?> </p> <br> <span id="jpcrm-woosync-status-long-text"><?php echo wp_kses( sprintf( __( 'To get started with WooSync please <a href="%s">Connect to a Store</a>.', 'zero-bs-crm' ), $connections_page_url ), $zbs->acceptable_restricted_html ); ?></span> <i style="display:none" id="jpcrm_failed_ajax" class="grey exclamation circle icon"></i> <script> var jpcrm_woo_connect_initiate_ajax_sync = false; var jpcrm_woosync_nonce = '<?php echo esc_js( wp_create_nonce( 'jpcrm_woosync_hubsync' ) ); ?>'; </script> </div> </div> </h2> <?php } else { // Has Connection(s) // language $syncing_biline = __( 'Syncing content from WooCommerce...', 'zero-bs-crm' ); $initial_action = __( 'WooSync is importing orders...', 'zero-bs-crm' ); if ( $total_active_connections === 0 ){ $syncing_biline = __( 'Not Currently Syncing', 'zero-bs-crm' ); $initial_action = ''; } ?> <h2 class="ui header"> <i id="jpcrm-woosync-status-icon" class="icon hourglass half green"></i> <div class="content"> <?php esc_html_e( 'Status: ', 'zero-bs-crm' ); ?> <span id="jpcrm-woosync-status-short-text" class="status green"><?php echo esc_html( $syncing_biline ); ?></span> <div class="sub header"> <p class="jpcrm-woosync-recap"> <?php esc_html_e( 'Setup Type:', 'zero-bs-crm' ); ?> <?php echo esc_html( $wc_setup_type_text ); ?> <span id="jpcrm-woosync-stat-last-order-synced"><?php echo $jpcrm_woo_latest_stats['last_order_synced']; ?></span> </p> <br> <span id="jpcrm-woosync-status-long-text"><?php echo esc_html( $initial_action ); ?></span> <i style="display:none" id="jpcrm_failed_ajax" class="grey exclamation circle icon"></i> <script> var jpcrm_woo_connect_initiate_ajax_sync = true; var jpcrm_woosync_nonce = '<?php echo esc_js( wp_create_nonce( 'jpcrm_woosync_hubsync' ) ); ?>'; </script> <div class="ui inline loader" id="jpcrm_firing_ajax" title="<?php esc_attr_e( 'Keeping this page open will improve the background sync speed when synchronising.', 'zero-bs-crm' ); ?>"></div> </div> </div> </h2> <?php } ?> <div id="jpcrm-woo-stats" class="ui"> <?php if ( $jpcrm_woo_latest_stats['contacts_synced'] < 1 && $has_woosync_errors ) { ?> <div id="jpcrm-woo-stats-nothing-yet" class="ui active dimmer"> <div> <p><?php esc_html_e( "You don't have any data synced from WooCommerce yet.", 'zero-bs-crm' ); ?></p> <p> <a href="<?php echo esc_url( $settings_page_url ); ?>" target="_blank" class="ui small button"> <i class="cog icon"></i> <?php esc_html_e( 'Change Settings', 'zero-bs-crm' ); ?> </a> <?php ##WLREMOVE ?> <a href="<?php echo esc_url( $zbs->urls['kb-woosync-home'] ); ?>" target="_blank" class="ui small blue button"> <i class="file text outline icon"></i> <?php esc_html_e( 'Visit Setup Guide', 'zero-bs-crm' ); ?> </a> <?php ##/WLREMOVE ?> </p> </div> </div> <?php } ?> <div class="ui grid" id="jpcrm-woosync-stats-container"> <div class="five wide column"> <div class="jpcrm-woosync-stat ui inverted segment blue"> <div class="jpcrm-woosync-stat-container jpcrm-clickable" data-href="<?php echo esc_attr( zeroBSCRM_getAdminURL( $zbs->slugs['managecontacts'] . '&quickfilters=woo_customer' ) ); ?>"<?php // basic style scaling for large numbers. // On refining this hub page we should rethink if ( strlen( $jpcrm_woo_latest_stats['contacts_synced'] ) > 9 ) { // 10 million or more echo ' style="font-size:2.1em;"'; } ?>> <i class="user circle icon"></i><br /> <span id="jpcrm-woosync-stat-contacts-synced"><?php echo esc_html( $jpcrm_woo_latest_stats['contacts_synced'] ); ?></span> <div class="jpcrm-woosync-stat-label"><?php esc_html_e( 'Contacts', 'zero-bs-crm' ); ?></div> </div> </div> </div> <div class="five wide column"> <div class="jpcrm-woosync-stat ui inverted segment blue"> <div class="jpcrm-woosync-stat-container jpcrm-clickable" data-href="<?php echo esc_attr( zeroBSCRM_getAdminURL( $zbs->slugs['managetransactions'] . '&quickfilters=woo_transaction' ) ); ?>"<?php // basic style scaling for large numbers. // On refining this hub page we should rethink if ( strlen( $jpcrm_woo_latest_stats['transactions_synced'] ) > 9 ) { // 10 million or more echo ' style="font-size:2.1em;"'; } ?>> <i class="exchange icon"></i><br /> <span id="jpcrm-woosync-stat-transactions-synced"><?php echo esc_html( $jpcrm_woo_latest_stats['transactions_synced'] ); ?></span> <div class="jpcrm-woosync-stat-label"><?php esc_html_e( 'Transactions', 'zero-bs-crm' ); ?></div> </div> </div> </div> <div class="five wide column"> <div class="jpcrm-woosync-stat ui inverted segment blue"> <div class="jpcrm-woosync-stat-container"<?php // basic style scaling for large numbers. // On refining this hub page we should rethink if ( strlen( $jpcrm_woo_latest_stats['transaction_total'] ) > 11 ) { // millions echo ' style="font-size:1.7em;"'; } ?>> <i class="money bill alternate icon"></i><br /> <span id="jpcrm-woosync-stat-transaction-total"><?php echo esc_html( $jpcrm_woo_latest_stats['transaction_total'] ); ?></span> <div class="jpcrm-woosync-stat-label"><?php esc_html_e( 'WooCommerce Transaction Total', 'zero-bs-crm' ); ?></div> </div> </div> </div> </div> </div> </div> <div id="jpcrm-woosync-quiet-restart-link"> <?php esc_html_e( 'Admin Tools:', 'zero-bs-crm' ); // settings link if ( zeroBSCRM_isZBSAdminOrAdmin() ) { ?> <a href="<?php echo esc_url( $settings_page_url ); ?>"><?php esc_html_e( 'WooSync Settings', 'zero-bs-crm' ); ?></a> <?php ?>| <a href="<?php echo esc_url( $connections_page_url ); ?>"><?php esc_html_e( 'WooSync Connections', 'zero-bs-crm' ); ?></a> <?php } ?> | <a href="<?php echo jpcrm_esc_link( $zbs->modules->woosync->slugs['hub'] . '&restart_sync=1' ); ?>"><?php esc_html_e( 'Restart Sync', 'zero-bs-crm' ); ?></a> | <a href="<?php echo jpcrm_esc_link( $zbs->modules->woosync->slugs['hub'] . '&debug_sync=1' ); ?>"><?php esc_html_e( 'Run Sync debug', 'zero-bs-crm' ); ?></a> </div> </div> <?php jpcrm_woosync_output_language_labels(); } /* * Output <script> JS to pass language labels to JS * * @param $additional_labels - array; any key/value pairs here will be expressed in the JS label var */ function jpcrm_woosync_output_language_labels( $additional_labels = array() ){ // specify default (generic) labels $language_labels = array_merge( array( 'ajax_fail' => __( 'Failed retrieving data.', 'zero-bs-crm' ), 'complete' => __( 'Completed Sync.', 'zero-bs-crm' ), 'remaining_pages' => __( '{0} remaining pages.', 'zero-bs-crm' ), 'caught_mid_job' => __( 'Import job is running in the back end. If this message is still shown after some time, please contact support.', 'zero-bs-crm' ), 'server_error' => __( 'There was a general server error.', 'zero-bs-crm' ), 'incomplete_nextpage' => __( 'Completed page. Next: page {0} of {1} pages. ({2})', 'zero-bs-crm' ), 'complete_lastpage' => __( 'Completed last page, (page {0} of {1} pages)', 'zero-bs-crm' ), 'debug_return' => __( 'Return: {0}', 'zero-bs-crm' ), 'retrieving_page' => __( 'Retrieving page {0}', 'zero-bs-crm' ), ), $additional_labels ); ?><script>var jpcrm_woosync_language_labels = <?php echo json_encode( $language_labels ); ?></script><?php } /** * Styles and scripts for hub page */ function jpcrm_woosync_hub_page_styles_scripts(){ global $zbs; wp_enqueue_script( 'jpcrm-woo-sync', plugins_url( '/js/jpcrm-woo-sync-hub-page'.wp_scripts_get_suffix().'.js', JPCRM_WOO_SYNC_ROOT_FILE ), array( 'jquery' ), $zbs->modules->woosync->version ); wp_enqueue_style( 'jpcrm-woo-sync-hub-page', plugins_url( '/css/jpcrm-woo-sync-hub-page'.wp_scripts_get_suffix().'.css', JPCRM_WOO_SYNC_ROOT_FILE ) ); } /** * Run a sync in debug mode: */ function jpcrm_woosync_render_hub_page_debug_mode(){ global $zbs; ?><div id="jpcrm-woosync-hub-page"> <div id="jpcrm-woo-logo"> <img id="jpcrm-woosync-jpcrm-logo" src="<?php echo esc_url( ZEROBSCRM_URL ); ?>i/jpcrm-logo-horizontal-black.png" alt="" /> <i class="plus icon"></i> <img id="jpcrm-woosync-woo-logo" src="<?php echo esc_url( ZEROBSCRM_URL ); ?>i/woocommerce-logo-color-black@2x.png" alt="" /> </div> <div class="ui segment" id="jpcrm-woosync-page-body"> <h2>Debug Mode:</h2> <div id="jpcrm-woosync-debug-output"> <?php // set debug $zbs->modules->woosync->background_sync->debug = true; // call job function $zbs->modules->woosync->background_sync->sync_orders(); ?></div> </div> <p style="text-align: center;margin-top:2em"><a href="<?php echo jpcrm_esc_link( $zbs->modules->woosync->slugs['hub'] ) ?>" class="ui button green"><?php esc_html_e( 'Go back to WooSync Hub', 'zero-bs-crm' ); ?></a> </div><?php }
projects/plugins/crm/modules/woo-sync/admin/woo-sync-hub/main.page.ajax.php
<?php /** * Fired by AJAX on hub page (where still things to import, checks nonce and initiates import_orders) */ function jpcrm_woosync_ajax_import_orders( ){ global $zbs; // verify nonce check_ajax_referer( 'jpcrm_woosync_hubsync', 'sec' ); // init $return = $zbs->modules->woosync->background_sync->sync_orders(); // if something's returned, output via AJAX // (Mostly `background_sync->sync_orders()` will do this automatically) echo json_encode( $return ); exit(); } // import orders AJAX add_action( 'wp_ajax_jpcrm_woosync_fire_sync_job', 'jpcrm_woosync_ajax_import_orders' );
projects/plugins/crm/modules/automations/jpcrm-automations-init.php
<?php /** * Jetpack CRM * https://jetpackcrm.com * * Automation Module initialization * * @package automattic/jetpack-crm */ namespace Automattic\Jetpack_CRM\Modules\Automations; use Automattic\Jetpack\CRM\Automation\Automation_Bootstrap; if ( ! defined( 'ZEROBSCRM_PATH' ) ) { exit; } if ( ! apply_filters( 'jetpack_crm_feature_flag_automations', false ) ) { return; } /** * This is a temporary filter to disable the UI until we have completed building it * * @todo Remove this filter when the core Automation UI is ready to be released. * * @param bool $load_ui Whether to load the UI or not. * @return bool Whether to load the UI or not. */ function disable_ui_if_feature_flag_is_disabled( $load_ui ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable return apply_filters( 'jetpack_crm_feature_flag_automations', false ); } add_filter( 'jetpack_crm_automations_load_ui', __NAMESPACE__ . '\disable_ui_if_feature_flag_is_disabled', 99 ); /** * Load the Automation module. * * This is a core module that will always be loaded, so we do not allow it to be enabled/deactivated. * * @since 6.2.0 * * @return void */ function load_module() { define_constants(); require_once JPCRM_AUTOMATIONS_MODULE_PATH . '/admin/admin-page-init.php'; initialize_admin_page(); $bootstrap = new Automation_Bootstrap(); $bootstrap->init(); } add_action( 'jpcrm_load_modules', __NAMESPACE__ . '\load_module' ); /** * Defines constants * * @since 6.2.0 * * @return void */ function define_constants() { if ( ! defined( 'JPCRM_AUTOMATIONS_MODULE_ROOT_FILE' ) ) { define( 'JPCRM_AUTOMATIONS_MODULE_ROOT_FILE', __FILE__ ); } if ( ! defined( 'JPCRM_AUTOMATIONS_MODULE_PATH' ) ) { define( 'JPCRM_AUTOMATIONS_MODULE_PATH', __DIR__ ); } }
projects/plugins/crm/modules/automations/admin/admin-page-init.php
<?php /** * Jetpack CRM * https://jetpackcrm.com * * Automation admin page initialization * * @package automattic/jetpack-crm */ namespace Automattic\Jetpack_CRM\Modules\Automations; use Automattic\Jetpack\Assets; /** * The main initializing function. * * @since 6.2.0 * * @return void */ function initialize_admin_page() { add_action( 'load-jetpack-crm_page_jpcrm-automations', __NAMESPACE__ . '\admin_init' ); } /** * Actions to run on admin init * * @since 6.2.0 * * @return void */ function admin_init() { add_action( 'admin_enqueue_scripts', __NAMESPACE__ . '\enqueue_admin_scripts' ); } /** * Enqueues the React app bundle. * * @since 6.2.0 * * @return void */ function enqueue_admin_scripts() { Assets::register_script( 'jetpack-crm-automations', 'build/automations-admin/index.js', ZBS_ROOTFILE, array( 'in_footer' => true, 'textdomain' => 'zero-bs-crm', ) ); Assets::enqueue_script( 'jetpack-crm-automations' ); wp_add_inline_script( 'jetpack-crm-automations', render_initial_state(), 'before' ); } /** * Initial state to be served with the React app. * * @since 6.2.0 * * @return string */ function render_initial_state() { /** * Allow external plugins to modify Automations UI hydration data. * * @since 6.1.0 * * @param array { * Array of default data we need to render our React UI. * * @type string $apiRoot The base URL for the sites REST API. * @type string $apiNonce Nonce value to communicate with the sites REST API. * } */ $initial_state = apply_filters( 'jetpack_crm_automations_initial_state', array( 'apiRoot' => esc_url_raw( rest_url() ), 'apiNonce' => wp_create_nonce( 'wp_rest' ), ) ); return 'var jpcrmAutomationsInitialState=JSON.parse(decodeURIComponent( "' . rawurlencode( wp_json_encode( $initial_state ) ) . '" ) );'; }
projects/plugins/crm/modules/givewp/class-jpcrm-givewp.php
<?php /*! * Jetpack CRM * https://jetpackcrm.com * * GiveWP Module * */ namespace Automattic\JetpackCRM; // block direct access defined( 'ZEROBSCRM_PATH' ) || exit; /** * * GiveWP Connector for Jetpack CRM * */ class JPCRM_GiveWP { public function __construct() { if ( $this->check_dependencies() ) { $this->init_hooks(); } } /** * * Checks dependencies for GiveWP integration * * @return bool * */ public function check_dependencies() { global $zbs; $feature_name = 'GiveWP Connector for Jetpack CRM'; $give_core_reqs = array( 'req_core_ver' => $zbs->version, // will match current core version 'req_DAL_ver' => '3.0', ); $give_plug_reqs = array( 'name' => 'GiveWP', 'slug' => 'give/give.php', 'link' => 'https://wordpress.org/plugins/give/', 'kb_link' => $zbs->urls['kb_givewp'], 'req_ver' => '2.13.0', ); $meets_all_reqs = $zbs->dependency_checker->check_all_reqs( $feature_name, $give_core_reqs, $give_plug_reqs ); if ( $meets_all_reqs ) { return true; } return false; } /** * * Adds GiveWP hooks * */ public function init_hooks() { // fires at end of GiveWP's give_insert_payment() function add_action( 'give_insert_payment', array( $this, 'add_donation' ), 100, 2 ); // fires at end of GiveWP's Give_Payment::update_status() function add_action( 'give_update_payment_status', array( $this, 'update_donation_status' ), 200, 3 ); } /** * * Adds a donation transaction and its assigned donor contact * * This is hooked into the 'give_insert_payment' action, which is run at * the end of GiveWP's give_insert_payment() function * * @param int $givewp_donation_id donation ID * @param array $payment_data donor/donation info * */ public function add_donation( $givewp_donation_id, $payment_data ) { global $zbs; // add/update donor first $contact_id = $this->add_update_donor( $givewp_donation_id, $payment_data ); // check if transaction exists $transaction_id = $this->get_transaction_id_from_give_id( $givewp_donation_id ); // if donor now exists and the transaction ID does not exist, create! if ( $contact_id && !$transaction_id ) { // build transaction // status isn't always available, but we we don't really need it anyway as it'll be set by the 'update_donation_status' hook $transaction_status = isset( $payment_data['status'] ) ? ucfirst( $payment_data['status'] ) : 'pending'; // date isn't consistently available, so use now if it doesn't exist: // https://github.com/impress-org/givewp/blob/fd807ed0844996af33810dad11658e5c0b4aee5d/includes/payments/functions.php#L191-L193 // also, there's no indication as to timezone, so we'll just use server timezone $transaction_date = isset( $payment_data['post_date'] ) ? strtotime( $payment_data['post_date'] ) : date( 'U' ); $transaction_title = sprintf( __( 'GiveWP donation via the %s form', 'zero-bs-crm' ), $payment_data['give_form_title'] ); $new_transaction_data = array( 'status' => $transaction_status, 'type' => __( 'Sale', 'zero-bs-crm' ), // someday maybe we'll add a donation type 'ref' => $payment_data['purchase_key'], 'title' => $transaction_title, 'date' => $transaction_date, 'currency' => $payment_data['currency'], 'total' => $payment_data['price'], 'date_paid' => $transaction_date, 'date_completed' => $transaction_date, 'contacts' => array( $contact_id ), 'tags' => array( 'GiveWP' ), 'tag_mode' => 'append', 'externalSources' => array( array( 'source' => 'givewp', 'uid' => $givewp_donation_id, ), ), ); // add transaction $transaction_id = $zbs->DAL->transactions->addUpdateTransaction( array( 'data' => $new_transaction_data, 'extraMeta' => array( 'givewp_transaction_id' => $givewp_donation_id ), )); } } /** * * Adds or updates a donor contact * * @param int $givewp_donation_id donation ID * @param array $payment_data donor/donation info * * @return int $contact_id if successful * @return bool if unsuccessful * */ private function add_update_donor( $givewp_donation_id, $payment_data ) { global $zbs; // inspired by Jetpack Forms implementation $restricted_keys = array( 'externalSources', 'companies', 'lastcontacted', 'created', 'aliases', ); $jpcrm_field_prefix = 'jpcrm-'; // build contact $new_contact_data = array( 'status' => __( 'Donor', 'zero-bs-crm' ), 'tags' => array( 'GiveWP' ), 'tag_mode' => 'append', ); // note that GiveWP explicitly requires a name (first_name) and email by design // https://givewp.com/documentation/core/frequent-troubleshooting-issues/ foreach ( $payment_data['user_info'] as $k => $v ) { switch ( $k ) { case 'title': $new_contact_data['prefix'] = $v; break; case 'first_name': $new_contact_data['fname'] = $v; break; case 'last_name': $new_contact_data['lname'] = $v; break; case 'email': $new_contact_data['email'] = $v; break; case 'address': if ( !empty( $v ) ) { $new_contact_data['addr1'] = $v['line1']; $new_contact_data['addr2'] = $v['line2']; $new_contact_data['city'] = $v['city']; $new_contact_data['county'] = $v['state']; $new_contact_data['postcode'] = $v['zip']; $new_contact_data['country'] = $v['country']; } break; default: // handle any fields prefixed with $jpcrm_field_prefix as needed, // though by default GiveWP doesn't support custom fields if ( str_starts_with( $k, $jpcrm_field_prefix ) ) { $data_key = substr( $k, strlen( $jpcrm_field_prefix ) ); if ( ! in_array( $data_key, $restricted_keys, true ) ) { if ( $data_key === 'tags' ) { $new_contact_data['tags'] = explode( ',', $v ); $new_contact_data['tags'][] = 'GiveWP'; } else { $new_contact_data[ $data_key ] = $v; } } } } } // If this is an existing WordPress user, make sure not to lose that association. $wp_user = get_user_by( 'email', $new_contact_data['email'] ); if ( is_object( $wp_user ) ) { $new_contact_data['wpid'] = $wp_user->ID; } // specify contact source $new_contact_data['externalSources'] = array( array( 'source' => 'givewp', 'uid' => $new_contact_data['email'], ), ); // log if contact is created by GiveWP $longdesc = sprintf( __( 'User was created from GiveWP when submitting donation %s through the %s form.', 'zero-bs-crm' ), $givewp_donation_id, '<b>' . $payment_data['give_form_title'] . '</b>' ); $created_meta = array( 'note_override' => array( 'type' => __( 'Form filled', 'zero-bs-crm' ), 'shortdesc' => __( 'Created from GiveWP', 'zero-bs-crm' ), 'longdesc' => $longdesc, ), ); // log if GiveWP transaction was added to this contact $longdesc = sprintf( __( 'A GiveWP donation was submitted by this user via the %s form.', 'zero-bs-crm' ), '<b>' . $payment_data['give_form_title'] . '</b>' ); $exists_meta = array( 'type' => __( 'Form filled', 'zero-bs-crm' ), 'shortdesc' => __( 'Donation via GiveWP', 'zero-bs-crm' ), 'longdesc' => $longdesc, ); // add or update contact $contact_id = $zbs->DAL->contacts->addUpdateContact( array( 'data' => $new_contact_data, 'automatorPassthrough' => $created_meta, 'fallBackLog' => $exists_meta, 'extraMeta' => array(), ) ); return $contact_id; } /** * * Update a transaction status * * This is hooked into the 'give_update_payment_status' action, which * is run at the end of GiveWP's Give_Payment::update_status() function * * Note that this also runs when a new donation is created * * @param int $givewp_donation_id donation ID * @param string $new_status new donation status * @param string $old_status old donation status * * @return bool * */ public function update_donation_status( $givewp_donation_id, $new_status, $old_status ) { global $zbs; // completed status in GiveWP is actually publish if ( $new_status === 'publish' ) { $new_status = 'Completed'; } else { // GiveWP passes lowercase statuses $new_status = ucfirst( $new_status ); } // check if transaction exists $transaction_id = (int)$this->get_transaction_id_from_give_id( $givewp_donation_id ); // update status if transaction exists if ( $transaction_id > 0 ) { return $zbs->DAL->transactions->setTransactionStatus( $transaction_id, $new_status ); } return false; } /** * * Gets a transaction by its GiveWP donation ID * * @param int $givewp_donation_id the GiveWP donation ID * * @return int $contact_id if successful * @return bool if unsuccessful * */ public function get_transaction_id_from_give_id( $givewp_donation_id ) { global $zbs; return $zbs->DAL->getIDWithMeta( array( 'objtype' => ZBS_TYPE_TRANSACTION, 'key' => 'extra_givewp_transaction_id', 'val' => $givewp_donation_id, )); } }
projects/plugins/crm/modules/givewp/jpcrm-givewp-init.php
<?php if ( ! defined( 'ZEROBSCRM_PATH' ) ) exit; /** * This file registers the GiveWP module with core; it's pretty convoluted, * but that's due to a legacy init setup. The goal here is to have all * needed code self-contained in the module's folder. * * If the module is enabled, it is loaded with the jpcrm_load_modules hook */ global $zbs; $zbs->urls['kb_givewp'] = 'https://kb.jetpackcrm.com/knowledge-base/givewp-connector-for-jetpack-crm/'; // adds a feature that we can sniff for function jpcrm_sniff_feature_givewp() { global $zbs; $zbs->feature_sniffer->sniff_for_plugin( array( 'feature_slug' => 'givewp', 'plugin_slug' => 'give/give.php', 'more_info_link' => $zbs->urls['kb_givewp'], 'is_module' => true, ) ); } add_action( 'jpcrm_sniff_features', 'jpcrm_sniff_feature_givewp' ); // registers a GiveWP as a core extension function jpcrm_register_free_extension_givewp( $exts ) { $exts['givewp'] = array( 'name' => __( 'GiveWP Connector', 'zero-bs-crm' ), 'i' => 'givewp.png', 'short_desc' => __( 'Capture donations into your CRM.', 'zero-bs-crm' ), ); return $exts; } add_filter( 'jpcrm_register_free_extensions', 'jpcrm_register_free_extension_givewp' ); // registers a GiveWP as an external source function jpcrm_register_external_sources_givewp( $external_sources ) { $external_sources['givewp'] = array( 'GiveWP', 'ico' => 'fa-wpforms', ); return $external_sources; } add_filter( 'jpcrm_register_external_sources', 'jpcrm_register_external_sources_givewp' ); global $zeroBSCRM_extensionsCompleteList; $zeroBSCRM_extensionsCompleteList['givewp'] = array( 'fallbackname' => __( 'GiveWP Connector', 'zero-bs-crm' ), 'imgstr' => '<i class="fa fa-keyboard-o" aria-hidden="true"></i>', 'desc' => __( 'Capture donations in your CRM', 'zero-bs-crm' ), // 'url' => 'https://jetpackcrm.com/feature/', 'colour' => 'rgb(126, 88, 232)', 'helpurl' => 'https://kb.jetpackcrm.com/knowledge-base/givewp/', 'shortname' => __( 'GiveWP Connector', 'zero-bs-crm' ), // used where long name won't fit ); global $jpcrm_core_extension_setting_map; $jpcrm_core_extension_setting_map['givewp'] = 'feat_givewp'; // adds install/uninstall functions function zeroBSCRM_extension_install_givewp() { $is_installed = jpcrm_install_core_extension( 'givewp' ); if ( $is_installed ) { global $zbs; // add donor contact status if it doesn't exist $status_to_add = __( 'Donor', 'zero-bs-crm' ); $customised_fields_settings = $zbs->settings->get( 'customisedfields' ); $contact_statuses = explode( ',', $customised_fields_settings['customers']['status'][1] ); if ( !in_array( $status_to_add, $contact_statuses ) ) { $contact_statuses[] = $status_to_add; } $customised_fields_settings['customers']['status'][1] = implode( ',', $contact_statuses ); $zbs->settings->update( 'customisedfields', $customised_fields_settings ); } return $is_installed; } function zeroBSCRM_extension_uninstall_givewp() { return jpcrm_uninstall_core_extension( 'givewp' ); } // load the JPCRM_GiveWP class if feature is enabled function jpcrm_load_givewp() { global $zbs; if ( zeroBSCRM_isExtensionInstalled( 'givewp' ) ) { require_once( JPCRM_MODULES_PATH . 'givewp/class-jpcrm-givewp.php' ); // $zbs->givewp = new JPCRM_GiveWP; $zbs->modules->load_module( 'givewp', 'JPCRM_GiveWP' ); } } add_action( 'jpcrm_load_modules', 'jpcrm_load_givewp' );
projects/plugins/crm/src/automation/class-base-condition.php
<?php /** * Base Condition implementation * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation; /** * Base Condition Step. * * @since 6.2.0 * {@inheritDoc} */ abstract class Base_Condition extends Base_Step implements Condition { /** * The Automation logger. * * @since 6.2.0 * @var Automation_Logger $logger The Automation logger. */ protected $logger; /** * If the condition is met or not. * * @since 6.2.0 * @var bool If the condition is met or not. */ protected $condition_met = false; /** * All valid operators for this condition. * * @since 6.2.0 * @var string[] $valid_operators Valid operators. */ protected $valid_operators = array(); /** * Base_Condition constructor. * * @since 6.2.0 * * @param array $step_data The step data. */ public function __construct( array $step_data ) { parent::__construct( $step_data ); $this->logger = Automation_Logger::instance(); } /** * Get the next step. * * @since 6.2.0 * * @return string|int|null The next step data. */ public function get_next_step_id() { return ( $this->condition_met ? $this->next_step_true : $this->next_step_false ); } /** * Met the condition? * * @since 6.2.0 * * @return bool If the condition is met or not. */ public function condition_met(): bool { return $this->condition_met; } /** * Checks if this is a valid operator for this condition and throws an * exception if the operator is invalid. * * @since 6.2.0 * * @param string $operator The operator. * @return void * * @throws Automation_Exception If the operator is invalid for this condition. */ protected function check_for_valid_operator( string $operator ): void { if ( ! array_key_exists( $operator, $this->valid_operators ) ) { $this->condition_met = false; $this->logger->log( 'Invalid operator: ' . $operator ); throw new Automation_Exception( /* Translators: %s is the invalid operator. */ sprintf( __( 'Invalid condition operator: %s', 'zero-bs-crm' ), $operator ), Automation_Exception::CONDITION_INVALID_OPERATOR ); } } }
projects/plugins/crm/src/automation/class-base-step.php
<?php /** * Base Step * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation; use Automattic\Jetpack\CRM\Automation\Data_Types\Data_Type; /** * Base Step. * * @since 6.2.0 * {@inheritDoc} */ abstract class Base_Step implements Step { /** * Step attributes. * * @since 6.2.0 * @var array */ protected $attributes; /** * Attributes definitions. * * @since 6.2.0 * @var array */ protected $attribute_definitions = array(); /** * The next step if the current one is successful. * * @since 6.2.0 * @var int|string|null */ protected $next_step_true = null; /** * The next step if not successful. * * @since 6.2.0 * @var int|string|null */ protected $next_step_false = null; /** * Base_Step constructor. * * @since 6.2.0 * * @param array $step_data An array of data for the current step. */ public function __construct( array $step_data ) { $this->attributes = $step_data['attributes'] ?? array(); $this->next_step_true = $step_data['next_step_true'] ?? null; $this->next_step_false = $step_data['next_step_false'] ?? null; } /** * Get the data of the step. * * @since 6.2.0 * * @return array The step data. */ public function get_attributes(): array { return $this->attributes; } /** * Set attributes of the step. * * @since 6.2.0 * * @param array $attributes The attributes to set. */ public function set_attributes( array $attributes ) { $this->attributes = $attributes; } /** * Get attribute value. * * @since 6.2.0 * * @param string $attribute The attribute to get. * @param mixed $default The default value to return if the attribute is not set. * @return mixed The attribute value. */ public function get_attribute( string $attribute, $default = null ) { return $this->attributes[ $attribute ] ?? $default; } /** * Set attribute value. * * @since 6.2.0 * * @param string $attribute The attribute key. * @param mixed $value The default value. * @return void */ public function set_attribute( string $attribute, $value ): void { $this->attributes[ $attribute ] = $value; } /** * Get the step attribute definitions. * * @since 6.2.0 * * @return Attribute_Definition[] The attribute definitions of the step. */ public function get_attribute_definitions(): array { return $this->attribute_definitions; } /** * Set the step attributes. * * @since 6.2.0 * * @param Attribute_Definition[] $attribute_definitions Set the step attributes. */ public function set_attribute_definitions( array $attribute_definitions ) { $this->attribute_definitions = $attribute_definitions; } /** * Get the next step. * * Unless anything else is defined, then we assume to only continue with the * next step if the current one is successful. * One example of this will be conditions where a certain criteria has not been met. * * @since 6.2.0 * * @return int|string|null The next linked step id. */ public function get_next_step_id() { return $this->get_next_step_true(); } /** * Get the next step if the current one is successful. * * @since 6.2.0 * * @return int|string|null The next linked step id. */ public function get_next_step_true() { return $this->next_step_true; } /** * Set the next step if the current one is successful. * * @since 6.2.0 * * @param string|int|null $step_id The next linked step id. * @return void */ public function set_next_step_true( $step_id ): void { $this->next_step_true = $step_id; } /** * Get the next step if the current one is falsy. * * @since 6.2.0 * * @return int|string|null The next linked step id. */ public function get_next_step_false() { return $this->next_step_false; } /** * Set the next step if the current one is falsy. * * @since 6.2.0 * * @param string|int|null $step_id The next linked step id. * @return void */ public function set_next_step_false( $step_id ): void { $this->next_step_false = $step_id; } /** * Validate data passed to the step * * @since 6.2.0 * * @param Data_Type $data Data type passed. * @return void * * @throws Data_Type_Exception If the data type passed is not expected. */ public function validate( Data_Type $data ): void { $data_type_class = static::get_data_type(); if ( ! $data instanceof $data_type_class ) { throw new Data_Type_Exception( sprintf( 'Invalid data type passed to step: %s', static::class ), Data_Type_Exception::INVALID_DATA ); } } /** * Validate and execute the step. * * @since 6.2.0 * * @param Data_Type $data Data type passed. * @return void * * @throws Data_Type_Exception If the data type passed is not expected. */ public function validate_and_execute( Data_Type $data ): void { $this->validate( $data ); $this->execute( $data ); } /** * Execute the step. * * @since 6.2.0 * * @param Data_Type $data Data type passed from the trigger. */ abstract protected function execute( Data_Type $data ); /** * Get the slug name of the step. * * @since 6.2.0 * * @return string The slug name of the step. */ abstract public static function get_slug(): string; /** * Get the title of the step. * * @since 6.2.0 * * @return string|null The title of the step. */ abstract public static function get_title(): ?string; /** * Get the description of the step. * * @since 6.2.0 * * @return string|null The description of the step. */ abstract public static function get_description(): ?string; /** * Get the data type exepected by the step. * * @since 6.2.0 * * @return string The data type expected by the step. */ abstract public static function get_data_type(): string; /** * Get the category of the step. * * @since 6.2.0 * * @return string|null The category of the step. */ abstract public static function get_category(): ?string; /** * Get the step as an array. * * The main use-case to get the step as an array is to prepare * the items for an API response. * * @since 6.2.0 * * @return array The step as an array. */ public function to_array(): array { $step = array( 'title' => static::get_title(), 'description' => static::get_description(), 'slug' => static::get_slug(), 'category' => static::get_category(), 'step_type' => is_subclass_of( $this, Action::class ) ? 'action' : 'condition', 'next_step_true' => $this->get_next_step_true(), 'next_step_false' => $this->get_next_step_false(), 'attributes' => $this->get_attributes(), 'attribute_definitions' => array(), ); foreach ( $this->get_attribute_definitions() as $attribute_definition ) { $step['attribute_definitions'][ $attribute_definition->get_slug() ] = $attribute_definition->to_array(); } return $step; } }
projects/plugins/crm/src/automation/class-automation-workflow.php
<?php /** * Defines the Jetpack CRM Automation workflow base. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation; use Automattic\Jetpack\CRM\Automation\Data_Types\Data_Type; /** * Adds the Automation_Workflow class. * * @since 6.2.0 */ class Automation_Workflow { /** * The workflow id. * * @since 6.2.0 * @var int|string */ protected $id; /** * The CRM site ID the workflow belongs to. * * @since 6.2.0 * @var int */ protected $zbs_site; /** * The WP User who created the workflow. * * @since 6.2.0 * @var int */ protected $zbs_owner; /** * The workflow name. * * @since 6.2.0 * @var string */ public $name; /** * The workflow description. * * @since 6.2.0 * @var string */ public $description; /** * The workflow category. * * @since 6.2.0 * @var string */ public $category; /** * The workflow triggers. * * @since 6.2.0 * @var string[] */ public $triggers; /** * The workflow initial step id. * * @since 6.2.0 * @var int|string|null */ public $initial_step; /** * The workflow steps list * * @since 6.2.0 * @var array */ public $steps; /** * The workflow active status. * * @since 6.2.0 * @var bool */ public $active; /** * The version of the workflow. * * @since 6.2.0 * @var int */ protected $version; /** * A timestamp that reflects when the workflow was created. * * @since 6.2.0 * @var int */ protected $created_at; /** * A timestamp that reflects when the workflow was last updated. * * @since 6.2.0 * @var int */ protected $updated_at; /** * The automation engine. * * @since 6.2.0 * @var Automation_Engine */ protected $automation_engine; /** * The automation logger. * * @since 6.2.0 * @var Automation_Logger */ protected $logger; /** * Automation_Workflow constructor. * * @since 6.2.0 * * @param array $workflow_data The workflow data to be constructed. */ public function __construct( array $workflow_data ) { $this->id = $workflow_data['id'] ?? null; $this->zbs_site = $workflow_data['zbs_site'] ?? -1; $this->zbs_owner = $workflow_data['zbs_owner'] ?? -1; $this->triggers = $workflow_data['triggers'] ?? array(); $this->steps = $workflow_data['steps'] ?? array(); $this->initial_step = $workflow_data['initial_step'] ?? ''; $this->name = $workflow_data['name'] ?? ''; $this->description = $workflow_data['description'] ?? ''; $this->category = $workflow_data['category'] ?? ''; $this->active = $workflow_data['active'] ?? false; $this->version = $workflow_data['version'] ?? 1; $this->created_at = $workflow_data['created_at'] ?? null; $this->updated_at = $workflow_data['updated_at'] ?? null; } /** * Get the id of this workflow. * * This will either be a string if the workflow is registered in the codebase, * or an integer if it is a custom workflow stored in the database. * * @since 6.2.0 * * @return int|string The workflow id. */ public function get_id() { return $this->id; } /** * Get the CRM site the workflow should run on. * * @since 6.2.0 * * @return int */ public function get_zbs_site(): int { return $this->zbs_site; } /** * Set the CRM site teh workflow should run on. * * @since 6.2.0 * * @param int $site The CRM site the workflow should run on. * @return void */ public function set_zbs_site( int $site ): void { $this->zbs_site = $site; } /** * Get the CRM owner/creator of the workflow. * * @since 6.2.0 * * @return int */ public function get_zbs_owner(): int { return $this->zbs_owner; } /** * Set the CRM owner/creator of the workflow. * * @since 6.2.0 * * @param int $owner The CRM owner/creator of the workflow. * @return void */ public function set_zbs_owner( int $owner ): void { $this->zbs_owner = $owner; } /** * Get name. * * @since 6.2.0 * * @return string */ public function get_name(): string { return $this->name; } /** * Set name. * * @since 6.2.0 * * @param string $name The workflow name. * @return void */ public function set_name( string $name ): void { $this->name = $name; } /** * Get description. * * @since 6.2.0 * * @return string */ public function get_description(): string { return $this->description; } /** * Set description. * * @since 6.2.0 * * @param string $description The workflow description. * @return void */ public function set_description( string $description ): void { $this->description = $description; } /** * Get category. * * @since 6.2.0 * * @return string */ public function get_category(): string { return $this->category; } /** * Set category. * * @since 6.2.0 * * @param string $category The workflow category. * @return void */ public function set_category( string $category ): void { $this->category = $category; } /** * Get the database schema version. * * @since 6.2.0 * * @return int */ public function get_version(): int { return $this->version; } /** * Get the timestamp for when the workflow was created. * * @since 6.2.0 * * @return int|null */ public function get_created_at(): ?int { return $this->created_at; } /** * Get the timestamp for when the workflow was last updated. * * @since 6.2.0 * * @return int|null */ public function get_updated_at(): ?int { return $this->updated_at; } /** * Set the triggers within the workflow given an array of triggers. * * @since 6.2.0 * * @param string[] $triggers An array of triggers to be set. * @return void */ public function set_triggers( array $triggers ): void { $this->triggers = $triggers; } /** * Get the trigger names of this workflow. * * @since 6.2.0 * * @return string[] The workflow trigger names. */ public function get_triggers(): array { return $this->triggers; } /** * Instance the triggers of this workflow. * * @since 6.2.0 * * @throws Workflow_Exception Throws an exception if there is an issue initializing the trigger. * @return void */ public function init_triggers(): void { $this->get_logger()->log( 'Initializing Workflow triggers...' ); if ( ! $this->is_active() ) { $this->get_logger()->log( 'The workflow is not active. No triggers loaded.' ); return; } foreach ( $this->get_triggers() as $trigger_slug ) { try { $trigger_class = $this->get_engine()->get_trigger_class( $trigger_slug ); /** @var Base_Trigger $trigger */ $trigger = new $trigger_class(); $trigger->init( $this ); $this->get_logger()->log( 'Trigger initialized: ' . $trigger_slug ); } catch ( Automation_Exception $e ) { throw new Workflow_Exception( /* Translators: %s is the error message to be included in the exception string. */ sprintf( __( 'An error happened initializing the trigger. %s', 'zero-bs-crm' ), $e->getMessage() ), Workflow_Exception::ERROR_INITIALIZING_TRIGGER ); } } } /** * Set initial step of this workflow. * * @since 6.2.0 * * @param int|string|null $step_id The initial step id. * @return void */ public function set_initial_step( $step_id ): void { $this->initial_step = $step_id; } /** * Set the step list of this workflow. * * @since 6.2.0 * * @param array $steps The steps of the workflow. */ public function set_steps( array $steps ) { $this->steps = $steps; } /** * Get the workflow as an array. * * The main use-case to get the workflow as an array is to be stored * in the database or if it is being shared via API. * * @since 6.2.0 * * @return array The workflow as an array. */ public function to_array(): array { return array( 'id' => $this->get_id(), 'zbs_site' => $this->get_zbs_site(), 'zbs_owner' => $this->get_zbs_owner(), 'name' => $this->get_name(), 'description' => $this->get_description(), 'category' => $this->get_category(), 'triggers' => $this->get_triggers(), 'steps' => $this->get_steps(), 'initial_step' => $this->get_initial_step_index(), 'active' => $this->is_active(), 'version' => $this->get_version(), 'created_at' => $this->get_created_at(), 'updated_at' => $this->get_updated_at(), ); } /** * Get the initial step data of this workflow. * * @since 6.2.0 * * @return array|null The initial step data of the workflow. */ public function get_initial_step(): ?array { return $this->steps[ $this->get_initial_step_index() ] ?? null; } /** * Get the initial step index of this workflow. * * @since 6.2.0 * * @return int|string|null The index key for the next step of the workflow. */ public function get_initial_step_index() { return $this->initial_step; } /** * Get the steps of this workflow. * * @since 6.2.0 * * @return array The steps of the workflow. */ public function get_steps(): array { return $this->steps; } /** * Get the initial step of this workflow. * * @since 6.2.0 * * @param int|string $id The step id. * @return array|null The step data instance. */ public function get_step( $id ): ?array { if ( $id === null ) { return null; } return $this->steps[ $id ] ?? null; } /** * Start the workflow execution once a trigger is activated. * * @since 6.2.0 * * @param Trigger $trigger An instance of the Trigger class. * @param Data_Type|null $data All relevant object data to be passed through the workflow. * @return bool Whether the workflow was executed successfully. * * @throws Automation_Exception|Workflow_Exception Throws an exception if there is an issue executing the workflow. * @throws Data_Transformer_Exception Throws an exception if there is an issue transforming the data. */ public function execute( Trigger $trigger, Data_Type $data = null ): bool { return $this->get_engine()->execute_workflow( $this, $trigger, $data ); } /** * Turn on the workflow. * * @since 6.2.0 * * @return void */ public function turn_on(): void { $this->active = true; } /** * Turn off the workflow. * * @since 6.2.0 * * @return void */ public function turn_off(): void { $this->active = false; } /** * Check if the workflow is active. * * @since 6.2.0 * * @return bool Whether the workflow is active. */ public function is_active(): bool { return $this->active; } /** * Add a trigger to this workflow. * * @since 6.2.0 * * @param string $string The name of the trigger to add. * @return void */ public function add_trigger( string $string ): void { $this->triggers[] = $string; } /** * Set the automation engine. * * @since 6.2.0 * * @param Automation_Engine $engine An instance of the Automation_Engine class. * @return void * @throws Workflow_Exception|Automation_Exception Exception if there is an issue with the Engine. */ public function set_engine( Automation_Engine $engine ): void { $this->automation_engine = $engine; // Process and check the steps when the engine is set. $this->process_steps(); } /** * Get the automation engine. * * @since 6.2.0 * * @return Automation_Engine Return an instance of the Automation_Engine class. * * @throws Workflow_Exception Throws an exception if there is no engine instance. */ protected function get_engine(): Automation_Engine { if ( ! $this->automation_engine instanceof Automation_Engine ) { throw new Workflow_Exception( /* Translators: %s The ID of the workflow. */ sprintf( '[%s] Cannot run workflow logic without an engine instance', $this->get_id() ), Workflow_Exception::MISSING_ENGINE_INSTANCE ); } return $this->automation_engine; } /** * Set Logger. * * @since 6.2.0 * * @param Automation_Logger $logger An instance of the Automation_Logger class. * @return void */ public function set_logger( Automation_Logger $logger ) { $this->logger = $logger; } /** * Get Logger. * * @since 6.2.0 * * @return Automation_Logger Return an instance of the Automation_Logger class. */ public function get_logger(): Automation_Logger { return $this->logger ?? Automation_Logger::instance(); } /** * Process the steps of the workflow. * * @throws Workflow_Exception|Automation_Exception Exception if there is an issue processing the steps. * @since 6.2.0 */ private function process_steps() { foreach ( $this->steps as $step_data ) { if ( ! isset( $step_data['class_name'] ) ) { $step_data['class_name'] = $this->get_engine()->get_step_class( $step_data['slug'] ); } } } /** * Set the timestamp for when the workflow was created. * * @since 6.2.0 * * @param int $time The timestamp for when the workflow was created. * @return void */ public function set_created_at( int $time ): void { $this->created_at = $time; } /** * Set the timestamp for when the workflow was last updated. * * @since 6.2.0 * * @param int $time The timestamp for when the workflow was last updated. * @return void */ public function set_updated_at( int $time ): void { $this->updated_at = $time; } /** * Set the id of the workflow. * * @since 6.2.0 * * @param int|string $id The workflow id. * @return void */ public function set_id( $id ): void { $this->id = $id; } }
projects/plugins/crm/src/automation/class-base-trigger.php
<?php /** * Base Trigger implementation * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation; /** * Base Trigger implementation. * * @since 6.2.0 * {@inheritDoc} */ abstract class Base_Trigger implements Trigger { /** * The workflow to execute by this trigger. * * @since 6.2.0 * @var Automation_Workflow */ protected $workflow = null; /** * Set the workflow to execute by this trigger. * * @since 6.2.0 * * @param Automation_Workflow $workflow The workflow to execute by this trigger. */ public function set_workflow( Automation_Workflow $workflow ) { $this->workflow = $workflow; } /** * Execute the workflow. * * @since 6.2.0 * * @param mixed|null $data The data to pass to the workflow. * @param mixed|null $previous_data The previous data to pass to the workflow. * * @throws Workflow_Exception Exception when the workflow is executed. */ public function execute_workflow( $data = null, $previous_data = null ) { // Encapsulate the $data into a Data_Type object. $data_type_class = static::get_data_type(); $data_type = new $data_type_class( $data, $previous_data ); if ( $this->workflow ) { $this->workflow->execute( $this, $data_type ); } } /** * Initialize the trigger to listen to the desired event. * * @since 6.2.0 * * @param Automation_Workflow $workflow The workflow to execute by this trigger. */ public function init( Automation_Workflow $workflow ) { $this->workflow = $workflow; $this->listen_to_event(); } /** * Listen to the desired WP hook action. * * @param string $hook_name The hook name to listen to. * @param int $priority The priority of the action. * @param int $accepted_args The number of arguments the action accepts. * @since 6.2.0 * */ protected function listen_to_wp_action( string $hook_name, int $priority = 10, int $accepted_args = 1 ): void { add_action( $hook_name, array( $this, 'execute_workflow' ), $priority, $accepted_args ); } /** * Get the trigger slug. * * @since 6.2.0 * * @return string The trigger slug. */ abstract public static function get_slug(): string; /** * Get the trigger title. * * @since 6.2.0 * * @return string|null The trigger title. */ abstract public static function get_title(): ?string; /** * Get the trigger description. * * @since 6.2.0 * * @return string|null The trigger description. */ abstract public static function get_description(): ?string; /** * Get the trigger category. * * @since 6.2.0 * * @return string|null The trigger category. */ abstract public static function get_category(): ?string; /** * Listen to the desired event. It will be called by init(), it should * call the execute_workflow method when the event happens. * * @since 6.2.0 * * @return void */ abstract protected function listen_to_event(): void; /** * Get the trigger as an array. * * The main use-case to get the trigger as an array is to prepare * the items for an API response. * * @since 6.2.0 * * @return array The trigger as an array. */ public static function to_array(): array { return array( 'slug' => static::get_slug(), 'title' => static::get_title(), 'description' => static::get_description(), 'category' => static::get_category(), ); } }
projects/plugins/crm/src/automation/interface-action.php
<?php /** * Interface Action. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation; /** * Interface Action. * * @since 6.2.0 */ interface Action extends Step { }
projects/plugins/crm/src/automation/class-data-type-exception.php
<?php /** * Jetpack CRM Automation data type exception. * * @package automattic/jetpack-crm */ namespace Automattic\Jetpack\CRM\Automation; /** * Adds a Data_Type specific exception. * * @since 6.2.0 */ class Data_Type_Exception extends \Exception { /** * Error code for when the class doesn't exist. * * @since 6.2.0 * * @var int */ const CLASS_NOT_FOUND = 10; /** * Error code for when a transformer is passed, but doesn't extend the base class. * * @since 6.2.0 * * @var int */ const DO_NOT_EXTEND_BASE = 11; /** * Error code for when a slug is already being used. * * @since 6.2.0 * * @var int */ const SLUG_EXISTS = 12; /** * Error code for when a workflow tries to call a data type that doesn't exist. * * @since 6.2.0 * * @var int */ const SLUG_DO_NOT_EXIST = 13; /** * Error code for when the passed data do not match expected format/type. * * @since 6.2.0 * * @var int */ const INVALID_DATA = 20; }
projects/plugins/crm/src/automation/interface-step.php
<?php /** * Interface to define Step in an automation workflow. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation; /** * Interface Step. * * @since 6.2.0 */ interface Step { /** * Get the next step. * * @since 6.2.0 * * @return int|string|null The next linked step. */ public function get_next_step_id(); /** * Get the next step if the current one is successful. * * @since 6.2.0 * * @return int|string|null The next linked step id. */ public function get_next_step_true(); /** * Set the next step if the current one is successful. * * @since 6.2.0 * * @param string|int|null $step_id The next linked step id. * @return void */ public function set_next_step_true( $step_id ): void; /** * Get the next step if the current one is falsy. * * @since 6.2.0 * * @return int|string|null The next linked step id. */ public function get_next_step_false(); /** * Set the next step if the current one is falsy. * * @since 6.2.0 * * @param string|int|null $step_id The next linked step id. * @return void */ public function set_next_step_false( $step_id ): void; /** * Get the step attribute definitions. * * @since 6.2.0 * * @return Attribute_Definition[] The attribute definitions of the step. */ public function get_attribute_definitions(): ?array; /** * Get attribute value. * * @since 6.2.0 * * @param string $attribute The attribute to get. * @param mixed $default The default value to return if the attribute is not set. * @return mixed The attribute value. */ public function get_attribute( string $attribute, $default = null ); /** * Set attribute value. * * @since 6.2.0 * * @param string $attribute The attribute key. * @param mixed $value The default value. * @return void */ public function set_attribute( string $attribute, $value ); /** * Set the step attribute definitions. * * @since 6.2.0 * * @param Attribute_Definition[] $attribute_definitions Set the attribute definitions. */ public function set_attribute_definitions( array $attribute_definitions ); /** * Get the attributes of the step. * * @since 6.2.0 * * @return array The attributes of the step. */ public function get_attributes(): ?array; /** * Get the attributes of the step. * * @since 6.2.0 * * @param array $attributes Set attributes to this step. */ public function set_attributes( array $attributes ); /** * Get the slug name of the step. * * @since 6.2.0 * * @return string The slug name of the step. */ public static function get_slug(): string; /** * Get the title of the step. * * @since 6.2.0 * * @return string|null The title of the step. */ public static function get_title(): ?string; /** * Get the description of the step. * * @since 6.2.0 * * @return string|null The description of the step. */ public static function get_description(): ?string; /** * Get the data type expected by the step. * * @since 6.2.0 * * @return string|null The data type expected by the step. */ public static function get_data_type(): string; /** * Get the category of the step. * * @since 6.2.0 * * @return string|null The category of the step. */ public static function get_category(): ?string; /** * Get the step as an array. * * The main use-case to get the step as an array is to prepare * the items for an API response. * * @since 6.2.0 * * @return array The step as an array. */ public function to_array(): array; }
projects/plugins/crm/src/automation/class-attribute-definition.php
<?php /** * Attribute Definition * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation; /** * Attribute Definition. * * An attribute represents how a step is configured. For example, a step that * sends an email to a contact may have an attribute that represents the email * subject, another attribute that represents the email body, and so on. * * @since 6.2.0 */ class Attribute_Definition { /** * Represents a dropdown selection input. * * @since 6.2.0 * @var string */ const SELECT = 'select'; /** * Represents a checkbox input. * * @since 6.2.0 * @var string */ const CHECKBOX = 'checkbox'; /** * Represents a textarea input. * * @since 6.2.0 * @var string */ const TEXTAREA = 'textarea'; /** * Represents a text input. * * @since 6.2.0 * @var string */ const TEXT = 'text'; /** * Represents a date input. * * @since 6.2.0 * @var string */ const DATE = 'date'; /** * Represents a numerical input. * * @since 6.2.0 * @var string */ const NUMBER = 'number'; /** * The slug (key) that identifies this attribute. * * @since 6.2.0 * @var string */ protected $slug; /** * The title (label) for this attribute. * * @since 6.2.0 * @var string */ protected $title; /** * The description for this attribute. * * @since 6.2.0 * @var string */ protected $description; /** * Attribute type. * * This is a string that represents the type of the attribute. * E.g.: 'text', 'number', 'select', etc. * * @since 6.2.0 * @var string */ protected $type; /** * Data needed by this attribute (e.g. a map of "key -> description" in the case of a select). * * @since 6.2.0 * @var array|null */ protected $data; /** * Constructor. * * @since 6.2.0 * * @param string $slug The slug (key) that identifies this attribute. * @param string $title The title (label) for this attribute. * @param string $description The description for this attribute. * @param string $type Attribute type. * @param array|null $data Data needed by this attribute. */ public function __construct( string $slug, string $title, string $description, string $type, ?array $data = null ) { $this->slug = $slug; $this->title = $title; $this->description = $description; $this->type = $type; $this->data = $data; } /** * Get the slug. * * @since 6.2.0 * * @return string */ public function get_slug(): string { return $this->slug; } /** * Set the slug. * * @since 6.2.0 * * @param string $slug The slug (key) that identifies this attribute. */ public function set_slug( string $slug ): void { $this->slug = $slug; } /** * Get the title. * * @since 6.2.0 * * @return string */ public function get_title(): string { return $this->title; } /** * Set the title. * * @since 6.2.0 * * @param string $title The title (label) for this attribute. */ public function set_title( string $title ): void { $this->title = $title; } /** * Get the description. * * @since 6.2.0 * * @return string */ public function get_description(): string { return $this->description; } /** * Set the description. * * @since 6.2.0 * * @param string $description The description for this attribute. */ public function set_description( string $description ): void { $this->description = $description; } /** * Get the type. * * @since 6.2.0 * * @return string */ public function get_type(): string { return $this->type; } /** * Set the type. * * @since 6.2.0 * * @param string $type The attribute type. */ public function set_type( string $type ): void { $this->type = $type; } /** * Get the data. * * @since 6.2.0 * * @return array|null */ public function get_data(): ?array { return $this->data; } /** * Set the data. * * @since 6.2.0 * * @param array|null $data The data needed by this attribute. */ public function set_data( ?array $data ): void { $this->data = $data; } /** * Get the attribute definition as an array. * * The main use-case to get the attribute as an array is, * so we can easily share it via API. * * @since 6.2.0 * * @return array */ public function to_array(): array { return array( 'slug' => $this->get_slug(), 'title' => $this->get_title(), 'description' => $this->get_description(), 'type' => $this->get_type(), 'data' => $this->get_data(), ); } }
projects/plugins/crm/src/automation/class-automation-engine.php
<?php /** * Defines Jetpack CRM Automation engine. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation; use Automattic\Jetpack\CRM\Automation\Data_Transformers\Data_Transformer_Base; use Automattic\Jetpack\CRM\Automation\Data_Types\Data_Type; use Automattic\Jetpack\CRM\Automation\Data_Types\Data_Type_Base; /** * Automation Engine. * * @since 6.2.0 */ class Automation_Engine { /** * Instance singleton. * * @since 6.2.0 * @var Automation_Engine */ private static $instance = null; /** * The triggers map name => classname. * * @since 6.2.0 * @var string[] */ private $triggers_map = array(); /** * The steps map name => classname. * * @since 6.2.0 * @var string[] */ private $steps_map = array(); /** * The Automation logger. * * @since 6.2.0 * @var ?Automation_Logger */ private $automation_logger = null; /** * The list of registered workflows. * * @since 6.2.0 * @var Automation_Workflow[] */ private $workflows = array(); /** * An array of supported data types. * * @since 6.2.0 * * @var Data_Type_Base[] */ private $data_types = array(); /** * An array of supported data transformers. * * @since 6.2.0 * * @var Data_Transformer_Base[] */ private $data_transformers = array(); /** * An array of data type that represents support between types. * * @since 6.2.0 * * @var string[] */ public $data_transform_map = array(); /** * Instance singleton object. * * @since 6.2.0 * * @param bool $force Whether to force a new Automation_Engine instance. * @return Automation_Engine The Automation_Engine instance. */ public static function instance( bool $force = false ): Automation_Engine { if ( ! self::$instance || $force ) { self::$instance = new self(); } return self::$instance; } /** * Set the automation logger. * * @since 6.2.0 * * @param Automation_Logger $logger The automation logger. */ public function set_automation_logger( Automation_Logger $logger ) { $this->automation_logger = $logger; } /** * Register data transformer. * * @since 6.2.0 * * @param string $class_name The fully qualified class name for the data transformer. * @return void * * @throws Data_Transformer_Exception Throws an exception if the data transformer class do not look valid. */ public function register_data_transformer( string $class_name ): void { if ( ! class_exists( $class_name ) ) { throw new Data_Transformer_Exception( sprintf( 'Data Transformer class do not exist: %s', $class_name ), Data_Transformer_Exception::CLASS_NOT_FOUND ); } // Make sure that the class implements the Data_Transformer base class, // so we're certain that required logic exists to use the object. if ( ! is_subclass_of( $class_name, Data_Transformer_Base::class ) ) { throw new Data_Transformer_Exception( sprintf( 'Data Transformer class do not extend base class: %s', $class_name ), Data_Transformer_Exception::DO_NOT_EXTEND_BASE ); } if ( isset( $this->data_transformers[ $class_name ] ) ) { throw new Data_Transformer_Exception( sprintf( 'Data Transformer slug already exist: %s', $class_name ), Data_Transformer_Exception::SLUG_EXISTS ); } $this->data_transformers[ $class_name ] = $class_name; if ( ! isset( $this->data_transform_map[ $class_name::get_from() ] ) ) { $this->data_transform_map[ $class_name::get_from() ] = array(); } $this->data_transform_map[ $class_name::get_from() ][ $class_name::get_to() ] = $class_name; } /** * Register a trigger. * * @since 6.2.0 * * @param string $trigger_classname Trigger classname to add to the mapping. * * @throws Automation_Exception Throws an exception if the trigger class does not match the expected conditions. */ public function register_trigger( string $trigger_classname ) { if ( ! class_exists( $trigger_classname ) ) { throw new Automation_Exception( /* Translators: %s is the name of the trigger class that does not exist. */ sprintf( __( 'Trigger class %s does not exist', 'zero-bs-crm' ), $trigger_classname ), Automation_Exception::TRIGGER_CLASS_NOT_FOUND ); } // Check if the trigger implements the interface if ( ! in_array( Trigger::class, class_implements( $trigger_classname ), true ) ) { throw new Automation_Exception( /* Translators: %s is the name of the trigger class that does not implement the Trigger interface. */ sprintf( __( 'Trigger class %s does not implement the Trigger interface', 'zero-bs-crm' ), $trigger_classname ), Automation_Exception::TRIGGER_CLASS_NOT_FOUND ); } // Check if the trigger has proper slug $trigger_slug = $trigger_classname::get_slug(); if ( empty( $trigger_slug ) ) { throw new Automation_Exception( __( 'The trigger must have a non-empty slug', 'zero-bs-crm' ), Automation_Exception::TRIGGER_SLUG_EMPTY ); } if ( array_key_exists( $trigger_slug, $this->triggers_map ) ) { throw new Automation_Exception( /* Translators: %s is the name of the trigger slug that already exists. */ sprintf( __( 'Trigger slug already exists: %s', 'zero-bs-crm' ), $trigger_slug ), Automation_Exception::TRIGGER_SLUG_EXISTS ); } $this->triggers_map[ $trigger_slug ] = $trigger_classname; } /** * Register a step in the automation engine. * * @since 6.2.0 * * @param string $class_name The name of the class in which the step should belong. * * @throws Automation_Exception Throws an exception if the step class does not exist. */ public function register_step( string $class_name ) { if ( ! class_exists( $class_name ) ) { throw new Automation_Exception( /* Translators: %s is the name of the step class that does not exist. */ sprintf( __( 'Step class %s does not exist', 'zero-bs-crm' ), $class_name ), Step_Exception::DO_NOT_EXIST ); } if ( ! in_array( Step::class, class_implements( $class_name ), true ) ) { throw new Automation_Exception( sprintf( 'Step class %s does not implement the Base_Step interface', $class_name ), Step_Exception::DO_NOT_EXTEND_BASE ); } $step_slug = $class_name::get_slug(); $this->steps_map[ $step_slug ] = $class_name; } /** * Get a step class by name. * * @since 6.2.0 * * @param string $step_name The name of the step whose class we will be retrieving. * @return string The name of the step class. * * @throws Automation_Exception Throws an exception if the step class does not exist. */ public function get_step_class( string $step_name ): string { if ( ! isset( $this->steps_map[ $step_name ] ) ) { throw new Automation_Exception( /* Translators: %s is the name of the step class that does not exist. */ sprintf( __( 'Step %s does not exist', 'zero-bs-crm' ), $step_name ), Automation_Exception::STEP_CLASS_NOT_FOUND ); } return $this->steps_map[ $step_name ]; } /** * Add a workflow. * * @since 6.2.0 * * @param Automation_Workflow $workflow The workflow class instance to be added. * @param bool $init_workflow Whether or not to initialize the workflow. * * @throws Workflow_Exception Throws an exception if the workflow is not valid. */ public function add_workflow( Automation_Workflow $workflow, bool $init_workflow = false ) { $workflow->set_engine( $this ); $this->workflows[] = $workflow; if ( $init_workflow ) { $workflow->init_triggers(); } } /** * Build and add a workflow. * * @since 6.2.0 * * @param array $workflow_data The workflow data to be added. * @param bool $init_workflow Whether or not to initialize the workflow. * @return Automation_Workflow The workflow class instance to be added. * * @throws Workflow_Exception Throws an exception if the workflow is not valid. */ public function build_add_workflow( array $workflow_data, bool $init_workflow = false ): Automation_Workflow { $workflow = new Automation_Workflow( $workflow_data ); $this->add_workflow( $workflow, $init_workflow ); return $workflow; } /** * Init automation workflows. * * @since 6.2.0 * * @throws Workflow_Exception Throws an exception if the workflow is not valid. */ public function init_workflows() { /** @var Automation_Workflow $workflow */ foreach ( $this->workflows as $workflow ) { $workflow->init_triggers(); } } /** * Execute workflow. * * @since 6.2.0 * * @param Automation_Workflow $workflow The workflow to be executed. * @param Trigger $trigger The trigger that started the execution process. * @param Data_Type $trigger_data_type The data that was passed along by the trigger. * @return bool * * @throws Automation_Exception Throws exception if an error executing the workflow. * @throws Data_Transformer_Exception Throws exception if an error transforming the data. */ public function execute_workflow( Automation_Workflow $workflow, Trigger $trigger, Data_Type $trigger_data_type ): bool { $this->get_logger()->log( sprintf( 'Trigger activated: %s', $trigger->get_slug() ) ); $this->get_logger()->log( sprintf( 'Executing workflow: %s', $workflow->name ) ); $step_data = $workflow->get_initial_step(); while ( $step_data ) { try { $step_class = $step_data['class_name'] ?? $this->get_step_class( $step_data['slug'] ); if ( ! class_exists( $step_class ) ) { throw new Automation_Exception( /* Translators: %s is the name of the step class that does not exist. */ sprintf( __( 'The step class %s does not exist.', 'zero-bs-crm' ), $step_class ), Automation_Exception::STEP_CLASS_NOT_FOUND ); } /** @var Step $step */ $step = new $step_class( $step_data ); $step_slug = $step->get_slug(); $this->get_logger()->log( '[' . $step->get_slug() . '] Executing step. Type: ' . $step::get_data_type() ); $data_type = $this->maybe_transform_data_type( $trigger_data_type, $step::get_data_type() ); $step->validate_and_execute( $data_type ); //todo: return Step instance instead of array $step_id = $step->get_next_step_id(); $step_data = $workflow->get_step( $step_id ); $this->get_logger()->log( '[' . $step->get_slug() . '] Step executed!' ); if ( ! $step_data ) { $this->get_logger()->log( 'Workflow execution finished: No more steps found.' ); return true; } } catch ( Automation_Exception $automation_exception ) { $this->get_logger()->log( 'Error executing the workflow on step: ' . $step_slug . ' - ' . $automation_exception->getMessage() ); throw $automation_exception; } catch ( Data_Transformer_Exception $transformer_exception ) { $this->get_logger()->log( 'Error executing the workflow on step ' . $step_slug . '. Transformer error: ' . $transformer_exception->getMessage() ); throw $transformer_exception; } } return false; } /** * Maybe transform data type. * * @since 6.2.0 * * @param Data_Type $data_type The current data type. * @param string $new_data_type_class The new data type to transform the data to. * @return Data_Type The transformed data type. * * @throws Data_Transformer_Exception Throws an exception if the data type cannot be transformed. */ protected function maybe_transform_data_type( Data_Type $data_type, string $new_data_type_class ): Data_Type_Base { // Bail early if we do not have to transform the data. if ( $data_type instanceof $new_data_type_class ) { return $data_type; } $data_type_class = get_class( $data_type ); if ( ! isset( $this->data_transform_map[ $data_type_class ][ $new_data_type_class ] ) ) { throw new Data_Transformer_Exception( sprintf( 'Transforming from "%s" to "%s" is not supported', $data_type_class, $new_data_type_class ), Data_Transformer_Exception::TRANSFORM_IS_NOT_SUPPORTED ); } $transformer = new $this->data_transform_map[ $data_type_class ][ $new_data_type_class ](); return $transformer->transform( $data_type ); } /** * Get a step instance. * * @since 6.2.0 * * @param array $step_data The step data hydrate the step with. * @return Step A step class instance. * * @throws Automation_Exception Throws an exception if the step class does not exist. */ public function get_registered_step( array $step_data ): Step { $step_class = $this->get_step_class( $step_data['slug'] ); if ( ! class_exists( $step_class ) ) { throw new Automation_Exception( /* Translators: %s is the name of the step class that does not exist. */ sprintf( __( 'Step class %s does not exist', 'zero-bs-crm' ), $step_class ), Automation_Exception::STEP_CLASS_NOT_FOUND ); } return new $step_class( $step_data ); } /** * Get registered steps. * * @since 6.2.0 * * @return string[] The registered steps. */ public function get_registered_steps(): array { return $this->steps_map; } /** * Get trigger instance. * * @since 6.2.0 * * @param string $trigger_slug The name of the trigger slug with which to retrieve the trigger class. * @return string The name of the trigger class. * * @throws Automation_Exception Throws an exception if the step class does not exist. */ public function get_trigger_class( string $trigger_slug ): string { if ( ! isset( $this->triggers_map[ $trigger_slug ] ) ) { throw new Automation_Exception( /* Translators: %s is the name of the step class that does not exist. */ sprintf( __( 'Trigger %s does not exist', 'zero-bs-crm' ), $trigger_slug ), Automation_Exception::TRIGGER_CLASS_NOT_FOUND ); } return $this->triggers_map[ $trigger_slug ]; } /** * Get Automation logger. * * @since 6.2.0 * * @return Automation_Logger Return an instance of the Automation_Logger class. */ public function get_logger(): Automation_Logger { return $this->automation_logger ?? Automation_Logger::instance(); } /** * Get the registered triggers. * * @since 6.2.0 * * @return string[] The registered triggers. */ public function get_registered_triggers(): array { return $this->triggers_map; } }
projects/plugins/crm/src/automation/class-automation-logger.php
<?php /** * Defines the Jetpack CRM Automation logger. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation; /** * Adds the Automation_Logger class. * * @since 6.2.0 */ class Automation_Logger { /** * Instance singleton. * * @since 6.2.0 * @var Automation_Logger */ private static $instance = null; /** * The log list. * * @var string[] */ private $log = array(); /** * Whether or not the log is set to output. * * @since 6.2.0 * @var bool */ private $output = false; /** * Whether or not the logger is set to be active. * * @since 6.2.0 * @var bool */ private $is_active = true; /** * Initialize the logger. * * @since 6.2.0 * * @param bool $force Force a new instance. * @return Automation_Logger An instance of the Automation_Logger class. */ public static function instance( bool $force = false ): Automation_Logger { if ( ! self::$instance || $force ) { self::$instance = new self(); } return self::$instance; } /** * Set is_active to true to indicate the logger is active. * * @since 6.2.0 */ public function turn_on() { $this->is_active = true; } /** * Set is_active to false to indicate the logger is not active. * * @since 6.2.0 */ public function turn_off() { $this->is_active = false; } /** * Set if output the log or not. * * @since 6.2.0 * * @param bool $output Whether or not the log is set to output. */ public function with_output( bool $output ) { $this->output = $output; } /** * Get log list. * * @since 6.2.0 * * @return string[] The log list. */ public function get_log(): array { return $this->log; } /** * Get formatted log. * * @since 6.2.0 * * @param bool $output Whether or not the log is set to output. * @return string[]|null The formatted log as array. */ public function formatted_log( $output = false ): ?array { if ( $output ) { echo "***** LOGS *****\n"; foreach ( $this->log as $log ) { echo $log[0] . ' - ' . $log[1] . "\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped } echo "***** END LOGS *****\n"; } else { $output = array(); foreach ( $this->log as $log ) { $output[] = $log[0] . ' - ' . $log[1]; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped } return $output; } return null; } /** * Add a log entry. * * @since 6.2.0 * * @param string $message The message to be output in the log. */ public function log( string $message ) { if ( $this->output ) { error_log( $message ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Intention use of error_log. } $log = array( date( 'Y-m-d H:i' ), $message ); // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date -- we want the correct timezone showing in logs. $this->log[] = $log; } /** * Reset the log. * * @since 6.2.0 */ public function reset_log() { $this->log = array(); } }
projects/plugins/crm/src/automation/interface-condition.php
<?php /** * Interface Action. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation; /** * Interface Condition. * * @since 6.2.0 */ interface Condition extends Step { }
projects/plugins/crm/src/automation/class-automation-bootstrap.php
<?php /** * Bootstrap the Jetpack CRM Automation engine. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation; /** * Bootstrap the Jetpack CRM Automation engine. * * @since 6.2.0 */ final class Automation_Bootstrap { /** * The automation engine we want to bootstrap. * * @since 6.2.0 * * @var Automation_Engine */ private $engine; /** * Initialise the automation engine. * * @since 6.2.0 * * @return void */ public function init(): void { $this->engine = Automation_Engine::instance(); $this->register_data_transformers(); $this->register_triggers(); $this->register_conditions(); $this->register_actions(); $this->register_workflows(); } /** * Register data transformers. * * @since 6.2.0 * * @return void */ protected function register_data_transformers(): void { $data_transformers = array( \Automattic\Jetpack\CRM\Automation\Data_Transformers\Data_Transformer_Invoice_To_Contact::class, \Automattic\Jetpack\CRM\Automation\Data_Transformers\Data_Transformer_Entity_To_Tag_List::class, ); /** * Filter list of available data transformers for automation steps. * * This can be used to add and/or remove data transformers allowed in automations. * * @since 6.2.0 * * @param string[] $var A list of data transformer classes. */ $data_transformers = apply_filters( 'jpcrm_automation_data_types', $data_transformers ); foreach ( $data_transformers as $data_transformer ) { try { $this->engine->register_data_transformer( $data_transformer ); } catch ( \Exception $e ) { $this->engine->get_logger()->log( $e->getMessage() ); } } } /** * Register triggers. * * @since 6.2.0 * * @return void */ protected function register_triggers(): void { $triggers = array( \Automattic\Jetpack\CRM\Automation\Triggers\Company_Deleted::class, \Automattic\Jetpack\CRM\Automation\Triggers\Company_Created::class, \Automattic\Jetpack\CRM\Automation\Triggers\Company_Status_Updated::class, \Automattic\Jetpack\CRM\Automation\Triggers\Company_Updated::class, \Automattic\Jetpack\CRM\Automation\Triggers\Contact_Before_Deleted::class, \Automattic\Jetpack\CRM\Automation\Triggers\Contact_Deleted::class, \Automattic\Jetpack\CRM\Automation\Triggers\Contact_Email_Updated::class, \Automattic\Jetpack\CRM\Automation\Triggers\Contact_Created::class, \Automattic\Jetpack\CRM\Automation\Triggers\Contact_Status_Updated::class, \Automattic\Jetpack\CRM\Automation\Triggers\Contact_Updated::class, \Automattic\Jetpack\CRM\Automation\Triggers\Task_Created::class, \Automattic\Jetpack\CRM\Automation\Triggers\Task_Deleted::class, \Automattic\Jetpack\CRM\Automation\Triggers\Task_Updated::class, \Automattic\Jetpack\CRM\Automation\Triggers\Invoice_Deleted::class, \Automattic\Jetpack\CRM\Automation\Triggers\Invoice_Created::class, \Automattic\Jetpack\CRM\Automation\Triggers\Invoice_Status_Updated::class, \Automattic\Jetpack\CRM\Automation\Triggers\Invoice_Updated::class, \Automattic\Jetpack\CRM\Automation\Triggers\Quote_Accepted::class, \Automattic\Jetpack\CRM\Automation\Triggers\Quote_Created::class, \Automattic\Jetpack\CRM\Automation\Triggers\Quote_Deleted::class, \Automattic\Jetpack\CRM\Automation\Triggers\Quote_Status_Updated::class, \Automattic\Jetpack\CRM\Automation\Triggers\Quote_Updated::class, \Automattic\Jetpack\CRM\Automation\Triggers\Transaction_Created::class, \Automattic\Jetpack\CRM\Automation\Triggers\Transaction_Updated::class, \Automattic\Jetpack\CRM\Automation\Triggers\WP_User_Created::class, ); /** * Filter list of available triggers for automations. * * This can be used to add and/or remove triggers allowed in automations. * * @since 6.2.0 * * @param string[] $triggers A list of triggers classes. */ $triggers = apply_filters( 'jpcrm_automation_triggers', $triggers ); foreach ( $triggers as $trigger ) { try { $this->engine->register_trigger( $trigger ); } catch ( \Exception $e ) { $this->engine->get_logger()->log( $e->getMessage() ); } } } /** * Register conditions. * * @since 6.2.0 * * @return void */ protected function register_conditions(): void { $conditions = array( \Automattic\Jetpack\CRM\Automation\Conditions\Contact_Field_Changed::class, \Automattic\Jetpack\CRM\Automation\Conditions\Contact_Transitional_Status::class, \Automattic\Jetpack\CRM\Automation\Conditions\Invoice_Status_Changed::class, \Automattic\Jetpack\CRM\Automation\Conditions\Entity_Tag::class, ); /** * Filter list of available conditions for automations. * * This can be used to add and/or remove condition allowed in automations. * * @since 6.2.0 * * @param string[] $conditions A list of condition classes. */ $conditions = apply_filters( 'jpcrm_automation_conditions', $conditions ); foreach ( $conditions as $condition ) { try { $this->engine->register_step( $condition ); } catch ( \Exception $e ) { $this->engine->get_logger()->log( $e->getMessage() ); } } } /** * Register actions. * * @since 6.2.0 * * @return void */ protected function register_actions(): void { $actions = array( \Automattic\Jetpack\CRM\Automation\Actions\Add_Contact_Log::class, \Automattic\Jetpack\CRM\Automation\Actions\Add_Remove_Contact_Tag::class, \Automattic\Jetpack\CRM\Automation\Actions\Delete_Contact::class, \Automattic\Jetpack\CRM\Automation\Actions\New_Contact::class, \Automattic\Jetpack\CRM\Automation\Actions\Update_Contact::class, \Automattic\Jetpack\CRM\Automation\Actions\Update_Contact_Status::class, \Automattic\Jetpack\CRM\Automation\Actions\Send_Contact_Email::class, ); /** * Filter list of available actions for automations. * * This can be used to add and/or remove actions allowed in automations. * * @since 6.2.0 * * @param string[] $actions A list of actions class names. */ $actions = apply_filters( 'jpcrm_automation_actions', $actions ); foreach ( $actions as $action ) { try { $this->engine->register_step( $action ); } catch ( \Exception $e ) { $this->engine->get_logger()->log( $e->getMessage() ); } } } /** * Register workflows. * * @since 6.2.0 * * @return void */ protected function register_workflows(): void { $workflow_repository = new Workflow\Workflow_Repository(); $workflows = $workflow_repository->find_by( array( 'active' => true, ) ); /** * Filter list of available workflows. * * This can be used to add and/or remove actions allowed in automations. * * @since 6.2.0 * * @param Automation_Workflow[] $workflows A collection of registered workflows. */ $workflows = apply_filters( 'jpcrm_automation_workflows', $workflows ); foreach ( $workflows as $workflow ) { if ( $workflow instanceof Automation_Workflow ) { try { $this->engine->add_workflow( $workflow, true ); } catch ( \Exception $e ) { $this->engine->get_logger()->log( $e->getMessage() ); } } } } }
projects/plugins/crm/src/automation/class-step-exception.php
<?php /** * Defines the Jetpack CRM Automation step exception. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation; /** * Adds the Step_Exception class. * * @since 6.2.0 */ class Step_Exception extends Automation_Exception { /** * Step type not allowed code. * * @since 6.2.0 * @var int */ const STEP_TYPE_NOT_ALLOWED = 10; /** * Step class does not exist code. * * @since 6.2.0 * @var int */ const DO_NOT_EXIST = 11; /** * Step class do not extend base class or interface. * * @since 6.2.0 * @var int */ const DO_NOT_EXTEND_BASE = 12; }
projects/plugins/crm/src/automation/class-base-action.php
<?php /** * Base Action implementation * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation; /** * Base Action Step. * * @since 6.2.0 * {@inheritDoc} */ abstract class Base_Action extends Base_Step implements Action { }
projects/plugins/crm/src/automation/class-automation-exception.php
<?php /** * Defines Jetpack CRM Automation exceptions. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation; /** * Adds the Automation_Exception class. * * @since 6.2.0 */ class Automation_Exception extends \Exception { /** * Step class not found code. * * @since 6.2.0 * @var int */ const STEP_CLASS_NOT_FOUND = 10; /** * Step slug exists code. * * @since 6.2.0 * @var int */ const STEP_SLUG_EXISTS = 11; /** * Step slug empty code. * * @since 6.2.0 * @var int */ const STEP_SLUG_EMPTY = 12; /** * Trigger class not found code. * * @since 6.2.0 * @var int */ const TRIGGER_CLASS_NOT_FOUND = 20; /** * Trigger slug exists code. * * @since 6.2.0 * @var int */ const TRIGGER_SLUG_EXISTS = 21; /** * Trigger slug empty code. * * @since 6.2.0 * @var int */ const TRIGGER_SLUG_EMPTY = 22; /** * Condition invalid operator code. * * @since 6.2.0 * @var int */ const CONDITION_INVALID_OPERATOR = 30; /** * Condition operator not implemented code. * * @since 6.2.0 * @var int */ const CONDITION_OPERATOR_NOT_IMPLEMENTED = 31; /** * General error code. * * @since 6.2.0 * @var int */ const GENERAL_ERROR = 999; /** * Automation_Exception constructor. * * @since 6.2.0 * * @param string $message Allows an exception message to be passed. * @param int $code The error code to be included in the exception output. */ public function __construct( $message = 'Automation Exception', $code = self::GENERAL_ERROR ) { // phpcs:ignore Generic.CodeAnalysis.UselessOverridingMethod.Found parent::__construct( $message, $code ); } }
projects/plugins/crm/src/automation/interface-trigger.php
<?php /** * Interface Trigger * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation; /** * Interface Trigger. * * @since 6.2.0 */ interface Trigger { /** * Get the slug name of the trigger. * * @since 6.2.0 * * @return string The slug name of the trigger. */ public static function get_slug(): string; /** * Get the title of the trigger. * * @since 6.2.0 * * @return string|null The title of the trigger. */ public static function get_title(): ?string; /** * Get the description of the trigger. * * @since 6.2.0 * * @return string|null The description of the trigger. */ public static function get_description(): ?string; /** * Get the category of the trigger. * * @since 6.2.0 * * @return string|null The category of the trigger. */ public static function get_category(): ?string; /** * Get the trigger's data type. * * @since 6.2.0 * * @return string the trigger's data type. */ public static function get_data_type(): string; /** * Execute the workflow. * * @since 6.2.0 * * @param mixed|null $data The data to pass to the workflow. * @param mixed|null $previous_data The previous data to pass to the workflow. */ public function execute_workflow( $data = null, $previous_data = null ); /** * Set the workflow to execute by this trigger. * * @since 6.2.0 * * @param Automation_Workflow $workflow The workflow to execute by this trigger. */ public function set_workflow( Automation_Workflow $workflow ); /** * Init the trigger. * * @since 6.2.0 * * @param Automation_Workflow $workflow The workflow to which the trigger belongs. */ public function init( Automation_Workflow $workflow ); /** * Get the trigger as an array. * * The main use-case to get the trigger as an array is to prepare * the items for an API response. * * @since 6.2.0 * * @return array The trigger as an array. */ public static function to_array(): array; }
projects/plugins/crm/src/automation/class-data-transformer-exception.php
<?php /** * Jetpack CRM Automation data transformer exception. * * @package automattic/jetpack-crm */ namespace Automattic\Jetpack\CRM\Automation; /** * Adds a Data_Transformer specific exception. * * @since 6.2.0 */ class Data_Transformer_Exception extends \Exception { /** * Error code for when the class doesn't exist. * * @since 6.2.0 * * @var int */ const CLASS_NOT_FOUND = 10; /** * Error code for when a transformer is passed, but doesn't extend the base class. * * @since 6.2.0 * * @var int */ const DO_NOT_EXTEND_BASE = 11; /** * Error code for when a slug is already being used. * * @since 6.2.0 * * @var int */ const SLUG_EXISTS = 12; /** * Error code for when an object doesn't have a related ID to map to. * * @since 6.2.0 * * @var int */ const MISSING_LINK = 20; /** * Error code for when two objects cannot be mixed by the system (yet). * * @since 6.2.0 * * @var int */ const TRANSFORM_IS_NOT_SUPPORTED = 30; }
projects/plugins/crm/src/automation/class-workflow-exception.php
<?php /** * Defines the Jetpack CRM Automation workflow exception. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation; /** * Adds the Workflow_Exception class. * * @since 6.2.0 */ class Workflow_Exception extends \Exception { /** * Invalid Workflow error code. * * @since 6.2.0 * @var int */ const INVALID_WORKFLOW = 10; /** * Workflow require a trigger error code. * * @since 6.2.0 * @var int */ const WORKFLOW_REQUIRE_A_TRIGGER = 11; /** * Workflow require an initial step error code. * * @since 6.2.0 * @var int */ const WORKFLOW_REQUIRE_A_INITIAL_STEP = 12; /** * Error initializing trigger error code. * * @since 6.2.0 * @var int */ const ERROR_INITIALIZING_TRIGGER = 13; /** * Missing engine instance. * * This exception should be thrown if a workflow is attempted to be executed without an engine instance. * * @since 6.2.0 * @var int */ const MISSING_ENGINE_INSTANCE = 14; /** * Failed to insert the workflow. * * This exception should be thrown in the context of CRUD action(s). * * @since 6.2.0 * @var int */ const FAILED_TO_INSERT = 50; /** * Failed to update the workflow. * * This exception should be thrown in the context of CRUD action(s). * * @since 6.2.0 * @var int */ const FAILED_TO_UPDATE = 51; /** * Failed to delete the workflow. * * This exception should be thrown in the context of CRUD action(s). * * @since 6.2.0 * @var int */ const FAILED_TO_DELETE = 52; }
projects/plugins/crm/src/automation/data-transformers/class-data-transformer-entity-to-tag-list.php
<?php /** * CRM Entity to CRM Tag List Transformer class. * * @package automattic/jetpack-crm */ namespace Automattic\Jetpack\CRM\Automation\Data_Transformers; use Automattic\Jetpack\CRM\Automation\Data_Transformer_Exception; use Automattic\Jetpack\CRM\Automation\Data_Types\Data_Type; use Automattic\Jetpack\CRM\Automation\Data_Types\Entity_Data; use Automattic\Jetpack\CRM\Automation\Data_Types\Tag_List_Data; /** * CRM Entity to CRM Tag List Transformer class. * * @since 6.2.0 */ class Data_Transformer_Entity_To_Tag_List extends Data_Transformer_Base { /** * {@inheritDoc} */ public static function get_slug(): string { return 'entity_to_tag_list'; } /** * {@inheritDoc} */ public static function get_from(): string { return Entity_Data::class; } /** * {@inheritDoc} */ public static function get_to(): string { return Tag_List_Data::class; } /** * Get the tags from an CRM entity. * * @since 6.2.0 * * @param Data_Type $data The CRM entity data type we want to get the tags from. * @return array The CRM entity tags as an array. */ public static function get_tags( Data_Type $data ): array { return $data->get_tags(); } /** * Transform CRM entity entity to a list of tags. * * @since 6.2.0 * * @param Data_Type $data The CRM entity data type we want to transform. * @return Data_Type Return the Tag_Data of the CRM entity. * * @throws Data_Transformer_Exception If the CRM entity is not linked to a tag. */ public function transform( Data_Type $data ): Data_Type { $this->validate_from_type( $data ); $tags = $this->get_tags( $data ); return new Tag_List_Data( $tags ); } }
projects/plugins/crm/src/automation/data-transformers/class-data-transformer-invoice-to-contact.php
<?php /** * CRM Invoice to CRM Contact Transformer class. * * @package automattic/jetpack-crm */ namespace Automattic\Jetpack\CRM\Automation\Data_Transformers; use Automattic\Jetpack\CRM\Automation\Data_Transformer_Exception; use Automattic\Jetpack\CRM\Automation\Data_Types\Contact_Data; use Automattic\Jetpack\CRM\Automation\Data_Types\Data_Type; use Automattic\Jetpack\CRM\Automation\Data_Types\Invoice_Data; use Automattic\Jetpack\CRM\Entities\Factories\Contact_Factory; /** * CRM Invoice to CRM Contact Transformer class. * * @since 6.2.0 */ class Data_Transformer_Invoice_To_Contact extends Data_Transformer_Base { /** * {@inheritDoc} */ public static function get_slug(): string { return 'invoice_to_contact'; } /** * {@inheritDoc} */ public static function get_from(): string { return Invoice_Data::class; } /** * {@inheritDoc} */ public static function get_to(): string { return Contact_Data::class; } /** * Transform invoice entity to a contact. * * @since 6.2.0 * * @param Data_Type $data The invoice data type we want to transform. * @return Data_Type Return the Data_Type_Contact of the invoice owner. * * @throws Data_Transformer_Exception If the invoice is not linked to a contact. */ public function transform( Data_Type $data ): Data_Type { global $zbs; $this->validate_from_type( $data ); /* @todo We should really be using getInvoiceContact() but it's broken. */ $contact_id = $zbs->DAL->invoices->getInvoiceContactID( $data->get_id() ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase $contact_data = $zbs->DAL->contacts->getContact( $contact_id ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase if ( ! $contact_data ) { throw new Data_Transformer_Exception( 'Invoice is not linked to a contact.', Data_Transformer_Exception::MISSING_LINK ); } $contact = Contact_Factory::create( $contact_data ); return ( new Contact_Data( $contact ) ); } }
projects/plugins/crm/src/automation/data-transformers/class-data-transformer-base.php
<?php /** * Base Data Transformer class. * * @package automattic/jetpack-crm */ namespace Automattic\Jetpack\CRM\Automation\Data_Transformers; use Automattic\Jetpack\CRM\Automation\Data_Transformer_Exception; use Automattic\Jetpack\CRM\Automation\Data_Type_Exception; use Automattic\Jetpack\CRM\Automation\Data_Types\Data_Type; /** * Base Data Transformer class. * * @since 6.2.0 */ abstract class Data_Transformer_Base { /** * Validate the data type we transform from. * * @param Data_Type $data The data type we want to transform. * @return bool Return true if the data type is valid. * * @throws Data_Transformer_Exception Throw if the data type is not valid. */ protected function validate_from_type( Data_Type $data ): bool { $from_data_type = $this->get_from(); if ( ! $data instanceof $from_data_type ) { throw new Data_Transformer_Exception( 'Invoice data type is not valid.', Data_Type_Exception::INVALID_DATA ); } return true; } /** * Get the slug of the data transformer. * * This is meant to be unique and is used to make it easier for third * parties to identify the data type in filters. * * Example: 'invoice_to_contact', 'contact_to_woo_customer', etc. * * @since 6.2.0 * * @return string The slug of the data transformer. */ abstract public static function get_slug(): string; /** * Get the data type class we transform from. * * @since 6.2.0 * * @return string The data type class we transform from. */ abstract public static function get_from(): string; /** * Get the data type class we transform to. * * @since 6.2.0 * * @return string The data type class we transform to. */ abstract public static function get_to(): string; /** * Transform the data type into another type. * * This method should transform the data to the "to" data type. * * @since 6.2.0 * * @param Data_Type $data The data type we want to transform. * @return Data_Type Return a transformed data type. */ abstract public function transform( Data_Type $data ): Data_Type; }
projects/plugins/crm/src/automation/data-types/interface-entity-data.php
<?php /** * Entity Data Interface. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation\Data_Types; /** * Entity Data Interface. * * This interface is to be able to identify the JPCRM entities Data_Type classes. * * @since 6.2.0 */ interface Entity_Data { /** * Get the tags from the entity instance. * * @since 6.2.0 * * @return array The tags from the entity instance as an array. */ public function get_tags(): array; }
projects/plugins/crm/src/automation/data-types/class-tag-list-data.php
<?php /** * Tag_List Data Type. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation\Data_Types; use Automattic\Jetpack\CRM\Automation\Data_Type_Exception; /** * Tag_List Data Type. * * @since 6.2.0 */ class Tag_List_Data extends Data_Type_Base { /** * Validate the data. * * This method is meant to validate if the data has the expected inheritance * or structure and will be used to throw a fatal error if not. * * @since 6.2.0 * * @param mixed $data The data to validate. * @return bool Whether the data is valid. * @throws Data_Type_Exception If the tag list is not valid. */ public function validate_data( $data ): bool { if ( ! is_array( $data ) ) { throw new Data_Type_Exception( sprintf( 'Invalid tag list' ), Data_Type_Exception::INVALID_DATA ); } return true; } }
projects/plugins/crm/src/automation/data-types/class-task-data.php
<?php /** * Event Data Type. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation\Data_Types; use Automattic\Jetpack\CRM\Entities\Task; /** * Event Data Type. * * @since 6.2.0 */ class Task_Data extends Data_Type_Base implements Entity_Data { /** * Validate the data. * * This method is meant to validate if the data has the expected inheritance * or structure and will be used to throw a fatal error if not. * * @since 6.2.0 * * @param mixed $data The data to validate. * @return bool Whether the data is valid. */ public function validate_data( $data ): bool { return $data instanceof Task; } /** * {@inheritDoc} */ public function get_tags(): array { global $zbs; return $zbs->DAL->getTagsForObjID( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase array( 'objtypeid' => ZBS_TYPE_TASK, $this->get_data()->id, ) ); } }
projects/plugins/crm/src/automation/data-types/interface-data-type.php
<?php /** * Data Type Interface class. * * @package automattic/jetpack-crm */ namespace Automattic\Jetpack\CRM\Automation\Data_Types; /** * Data Type Interface. * * @since 6.2.0 */ interface Data_Type { /** * Validate the data. * * This method is meant to validate if the data has the expected inheritance * or structure and will be used to throw a fatal error if not. * * @since 6.2.0 * * @param mixed $data The data to validate. * @return bool Whether the data is valid. */ public function validate_data( $data ): bool; /** * Get the data. * * We do not know what shape this takes. It could be a class, object, * or array. * * @since 6.2.0 * * @return mixed */ public function get_data(); /** * Get the previous data, if any. * * We do not know what shape this takes. It could be a class, object, * or array. * * @since 6.2.0 * * @return mixed */ public function get_previous_data(); }
projects/plugins/crm/src/automation/data-types/class-tag-data.php
<?php /** * Tag Data Type. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation\Data_Types; use Automattic\Jetpack\CRM\Entities\Tag; /** * Tag Data Type. * * @since 6.2.0 */ class Tag_Data extends Data_Type_Base { /** * Validate the data. * * This method is meant to validate if the data has the expected inheritance * or structure and will be used to throw a fatal error if not. * * @since 6.2.0 * * @param mixed $data The data to validate. * @return bool Whether the data is valid. */ public function validate_data( $data ): bool { return $data instanceof Tag; } }
projects/plugins/crm/src/automation/data-types/class-contact-data.php
<?php /** * Contact Data Type. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation\Data_Types; use Automattic\Jetpack\CRM\Entities\Contact; /** * Contact Data Type. * * @since 6.2.0 */ class Contact_Data extends Data_Type_Base implements Entity_Data { /** * Validate the data. * * This method is meant to validate if the data has the expected inheritance * or structure and will be used to throw a fatal error if not. * * @since 6.2.0 * * @param mixed $data The data to validate. * @return bool Whether the data is valid. */ public function validate_data( $data ): bool { return $data instanceof Contact; } /** * {@inheritDoc} */ public function get_tags(): array { global $zbs; return $zbs->DAL->contacts->getContactTags( $this->get_data()->id ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase } }
projects/plugins/crm/src/automation/data-types/class-transaction-data.php
<?php /** * Transaction Data Type. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation\Data_Types; use Automattic\Jetpack\CRM\Entities\Transaction; /** * Transaction Data Type. * * @since 6.2.0 */ class Transaction_Data extends Data_Type_Base implements Entity_Data { /** * Validate the data. * * This method is meant to validate if the data has the expected inheritance * or structure and will be used to throw a fatal error if not. * * @since 6.2.0 * * @param mixed $data The data to validate. * @return bool Whether the data is valid. */ public function validate_data( $data ): bool { return $data instanceof Transaction; } /** * {@inheritDoc} */ public function get_tags(): array { global $zbs; return $zbs->DAL->getTagsForObjID( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase array( 'objtypeid' => ZBS_TYPE_TRANSACTION, $this->get_data()->id, ) ); } }
projects/plugins/crm/src/automation/data-types/class-company-data.php
<?php /** * Company Data Type. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation\Data_Types; use Automattic\Jetpack\CRM\Entities\Company; /** * Company Data Type. * * @since 6.2.0 */ class Company_Data extends Data_Type_Base implements Entity_Data { /** * Validate the data. * * This method is meant to validate if the data has the expected inheritance * or structure and will be used to throw a fatal error if not. * * @since 6.2.0 * * @param mixed $data The data to validate. * @return bool Whether the data is valid. */ public function validate_data( $data ): bool { return $data instanceof Company; } /** * {@inheritDoc} */ public function get_tags(): array { global $zbs; return $zbs->DAL->companies->getCompanyTags( $this->get_data()->id ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase } }
projects/plugins/crm/src/automation/data-types/class-invoice-data.php
<?php /** * Invoice Data Type. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation\Data_Types; use Automattic\Jetpack\CRM\Entities\Invoice; /** * Invoice Data Type. * * @since 6.2.0 */ class Invoice_Data extends Data_Type_Base implements Entity_Data { /** * Validate the data. * * This method is meant to validate if the data has the expected inheritance * or structure and will be used to throw a fatal error if not. * * @since 6.2.0 * * @param mixed $data The data to validate. * @return bool Whether the data is valid. */ public function validate_data( $data ): bool { return $data instanceof Invoice; } /** * {@inheritDoc} */ public function get_tags(): array { global $zbs; return $zbs->DAL->getTagsForObjID( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase array( 'objtypeid' => ZBS_TYPE_INVOICE, $this->get_data()->id, ) ); } }
projects/plugins/crm/src/automation/data-types/class-data-type-base.php
<?php /** * Base Data Type class. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation\Data_Types; use Automattic\Jetpack\CRM\Automation\Data_Type_Exception; /** * Abstract Data Type base class. * * @since 6.2.0 */ abstract class Data_Type_Base implements Data_Type { /** * The data that represents an instance of the data type. * * This could be of any shape: a class, object, array, or a simple value. * * @since 6.2.0 * @var mixed */ protected $data = null; /** * The previous data that represents an instance of the data type. * This could be of any shape: a class, object, array, or a simple value. * * @since 6.2.0 * @var mixed */ protected $previous_data = null; /** * Constructor. * * @since 6.2.0 * * @param mixed $data A data that represents the data type. * @param mixed $previous_data A data that represents the previous data. * * @throws Data_Type_Exception If the data do not look valid. */ public function __construct( $data, $previous_data = null ) { if ( ! $this->validate_data( $data ) || ( $previous_data !== null && ! $this->validate_data( $previous_data ) ) ) { throw new Data_Type_Exception( sprintf( 'Invalid data for data type: %s', static::class ), Data_Type_Exception::INVALID_DATA ); } $this->data = $data; $this->previous_data = $previous_data; } /** * Validate the data. * * This method is meant to validate if the data has the expected inheritance * or structure and will be used to throw a fatal error if not. * * @since 6.2.0 * * @param mixed $data The data to validate. * @return bool Whether the data is valid. */ abstract public function validate_data( $data ): bool; /** * Get the data. * * We do not know what shape this takes. It could be a class, object, * or array. We leave it up to the data type to decide. * * @since 6.2.0 * * @return mixed */ public function get_data() { return $this->data; } /** * Get the previous data. * * We do not know what shape this takes. It could be a class, object, * or array. We leave it up to the data type to decide. * * @since 6.2.0 * * @return mixed */ public function get_previous_data() { return $this->previous_data; } }
projects/plugins/crm/src/automation/data-types/class-quote-data.php
<?php /** * Quote Data Type. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation\Data_Types; use Automattic\Jetpack\CRM\Entities\Quote; /** * Quote Data Type. * * @since 6.2.0 */ class Quote_Data extends Data_Type_Base implements Entity_Data { /** * Validate the data. * * This method is meant to validate if the data has the expected inheritance * or structure and will be used to throw a fatal error if not. * * @since 6.2.0 * * @param mixed $data The data to validate. * @return bool Whether the data is valid. */ public function validate_data( $data ): bool { return $data instanceof Quote; } /** * {@inheritDoc} */ public function get_tags(): array { global $zbs; return $zbs->DAL->getTagsForObjID( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase array( 'objtypeid' => ZBS_TYPE_QUOTE, $this->get_data()->id, ) ); } }
projects/plugins/crm/src/automation/data-types/class-wp-user-data.php
<?php /** * WP_User Data Type. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation\Data_Types; /** * WP_User Data Type. * * @since 6.2.0 */ class WP_User_Data extends Data_Type_Base { /** * Validate the data. * * This method is meant to validate if the data has the expected inheritance * or structure and will be used to throw a fatal error if not. * * @since 6.2.0 * * @param mixed $data The data to validate. * @return bool Whether the data is valid. */ public function validate_data( $data ): bool { return $data instanceof \WP_User; } }
projects/plugins/crm/src/automation/commons/triggers/tasks/class-task-deleted.php
<?php /** * Jetpack CRM Automation Task_Deleted trigger. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation\Triggers; use Automattic\Jetpack\CRM\Automation\Base_Trigger; use Automattic\Jetpack\CRM\Automation\Data_Types\Task_Data; /** * Adds the Task_Deleted class. * * @since 6.2.0 */ class Task_Deleted extends Base_Trigger { /** * Get the slug name of the trigger. * * @since 6.2.0 * * @return string The slug name of the trigger. */ public static function get_slug(): string { return 'jpcrm/task_deleted'; } /** * Get the title of the trigger. * * @since 6.2.0 * * @return string The title of the trigger. */ public static function get_title(): string { return __( 'Task Deleted', 'zero-bs-crm' ); } /** * Get the description of the trigger. * * @since 6.2.0 * * @return string The description of the trigger. */ public static function get_description(): string { return __( 'Triggered when a task is deleted', 'zero-bs-crm' ); } /** * Get the category of the trigger. * * @since 6.2.0 * * @return string The category of the trigger. */ public static function get_category(): string { return __( 'Task', 'zero-bs-crm' ); } /** * Get the date type. * * @return string The type of the step */ public static function get_data_type(): string { return Task_Data::class; } /** * Listen to this trigger's target event. * * @since 6.2.0 * * @return void */ protected function listen_to_event(): void { $this->listen_to_wp_action( 'jpcrm_task_delete' ); } }
projects/plugins/crm/src/automation/commons/triggers/tasks/class-task-updated.php
<?php /** * Jetpack CRM Automation Task_Updated trigger. * * @package automattic/jetpack-crm */ namespace Automattic\Jetpack\CRM\Automation\Triggers; use Automattic\Jetpack\CRM\Automation\Base_Trigger; use Automattic\Jetpack\CRM\Automation\Data_Types\Task_Data; /** * Adds the Task_Updated class. * * @since 6.2.0 */ class Task_Updated extends Base_Trigger { /** * Get the slug name of the trigger. * * @since 6.2.0 * * @return string The trigger slug. */ public static function get_slug(): string { return 'jpcrm/task_updated'; } /** * Get the title of the trigger. * * @since 6.2.0 * * @return string The title. */ public static function get_title(): string { return __( 'Task Updated', 'zero-bs-crm' ); } /** * Get the description of the trigger. * * @since 6.2.0 * * @return string The description. */ public static function get_description(): string { return __( 'Triggered when a task is updated', 'zero-bs-crm' ); } /** * Get the category of the trigger. * * @since 6.2.0 * * @return string The category. */ public static function get_category(): string { return __( 'Task', 'zero-bs-crm' ); } /** * Get the date type. * * @return string The type of the step */ public static function get_data_type(): string { return Task_Data::class; } /** * Listen to this trigger's target event. * * @since 6.2.0 * * @return void */ protected function listen_to_event(): void { $this->listen_to_wp_action( 'jpcrm_task_updated' ); } }
projects/plugins/crm/src/automation/commons/triggers/tasks/class-task-created.php
<?php /** * Jetpack CRM Automation Task_Created trigger. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation\Triggers; use Automattic\Jetpack\CRM\Automation\Base_Trigger; use Automattic\Jetpack\CRM\Automation\Data_Types\Task_Data; /** * Adds the Task_Created class. * * @since 6.2.0 */ class Task_Created extends Base_Trigger { /** * Get the slug name of the trigger. * * @since 6.2.0 * * @return string The slug name of the trigger. */ public static function get_slug(): string { return 'jpcrm/task_created'; } /** * Get the title of the trigger. * * @since 6.2.0 * * @return string The title of the trigger. */ public static function get_title(): string { return __( 'New Task', 'zero-bs-crm' ); } /** * Get the description of the trigger. * * @since 6.2.0 * * @return string The description of the trigger. */ public static function get_description(): string { return __( 'Triggered when a new task status is added', 'zero-bs-crm' ); } /** * Get the category of the trigger. * * @since 6.2.0 * * @return string The category of the trigger. */ public static function get_category(): string { return __( 'Task', 'zero-bs-crm' ); } /** * Get the date type. * * @return string The type of the step. */ public static function get_data_type(): string { return Task_Data::class; } /** * Listen to this trigger's target event. * * @since 6.2.0 * @return void */ protected function listen_to_event(): void { $this->listen_to_wp_action( 'jpcrm_task_created' ); } }
projects/plugins/crm/src/automation/commons/triggers/invoices/class-invoice-updated.php
<?php /** * Jetpack CRM Automation Invoice_Updated trigger. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation\Triggers; use Automattic\Jetpack\CRM\Automation\Base_Trigger; use Automattic\Jetpack\CRM\Automation\Data_Types\Invoice_Data; /** * Adds the Invoice_Updated class. * * @since 6.2.0 */ class Invoice_Updated extends Base_Trigger { /** * Get the slug name of the trigger. * * @since 6.2.0 * * @return string The slug name of the trigger. */ public static function get_slug(): string { return 'jpcrm/invoice_updated'; } /** * Get the title of the trigger. * * @since 6.2.0 * * @return string|null The title of the trigger. */ public static function get_title(): ?string { return __( 'Invoice Updated', 'zero-bs-crm' ); } /** * Get the description of the trigger. * * @since 6.2.0 * * @return string|null The description of the trigger. */ public static function get_description(): ?string { return __( 'Triggered when an invoice is updated', 'zero-bs-crm' ); } /** * Get the category of the trigger. * * @since 6.2.0 * * @return string|null The category of the trigger. */ public static function get_category(): ?string { return __( 'Invoice', 'zero-bs-crm' ); } /** * Get the date type. * * @return string The type of the step */ public static function get_data_type(): string { return Invoice_Data::class; } /** * Listen to the desired event. * * @since 6.2.0 * * @return void */ protected function listen_to_event(): void { $this->listen_to_wp_action( 'jpcrm_invoice_updated' ); } }
projects/plugins/crm/src/automation/commons/triggers/invoices/class-invoice-created.php
<?php /** * Jetpack CRM Automation Invoice_Created trigger. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation\Triggers; use Automattic\Jetpack\CRM\Automation\Base_Trigger; use Automattic\Jetpack\CRM\Automation\Data_Types\Invoice_Data; /** * Adds the Invoice_Created class. * * @since 6.2.0 */ class Invoice_Created extends Base_Trigger { /** * Get the slug name of the trigger. * * @since 6.2.0 * * @return string */ public static function get_slug(): string { return 'jpcrm/invoice_created'; } /** * Get the title of the trigger. * * @since 6.2.0 * * @return string|null The title of the trigger. */ public static function get_title(): ?string { return __( 'New Invoice', 'zero-bs-crm' ); } /** * Get the description of the trigger. * * @since 6.2.0 * * @return string|null The description of the trigger. */ public static function get_description(): ?string { return __( 'Triggered when a new invoice status is added', 'zero-bs-crm' ); } /** * Get the category of the trigger. * * @since 6.2.0 * * @return string|null The category of the trigger. */ public static function get_category(): ?string { return __( 'Invoice', 'zero-bs-crm' ); } /** * Get the date type. * * @return string The type of the step */ public static function get_data_type(): string { return Invoice_Data::class; } /** * Listen to the desired event. * * @since 6.2.0 * * @return void */ protected function listen_to_event(): void { $this->listen_to_wp_action( 'jpcrm_invoice_created' ); } }
projects/plugins/crm/src/automation/commons/triggers/invoices/class-invoice-status-updated.php
<?php /** * Jetpack CRM Automation Invoice_Status_Updated trigger. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation\Triggers; use Automattic\Jetpack\CRM\Automation\Base_Trigger; use Automattic\Jetpack\CRM\Automation\Data_Types\Invoice_Data; /** * Adds the Invoice_Status_Updated class. * * @since 6.2.0 */ class Invoice_Status_Updated extends Base_Trigger { /** * Get the slug name of the trigger. * * @since 6.2.0 * * @return string The slug name of the trigger. */ public static function get_slug(): string { return 'jpcrm/invoice_status_updated'; } /** * Get the title of the trigger. * * @since 6.2.0 * * @return string|null The title of the trigger. */ public static function get_title(): ?string { return __( 'Invoice Status Updated', 'zero-bs-crm' ); } /** * Get the description of the trigger. * * @since 6.2.0 * * @return string|null The description of the trigger. */ public static function get_description(): ?string { return __( 'Triggered when an invoice status is updated', 'zero-bs-crm' ); } /** * Get the category of the trigger. * * @since 6.2.0 * * @return string|null The category of the trigger. */ public static function get_category(): ?string { return __( 'Invoice', 'zero-bs-crm' ); } /** * Get the date type. * * @return string The type of the step */ public static function get_data_type(): string { return Invoice_Data::class; } /** * Listen to the desired event. * * @since 6.2.0 * * @return void */ protected function listen_to_event(): void { $this->listen_to_wp_action( 'jpcrm_invoice_status_updated' ); } }
projects/plugins/crm/src/automation/commons/triggers/invoices/class-invoice-deleted.php
<?php /** * Jetpack CRM Automation Invoice_Deleted trigger. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation\Triggers; use Automattic\Jetpack\CRM\Automation\Base_Trigger; use Automattic\Jetpack\CRM\Automation\Data_Types\Invoice_Data; /** * Adds the Invoice_Deleted class. * * @since 6.2.0 */ class Invoice_Deleted extends Base_Trigger { /** * Get the slug name of the trigger. * * @since 6.2.0 * * @return string The slug name of the trigger. */ public static function get_slug(): string { return 'jpcrm/invoice_delete'; } /** * Get the title of the trigger. * * @since 6.2.0 * * @return string|null The title of the trigger. */ public static function get_title(): ?string { return __( 'Delete Invoice', 'zero-bs-crm' ); } /** * Get the description of the trigger. * * @since 6.2.0 * * @return string|null The description of the trigger. */ public static function get_description(): ?string { return __( 'Triggered when an invoice is deleted', 'zero-bs-crm' ); } /** * Get the category of the trigger. * * @since 6.2.0 * * @return string|null The category of the trigger. */ public static function get_category(): ?string { return __( 'Invoice', 'zero-bs-crm' ); } /** * Get the date type. * * @return string The type of the step */ public static function get_data_type(): string { return Invoice_Data::class; } /** * Listen to the desired event. * * @since 6.2.0 * * @return void */ protected function listen_to_event(): void { $this->listen_to_wp_action( 'jpcrm_invoice_deleted' ); } }
projects/plugins/crm/src/automation/commons/triggers/wordpress/class-wp-user-created.php
<?php /** * Jetpack CRM Automation WP_User_Created trigger. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation\Triggers; use Automattic\Jetpack\CRM\Automation\Automation_Workflow; use Automattic\Jetpack\CRM\Automation\Base_Trigger; use Automattic\Jetpack\CRM\Automation\Data_Types\WP_User_Data; /** * Adds the WP_User_Created class. * * @since 6.2.0 */ class WP_User_Created extends Base_Trigger { /** * The Automation workflow object. * * @since 6.2.0 * @var Automation_Workflow */ protected $workflow; /** * Get the slug name of the trigger. * * @since 6.2.0 * * @return string The slug name of the trigger. */ public static function get_slug(): string { return 'jpcrm/wp_user_created'; } /** * Get the title of the trigger. * * @since 6.2.0 * * @return string|null The title of the trigger. */ public static function get_title(): string { return __( 'New WP User', 'zero-bs-crm' ); } /** * Get the description of the trigger. * * @since 6.2.0 * * @return string|null The description of the trigger. */ public static function get_description(): string { return __( 'Triggered when a new WP user is created', 'zero-bs-crm' ); } /** * Get the category of the trigger. * * @since 6.2.0 * * @return string|null The category of the trigger. */ public static function get_category(): string { return __( 'WP User', 'zero-bs-crm' ); } /** * Get the data type. * * @return string The type of the step */ public static function get_data_type(): string { return WP_User_Data::class; } /** * Listen to the desired event. * * @since 6.2.0 */ protected function listen_to_event(): void { add_action( 'user_register', function ( $user_id ) { $wp_user = new \WP_User( $user_id ); $this->execute_workflow( $wp_user ); } ); } }
projects/plugins/crm/src/automation/commons/triggers/quotes/class-quote-created.php
<?php /** * Jetpack CRM Automation Quote_Created trigger. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation\Triggers; use Automattic\Jetpack\CRM\Automation\Base_Trigger; use Automattic\Jetpack\CRM\Automation\Data_Types\Quote_Data; /** * Adds the Quote_Created class. * * @since 6.2.0 */ class Quote_Created extends Base_Trigger { /** * Get the slug name of the trigger. * * @since 6.2.0 * * @return string The slug name of the trigger. */ public static function get_slug(): string { return 'jpcrm/quote_created'; } /** * Get the title of the trigger. * * @since 6.2.0 * * @return string|null The title of the trigger. */ public static function get_title(): ?string { return __( 'New Quote', 'zero-bs-crm' ); } /** * Get the description of the trigger. * * @since 6.2.0 * * @return string|null The description of the trigger. */ public static function get_description(): ?string { return __( 'Triggered when a new quote status is added', 'zero-bs-crm' ); } /** * Get the category of the trigger. * * @since 6.2.0 * * @return string|null The category of the trigger. */ public static function get_category(): ?string { return __( 'Quote', 'zero-bs-crm' ); } /** * Get the date type. * * @return string The type of the step */ public static function get_data_type(): string { return Quote_Data::class; } /** * Listen to this trigger's target event. * * @since 6.2.0 * * @return void */ protected function listen_to_event(): void { $this->listen_to_wp_action( 'jpcrm_quote_created' ); } }
projects/plugins/crm/src/automation/commons/triggers/quotes/class-quote-updated.php
<?php /** * Jetpack CRM Automation Quote_Updated trigger. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation\Triggers; use Automattic\Jetpack\CRM\Automation\Base_Trigger; use Automattic\Jetpack\CRM\Automation\Data_Types\Quote_Data; /** * Adds the Quote_Updated class. * * @since 6.2.0 */ class Quote_Updated extends Base_Trigger { /** * Get the slug name of the trigger * * @since 6.2.0 * * @return string The slug name of the trigger. */ public static function get_slug(): string { return 'jpcrm/quote_updated'; } /** * Get the title of the trigger. * * @since 6.2.0 * * @return string|null The title of the trigger. */ public static function get_title(): ?string { return __( 'Quote Updated', 'zero-bs-crm' ); } /** * Get the description of the trigger. * * @since 6.2.0 * * @return string|null The description of the trigger. */ public static function get_description(): ?string { return __( 'Triggered when a quote is updated', 'zero-bs-crm' ); } /** * Get the category of the trigger. * * @since 6.2.0 * * @return string|null The category of the trigger. */ public static function get_category(): ?string { return __( 'Quote', 'zero-bs-crm' ); } /** * Get the date type. * * @return string The type of the step */ public static function get_data_type(): string { return Quote_Data::class; } /** * Listen to this trigger's target event. * * @since 6.2.0 * * @return void */ protected function listen_to_event(): void { $this->listen_to_wp_action( 'jpcrm_quote_update' ); } }
projects/plugins/crm/src/automation/commons/triggers/quotes/class-quote-status-updated.php
<?php /** * Jetpack CRM Automation Quote_Status_Updated trigger. * * @package automattic/jetpack-crm * @since 6.2.0 */ namespace Automattic\Jetpack\CRM\Automation\Triggers; use Automattic\Jetpack\CRM\Automation\Base_Trigger; use Automattic\Jetpack\CRM\Automation\Data_Types\Quote_Data; /** * Adds the Quote_Status_Updated class. * * @since 6.2.0 */ class Quote_Status_Updated extends Base_Trigger { /** * Get the slug name of the trigger. * * @since 6.2.0 * * @return string The slug name of the trigger. */ public static function get_slug(): string { return 'jpcrm/quote_status_updated'; } /** * Get the title of the trigger. * * @since 6.2.0 * * @return string|null The title of the trigger. */ public static function get_title(): ?string { return __( 'Quote Status Updated', 'zero-bs-crm' ); } /** * Get the description of the trigger. * * @since 6.2.0 * * @return string|null The description of the trigger. */ public static function get_description(): ?string { return __( 'Triggered when a quote status is updated', 'zero-bs-crm' ); } /** * Get the category of the trigger. * * @since 6.2.0 * * @return string|null The category of the trigger. */ public static function get_category(): ?string { return __( 'Quote', 'zero-bs-crm' ); } /** * Get the date type. * * @return string The type of the step */ public static function get_data_type(): string { return Quote_Data::class; } /** * Listen to this trigger's target event. * * @since 6.2.0 * * @return void */ protected function listen_to_event(): void { $this->listen_to_wp_action( 'jpcrm_quote_status_update' ); } }