Overview

Packages

  • ACF
  • Automation
    • Actions
    • Activation
    • LeadProfile
    • Menus
    • Queries
    • Rules
    • Triggers
  • CTA
    • Activation
    • AJAXListeners
    • Cloning
    • Core
    • Display
    • EditPage
    • Enqueues
    • GPLSettings
    • LeadsProfile
    • Loading
    • Menus
    • Notices
    • PlacementMetabox
    • PostType
    • Templates
    • Tracking
    • Variations
    • YOAST
  • InboundPro
    • Activation
    • AdminAJAX
    • AutoLoading
    • Cron
    • DataInterface
    • FieldMapping
    • Funnels
    • InboundNowAPI
    • Installer
    • LeadStatuses
    • Menus
    • Notifications
    • Ouath
    • Reports
    • Settings
    • Tracking
    • Translations
    • Updates
  • LandingPages
    • Activation
    • DataInterfaces
    • Management
    • Menus
    • NeedsAttention
    • Notices
    • Sidebars
    • Templates
    • Tracking
    • Variations
    • WelcomeScreen
    • Widgets
  • Leads
    • Activation
    • Akismet
    • BranchControl
    • BulkActions
    • Dashboard
    • Management
    • Notifications
    • Settings
    • Tracking
    • UserProfile
    • WPLogin
  • Mailer
    • Activation
    • Admin
    • ClickTracking
    • DataInterface
    • InboundForms
    • Leads
    • Management
    • Notifications
    • Scheduling
    • Sending
    • Settings
    • ShortcodesAndTokens
    • SparkPost
    • Templates
    • Unsubscribes
    • Variations
    • YoastSEO
  • None
  • Shared
    • APIs
    • CPT
    • DatabaseRoutines
    • DebugTricks
    • DoubleOptin
    • EventManagement
    • FieldMapping
    • InboundForms
    • LeadSorage
    • MarketingButton
    • Menus
    • Notifications
    • Shortcodes
    • ShortcodesAndTokens
    • StandAloneLicensing
    • Tracking
    • VisualEditor
  • xDepreciated

Classes

  • CTA_Activation
  • CTA_Activation_Update_Routines
  • CTA_Admin_Notices
  • CTA_Ajax_Listeners
  • CTA_Clone_Post
  • CTA_Conversion_Tracking
  • CTA_Dynamic_Widget
  • CTA_Enqueues
  • CTA_Load_Extensions
  • CTA_Menus
  • CTA_Metaboxes
  • CTA_Metaboxes_Global
  • CTA_Post_Type
  • CTA_Render
  • CTA_Settings
  • CTA_Static_Widget
  • CTA_Template_Manager
  • CTA_Template_Manager_List
  • CTA_Variations
  • CTA_WordPress_Leads
  • CTA_WordPress_SEO
  • Inbound_Ajax
  • Inbound_Akismet
  • Inbound_Analytics
  • Inbound_API
  • Inbound_API_Keys_Generation
  • Inbound_API_Keys_Table
  • Inbound_API_Wrapper
  • Inbound_Asset_Loader
  • Inbound_Automation_Action_Add_Remove_List
  • Inbound_Automation_Action_Add_Remove_Tag
  • Inbound_Automation_Action_Create_Lead
  • Inbound_Automation_Action_Create_User
  • Inbound_Automation_Action_Kill_Tasks
  • Inbound_Automation_Action_Relay_Data
  • Inbound_Automation_Action_Send_Email
  • Inbound_Automation_Action_Wait
  • Inbound_Automation_Activation
  • Inbound_Automation_Activation_Update_Routines
  • Inbound_Automation_Adminbar
  • Inbound_Automation_Lead_Profile
  • Inbound_Automation_Loader
  • Inbound_Automation_Plugin
  • Inbound_Automation_Post_Type
  • Inbound_Automation_Processing
  • Inbound_Automation_Query_Lead
  • Inbound_Automation_Query_User
  • Inbound_Automation_Trigger_inbound_double_optin_confirm
  • Inbound_Automation_Trigger_inbound_store_lead_post
  • Inbound_Automation_Trigger_inbound_track_link
  • Inbound_Automation_Trigger_Publish_Post
  • Inbound_Automation_Trigger_Save_Post_Deactivated
  • Inbound_Automation_Trigger_Set_Object_Terms
  • Inbound_Automation_Trigger_Update_Lead
  • Inbound_Automation_Trigger_User_Register
  • Inbound_Calls_To_Action_Plugin
  • Inbound_Confirm_Double_Optin
  • Inbound_Cron
  • Inbound_CTA_Quick_View
  • Inbound_Customizer
  • Inbound_Debug_Scripts
  • Inbound_Email_Meta
  • Inbound_Email_Preview
  • Inbound_Email_Template_Shortcodes
  • Inbound_Event_Report
  • Inbound_Events
  • Inbound_Events_Report
  • Inbound_Extension_Loads
  • Inbound_Forms
  • Inbound_Funnel_Reporting
  • Inbound_Impressions_Report
  • Inbound_Landing_Pages_Plugin
  • Inbound_Lead_Statuses
  • Inbound_Leads
  • Inbound_Leads_Custom_fields
  • Inbound_Leads_Plugin
  • Inbound_License
  • Inbound_List_Double_Optin
  • Inbound_Load_Shared
  • Inbound_Logging_Automation
  • Inbound_Login
  • Inbound_Mail_Daemon
  • Inbound_Mailer_ACF
  • Inbound_Mailer_Activation
  • Inbound_Mailer_Activation_Update_Routines
  • Inbound_Mailer_Ajax_Listeners
  • Inbound_Mailer_Clone_Post
  • Inbound_Mailer_Common_Settings
  • Inbound_Mailer_Customizer
  • Inbound_Mailer_Direct_Email_Leads
  • Inbound_Mailer_Enqueues
  • Inbound_Mailer_Forms_Integration
  • Inbound_Mailer_Load_Templates
  • Inbound_Mailer_Menus
  • Inbound_Mailer_Metaboxes
  • Inbound_Mailer_Notifications
  • Inbound_Mailer_Plugin
  • Inbound_Mailer_Post_Type
  • Inbound_Mailer_Scheduling
  • Inbound_Mailer_Settings
  • Inbound_Mailer_SparkPost
  • Inbound_Mailer_Stats_Report
  • Inbound_Mailer_Template_Manager
  • Inbound_Mailer_Template_Manager_List
  • Inbound_Mailer_Tokens
  • Inbound_Mailer_Tracking
  • Inbound_Mailer_Unsubscribe
  • Inbound_Mailer_Variations
  • Inbound_Mailer_WordPress_SEO
  • Inbound_Maintenance_Lists
  • Inbound_Marketing_Button
  • Inbound_Menus_Admin
  • Inbound_Menus_Adminbar
  • Inbound_Metaboxes_Automation
  • Inbound_Metaboxes_Leads
  • Inbound_Notifications
  • Inbound_Now_Store
  • Inbound_Options_API
  • Inbound_Pro_Activation
  • Inbound_Pro_Admin_Ajax_Listeners
  • Inbound_Pro_Automatic_Updates
  • Inbound_Pro_Downloads
  • Inbound_Pro_Notifications
  • Inbound_Pro_Oauth_Engine
  • Inbound_Pro_Plugin
  • Inbound_Pro_Settings
  • Inbound_Quick_View
  • Inbound_Reporting_Templates
  • Inbound_Search_And_Comment_Report
  • Inbound_Shared_ACF_BootStrap
  • Inbound_Shortcodes
  • Inbound_Shortcodes_Cookies
  • Inbound_Shortcodes_Fields
  • Inbound_SparkPost
  • Inbound_SparkPost_Stats
  • Inbound_Template_Utils
  • Inbound_Templating_Engine
  • Inbound_Tracking
  • Inbound_Translation_Updater
  • Inbound_Updater
  • Inbound_Upgrade_For_More_Reports
  • Inbound_Upgrade_Routines
  • Inbound_Visitor_Event_Report
  • Inbound_Visitor_Impressions_Report
  • Inbound_Visitors_Report
  • INBOUNDNOW_EXTEND
  • Landing_Pages_ACF
  • Landing_Pages_Activation
  • Landing_Pages_Activation_Update_Routines
  • Landing_Pages_Admin_Menus
  • Landing_Pages_Admin_Notices
  • Landing_Pages_Install
  • Landing_Pages_Load_Extensions
  • Landing_Pages_Meta
  • Landing_Pages_Metaboxes
  • Landing_Pages_Post_Type
  • Landing_Pages_Row_Actions
  • Landing_Pages_Settings
  • Landing_Pages_Sidebars
  • Landing_Pages_Split_Testing_Stats
  • Landing_Pages_Template_Management
  • Landing_Pages_Template_Switcher
  • Landing_Pages_Templates_List_Table
  • Landing_Pages_Variations
  • LandingPages_Welcome
  • Leads_Activation
  • Leads_Activation_Update_Routines
  • Leads_Admin_Notices
  • Leads_Batch_Processor
  • Leads_Branching
  • Leads_Dashboard
  • Leads_Field_Map
  • Leads_Manager
  • Leads_Post_Type
  • Leads_Settings
  • Leads_Tracking
  • Leads_User_Profile
  • LeadStorage
  • LP_EXTENSION_LICENSENING
  • LP_EXTENSION_UPDATER
  • LP_Variation_Rotation
  • LP_Widget_Conversion_Area

