update_option() public static method

Updates the single given option. Updates jetpack_options or jetpack_$name as appropriate.
public static update_option ( string $name, mixed $value, string $autoload = null ) : boolean
$name string Option name
$value mixed Option value
$autoload string If not compact option, allows specifying whether to autoload or not.
return boolean Was the option successfully updated?
 /**
  * Synchronize connected user role changes
  */
 static function user_role_change($user_id)
 {
     if (Jetpack::is_active() && Jetpack::is_user_connected($user_id)) {
         $current_user_id = get_current_user_id();
         wp_set_current_user($user_id);
         $role = Jetpack::translate_current_user_to_role();
         $signed_role = Jetpack::sign_role($role);
         wp_set_current_user($current_user_id);
         $master_token = Jetpack_Data::get_access_token(JETPACK_MASTER_USER);
         $master_user_id = absint($master_token->external_user_id);
         if (!$master_user_id) {
             return;
         }
         // this shouldn't happen
         Jetpack::xmlrpc_async_call('jetpack.updateRole', $user_id, $signed_role);
         //@todo retry on failure
         //try to choose a new master if we're demoting the current one
         if ($user_id == $master_user_id && 'administrator' != $role) {
             $query = new WP_User_Query(array('fields' => array('id'), 'role' => 'administrator', 'orderby' => 'id', 'exclude' => array($master_user_id)));
             $new_master = false;
             foreach ($query->results as $result) {
                 $uid = absint($result->id);
                 if ($uid && Jetpack::is_user_connected($uid)) {
                     $new_master = $uid;
                     break;
                 }
             }
             if ($new_master) {
                 Jetpack_Options::update_option('master_user', $new_master);
             }
             // else disconnect..?
         }
     }
 }
 /**
  * Method that gets executed on the wp-cron call
  *
  * @since 2.3.3
  * @global string $wp_version
  */
 public function cron_exec()
 {
     $jetpack = Jetpack::init();
     /*
      * This should run daily.  Figuring in for variances in
      * WP_CRON, don't let it run more than every 23 hours at most.
      *
      * i.e. if it ran less than 23 hours ago, fail out.
      */
     $last = (int) Jetpack_Options::get_option('last_heartbeat');
     if ($last && $last + DAY_IN_SECONDS - HOUR_IN_SECONDS > time()) {
         return;
     }
     /*
      * Check for an identity crisis
      *
      * If one exists:
      * - Bump stat for ID crisis
      * - Email site admin about potential ID crisis
      */
     // Coming Soon!
     foreach (self::generate_stats_array('v2-') as $key => $value) {
         $jetpack->stat($key, $value);
     }
     Jetpack_Options::update_option('last_heartbeat', time());
     $jetpack->do_stats('server_side');
 }
 public function default_action()
 {
     $args = $this->input();
     if (isset($args['autoupdate']) && is_bool($args['autoupdate'])) {
         Jetpack_Options::update_option('autoupdate_core', $args['autoupdate']);
     }
     return true;
 }
Exemplo n.º 4
0
function jetpack_json_api_configuration_load()
{
    if (isset($_POST['action']) && $_POST['action'] == 'save_options' && wp_verify_nonce($_POST['_wpnonce'], 'json-api')) {
        Jetpack_Options::update_option('json_api_full_management', isset($_POST['json_api_full_management']));
        Jetpack::state('message', 'module_configured');
        wp_safe_redirect(Jetpack::module_configuration_url('json-api'));
        exit;
    }
}
 /**
  * Gets the value for which connection banner to show, and initializes if not set.
  *
  * @since 4.4.0
  *
  * @return int
  */
 static function get_random_connection_banner_value()
 {
     $random_connection_banner = Jetpack_Options::get_option('connection_banner_ab');
     if (!$random_connection_banner) {
         $random_connection_banner = mt_rand(1, 2);
         Jetpack_Options::update_option('connection_banner_ab', $random_connection_banner);
     }
     return $random_connection_banner;
 }
 function test_delete_non_compact_option_returns_true_when_successfully_deleted()
 {
     Jetpack_Options::update_option('migrate_for_idc', true);
     // Make sure the option is set
     $this->assertTrue(Jetpack_Options::get_option('migrate_for_idc'));
     $deleted = Jetpack_Options::delete_option('migrate_for_idc');
     // Was the option successfully deleted?
     $this->assertFalse(Jetpack_Options::get_option('migrate_for_idc'));
     // Did Jetpack_Options::delete_option() properly return true?
     $this->assertTrue($deleted);
 }
 function test_sync_deactivate_module_event()
 {
     Jetpack_Options::update_option('active_modules', array('stuff'));
     Jetpack::deactivate_module('stuff');
     $this->client->do_sync();
     $events = $this->server_event_storage->get_all_events('jetpack_deactivate_module');
     $event = $events[0];
     $this->assertEquals('jetpack_deactivate_module', $event->action);
     $this->assertEquals('stuff', $event->args[0]);
     $this->assertEquals(1, count($events));
 }
