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: 
<?php

/**
 * Class Inbound_Mail_Daemon provides cronjob daemon for reading `inbound_email_queue` and processing sends.
 * @package Mailer
 * @subpackage Sending
 */
class Inbound_Mail_Daemon {

    static $table_name; /* name of the mysql table we use for querying queued emails */
    static $email_service; /* number of emails we send during a processing job  (wp_mail only) */
    static $send_limit; /* number of emails we send during a processing job (wp_mail only) */
    static $thread_limit; /* number of emails we send during a processing job   (wp_mail only) */
    static $timestamp; /* the current date time in ISO 8601 gmdate() */
    static $dom; /* reusable object for parsing html for link modification */
    static $row; /* current mysql row object being processed */
    static $email_settings; /* settings array of the email being processed */
    static $templates; /* array of html templates for processing */
    static $tags; /* array of html templates for processing */
    static $email; /* arg array of email being processed */
    static $results; /* results from sql query */
    static $response; /* return result after send */
    static $error_mode; /* detects if there is an error flag already in the data base */
    static $last; /* time measurement */
    static $first; /* time measurement */

    /**
     *    Initialize class
     */
    function __construct() {

        /* Load static vars */
        self::load_static_vars();

        /* Load hooks */
        self::load_hooks();

    }

    /**
     *    Loads static variables
     */
    public static function load_static_vars() {
        global $wpdb, $inbound_settings;

        /* Set email service */
        self::$email_service = (isset($inbound_settings['mailer']['mail-service'])) ? $inbound_settings['mailer']['mail-service'] : 'sparkpost';

        /* Set send limit */
        self::$send_limit = (isset($inbound_settings['mailer']['processing-limit'])) ? $inbound_settings['mailer']['processing-limit'] : 100;

        /* Set thread limit */
        self::$thread_limit = (isset($inbound_settings['mailer']['thread-limit'])) ? $inbound_settings['mailer']['thread-limit'] : 1;

        /* Set target mysql table name */
        self::$table_name = $wpdb->prefix . "inbound_email_queue";

        /* Get now timestamp */
        self::$timestamp = gmdate("Y-m-d\\TG:i:s\\Z");

        /* Check if there is an error flag in db from previous processing run */
        self::$error_mode = Inbound_Options_API::get_option('inbound-email', 'errors-detected', false);

    }

    /*
    * Load Hooks & Filters
    */
    public static function load_hooks() {

        /* If no email service set then abort loading class */
        if (!self::$email_service) {
            return;
        }

        /* Adds mail processing to Inbound Heartbeat */
        add_action('inbound_mailer_heartbeat', array(__CLASS__, 'process_mail_queue'));

        /* For debugging */
        add_filter('init', array(__CLASS__, 'process_mail_queue'), 12);

    }


    public static function process_mail_queue() {

        if (!isset($_GET['forceprocess']) && current_filter() == 'init') {
            return;
        }

        /* send automation emails */
        self::send_automated_emails();

        /* send batch emails */
        self::send_batch_emails();

    }


    /**
     *    Tells WordPress to send emails as HTML
     */
    public static function toggle_email_type() {
        add_filter('wp_mail_content_type', array(__CLASS__, 'toggle_email_type_html'));
    }

    /**
     *    Set email type to html for wp_mail
     */
    public static function toggle_email_type_html($type) {
        return 'text/html';
    }

    /**
     *    Loads DOMDocument class object
     */
    public static function toggle_dom_parser() {
        self::$dom = new DOMDocument;
    }