Functions

  • cta_check_active
  • cta_example_template_function
  • cta_load_dynamic_widget
  • CTA_Load_Extensions
  • cta_load_static_widget
  • CTA_Render
  • inbound_add_conversion_to_lead
  • inbound_automation_check_active
  • inbound_automation_load_definitions
  • inbound_automation_metaboxes
  • inbound_automation_processing
  • inbound_color
  • inbound_color_scheme
  • inbound_confirm_email_service_provider
  • inbound_email_kill_ie8
  • inbound_email_load_templates
  • inbound_form_add_lead_list
  • inbound_form_auto_publish
  • inbound_form_delete_transient
  • inbound_form_get_data
  • inbound_form_save
  • inbound_forms_change_columns
  • inbound_forms_cpt
  • inbound_forms_custom_columns
  • inbound_forms_default_content
  • inbound_get_form_names
  • inbound_get_parent_directory
  • inbound_Hex_2_RGB
  • inbound_inbound_email_example_template_function
  • inbound_load_lead_manager
  • inbound_load_token_engine
  • inbound_mailer_acf_integration
  • Inbound_Mailer_Common_Settings
  • Inbound_Mailer_Load_Templates
  • inbound_qtrans_disable
  • inbound_record_log
  • inbound_register_form_role_capabilities
  • inbound_shortcode_alert
  • inbound_shortcode_callout
  • inbound_shortcode_columns
  • inbound_shortcode_content_box
  • inbound_shortcode_divider
  • inbound_shortcode_empty_paragraph_fix
  • inbound_shortcode_four_fifth_columns
  • inbound_shortcode_full_columns
  • inbound_shortcode_gmap
  • inbound_shortcode_icon
  • inbound_shortcode_intro
  • inbound_shortcode_landing_pages
  • inbound_shortcode_leadp
  • inbound_shortcode_list_icons
  • inbound_shortcode_one_fifth_columns
  • inbound_shortcode_one_fourth_columns
  • inbound_shortcode_one_half_columns
  • inbound_shortcode_one_third_columns
  • inbound_shortcode_portfolio
  • inbound_shortcode_pricing
  • inbound_shortcode_profile
  • inbound_shortcode_social_links
  • inbound_shortcode_tabs
  • inbound_shortcode_teaser
  • inbound_shortcode_testimonial
  • inbound_shortcode_three_fifth_columns
  • inbound_shortcode_three_fourth_columns
  • inbound_shortcode_two_fifth_columns
  • inbound_shortcode_two_third_columns
  • inbound_shortcode_video
  • inbound_store_lead
  • inbound_template_brightness
  • inbound_template_color
  • Inbound_Templating_Engine
  • inbound_travis_check
  • inboundnow_add_master_license
  • json_encode_fallback
  • landingpage_fix_known_wp_title_isses
  • landingpages_is_active
  • load_CTA_Settings
  • load_CTA_Template_Manager
  • load_Inbound_API_Keys_Generation
  • load_Inbound_Lead_Statuses
  • load_Inbound_Leads_Custom_fields
  • load_inbound_mail_daemon
  • load_Inbound_Mailer_Settings
  • load_Inbound_Mailer_Template_Manager
  • load_Inbound_Pro_Downloads
  • lp_ab_testing_get_current_variation_id
  • lp_add_option
  • lp_body_class
  • lp_check_active
  • lp_content_area
  • lp_conversion_area
  • lp_discover_important_wrappers
  • lp_footer
  • lp_generate_drowndown
  • lp_get_parent_directory
  • lp_get_value
  • lp_global_config
  • lp_head
  • lp_in_admin_header
  • lp_init
  • lp_list_feature
  • lp_load_widgets
  • lp_main_headline
  • lp_manage_templates
  • lp_move_template_files
  • lp_rebuild_attributes
  • lp_templates_upload
  • mailer_check_active
  • wp_cta_check_active
  • wp_cta_kill_ie8
  • wp_cta_load_calls_to_action
  • wp_leads_get_page_final_id
  • wpl_url_to_postid
  • wpleads_add_lead_to_list
  • wpleads_check_active
  • wpleads_get_lead_lists_as_array
  • Overview
  • Package
  • Class
  1:   2:   3:   4:   5:   6:   7:   8:   9:  10:  11:  12:  13:  14:  15:  16:  17:  18:  19:  20:  21:  22:  23:  24:  25:  26:  27:  28:  29:  30:  31:  32:  33:  34:  35:  36:  37:  38:  39:  40:  41:  42:  43:  44:  45:  46:  47:  48:  49:  50:  51:  52:  53:  54:  55:  56:  57:  58:  59:  60:  61:  62:  63:  64:  65:  66:  67:  68:  69:  70:  71:  72:  73:  74:  75:  76:  77:  78:  79:  80:  81:  82:  83:  84:  85:  86:  87:  88:  89:  90:  91:  92:  93:  94:  95:  96:  97:  98:  99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: 168: 169: 170: 171: 172: 173: 174: 175: 176: 177: 178: 179: 180: 181: 182: 183: 184: 185: 186: 187: 188: 189: 190: 191: 192: 193: 194: 195: 196: 197: 198: 199: 200: 201: 202: 203: 204: 205: 206: 207: 208: 209: 210: 211: 212: 213: 214: 215: 216: 217: 218: 219: 220: 221: 222: 223: 224: 225: 226: 227: 228: 229: 230: 231: 232: 233: 234: 235: 236: 237: 238: 239: 240: 241: 242: 243: 244: 245: 246: 247: 248: 249: 250: 251: 252: 253: 254: 255: 256: 257: 258: 259: 260: 261: 262: 263: 264: 265: 266: 267: 268: 269: 270: 271: 272: 273: 274: 275: 276: 277: 278: 279: 280: 281: 282: 283: 284: 285: 286: 287: 288: 289: 290: 291: 292: 293: 294: 295: 296: 297: 298: 299: 300: 301: 302: 303: 304: 305: 306: 307: 308: 309: 310: 311: 312: 313: 314: 315: 316: 317: 318: 319: 320: 321: 322: 323: 324: 325: 326: 327: 328: 329: 330: 331: 332: 333: 334: 335: 336: 337: 338: 339: 340: 341: 342: 343: 344: 345: 346: 347: 348: 349: 350: 351: 352: 353: 354: 355: 356: 357: 358: 359: 360: 361: 362: 363: 364: 365: 366: 367: 368: 369: 370: 371: 372: 373: 374: 375: 376: 377: 378: 379: 380: 381: 382: 383: 384: 385: 386: 387: 388: 389: 390: 391: 392: 393: 394: 395: 396: 397: 398: 399: 400: 401: 402: 403: 404: 405: 406: 407: 408: 409: 410: 411: 412: 413: 414: 415: 416: 417: 418: 419: 420: 421: 422: 423: 424: 425: 426: 427: 428: 429: 430: 431: 432: 433: 434: 435: 436: 437: 438: 439: 440: 441: 442: 443: 444: 445: 446: 447: 448: 449: 450: 451: 452: 453: 454: 455: 456: 457: 458: 459: 460: 461: 462: 463: 464: 465: 466: 467: 468: 469: 470: 471: 472: 473: 474: 475: 476: 477: 478: 479: 480: 481: 482: 483: 484: 485: 486: 487: 488: 489: 490: 491: 492: 493: 494: 495: 496: 497: 498: 499: 500: 501: 502: 503: 504: 505: 506: 507: 508: 509: 510: 511: 512: 513: 514: 515: 516: 517: 518: 519: 520: 521: 522: 523: 524: 525: 526: 527: 528: 529: 530: 531: 532: 533: 534: 535: 536: 537: 538: 539: 540: 541: 542: 543: 544: 545: 546: 547: 548: 549: 550: 551: 552: 553: 554: 555: 556: 557: 558: 559: 560: 561: 562: 563: 564: 565: 566: 567: 568: 569: 570: 571: 572: 573: 574: 575: 576: 577: 578: 579: 580: 581: 582: 583: 584: 585: 586: 587: 588: 589: 590: 591: 592: 593: 594: 595: 596: 597: 598: 599: 600: 601: 602: 603: 604: 605: 606: 607: 608: 609: 610: 611: 612: 613: 614: 615: 616: 617: 618: 619: 620: 621: 622: 623: 624: 625: 626: 627: 628: 629: 630: 631: 632: 633: 634: 635: 636: 637: 638: 639: 640: 641: 642: 643: 644: 645: 646: 647: 648: 649: 650: 651: 652: 653: 654: 655: 656: 657: 658: 659: 660: 661: 662: 663: 664: 665: 666: 667: 668: 669: 670: 671: 672: 673: 674: 675: 676: 677: 678: 679: 680: 681: 682: 683: 684: 685: 686: 687: 688: 689: 690: 691: 692: 693: 694: 695: 696: 697: 698: 699: 700: 701: 702: 703: 704: 705: 706: 707: 708: 709: 710: 711: 712: 713: 714: 715: 716: 717: 718: 719: 720: 721: 722: 723: 724: 725: 726: 727: 728: 729: 730: 731: 732: 733: 734: 735: 736: 737: 738: 739: 740: 741: 742: 743: 744: 745: 746: 747: 748: 749: 750: 751: 752: 753: 754: 755: 756: 757: 758: 759: 760: 761: 762: 763: 764: 765: 766: 767: 768: 769: 770: 771: 772: 773: 774: 775: 776: 777: 778: 779: 780: 781: 782: 783: 784: 785: 786: 787: 788: 789: 790: 791: 792: 793: 794: 795: 796: 797: 798: 799: 800: 801: 802: 803: 804: 805: 806: 807: 808: 809: 810: 811: 812: 813: 814: 815: 816: 817: 818: 819: 820: 821: 822: 823: 824: 825: 826: 827: 828: 829: 830: 831: 832: 833: 834: 835: 836: 837: 838: 839: 840: 841: 842: 843: 844: 845: 846: 847: 848: 849: 850: 851: 852: 853: 854: 855: 856: 857: 858: 859: 860: 861: 862: 863: 864: 865: 866: 867: 868: 869: 870: 871: 872: 873: 874: 875: 876: 877: 878: 879: 880: 881: 882: 883: 884: 885: 886: 887: 888: 889: 890: 891: 892: 893: 894: 895: 896: 897: 898: 899: 900: 901: 902: 903: 904: 905: 906: 907: 908: 909: 910: 911: 912: 913: 914: 915: 916: 917: 918: 919: 920: 921: 922: 923: 924: 925: 926: 927: 928: 929: 930: 931: 932: 933: 934: 935: 936: 937: 938: 939: 940: 941: 942: 943: 944: 945: 946: 947: 948: 949: 950: 951: 952: 953: 954: 955: 956: 957: 958: 959: 960: 961: 962: 963: 964: 965: 966: 967: 968: 969: 970: 971: 972: 973: 974: 975: 976: 977: 978: 979: 980: 981: 982: 983: 984: 