Exemplo n.º 8
0
 function test_clear_all_idc_options_clears_expected()
 {
     $options = array('sync_error_idc', 'safe_mode_confirmed', 'migrate_for_idc');
     foreach ($options as $option) {
         Jetpack_Options::update_option($option, true);
         $this->assertTrue(Jetpack_Options::get_option($option));
     }
     Jetpack_IDC::clear_all_idc_options();
     foreach ($options as $option) {
         $this->assertFalse(Jetpack_Options::get_option($option));
     }
 }
 public function setUp()
 {
     global $wp_version;
     parent::setUp();
     if (version_compare($wp_version, '4.4', '>=')) {
         add_filter('get_site_icon_url', array($this, '_get_site_icon'), 99, 3);
         update_option('site_icon', '5');
     } else {
         // wp 4.3 or less
         Jetpack_Options::update_option('site_icon_url', 'http://foo.com/icon.gif');
     }
     $this->client->do_sync();
 }
 static function reindex_trigger()
 {
     $response = array('status' => 'ERROR');
     // Force a privacy check
     Jetpack::check_privacy(JETPACK__PLUGIN_FILE);
     Jetpack::load_xml_rpc_client();
     $client = new Jetpack_IXR_Client(array('user_id' => JETPACK_MASTER_USER));
     $client->query('jetpack.reindexTrigger');
     if (!$client->isError()) {
         $response = $client->getResponse();
         Jetpack_Options::update_option('sync_bulk_reindexing', true);
     }
     return $response;
 }
 public function test_autoupdate_enabled_and_disabled_is_synced()
 {
     // enable autoupdates
     $autoupdate_plugins = Jetpack_Options::get_option('autoupdate_plugins', array());
     $autoupdate_plugins = array_unique(array_merge($autoupdate_plugins, array('hello')));
     Jetpack_Options::update_option('autoupdate_plugins', $autoupdate_plugins);
     $this->sender->do_sync();
     $set_autoupdate_plugin = $this->server_replica_storage->get_option('jetpack_autoupdate_plugins', array());
     $this->assertEquals(Jetpack_Options::get_option('autoupdate_plugins', array()), $set_autoupdate_plugin);
     $this->assertTrue(in_array('hello', $set_autoupdate_plugin));
     // disable autoupdates
     $autoupdate_plugins = Jetpack_Options::get_option('autoupdate_plugins', array());
     $autoupdate_plugins = array_diff($autoupdate_plugins, array('hello'));
     Jetpack_Options::update_option('autoupdate_plugins', $autoupdate_plugins);
     $this->sender->do_sync();
     $set_autoupdate_plugin = $this->server_replica_storage->get_option('jetpack_autoupdate_plugins');
     $this->assertEquals(Jetpack_Options::get_option('autoupdate_plugins', array()), $set_autoupdate_plugin);
     $this->assertFalse(in_array('hello', $set_autoupdate_plugin));
 }
Exemplo n.º 12
0
 static function maybe_demote_master_user($user_id)
 {
     $master_user_id = Jetpack_Options::get_option('master_user');
     $role = self::get_role($user_id);
     if ($user_id == $master_user_id && 'administrator' != $role) {
         $query = new WP_User_Query(array('fields' => array('id'), 'role' => 'administrator', 'orderby' => 'id', 'exclude' => array($master_user_id)));
         $new_master = false;
         foreach ($query->results as $result) {
             $found_user_id = absint($result->id);
             if ($found_user_id && Jetpack::is_user_connected($found_user_id)) {
                 $new_master = $found_user_id;
                 break;
             }
         }
         if ($new_master) {
             Jetpack_Options::update_option('master_user', $new_master);
         }
         // else disconnect..?
     }
 }
 function jetpack_my_jetpack_change_user()
 {
     if (!isset($_POST['_my_jetpack_nonce']) || !wp_verify_nonce($_POST['_my_jetpack_nonce'], 'jetpack_change_primary_user')) {
         wp_die(__('Failed permissions, please try again.', 'jetpack'));
         exit;
     }
     if (isset($_POST['jetpack-new-master'])) {
         $old_master_user = Jetpack_Options::get_option('master_user');
         $new_master_user = $_POST['jetpack-new-master'];
         $user_token = Jetpack_Data::get_access_token($new_master_user);
         $is_user_connected = $user_token && !is_wp_error($user_token);
         if (current_user_can('manage_options') && $is_user_connected) {
             Jetpack::log('switch_master_user', array('old_master' => $old_master_user, 'new_master' => $new_master_user));
             Jetpack_Options::update_option('master_user', $new_master_user);
             Jetpack::state('message', 'switch_master');
             //My Jetpack primary user successfully changed, send to MC Stats
             Jetpack::init()->stat('admin', 'change-primary-successful');
             Jetpack::init()->do_stats('server_side');
             // Change the blog owner dotcom side
             $this->wpcom_switch_blog_owner($new_master_user);
         }
     }
 }
