/**
  * Sends the leads history email
  *
  * @param   string
  * @return  bool $email_sent    Whether the email contents were sent successfully. A true return value does not automatically mean that the user received the email successfully. It just only means that the method used was able to process the request without any errors.
  */
 function send_new_lead_email($hashkey)
 {
     $ir_contact = new IR_Contact();
     $ir_contact->hashkey = $hashkey;
     $ir_contact->get_contact_history();
     $history = $ir_contact->history;
     $lead_email = isset($history->lead->lead_email) ? $history->lead->lead_email : '';
     $body = null;
     $body = $this->build_body($history);
     // Each line in an email can only be 998 characters long, so lines need to be broken with a wordwrap
     $body = wordwrap($body, 900, "\r\n");
     $options = get_option('inboundrocket_options');
     $to = $options['ir_email'] ? $options['ir_email'] : get_bloginfo('admin_email');
     // Get email from plugin settings, if none set, use admin email
     $tag_status = '';
     if (count($history->lead->last_submission['form_tags'])) {
         $tag_status = __('labeled as', 'inboundrocket') . ' "' . $history->lead->last_submission['form_tags'][0]['tag_text'] . '" ';
     }
     $return_status = $tag_status ? '' : ' ';
     if ($history->lead->total_visits > 1) {
         $return_status = __('by a returning visitor', 'inboundrocket') . ' ';
     }
     if ($history->lead->total_submissions > 1) {
         $return_status = __('by a returning contact', 'inboundrocket') . ' ';
     }
     $subject = __('Form submission', 'inboundrocket') . " " . $tag_status . $return_status . "on " . get_bloginfo('name') . " - " . $lead_email;
     $headers = "From: Inbound Rocket <*****@*****.**>\r\n";
     $headers .= "Reply-To: Inbound Rocket <*****@*****.**>\r\n";
     $headers .= "X-Mailer: PHP/" . phpversion() . "\r\n";
     $headers .= "MIME-Version: 1.0\r\n";
     $headers .= "Content-type: text/html; charset=utf-8\r\n";
     $email_sent = wp_mail($to, $subject, $body, $headers);
     inboundrocket_track_plugin_activity('Contact Notification Sent', array('service' => 'php_mail', 'to_email' => $to));
     return $email_sent;
 }
/**
 * Send Mixpanel event when plugin is activated/deactivated
 *
 * @param   bool
 *
 * @return  bool
 */
function inboundrocket_track_plugin_registration_hook($activated)
{
    if ($activated) {
        inboundrocket_track_plugin_activity("Activated Plugin");
        inboundrocket_set_install_status('activated');
    } else {
        inboundrocket_track_plugin_activity("Deactivated Plugin");
        inboundrocket_set_install_status('deactivated');
    }
    return TRUE;
}
 /**
  * Sets the company_data on a contact
  *
  * @param	object
  * @return	object
  */
 function get_company_details($lead)
 {
     global $blacklist_freemail_domains;
     global $blacklist_nonmail_domains;
     $site_url = site_url();
     $email_domain = end(explode('@', $lead->lead_email));
     $inboundrocket_user = inboundrocket_get_current_user();
     $company_data = '';
     if (strstr($inboundrocket_user['email'], ',')) {
         $inboundrocket_user_email = reset(explode(',', $inboundrocket_user['email']));
     } else {
         $inboundrocket_user_email = $inboundrocket_user['email'];
     }
     if (!in_array($email_domain, $blacklist_nonmail_domains) && !in_array($email_domain, $blacklist_freemail_domains)) {
         if (!$lead->company_data) {
             // Grab the company intel lookup
             $company_data = json_decode($this->query_company_lookup_endpoint($email_domain, $inboundrocket_user_email, $site_url));
             if (isset($company_data->status) && $company_data->status != 'error') {
                 $this->update_company_lookup_data($this->hashkey, serialize($company_data));
                 inboundrocket_track_plugin_activity('Company Lookup Result', array('status' => 'success'));
             } else {
                 inboundrocket_track_plugin_activity('Company Lookup Result', array('status' => 'error'));
             }
         } else {
             $company_data = unserialize($lead->company_data);
         }
     }
     return $company_data;
 }