<?php

/**
 * Class Inbound_Mailer_Direct_Email_Leads extends lead profile with statistic reports and direct email capabilities
 * @package Mailer
 * @subpackage Leads
 */
class Inbound_Mailer_Direct_Email_Leads {
    static $range;

    /**
     * Inbound_Mailer_Direct_Email_Leads constructor.
     */
    public function __construct() {
        self::add_hooks();
    }

    /**
     *
     */
    public static function add_hooks() {
        /*get the mail service settings*/
        $settings = Inbound_Mailer_Settings::get_settings();


        /*Add the "Email Lead" tab to the edit lead list of tabs*/
        add_filter('wpl_lead_tabs', array(__CLASS__, 'add_direct_email_tab'), 10, 1);

        /*Add the contents to the "Email Lead" tab*/
        add_action('wpl_print_lead_tab_sections', array(__CLASS__, 'add_direct_email_tab_contents'));

        /*Add ajax listener for populating the address headers when a premade template is selected*/
        add_action('wp_ajax_get_addressing_settings', array(__CLASS__, 'ajax_get_addressing_settings'));

        /*Add ajax listener for sending the email*/
        add_action('wp_ajax_send_email_to_lead', array(__CLASS__, 'ajax_send_email_to_lead'));

        /*Adds direct messages to quick stats */
        add_action('wpleads_display_quick_stat', array(__CLASS__, 'display_quick_stat_direct_messages') , 20 , 1);

        /*Adds direct messages to quick stats */
        add_action('wpleads_display_quick_stat', array(__CLASS__, 'display_quick_stat_unsubscribes') , 20 , 1);

        /*Adds email clicks to quick stats */
        add_action('wpleads_display_quick_stat', array(__CLASS__, 'display_quick_stat_email_clicks') , 20 , 1 );

        /*Adds email opens to quick stats */
        add_action('wpleads_display_quick_stat', array(__CLASS__, 'display_quick_stat_email_opens') , 20 , 1 );

        /*Adds email opens to quick stats */
        add_action('wpleads_display_quick_stat', array(__CLASS__, 'display_quick_stat_email_bounces') , 20 , 1 );

    }