Exemplo n.º 14
0
 /**
  * Registers a subsite with the Jetpack servers
  *
  * @since 2.9
  * @todo  Break apart into easier to manage chunks that can be unit tested
  * @see   Jetpack_Network::jetpack_sites_list();
  */
 public function do_subsiteregister($site_id = null)
 {
     if (!current_user_can('jetpack_disconnect')) {
         return;
     }
     $jp = Jetpack::init();
     // Figure out what site we are working on
     $site_id = is_null($site_id) ? $_GET['site_id'] : $site_id;
     // Build secrets to sent to wpcom for verification
     $secrets = $jp->generate_secrets();
     // Remote query timeout limit
     $timeout = $jp->get_remote_query_timeout_limit();
     // The blog id on WordPress.com of the primary network site
     $network_wpcom_blog_id = Jetpack_Options::get_option('id');
     /*
      * Here we need to switch to the subsite
      * For the registration process we really only hijack how it
      * works for an individual site and pass in some extra data here
      */
     switch_to_blog($site_id);
     // Save the secrets in the subsite so when the wpcom server does a pingback it
     // will be able to validate the connection
     Jetpack_Options::update_option('register', $secrets[0] . ':' . $secrets[1] . ':' . $secrets[2]);
     // Gra info for gmt offset
     $gmt_offset = get_option('gmt_offset');
     if (!$gmt_offset) {
         $gmt_offset = 0;
     }
     /*
      * Get the stats_option option from the db.
      * It looks like the server strips this out so maybe it is not necessary?
      * Does it match the Jetpack site with the old stats plugin id?
      *
      * @todo Find out if sending the stats_id is necessary
      */
     $stat_options = get_option('stats_options');
     $stat_id = $stat_options = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
     $args = array('method' => 'POST', 'body' => array('network_url' => $this->get_url('network_admin_page'), 'network_wpcom_blog_id' => $network_wpcom_blog_id, 'siteurl' => site_url(), 'home' => home_url(), 'gmt_offset' => $gmt_offset, 'timezone_string' => (string) get_option('timezone_string'), 'site_name' => (string) get_option('blogname'), 'secret_1' => $secrets[0], 'secret_2' => $secrets[1], 'site_lang' => get_locale(), 'timeout' => $timeout, 'stats_id' => $stat_id, 'user_id' => get_current_user_id()), 'headers' => array('Accept' => 'application/json'), 'timeout' => $timeout);
     // Attempt to retrieve shadow blog details
     $response = Jetpack_Client::_wp_remote_request(Jetpack::fix_url_for_bad_hosts(Jetpack::api_url('subsiteregister')), $args, true);
     /*
      * $response should either be invalid or contain:
      * - jetpack_id	=> id
      * - jetpack_secret => blog_token
      * - jetpack_public
      *
      * Store the wpcom site details
      */
     $valid_response = $jp->validate_remote_register_response($response);
     if (is_wp_error($valid_response) || !$valid_response) {
         restore_current_blog();
         return $valid_response;
     }
     // Grab the response values to work with
     $code = wp_remote_retrieve_response_code($response);
     $entity = wp_remote_retrieve_body($response);
     if ($entity) {
         $json = json_decode($entity);
     } else {
         $json = false;
     }
     if (empty($json->jetpack_secret) || !is_string($json->jetpack_secret)) {
         restore_current_blog();
         return new Jetpack_Error('jetpack_secret', '', $code);
     }
     if (isset($json->jetpack_public)) {
         $jetpack_public = (int) $json->jetpack_public;
     } else {
         $jetpack_public = false;
     }
     Jetpack_Options::update_options(array('id' => (int) $json->jetpack_id, 'blog_token' => (string) $json->jetpack_secret, 'public' => $jetpack_public));
     /*
      * Update the subsiteregister method on wpcom so that it also sends back the
      * token in this same request
      */
     $is_master_user = !Jetpack::is_active();
     Jetpack::update_user_token(get_current_user_id(), sprintf('%s.%d', $json->token->secret, get_current_user_id()), $is_master_user);
     Jetpack::activate_default_modules();
     restore_current_blog();
 }
Exemplo n.º 15
0
 function options_save_tumblr()
 {
     // Nonce check
     check_admin_referer('save_tumblr_blog_' . $_REQUEST['connection']);
     $id = $_POST['connection'];
     $options = array('tumblr_base_hostname' => $_POST['selected_id']);
     Jetpack::load_xml_rpc_client();
     $xml = new Jetpack_IXR_Client();
     $xml->query('jetpack.setPublicizeOptions', $id, $options);
     if (!$xml->isError()) {
         $response = $xml->getResponse();
         Jetpack_Options::update_option('publicize_connections', $response);
     }
     $this->globalization();
 }
 public static function jumpstart_has_updated_module_option($option_name = '')
 {
     // Bail if Jump Start has already been dismissed
     if ('new_connection' !== Jetpack::get_option('jumpstart')) {
         return false;
     }
     $jetpack = Jetpack::init();
     // Manual build of module options
     $option_names = self::get_jetpack_options_for_reset();
     if (in_array($option_name, $option_names['wp_options'])) {
         Jetpack_Options::update_option('jumpstart', 'jetpack_action_taken');
         //Jump start is being dismissed send data to MC Stats
         $jetpack->stat('jumpstart', 'manual,' . $option_name);
         $jetpack->do_stats('server_side');
     }
 }
 protected function autoupdate_off()
 {
     $autoupdate_plugins = Jetpack_Options::get_option('autoupdate_plugins', array());
     $autoupdate_plugins = array_diff($autoupdate_plugins, $this->plugins);
     Jetpack_Options::update_option('autoupdate_plugins', $autoupdate_plugins);
 }