/**
 * Creates or updates the inboundrocket tables
 */
function inboundrocket_db_install()
{
    global $wpdb;
    $charset_collate = $wpdb->get_charset_collate();
    inboundrocket_set_wpdb_tables();
    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    $sql = "CREATE TABLE IF NOT EXISTS {$wpdb->ir_leads} (\n\t\t  `lead_id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n\t\t  `lead_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\t\t  `hashkey` varchar(16) DEFAULT NULL,\n\t\t  `lead_ip` varchar(40) DEFAULT NULL,\n\t\t  `lead_source` text,\n\t\t  `lead_email` varchar(255) DEFAULT NULL,\n\t\t  `lead_first_name` varchar(255) NOT NULL,\n  \t\t  `lead_last_name` varchar(255) NOT NULL,\n\t\t  `lead_status` set('leads','contact','contacted','customers','ambassadors','commenters','subscribers') NOT NULL DEFAULT 'leads',\n\t\t  `merged_hashkeys` text,\n\t\t  `lead_deleted` int(1) NOT NULL DEFAULT '0',\n\t\t  `blog_id` int(11) unsigned NOT NULL,\n\t\t  `company_data` mediumtext NOT NULL,\n  \t\t  `social_data` mediumtext NOT NULL,\n\t\t  PRIMARY KEY (`lead_id`),\n\t\t  KEY `hashkey` (`hashkey`)\n\t\t) {$charset_collate};";
    dbDelta($sql);
    $sql = "CREATE TABLE IF NOT EXISTS {$wpdb->ir_pageviews} (\n\t\t  `pageview_id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n\t\t  `pageview_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\t\t  `lead_hashkey` varchar(16) NOT NULL,\n\t\t  `pageview_title` varchar(255) NOT NULL,\n\t\t  `pageview_url` text NOT NULL,\n\t\t  `pageview_source` text NOT NULL,\n\t\t  `pageview_session_start` int(1) NOT NULL,\n\t\t  `pageview_deleted` int(1) NOT NULL DEFAULT '0',\n\t\t  `blog_id` int(11) unsigned NOT NULL,\n\t\t  PRIMARY KEY (`pageview_id`),\n\t\t  KEY `lead_hashkey` (`lead_hashkey`)\n\t\t) {$charset_collate};";
    dbDelta($sql);
    $sql = "CREATE TABLE IF NOT EXISTS {$wpdb->ir_submissions} (\n\t\t  `form_id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n\t\t  `form_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\t\t  `lead_hashkey` varchar(16) NOT NULL,\n\t\t  `form_page_title` varchar(255) NOT NULL,\n\t\t  `form_page_url` text NOT NULL,\n\t\t  `form_fields` text NOT NULL,\n\t\t  `form_selector_id` mediumtext NOT NULL,\n\t\t  `form_selector_classes` mediumtext NOT NULL,\n\t\t  `form_hashkey` varchar(16) NOT NULL,\n\t\t  `form_deleted` int(1) NOT NULL DEFAULT '0',\n\t\t  `blog_id` int(11) unsigned NOT NULL,\n\t\t  PRIMARY KEY (`form_id`),\n\t\t  KEY `lead_hashkey` (`lead_hashkey`)\n\t\t) {$charset_collate};";
    dbDelta($sql);
    $sql = "CREATE TABLE IF NOT EXISTS {$wpdb->ir_shares} (\n\t\t  `share_id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n\t\t  `share_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\t\t  `lead_hashkey` varchar(16) NOT NULL,\n\t\t  `share_type` set('contact','ss-twitter-text','is-twitter-image','click-to-tweet','ss-email-text','ss-email-image','ss-facebook-text','is-facebook-image','ss-linkedin-text','is-pinterest-image') NOT NULL,\n\t\t  `share_deleted` int(1) NOT NULL DEFAULT '0',\n\t\t  `share` text NOT NULL,\n\t\t  `post_id` int(11) NOT NULL,\n\t\t  `blog_id` int(11) unsigned NOT NULL,\n\t\t  PRIMARY KEY (`share_id`),\n\t\t  KEY `lead_hashkey` (`lead_hashkey`)\n\t\t) {$charset_collate};";
    dbDelta($sql);
    $sql = "CREATE TABLE IF NOT EXISTS {$wpdb->ir_sharer_stats} (\n\t\t\t`id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n   \t\t\t`share_id` int(11) unsigned NOT NULL,\n   \t\t\t`timestamp` timestamp NOT NULL,\n   \t\t\t`type` TEXT NOT NULL,\n   \t\t\tPRIMARY KEY (`id`),\n   \t\t\tCONSTRAINT `{$wpdb->ir_sharer_stats}` FOREIGN KEY (`share_id`) REFERENCES `{$wpdb->ir_shares}` (`id`) ON DELETE CASCADE\n   \t\t) {$charset_collate};";
    dbDelta($sql);
    $sql = "CREATE TABLE IF NOT EXISTS {$wpdb->ir_tags} (\n\t\t  `tag_id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n\t\t  `tag_text` varchar(255) NOT NULL,\n\t\t  `tag_slug` varchar(255) NOT NULL,\n\t\t  `tag_form_selectors` mediumtext NOT NULL,\n\t\t  `tag_synced_lists` mediumtext NOT NULL,\n\t\t  `tag_order` int(11) unsigned NOT NULL,\n\t\t  `blog_id` int(11) unsigned NOT NULL,\n\t\t  `tag_deleted` int(1) NOT NULL,\n\t\t  PRIMARY KEY (`tag_id`)\n\t\t) {$charset_collate};";
    dbDelta($sql);
    $sql = "CREATE TABLE IF NOT EXISTS {$wpdb->ir_tag_relationships} (\n\t\t  `tag_relationship_id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n\t\t  `tag_id` int(11) unsigned NOT NULL,\n\t\t  `contact_hashkey` varchar(16) NOT NULL,\n  \t\t  `form_hashkey` varchar(16) NOT NULL,\n\t\t  `tag_relationship_deleted` int(1) unsigned NOT NULL,\n\t\t  `blog_id` int(11) unsigned NOT NULL,\n\t\t  PRIMARY KEY (`tag_relationship_id`)\n\t\t) {$charset_collate};";
    dbDelta($sql);
    $sql = "CREATE TABLE IF NOT EXISTS {$wpdb->ir_emails} (\n\t\t  `email_id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n\t\t  `email_subject` varchar(255) NOT NULL,\n\t\t  `email_text_content` varchar(255) NOT NULL,\n\t\t  `email_html_content` mediumtext NOT NULL,\n\t\t  `email_deleted` int(1) NOT NULL,\n\t\t  PRIMARY KEY (`email_id`)\n\t\t) {$charset_collate};";
    dbDelta($sql);
    inboundrocket_update_option('inboundrocket_options', 'ir_db_version', INBOUNDROCKET_DB_VERSION);
    inboundrocket_track_plugin_activity("Databases Installed");
}
 /**
  * Get the leads for the contacts table based on $GET_['contact_type'] or $_GET['s'] (search)
  *
  * @return  array           associative array of all contacts
  */
 function get_contacts()
 {
     /*** 
            == FILTER ARGS ==
            - filter_action (visited)      = visited a specific page url (filter_action) 
            - filter_action (submitted)    = submitted a form on specific page url (filter_action) 
            - filter_content               = content for filter_action
            - filter_form                  = selector id/class
            - num_pageviews                = visited at least #n pages
            - s                            = search query on lead_email/lead_source
        */
     global $wpdb;
     $mysql_search_filter = '';
     $mysql_contact_type_filter = '';
     $mysql_action_filter = '';
     $filter_action_set = FALSE;
     $contact_type = isset($_GET['contact_type']) ? esc_attr($_GET['contact_type']) : 'all';
     $filter_action = isset($_GET['filter_action']) ? esc_attr($_GET['filter_action']) : 'visited';
     $filter_content = isset($_GET['filter_content']) ? esc_attr($_GET['filter_content']) : 'any-page';
     $s = isset($_GET['s']) ? esc_url($_GET['s']) : '';
     $filter_form = isset($_GET['filter_form']) ? esc_attr($_GET['filter_form']) : '';
     // search filter
     if (isset($s)) {
         $wp_version = get_bloginfo('version');
         $escaped_query = '';
         if ($wp_version >= 4) {
             $escaped_query = $wpdb->esc_like($s);
         } else {
             $escaped_query = @like_escape($s);
         }
         $mysql_search_filter = $wpdb->prepare(" AND ( l.lead_email LIKE '%%%s%%' OR l.lead_source LIKE '%%%s%%' ) ", $escaped_query, $escaped_query);
         inboundrocket_track_plugin_activity('Filtered on search term');
     }
     $filtered_contacts = array();
     // contact type filter
     if (!empty($contact_type) && $contact_type !== 'all') {
         // Query for the list_id, then find all hashkeys with that tag ID tied to them. Use those hashkeys to modify the query
         $q = $wpdb->prepare("SELECT \n                    DISTINCT ltr.contact_hashkey as lead_hashkey \n                FROM \n                    {$wpdb->ir_tag_relationships} ltr, {$wpdb->ir_tags} lt \n                WHERE \n                    lt.tag_id = ltr.tag_id AND \n                    ltr.tag_relationship_deleted = 0 AND  \n                    lt.tag_slug = %s GROUP BY ltr.contact_hashkey", $contact_type);
         $filtered_contacts = $wpdb->get_results($q, 'ARRAY_A');
         $num_contacts = count($filtered_contacts);
     } else {
         $q = "SELECT \n                    DISTINCT hashkey as lead_hashkey \n                FROM \n                    {$wpdb->ir_leads}\n                WHERE\n                \tlead_email IS NOT NULL\n                GROUP BY hashkey";
         $nonfiltered_contacts = $wpdb->get_results($q, 'ARRAY_A');
         $num_contacts = count($nonfiltered_contacts);
     }
     if (!empty($filter_action) && $filter_action === 'visited') {
         if (!empty($filter_content) && $filter_content !== 'any-page') {
             $q = $wpdb->prepare("SELECT lead_hashkey FROM {$wpdb->ir_pageviews} WHERE pageview_title LIKE '%%%s%%' GROUP BY lead_hashkey", $filter_content);
             $filtered_contacts = inboundrocket_merge_filtered_contacts($wpdb->get_results($q, 'ARRAY_A'), $filtered_contacts);
             $filter_action_set = TRUE;
             inboundrocket_track_plugin_activity('Filtered on page visited');
         }
     }
     // filter for a form submitted on a specific page
     if (!empty($filter_action) && $filter_action === 'submitted') {
         $filter_form = '';
         $filter_form_query = '';
         if (!empty($filter_form) && $filter_form && $filter_form !== 'any-form') {
             $filter_form = str_replace(array('#', '.'), '', $filter_form);
             $filter_form_query = $wpdb->prepare(" AND ( form_selector_id LIKE '%%%s%%' OR form_selector_classes LIKE '%%%s%%' )", $filter_form, $filter_form);
             inboundrocket_track_plugin_activity('Filtered on form submitted');
         }
         $q = $wpdb->prepare("SELECT lead_hashkey FROM {$wpdb->ir_submissions} WHERE form_page_title LIKE '%%%s%%' ", $filter_content != 'any-page' ? $filter_content : '');
         $q .= $filter_form_query ? $filter_form_query : '';
         $q .= " GROUP BY lead_hashkey";
         $filtered_contacts = inboundrocket_merge_filtered_contacts($wpdb->get_results($q, 'ARRAY_A'), $filtered_contacts);
         $filter_action_set = TRUE;
     }
     $filtered_hashkeys = inboundrocket_explode_filtered_contacts($filtered_contacts);
     $mysql_action_filter = '';
     if ($filter_action_set) {
         // If a filter action is set and there are no contacts, do a blank
         $mysql_action_filter = " AND l.hashkey IN ( " . ($filtered_hashkeys ? $filtered_hashkeys : "''") . " ) ";
     } else {
         $mysql_action_filter = $filtered_hashkeys ? " AND l.hashkey IN ( " . $filtered_hashkeys . " ) " : '';
     }
     // If a filter action isn't set, use the filtered hashkeys if they exist, else, don't include the statement
     // There's a filter and leads are in it
     if (isset($contact_type) && ($num_contacts || !$contact_type) || !isset($contact_type)) {
         $q = $wpdb->prepare("\n                SELECT \n                    l.lead_id AS lead_id,\n                    COUNT(DISTINCT ls.share_id) AS lead_shares,\n                    LOWER(DATE_SUB(l.lead_date, INTERVAL %d HOUR)) AS lead_date, l.lead_ip, l.lead_source, l.lead_email, l.hashkey, l.lead_first_name, l.lead_last_name,\n                    COUNT(DISTINCT s.form_id) AS lead_form_submissions,\n                    COUNT(DISTINCT p.pageview_id) AS lead_pageviews,\n                    LOWER(DATE_SUB(MAX(p.pageview_date), INTERVAL %d HOUR)) AS last_visit,\n                    ( SELECT COUNT(DISTINCT pageview_id) FROM {$wpdb->ir_pageviews} WHERE lead_hashkey = l.hashkey AND pageview_session_start = 1 AND pageview_deleted = 0 ) AS visits,\n                    ( SELECT MIN(pageview_source) AS pageview_source FROM {$wpdb->ir_pageviews} WHERE lead_hashkey = l.hashkey AND pageview_session_start = 1 AND pageview_deleted = 0 ) AS pageview_source \n                FROM \n                    {$wpdb->ir_leads} l\n                LEFT JOIN {$wpdb->ir_submissions} s ON l.hashkey = s.lead_hashkey\n                LEFT JOIN {$wpdb->ir_pageviews} p ON l.hashkey = p.lead_hashkey\n                LEFT JOIN {$wpdb->ir_shares} ls ON l.hashkey = ls.lead_hashkey \n                WHERE l.lead_email != '' AND l.lead_deleted = 0 AND l.hashkey != '' ", $wpdb->db_hour_offset, $wpdb->db_hour_offset);
         $q .= $mysql_contact_type_filter;
         $q .= $mysql_search_filter ? $mysql_search_filter : "";
         $q .= $mysql_action_filter ? $mysql_action_filter : "";
         $q .= " GROUP BY l.hashkey";
         $leads = $wpdb->get_results($q);
     } else {
         $leads = array();
     }
     $all_leads = array();
     $contact_count = 0;
     $num_pageviews = isset($_GET['num_pageviews']) ? esc_attr($_GET['num_pageviews']) : '';
     $page = isset($_REQUEST['page']) ? esc_attr($_REQUEST['page']) : '';
     $paged = isset($_GET['paged']) ? esc_attr($_GET['paged']) : '';
     if (count($leads)) {
         foreach ($leads as $key => $lead) {
             // filter for number of page views and skipping lead if it doesn't meet the minimum
             if (isset($filter_action) && $filter_action === 'num_pageviews') {
                 if ($lead->lead_pageviews < $filter_content) {
                     continue;
                 }
             }
             $url = inboundrocket_strip_params_from_url($lead->lead_source);
             $redirect_url = '';
             if (isset($contact_type) || isset($filter_action) || isset($filter_form) || isset($filter_content) || isset($num_pageviews) || isset($s) || isset($paged)) {
                 $redirect_url = urlencode(inboundrocket_get_current_url());
             }
             $lead_array = array('ID' => $lead->lead_id, 'hashkey' => $lead->hashkey, 'email' => sprintf('<a href="?page=%s&action=%s&lead=%s%s">' . "<img class='pull-left inboundrocket-contact-avatar inboundrocket-dynamic-avatar_" . substr($lead->lead_id, -1) . "' src='http://www.gravatar.com/avatar/" . md5(strtolower(trim($lead->lead_email))) . "' width='50px' height='50px' style='margin-top: 2px; border-radius: 25px;'/> " . '</a>', $page, 'view', $lead->lead_id, $redirect_url ? '&redirect_to=' . $redirect_url : '') . sprintf('<a href="?page=%s&action=%s&lead=%s%s">%s' . $lead->lead_email . '</a>', $page, 'view', $lead->lead_id, $redirect_url ? '&redirect_to=' . $redirect_url : '', strlen($lead->lead_first_name) || strlen($lead->lead_last_name) ? '<b>' . $lead->lead_first_name . ' ' . $lead->lead_last_name . '</b><br>' : ''), 'visits' => !isset($lead->visits) ? 1 : $lead->visits, 'submissions' => $lead->lead_form_submissions, 'shares' => isset($lead->lead_shares) ? $lead->lead_shares : '0', 'pageviews' => isset($lead->lead_pageviews) ? $lead->lead_pageviews : '0', 'date' => date('Y-m-d g:ia', strtotime($lead->lead_date)), 'source' => $lead->pageview_source ? "<a title=\"Visit page\" href=\"" . esc_url($lead->pageview_source) . "\" target=\"_blank\">" . inboundrocket_strip_params_from_url($lead->pageview_source) . "</a>" : 'Direct', 'last_visit' => date('Y-m-d g:ia', strtotime($lead->last_visit)), 'source' => $lead->lead_source ? "<a title=\"Visit page\" href=\"" . esc_url($lead->lead_source) . "\" target=\"_blank\">" . inboundrocket_strip_params_from_url($lead->lead_source) . "</a>" : 'Direct');
             array_push($all_leads, $lead_array);
             $contact_count++;
         }
     }
     $this->total_filtered = count($all_leads);
     return $all_leads;
 }
 function check_admin_action()
 {
     if (isset($_GET['inboundrocket_action'])) {
         switch ($_GET['inboundrocket_action']) {
             case 'activate':
                 $power_up = esc_attr($_GET['power_up']);
                 if (strpos($power_up, ',') !== false) {
                     $power_ups = explode(',', $power_up);
                     foreach ($power_ups as $power_up) {
                         WPInboundRocket::activate_power_up($power_up, FALSE);
                         inboundrocket_track_plugin_activity($power_up . " power-up activated");
                     }
                 } else {
                     WPInboundRocket::activate_power_up($power_up, FALSE);
                     inboundrocket_track_plugin_activity($power_up . " power-up activated");
                 }
                 if (isset($_GET['redirect_to'])) {
                     wp_redirect($_GET['redirect_to']);
                 } else {
                     wp_redirect(admin_url('admin.php?page=inboundrocket_power_ups'));
                 }
                 exit;
                 break;
             case 'deactivate':
                 $power_up = esc_attr($_GET['power_up']);
                 if (strpos($power_up, ',') !== false) {
                     $power_ups = explode(',', $power_up);
                     foreach ($power_ups as $power_up) {
                         WPInboundRocket::deactivate_power_up($power_up, FALSE);
                         inboundrocket_track_plugin_activity($power_up . " power-up deactivated");
                     }
                 } else {
                     WPInboundRocket::deactivate_power_up($power_up, FALSE);
                     inboundrocket_track_plugin_activity($power_up . " power-up deactivated");
                 }
                 wp_redirect(admin_url('admin.php?page=inboundrocket_power_ups'));
                 exit;
                 break;
         }
     }
 }