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: 
<?php
/**
 * Class handles all lead storage/update procedures
 * @package Shared
 * @subpackage LeadSorage
 */
if (!class_exists('LeadStorage')) {
    class LeadStorage {
        static $mapped_fields;
        static $is_ajax;

        /**
         *  Initialize class
         */
        static function init() {
            /* determines if in ajax mode */
            self::set_mode();

            /* sets up ajax listeners */
            add_action('wp_ajax_inbound_lead_store', array(__CLASS__, 'inbound_lead_store'), 10, 1);
            add_action('wp_ajax_nopriv_inbound_lead_store', array(__CLASS__, 'inbound_lead_store'), 10, 1);

            /* filters name data to build a more comprehensive data set */
            add_filter( 'inboundnow_store_lead_pre_filter_data',    array(__CLASS__, 'improve_lead_name'), 10, 1);
        }

        /**
         *  Checks if running in ajax mode
         */
        static function set_mode( $mode = 'auto' ) {
            /* http://davidwalsh.name/detect-ajax */
            switch( $mode ) {
                case 'auto':
                    self::$is_ajax =    ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ? true : false;
                    BREAK;
                case 'ajax':
                    self::$is_ajax = true;
                    BREAK;
                case 'return':
                    self::$is_ajax = false;
                    BREAK;
            }
        }

        /**
         *  Stores lead
         */
        static function inbound_lead_store( $args ) {
            global $user_ID, $wpdb;
            if (!is_array($args)) { $args = array(); }

            /* Mergs $args with POST request for support of ajax and direct calls */
            if(isset($_POST)){
                $args = array_merge( $args, $_POST );
            }

            $lead = array();
            if(isset($user_ID)){
                $lead['user_ID'] = $user_ID;
            }
            /* Current wordpress time from settings */
            $time = current_time( 'timestamp', 0 );
            $lead['wordpress_date_time'] = date("Y-m-d G:i:s T", $time);

            $lead['email'] = str_replace("%40", "@", self::check_val('email', $args));
            $lead['email'] = str_replace("%2B", "+", $lead['email']);
            $lead['page_id'] = self::check_val('page_id', $args);
            $lead['page_views'] = self::check_val('page_views', $args);
            $lead['raw_params'] = self::check_val('raw_params', $args);
            $lead['inbound_form_id'] = self::check_val('inbound_form_id', $args);
            $lead['mapped_params'] = self::check_val('mapped_params', $args);
            $lead['url_params'] = self::check_val('url_params', $args);
            $lead['variation'] = self::check_val('variation', $args);
            $lead['source'] = self::check_val('source', $args);
            $lead['wp_lead_status'] = self::check_val('wp_lead_status', $args);
            $lead['ip_address'] = self::lookup_ip_address( $args );


            if($lead['raw_params']){
                parse_str($lead['raw_params'], $raw_params);
            } else {
                $raw_params = array();
            }

            if($lead['mapped_params']){
                parse_str($lead['mapped_params'], $mappedData);
            } else {
                $mappedData = array();
            }


            $mappedData = self::improve_mapping($mappedData, $lead , $args);
            $lead = array_merge($lead ,$mappedData);


            /* prepate lead lists */
            $lead['lead_lists'] = (isset($args['lead_lists'])) ? $args['lead_lists'] : null;
            if ( !$lead['lead_lists'] && array_key_exists('inbound_form_lists', $mappedData) ) {
                $lead['lead_lists'] = explode(",", $mappedData['inbound_form_lists']);
            }

            /* prepate lead tags */
            $lead['lead_tags'] = (isset($args['lead_tags'])) ? $args['lead_tags'] : null;
            if ( !$lead['lead_tags'] && array_key_exists('inbound_form_tags', $mappedData) ) {
                $lead['lead_tags'] = explode(",", $mappedData['inbound_form_tags']);
            }


            /* Look for direct key matches & clean up $lead_data */
            $lead = apply_filters( 'inboundnow_store_lead_pre_filter_data', $lead, $args);

            /* TODO have fallbacks for existing lead ID or Lead UID lookups*/
            /* check for set email */
            if ( (isset($lead['email']) && !empty($lead['email']) && strstr($lead['email'] ,'@'))) {


                $leadExists = self::lookup_lead_by_email($lead['email']);

                /* If lead already exists run update action hook */
                if ($leadExists) {
                    $lead['id'] = $leadExists;
                    do_action('wpleads_existing_lead_update', $lead);
                }
                /* else create new lead */
                else {
                    $lead['id'] = self::store_new_lead($lead);
                }


                /* Store Mapped Form Data */
                if(!empty($mappedData)){
                    self::store_mapped_data($lead, $mappedData);
                }

                /* if status is included in lead array then set status */
                if (isset($lead['wp_lead_status']) && !empty($lead['wp_lead_status'])) {
                    update_post_meta($lead['id'], 'wp_lead_status', $lead['wp_lead_status']);
                }
                /* else if new lead then set status to new */
                else if (!$leadExists) {
                    update_post_meta($lead['id'], 'wp_lead_status', 'new');
                }

                /* do everything else for lead storage */
                self::update_common_meta($lead);

                do_action('wpleads_after_conversion_lead_insert', $lead['id']); /* action hook on all lead inserts */

                /* Add Leads to List on creation */
                if(!empty($lead['lead_lists']) && is_array($lead['lead_lists'])){
                    $double_optin_lists = array();
                    $normal_lists = array();

                    /*differentiate between double optin lists and lists that don't require double optin*/
                    foreach($lead['lead_lists'] as $list_id){
                        $list_meta_settings = get_term_meta($list_id, 'wplead_lead_list_meta_settings', true);
                        if(isset($list_meta_settings['double_optin']) && $list_meta_settings['double_optin'] == '1'){
                            $double_optin_lists[] = $list_id;
                        }else{
                            $normal_lists[] = $list_id;
                        }
                    }

                    /*remove any groups that the lead is already on from the double optin groups*/
                    if(array_filter($double_optin_lists)){
                        $existing_lists = wp_get_post_terms( $lead['id'], 'wplead_list_category');
                        foreach($existing_lists as $existing_list){
                            if(in_array($existing_list->term_id, $double_optin_lists)){
                                $index = array_search($existing_list->term_id, $double_optin_lists);
                                unset($double_optin_lists[$index]);
                            }
                        }
                    }

                    if(array_filter($double_optin_lists)){
                        /*get the double optin waiting list id*/
                        if(!defined('INBOUND_PRO_CURRENT_VERSION')){
                            $double_optin_list_id = get_option('list-double-optin-list-id', '');
                        }else{
                            $settings = Inbound_Options_API::get_option('inbound-pro', 'settings', array());
                            $double_optin_list_id = $settings['leads']['list-double-optin-list-id'];
                        }

                        /*if there is a list to store the leads in*/
                        if($double_optin_list_id){
                            /*store the list ids that need confirmation*/
                            update_post_meta($lead['id'], 'double_optin_lists', $double_optin_lists);

                            /*change the lead status to waiting for double optin*/
                            update_post_meta( $lead['id'] , 'wp_lead_status' , 'double-optin');

                            /*add the lead to the double optin confirmation list*/
                            Inbound_Leads::add_lead_to_list($lead['id'], $double_optin_list_id);
                            Inbound_List_Double_Optin::send_double_optin_confirmation($lead);
                        }
                    }

                    /*add the lead to all lists that don't require double optin*/
                    Inbound_Leads::add_lead_to_list($lead['id'], $normal_lists);

                    /* store lead list cookie */
                    if (class_exists('Leads_Tracking')) {
                        Leads_Tracking::cookie_lead_lists($lead['id'] , $normal_lists);
                    }
                }

                /* Add Leads to List on creation */
                if(!empty($lead['lead_tags']) && is_array($lead['lead_tags'])){

                    /*add the lead to all lists that don't require double optin*/
                    foreach ( $lead['lead_tags'] as $tag_id ) {
                        Inbound_Leads::add_tag_to_lead( $lead['id'] , intval($tag_id) );
                    }

                    /* store lead list cookie */
                    if (class_exists('Leads_Tracking')) {
                        Leads_Tracking::cookie_lead_tags($lead['id'] , $lead['lead_tags']);
                    }
                }

                /* Store page views for people with ajax tracking off */
                $ajax_tracking_off = false; /* get_option */
                if($lead['page_views'] && $ajax_tracking_off ) {
                    self::store_page_views($lead);
                }

                /* Store past search history */
                if(isset($lead['search_data'])){
                    self::store_search_history($lead);
                }

                /* attempt to determine page id that refered lead */
                if (!isset($lead['page_id']) || !$lead['page_id']) {
                    $referer = wp_get_referer();
                    $referer = ($referer) ? $referer : $_SERVER['HTTP_REFERER'];
                    $page_id = url_to_postid($referer);
                    if ($page_id) {
                        $lead['page_id'] = $page_id;
                    }
                }

                /* Store Legacy Conversion Data to LANDING PAGE/CTA DATA    */
                if (isset($lead['page_id']) && $lead['page_id'] ) {
                    self::store_conversion_stats($lead);

                }

                /* Store URL Params */
                if($lead['url_params']) {
                    $param_array = json_decode(stripslashes($lead['url_params']));
                    /*print_r($param_array); exit; */
                    if(is_array($param_array)){

                    }
                }

                /* Store IP addresss & Store GEO Data */
                if ($lead['ip_address']) {
                    update_post_meta( $lead['id'], 'wpleads_ip_address', $lead['ip_address'] );
                }

                /* store raw form data */
                self::store_raw_form_data($lead);

                /* look for form_id and set it into main array */
                if (isset($args['form_id'])) {
                    $lead['form_id'] = $args['form_id'];
                }
                if (isset($args['form_name'])) {
                    $lead['form_name'] = $args['form_name'];
                }

                /* look for an inbound_form_id and set it into main array */
                if (isset($args['inbound_form_id'])) {
                    $lead['inbound_form_id'] = $args['inbound_form_id'];
                    $lead['form_id'] = (isset($args['inbound_form_id'])) ? $args['inbound_form_id'] : 0;
                    $lead['form_name'] = (isset($args['inbound_form_n'])) ? $args['inbound_form_n'] : '';
                }


                /* update lead id cookie */
                setcookie('wp_lead_id', $lead['id'] , time() + (20 * 365 * 24 * 60 * 60), '/');

                /* set unset pageviews to lead using lead_uid */
                self::update_pageviews($lead);

                /* set unset events to lead using lead_uid */
                self::update_events($lead);

                /* send data back and perform action hooks */
                if ( self::$is_ajax ) {
                    do_action('inbound_store_lead_post', $lead );
                    echo $lead['id'];
                    exit;
                } else {
                    do_action('inbound_store_lead_post', $lead );
                    return $lead['id'];
                }

            }
        }

        /**
         *  Creates new lead in wp-lead post type
         */
        static function store_new_lead($lead){
            /* Create New Lead */
            $post = array(
                'post_title'        => $lead['email'],
                /*'post_content'        => $json, */
                'post_status'       => 'publish',
                'post_type'     => 'wp-lead',
                'post_author'       => 1
            );

            /*$post = add_filter('lp_leads_post_vars',$post); */
            $id = wp_insert_post($post);
            /* specific updates for new leads */
            update_post_meta( $id, 'wpleads_email_address', $lead['email'] );
            /* new lead run simple page_view storage */
            update_post_meta( $id, 'page_views', $lead['page_views']);
            /* dont need update_post_meta( $id, 'wpleads_page_view_count', $lead['page_view_count']); */

            do_action('wpleads_new_lead_insert', $lead ); /* action hook on new leads only */
            return $id;
        }

        /**
         *  Updates pages viewed object
         */
        static function store_page_views($lead){
            $page_view_data = get_post_meta( $lead['id'], 'page_views', TRUE );
            $page_view_data = json_decode($page_view_data,true);

            /* If page_view meta exists do this */
            if (is_array($page_view_data)) {
                $new_page_views = self::json_array_merge( $page_view_data, $lead['page_views']);
                $page_views = json_encode($new_page_views);
            } else {
                /* Create page_view meta if it doesn't exist */
                $page_views = $lead['page_views'];
                $page_views = json_encode($page_views);
            }
            update_post_meta($lead['id'], 'page_views', $page_views );
        }

        /**
         *  Prefixes keys with wpleads_ if key is not prepended with wpleads_
         */
        static function store_mapped_data($lead, $mappedData){

            foreach ($mappedData as $key => $value) {

                if (!$value) {
                    continue;
                }

                /* sanitise inputs */
                if (is_string($value)) {
                    $value = strip_tags( $value );
                }

                /* Old convention with wpleads_ prefix */
                if( !strstr($key,'wpleads_') ) {
                    $key = 'wpleads_'.$key;
                    update_post_meta($lead['id'], $key, $value);
                } else {
                    update_post_meta($lead['id'], $key, $value);
                }

                /* update options for custom field type */
                global $inbound_settings;
                $field = ( isset($inbound_settings['leads-custom-fields']['fields'][ $key ]) ) ? $inbound_settings['leads-custom-fields']['fields'][ $key ] : array();


                /* update custom field options for dropdown */
                if (isset($field['type']) && $field['type']== 'dropdown' ) {
                    $options = $inbound_settings['leads-custom-fields']['fields'][ $key ][ 'options' ];

                    if ( !isset($options[ $value ]) ) {
                        $options[$value] = $value;
                        $inbound_settings['leads-custom-fields']['fields'][ $key ][ 'options' ] = $options;
                        Inbound_Options_API::update_option('inbound-pro', 'settings', $inbound_settings);
                    }

                }

            }
        }

        /**
         *  Updates search history object
         */
        static function store_search_history($lead){
            $search = $lead['search_data'];
            $search_data = get_post_meta( $lead['id'], 'wpleads_search_data', TRUE );
            $search_data = json_decode($search_data,true);
            if (is_array($search_data)){
                $s_count = count($search_data) + 1;
                $loop_count = 1;
                foreach ($search as $key => $value) {
                    $search_data[$s_count]['date'] = $search[$loop_count]['date'];
                    $search_data[$s_count]['value'] = $search[$loop_count]['value'];
                    $s_count++; $loop_count++;
                }
            } else {
                /* Create search obj */
                $s_count = 1;
                $loop_count = 1;
                foreach ($search as $key => $value) {
                    $search_data[$s_count]['date'] = $search[$loop_count]['date'];
                    $search_data[$s_count]['value'] = $search[$loop_count]['value'];
                    $s_count++; $loop_count++;
                }
            }
            $search_data = json_encode($search_data);
            update_post_meta($lead['id'], 'wpleads_search_data', $search_data); /* Store search object */
        }

        /**
         *      updates conversion data object
         */
        static function store_conversion_data( $lead ) {

            $conversion_data = get_post_meta( $lead['id'], 'wpleads_conversion_data', TRUE );
            $conversion_data = json_decode($conversion_data,true);
            $variation = $lead['variation'];

            if ( is_array($conversion_data)) {
                $c_count = count($conversion_data) + 1;
                $conversion_data[$c_count]['id'] = $lead['page_id'];
                $conversion_data[$c_count]['variation'] = $variation;
                $conversion_data[$c_count]['datetime'] = $lead['wordpress_date_time'];
            } else {
                $c_count = 1;
                $conversion_data[1]['id'] = $lead['page_id'];
                $conversion_data[1]['variation'] = $variation;
                $conversion_data[1]['datetime'] = $lead['wordpress_date_time'];
                $conversion_data[1]['first_time'] = 1;
            }

            $lead['conversion_data'] = json_encode($conversion_data);
            update_post_meta($lead['id'],'wpleads_conversion_count', $c_count); /* Store conversions count */
            update_post_meta($lead['id'], 'wpleads_conversion_data', $lead['conversion_data']);/* Store conversion obj */

        }
        /**
         *  Store Conversion Data to LANDING PAGE/CTA DATA
         */
        static function store_conversion_stats($lead){
            $page_conversion_data = get_post_meta( $lead['page_id'], '_inbound_conversion_data', TRUE );
            $page_conversion_data = json_decode($page_conversion_data,true);
            $version = ($lead['variation'] != 'default') ? $lead['variation'] : '0';
            if (is_array($page_conversion_data)) {
                $convert_count = count($page_conversion_data) + 1;
                $page_conversion_data[$convert_count]['lead_id'] = $lead['id'];
                $page_conversion_data[$convert_count]['variation'] = $version;
                $page_conversion_data[$convert_count]['datetime'] = $lead['wordpress_date_time'];
            } else {
                $page_conversion_data[1]['lead_id'] = $lead['id'];
                $page_conversion_data[1]['variation'] = $version;
                $page_conversion_data[1]['datetime'] = $lead['wordpress_date_time'];
            }
            $page_conversion_data = json_encode($page_conversion_data);
            update_post_meta($lead['page_id'], '_inbound_conversion_data', $page_conversion_data);
        }


        /**
         *      Loop trough lead_data array and update post meta
         */
        static function update_common_meta($lead) {

            if (!empty($lead['user_ID'])) {
                /* Update user_ID if exists */
                update_post_meta( $lead['id'], 'wpleads_wordpress_user_id', $lead['user_ID'] );
            }

            /* Update wp_lead_uid if exist */
            if (!empty($lead['wp_lead_uid'])) {
                update_post_meta( $lead['id'], 'wp_leads_uid', $lead['wp_lead_uid'] );
            }

            /* Update email address */
            if (!empty($lead['email'])) {
                update_post_meta( $lead['id'], 'wplead_emails_address', $lead['email'] );
            }

            /* Update mappable fields that have a value associated with them */
            $lead_fields = Leads_Field_Map::build_map_array();
            foreach ( $lead_fields as $key => $value ) {
                $shortkey = str_replace('wpleads_', '', $key );
                if (!empty($lead[$shortkey]) && $lead[$shortkey] !== 0 ) {
                    update_post_meta( $lead['id'], $key, $lead[$shortkey] );
                }
            }
        }

        /**
         * Associates prior unassociated pageviews with lead id
         */
        public static function update_pageviews( $lead ) {
            global $wpdb;

            $table_name = $wpdb->prefix . "inbound_page_views";
            $lead_uid_cookie = (isset($_COOKIE["wp_lead_uid"])) ? $_COOKIE["wp_lead_uid"] : '';
            $args = array(
                'lead_id' => $lead['id'],
            );


            /* update inbound_page_view page view records associated with lead */
            $wpdb->update(
                $table_name,
                $args,
                array(
                    'lead_id' => 0,
                    'lead_uid' => (isset($lead['wp_lead_uid'])) ? $lead['wp_lead_uid'] :  $lead_uid_cookie
                ),
                array(
                    '%d',
                    '%s'
                )
            );
        }

        /**
         * Associates prior unassociated pageviews with lead id
         */
        public static function update_events( $lead ) {
            global $wpdb;
            $table_name = $wpdb->prefix . "inbound_events";
            $lead_uid_cookie = (isset($_COOKIE["wp_lead_uid"])) ? $_COOKIE["wp_lead_uid"] : '';

            $args = array(
                'lead_id' => $lead['id'],
            );

            /* update inbound_page_view page view records associated with lead */
            $wpdb->update(
                $table_name,
                $args,
                array(
                    'lead_id' => 0,
                    'lead_uid' => (isset($lead['wp_lead_uid'])) ? $lead['wp_lead_uid'] :  $lead_uid_cookie
                ),
                array(
                    '%d',
                    '%s'
                )
            );
        }


        /**
         *  Updates raw form data object
         */
        static function store_raw_form_data($lead){

            /* Raw Form Values Store */
            if (!$lead['raw_params']) {
                return;
            }

            $raw_post_data = get_post_meta($lead['id'],'wpleads_raw_post_data', true);
            $a1 = json_decode( $raw_post_data, true );
            parse_str($lead['raw_params'], $a2 );
            $exclude_array = array('card_number','card_cvc','card_exp_month','card_exp_year'); /* add filter */
            $lead_mapping_fields = Leads_Field_Map::build_map_array();

            foreach ($a2 as $key=>$value)
            {
                if (array_key_exists( $key, $exclude_array )) {
                    unset($a2[$key]);
                    continue;
                }
                if (preg_match("/\[\]/", $key)) {
                    $key = str_replace("[]", "", $key); /* fix array value keys */
                }
                if (array_key_exists($key, $lead_mapping_fields)) {
                    update_post_meta( $lead['id'], $key, $value );
                }

                if (stristr($key,'company')) {
                    update_post_meta( $lead['id'], 'wpleads_company_name', $value );
                }
                else if (stristr($key,'website'))
                {
                    $websites = get_post_meta( $lead['id'], 'wpleads_websites', $value );
                    if(is_array($websites)) {
                        $array_websites = explode(';',$websites);
                    }
                    $array_websites[] = $value;
                    $websites = implode(';',$array_websites);
                    update_post_meta( $lead['id'], 'wpleads_websites', $websites );
                }
            }
            /* Merge form fields if exist */
            if (is_array($a1)) {
                $new_raw_post_data = array_merge_recursive( $a1, $a2 );
            } else {
                $new_raw_post_data = $a2;
            }
            $new_raw_post_data = json_encode( $new_raw_post_data );
            update_post_meta( $lead['id'],'wpleads_raw_post_data', $new_raw_post_data );

        }

        /**
         *  Parses & improves lead name
         */
        static function improve_lead_name( $lead ) {
            /* */
            $lead['wpleads_name'] = (isset($lead['wpleads_name'])) ? $lead['wpleads_name'] : '';
            $lead['wpleads_first_name'] = (isset($lead['wpleads_first_name'])) ? $lead['wpleads_first_name'] : '';
            $lead['wpleads_last_name'] = (isset($lead['wpleads_last_name'])) ? $lead['wpleads_last_name'] : '';

            /* do not let names with 'false' pass */
            if ( !empty($lead['wpleads_name']) && $lead['name'] == 'false' ) {
                $lead['wpleads_name'] = '';
            }

            if ( !empty($lead['wpleads_first_name']) && $lead['wpleads_first_name'] == 'false' ) {
                $lead['wpleads_first_name'] = '';
            }

            /* if last name empty and full name present */
            if ( empty($lead['wpleads_last_name']) && $lead['wpleads_name'] ) {
                $parts = explode(' ', $lead['wpleads_name']);

                /* Set first name */
                $lead['wpleads_first_name'] = trim($parts[0]);

                /* Set last name */
                if (isset($parts[1])) {
                    $lead['wpleads_last_name'] = trim($parts[1]);
                }
            }
            /* if last name empty and first name present */
            else if (empty($lead['wpleads_last_name']) && $lead['wpleads_first_name'] ) {
                $parts = explode(' ', $lead['wpleads_first_name']);

                /* Set First Name */
                $lead['wpleads_first_name'] = trim($parts[0]);

                /* Set Last Name */
                if (isset($parts[1])) {
                    $lead['wpleads_last_name'] = trim($parts[1]);
                }
            }

            /* set full name */
            if (!$lead['wpleads_name'] && $lead['wpleads_first_name'] && $lead['wpleads_last_name'] ) {
                $lead['wpleads_name'] = $lead['wpleads_first_name'] .' '. $lead['wpleads_last_name'];
            }

            return $lead;
        }

        /**
         *  Uses mapped data if not programatically set
         */
        static function improve_mapping($mappedData, $lead , $args) {

            /* check to see if there are any mapped values arriving through inbound_store_lead */
            $fields = Leads_Field_Map::build_map_array();

            foreach ($fields as $key => $label ) {
                if( isset( $args[ $key ]) && !isset($mappedData[$key]) ) {
                    $mappedData[$key] =  sanitize_text_field($args[ $key ]);
                }
            }

            return $mappedData;
        }

        /**
         *  Search lead by email
         */
        static function lookup_lead_by_email($email){
            global $wpdb;
            $query = $wpdb->prepare(
                'SELECT ID FROM ' . $wpdb->posts . '
                WHERE post_title = %s
                AND post_type = \'wp-lead\'',
                $email
            );
            $wpdb->query( $query );
            if ( $wpdb->num_rows ) {
                $lead_id = $wpdb->get_var( $query );
                return $lead_id;
            } else {
                return false;
            }

        }

        static function check_val($key, $args) {
            $val = (isset($args[$key])) ? $args[$key] : false;
            return $val;
        }
        static function json_array_merge( $arr1, $arr2 ) {
            $keys = array_keys( $arr2 );
            foreach( $keys as $key ) {
                if( isset( $arr1[$key] )
                    && is_array( $arr1[$key] )
                    && is_array( $arr2[$key] )
                ) {
                    $arr1[$key] = my_merge( $arr1[$key], $arr2[$key] );
                } else {
                    $arr1[$key] = $arr2[$key];
                }
            }
            return $arr1;
        }

        /**
         *  Discover session IP address
         */
        static function lookup_ip_address( $args = array() ) {

            /* make sure this field is not preset. It could be arriving from an import routine */
            if (isset($args['wpleads_ip_address']) && $args['wpleads_ip_address']) {
                return $args['wpleads_ip_address'];
            }

            if(isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
                if(isset($_SERVER["HTTP_CLIENT_IP"])) {
                    $proxy = $_SERVER["HTTP_CLIENT_IP"];
                } else {
                    $proxy = $_SERVER["REMOTE_ADDR"];
                }
                $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
            } else {
                if(isset($_SERVER["HTTP_CLIENT_IP"])) {
                    $ip = $_SERVER["HTTP_CLIENT_IP"];
                } else {
                    $ip = $_SERVER["REMOTE_ADDR"];
                }
            }
            return $ip;
        }

        /**
         * Create a lead from a user id
         * @param $user_id
         */
        public static function create_lead_from_user( $user_id ) {

        }

    }

    LeadStorage::init();
}