Exemplo n.º 18
0
 /**
  * Compares the currently saved links with the connected services and removes
  * links from services that are no longer connected.
  *
  * @return void
  */
 public function check_links()
 {
     $active_links = array_intersect_key($this->links, array_flip($this->services));
     if ($active_links !== $this->links) {
         $this->links = $active_links;
         Jetpack_Options::update_option('social_links', $active_links);
     }
 }
 public static function set_time_diff(&$response, $force_set = false)
 {
     $code = wp_remote_retrieve_response_code($response);
     // Only trust the Date header on some responses
     if (200 != $code && 304 != $code && 400 != $code && 401 != $code) {
         return;
     }
     if (!($date = wp_remote_retrieve_header($response, 'date'))) {
         return;
     }
     if (0 >= ($time = (int) strtotime($date))) {
         return;
     }
     $time_diff = $time - time();
     if ($force_set) {
         // during register
         Jetpack_Options::update_option('time_diff', $time_diff);
     } else {
         // otherwise
         $old_diff = Jetpack_Options::get_option('time_diff');
         if (false === $old_diff || abs($time_diff - (int) $old_diff) > 10) {
             Jetpack_Options::update_option('time_diff', $time_diff);
         }
     }
 }
 /**
  * Dismisses Jumpstart so user is not prompted to go through it again.
  *
  * @since 4.3.0
  *
  * @param WP_REST_Request $data {
  *     Array of parameters received by request.
  * }
  *
  * @return bool|WP_Error True if Jumpstart was disabled or was nothing to dismiss. Otherwise, a WP_Error instance with a message.
  */
 public static function jumpstart_deactivate($data)
 {
     // If dismissed, flag the jumpstart option as such.
     if ('new_connection' === Jetpack_Options::get_option('jumpstart')) {
         if (Jetpack_Options::update_option('jumpstart', 'jumpstart_dismissed')) {
             return rest_ensure_response(array('code' => 'success', 'message' => esc_html__('Jumpstart dismissed.', 'jetpack')));
         } else {
             return new WP_Error('jumpstart_failed_dismiss', esc_html__('Jumpstart could not be dismissed.', 'jetpack'), array('status' => 400));
         }
     }
     // If this was not a new connection and there was nothing to dismiss, don't fail.
     return rest_ensure_response(array('code' => 'success', 'message' => esc_html__('Nothing to dismiss. This was not a new connection.', 'jetpack')));
 }
 /**
  * Updates site settings for authorized users
  *
  * @return (array)
  */
 public function update_settings()
 {
     // $this->input() retrieves posted arguments whitelisted and casted to the $request_format
     // specs that get passed in when this class is instantiated
     /**
      * Filters the settings to be updated on the site.
      *
      * @since 3.6.0
      *
      * @param array $input Associative array of site settings to be updated.
      */
     $input = apply_filters('rest_api_update_site_settings', $this->input());
     $jetpack_relatedposts_options = array();
     $sharing_options = array();
     $updated = array();
     foreach ($input as $key => $value) {
         if (!is_array($value)) {
             $value = trim($value);
         }
         $value = wp_unslash($value);
         switch ($key) {
             case 'default_ping_status':
             case 'default_comment_status':
                 // settings are stored as closed|open
                 $coerce_value = $value ? 'open' : 'closed';
                 if (update_option($key, $coerce_value)) {
                     $updated[$key] = $value;
                 }
                 break;
             case 'jetpack_protect_whitelist':
                 if (function_exists('jetpack_protect_save_whitelist')) {
                     $result = jetpack_protect_save_whitelist($value);
                     if (is_wp_error($result)) {
                         return $result;
                     }
                     $updated[$key] = jetpack_protect_format_whitelist();
                 }
                 break;
             case 'jetpack_sync_non_public_post_stati':
                 Jetpack_Options::update_option('sync_non_public_post_stati', $value);
                 break;
             case 'jetpack_relatedposts_enabled':
             case 'jetpack_relatedposts_show_thumbnails':
             case 'jetpack_relatedposts_show_headline':
                 if (!$this->jetpack_relatedposts_supported()) {
                     break;
                 }
                 if ('jetpack_relatedposts_enabled' === $key && method_exists('Jetpack', 'is_module_active') && $this->jetpack_relatedposts_supported()) {
                     $before_action = Jetpack::is_module_active('related-posts');
                     if ($value) {
                         Jetpack::activate_module('related-posts', false, false);
                     } else {
                         Jetpack::deactivate_module('related-posts');
                     }
                     $after_action = Jetpack::is_module_active('related-posts');
                     if ($after_action == $before_action) {
                         break;
                     }
                 }
                 $just_the_key = substr($key, 21);
                 $jetpack_relatedposts_options[$just_the_key] = $value;
                 break;
             case 'social_notifications_like':
             case 'social_notifications_reblog':
             case 'social_notifications_subscribe':
                 // settings are stored as on|off
                 $coerce_value = $value ? 'on' : 'off';
                 if (update_option($key, $coerce_value)) {
                     $updated[$key] = $value;
                 }
                 break;
             case 'wga':
                 if (!isset($value['code']) || !preg_match('/^$|^UA-[\\d-]+$/i', $value['code'])) {
                     return new WP_Error('invalid_code', 'Invalid UA ID');
                 }
                 $wga = get_option('wga', array());
                 $wga['code'] = $value['code'];
                 // maintain compatibility with wp-google-analytics
                 if (update_option('wga', $wga)) {
                     $updated[$key] = $value;
                 }
                 $enabled_or_disabled = $wga['code'] ? 'enabled' : 'disabled';
                 do_action('jetpack_bump_stats_extras', 'google-analytics', $enabled_or_disabled);
                 $business_plugins = WPCOM_Business_Plugins::instance();
                 $business_plugins->activate_plugin('wp-google-analytics');
                 break;
             case 'jetpack_comment_likes_enabled':
                 // settings are stored as 1|0
                 $coerce_value = (int) $value;
                 if (update_option($key, $coerce_value)) {
                     $updated[$key] = $value;
                 }
                 break;
                 // Sharing options
             // Sharing options
             case 'sharing_button_style':
             case 'sharing_show':
             case 'sharing_open_links':
                 $sharing_options[preg_replace('/^sharing_/', '', $key)] = $value;
                 break;
             case 'sharing_label':
                 $sharing_options[$key] = $value;
                 break;
                 // Keyring token option
             // Keyring token option
             case 'eventbrite_api_token':
                 // These options can only be updated for sites hosted on WordPress.com
                 if (defined('IS_WPCOM') && IS_WPCOM) {
                     if (empty($value) || WPCOM_JSON_API::is_falsy($value)) {
                         if (delete_option($key)) {
                             $updated[$key] = null;
                         }
                     } else {
                         if (update_option($key, $value)) {
                             $updated[$key] = (int) $value;
                         }
                     }
                 }
                 break;
                 // no worries, we've already whitelisted and casted arguments above
             // no worries, we've already whitelisted and casted arguments above
             default:
                 if (update_option($key, $value)) {
                     $updated[$key] = $value;
                 }
         }
     }
     if (count($jetpack_relatedposts_options)) {
         // track new jetpack_relatedposts options against old
         $old_relatedposts_options = Jetpack_Options::get_option('relatedposts');
         if (Jetpack_Options::update_option('relatedposts', $jetpack_relatedposts_options)) {
             foreach ($jetpack_relatedposts_options as $key => $value) {
                 if ($value !== $old_relatedposts_options[$key]) {
                     $updated['jetpack_relatedposts_' . $key] = $value;
                 }
             }
         }
     }
     if (!empty($sharing_options) && class_exists('Sharing_Service')) {
         $ss = new Sharing_Service();
         // Merge current values with updated, since Sharing_Service expects
         // all values to be included when updating
         $current_sharing_options = $ss->get_global_options();
         foreach ($current_sharing_options as $key => $val) {
             if (!isset($sharing_options[$key])) {
                 $sharing_options[$key] = $val;
             }
         }
         $updated_social_options = $ss->set_global_options($sharing_options);
         if (isset($input['sharing_button_style'])) {
             $updated['sharing_button_style'] = (string) $updated_social_options['button_style'];
         }
         if (isset($input['sharing_label'])) {
             // Sharing_Service won't report label as updated if set to default
             $updated['sharing_label'] = (string) $sharing_options['sharing_label'];
         }
         if (isset($input['sharing_show'])) {
             $updated['sharing_show'] = (array) $updated_social_options['show'];
         }
         if (isset($input['sharing_open_links'])) {
             $updated['sharing_open_links'] = (string) $updated_social_options['open_links'];
         }
     }
     return array('updated' => $updated);
 }
