Plugin Directory

Changeset 1266757


Ignore:
Timestamp:
10/15/2015 05:06:41 PM (9 years ago)
Author:
unbouncewordpress
Message:

Releasing version 1.0.5

Location:
unbounce
Files:
2 added
14 edited
1 copied

Legend:

Unmodified
Added
Removed
  • unbounce/tags/1.0.5/UBConfig.php

    r1256907 r1266757  
    88  const UB_PAGE_SERVER_DOMAIN_KEY = 'ub-page-server-domain';
    99  const UB_REMOTE_LOG_URL_KEY = 'ub-remote-log-url';
     10  const UB_REMOTE_EVENTS_URL_KEY = 'ub-remote-events-url';
    1011  const UB_API_URL_KEY = 'ub-api-url';
    1112  const UB_API_CLIENT_ID_KEY = 'ub-api-client-id';
    1213  const UB_AUTHORIZED_DOMAINS_KEY = 'ub-authorized-domains';
    1314  const UB_HAS_AUTHORIZED_KEY = 'ub-has-authorized';
     15  const UB_USER_ID_KEY = 'ub-user-id';
     16  const UB_DOMAIN_ID_KEY = 'ub-domain-id';
     17  const UB_CLIENT_ID_KEY = 'ub-client-id';
    1418  const UB_CACHE_TIMEOUT_ENV_KEY = 'UB_WP_ROUTES_CACHE_EXP';
    15   const UB_USER_AGENT = 'Unbounce WP Plugin 1.0.4';
    16   const UB_VERSION = '1.0.4';
     19  const UB_USER_AGENT = 'Unbounce WP Plugin 1.0.5';
     20  const UB_VERSION = '1.0.5';
    1721
    1822  public static function default_page_server_domain() {
     
    2933  }
    3034
     35  public static function default_remote_events_url() {
     36    $url = getenv('UB_REMOTE_EVENTS_URL');
     37    if ($url == null) {
     38      return 'https://events-gateway.unbounce.com/events/domains';
     39    }
     40    return $url;
     41  }
     42
    3143  public static function default_api_url() {
    3244    $url = getenv('UB_API_URL');
     
    5264  }
    5365
     66  public static function remote_events_url() {
     67    return get_option(UBConfig::UB_REMOTE_EVENTS_URL_KEY, UBConfig::default_remote_events_url());
     68  }
     69
    5470  public static function api_url() {
    5571    return get_option(UBConfig::UB_API_URL_KEY, UBConfig::default_api_url());
     
    7692  }
    7793
     94  public static function create_none_response() {
     95    return array(array('status' => 'NONE'), null, null, null);
     96  }
     97
     98  public static function create_same_response($etag, $max_age) {
     99    return array(array('status' => 'SAME'), $etag, $max_age, null);
     100  }
     101
     102  public static function create_new_response($etag, $max_age, $proxyable_url_set) {
     103    return array(array('status' => 'NEW'), $etag, $max_age, $proxyable_url_set);
     104  }
     105
     106  public static function create_failure_response($failure_message) {
     107    return array(array('status' => 'FAILURE',
     108                       'failure_message' => $failure_message),
     109                 null, null, null);
     110  }
     111
     112  public static function domain() {
     113    return parse_url(get_home_url(), PHP_URL_HOST);
     114  }
     115
     116  public static function domain_with_port() {
     117    $port = parse_url(get_home_url(), PHP_URL_PORT);
     118    $host = parse_url(get_home_url(), PHP_URL_HOST);
     119    if ($port) {
     120      return $host . ':' . $port;
     121    } else {
     122      return $host;
     123    }
     124  }
     125
    78126  public static function fetch_proxyable_url_set($domain, $etag, $ps_domain) {
    79127    if(!$domain) {
    80       UBLogger::warning('Domain not provided, not fetching sitemap.xml');
    81       return array('FAILURE', null, null, null);
     128      $failure_message = 'Domain not provided, not fetching sitemap.xml';
     129      UBLogger::warning($failure_message);
     130      return UBConfig::create_failure_response($failure_message);
    82131    }
    83132
     
    130179        if ($success) {
    131180          UBLogger::debug("Retrieved new routes, HTTP code: '$http_code'");
    132           return array('NEW', $etag, $max_age, $result);
     181          return UBConfig::create_new_response($etag, $max_age, $result);
    133182        }
    134183        else {
    135184          $errors = join(', ', $result);
    136           UBLogger::warning("An error occurred while processing routes, XML errors: '$errors'");
    137           return array('FAILURE', null, null, null);
     185          $failure_message = "An error occurred while processing pages, XML errors: '$errors'";
     186          UBLogger::warning($failure_message);
     187          return UBConfig::create_failure_response($failure_message);
    138188        }
    139189      }
    140190      if ($http_code == 304) {
    141191        UBLogger::debug("Routes have not changed, HTTP code: '$http_code'");
    142         return array('SAME', $etag, $max_age, null);
     192        return UBConfig::create_same_response($etag, $max_age);
    143193      }
    144194      if ($http_code == 404) {
    145195        UBLogger::debug("No routes to retrieve, HTTP code: '$http_code'");
    146         return array('NONE', null, null, null);
     196        return UBConfig::create_none_response();
    147197      }
    148198      else {
    149         UBLogger::warning("An error occurred while retrieving routes; HTTP code: '$http_code'; Error: " . $curl_error);
    150         return array('FAILURE', null, null, null);
    151       }
     199        $failure_message = "An error occurred while retrieving routes; HTTP code: '$http_code'; Error: " . $curl_error;
     200        UBLogger::warning($failure_message);
     201        return UBConfig::create_failure_response($failure_message);
     202      }
     203
    152204    } catch (Exception $e) {
    153       UBLogger::warning("An error occurred while retrieving routes; Error: " . $e);
    154       return array('FAILURE', null, null, null);
     205      $failure_message = "An error occurred while retrieving routes; Error: " . $e;
     206      UBLogger::warning($failure_message);
     207      return UBConfig::create_failure_response($failure_message);
    155208    }
    156209  }
     
    224277      list($routes_status, $etag, $max_age, $proxyable_url_set_new) = $result_array;
    225278
    226       if ($routes_status == 'NEW') {
     279      if ($routes_status['status'] == 'NEW') {
    227280        $domain_info['proxyable_url_set'] = $proxyable_url_set_new;
    228281        $domain_info['proxyable_url_set_etag'] = $etag;
    229282        $domain_info['proxyable_url_set_cache_timeout'] = $max_age;
    230283      }
    231       elseif ($routes_status == 'SAME') {
     284      elseif ($routes_status['status'] == 'SAME') {
    232285        // Just extend the cache
    233286        $domain_info['proxyable_url_set_cache_timeout'] = $max_age;
    234287      }
    235       elseif ($routes_status == 'NONE') {
     288      elseif ($routes_status['status'] == 'NONE') {
    236289        $domain_info['proxyable_url_set'] = array();
    237290        $domain_info['proxyable_url_set_etag'] = null;
    238291      }
    239       elseif ($routes_status == 'FAILURE') {
     292      elseif ($routes_status['status'] == 'FAILURE') {
    240293        UBLogger::warning('Route fetching failed');
    241294      }
     
    244297      }
    245298
     299      // Creation of domain_info entry
    246300      $domain_info['proxyable_url_set_fetched_at'] = $current_time;
    247       $domain_info['last_status'] = $routes_status;
     301      $domain_info['last_status'] = $routes_status['status'];
     302      if ($routes_status['status'] == 'FAILURE') {
     303        $domain_info['failure_message'] = $routes_status['failure_message'];
     304      }
    248305      $domains_info[$domain] = $domain_info;
    249306      $options_setter(UBConfig::UB_ROUTES_CACHE_KEY, $domains_info);
     
    253310                                       array('proxyable_url_set',
    254311                                             'proxyable_url_set_fetched_at',
     312                                             'failure_message',
    255313                                             'last_status'));
    256314  }
     
    271329  }
    272330
     331  public static function update_authorization_options($domains, $data) {
     332    update_option(UBConfig::UB_USER_ID_KEY, $data['user_id']);
     333    update_option(UBConfig::UB_DOMAIN_ID_KEY, $data['domain_id']);
     334    update_option(UBConfig::UB_CLIENT_ID_KEY, $data['client_id']);
     335    update_option(UBConfig::UB_AUTHORIZED_DOMAINS_KEY, $domains);
     336    update_option(UBConfig::UB_HAS_AUTHORIZED_KEY, true);
     337  }
     338
     339  public static function int_min() {
     340    return (PHP_INT_MAX * -1) - 1;
     341  }
     342
    273343}
    274344?>
  • unbounce/tags/1.0.5/UBDiagnostics.php

    r1256907 r1266757  
    2929      'PHP Version'             => phpversion(),
    3030      'WordPress Version'       => UBDiagnostics::wordpress_version(),
    31       'Unbounce Plugin Version' => "1.0.4",
     31      'Unbounce Plugin Version' => "1.0.5",
    3232      'Permalink Structure'     => get_option('permalink_structure', ''),
    3333      'Domain'                  => $domain,
    3434      'Domain Authorized'       => print_r(UBConfig::is_authorized_domain($domain), true),
    35       'Domain Information'      => print_r($domain_info, true),
    36       'Page Server Domain'      => UBConfig::page_server_domain(),
    37       'Remote Log URL'          => UBConfig::remote_log_url(),
    38       'API URL'                 => UBConfig::api_url(),
    39       'API Client ID'           => UBConfig::api_client_id(),
    40       'Authorized Domains'      => join(', ', UBConfig::authorized_domains()),
    4135      'Has Authorized'          => print_r(UBConfig::has_authorized(), true),
    4236      'Active Plugins'          => print_r(get_option('active_plugins'), true),
     
    4640      'Extensions'              => print_r(get_loaded_extensions(), true),
    4741      'Operating System'        => php_uname(),
    48       'Checks'                  => print_r(UBDiagnostics::checks($domain, $domain_info), true)
     42      'Checks'                  => print_r(UBDiagnostics::checks($domain, $domain_info), true),
     43      'Options'                 => print_r(UBDiagnostics::ub_options(), true)
    4944    );
     45  }
     46
     47  private static function ub_options() {
     48    $ub_options = array_filter(wp_load_alloptions(), function($key) {
     49      return strpos($key, 'ub-') === 0;
     50    }, ARRAY_FILTER_USE_KEY);
     51
     52    return array_map(function($value) {
     53      $unserialized = @unserialize($value);
     54      return $unserialized ? $unserialized : $value;
     55    }, $ub_options);
    5056  }
    5157
     
    6672  private static function last_status_success($domain_info) {
    6773    $last_status = UBUtil::array_fetch($domain_info, 'last_status');
    68     return $last_status !== 'FAILURE' && $last_status !== null;
     74    return $last_status !== null && $last_status !== 'FAILURE';
    6975  }
    7076
  • unbounce/tags/1.0.5/UBHTTP.php

    r1256907 r1266757  
    228228  }
    229229
     230  public static function send_event_to_events_gateway($url, $data_string) {
     231    try {
     232      $stream_function = function($curl, $str) { return strlen($str); };
     233
     234      $curl = curl_init();
     235      $curl_options = array(
     236        CURLOPT_URL => $url,
     237        CURLOPT_CUSTOMREQUEST => 'POST',
     238        CURLOPT_USERAGENT => UBConfig::UB_USER_AGENT,
     239        CURLOPT_FOLLOWLOCATION => false,
     240        CURLOPT_HTTPHEADER => array(
     241          'Content-Type: application/json',
     242          'Content-Length: ' . strlen($data_string)
     243        ),
     244        CURLOPT_HEADERFUNCTION => $stream_function,
     245        CURLOPT_WRITEFUNCTION => $stream_function,
     246        CURLOPT_POSTFIELDS => $data_string,
     247        CURLOPT_TIMEOUT => 2
     248      );
     249      curl_setopt_array($curl, $curl_options);
     250      $success = curl_exec($curl);
     251      $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
     252
     253      if(!$success) {
     254        $message = 'Unable to send log messages to ' . $url . ': "'
     255                 . curl_error($curl) . '" - HTTP status: ' . curl_errno($curl);
     256        UBLogger::warning($message);
     257      } elseif($http_code >= 200 && $http_code < 300) {
     258        $message = 'Successfully sent log messsages to ' . $url
     259                 . ' - HTTP status: ' . $http_code;
     260        UBLogger::debug($message);
     261      } else {
     262        $message = 'Unable to send log messages to ' . $url
     263                 . ' - HTTP status: ' . $http_code;
     264        UBLogger::warning($message);
     265      }
     266
     267      curl_close($curl);
     268    } catch (Exception $e) {
     269      $message = 'Unable to send log messages to ' . $url
     270               . ' - Error: ' . $e;
     271      UBLogger::warning($message);
     272    }
     273  }
     274
    230275}
    231276
  • unbounce/tags/1.0.5/UBLogger.php

    r1255261 r1266757  
    22
    33require_once dirname(__FILE__) . '/UBConfig.php';
     4require_once dirname(__FILE__) . '/UBEvents.php';
    45
    56class UBLogger {
     
    1617  public static function upload_logs_to_unbounce($url) {
    1718    if(UBConfig::remote_debug_logging_enabled()) {
    18       $datetime = new DateTime('NOW', new DateTimeZone('UTC'));
    1919      $data = array(
    20         'type' => 'WordpressLogV1.0',
    2120        'messages' => $GLOBALS['wp_log'][UBConfig::UB_PLUGIN_NAME],
    2221        'vars' => $GLOBALS['wp_log'][UBConfig::UB_PLUGIN_NAME . '-vars'],
    23         'id' => uniqid(),
    24         'time_sent' => $datetime->format('Y-m-d\TH:i:s.000\Z'),
    25         'source' => UBConfig::UB_USER_AGENT . ' ' . gethostname()
    2622      );
    27       $json_unescaped = json_encode($data);
    28       $data_string = str_replace('\\/', '/', $json_unescaped);
    29 
    30       try {
    31         $curl = curl_init();
    32         $curl_options = array(
    33           CURLOPT_URL => $url,
    34           CURLOPT_CUSTOMREQUEST => 'POST',
    35           CURLOPT_USERAGENT => UBConfig::UB_USER_AGENT,
    36           CURLOPT_FOLLOWLOCATION => false,
    37           CURLOPT_HTTPHEADER => array(
    38             'Content-Type: application/json',
    39             'Content-Length: ' . strlen($data_string)
    40           ),
    41           CURLOPT_POSTFIELDS => $data_string,
    42           CURLOPT_TIMEOUT => 2
    43         );
    44         curl_setopt_array($curl, $curl_options);
    45         $success = curl_exec($curl);
    46         $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    47 
    48         if(!$success) {
    49           $message = 'Unable to send log messages to ' . $url . ': "'
    50                    . curl_error($curl) . '" - HTTP status: ' . curl_errno($curl);
    51           UBLogger::warning($message);
    52         } elseif($http_code >= 200 && $http_code < 300) {
    53           $message = 'Successfully sent log messsages to ' . $url
    54                    . ' - HTTP status: ' . $http_code;
    55           UBLogger::debug($message);
    56         } else {
    57           $message = 'Unable to send log messages to ' . $url
    58                    . ' - HTTP status: ' . $http_code;
    59           UBLogger::warning($message);
    60         }
    61 
    62         curl_close($curl);
    63       } catch (Exception $e) {
    64         $message = 'Unable to send log messages to ' . $url
    65                  . ' - Error: ' . $e;
    66         UBLogger::warning($message);
    67       }
     23      UBHTTP::send_event_to_events_gateway($url, UBEvents::log_event($data));
    6824    }
    6925  }
  • unbounce/tags/1.0.5/Unbounce-Page.php

    r1256907 r1266757  
    44Plugin URI: http://unbounce.com
    55Description: Publish Unbounce Landing Pages to your Wordpress Domain.
    6 Version: 1.0.4
     6Version: 1.0.5
    77Author: Unbounce
    88Author URI: http://unbounce.com
     
    1818require_once dirname(__FILE__) . '/UBIcon.php';
    1919require_once dirname(__FILE__) . '/UBPageTable.php';
     20require_once dirname(__FILE__) . '/UBEvents.php';
    2021
    2122register_activation_hook(__FILE__, function() {
     
    3334             UBConfig::default_authorized_domains());
    3435  add_option(UBConfig::UB_HAS_AUTHORIZED_KEY);
     36  add_option(UBConfig::UB_REMOTE_EVENTS_URL_KEY,
     37             UBConfig::default_remote_events_url());
     38  add_option(UBConfig::UB_USER_ID_KEY);
     39  add_option(UBConfig::UB_DOMAIN_ID_KEY);
     40  add_option(UBConfig::UB_CLIENT_ID_KEY);
    3541});
    3642
     
    4450  delete_option(UBConfig::UB_AUTHORIZED_DOMAINS_KEY);
    4551  delete_option(UBConfig::UB_HAS_AUTHORIZED_KEY);
     52  delete_option(UBConfig::UB_REMOTE_EVENTS_URL_KEY);
     53  delete_option(UBConfig::UB_USER_ID_KEY);
     54  delete_option(UBConfig::UB_DOMAIN_ID_KEY);
     55  delete_option(UBConfig::UB_CLIENT_ID_KEY);
    4656});
    4757
     
    4959  UBLogger::setup_logger();
    5060
    51   $domain = parse_url(get_home_url(), PHP_URL_HOST);
     61  $domain = UBConfig::domain();
    5262
    5363  if(!UBConfig::is_authorized_domain($domain)) {
     
    90100  }
    91101  elseif ($url_purpose == 'HealthCheck') {
     102    if (UBConfig::domain_with_port() !== UBUtil::array_fetch($_SERVER, 'HTTP_HOST')) {
     103      http_response_code(412);
     104    }
     105
    92106    header('Content-Type: application/json');
    93107    $version = UBConfig::UB_VERSION;
     
    105119    }
    106120
    107     // Disable CDN for W3 Total Cache
    108121    if(!defined('DONOTCDN')) {
    109122      define('DONOTCDN', true);
     123    }
     124
     125    if(!defined('DONOTCACHEDB')) {
     126      define('DONOTCACHEDB', true);
     127    }
     128
     129    if(!defined('DONOTMINIFY')) {
     130      define('DONOTMINIFY', true);
     131    }
     132
     133    if(!defined('DONOTCACHEOBJECT')) {
     134      define('DONOTCACHEOBJECT', true);
    110135    }
    111136
     
    137162    exit(0);
    138163  }
    139 });
     164}, UBConfig::int_min());
    140165
    141166add_action('admin_init', function() {
     
    165190}, 0);
    166191
    167 function authorization_button($text, $wrap_in_p = false, $is_primary = true, $outer_text = '') {
     192function authorization_button($text, $domain, $wrap_in_p = false, $is_primary = true, $outer_text = '') {
    168193  $set_domains_url = admin_url('admin-post.php?action=set_unbounce_domains');
    169194  echo "<form method='post' action='$set_domains_url'>";
    170195  echo "<input type='hidden' name='domains' />";
     196  echo "<input type='hidden' name='user_id' />";
     197  echo "<input type='hidden' name='domain_id' />";
     198  echo "<input type='hidden' name='client_id' />";
    171199  echo $outer_text;
    172200  $style = $outer_text ? 'vertical-align: baseline' : '';
     
    179207                               'data-api-url' => UBConfig::api_url(),
    180208                               'data-api-client-id' => UBConfig::api_client_id(),
     209                               'data-wordpress-domain-name' => $domain,
    181210                               'style' => $style));
    182211  echo '</form>';
     
    217246    $proxyable_url_set_fetched_at = UBUtil::array_fetch($domain_info, 'proxyable_url_set_fetched_at');
    218247    echo '<p>Last refreshed  ' . UBUtil::time_ago($proxyable_url_set_fetched_at) . '.</p>';
    219     authorization_button('Update WordPress Enabled Domains', false, false);
     248    authorization_button('Update WordPress Enabled Domains', $domain, false, false);
    220249    echo '</p>';
    221250    echo '</div>';
     
    234263      $diagnostics_url = admin_url('admin.php?page=unbounce-pages-diagnostics');
    235264      echo "<br/><a class='ub-diagnostics-link' href='${diagnostics_url}'>Diagnostics</a>";
    236       echo '<p class="ub-version">Unbounce Version 1.0.4</p>';
     265      echo '<p class="ub-version">Unbounce Version 1.0.5</p>';
    237266    });
    238267  } else {
     
    249278      echo '</form>';
    250279
    251       authorization_button('Update WordPress Enabled Domains', false, false, 'After adding your domain in Unbounce, come back here and ');
     280      authorization_button('Update WordPress Enabled Domains', $domain, false, false, 'After adding your domain in Unbounce, come back here and ');
    252281    } else {
    253282      echo '<div class="ub-authorize-message">Before you can publish your pages to WordPress you will have to authorize your Unbounce account.</div>';
    254283
    255       authorization_button('Authorize With Unbounce', true);
     284      authorization_button('Authorize With Unbounce', $domain, true);
    256285
    257286      $try_unbounce_url = "http://unbounce.com/landing-pages-for-wordpress/";
     
    271300      $diagnostics_url = admin_url('admin.php?page=unbounce-pages-diagnostics');
    272301      echo "<br/><a class='ub-diagnostics-link' href='${diagnostics_url}'>Diagnostics</a>";
    273       echo '<p class="ub-version">Unbounce Version 1.0.4</p>';
     302      echo '<p class="ub-version">Unbounce Version 1.0.5</p>';
    274303    });
    275304  }
     
    307336  // Main admin page
    308337  $print_admin_panel = function() {
    309     $domain = parse_url(get_home_url(), PHP_URL_HOST);
     338    $domain = UBConfig::domain();
    310339    $domain_info = UBConfig::read_unbounce_domain_info($domain, false);
    311340
     
    322351  // Diagnostics page
    323352  $print_diagnostics_panel = function() {
    324     $domain = parse_url(get_home_url(), PHP_URL_HOST);
     353    $domain = UBConfig::domain();
    325354    $domain_info = UBConfig::read_unbounce_domain_info($domain, false);
    326355
     
    337366
    338367add_action('admin_post_set_unbounce_domains', function() {
    339   $domains_json = UBUtil::array_fetch($_POST, 'domains', '');
    340   $domains = explode(',', $domains_json);
    341 
    342   if($domains_json && is_array($domains)) {
    343     update_option(UBConfig::UB_AUTHORIZED_DOMAINS_KEY, $domains);
    344     update_option(UBConfig::UB_HAS_AUTHORIZED_KEY, true);
     368  $domains_list = UBUtil::array_fetch($_POST, 'domains', '');
     369  $domains = explode(',', $domains_list);
     370
     371  if($domains && is_array($domains)) {
    345372    $authorization = 'success';
     373    $has_authorized = get_option(UBConfig::UB_HAS_AUTHORIZED_KEY, false);
     374
     375    $data = array(
     376      'domain_name' => UBConfig::domain(),
     377      'first_authorization' => !$has_authorized,
     378      'user_id' => UBUtil::array_fetch($_POST, 'user_id', ''),
     379      'client_id' => UBUtil::array_fetch($_POST, 'client_id', ''),
     380      'domain_id' => UBUtil::array_fetch($_POST, 'domain_id', ''),
     381    );
     382
     383    UBConfig::update_authorization_options($domains, $data);
     384
     385    if(UBConfig::is_authorized_domain(UBConfig::domain())) {
     386      $event = UBEvents::successful_authorization_event($data);
     387    } else {
     388      $event = UBEvents::failed_authorization_event($data);
     389    }
     390    UBHTTP::send_event_to_events_gateway(UBConfig::remote_events_url(), $event);
    346391  } else {
    347392    $authorization = 'failure';
     
    356401
    357402add_action('admin_post_flush_unbounce_pages', function() {
    358   $domain = parse_url(get_home_url(), PHP_URL_HOST);
     403  $domain = UBConfig::domain();
    359404  // Expire cache and redirect
    360405  $_domain_info = UBConfig::read_unbounce_domain_info($domain, true);
     
    365410
    366411add_action('shutdown', function() {
    367   UBLogger::upload_logs_to_unbounce(get_option(UBConfig::UB_REMOTE_LOG_URL_KEY));
     412  UBLogger::upload_logs_to_unbounce(UBConfig::remote_log_url());
    368413});
    369414
  • unbounce/tags/1.0.5/js/set-unbounce-domains.js

    r1248703 r1266757  
    11(function($) {
    22
    3   function apiGet(url, token) {
    4     var request = $.ajax({
     3  function apiGetPromise(url, token) {
     4    return $.ajax({
    55      url: url,
    66      method: 'get',
     
    88                 'Accept': 'application/vnd.unbounce.api.v0.4+json' },
    99      dataType: 'json'
    10     });
    11     return Rx.Observable.fromPromise(request.promise());
     10    }).promise();
    1211  }
    1312
    14   function getDomainNames(result) {
    15     if($.isArray(result.domains)) {
     13  function apiGet(url, token) {
     14    return Rx.Observable.fromPromise(apiGetPromise(url, token));
     15  }
     16
     17  function getDomainData(subAccount, domains) {
     18    if($.isArray(domains)) {
    1619      return Rx.Observable.fromArray(
    17         $.map(result.domains, function(domain) {
     20        $.map(domains, function(domain) {
    1821          if(domain && domain.name) {
    19             return domain.name;
     22            return {
     23              clientId: subAccount.id,
     24              domainId: domain.id,
     25              name: domain.name
     26            };
    2027          } else {
    2128            throw 'Unable to fetch domain name';
     
    2734  }
    2835
    29   function getUserSubAccountIds(user) {
     36  function getUserSubAccounts(user, token) {
    3037    if(user.metadata && user.metadata.related && $.isArray(user.metadata.related.sub_accounts)) {
    31       return Rx.Observable.fromArray(
    32         $.map(user.metadata.related.sub_accounts, function(sub_account_url) {
    33           var pieces = sub_account_url.split('/');
    34           return pieces[pieces.length - 1];
    35         }));
     38      var promises = $.map(user.metadata.related.sub_accounts, function(subAccountUrl) {
     39        return apiGetPromise(subAccountUrl, token);
     40      });
     41      return Rx.Observable.fromArray(promises).flatMap(Rx.Observable.fromPromise);
    3642    } else {
    3743      throw 'Unable to fetch user';
     
    3945  }
    4046
    41   function postDomainsToWordpress($form, domains) {
    42     $form.find('[name="domains"]').val(domains.join(','));
     47  function postDomainsToWordpress($form, data, wordpressDomainName) {
     48    if($.isArray(data.domains)) {
     49      var wordpressDomains = data.domains.filter(function(domain) {
     50        return domain.name === wordpressDomainName;
     51      });
     52
     53      if(wordpressDomains[0]) {
     54        var wordpressDomain = wordpressDomains[0];
     55        $form.find('[name="domain_id"]').val(wordpressDomain.domainId);
     56        $form.find('[name="client_id"]').val(wordpressDomain.clientId);
     57      }
     58
     59      var domainNames = $.map(data.domains, function(domain) {
     60        return domain.name;
     61      });
     62
     63      $form.find('[name="user_id"]').val(data.userId);
     64      $form.find('[name="domains"]').val(domainNames.join(','));
     65    }
     66
    4367    $form.submit();
    4468  }
     
    6488          redirectUri = $submitButton.attr('data-redirect-uri'),
    6589          apiClientId = $submitButton.attr('data-api-client-id'),
     90          wordpressDomainName = $submitButton.attr('data-wordpress-domain-name'),
    6691          getTokenUrl = apiUrl + '/oauth/authorize?response_type=token&client_id=' + apiClientId + '&redirect_uri=' + redirectUri,
    6792          getUserUrl = apiUrl + '/users/self?limit=1000',
     
    84109        loadingUI($submitButton, loadingText);
    85110
    86         var source = apiGet(getUserUrl, accessToken)
     111        var userObservable = apiGet(getUserUrl, accessToken).publish(),
     112            domainsObservable = userObservable
    87113              .flatMap(function(user) {
    88                 return getUserSubAccountIds(user);
    89               })
    90               .flatMap(function (subAccountId) {
    91                 return apiGet(getDomainsUrl.replace('{subAccountId}', subAccountId), accessToken);
    92               })
    93               .flatMap(function(domains) {
    94                 return getDomainNames(domains);
     114                return getUserSubAccounts(user, accessToken);
     115              }).flatMap(function (subAccount) {
     116                return apiGet(getDomainsUrl.replace('{subAccountId}', subAccount.id), accessToken)
     117                  .flatMap(function(response) {
     118                    return getDomainData(subAccount, response.domains);
     119                  });
    95120              }).toArray().publish(),
    96             subscription = source.subscribe(
     121            userDomainsObservable = Rx.Observable.zip(
     122              userObservable,
     123              domainsObservable,
     124              function(user, domains) {
     125                return {userId: user.id, domains: domains};
     126              }).publish(),
     127            subscription = userDomainsObservable.subscribe(
    97128              function (domains) {
    98                 postDomainsToWordpress($form, domains);
     129                postDomainsToWordpress($form, domains, wordpressDomainName);
    99130              },
    100131              function (error) {
     
    107138              });
    108139
    109         source.connect();
     140        userDomainsObservable.connect();
     141        domainsObservable.connect();
     142        userObservable.connect();
    110143      }
    111144    }
  • unbounce/tags/1.0.5/readme.txt

    r1256907 r1266757  
    44Requires at least: 4.1.5
    55Tested up to: 4.3
    6 Stable tag: 1.0.4
     6Stable tag: 1.0.5
    77License: GPLv2 or later
    88License URI: http://www.gnu.org/licenses/gpl-2.0.html
  • unbounce/trunk/UBConfig.php

    r1256907 r1266757  
    88  const UB_PAGE_SERVER_DOMAIN_KEY = 'ub-page-server-domain';
    99  const UB_REMOTE_LOG_URL_KEY = 'ub-remote-log-url';
     10  const UB_REMOTE_EVENTS_URL_KEY = 'ub-remote-events-url';
    1011  const UB_API_URL_KEY = 'ub-api-url';
    1112  const UB_API_CLIENT_ID_KEY = 'ub-api-client-id';
    1213  const UB_AUTHORIZED_DOMAINS_KEY = 'ub-authorized-domains';
    1314  const UB_HAS_AUTHORIZED_KEY = 'ub-has-authorized';
     15  const UB_USER_ID_KEY = 'ub-user-id';
     16  const UB_DOMAIN_ID_KEY = 'ub-domain-id';
     17  const UB_CLIENT_ID_KEY = 'ub-client-id';
    1418  const UB_CACHE_TIMEOUT_ENV_KEY = 'UB_WP_ROUTES_CACHE_EXP';
    15   const UB_USER_AGENT = 'Unbounce WP Plugin 1.0.4';
    16   const UB_VERSION = '1.0.4';
     19  const UB_USER_AGENT = 'Unbounce WP Plugin 1.0.5';
     20  const UB_VERSION = '1.0.5';
    1721
    1822  public static function default_page_server_domain() {
     
    2933  }
    3034
     35  public static function default_remote_events_url() {
     36    $url = getenv('UB_REMOTE_EVENTS_URL');
     37    if ($url == null) {
     38      return 'https://events-gateway.unbounce.com/events/domains';
     39    }
     40    return $url;
     41  }
     42
    3143  public static function default_api_url() {
    3244    $url = getenv('UB_API_URL');
     
    5264  }
    5365
     66  public static function remote_events_url() {
     67    return get_option(UBConfig::UB_REMOTE_EVENTS_URL_KEY, UBConfig::default_remote_events_url());
     68  }
     69
    5470  public static function api_url() {
    5571    return get_option(UBConfig::UB_API_URL_KEY, UBConfig::default_api_url());
     
    7692  }
    7793
     94  public static function create_none_response() {
     95    return array(array('status' => 'NONE'), null, null, null);
     96  }
     97
     98  public static function create_same_response($etag, $max_age) {
     99    return array(array('status' => 'SAME'), $etag, $max_age, null);
     100  }
     101
     102  public static function create_new_response($etag, $max_age, $proxyable_url_set) {
     103    return array(array('status' => 'NEW'), $etag, $max_age, $proxyable_url_set);
     104  }
     105
     106  public static function create_failure_response($failure_message) {
     107    return array(array('status' => 'FAILURE',
     108                       'failure_message' => $failure_message),
     109                 null, null, null);
     110  }
     111
     112  public static function domain() {
     113    return parse_url(get_home_url(), PHP_URL_HOST);
     114  }
     115
     116  public static function domain_with_port() {
     117    $port = parse_url(get_home_url(), PHP_URL_PORT);
     118    $host = parse_url(get_home_url(), PHP_URL_HOST);
     119    if ($port) {
     120      return $host . ':' . $port;
     121    } else {
     122      return $host;
     123    }
     124  }
     125
    78126  public static function fetch_proxyable_url_set($domain, $etag, $ps_domain) {
    79127    if(!$domain) {
    80       UBLogger::warning('Domain not provided, not fetching sitemap.xml');
    81       return array('FAILURE', null, null, null);
     128      $failure_message = 'Domain not provided, not fetching sitemap.xml';
     129      UBLogger::warning($failure_message);
     130      return UBConfig::create_failure_response($failure_message);
    82131    }
    83132
     
    130179        if ($success) {
    131180          UBLogger::debug("Retrieved new routes, HTTP code: '$http_code'");
    132           return array('NEW', $etag, $max_age, $result);
     181          return UBConfig::create_new_response($etag, $max_age, $result);
    133182        }
    134183        else {
    135184          $errors = join(', ', $result);
    136           UBLogger::warning("An error occurred while processing routes, XML errors: '$errors'");
    137           return array('FAILURE', null, null, null);
     185          $failure_message = "An error occurred while processing pages, XML errors: '$errors'";
     186          UBLogger::warning($failure_message);
     187          return UBConfig::create_failure_response($failure_message);
    138188        }
    139189      }
    140190      if ($http_code == 304) {
    141191        UBLogger::debug("Routes have not changed, HTTP code: '$http_code'");
    142         return array('SAME', $etag, $max_age, null);
     192        return UBConfig::create_same_response($etag, $max_age);
    143193      }
    144194      if ($http_code == 404) {
    145195        UBLogger::debug("No routes to retrieve, HTTP code: '$http_code'");
    146         return array('NONE', null, null, null);
     196        return UBConfig::create_none_response();
    147197      }
    148198      else {
    149         UBLogger::warning("An error occurred while retrieving routes; HTTP code: '$http_code'; Error: " . $curl_error);
    150         return array('FAILURE', null, null, null);
    151       }
     199        $failure_message = "An error occurred while retrieving routes; HTTP code: '$http_code'; Error: " . $curl_error;
     200        UBLogger::warning($failure_message);
     201        return UBConfig::create_failure_response($failure_message);
     202      }
     203
    152204    } catch (Exception $e) {
    153       UBLogger::warning("An error occurred while retrieving routes; Error: " . $e);
    154       return array('FAILURE', null, null, null);
     205      $failure_message = "An error occurred while retrieving routes; Error: " . $e;
     206      UBLogger::warning($failure_message);
     207      return UBConfig::create_failure_response($failure_message);
    155208    }
    156209  }
     
    224277      list($routes_status, $etag, $max_age, $proxyable_url_set_new) = $result_array;
    225278
    226       if ($routes_status == 'NEW') {
     279      if ($routes_status['status'] == 'NEW') {
    227280        $domain_info['proxyable_url_set'] = $proxyable_url_set_new;
    228281        $domain_info['proxyable_url_set_etag'] = $etag;
    229282        $domain_info['proxyable_url_set_cache_timeout'] = $max_age;
    230283      }
    231       elseif ($routes_status == 'SAME') {
     284      elseif ($routes_status['status'] == 'SAME') {
    232285        // Just extend the cache
    233286        $domain_info['proxyable_url_set_cache_timeout'] = $max_age;
    234287      }
    235       elseif ($routes_status == 'NONE') {
     288      elseif ($routes_status['status'] == 'NONE') {
    236289        $domain_info['proxyable_url_set'] = array();
    237290        $domain_info['proxyable_url_set_etag'] = null;
    238291      }
    239       elseif ($routes_status == 'FAILURE') {
     292      elseif ($routes_status['status'] == 'FAILURE') {
    240293        UBLogger::warning('Route fetching failed');
    241294      }
     
    244297      }
    245298
     299      // Creation of domain_info entry
    246300      $domain_info['proxyable_url_set_fetched_at'] = $current_time;
    247       $domain_info['last_status'] = $routes_status;
     301      $domain_info['last_status'] = $routes_status['status'];
     302      if ($routes_status['status'] == 'FAILURE') {
     303        $domain_info['failure_message'] = $routes_status['failure_message'];
     304      }
    248305      $domains_info[$domain] = $domain_info;
    249306      $options_setter(UBConfig::UB_ROUTES_CACHE_KEY, $domains_info);
     
    253310                                       array('proxyable_url_set',
    254311                                             'proxyable_url_set_fetched_at',
     312                                             'failure_message',
    255313                                             'last_status'));
    256314  }
     
    271329  }
    272330
     331  public static function update_authorization_options($domains, $data) {
     332    update_option(UBConfig::UB_USER_ID_KEY, $data['user_id']);
     333    update_option(UBConfig::UB_DOMAIN_ID_KEY, $data['domain_id']);
     334    update_option(UBConfig::UB_CLIENT_ID_KEY, $data['client_id']);
     335    update_option(UBConfig::UB_AUTHORIZED_DOMAINS_KEY, $domains);
     336    update_option(UBConfig::UB_HAS_AUTHORIZED_KEY, true);
     337  }
     338
     339  public static function int_min() {
     340    return (PHP_INT_MAX * -1) - 1;
     341  }
     342
    273343}
    274344?>
  • unbounce/trunk/UBDiagnostics.php

    r1256907 r1266757  
    2929      'PHP Version'             => phpversion(),
    3030      'WordPress Version'       => UBDiagnostics::wordpress_version(),
    31       'Unbounce Plugin Version' => "1.0.4",
     31      'Unbounce Plugin Version' => "1.0.5",
    3232      'Permalink Structure'     => get_option('permalink_structure', ''),
    3333      'Domain'                  => $domain,
    3434      'Domain Authorized'       => print_r(UBConfig::is_authorized_domain($domain), true),
    35       'Domain Information'      => print_r($domain_info, true),
    36       'Page Server Domain'      => UBConfig::page_server_domain(),
    37       'Remote Log URL'          => UBConfig::remote_log_url(),
    38       'API URL'                 => UBConfig::api_url(),
    39       'API Client ID'           => UBConfig::api_client_id(),
    40       'Authorized Domains'      => join(', ', UBConfig::authorized_domains()),
    4135      'Has Authorized'          => print_r(UBConfig::has_authorized(), true),
    4236      'Active Plugins'          => print_r(get_option('active_plugins'), true),
     
    4640      'Extensions'              => print_r(get_loaded_extensions(), true),
    4741      'Operating System'        => php_uname(),
    48       'Checks'                  => print_r(UBDiagnostics::checks($domain, $domain_info), true)
     42      'Checks'                  => print_r(UBDiagnostics::checks($domain, $domain_info), true),
     43      'Options'                 => print_r(UBDiagnostics::ub_options(), true)
    4944    );
     45  }
     46
     47  private static function ub_options() {
     48    $ub_options = array_filter(wp_load_alloptions(), function($key) {
     49      return strpos($key, 'ub-') === 0;
     50    }, ARRAY_FILTER_USE_KEY);
     51
     52    return array_map(function($value) {
     53      $unserialized = @unserialize($value);
     54      return $unserialized ? $unserialized : $value;
     55    }, $ub_options);
    5056  }
    5157
     
    6672  private static function last_status_success($domain_info) {
    6773    $last_status = UBUtil::array_fetch($domain_info, 'last_status');
    68     return $last_status !== 'FAILURE' && $last_status !== null;
     74    return $last_status !== null && $last_status !== 'FAILURE';
    6975  }
    7076
  • unbounce/trunk/UBHTTP.php

    r1256907 r1266757  
    228228  }
    229229
     230  public static function send_event_to_events_gateway($url, $data_string) {
     231    try {
     232      $stream_function = function($curl, $str) { return strlen($str); };
     233
     234      $curl = curl_init();
     235      $curl_options = array(
     236        CURLOPT_URL => $url,
     237        CURLOPT_CUSTOMREQUEST => 'POST',
     238        CURLOPT_USERAGENT => UBConfig::UB_USER_AGENT,
     239        CURLOPT_FOLLOWLOCATION => false,
     240        CURLOPT_HTTPHEADER => array(
     241          'Content-Type: application/json',
     242          'Content-Length: ' . strlen($data_string)
     243        ),
     244        CURLOPT_HEADERFUNCTION => $stream_function,
     245        CURLOPT_WRITEFUNCTION => $stream_function,
     246        CURLOPT_POSTFIELDS => $data_string,
     247        CURLOPT_TIMEOUT => 2
     248      );
     249      curl_setopt_array($curl, $curl_options);
     250      $success = curl_exec($curl);
     251      $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
     252
     253      if(!$success) {
     254        $message = 'Unable to send log messages to ' . $url . ': "'
     255                 . curl_error($curl) . '" - HTTP status: ' . curl_errno($curl);
     256        UBLogger::warning($message);
     257      } elseif($http_code >= 200 && $http_code < 300) {
     258        $message = 'Successfully sent log messsages to ' . $url
     259                 . ' - HTTP status: ' . $http_code;
     260        UBLogger::debug($message);
     261      } else {
     262        $message = 'Unable to send log messages to ' . $url
     263                 . ' - HTTP status: ' . $http_code;
     264        UBLogger::warning($message);
     265      }
     266
     267      curl_close($curl);
     268    } catch (Exception $e) {
     269      $message = 'Unable to send log messages to ' . $url
     270               . ' - Error: ' . $e;
     271      UBLogger::warning($message);
     272    }
     273  }
     274
    230275}
    231276
  • unbounce/trunk/UBLogger.php

    r1255261 r1266757  
    22
    33require_once dirname(__FILE__) . '/UBConfig.php';
     4require_once dirname(__FILE__) . '/UBEvents.php';
    45
    56class UBLogger {
     
    1617  public static function upload_logs_to_unbounce($url) {
    1718    if(UBConfig::remote_debug_logging_enabled()) {
    18       $datetime = new DateTime('NOW', new DateTimeZone('UTC'));
    1919      $data = array(
    20         'type' => 'WordpressLogV1.0',
    2120        'messages' => $GLOBALS['wp_log'][UBConfig::UB_PLUGIN_NAME],
    2221        'vars' => $GLOBALS['wp_log'][UBConfig::UB_PLUGIN_NAME . '-vars'],
    23         'id' => uniqid(),
    24         'time_sent' => $datetime->format('Y-m-d\TH:i:s.000\Z'),
    25         'source' => UBConfig::UB_USER_AGENT . ' ' . gethostname()
    2622      );
    27       $json_unescaped = json_encode($data);
    28       $data_string = str_replace('\\/', '/', $json_unescaped);
    29 
    30       try {
    31         $curl = curl_init();
    32         $curl_options = array(
    33           CURLOPT_URL => $url,
    34           CURLOPT_CUSTOMREQUEST => 'POST',
    35           CURLOPT_USERAGENT => UBConfig::UB_USER_AGENT,
    36           CURLOPT_FOLLOWLOCATION => false,
    37           CURLOPT_HTTPHEADER => array(
    38             'Content-Type: application/json',
    39             'Content-Length: ' . strlen($data_string)
    40           ),
    41           CURLOPT_POSTFIELDS => $data_string,
    42           CURLOPT_TIMEOUT => 2
    43         );
    44         curl_setopt_array($curl, $curl_options);
    45         $success = curl_exec($curl);
    46         $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    47 
    48         if(!$success) {
    49           $message = 'Unable to send log messages to ' . $url . ': "'
    50                    . curl_error($curl) . '" - HTTP status: ' . curl_errno($curl);
    51           UBLogger::warning($message);
    52         } elseif($http_code >= 200 && $http_code < 300) {
    53           $message = 'Successfully sent log messsages to ' . $url
    54                    . ' - HTTP status: ' . $http_code;
    55           UBLogger::debug($message);
    56         } else {
    57           $message = 'Unable to send log messages to ' . $url
    58                    . ' - HTTP status: ' . $http_code;
    59           UBLogger::warning($message);
    60         }
    61 
    62         curl_close($curl);
    63       } catch (Exception $e) {
    64         $message = 'Unable to send log messages to ' . $url
    65                  . ' - Error: ' . $e;
    66         UBLogger::warning($message);
    67       }
     23      UBHTTP::send_event_to_events_gateway($url, UBEvents::log_event($data));
    6824    }
    6925  }
  • unbounce/trunk/Unbounce-Page.php

    r1256907 r1266757  
    44Plugin URI: http://unbounce.com
    55Description: Publish Unbounce Landing Pages to your Wordpress Domain.
    6 Version: 1.0.4
     6Version: 1.0.5
    77Author: Unbounce
    88Author URI: http://unbounce.com
     
    1818require_once dirname(__FILE__) . '/UBIcon.php';
    1919require_once dirname(__FILE__) . '/UBPageTable.php';
     20require_once dirname(__FILE__) . '/UBEvents.php';
    2021
    2122register_activation_hook(__FILE__, function() {
     
    3334             UBConfig::default_authorized_domains());
    3435  add_option(UBConfig::UB_HAS_AUTHORIZED_KEY);
     36  add_option(UBConfig::UB_REMOTE_EVENTS_URL_KEY,
     37             UBConfig::default_remote_events_url());
     38  add_option(UBConfig::UB_USER_ID_KEY);
     39  add_option(UBConfig::UB_DOMAIN_ID_KEY);
     40  add_option(UBConfig::UB_CLIENT_ID_KEY);
    3541});
    3642
     
    4450  delete_option(UBConfig::UB_AUTHORIZED_DOMAINS_KEY);
    4551  delete_option(UBConfig::UB_HAS_AUTHORIZED_KEY);
     52  delete_option(UBConfig::UB_REMOTE_EVENTS_URL_KEY);
     53  delete_option(UBConfig::UB_USER_ID_KEY);
     54  delete_option(UBConfig::UB_DOMAIN_ID_KEY);
     55  delete_option(UBConfig::UB_CLIENT_ID_KEY);
    4656});
    4757
     
    4959  UBLogger::setup_logger();
    5060
    51   $domain = parse_url(get_home_url(), PHP_URL_HOST);
     61  $domain = UBConfig::domain();
    5262
    5363  if(!UBConfig::is_authorized_domain($domain)) {
     
    90100  }
    91101  elseif ($url_purpose == 'HealthCheck') {
     102    if (UBConfig::domain_with_port() !== UBUtil::array_fetch($_SERVER, 'HTTP_HOST')) {
     103      http_response_code(412);
     104    }
     105
    92106    header('Content-Type: application/json');
    93107    $version = UBConfig::UB_VERSION;
     
    105119    }
    106120
    107     // Disable CDN for W3 Total Cache
    108121    if(!defined('DONOTCDN')) {
    109122      define('DONOTCDN', true);
     123    }
     124
     125    if(!defined('DONOTCACHEDB')) {
     126      define('DONOTCACHEDB', true);
     127    }
     128
     129    if(!defined('DONOTMINIFY')) {
     130      define('DONOTMINIFY', true);
     131    }
     132
     133    if(!defined('DONOTCACHEOBJECT')) {
     134      define('DONOTCACHEOBJECT', true);
    110135    }
    111136
     
    137162    exit(0);
    138163  }
    139 });
     164}, UBConfig::int_min());
    140165
    141166add_action('admin_init', function() {
     
    165190}, 0);
    166191
    167 function authorization_button($text, $wrap_in_p = false, $is_primary = true, $outer_text = '') {
     192function authorization_button($text, $domain, $wrap_in_p = false, $is_primary = true, $outer_text = '') {
    168193  $set_domains_url = admin_url('admin-post.php?action=set_unbounce_domains');
    169194  echo "<form method='post' action='$set_domains_url'>";
    170195  echo "<input type='hidden' name='domains' />";
     196  echo "<input type='hidden' name='user_id' />";
     197  echo "<input type='hidden' name='domain_id' />";
     198  echo "<input type='hidden' name='client_id' />";
    171199  echo $outer_text;
    172200  $style = $outer_text ? 'vertical-align: baseline' : '';
     
    179207                               'data-api-url' => UBConfig::api_url(),
    180208                               'data-api-client-id' => UBConfig::api_client_id(),
     209                               'data-wordpress-domain-name' => $domain,
    181210                               'style' => $style));
    182211  echo '</form>';
     
    217246    $proxyable_url_set_fetched_at = UBUtil::array_fetch($domain_info, 'proxyable_url_set_fetched_at');
    218247    echo '<p>Last refreshed  ' . UBUtil::time_ago($proxyable_url_set_fetched_at) . '.</p>';
    219     authorization_button('Update WordPress Enabled Domains', false, false);
     248    authorization_button('Update WordPress Enabled Domains', $domain, false, false);
    220249    echo '</p>';
    221250    echo '</div>';
     
    234263      $diagnostics_url = admin_url('admin.php?page=unbounce-pages-diagnostics');
    235264      echo "<br/><a class='ub-diagnostics-link' href='${diagnostics_url}'>Diagnostics</a>";
    236       echo '<p class="ub-version">Unbounce Version 1.0.4</p>';
     265      echo '<p class="ub-version">Unbounce Version 1.0.5</p>';
    237266    });
    238267  } else {
     
    249278      echo '</form>';
    250279
    251       authorization_button('Update WordPress Enabled Domains', false, false, 'After adding your domain in Unbounce, come back here and ');
     280      authorization_button('Update WordPress Enabled Domains', $domain, false, false, 'After adding your domain in Unbounce, come back here and ');
    252281    } else {
    253282      echo '<div class="ub-authorize-message">Before you can publish your pages to WordPress you will have to authorize your Unbounce account.</div>';
    254283
    255       authorization_button('Authorize With Unbounce', true);
     284      authorization_button('Authorize With Unbounce', $domain, true);
    256285
    257286      $try_unbounce_url = "http://unbounce.com/landing-pages-for-wordpress/";
     
    271300      $diagnostics_url = admin_url('admin.php?page=unbounce-pages-diagnostics');
    272301      echo "<br/><a class='ub-diagnostics-link' href='${diagnostics_url}'>Diagnostics</a>";
    273       echo '<p class="ub-version">Unbounce Version 1.0.4</p>';
     302      echo '<p class="ub-version">Unbounce Version 1.0.5</p>';
    274303    });
    275304  }
     
    307336  // Main admin page
    308337  $print_admin_panel = function() {
    309     $domain = parse_url(get_home_url(), PHP_URL_HOST);
     338    $domain = UBConfig::domain();
    310339    $domain_info = UBConfig::read_unbounce_domain_info($domain, false);
    311340
     
    322351  // Diagnostics page
    323352  $print_diagnostics_panel = function() {
    324     $domain = parse_url(get_home_url(), PHP_URL_HOST);
     353    $domain = UBConfig::domain();
    325354    $domain_info = UBConfig::read_unbounce_domain_info($domain, false);
    326355
     
    337366
    338367add_action('admin_post_set_unbounce_domains', function() {
    339   $domains_json = UBUtil::array_fetch($_POST, 'domains', '');
    340   $domains = explode(',', $domains_json);
    341 
    342   if($domains_json && is_array($domains)) {
    343     update_option(UBConfig::UB_AUTHORIZED_DOMAINS_KEY, $domains);
    344     update_option(UBConfig::UB_HAS_AUTHORIZED_KEY, true);
     368  $domains_list = UBUtil::array_fetch($_POST, 'domains', '');
     369  $domains = explode(',', $domains_list);
     370
     371  if($domains && is_array($domains)) {
    345372    $authorization = 'success';
     373    $has_authorized = get_option(UBConfig::UB_HAS_AUTHORIZED_KEY, false);
     374
     375    $data = array(
     376      'domain_name' => UBConfig::domain(),
     377      'first_authorization' => !$has_authorized,
     378      'user_id' => UBUtil::array_fetch($_POST, 'user_id', ''),
     379      'client_id' => UBUtil::array_fetch($_POST, 'client_id', ''),
     380      'domain_id' => UBUtil::array_fetch($_POST, 'domain_id', ''),
     381    );
     382
     383    UBConfig::update_authorization_options($domains, $data);
     384
     385    if(UBConfig::is_authorized_domain(UBConfig::domain())) {
     386      $event = UBEvents::successful_authorization_event($data);
     387    } else {
     388      $event = UBEvents::failed_authorization_event($data);
     389    }
     390    UBHTTP::send_event_to_events_gateway(UBConfig::remote_events_url(), $event);
    346391  } else {
    347392    $authorization = 'failure';
     
    356401
    357402add_action('admin_post_flush_unbounce_pages', function() {
    358   $domain = parse_url(get_home_url(), PHP_URL_HOST);
     403  $domain = UBConfig::domain();
    359404  // Expire cache and redirect
    360405  $_domain_info = UBConfig::read_unbounce_domain_info($domain, true);
     
    365410
    366411add_action('shutdown', function() {
    367   UBLogger::upload_logs_to_unbounce(get_option(UBConfig::UB_REMOTE_LOG_URL_KEY));
     412  UBLogger::upload_logs_to_unbounce(UBConfig::remote_log_url());
    368413});
    369414
  • unbounce/trunk/js/set-unbounce-domains.js

    r1248703 r1266757  
    11(function($) {
    22
    3   function apiGet(url, token) {
    4     var request = $.ajax({
     3  function apiGetPromise(url, token) {
     4    return $.ajax({
    55      url: url,
    66      method: 'get',
     
    88                 'Accept': 'application/vnd.unbounce.api.v0.4+json' },
    99      dataType: 'json'
    10     });
    11     return Rx.Observable.fromPromise(request.promise());
     10    }).promise();
    1211  }
    1312
    14   function getDomainNames(result) {
    15     if($.isArray(result.domains)) {
     13  function apiGet(url, token) {
     14    return Rx.Observable.fromPromise(apiGetPromise(url, token));
     15  }
     16
     17  function getDomainData(subAccount, domains) {
     18    if($.isArray(domains)) {
    1619      return Rx.Observable.fromArray(
    17         $.map(result.domains, function(domain) {
     20        $.map(domains, function(domain) {
    1821          if(domain && domain.name) {
    19             return domain.name;
     22            return {
     23              clientId: subAccount.id,
     24              domainId: domain.id,
     25              name: domain.name
     26            };
    2027          } else {
    2128            throw 'Unable to fetch domain name';
     
    2734  }
    2835
    29   function getUserSubAccountIds(user) {
     36  function getUserSubAccounts(user, token) {
    3037    if(user.metadata && user.metadata.related && $.isArray(user.metadata.related.sub_accounts)) {
    31       return Rx.Observable.fromArray(
    32         $.map(user.metadata.related.sub_accounts, function(sub_account_url) {
    33           var pieces = sub_account_url.split('/');
    34           return pieces[pieces.length - 1];
    35         }));
     38      var promises = $.map(user.metadata.related.sub_accounts, function(subAccountUrl) {
     39        return apiGetPromise(subAccountUrl, token);
     40      });
     41      return Rx.Observable.fromArray(promises).flatMap(Rx.Observable.fromPromise);
    3642    } else {
    3743      throw 'Unable to fetch user';
     
    3945  }
    4046
    41   function postDomainsToWordpress($form, domains) {
    42     $form.find('[name="domains"]').val(domains.join(','));
     47  function postDomainsToWordpress($form, data, wordpressDomainName) {
     48    if($.isArray(data.domains)) {
     49      var wordpressDomains = data.domains.filter(function(domain) {
     50        return domain.name === wordpressDomainName;
     51      });
     52
     53      if(wordpressDomains[0]) {
     54        var wordpressDomain = wordpressDomains[0];
     55        $form.find('[name="domain_id"]').val(wordpressDomain.domainId);
     56        $form.find('[name="client_id"]').val(wordpressDomain.clientId);
     57      }
     58
     59      var domainNames = $.map(data.domains, function(domain) {
     60        return domain.name;
     61      });
     62
     63      $form.find('[name="user_id"]').val(data.userId);
     64      $form.find('[name="domains"]').val(domainNames.join(','));
     65    }
     66
    4367    $form.submit();
    4468  }
     
    6488          redirectUri = $submitButton.attr('data-redirect-uri'),
    6589          apiClientId = $submitButton.attr('data-api-client-id'),
     90          wordpressDomainName = $submitButton.attr('data-wordpress-domain-name'),
    6691          getTokenUrl = apiUrl + '/oauth/authorize?response_type=token&client_id=' + apiClientId + '&redirect_uri=' + redirectUri,
    6792          getUserUrl = apiUrl + '/users/self?limit=1000',
     
    84109        loadingUI($submitButton, loadingText);
    85110
    86         var source = apiGet(getUserUrl, accessToken)
     111        var userObservable = apiGet(getUserUrl, accessToken).publish(),
     112            domainsObservable = userObservable
    87113              .flatMap(function(user) {
    88                 return getUserSubAccountIds(user);
    89               })
    90               .flatMap(function (subAccountId) {
    91                 return apiGet(getDomainsUrl.replace('{subAccountId}', subAccountId), accessToken);
    92               })
    93               .flatMap(function(domains) {
    94                 return getDomainNames(domains);
     114                return getUserSubAccounts(user, accessToken);
     115              }).flatMap(function (subAccount) {
     116                return apiGet(getDomainsUrl.replace('{subAccountId}', subAccount.id), accessToken)
     117                  .flatMap(function(response) {
     118                    return getDomainData(subAccount, response.domains);
     119                  });
    95120              }).toArray().publish(),
    96             subscription = source.subscribe(
     121            userDomainsObservable = Rx.Observable.zip(
     122              userObservable,
     123              domainsObservable,
     124              function(user, domains) {
     125                return {userId: user.id, domains: domains};
     126              }).publish(),
     127            subscription = userDomainsObservable.subscribe(
    97128              function (domains) {
    98                 postDomainsToWordpress($form, domains);
     129                postDomainsToWordpress($form, domains, wordpressDomainName);
    99130              },
    100131              function (error) {
     
    107138              });
    108139
    109         source.connect();
     140        userDomainsObservable.connect();
     141        domainsObservable.connect();
     142        userObservable.connect();
    110143      }
    111144    }
  • unbounce/trunk/readme.txt

    r1256907 r1266757  
    44Requires at least: 4.1.5
    55Tested up to: 4.3
    6 Stable tag: 1.0.4
     6Stable tag: 1.0.5
    77License: GPLv2 or later
    88License URI: http://www.gnu.org/licenses/gpl-2.0.html
Note: See TracChangeset for help on using the changeset viewer.