/**
 * Legacy function used by some extensions
 * @param ARRAY $args legacy dataset of mapped lead fields
 * @param BOOL $return set to true to disable printing of lead id
 */
if (!function_exists('inbound_store_lead')) {
    function inbound_store_lead( $args, $return = true  ) {
        global $user_ID, $wpdb;

        if (!is_array($args)) {
            $args = array();
        }

        /* Mergs $args with POST request for support of ajax and direct calls */
        $args = array_merge( $args, $_POST );

        /* wpleads_email_address becomes wpleads_email */
        $args['email'] = sanitize_text_field($args['wpleads_email_address']);

        /* Send data through new method */
        $Leads = new LeadStorage();
        if ($return) {
            $Leads->set_mode('return');
        } else {
            $Leads->set_mode('ajax');
        }

        /* prepare lead lists as array */
        if (isset($args['lead_lists']) && !is_array($args['lead_lists'])) {
            $args['lead_lists'] = explode(',',$args['lead_lists']);
        }

        $lead_id = $Leads::inbound_lead_store( $args );

        return $lead_id;


    }
}


/**
 *  Legacy functions for adding conversion to lead profile
 *  @param INT $lead_id
 *  @param ARRAY dataset of lead informaiton
 */
if (!function_exists('inbound_add_conversion_to_lead')) {
    function inbound_add_conversion_to_lead( $lead_id, $lead_data ) {


        if ( $lead_data['page_id'] ) {
            $time = current_time( 'timestamp', 0 ); /* Current wordpress time from settings */
            $lead_data['wordpress_date_time'] = date("Y-m-d G:i:s T", $time);
            $conversion_data = get_post_meta( $lead_id, 'wpleads_conversion_data', TRUE );
            $conversion_data = json_decode($conversion_data,true);
            $variation = (isset($lead_data['variation'])) ? $lead_data['variation']:0;

            if ( is_array($conversion_data)) {
                $c_count = count($conversion_data) + 1;
                $conversion_data[$c_count]['id'] = $lead_data['page_id'];
                $conversion_data[$c_count]['variation'] = $variation;
                $conversion_data[$c_count]['datetime'] = $lead_data['wordpress_date_time'];
            } else {
                $c_count = 1;
                $conversion_data[$c_count]['id'] = $lead_data['page_id'];
                $conversion_data[$c_count]['variation'] = $variation;
                $conversion_data[$c_count]['datetime'] = $lead_data['wordpress_date_time'];
                $conversion_data[$c_count]['first_time'] = 1;
            }

            $lead_data['conversion_data'] = json_encode($conversion_data);
            update_post_meta($lead_id,'wpleads_conversion_count', $c_count); /* Store conversions count */
            update_post_meta($lead_id, 'wpleads_conversion_data', $lead_data['conversion_data']); /* Store conversion object */

        }
    }
}
Inbound Pro Plugin - PHP Codex API documentation generated by ApiGen