Exemplo n.º 22
0
function jetpack_protect_save_whitelist($whitelist, $global = false)
{
    $whitelist_error = false;
    $new_items = array();
    if (!is_array($whitelist)) {
        return new WP_Error('invalid_parameters', __('Expecting an array', 'jetpack'));
    }
    if ($global && !is_multisite()) {
        return new WP_Error('invalid_parameters', __('Cannot use global flag on non-multisites', 'jetpack'));
    }
    if ($global && !current_user_can('manage_network')) {
        return new WP_Error('permission_denied', __('Only super admins can edit the global whitelist', 'jetpack'));
    }
    // validate each item
    foreach ($whitelist as $item) {
        $item = trim($item);
        if (empty($item)) {
            continue;
        }
        $range = false;
        if (strpos($item, '-')) {
            $item = explode('-', $item);
            $range = true;
        }
        $new_item = new stdClass();
        $new_item->range = $range;
        if (!empty($range)) {
            $low = trim($item[0]);
            $high = trim($item[1]);
            if (!filter_var($low, FILTER_VALIDATE_IP) || !filter_var($high, FILTER_VALIDATE_IP)) {
                $whitelist_error = true;
                break;
            }
            if (!jetpack_convert_ip_address($low) || !jetpack_convert_ip_address($high)) {
                $whitelist_error = true;
                break;
            }
            $new_item->range_low = $low;
            $new_item->range_high = $high;
        } else {
            if (!filter_var($item, FILTER_VALIDATE_IP)) {
                $whitelist_error = true;
                break;
            }
            if (!jetpack_convert_ip_address($item)) {
                $whitelist_error = true;
                break;
            }
            $new_item->ip_address = $item;
        }
        $new_items[] = $new_item;
    }
    // end item loop
    if (!empty($whitelist_error)) {
        return new WP_Error('invalid_ip', __('One of your IP addresses was not valid.', 'jetpack'));
    }
    if ($global) {
        update_site_option('jetpack_protect_global_whitelist', $new_items);
        // once a user has saved their global whitelist, we can permanently remove the legacy option
        delete_site_option('jetpack_protect_whitelist');
    } else {
        Jetpack_Options::update_option('protect_whitelist', $new_items);
    }
    return true;
}
Exemplo n.º 23
0
 /**
  * Update VideoPress options
  */
 function update_options($options)
 {
     Jetpack_Options::update_option($this->option_name, $options);
 }