    /**
     *    Rebuild links with tracking params
     */
    public static function rebuild_links($html) {
        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' => self::$row->email_id,
                'lead_lists' => implode(',', self::$email_settings['recipients']),
                'id' => self::$row->lead_id,
                'lead_id' => self::$row->lead_id,
                'page_id' => 0,
                'vid' => self::$row->variation_id,
                'url' => $link,
                'utm_source' => urlencode(self::$email['email_title']),
                'utm_medium' => 'email',
                'utm_campaign' => '',
                'tracking_id' => urlencode(self::$email['email_title'])
            ));

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

        }

        return $html;
    }


    /**
     *    Sends scheduled automated emails
     */
    public static function send_automated_emails() {
        global $wpdb;

        $query = "select * from " . self::$table_name . " WHERE `status` != 'processed' && `type` = 'automated' && `datetime` < '" . self::$timestamp . "' && `email_id` = `email_id` order by email_id  ASC LIMIT " . self::$send_limit;
        self::$results = $wpdb->get_results($query);

        if (!self::$results) {
            return;
        }

        /* get first row of result set for determining email_id */
        self::$row = self::$results[0];

        /* Get email title */
        self::$email['email_title'] = get_the_title(self::$row->email_id);

        /* Get email settings if they have not been loaded yet */
        self::$email_settings = Inbound_Email_Meta::get_settings(self::$row->email_id);

        /* set list ids if available */
        if (isset(self::$row->list_ids)) {
            self::$email_settings['recipients'] = json_decode(self::$row->list_ids ,true);
        }

        /* Build array of html content for variations */
        self::get_templates();

        /* Get tags for this email */
        self::get_tags();

        /* Make sure we send emails as html */
        self::toggle_email_type();

        /* load dom parser class object */
        self::toggle_dom_parser();

        $i=0;
        //error_log('Starting Cronjob' . self::time_elapsed());
        foreach (self::$results as $row) {

            self::$row = $row;

            //error_log('Starting Email ' . self::time_elapsed());
            self::get_email();

            switch (self::$email_service) {
                case "sparkpost":
                    Inbound_Mailer_SparkPost::send_email( true ); /* send immediately */
                    break;
            }

            /* check response for errors  */
            self::check_response();
            //error_log('Check Response ' . self::time_elapsed());

            /* if error in batch then bail on processing job */
            if (self::$error_mode) {
                error_log('error mode');
                return;
            }
            self::delete_from_queue();

            //error_log('Delete  '.$i.' From Queue ' . self::time_elapsed());
            $i++;
        }

        //error_log('Done');
        //error_log('Rows processed ' . $i);
    }

    /**
     *    Sends scheduled batch emails
     */
    public static function send_batch_emails() {
        global $wpdb;

        /* Get results for singular email id */
        $query = "select * from " . self::$table_name . " WHERE `status` != 'processed' && `type` = 'batch' && email_id = email_id order by email_id ASC LIMIT " . self::$send_limit;
        self::$results = $wpdb->get_results($query);

        if (!self::$results) {
            return;
        }

        /* get datetime */
        $wordpress_date_time = date_i18n('Y-m-d G:i:s');

        /* get first row of result set for determining email_id */
        self::$row = self::$results[0];

        /* Get email title */
        self::$email['email_title'] = get_the_title(self::$row->email_id);

        /* Get email settings if they have not been loaded yet */
        self::$email_settings = Inbound_Email_Meta::get_settings(self::$row->email_id);

        /* Build array of html content for variations */
        self::get_templates();

        /* Get tags for this email */
        self::get_tags();

        /* Make sure we send emails as html */
        self::toggle_email_type();

        /* load dom parser class object */
        self::toggle_dom_parser();

        $send_count = 1;
        foreach (self::$results as $row) {

            self::$row = $row;

            /* make sure not to try and send more than wp can handle */
            if ($send_count > self::$send_limit) {
                return;
            }

            /* skip sending if lead has temprarily paused email sending */
            $pass = self::check_stop_rules();
            if (!$pass) {
                self::delete_from_queue();
                continue;
            }


            self::get_email();

            /* delete from database queue */
            if (!self::$email['send_address']) {
                self::delete_from_queue();
                continue;
            }

            switch (self::$email_service) {
                case "sparkpost":
                    Inbound_Mailer_SparkPost::send_email();
                    break;
            }

            /* check response for errors  */
            self::check_response();

            /* if error in batch then bail on processing job */
            if (self::$error_mode) {
                return;
            }

            self::delete_from_queue();

            $send_count++;
        }

        /* mark batch email as sent if no more emails with this email id exists */
        $count = $wpdb->get_var("SELECT COUNT(*) FROM " . self::$table_name . " where email_id = '" . self::$row->email_id . "'");
        if ($count < 1) {
            self::mark_email_sent();
        }
    }


    /**
     *    Send email by lead id
     */
    public static function send_solo_email($args) {
        global $wpdb;

        if (!$args['email_id'] || !$args['email_address']) {
            return;
        }

        /* setup test tags */
        self::$tags[$args['email_id']] = (isset($args['tags'])) ? $args['tags'] : array('test');

        /* setup email send params */
        self::$row = new stdClass();
        self::$row->email_id = $args['email_id'];
        self::$row->variation_id = $args['vid'];
        self::$row->lead_id = (isset($args['lead_id'])) ? $args['lead_id'] : 0;
        self::$row->datetime = gmdate('Y-m-d h:i:s \G\M\T');
        self::$row->rule_id = (isset($args['rule_id'])) ? $args['rule_id'] : 0;
        self::$row->job_id = (isset($args['job_id'])) ? $args['job_id'] : 0;
        self::$row->tokens = (isset($args['tokens'])) ? $args['tokens'] : '';

        /* load extras */
        self::$email_settings = Inbound_Email_Meta::get_settings(self::$row->email_id);
        self::$email_settings['recipients'] = (isset($args['lead_lists'])) ? $args['lead_lists'] : array();
        self::get_templates(self::$row->variation_id);
        self::toggle_dom_parser();


        /* build email */
        self::$email['send_address'] = $args['email_address'];
        self::$email['subject'] = self::get_variation_subject();
        self::$email['from_name'] = self::get_variation_from_name();
        self::$email['from_email'] = self::get_variation_from_email();
        self::$email['email_title'] = get_the_title(self::$row->email_id);
        self::$email['reply_email'] = self::get_variation_reply_email();

        /* If direct email we won't load from template */
        if (isset($args['is_direct']) && $args['is_direct']) {
            $email = get_post($args['email_id']);
            self::$email['body'] = do_shortcode($email->post_content);
        } else {
            self::$email['body'] = self::get_email_body();
        }

        if (isset($args['is_test']) && $args['is_test']) {
            self::$email['is_test'] = true;
        }

        switch (self::$email_service) {
            case "sparkpost":
                Inbound_Mailer_SparkPost::send_email(true);
                break;
        }

        /* return response */
        return self::$response;

    }


    /**
     *    Updates the status of the email in the queue
     */
    public static function delete_from_queue() {
        global $wpdb;

        $query = "delete from " . self::$table_name . " where `id` = '" . self::$row->id . "'";
        $wpdb->query($query);

    }

    /**
     *    Updates the post status of an email to sent
     */
    public static function mark_email_sent() {

        $wordpress_date_time = date_i18n('Y-m-d G:i:s');
        $today = new DateTime($wordpress_date_time);
        $schedule_date = new DateTime(self::$row->datetime);
        $interval = $today->diff($schedule_date);

        $status = ($interval->format('%R') == '+') ? 'scheduled' : 'sent';

        $args = array(
            'ID' => self::$row->email_id,
            'post_status' => $status,
        );

        wp_update_post($args);
    }


    /**
     *    Gets array of raw html for each variation
     */
    public static function get_templates($variation_id = null) {


        /* setup static var as empty array */
        self::$templates = array();

        if (!isset(self::$email_settings['variations']) || !self::$email_settings['variations']) {
            return array();
        }


        foreach (self::$email_settings['variations'] as $vid => $variation) {

            if ($variation_id !== null && $vid != $variation_id) {
                continue;
            }

            /* get permalink */
            $permalink = get_post_permalink(self::$row->email_id);

            /* query args */
            $query_args = array('inbvid' => $vid, 'disable_shortcodes' => true);

            /* encode post_id */
            if (isset(self::$row->post_id)) {
                $query_args['post_id'] = self::$row->post_id ;
            }

            /* encode tokens */
            if (self::$row->tokens && strlen(self::$row->tokens) < 1000 )  {
                $token = Inbound_API::analytics_get_tracking_code(json_decode(self::$row->tokens,true));
                $query_args['tokens'] = $token ;
            }

            /* add param */
            $permalink = add_query_arg( $query_args , $permalink);

            /* Stash variation template in static array */
            self::$templates[self::$row->email_id][$vid] = self::get_variation_html($permalink);
        }

    }

    /**
     *    Gets tags & sets them into static array
     */
    public static function get_tags() {

        $array = array();

        /* Mandrill can't accept user defined tags due to tag limitations
        $terms = wp_get_post_terms( self::$row->email_id , 'inbound_email_tag' );

        foreach ($terms as $term) {
            $array[] = $term->name;
        }
        */

        $array[] = self::$email_settings['email_type'];

        self::$tags[self::$row->email_id] = $array;
    }

    /**
     * Prepares email data for sending
     * @return ARRAY $email
     */
    public static function get_email() {

        self::$email['send_address'] = Leads_Field_Map::get_field(self::$row->lead_id, 'wpleads_email_address');
        self::$email['from_name'] = self::get_variation_from_name();
        self::$email['from_email'] = self::get_variation_from_email();
        self::$email['reply_email'] = self::get_variation_reply_email();
        self::$email['body'] = self::get_email_body();
        self::$email['subject'] = self::get_variation_subject();

    }

    /**
     *    Generates targeted email body html
     */
    public static function get_email_body() {
        $last = self::$last;

        /* set required variables if empty */
        self::$email_settings['recipients'] = (isset(self::$email_settings['recipients'])) ? self::$email_settings['recipients'] : array();

        $html = self::$templates[self::$row->email_id][self::$row->variation_id];

        /* add lead id to all shortcodes before processing */
        $html = str_replace('[lead-field ', '[lead-field lead_id="' . self::$row->lead_id . '" ', $html);
        $unsubscribe = do_shortcode('[unsubscribe-link lead_id="' . self::$row->lead_id . '" list_ids="' . implode(',', self::$email_settings['recipients']) . '" email_id="' . self::$row->email_id . '" rule_id="' . self::$row->rule_id . '" job_id="' . self::$row->job_id . '"]');

        /* add lead id & list ids to unsubscribe shortcode */
        $html = str_replace('[unsubscribe-link]', $unsubscribe, $html);

        $html = Inbound_List_Double_Optin::add_confirm_link_shortcode_params($html, array(
            'lead_id' => self::$row->lead_id,
            'list_ids' => self::$email_settings['recipients'],
            'email_id' => self::$row->email_id
        ));

        /* clean mal formatted quotations */
        $html = str_replace('&#8221;', '"', $html);

        /* remove ctas before rendering shortcodes */
        $pattern = '/\[(cta).*?\]/';
        $content = preg_replace($pattern, '', $html);

        /* process shortcodes */
        $html = do_shortcode($html);

        /* add tracking params to links */
        //$html = self::rebuild_links($html);

        /* remove script tags */
        $html = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $html);

        return $html;
    }

    /**
     * Generate HTML for email
     * @param STRING $permalink
     * @return STRING
     */
    public static function get_variation_html($permalink) {

        $response = wp_remote_get($permalink, array('timeout' => 120));

        if (is_wp_error($response)) {
            error_log(print_r($response, true));
            print_r($response);
            exit;
        }

        $html = wp_remote_retrieve_body($response);
        return $html;
    }

    /**
     *    Gets the subject line from variation settings
     */
    public static function get_variation_subject() {

        /* add lead id to all shortcodes before processing */
        $subject = str_replace('[lead-field ', '[lead-field lead_id="' . self::$row->lead_id . '" ', self::$email_settings['variations'] [self::$row->variation_id] ['subject']);

        $email_tokens = json_decode(self::$row->tokens , true);

        /* rebuild tokens if id present */
        if (isset(self::$row->post_id)) {
            $post = get_post(self::$row->post_id);
            $email_tokens = (array) $post;
            $email_tokens['permalink'] = get_the_permalink((int) self::$row->post_id);
            $email_tokens['featured_image'] = wp_get_attachment_url(get_post_thumbnail_id(self::$row->post_id));
            wp_reset_query();
        }

        /* process tokens */
        $subject = Inbound_Mailer_Tokens::process_tokens($subject , $email_tokens );

        return do_shortcode($subject);
    }

    /**
     *    Gets the from name from variation settings
     */
    public static function get_variation_from_name() {
        return self::$email_settings['variations'] [self::$row->variation_id] ['from_name'];
    }

    /**
     *    Gets the from email from variation settings
     */
    public static function get_variation_from_email() {
        return self::$email_settings['variations'] [self::$row->variation_id] ['from_email'];
    }

    /**
     *    Gets the reply email from variation settings
     */
    public static function get_variation_reply_email() {

        /* add lead id to all shortcodes before processing */
        self::$email_settings['variations'][self::$row->variation_id]['reply_email'] = str_replace('[lead-field ', '[lead-field lead_id="' . self::$row->lead_id . '" ', self::$email_settings['variations'][self::$row->variation_id]['reply_email']);

        /* process tokens */
        self::$email_settings['variations'][self::$row->variation_id]['reply_email'] = Inbound_Mailer_Tokens::process_tokens(
            self::$email_settings['variations'][self::$row->variation_id]['reply_email'] ,
            json_decode(self::$row->tokens , true)
        );

        return do_shortcode(self::$email_settings['variations'][self::$row->variation_id]['reply_email']);
    }


    /**
     *    Generate text version of html email automatically
     */
    public static function get_text_version() {


    }

    /**
     * Check stop rules for lead
     * returns true to OK sending and false to prevent sending
     */
    public static function check_stop_rules() {

        $stop_rules = Inbound_Mailer_Unsubscribe::get_stop_rules(self::$row->lead_id);
        $wordpress_date_time = date_i18n('Y-m-d G:i:s');

        $passed = 0;
        $failed = 0;

        foreach (self::$email_settings['recipients'] as $list_id) {
            if (!isset($stop_rules[$list_id])) {
                $passed++;
                continue;
            }

            /* if lead has unsubscribed to this list skip it */
            if ($stop_rules[$list_id] == 'unsubscribed') {
                $failed++;
                continue;
            }

            /* if not a datetime string then skip stop rule (treat as pass) */
            if (!is_string($stop_rules[$list_id])) {
                $passed++;
                continue;
            }

            /* if lead has emails for this list paused then set $pass to false */
            if (strtotime($stop_rules[$list_id]) > strtotime($wordpress_date_time)) {
                $failed++;
            } else {
                $passed++;
                Inbound_Mailer_Unsubscribe::remove_stop_rule(self::$row->lead_id, $list_id);
            }
        }

        if ($passed >= $failed) {
            return true;
        } else {
            return false;
        }

    }

    /**
     *  Checks Email Service Response for Errors
     */
    public static function check_response() {
        global $current_user, $post;
        $user_id = $current_user->ID;

        /* check if there is an error and if there is then exit */
        if (isset(self::$response['status']) && self::$response['status'] == 'error' || isset(self::$response['error'])) {
            if (isset($resonse['description'])) {
                self::$response['message'] = self::$response['message'] . ' : ' . self::$response['description'];
            }

            Inbound_Options_API::update_option('inbound-email', 'errors-detected', self::$response['message']);
            self::$error_mode = true;
            return;
        }

        /* if error mode is on and response is good then turn it off */
        if (self::$error_mode) {
            Inbound_Options_API::update_option('inbound-email', 'errors-detected', false);
            self::$error_mode = false;
        }

    }

    public static function time_elapsed( $last = null)
    {

        self::$last = ($last) ? $last : self::$last;
        $now = microtime(true);

        if (self::$last != null) {

            $elapsed =  '<!---- ' . date("H:i:s", $now - self::$first) . ' ' . date("H:i:s", $now - self::$last) . '  now: '.$now.' last: '.self::$last.' -->';
        }

        self::$last = ($last) ? $last :$now;
        self::$first = (self::$first) ? self::$first : self::$last;
        return $elapsed;
    }
}

/**
 *    Load Mail Daemon on init
 */
function load_inbound_mail_daemon() {
    new Inbound_Mail_Daemon();
}

add_action('init', 'load_inbound_mail_daemon', 2);
Inbound Pro Plugin - PHP Codex API documentation generated by ApiGen