/ph-salesforce.php
PHP | 1480 lines | 739 code | 450 blank | 291 comment | 111 complexity | 3ad03cebfb348502c425110c2bbe1290 MD5 | raw file
- <?php /*
- **************************************************************************
- Plugin Name: Project Homecoming Salesforce Integration
- Plugin URI: http://projecthomecoming.net/
- Description: Sync Project Homecoming Salesforce data with WordPress..
- Version: 0.0.1
- Author: Caliper Creative
- Author URI: http://madebycaliper.com
- License: GPLv2 or later
- **************************************************************************/
- // Make sure we don't expose any info if called directly
- if ( !function_exists( 'add_action' ) ) {
- echo 'PH Salesforce Plugin can\'t be called directly!';
- exit;
- }
- global $chrome_php_enabled;
- $chrome_php_enabled = defined('CHROME_PHP') && CHROME_PHP;
- // Autoload global composer libs
- if ( isset( $_SERVER['HTTP_HOST'] ) && strstr( $_SERVER['HTTP_HOST'], 'localhost' ) ) :
- if( $chrome_php_enabled ) {
- require_once '/Users/krumpla/.composer/vendor/autoload.php';
- }
- endif;
- date_default_timezone_set("America/Chicago");
- define( 'PH_SF_DEBUG', TRUE );
- require_once 'core/includes/helper-functions.php';
- if ( ! class_exists('PH_Salesforce')) {
- // Don't activate on anything less than PHP & WP Requirments
- $php_min_version = '5.3';
- $wp_min_version = '3.2';
-
- if ( version_compare( PHP_VERSION, $php_min_version, '<' ) || version_compare( get_bloginfo( 'version' ), $wp_min_version, '<' ) ) {
- require_once ABSPATH . 'wp-admin/includes/plugin.php';
- deactivate_plugins( basename( __FILE__ ) );
- if ( isset( $_GET['action'] ) && ( $_GET['action'] == 'activate' || $_GET['action'] == 'error_scrape' ) )
- die( __( "PH Salesforce requires PHP version $php_min_version or greater and WordPress $wp_min_version or greater.", 'ph-salesforce' ) );
- }
- class PH_Salesforce {
-
- const PLUGIN_NAME = 'PH_Salesforce';
- const PLUGIN_SLUG = 'ph_salesforce';
- const PLUGIN_PREFIX = 'phs_';
- const PLUGIN_VERSION = '0.1.0';
- const MIN_WP_VERSION = '3.6.0';
- private $cpts = array();
- // Options table settings
- const SETTINGS_GROUP_NAME = 'ph_sf_settings';
- const SETTINGS_SLUG = 'ph_sf';
- public $settings = array();
- public $opts = array();
- // Instance vars
- public $plugin_path;
- public $json_path;
- public $sf_api_path;
- public $projects;
- public $the_project;
- public $volunteer_orgs = array();
- public $the_vol_org;
- public $volunteers = array();
- public $accounts;
- public $account_lookup = array();
- public $work_records = array();
- public $project_udpates = array();
- public $the_emply;
- public $emply_meta = array();
- public $run_time;
- public $current_project_sf_id = 0;
- public $current_project_key = '';
- public $import_results = array(
- 'projects' => array(),
- 'employees' => array()
- );
- protected static $api;
- /**
- * Hook into init and admin/non-admin actions.
- * Include, initialize & add theme support for widgets.
- *
- * @access public
- * @return void
- */
- function __construct() {
- // Initialize the plugin
- add_action( 'init', array(&$this, 'init' ) );
-
- if ( is_admin() ) {
-
- // Initialize admin settings and enqueue assets for admin
- add_action( 'admin_init', array( &$this, 'admin_init' ) );
-
- // Add Plugin Settings Page
- add_action( 'admin_menu', array( &$this, 'add_admin_menu' ) );
- } else { // Non-Admin
-
- // Process the_content based on settings and content type
- add_action( 'pre_get_posts' , array( &$this, 'pre_get_posts' ) );
- }
-
- } // END __construct()
- ///////////////// Activation & Deactivation
- /**
- * Setup plugin for the first time
- * Register Post Types
- * Flush Rewrite Rules
- *
- * @access public
- * @return void
- */
- function activate() {
- if ( ! $this->_get_options() ) {
- // If no options exist, set initial vars
- $this->_update_options( FALSE , 'has_imported');
- }
- // Register post types then flush rewrite rules
- $this->register_post_types();
- flush_rewrite_rules( true );
- } // END activate()
- /**
- * Clear the WP scheduled events and flush rewrite rules.
- *
- * @access public
- * @return void
- */
- function deactivate() {
- wp_clear_scheduled_hook('try_import_event_hook');
- flush_rewrite_rules();
- } // END deactivate()
-
- // END Activation & Deactivation
-
- /**
- * Initialize plugin: Post Types, variables, terms
- *
- * Check if plugin is configured and either push notice
- * or get API instance.
- *
- * @access public
- * @return void
- */
- function init() {
- ///// Things that should happen on every page load
- // Included classes that should be available from the get go
- $this->include_classes();
-
- // Initial Class properties/variables
- $this->init_vars();
- // Register CPTs
- $this->register_post_types();
-
- if( is_admin() ) {
- // Add Import/Refresh AJAX action for Settings page
- add_action( 'wp_ajax_ph_sf_refresh_all', array( &$this, 'ajax_refresh_all' ) );
- // Change the title of the Options page
- if( function_exists('acf_set_options_page_title') )
- {
- acf_set_options_page_title( __('Project Homecoming Organization Info') );
- }
- // Rename Options Page in Admin Menu
- if( function_exists('acf_set_options_page_menu') )
- {
- acf_set_options_page_menu( __('PH Info') );
- }
- } else { // Non-Admin pages
-
- // Front End Scripts & Styles
- // add_action( 'wp_enqueue_scripts', array( &$this , 'enqueue_scripts_and_styles' ) );
- }
-
- // Allow manual import triggered by command line
- $this->opts = getopt( "", array('import::','no-sf-query::', 'migrate') );
- if( isset( $this->opts['import'] ) && $this->opts['import'] ) {
- $this->run_import();
- } else if ( isset( $this->opts['migrate'] ) ) {
- _log('Running migration...');
- $this->run_migration();
- }
- } // END init()
- /**
- * Initialize plugin with relevant admin behaviors.
- *
- * @access public
- * @return void
- */
- function admin_init() {
- // Include Plugin Scripts & Styling for Admin pages
- add_action( 'admin_enqueue_scripts', array( &$this, 'add_admin_assets' ) );
- // Add settings update notice, if updated
- if( isset( $_GET['settings-updated'] ) ) {
- add_action( 'admin_notices', array( &$this, 'admin_notice_settings_updated' ) );
- }
- } // END admin_init()
-
- function add_admin_menu() {
- add_options_page(
- 'Project Homecoming Salesforce Options',
- 'PH Salesforce',
- 'manage_options',
- $this->settings_page_slug,
- array( $this, 'plugin_settings_page' )
- );
- } // end add_admin_menu()
- function include_classes() {
- include_once 'core/classes/class-ph-project.php';
- include_once 'core/classes/class-ph-employee.php';
- include_once 'core/classes/class-ph-vol-org.php';
- include_once 'core/api.php';
- } // END include_classes()
- /**
- * Initialize variables that depend on Constants
- *
- * @access public
- * @return void
- */
- private function init_vars() {
- // Set this' settings to settings from options table
- $this->settings = $this->_get_options();
-
- $this->settings_page_slug = self::PLUGIN_PREFIX . "settings";
- $this->plugin_path = plugin_dir_path( __FILE__ );
- $this->json_path = "{$this->plugin_path}json/";
- $this->sf_api_path = "{$this->plugin_path}vendor/developerforce/force.com-toolkit-for-php";
- $this->run_time = date('y-m-d_Hms', time() );
- $this->ph_sf_api = new PH_Salesforce_API();
- // Set menu and related properties
- $this->main_menu_slug = self::PLUGIN_PREFIX . 'main-menu';
- $this->menu_pages = array(
- 'Settings' => array(
- 'page_title' => 'PH Salesforce Settings',
- 'capability' => 'read_private_posts',
- 'menu_slug' => $this->settings_page_slug,
- 'function' => array( &$this, 'plugin_settings_page' )
- )
- );
- // Setup Custom Post Types
- $this->cpts = array(
- PH_Project::CPT_NAME => array(
- 'singular' => 'Project',
- 'plural' => 'Projects',
- 'show_in_menu' => true,
- 'supports' => array('excerpt'),
- 'taxonomies' => array('post_tag','category'),
- 'has_archive' => true,
- 'public' => true,
- 'rewrite_slug' => 'projects'
- ),
- PH_Employee::CPT_NAME => array(
- 'singular' => 'Staff',
- 'plural' => 'Staff',
- 'show_in_menu' => true,
- 'supports' => array('excerpt'),
- 'taxonomies' => array('post_tag','category'),
- 'has_archive' => true,
- 'public' => true,
- 'rewrite_slug' => 'staff'
- ),
- PH_Volunteer_Org::CPT_NAME => array(
- 'singular' => 'Volunteer Org',
- 'plural' => 'Volunteer Orgs',
- 'show_in_menu' => true,
- // 'supports' => array('excerpt'),
- 'taxonomies' => array('post_tag','category'),
- 'has_archive' => false,
- 'public' => true,
- 'rewrite_slug' => 'volunteer-orgs'
- )
- );
- } // END init_vars()
- /**
- * Register and add support for PH-SF CPTs, flush rewrite rules.
- *
- * @access public
- * @return void
- */
- private function register_post_types() {
- global $db_cpt_name;
- foreach ($this->cpts as $key => $cpt) {
- $db_cpt_name = $key;
- $singular = $cpt['singular'];
- $plural = $cpt['plural'];
- $show_in_menu = $cpt['show_in_menu'];
- $passed_supports_args = (isset($cpt['supports']) ? (array) $cpt['supports'] : array() );
- $passed_taxonomies = (isset($cpt['taxonomies']) ? (array) $cpt['taxonomies'] : array() );
-
- $supports_defaults = array( 'title', 'editor', 'comments', 'thumbnail', 'custom-fields' );
- $supports_array = array_merge($supports_defaults, $passed_supports_args);
-
- $taxonomies_defaults = array('');
- $taxonomies_array = array_merge($taxonomies_defaults, $passed_taxonomies);
-
- $hasArchive = isset($cpt['has_archive']) ? $cpt['has_archive'] : true;
- $exclude_from_search = isset($cpt['exclude_from_search']) ? $cpt['exclude_from_search'] : false;
- $public = isset($cpt['public']) ? $cpt['public'] : false;
-
- $rewrite_slug = (isset($cpt['rewrite_slug']) ? $cpt['rewrite_slug'] : $cpt['plural'] );
- register_post_type( $db_cpt_name,
- array(
- 'labels' => array(
- 'name' => $plural,
- 'singular_name' => $singular,
- 'add_new' => 'Add New',
- 'add_new_item' => 'Add New '. $singular,
- 'edit' => 'Edit',
- 'edit_item' => 'Edit '. $singular,
- 'new_item' => 'New '. $singular,
- 'view' => 'View',
- 'view_item' => 'View '. $singular,
- 'search_items' => 'Search '. $plural,
- 'not_found' => 'No '. $plural .' found',
- 'not_found_in_trash' => 'No '. $plural .' found in Trash',
- 'parent' => 'Parent '. $singular
- ),
- 'public' => $public,
- 'menu_position' => 15,
- 'supports' => $supports_array,
- 'taxonomies' => $taxonomies_array,
- // 'menu_icon' => get_bloginfo('stylesheet_directory') . '/images/'.strtolower($plural).'.png',
- 'has_archive' => $hasArchive,
- 'rewrite' => array( 'slug' => $rewrite_slug ),
- // 'rewrite' => true,
- 'show_in_menu' => $show_in_menu,
- /* 'exclude_from_search' => $exclude_from_search, */
-
- )
- );
- } // end foreach cpt
- // Add theme support for thumbnails
- if ( function_exists( 'add_theme_support' ) ) {
- add_theme_support( 'post-thumbnails' );
- }
- flush_rewrite_rules( true );
-
- } // register_post_types()
-
- /**
- * Adds filter hooks that add content before and/or after posts,
- * depending on Settings.
- *
- * @access public
- * @return void
- */
- function pre_get_posts() {
-
- } // END pre_get_posts
-
-
- /**
- * Add admin assets to relevant pages
- *
- * @access public
- * @return void
- */
- function add_admin_assets() {
-
- if( ! $this->is_ph_sf_admin_page() )
- return;
-
- // Javascript
- wp_enqueue_script(
- self::PLUGIN_SLUG . '_admin_js',
- plugin_dir_url( __FILE__ ) . 'assets/js/admin.js',
- array('jquery'),
- self::PLUGIN_VERSION ,
- true
- );
-
- // Get current page protocol
- $protocol = isset( $_SERVER['HTTPS'] ) ? 'https://' : 'http://' ;
-
- // Output admin-ajax.php URL with same protocol as current page
- $params = array(
- 'ajaxurl' => admin_url( 'admin-ajax.php' , $protocol )
- );
- wp_localize_script( 'ph_salesforce_admin_js' , 'ph_salesforce_admin_js', $params );
- // CSS
- wp_register_style( 'ph_salesforce_admin_css', plugin_dir_url( __FILE__ ) . 'assets/css/admin.css', false, self::PLUGIN_VERSION );
- wp_enqueue_style( 'ph_salesforce_admin_css' );
- } // END add_admin_js
-
- // Options Helpers
-
- /**
- * Get all of the plugin's options.
- *
- * @access public
- * @return void
- */
- public function _get_options() {
-
- if( empty( $this->settings ) )
- $this->settings = get_option( self::SETTINGS_GROUP_NAME );
- return $this->settings;
- } // END _get_options()
-
- /**
- * Get a specified key from the options array
- *
- * @access public
- * @param mixed $key
- * @return void
- */
- function _get_the_option( $key = false ) {
- if ( !$key )
- return false;
-
- $options = $this->_get_options();
- return isset( $options[ $key ] ) ? $options[ $key ] : false;
-
- } // END _get_the_option()
-
- /**
- * Update one or all options saved in the WP Options table
- *
- * @access private
- * @param mixed $value : New value to save into option
- * @param String $key (default: null) : option key to modify
- * @return void
- */
- private function _update_options( $value = null, $key = null ) {
-
- if( is_null( $value ) )
- return false;
-
- // Get plugin options
- $options = $this->_get_options();
-
- // If the key is not set, overwrite all options
- if ( !isset($key) ) {
- $options = $value;
- } else {
- // Set the key to the new value
- $options[ $key ] = $value;
- }
- // Update options with new values
- update_option(self::SETTINGS_GROUP_NAME, $options );
-
- // Update the obj settings
- return $this->settings = $options;
-
- } // END _update_options()
-
-
- // Import Functions
-
- /**
- * Schedule an import event to run from wp-cron.php
- *
- * @access public
- * @return void
- */
- function schedule_import() {
-
- if ( !wp_next_scheduled( 'try_import_event_hook' ) ) {
- wp_schedule_event( time(), 'hourly', array( &$this, 'try_import_event_hook' ) );
- }
-
- add_filter('cron_schedules', array( &$this, 'add_schedules' ) );
-
- } // END schedule_import
- function add_schedules($schedules) {
- // interval in seconds
- $schedules['every10min'] = array('interval' => 10*60, 'display' => 'Every 10 minutes');
- return $schedules;
- } // END my_additional_schedules
- /**
- * Try to run the import script.
- * Will only execute if called from the shell and DOING_CRON
- *
- * @access public
- */
- function try_import( ) {
- $doing_cron = defined( 'DOING_CRON' ) && DOING_CRON;
- $called_from_shell = !isset( $_SERVER['HTTP_HOST'] );
-
- // Make sure we don't expose any info if called directly
- if ( !function_exists( 'add_action' ) ) {
- _log('PH Salesforce Plugin can\'t be called directly!');
- exit;
- }
-
- // If this is a WP-Cron call, not from shell, return
- if ( !$called_from_shell ) {
- _log( "try_import() Not called from shell. Returning...");
- return false;
- }
- // _log($_SERVER, 'server');
-
- if ( $doing_cron ) {
- _log("\t -------- try_import() Called from shell && DOING_CRON -------- ");
- _log("\t Executing import script...");
- // Determine caller function
- $backtrace = debug_backtrace();
- if ( isset( $backtrace[1] ) ) {
- $caller = $backtrace[1];
- }
-
- if ( !empty( $caller['file'] ) )
- _log("from ".$caller["function"]."() in ".$caller["file"] , 'importing...');
- return $this->run_import();
-
- } else {
- // Triggered from SHELL/CRON but not doing_wp_cron
- _log("\t---- Called from shell but not DOING_CRON ----");
- }
- return false;
- } // END try_import
- /**
- * Fetch all Salesforce data and Import/Update WP Objects
- *
- * @access public
- */
- function run_import() {
- $this->fetch_salesforce_data();
- _log(' Finished Fetching SF Data...');
- $this->add_relational_data_to_projects();
- _log(' ========== Finished Processing SF Data ==========');
- $this->remove_stale_cache();
- _log(' Saving Sforce Data to WP...');
- $this->save_sforce_data_to_wp();
-
- $this->_update_options( TRUE, 'has_imported');
- $this->_update_options( time(), 'last_import_time');
- $this->_update_options( $this->import_results, 'last_import_results');
- return $this->import_results;
-
- } // END run_import()
- function echo_import_results() {
- $last_import_results = $this->_get_the_option('last_import_results');
- if( !$last_import_results ) return '';
- $html = '<ul class="response-list">';
- if( !empty( $last_import_results['projects']['created'] ) ) {
- $html .= "<h3>Newly Imported Projects</h3>";
- unset( $project_names );
- foreach ($last_import_results['projects']['created'] as $project) {
- $project_names[] = sprintf( "<li class='project created'>[ %s ]</li>", $project['details']->Name );
- }
- $html .= implode(', ', $project_names);
- }
- if( !empty( $last_import_results['projects']['updated'] ) ) {
- $html .= "<h3>Updated Projects</h3>";
- unset( $project_names );
- foreach ($last_import_results['projects']['updated'] as $project) {
- $project_names[] = $project['details']->Name;
- }
- $html .= sprintf( "<p class='updated-projects'>%s.</p>", implode(', ', $project_names) );
- }
- if( !empty( $last_import_results['employees']['created'] ) ) {
- $html .= "<h3>Newly Imported Employees</h3>";
- unset( $employee_names );
- foreach ($last_import_results['employees']['created'] as $employee_name ) {
- $employee_names[] = sprintf( "<li class='employee created'>[ %s ]</li>", $employee_name );
- }
- $html .= implode(', ', $employee_names);
- }
- if( !empty( $last_import_results['employees']['updated'] ) ) {
- $html .= "<h3>Updated employees</h3>";
- unset( $employee_names );
- foreach ( $last_import_results['employees']['updated'] as $employee_name ) {
- $employee_names[] = $employee_name;
- }
- $html .= sprintf( "<p class='updated-employees'>%s.</p>", implode(', ', $employee_names) );
- }
- $html .= "</ul>";
- echo $html;
- } // END echo_import_results()
-
- function fetch_salesforce_data() {
-
- $this->get_projects();
- $this->save_employees_json();
- $this->get_volunteers();
- $this->save_volunteers_to_json();
- $this->get_volunteer_orgs();
- $this->save_volunteer_orgs_to_json();
- $this->build_account_lookup_hash();
- } // END fetch_salesforce_data()
- /**
- * Fetch projects from Salesforce.
- */
- function get_projects() {
- $this->projects = $this->ph_sf_api->get_projects();
- } // end get_projects()
- /**
- * Fetch employees from Salesforce and save them to JSON.
- */
- function save_employees_json() {
- $this->employees = $this->ph_sf_api->get_unsuppressed_employees();
- // $fp = fopen( $this->json_path . "employees-{$this->run_time}.json", "w");
- $fp = fopen( $this->json_path . "employees.json", "w");
- // $this->employees['timestamp'] = date("Y-m-d g:i:s a");
- fwrite( $fp, json_encode( $this->employees ) );
- fclose( $fp );
- } // end save_employees_json()
- /**
- * Fetch volunteers from Salesforce.
- */
- function get_volunteers() {
- $this->volunteers = $this->ph_sf_api->get_all_volunteers();
- } // end get_volunteers()
- /**
- * Fetch volunteers from Salesforce.
- */
- function get_volunteer_orgs() {
- _log_v('Fetching all Volunteer Orgs..');
- $this->volunteer_orgs = $this->ph_sf_api->get_all_volunteer_orgs();
- } // end get_volunteer_orgs()
- /**
- * Build account lookup hash.
- */
- function build_account_lookup_hash() {
- $this->accounts = $this->ph_sf_api->get_all_accounts();
- foreach ( $this->accounts as $account ) {
- $this->account_lookup[ $account['Id'] ]['name']= $account['Name'];
- $this->account_lookup[ $account['Id'] ]['startDate']= $account['Start_Date__c'];
- $this->account_lookup[ $account['Id'] ]['location'] = $account['Team_Reg_Location__c'];
- }
- // Recovery Memory / temp storage
- unset( $this->accounts );
- }
- /**
- * Iterates through all the projects and adds relational data.
- */
- function add_relational_data_to_projects() {
- _mem_v('Looping Each Project to add Relational Data...');
- $num_projs = 0;
- foreach( $this->projects as $project_key => $project ) :
- // "Globalize" current Project data for access in functions
- $this->current_project = $project;
- $this->current_project_sf_id = $this->get_project_field_value('Project_SF_ID__c');
- $this->current_project_key = $project_key;
- $this->add_project_donors();
- $this->add_funding_partners();
- $this->add_work_records();
- $this->add_project_updates();
- if( !isset( $this->opts['no-sf-query'] ) || ( isset( $this->opts['no-sf-query'] ) && !$this->opts['no-sf-query'] ) ) {
- _mem("Proj #" . $num_projs++ );
- // $this->_log_queries();
- } else {
- _log_v( sprintf("Proj #%d ( %s )", $num_projs++, $project['Name'] ) );
- }
- endforeach;
- $this->save_projects_to_json();
- _log('Done looping each project');
- } // end add_relational_data_to_projects()
- /**
- * Add Project Donor data to the projects Obj.
- */
- function add_project_donors() {
- // _mem('donors...');
- $donors = $this->ph_sf_api->get_project_donors();
- if( !empty( $donors ) ) {
- $this->projects[ $this->current_project_key ]['Donors'] = $donors;
- }
- } // end connect_project_donors()
- /**
- * Add Funding Partners data to the projects Obj.
- */
- function add_funding_partners() {
- // $this->_log_queries();
- // _mem('Funding Partners...');
- $partners = $this->ph_sf_api->get_funding_partners();
-
- // Don't iterate through this project if there aren't partners
- if( empty( $partners ) ) { return; }
- foreach ( $partners as $partner ) {
- if ( isset( $partner['Contact__c'] ) ) {
- $partner['Donor_Name'] = $this->ph_sf_api->get_contact( $partner['Contact__c'] );
-
- // Sanitize partner URL
- if( isset( $partner['Funder_Website__c'] ) ) {
- // Replace double http:// and missing colon with proper one
- $scheme = 'http';
- $partner['Funder_Website__c'] = str_replace( array("{$scheme}://{$scheme}://","{$scheme}//"), "{$scheme}://", $partner['Funder_Website__c'] );
- // Same for https
- $scheme = 'https';
- $partner['Funder_Website__c'] = str_replace( array("{$scheme}://{$scheme}://","{$scheme}//"), "{$scheme}://", $partner['Funder_Website__c'] );
- // Prepend the scheme if it ain't got one
- if( preg_match("#https?://#", $partner['Funder_Website__c'] ) === 0 ) {
- $partner['Funder_Website__c'] = 'http://'.$partner['Funder_Website__c'];
- }
- }
- $this->projects[ $this->current_project_key ]['Funding_Partners'][] = $partner;
- } else {
- // _log($partner, 'partner does not have contact__c');
- }
- } // END foreach partners
- } // end add_funding_partners()
- /**
- * Add Work Records to the projects Obj.
- */
- function add_work_records() {
- // $this->_log_queries();
- // _mem('Work Records...');
- $work_records = &$this->work_records;
- $the_project = &$this->projects[ $this->current_project_key ];
- $work_records[ $this->current_project_key ] = $this->ph_sf_api->get_project_work_records();
- $site_managers = $work_records[ $this->current_project_key ]['Site_Managers'];
- $volunteer_orgs = $work_records[ $this->current_project_key ]['Volunteer_Orgs'];
- if( count( $site_managers ) ) { // If there are site managers listed on the current work record...
- // Iterate through each site manager and to the project's work records
- foreach( $site_managers as $site_manager_key => $site_manager_id ){
- $site_manager_obj = $this->ph_sf_api->get_contact( $site_manager_id );
- $the_project['work_records']['Site_Managers'][ $site_manager_id ] = $site_manager_obj;
- $this->add_project_to_emply( $site_manager_id );
- }
- }
- $constr_mgr_id = $this->get_project_field_value('proj_cm__c');
- if( !empty( $constr_mgr_id ) ) {
- $constr_mgr_obj = $this->ph_sf_api->get_contact( $constr_mgr_id );
- $the_project['work_records']['Site_Managers'][ $constr_mgr_id ] = $constr_mgr_obj;
- $this->add_project_to_emply( $constr_mgr_id );
- }
- if( count( $volunteer_orgs ) ) :
- // add all IDs to the work record obj
- $the_project['Volunteer_Orgs'] = $volunteer_orgs;
- foreach( $volunteer_orgs as $org_id ) :
- $this->add_project_to_volunteer_org( $org_id );
- endforeach;
- endif;
- } // end add_work_records()
- /**
- * Add a project ID to an Employee related projects hash.
- */
- function add_project_to_emply( $emply_id = 0 ) {
- if( !$emply_id ) return false;
- $project = PH_Project::get_project_from_sf_id( $this->current_project_sf_id );
- if( "publish" == $project->post_status ) // Only add the published Projects to the emply details
- $this->projects_by_emply[ $emply_id ][] = $project->ID;
- } // END add_project_to_emply()
-
- /**
- * Add a project ID to Vol. Org's related projects hash.
- */
- function add_project_to_volunteer_org( $org_id = 0 ) {
- if( !$org_id ) return false;
- $project = PH_Project::get_project_from_sf_id( $this->current_project_sf_id );
- // _log_v("Adding org id {$org_id} to project {$project->post_title}...");
- $this->projects_by_volunteer_org[ $org_id ][] = $project->ID;
- } // END add_project_to_volunteer_org()
- /**
- * Add Volunteer data to the projects Obj.
- */
- function add_volunteers() {
- // $this->_log_queries();
- // _mem('Volunteers...');
- $project_key = $this->current_project_key;
- $work_records = &$this->work_records;
- if( count( $work_records[ $project_key ]['Volunteer_Registrations'])){
- foreach( $work_records[ $project_key ]['Volunteer_Registrations'] as $volreg_key ){
- $teamreg = $this->get_project_volunteer_single( $volreg_key );
- $team_sf_ID = $teamreg[0]['Team_Reg__c'];
- if ( $team_sf_ID ){
- $this->projects[ $project_key ]['work_records']['Volunteer_Registrations'][ $team_sf_ID ] = array(
- 'contact' => $accountLookup[ $team_sf_ID ]['name'],
- 'startDate' => $accountLookup[ $team_sf_ID ]['startDate'],
- 'location' => $accountLookup[ $team_sf_ID ]['location']
- );
- }
- }
- }
- } // end add_volunteers()
- /**
- * Add Project Updates to the projects Objs.
- */
- function add_project_updates(){
- $proj_updates = &$this->proj_updates;
- $the_project = &$this->projects[ $this->current_project_key ];
- $proj_updates[ $this->current_project_key ] = $this->ph_sf_api->get_project_updates();
- $the_updates = $proj_updates[ $this->current_project_key ];
- if( count( $the_updates ) ) {
- $the_project['updates'] = $the_updates;
- }
-
- } // END add_project_updates()
- /**
- * Save Projects to JSON.
- */
- function save_projects_to_json() {
- _log_v('Saving projects to JSON...');
- $fp = fopen( $this->json_path . "projects.json", "w");
- // $this->projects['timestamp'] = date("Y-m-d g:i:s a");
- fwrite( $fp, json_encode( $this->projects ) );
- fclose( $fp );
- } // end save_projects_to_json()
- /**
- * Save volunteers to JSON.
- */
- function save_volunteers_to_json() {
- $fp = fopen( $this->json_path . "volunteers.json", "w");
- $this->volunteers['timestamp'] = date("Y-m-d g:i:s a");
- fwrite( $fp, json_encode( $this->volunteers ) );
- fclose( $fp );
- // Recovery Memory / temp storage
- // unset( $this->volunteers );
- } // end save_volunteers_to_json()
- function save_volunteer_orgs_to_json() {
- _log_v('Saving Volunteer Orgs to JSON...');
- $fp = fopen( $this->json_path . "volunteer-orgs.json", "w");
- // $this->volunteer_orgs['timestamp'] = date("Y-m-d g:i:s a");
- fwrite( $fp, json_encode( $this->volunteer_orgs ) );
- fclose( $fp );
- _log_v('Volunteer Orgs saved.');
- // Recovery Memory / temp storage
- // unset( $this->volunteers );
- } // end save_volunteer_orgs_to_json()
- function remove_stale_cache() {
- // Return if told not to ping SF
- if( isset( $this->opts['no-sf-query'] ) && $this->opts['no-sf-query'] ) return false;
- // Remove all old cache folders
- $hour_stamp = date("Y-m-d_H");
- $cache_dir = "sf_cache_$hour_stamp";
- $cache_base_dir = $this->plugin_path . "query-cache";
- $iterator = new DirectoryIterator( $cache_base_dir );
- _log("cache dir : $cache_base_dir/$cache_dir/");
- foreach ($iterator as $fileinfo) {
- $target_dir = $cache_base_dir. "/" . $fileinfo->getFilename() . "/";
- if (!$fileinfo->isDot()) {
- if( $fileinfo->getFilename() !== $cache_dir ) {
- _log("deleting : $target_dir");
- if( $fileinfo->isDir() ) $this->delete_files( $target_dir );
- } else {
- _log("Saving : $target_dir" );
- }
- }
- }
- _log('Finished Removing Stale Cache...');
- } // END remove_stale_cache()
- function save_sforce_data_to_wp() {
- _mem_v('Saving to WP...');
- $sf_projects = $this->get_decoded_json_file('projects');
- $sf_employees = $this->get_decoded_json_file('employees.json');
- $sf_volunteer_orgs = $this->get_decoded_json_file('volunteer-orgs.json');
- // Try to retrieve some memory...
- unset( $this->projects, $this->work_records );
- _log('Importing projects to WP...');
- $proj_import_success = $this->import_projects_to_wp( $sf_projects );
- // _log('Importing Employees to WP...');
- $emply_import_success = $this->import_employees_to_wp( $sf_employees );
- // _log('Importing Vol. Orgs to WP...');
- $vol_org_import_success = $this->import_volunteer_orgs_to_wp( $sf_volunteer_orgs );
- if( $proj_import_success && $emply_import_success && $vol_org_import_success ) {
- _mem_v('Finished import');
- _log('');
- _log('=======================================');
- _log('========== Done Saving to WP ==========');
- _log('=======================================');
- _log('');
- } else {
- return false;
- _log('IMPORT FAILED');
- }
- } // end save_sforce_data_to_wp()
- function import_projects_to_wp( $projects = 0 ) {
- if( !$projects ) return false;
- foreach ( $projects as $details ) :
- // "Globalize" this project
- $project_args = array(
- 'details' => (object) $details
- );
- $project = new PH_Project( $project_args );
- $this->the_project = $project;
- if ( $project->get_wp_id() ) :
- $this->import_results['projects']['updated'][] = (array) $project;
- $project->update_in_wp();
- else :
- $this->import_results['projects']['created'][] = (array) $project;
- $project->create_in_wp();
- endif; // If Project exists in WP
- endforeach;
- _log_v('Done importing Projects to WP.');
- return $projects;
- } // END import_projects_to_wp()
- function import_employees_to_wp( $employees = 0 ) {
- if( !$employees ) return false;
- foreach ( $employees as $details ) :
- // Add related projects, if available in the 'global' hash
- if( isset( $this->projects_by_emply[ $details->Id ] ) ) {
- $details->related_projects = (array) $this->projects_by_emply[ $details->Id ];
- }
- $employee_args = array(
- 'details' => (object) $details
- );
- $employee = new PH_Employee( $employee_args );
-
- // "Globalize" this employee
- $this->the_employee = $employee;
- if ( $employee->get_wp_id() ) {
- $this->import_results['employees']['updated'][] = $employee->detail('Name');
- $employee->update_in_wp();
- } else {
- $this->import_results['employees']['created'][] = $employee->detail('Name');
- $employee->create_in_wp();
- } // If Employee exists in WP
- endforeach;
- _log_v('Done importing Employees to WP.');
- return $employees;
- } // END import_employees_to_wp()
- function import_volunteer_orgs_to_wp( $vol_orgs = 0 ) {
- if( !$vol_orgs ) return false;
- _log_v('Importing Volunteer Orgs to WP...');
- foreach ( $vol_orgs as $details ) :
- // Add related projects, if available in the 'global' hash
- if( isset( $this->projects_by_volunteer_org[ $details->Id ] ) ) {
- $details->related_projects = (array) $this->projects_by_volunteer_org[ $details->Id ];
- }
- $vol_org_args = array(
- 'details' => (object) $details
- );
-
- $vol_org = new PH_Volunteer_Org( $vol_org_args );
-
- // "Globalize" this vol_org
- $this->the_vol_org = $vol_org;
- if ( $vol_org->get_wp_id() ) {
- $vol_org->update_in_wp();
- } else {
- $vol_org->create_in_wp();
- } // If vol_org exists in WP
- endforeach;
- _log_v('Done importing Volunteer Orgs to WP.');
- return $vol_orgs;
- } // END import_volunteer_orgs_to_wp()
- function get_decoded_json_file( $file_name = 0 ) {
- if( !$file_name ) return false;
- // Append '.json' if the $file_name don't have it
- $has_json_ext = strpos( $file_name, '.json' );
- if( $has_json_ext === false ) { // <---- the triple equals is important ===
- $file_name .= '.json';
- }
- $file_contents = file_get_contents( $this->json_path . $file_name ); // Get .json file as string
- $return_obj = json_decode( $file_contents ); // Convert file to PHP array
- return isset_or_false( $return_obj );
- } // END get_decoded_json_file()
- /*
- * php delete function that deals with directories recursively
- */
- function delete_files($target) {
- if(is_dir($target)){
- $files = glob( $target . '*', GLOB_MARK ); //GLOB_MARK adds a slash to directories returned
- foreach( $files as $file ) {
- $this->delete_files( $file );
- }
- rmdir( $target );
- } elseif(is_file($target)) {
- unlink( $target );
- }
- } // END delete_files()
-
- /*======================================
- = AJAX Functions =
- ======================================*/
-
- /**
- * Handle AJAX call to import all data from Salesforce.
- *
- * Echoes JSON econded list of imported results.
- *
- * @access public
- * @return void
- */
- function ajax_refresh_all() {
-
- $this->run_import();
-
- echo json_encode( $this->import_results );
-
- die();
-
- } // END ajax_refresh_all()
- /*===============================================
- = Settings Page Functions =
- ===============================================*/
- function plugin_settings_page() {
- if ( !current_user_can( 'manage_options' ) ) {
- wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
- }
-
- // Render the settings template
- include_once( plugin_dir_path( __FILE__ ) . 'core/settings/settings.php' );
- }
- function admin_notice_settings_updated() {
- ?>
- <div id="message" class="updated">
- <p><strong>Plugin Settings updated.</strong></p>
- </div>
- <?php
- }
- /*===============================================
- = Misc & Helper Functions =
- ===============================================*/
-
- /**
- * Get the value of a Project Field if it exists
- */
- function get_project_field_value( $key = 0 ) {
-
- if ( !$key ) { return false; }
- // If that key is set, return it. Otherwise return false.
- return isset( $this->current_project[ $key ] ) ? $this->current_project[ $key ] : false;
- } // END get_project_field_value
- function get_project_volunteer_single( $id ) {
- return !empty( $this->volunteers[ $id ] ) ? $this->volunteers[ $id ] : false;
- }
- function stored_emply_meta( $wp_id ) {
- return isset_or_false( $this->emply_meta[ $wp_id ] );
- } // END stored_emply_meta()
-
- /**
- * Keep track of the number of queries run on the Sforce DB
- **/
- function _log_queries() {
- error_log("Queries: " . $_SESSION['queries']);
- _log("Queries: " . $_SESSION['queries']);
- } // end _log_queries()
- /**
- * Echo the HTML markup for the current post's title linked to the post permalink.
- *
- * @access public
- * @param mixed $args
- * @return void
- */
- function permalinked_title( $args ) {
- $defaults = array (
- 'class' => '',
- 'post_id' => 0
- );
-
- $args = wp_parse_args( $args, $defaults );
-
- extract( $args, EXTR_SKIP );
-
- if( !$post_id )
- {
- global $post;
-
- if( $post )
- {
- $post_id = intval( $post->ID );
- }
- }
-
- $title = get_the_title( $post_id );
- ?>
- <a class="<?php echo $class; ?>" href="<?php echo get_permalink( $post_id ); ?>" title="<?php echo $title ; ?>"><?php echo $title; ?></a>
- <?php
- } // END permalinked_title()
- /**
- * Used to determine whether admin assets should be loaded
- *
- * @access public
- * @return bool
- */
- function is_ph_sf_admin_page() {
- $screen = get_current_screen();
- $is_settings_page = isset( $_GET['page'] ) && $_GET['page'] == $this->settings_page_slug;
- $is_cpt_page = $screen->post_type == PH_Project::CPT_NAME || $screen->post_type == PH_Employee::CPT_NAME;
- return $is_settings_page || $is_cpt_page;
- } // END is_ph_sf_admin_page()
-
- function run_migration() {
- global $ph_migrator;
- include_once 'core/includes/migration.php';
- $ph_migrator = new PH_Migrator();
- } // end run_migration
- } // end PH_Salesforce class def
-
- } // end if !class_exists("PH_Salesforce")
- $doing_ajax = defined('DOING_AJAX') && DOING_AJAX ;
- $is_local = ( isset( $_SERVER['HTTP_HOST'] ) && strstr( $_SERVER['HTTP_HOST'], 'localhost' ) ) || isset( $_SERVER['TERM'] );
- if( !$doing_ajax && !$chrome_php_enabled && $is_local )
- _log("\t\t--------- Runnin ".date('Y-m-d h:i:s A', time() )." EST ---------\n");
- if( class_exists('PH_Salesforce') ) {
- global $ph_salesforce;
-
- $ph_salesforce = new PH_Salesforce();
-
- // Installation and uninstallation hooks
- register_activation_hook(__FILE__, array( &$ph_salesforce, 'activate'));
- register_deactivation_hook(__FILE__, array( &$ph_salesforce, 'deactivate'));
- add_action('try_import_event_hook', array( &$ph_salesforce, 'try_import' ) );
- if( isset( $ph_salesforce ) ) { // Add the settings link to the plugins page
- include_once 'core/includes/public-functions.php';
-
- /**
- * Add Plugin Settings page link next to the Edit / Activate links on the Plugins page
- */
- function plugin_settings_link($links) {
- global $ph_salesforce;
- $settings_link = '<a href="admin.php?page=' .$ph_salesforce->settings_page_slug .'">Settings</a>';
- array_unshift($links, $settings_link);
- return $links;
- } //end plugin_settings_link
- $plugin = plugin_basename(__FILE__);
- add_filter("plugin_action_links_$plugin", 'plugin_settings_link');
- //Add custom classes to body
- function ph_sf_cpt_body_class( $classes ){
-
- global $post;
- // If this is a single page w/a post type param
- if( is_single() && isset( $post->post_type ) ) {
- $post_type_obj = get_post_type_object( $post->post_type );
- $rewrite_slug = '';
- if( is_array( $post_type_obj->rewrite ) ) {
- $rewrite_slug = $post_type_obj->rewrite['slug'];
- }
- $classes[] = 'single-' . sanitize_html_class( $rewrite_slug );
- }
- return $classes;
- } // END ph_sf_cpt_body_class()
- add_filter( 'body_class', 'ph_sf_cpt_body_class' );
-
- }
- } // END class_exists('PH_Salesforce')
- ?>