Exemplo n.º 24
0
 public static function jumpstart_has_updated_module_option($option_name = '')
 {
     // Bail if Jump Start has already been dismissed
     if ('new_connection' !== Jetpack::get_option('jumpstart')) {
         return false;
     }
     $jetpack = Jetpack::init();
     // Manual build of module options
     $option_names = array('sharing-options', 'disabled_likes', 'disabled_reblogs', 'jetpack_comments_likes_enabled', 'wp_mobile_excerpt', 'wp_mobile_featured_images', 'wp_mobile_app_promos', 'stats_options', 'stats_dashboard_widget', 'safecss_preview_rev', 'safecss_rev', 'safecss_revision_migrated', 'nova_menu_order', 'jetpack_portfolio', 'jetpack_portfolio_posts_per_page', 'jetpack_testimonial', 'jetpack_testimonial_posts_per_page', 'wp_mobile_custom_css', 'sharedaddy_disable_resources', 'sharing-options', 'sharing-services', 'site_icon_temp_data', 'featured-content', 'site_logo');
     if (in_array($option_name, $option_names)) {
         Jetpack_Options::update_option('jumpstart', 'jetpack_action_taken');
         //Jump start is being dismissed send data to MC Stats
         $jetpack->stat('jumpstart', 'manual,' . $option_name);
         $jetpack->do_stats('server_side');
     }
 }
Exemplo n.º 25
0
/**
 * Fetches stats data from the REST API.  Caches locally for 5 minutes.
 *
 * @link: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/
 *
 * @param  array|string   $args     The args that are passed to the endpoint
 * @param  string         $resource Optional sub-endpoint following /stats/
 * @return array|WP_Error
 */
function stats_get_from_restapi($args = array(), $resource = '')
{
    $endpoint = jetpack_stats_api_path($resource);
    $api_version = '1.1';
    $args = wp_parse_args($args, array());
    $cache_key = md5(implode('|', array($endpoint, $api_version, serialize($args))));
    // Get cache
    $stats_cache = Jetpack_Options::get_option('restapi_stats_cache', array());
    if (!is_array($stats_cache)) {
        $stats_cache = array();
    }
    // Return or expire this key
    if (isset($stats_cache[$cache_key])) {
        $time = key($stats_cache[$cache_key]);
        if (time() - $time < 5 * MINUTE_IN_SECONDS) {
            $cached_stats = $stats_cache[$cache_key][$time];
            $cached_stats = (object) array_merge(array('cached_at' => $time), (array) $cached_stats);
            return $cached_stats;
        }
        unset($stats_cache[$cache_key]);
    }
    // Do the dirty work.
    $response = Jetpack_Client::wpcom_json_api_request_as_blog($endpoint, $api_version, $args);
    if (200 !== wp_remote_retrieve_response_code($response)) {
        // If bad, just return it, don't cache.
        return $response;
    }
    $data = json_decode(wp_remote_retrieve_body($response));
    // Expire old keys
    foreach ($stats_cache as $k => $cache) {
        if (!is_array($cache) || 5 * MINUTE_IN_SECONDS < time() - key($cache)) {
            unset($stats_cache[$k]);
        }
    }
    // Set cache
    $stats_cache[$cache_key] = array(time() => $data);
    Jetpack_Options::update_option('restapi_stats_cache', $stats_cache, false);
    return $data;
}
Exemplo n.º 26
0
 /**
  * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
  *
  * @param string $name  Option name
  * @param mixed  $value Option value
  */
 public static function update_option($name, $value)
 {
     return Jetpack_Options::update_option($name, $value);
 }