    /**
     * @param $tabs
     * @return mixed
     */
    public static function add_direct_email_tab($tabs) {
        $args = array(
            'id' => 'wpleads_lead_tab_direct_email',
            'label' => __('Direct Email', 'inbound-pro')
        );

        array_push($tabs, $args);

        return $tabs;
    }

    /**
     *
     */
    public static function add_direct_email_tab_contents() {
        global $post;


        /* Enqueue Sweet Alert support  */
        wp_enqueue_script('sweet-alert-js', INBOUND_EMAIL_URLPATH . 'assets/libraries/SweetAlert/sweet-alert.js');
        wp_enqueue_style('sweet-alert-css', INBOUND_EMAIL_URLPATH . 'assets/libraries/SweetAlert/sweet-alert.css');


        /*get the email address we're sending to*/
        $recipient_email_addr = Leads_Field_Map::get_field($post->ID, 'wpleads_email_address');

        /*get all the "automated" emails*/
        $email_templates = get_posts(array(
            'numberposts' => -1,
            'post_status' => 'automated',
            'post_type' => 'inbound-email',
        ));

        /*get the current user*/
        $user = wp_get_current_user();

        /*get the current user's email*/
        $parts = explode('@', $user->data->user_email );
        $user_email = $parts[0];

        /*get the mail service settings*/
        $inbound_settings = Inbound_Mailer_Settings::get_settings();

        /***setup the sending domains dropdown***/
        /*get the available Sparkpost sending domains*/
        if($inbound_settings['mail-service'] == 'sparkpost' ){
            $sparkpost = new Inbound_SparkPost(  $inbound_settings['sparkpost-key'] );
            $domain_query = $sparkpost->get_domains();
            /*if there are no errors*/
            if(!isset($domain_query['errors']) && empty($domain_query['errors'])){
                if (count($domain_query['results']) <1 ) {
                    $sending_dropdown = '<option value="null">' . __('No Domains Detected', 'inbound-pro') . '</option>';
                } else {
                    $sending_dropdown = '';
                }

                foreach($domain_query as $domains){
                    foreach($domains as $domain){
                        /*if the sending domain is owned, or has DKIM or SPF setup*/
                        if($domain['status']['ownership_verified'] == 1 || $domain['status']['spf_status'] == 'valid' || $domain['status']['dkim_status'] == 'valid'){

                            /*if the user's email is hosted on a verified sending domain*/
                            if(substr($user->email, strpos($user->email, '@') +1) == $domain['domain']){

                                /*set that domain as the selected one for the domain selector dropdown*/
                                $sending_dropdown .= '<option value="' . '@' . $domain['domain'] . '" selected="selected">' . '@' . $domain['domain'] . '</option>';

                            }else{

                                $sending_dropdown .= '<option value="' . '@' . $domain['domain'] . '">' . '@' . $domain['domain'] . '</option>';

                            }
                        }
                    }
                }
                $sending_dropdown .= '<option value="">' . __('Type out full address', 'inbound-pro') . '</option>';
                echo '<select id="sending-domain-selector" class="form-control">'.$sending_dropdown.'</select>';
            }else{

            }
        }

        /*put the email ids and names in an array for use in the email dropdown selector*/
        $template_id_and_name = array();
        foreach ($email_templates as $email_template) {
            $template_id_and_name[$email_template->ID] = $email_template->post_title;
        }


        /*these are the fields in the "Email Lead" tab*/
        $custom_fields = array(
            'use_premade_template' => array(
                'label' => __('Use template?', 'inbound-pro'),
                'description' => __('Use this to choose whether to send a custom or a premade email', 'inbound-pro'),
                'id' => 'premade_template_chooser',
                'type' => 'dropdown',
                'default' => '0',
                'class' => 'premade_template_chooser',
                'options' => array('0' => 'No', '1' => 'Yes'),
            ),
            'subject' => array(
                'description' => __('Subject line of the email. This field is variation dependant!', 'inbound-pro'),
                'label' => __('Subject', 'inbound-pro'),
                'id' => 'subject',
                'type' => 'text',
                'default' => '',
                'class' => 'direct_email_lead_field',
            ),
            'from_name' => array(
                'label' => __('From Name', 'inbound-pro'),
                'description' => __('The name of the sender. This field is variation dependant!', 'inbound-pro'),
                'id' => 'from_name',
                'type' => 'text',
                'default' => $user->display_name,
                'class' => 'direct_email_lead_field',
            ),
            'from_email' => array(
                'label' => __('From Email', 'inbound-pro'),
                'description' => __('The email address of the sender. This field is variation dependant!', 'inbound-pro'),
                'id' => 'from_email',
                'type' => 'text',
                'default' => $user_email,
                'class' => 'direct_email_lead_field',
            ),
            'reply_email' => array(
                'label' => __('Reply Email', 'inbound-pro'),
                'description' => __('The email address recipients can reply to. This field is variation dependant!', 'inbound-pro'),
                'id' => 'reply_email',
                'type' => 'text',
                'default' => $user->user_email,
                'class' => 'direct_email_lead_field',
            ),
            'recipient_email_address' => array(
                'label' => __('Recipient', 'inbound-pro'),
                'description' => __('The email address of the recipient.', 'inbound-pro'),
                'id' => 'recipient_email_address',
                'type' => 'text',
                'default' => $recipient_email_addr,
                'class' => '',
            ),
            'email_message_box' => array(
                'label' => __('Message', 'inbound-pro'),
                'description' => __('Use this editor to create a short custom email messages', 'inbound-pro'),
                'id' => 'email_message_box',
                'type' => 'wysiwyg',
                'default' => __('Email content goes in here. You may want to send yourself one to see how it looks.', 'inbound-pro'),
                'class' => 'email_message_box',
                'disable_variants' => '1',
            ),
            'premade_email_templates' => array(
                'label' => __('Select Template', 'inbound-pro'),
                'description' => __('Use this to select which premade email to use.', 'inbound-pro'),
                'id' => 'premade_template_selector',
                'type' => 'dropdown',
                'default' => '0',
                'class' => 'premade_template_selector',
                'options' => $template_id_and_name,
            ),
            'email_variation' => array(
                'label' => __('Choose varation', 'inbound-pro'),
                'description' => __('Use this to select which variation of the premade email to use.', 'inbound-pro'),
                'id' => 'email_variation_selector',
                'type' => 'dropdown',
                'default' => '0',
                'class' => 'email_variation_selector',
                'options' => array('0' => 'A'),
            )
        );

        ?>


        <div class="lead-profile-section" id="wpleads_lead_tab_direct_email">
            <?php

            Inbound_Mailer_Metaboxes::render_settings('inbound-email', $custom_fields, $post);
            Inbound_Metaboxes_Leads::display_profile_image();
            ?>


            <button id="send-email-button" type="button" style="">
                <?php _e('Send Email', 'inbound-pro'); ?>
                <i class="fa fa-envelope" aria-hidden="true"></i>
            </button>
        </div>
        </div>


        <script>
            jQuery(document).ready(function () {
                var variationSettings;
                var sendingDomainSelector = jQuery('#sending-domain-selector').remove();

                /*page load actions*/
                jQuery('.premade_template_selector').css('display', 'none');
                jQuery('.email_variation_selector').css('visibility', 'hidden');
                jQuery('.inbound-tooltip').css('display', 'none');
                jQuery('.open-marketing-button-popup.inbound-marketing-button.button, a.button.lead-fields-button').css('display', 'none');

                if(jQuery(sendingDomainSelector).val() != undefined){
                    jQuery('.from_email > .inbound-email-option-td.inbound-meta-box-option.inbound-text-option').append(sendingDomainSelector);
                    jQuery('input#from_email').css({'width' : '34%'});
                }

                jQuery('#premade_template_chooser').on('change', function () {
                    if (jQuery('#premade_template_chooser').val() == 1) {
                        jQuery('div.email_message_box.inbound-wysiwyg-row.div-email_message_box.inbound-email-option-row.inbound-meta-box-row').css('display', 'none');
                        jQuery('.premade_template_selector, .email_variation_selector').css('display', 'block');
                        jQuery('.direct_email_lead_field, .div-direct_email_lead_field').css('display', 'none');
                    } else {
                        jQuery('div.email_message_box.inbound-wysiwyg-row.div-email_message_box.inbound-email-option-row.inbound-meta-box-row').css('display', 'block');
                        jQuery('.premade_template_selector, .email_variation_selector').css('display', 'none');
                        jQuery('.direct_email_lead_field, .div-direct_email_lead_field').css('display', '');
                    }

                });

                jQuery('#premade_template_selector').on('change', function () {
                    var id = jQuery('#premade_template_selector').val();
                    console.log(id);
                    jQuery.ajax({
                        type: 'POST',
                        url: ajaxurl,
                        data: {
                            action: 'get_addressing_settings',
                            email_id: id,

                        },
                        success: function (response) {
                            response = JSON.parse(response);
                            //                  console.log(response);
                            variationSettings = response.variations;
                            //                  console.log(variationSettings);

                            jQuery('#email_variation_selector').find('option').remove();
                            if (variationSettings.length > 1) {
                                var alphabetObject = {
                                    0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E',
                                    5: 'F', 6: 'G', 7: 'H', 8: 'I', 9: 'J',
                                    10: 'K', 11: 'L', 12: 'M', 13: 'N', 14: 'O',
                                    15: 'P', 16: 'Q', 17: 'R', 18: 'S', 19: 'T',
                                    20: 'U', 21: 'V', 22: 'W', 23: 'X', 24: 'Y',
                                    25: 'Z',
                                }
                                console.log(variationSettings.length);

                                for (var index = 0; index < variationSettings.length; index++) {
                                    jQuery('#email_variation_selector').append('<option value="' + index + '">' + alphabetObject[index] + '</option>');
                                }

                                jQuery('.email_variation_selector').css('visibility', 'visible');

                            } else {
                                jQuery('#email_variation_selector').append('<option value="0">A</option>');
                                jQuery('.email_variation_selector').css('visibility', 'hidden');
                            }

                        },
                        error: function (MLHttpRequest, textStatus, errorThrown) {
                            alert("<?php _e('Ajax not enabled', 'inbound-pro'); ?>");
                        },
                    });

                });

                /*Send the email*/
                jQuery('#send-email-button').on('click', function () {
                    var postId = <?php echo $post->ID; ?>;
                    var userId = <?php echo $user->ID; ?>;
                    var subject = jQuery('#subject').val();
                    var fromName = jQuery('#from_name').val();
                    var sendingDomain = (jQuery('#sending-domain-selector').val() != undefined) ? jQuery('#sending-domain-selector').val() : '';
                    var fromEmail = jQuery('#from_email').val() + sendingDomain;
                    var replyEmail = jQuery('#reply_email').val();
                    var emailContent = get_tinymce_content();
                    var recipientEmail = jQuery('#recipient_email_address').val();
                    var usePremadeTemplate = jQuery('#premade_template_chooser').val();
                    var isPremadeTemplate = jQuery('#premade_template_chooser').val();
                    var premadeEmailId = jQuery('#premade_template_selector').val();
                    var variationSelected = jQuery('#email_variation_selector').val();

                    swal({
                        title: "<?php _e('Please wait', 'inbound-pro'); ?>",
                        text: "<?php _e('We are sending your email now.', 'inbound-pro'); ?>",
                        imageUrl: '<?php echo INBOUND_EMAIL_URLPATH; ?>/assets/images/loading_colorful.gif'
                    });


                    jQuery.ajax({
                        type: 'POST',
                        url: ajaxurl,
                        data: {
                            action: 'send_email_to_lead',
                            post_id: postId,
                            user_id: userId,
                            subject: subject,
                            from_name: fromName,
                            from_email: fromEmail,
                            reply_email: replyEmail,
                            email_content: emailContent,
                            recipient_email: recipientEmail,
                            use_premade_template: usePremadeTemplate,
                            is_premade_template: isPremadeTemplate,
                            premade_email_id: premadeEmailId,
                            variation_selected: variationSelected
                        },

                        success: function (response) {
                            response = JSON.parse(response);
                            console.log(response);

                            /**error check**/
                            /*if it's a basic error, like a field isn't filled in*/
                            if (response.basic_error) {
                                swal({
                                    title: response.title,
                                    text: response.basic_error,
                                    type: 'error',
                                });
                                return false;
                            }

                            /*if it's a system error, like some data wasn't supplied*/
                            if (response.system_error) {
                                swal({
                                    title: response.title,
                                    text: response.system_error,
                                    type: 'error',
                                });
                                return false;
                            }

                            /*if it's a Sparkpost error, like some data wasn't supplied*/
                            console.log(response);
                            if (response.errors) {
                                swal({
                                    title: response.errors[0].message,
                                    text: response.errors[0].description,
                                    type: 'error',
                                });
                                return false;
                            }


                            /*...no errors? THEN SUCCESS!*/
                            if (response.success) {
                                swal({
                                    title: response.title,
                                    text: response.success,
                                    type: 'success',
                                });
                                return false;
                            }

                            alert(response);
                            jQuery('.confirm').click();


                        },
                        error: function (MLHttpRequest, textStatus, errorThrown) {
                            alert("<?php _e('Ajax not enabled', 'inbound-pro'); ?>");
                        },


                    });
                });


                function get_tinymce_content() {
                    if (jQuery('#wp-inbound_email_message_box-wrap').hasClass('tmce-active')) {
                        return tinyMCE.activeEditor.getContent();

                    } else {
                        return jQuery('textarea.email_message_box').val();
                    }
                }

            });
        </script>
        <style type="text/css">
           #wpleads_lead_tab_direct_email #show-hidden-fields, #wpleads_lead_tab_direct_email #show-edit-user {
               display:none;
           }
           #wpleads_lead_tab_direct_email .form-table {
               float:right;
               width:70%;
           }
           #wpleads_lead_tab_direct_email .inbound-meta-box-label {
               width:98px;
           }

           #wpleads_lead_tab_direct_email #send-email-button {
                text-align:center;
                margin-left:auto;
                margin-right:auto;
                width:100%;
                padding:10px;
                cursor:pointer
           }

           #wpleads_lead_tab_direct_email #sending-domain-selector{
               width: 45%;
               display: inherit;
               padding: 2px;
               height: 33px;
               vertical-align: top;
            }

           #wpleads_lead_tab_direct_email .direct_email_lead_field {
               display:inherit;
           }

           #wpleads_lead_tab_direct_email #left-sidebar {
               width:20%;
           }

           .email_message_box .inbound-wysiwyg-option {
               display:table-row-group;
           }
        </style>

        <?php
    }


    /**
     * Determines if automation email has variations.
     * echos
     */
    public static function ajax_get_addressing_settings() {
        if (isset($_POST['email_id']) && !empty($_POST['email_id'])) {

            $id = intval($_POST['email_id']);
            $email_settings = Inbound_Email_Meta::get_settings($id);
            echo json_encode($email_settings);
        }
        die();

    }


    /**
     *
     */
    public static function ajax_send_email_to_lead() {

        /*if the email is a premade auto one, make sure the info is provided to send it and send it*/
        if ($_POST['use_premade_template'] == '1') {
            self::send_automated_email_to_lead();
        } else {
            self::send_direct_message_to_lead();
        }

    }

    /**
     * Sends an pre-fabricated automated email to the lead
     */
    public static function send_automated_email_to_lead() {
        /*make sure the settings have been supplied*/
        if (empty($_POST['post_id']) && $_POST['post_id'] != '0') {
            echo json_encode(array('system_error' => __('The lead id was not supplied', 'inbound-pro'), 'title' => __('System Error:', 'inbound-pro')));
            die();
        }
        if (empty($_POST['recipient_email']) || !is_email($_POST['recipient_email'])) {
            echo json_encode(array('basic_error' => __('There\'s an error with the recipient email', 'inbound-pro'), 'title' => __('Field Error:', 'inbound-pro')));
            die();
        }
        if (empty($_POST['premade_email_id']) && $_POST['premade_email_id'] != '0') {
            echo json_encode(array('system_error' => __('The email template id was not supplied', 'inbound-pro'), 'title' => __('System Error:', 'inbound-pro')));
            die();
        }
        if (empty($_POST['variation_selected']) && $_POST['variation_selected'] != '0') {
            echo json_encode(array('system_error' => __('The variation id was not supplied', 'inbound-pro'), 'title' => __('System Error:', 'inbound-pro')));
            die();
        }

        $post_id = intval($_POST['post_id']);
        $recipient_email = sanitize_text_field($_POST['recipient_email']);
        $premade_email_id = intval($_POST['premade_email_id']);
        $variation_selected = intval($_POST['variation_selected']);

        /*sending args*/
        $args = array(
            'email_address' => $recipient_email,
            'email_id' => $premade_email_id,
            'vid' => $variation_selected,
            'lead_id' => $post_id,
            'is_test' => 0,
            'tags' => array('direct-email')
        );

        /*send the email!*/
        Inbound_Mail_Daemon::send_solo_email($args);
        echo json_encode(array('success' => __('Your email has been sent!', 'inbound-pro'), 'title' => __('SUCCESS!', 'inbound-pro')));
        die();
    }

    /**
     *
     */
    public static function send_direct_message_to_lead() {


        /* these are the variables set by the user */
        $data = array(
            'subject' => array(
                'label' => __('Subject', 'inbound-pro'),
                'value' => sanitize_text_field($_POST['subject'])
            ),
            'from_name' => array(
                'label' => __('From Name', 'inbound-pro'),
                'value' => sanitize_text_field($_POST['from_name'])
            ),
            'from_email' => array(
                'label' => __('From Email', 'inbound-pro'),
                'value' => sanitize_text_field($_POST['from_email'])
            ),
            'reply_email' => array(
                'label' => __('Reply Email', 'inbound-pro'),
                'value' => sanitize_text_field($_POST['reply_email'])
            ),
            'recipient_email' => array(
                'label' => __('Recipeient Email', 'inbound-pro'),
                'value' => sanitize_text_field($_POST['recipient_email'])
            ),
            'email_content' => array(
                'label' => __('Email Content', 'inbound-pro'),
                'value' => stripslashes($_POST['email_content'])
            )
        );

        /*check to make sure the variables are set*/
        foreach ($data as $key => $value) {
            if (empty($value['value'])) {
                echo json_encode(array('basic_error' => __('Please fill in the ' . $value['label'], 'inbound-pro'), 'title' => __('Empty field', 'inbound-pro')));
                die();
            }

        }

        /* sanitise hidden values */
        $data['post_id'] = (int) $_POST['post_id'];
        $data['lead_id'] = (int) $_POST['post_id'];
        $data['user_id'] = (int) $_POST['user_id'];

        /*check to make sure the email addresses are setup correctly*/
        if (!is_email($data['recipient_email']['value'])) {
            echo json_encode(array('basic_error' => __('There\'s an error with the Recipient Email Address', 'inbound-pro'), 'title' => __('Field Error:', 'inbound-pro')));
            die();
        }

        if (!is_email($data['from_email']['value'])) {
            echo json_encode(array('basic_error' => __('There\'s an error with the From Email', 'inbound-pro'), 'title' => __('Field Error:', 'inbound-pro')));
            die();
        }

        if (!is_email($data['reply_email']['value']) && !strstr($data['reply_email']['value'] , '[') && !strstr($data['reply_email']['value'] ,'%') ) {
            echo json_encode(array('basic_error' => __('There\'s an error with the Reply Email', 'inbound-pro'), 'title' => __('Field Error:', 'inbound-pro')));
            die();
        }

        /*check to make sure the post and user ids have been supplied*/
        if (empty($data['post_id'])) {
            echo json_encode(array('system_error' => __('The post id was not supplied', 'inbound-pro'), 'title' => __('System Error:', 'inbound-pro')));
            die();
        }
        if (empty($data['user_id'])) {
            echo json_encode(array('system_error' => __('The user id was not supplied', 'inbound-pro'), 'title' => __('System Error:', 'inbound-pro')));
            die();
        }


        /*get the current time according to the wp format*/
        $timezone = get_option('timezone_string' , 'EST');
        $timezone = ($timezone) ? $timezone : 'EST';
        $time = new DateTime('', new DateTimeZone($timezone));
        $format = get_option('date_format') . ' \a\t ' . get_option('time_format');


        /* sanitize email content */
        $data['email_content']['value'] = strip_tags( $data['email_content']['value'],'<br><i><b><strong><div><span><h1><h2><h3><h4><table><tr><td><tbody><a><img><p><ol><li>');

        /* prepare content with tracked links */
        $data['email_content']['value'] = self::rebuild_links( $data['email_content']['value'] , $data );

        /*assemble the post data*/
        $direct_email = array(
            'post_title' => __('Direct email to ', 'inbound-pro') . $data['recipient_email']['value'] . __(' on ', 'inbound-pro') . $time->format($format),
            'post_content' => wpautop($data['email_content']['value']),
            'post_status' => 'direct_email',
            'post_author' => $data['user_id'],
            'post_type' => 'inbound-email',
        );

        /*create the email*/
        $data['direct_email_id'] = wp_insert_post($direct_email);

        /* assemble the settings mailer uses for sending the email */
        $mailer_settings = array(
            'variations' => array(
                0 => array(
                    'selected_template' => '',
                    'user_ID' => $data['user_id'],
                    'subject' => $data['subject']['value'],
                    'from_name' => $data['from_name']['value'],
                    'from_email' => $data['from_email']['value'],
                    'reply_email' => $data['reply_email']['value'],
                    'variation_status' => 'active',
                ),
            ),
            'email_type' => 'direct',
        );

        /*add the settings to the email*/
        Inbound_Email_Meta::update_settings($data['direct_email_id'], $mailer_settings);

        /*sending args*/
        $args = array(
            'email_address' => $data['recipient_email']['value'],
            'email_id' => $data['direct_email_id'],
            'vid' => 0,
            'lead_id' => $data['post_id'],
            'is_test' => 0,
            'is_direct' => true,
            'tags' => array('direct-email')
        );

        /*and send*/
        $response = Inbound_Mail_Daemon::send_solo_email($args);
        $repsonse = wp_remote_retrieve_body( $response );


        if (isset($response['errors'])) {
            wp_delete_post($data['direct_email_id'], true);
            echo json_encode($response);
        } else {
            echo json_encode(array('success' => __('Your custom email has been sent!', 'inbound-pro'), 'title' => __('SUCCESS!', 'inbound-pro')));
            $data['response'] = $response;
            self::store_direct_mail_event( $data );
        }

        //      echo json_encode(error_get_last()); //debug
        die();
    }

    /**
     * @param $data
     */
    public static function store_direct_mail_event( $data ) {
        /* recipients */
        $args = array(
            'event_name' => 'inbound_direct_message',
            'email_id' => $data['direct_email_id'],
            'variation_id' =>  0,
            'form_id' => 0,
            'lead_id' => $data['post_id'],
            'event_details' => json_encode($data)
        );

        Inbound_Events::store_event($args);
    }

    /**
     * Adds Inbound Form Submissions to Quick Stat Box
     */
    public static function display_quick_stat_direct_messages($post) {
        global $post;
        if (!isset($_REQUEST['range'])) {
            self::$range = 90;
        } else {
            self::$range = intval($_REQUEST['range']);
        }
        ?>
        <div class="quick-stat-label">
            <div class="label_1"><?php _e('Direct E-Mails', 'inbound-pro'); ?>:</div>
            <div class="label_2">
                <?php
                if (class_exists('Inbound_Analytics')) {
                    ?>
                    <a href='<?php echo admin_url('index.php?action=inbound_generate_report&lead_id='.$post->ID.'&class=Inbound_Event_Report&event_name=inbound_direct_message&range=10000&tb_hide_nav=true&TB_iframe=true&width=1000&height=600'); ?>' class='thickbox inbound-thickbox'>
                        <?php echo self::get_direct_mail_count($post->ID); ?>
                    </a>
                    <?php
                } else {
                    echo self::get_direct_mail_count($post->ID);
                }
                ?>
            </div>
            <div class="clearfix"></div>
        </div>
        <?php
    }

    /**
     * Adds Inbound Form Submissions to Quick Stat Box
     */
    public static function display_quick_stat_unsubscribes($post) {
        global $post;
        ?>
        <div class="quick-stat-label">
            <div class="label_1"><?php _e('Unsubscribes', 'inbound-pro'); ?>:</div>
            <div class="label_2">
                <?php
                if (class_exists('Inbound_Analytics')) {
                    ?>
                    <a href='<?php echo admin_url('index.php?action=inbound_generate_report&lead_id='.$post->ID.'&class=Inbound_Event_Report&event_name=inbound_unsubscribe&range='.self::$range.'&tb_hide_nav=true&TB_iframe=true&width=1000&height=600'); ?>' class='thickbox inbound-thickbox'>
                        <?php echo self::get_unsubscribes_count($post->ID); ?>
                    </a>
                    <?php
                } else {
                    echo self::get_unsubscribes_count($post->ID);
                }
                ?>
            </div>
            <div class="clearfix"></div>
        </div>
        <?php
    }


    /**
     * Adds a quick stat form email clicks to the Quick Stats box
     */
    public static function display_quick_stat_email_clicks() {
        global $post;

        /* get daily action counts for chart 1 */
        $params = array(
            'lead_id' => $post->ID,
            'event_name' => 'sparkpost_click'
        );
        $click_events = Inbound_Events::get_events($params);


        ?>
        <div  class="quick-stat-label">
            <div class="label_1">
                <?php _e('Email Clicks', 'inbound-pro'); ?>
            </div>
            <div class="label_2">
                <?php
                if (class_exists('Inbound_Analytics')) {
                    ?>
                    <a href='<?php echo admin_url('index.php?action=inbound_generate_report&lead_id='.$post->ID.'&class=Inbound_Event_Report&event_name=sparkpost_click&range='.self::$range.'&title='.__('Email Clicks' , 'inbound-pro').'&tb_hide_nav=true&TB_iframe=true&width=1000&height=600'); ?>' class='thickbox inbound-thickbox'>
                        <?php echo count($click_events); ?>
                    </a>
                    <?php
                } else {
                    echo count($click_events);
                }
                ?>
            </div>
            <div class="clearfix"></div>
        </div>
        <?php

    }

    /**
     * Adds a quick stat form email clicks to the Quick Stats box
     */
    public static function display_quick_stat_email_opens() {
        global $post;

        /* get daily action counts for chart 1 */
        $params = array(
            'lead_id' => $post->ID,
            'event_name' => 'sparkpost_open'
        );
        $opens = Inbound_Events::get_events($params);


        ?>
        <div  class="quick-stat-label">
            <div class="label_1">
                <?php _e('Email Opens', 'inbound-pro'); ?>
            </div>
            <div class="label_2">
                <?php
                if (class_exists('Inbound_Analytics')) {
                    ?>
                    <a href='<?php echo admin_url('index.php?action=inbound_generate_report&lead_id='.$post->ID.'&class=Inbound_Event_Report&event_name=sparkpost_open&range='.self::$range.'&title='.__('Email Opens' , 'inbound-pro').'&tb_hide_nav=true&TB_iframe=true&width=1000&height=600'); ?>' class='thickbox inbound-thickbox'>
                        <?php echo count($opens); ?>
                    </a>
                    <?php
                } else {
                    echo count($opens);
                }
                ?>
            </div>
            <div class="clearfix"></div>
        </div>
        <?php

    }

    /**
     * Adds a quick stat form email clicks to the Quick Stats box
     */
    public static function display_quick_stat_email_bounces() {
        global $post;

        /* get daily action counts for chart 1 */
        $params = array(
            'lead_id' => $post->ID,
            'event_name' => 'sparkpost_bounce'
        );

        $bounces = Inbound_Events::get_events($params);


        ?>
        <div  class="quick-stat-label">
            <div class="label_1">
                <?php _e('Email Bounces', 'inbound-pro'); ?>
            </div>
            <div class="label_2">
                <?php
                if (class_exists('Inbound_Analytics')) {
                    ?>
                    <a href='<?php echo admin_url('index.php?action=inbound_generate_report&lead_id='.$post->ID.'&class=Inbound_Event_Report&event_name=sparkpost_bounce&title='.__('SparkPost Bounces' , 'inbound-pro') .'&range='.self::$range.'&tb_hide_nav=true&TB_iframe=true&width=1000&height=600'); ?>' class='thickbox inbound-thickbox'>
                        <?php echo count($bounces); ?>
                    </a>
                    <?php
                } else {
                    echo count($opens);
                }
                ?>
            </div>
            <div class="clearfix"></div>
        </div>
        <?php

    }

    /**
     * Gets number of direct mail messages sent to lead
     */
    public static function get_direct_mail_count( $lead_id  ){
        global $wpdb;

        $table_name = $wpdb->prefix . "inbound_events";

        $query = 'SELECT count(*) FROM '.$table_name.' WHERE `lead_id` = "'.$lead_id.'"';

        $query .= 'AND `event_name` = "inbound_direct_message"';

        $count = $wpdb->get_var( $query , 0, 0 );

        /* return null if nothing there */
        return ($count) ? $count : 0;
    }

    /**
     * Gets number of direct mail messages sent to lead
     */
    public static function get_unsubscribes_count( $lead_id  ){
        global $wpdb;

        $table_name = $wpdb->prefix . "inbound_events";

        $query = 'SELECT count(*) FROM '.$table_name.' WHERE `lead_id` = "'.$lead_id.'"';

        $query .= 'AND `event_name` = "inbound_unsubscribe"';

        $count = $wpdb->get_var( $query , 0, 0 );

        /* return null if nothing there */
        return ($count) ? $count : 0;
    }

    /**
     *    Rebuild links with tracking params
     */
    public static function rebuild_links($html , $data ) {
        preg_match_all('/href="([^\s"]+)/', $html, $links);

        if (!$links) {
            return $html;
        }

        /* Iterate over the extracted links and display their URLs */
        foreach ($links[1] as $link) {

            /* Do not modify unsubscribe links or non links */
            if (strstr($link, '?token=') || !strstr($link, '://')) {
                continue;
            }

            $safe_link = Inbound_API::analytics_track_links(array(
                'email_id' => '',
                'lead_lists' => '',
                'id' => $data['lead_id'],
                'lead_id' => $data['lead_id'],
                'page_id' => $data['lead_id'],
                'vid' =>0,
                'url' => $link,
                'utm_source' => urlencode($data['subject']['value']),
                'utm_medium' => 'email',
                'utm_campaign' => '',
                'tracking_id' => urlencode($data['subject']['value'])
            ));

            $html = str_replace("'" . $link . "'", "'" . $safe_link['url'] . "'", $html);
            $html = str_replace('"' . $link . '"', '"' . $safe_link['url'] . '"', $html);

        }

        return $html;
    }
}


add_action('admin_init', 'inbound_confirm_email_service_provider');
/**
 *    Only load Inbound_Mailer_Direct_Email_Leads if an email service provider has been selected
 */
function inbound_confirm_email_service_provider() {
    $email_settings = Inbound_Mailer_Settings::get_settings();
    if (isset($email_settings['mail-service']) && $email_settings['mail-service'] != 'none' ) {
        new Inbound_Mailer_Direct_Email_Leads;
    }
}

Inbound Pro Plugin - PHP Codex API documentation generated by ApiGen