Exemplo n.º 27
0
 /**
  * Manage Jetpack Options
  *
  * ## OPTIONS
  *
  * list   : List all jetpack options and their values
  * delete : Delete an option
  *          - can only delete options that are white listed.
  * update : update an option
  *          - can only update option strings
  * get    : get the value of an option
  *
  * ## EXAMPLES
  *
  * wp jetpack options list
  * wp jetpack options get    <option_name>
  * wp jetpack options delete <option_name>
  * wp jetpack options update <option_name> [<option_value>]
  *
  * @synopsis <list|get|delete|update> [<option_name>] [<option_value>]
  */
 public function options($args, $assoc_args)
 {
     $action = isset($args[0]) ? $args[0] : 'list';
     $safe_to_modify = Jetpack::get_jetpack_options_for_reset();
     // Jumpstart is special
     array_push($safe_to_modify, 'jumpstart');
     // Is the option flagged as unsafe?
     $flagged = !in_array($args[1], $safe_to_modify);
     if (!in_array($action, array('list', 'get', 'delete', 'update'))) {
         WP_CLI::error(sprintf(__('%s is not a valid command.', 'jetpack'), $action));
     }
     if (isset($args[0])) {
         if ('get' == $args[0] && isset($args[1])) {
             $action = 'get';
         } else {
             if ('delete' == $args[0] && isset($args[1])) {
                 $action = 'delete';
             } else {
                 if ('update' == $args[0] && isset($args[1])) {
                     $action = 'update';
                 } else {
                     $action = 'list';
                 }
             }
         }
     }
     // Bail if the option isn't found
     $option = isset($args[1]) ? Jetpack_Options::get_option($args[1]) : false;
     if (isset($args[1]) && !$option && 'update' !== $args[0]) {
         WP_CLI::error(__('Option not found or is empty.  Use "list" to list option names', 'jetpack'));
     }
     // Let's print_r the option if it's an array
     // Used in the 'get' and 'list' actions
     $option = is_array($option) ? print_r($option) : $option;
     switch ($action) {
         case 'get':
             WP_CLI::success("\t" . $option);
             break;
         case 'delete':
             jetpack_cli_are_you_sure($flagged);
             Jetpack_Options::delete_option($args[1]);
             WP_CLI::success(sprintf(__('Deleted option: %s', 'jetpack'), $args[1]));
             break;
         case 'update':
             jetpack_cli_are_you_sure($flagged);
             // Updating arrays would get pretty tricky...
             $value = Jetpack_Options::get_option($args[1]);
             if ($value && is_array($value)) {
                 WP_CLI::error(__('Sorry, no updating arrays at this time', 'jetpack'));
             }
             Jetpack_Options::update_option($args[1], $args[2]);
             WP_CLI::success(sprintf(_x('Updated option: %s to "%s"', 'Updating an option from "this" to "that".', 'jetpack'), $args[1], $args[2]));
             break;
         case 'list':
             $options_compact = Jetpack_Options::get_option_names();
             $options_non_compact = Jetpack_Options::get_option_names('non_compact');
             $options_private = Jetpack_Options::get_option_names('private');
             $options = array_merge($options_compact, $options_non_compact, $options_private);
             // Table headers
             WP_CLI::line("\t" . str_pad(__('Option', 'jetpack'), 30) . __('Value', 'jetpack'));
             // List out the options and their values
             // Tell them if the value is empty or not
             // Tell them if it's an array
             foreach ($options as $option) {
                 $value = Jetpack_Options::get_option($option);
                 if (!$value) {
                     WP_CLI::line("\t" . str_pad($option, 30) . 'Empty');
                     continue;
                 }
                 if (!is_array($value)) {
                     WP_CLI::line("\t" . str_pad($option, 30) . $value);
                 } else {
                     if (is_array($value)) {
                         WP_CLI::line("\t" . str_pad($option, 30) . 'Array - Use "get <option>" to read option array.');
                     }
                 }
             }
             $option_text = '{' . _x('option', 'a variable command that a user can write, provided in the printed instructions', 'jetpack') . '}';
             $value_text = '{' . _x('value', 'the value that they want to update the option to', 'jetpack') . '}';
             WP_CLI::success(_x("Above are your options. You may 'get', 'delete', and 'update' them.", "'get', 'delete', and 'update' are commands - do not translate.", 'jetpack') . "\n" . str_pad('wp jetpack options get', 26) . $option_text . "\n" . str_pad('wp jetpack options delete', 26) . $option_text . "\n" . str_pad('wp jetpack options update', 26) . "{$option_text} {$value_text}" . "\n" . _x("Type 'wp jetpack options' for more info.", "'wp jetpack options' is a command - do not translate.", 'jetpack') . "\n");
             break;
     }
 }
Exemplo n.º 28
0
 /**
  * @author tonykova
  * @covers Jetpack::check_identity_crisis
  * @since 3.2.0
  */
 public function test_check_identity_crisis_will_not_report_crisis_if_a_siteurl_mismatch_when_forcing_ssl()
 {
     // Kick in with force ssl and store master user data
     force_ssl_admin(true);
     Jetpack_Options::update_option('master_user', 'test');
     Jetpack_Options::update_option('user_tokens', array('test' => 'herp.derp.test'));
     add_filter('jetpack_development_mode', '__return_false', 1, 1);
     // Mock get_cloud_site_options
     $jp = $this->getMock('MockJetpack', array('get_cloud_site_options'));
     $jp->init();
     Jetpack::$instance = $jp;
     $jp->expects($this->any())->method('get_cloud_site_options')->will($this->returnValue(array('siteurl' => 'https://test.site.com')));
     // Save the mismatching option for comparison
     // Using @ to prevent throwing an error on a bug in WP core when attempting to change .htaccess
     @update_option('siteurl', 'http://test.site.com');
     // Attach hook for checking the errors
     add_filter('jetpack_has_identity_crisis', array($this, 'pre_test_check_identity_crisis_will_not_report_crisis_if_a_siteurl_mismatch_when_forcing_ssl'));
     $this->assertTrue(false !== MockJetpack::check_identity_crisis(true));
     remove_filter('jetpack_has_identity_crisis', array($this, 'pre_test_check_identity_crisis_will_not_report_crisis_if_a_siteurl_mismatch_when_forcing_ssl'));
 }
Exemplo n.º 29
0
 /**
  * Adds a value to the whitelist for the specified key.
  *
  * @param string $key The option name that we're whitelisting the value for.
  * @param string $value The value that we're intending to add to the whitelist.
  *
  * @return bool Whether the value was added to the whitelist, or false if it was already there.
  */
 public static function whitelist_identity_crisis_value($key, $value)
 {
     if (self::is_identity_crisis_url_whitelisted($key, $value)) {
         return false;
     }
     $whitelist = Jetpack_Options::get_option('identity_crisis_whitelist', array());
     if (empty($whitelist[$key]) || !is_array($whitelist[$key])) {
         $whitelist[$key] = array();
     }
     array_push($whitelist[$key], $value);
     Jetpack_Options::update_option('identity_crisis_whitelist', $whitelist);
     return true;
 }
 public static function do_migration()
 {
     Jetpack_Options::update_option('custom_css_4.7_migration', true);
     Jetpack::log('custom_css_4.7_migration', 'start');
     if (!post_type_exists('safecss')) {
         self::register_legacy_post_type();
     }
     /** This filter is documented in modules/custom-css/custom-css.php */
     $preprocessors = apply_filters('jetpack_custom_css_preprocessors', array());
     $core_css_post = wp_get_custom_css_post();
     $jetpack_css_post = self::get_post();
     $revisions = self::get_all_revisions();
     // Migrate the settings from revision meta to theme mod.
     $options = self::get_options($jetpack_css_post->ID);
     set_theme_mod('jetpack_custom_css', $options);
     if (empty($revisions) || !is_array($revisions)) {
         if ($jetpack_css_post instanceof WP_Post) {
             // Feed in the raw, if the current setting is Sass/LESS, it'll filter it inside.
             wp_update_custom_css_post($jetpack_css_post->post_content);
             return 1;
         }
         return null;
     }
     $revisions = array_reverse($revisions);
     $themes = Jetpack_Custom_CSS_Enhancements::get_themes();
     $migrated = array();
     foreach ($revisions as $post_id => $post) {
         // Jetpack had stored the theme Name, not the stylesheet directory, for ... reasons.
         // Get the stylesheet.  If null, the theme is no longer available.  Skip.
         $stylesheet = isset($themes[$post->post_excerpt]) ? $themes[$post->post_excerpt] : null;
         if (empty($stylesheet)) {
             continue;
         }
         $migrated[] = $post->ID;
         $preprocessor = get_post_meta($post->ID, 'custom_css_preprocessor', true);
         $css = $post->post_content;
         $pre = '';
         // Do a revision by revision parsing.
         if ($preprocessor && isset($preprocessors[$preprocessor])) {
             $pre = $css;
             $css = call_user_func($preprocessors[$preprocessor]['callback'], $pre);
         }
         // Do we need to remove any filters here for users without `unfiltered_html` ?
         wp_update_custom_css_post($css, array('stylesheet' => $stylesheet, 'preprocessed' => $pre));
     }
     // If we've migrated some CSS for the current theme and there was already something there in the Core dataset ...
     if ($core_css_post && $jetpack_css_post) {
         $preprocessor = $options['preprocessor'];
         $css = $core_css_post->post_content;
         $pre = $core_css_post->post_content_filtered;
         if ($preprocessor) {
             if ($pre) {
                 $pre .= "\r\n\r\n/*\r\n\t" . esc_js(__('CSS Migrated from Jetpack:', 'jetpack')) . "\r\n*/\r\n\r\n";
             }
             $pre .= $jetpack_css_post->post_content;
             $css .= "\r\n\r\n/*\r\n\t" . esc_js(__('CSS Migrated from Jetpack:', 'jetpack')) . "\r\n*/\r\n\r\n";
             $css .= call_user_func($preprocessors[$preprocessor]['callback'], $jetpack_css_post->post_content);
         } else {
             $css .= "\r\n\r\n/*\r\n\t" . esc_js(__('CSS Migrated from Jetpack:', 'jetpack')) . "\r\n*/\r\n\r\n";
             $css .= $jetpack_css_post->post_content;
         }
         wp_update_custom_css_post($css, array('preprocessed' => $pre));
     }
     Jetpack::log('custom_css_4.7_migration', sizeof($migrated) . 'revisions migrated');
     return sizeof($migrated);
 }