/**
  * @ticket 22846
  */
 public function test_update_network_option_is_not_stored_as_autoload_option()
 {
     $key = rand_str();
     if (is_multisite()) {
         $this->markTestSkipped('Does not apply when used in multisite.');
     }
     update_network_option(null, $key, 'Not an autoload option');
     $options = wp_load_alloptions();
     $this->assertFalse(isset($options[$key]));
 }
Ejemplo n.º 2
0
 /**
  * Get/set sys version.
  *
  * @since 160531 Sys options.
  *
  * @param string     $key      Sys option key.
  * @param mixed|null $value    If setting value.
  * @param bool       $autoload Autoload option key?
  *
  * @return mixed|null Sys option value or `null`.
  */
 public function __invoke(string $key, $value = null, bool $autoload = true)
 {
     $key = $this->App->Config->©brand['©var'] . '_' . $key;
     if ($this->App->Config->§specs['§is_network_wide'] && $this->Wp->is_multisite) {
         if (isset($value)) {
             update_network_option(null, $key, $value);
         }
         if (($value = get_network_option(null, $key)) === null || $value === false) {
             add_network_option(null, $key, ':null');
             // Autoload impossible.
             // These will not autoload and there is no way to change this.
         }
     } else {
         // Default.
         if (isset($value)) {
             update_option($key, $value);
         }
         if (($value = get_option($key)) === null || $value === false) {
             add_option($key, ':null', '', $autoload ? 'yes' : 'no');
         }
     }
     return $value === null || $value === false || $value === ':null' ? null : $value;
 }
 /**
  * Saves the modules persistently.
  *
  * @since 3.0.0
  *
  * @return bool Whether or not the modules were saved successfully.
  */
 public function save_modules()
 {
     return update_network_option(null, $this->option, $this->states);
 }
Ejemplo n.º 4
0
if (is_subdomain_install()) {
    echo '<p class="description">' . __('If registration is disabled, please set <code>NOBLOGREDIRECT</code> in <code>wp-config.php</code> to a URL you will redirect visitors to if they visit a non-existent site.') . '</p>';
}
?>
					</fieldset>
				</td>
			</tr>

			<tr>
				<th scope="row"><?php 
_e('Registration notification');
?>
</th>
				<?php 
if (!get_network_option('registrationnotification')) {
    update_network_option('registrationnotification', 'yes');
}
?>
				<td>
					<label><input name="registrationnotification" type="checkbox" id="registrationnotification" value="yes"<?php 
checked(get_network_option('registrationnotification'), 'yes');
?>
 /> <?php 
_e('Send the network admin an email notification every time someone registers a site or user account.');
?>
</label>
				</td>
			</tr>

			<tr id="addnewusers">
				<th scope="row"><?php 
Ejemplo n.º 5
0
/**
 * Revokes Super Admin privileges.
 *
 * @since 3.0.0
 *
 * @global array $super_admins
 *
 * @param int $user_id ID of the user Super Admin privileges to be revoked from.
 * @return bool True on success, false on failure. This can fail when the user's email
 *              is the network admin email or when the `$super_admins` global is defined.
 */
function revoke_super_admin($user_id)
{
    // If global super_admins override is defined, there is nothing to do here.
    if (isset($GLOBALS['super_admins'])) {
        return false;
    }
    /**
     * Fires before the user's Super Admin privileges are revoked.
     *
     * @since 3.0.0
     *
     * @param int $user_id ID of the user Super Admin privileges are being revoked from.
     */
    do_action('revoke_super_admin', $user_id);
    // Directly fetch site_admins instead of using get_super_admins()
    $super_admins = get_network_option('site_admins', array('admin'));
    $user = get_userdata($user_id);
    if ($user && 0 !== strcasecmp($user->user_email, get_network_option('admin_email'))) {
        if (false !== ($key = array_search($user->user_login, $super_admins))) {
            unset($super_admins[$key]);
            update_network_option('site_admins', $super_admins);
            /**
             * Fires after the user's Super Admin privileges are revoked.
             *
             * @since 3.0.0
             *
             * @param int $user_id ID of the user Super Admin privileges were revoked from.
             */
            do_action('revoked_super_admin', $user_id);
            return true;
        }
    }
    return false;
}
Ejemplo n.º 6
0
/**
 * Set/update the value of a site transient.
 *
 * You do not need to serialize values, if the value needs to be serialize, then
 * it will be serialized before it is set.
 *
 * @since 2.9.0
 *
 * @see set_transient()
 *
 * @param string $transient  Transient name. Expected to not be SQL-escaped. Must be
 *                           40 characters or fewer in length.
 * @param mixed  $value      Transient value. Expected to not be SQL-escaped.
 * @param int    $expiration Optional. Time until expiration in seconds. Default 0.
 * @return bool False if value was not set and true if value was set.
 */
function set_site_transient($transient, $value, $expiration = 0)
{
    /**
     * Filter the value of a specific site transient before it is set.
     *
     * The dynamic portion of the hook name, `$transient`, refers to the transient name.
     *
     * @since 3.0.0
     * @since 4.4.0 The `$transient` parameter was added
     *
     * @param mixed  $value     Value of site transient.
     * @param string $transient Transient name.
     */
    $value = apply_filters('pre_set_site_transient_' . $transient, $value, $transient);
    $expiration = (int) $expiration;
    if (wp_using_ext_object_cache()) {
        $result = wp_cache_set($transient, $value, 'site-transient', $expiration);
    } else {
        $transient_timeout = '_site_transient_timeout_' . $transient;
        $option = '_site_transient_' . $transient;
        if (false === get_network_option($option)) {
            if ($expiration) {
                add_network_option($transient_timeout, time() + $expiration);
            }
            $result = add_network_option($option, $value);
        } else {
            if ($expiration) {
                update_network_option($transient_timeout, time() + $expiration);
            }
            $result = update_network_option($option, $value);
        }
    }
    if ($result) {
        /**
         * Fires after the value for a specific site transient has been set.
         *
         * The dynamic portion of the hook name, `$transient`, refers to the transient name.
         *
         * @since 3.0.0
         * @since 4.4.0 The `$transient` parameter was added
         *
         * @param mixed  $value      Site transient value.
         * @param int    $expiration Time until expiration in seconds. Default 0.
         * @param string $transient  Transient name.
         */
        do_action('set_site_transient_' . $transient, $value, $expiration, $transient);
        /**
         * Fires after the value for a site transient has been set.
         *
         * @since 3.0.0
         *
         * @param string $transient  The name of the site transient.
         * @param mixed  $value      Site transient value.
         * @param int    $expiration Time until expiration in seconds. Default 0.
         */
        do_action('setted_site_transient', $transient, $value, $expiration);
    }
    return $result;
}
Ejemplo n.º 7
0
 /**
  * Sends an email upon the completion or failure of a background core update.
  *
  * @since 3.7.0
  * @access protected
  *
  * @global string $wp_version
  *
  * @param string $type        The type of email to send. Can be one of 'success', 'fail', 'manual', 'critical'.
  * @param object $core_update The update offer that was attempted.
  * @param mixed  $result      Optional. The result for the core update. Can be WP_Error.
  */
 protected function send_email($type, $core_update, $result = null)
 {
     update_network_option('auto_core_update_notified', array('type' => $type, 'email' => get_network_option('admin_email'), 'version' => $core_update->current, 'timestamp' => time()));
     $next_user_core_update = get_preferred_from_update_core();
     // If the update transient is empty, use the update we just performed
     if (!$next_user_core_update) {
         $next_user_core_update = $core_update;
     }
     $newer_version_available = 'upgrade' == $next_user_core_update->response && version_compare($next_user_core_update->version, $core_update->version, '>');
     /**
      * Filter whether to send an email following an automatic background core update.
      *
      * @since 3.7.0
      *
      * @param bool   $send        Whether to send the email. Default true.
      * @param string $type        The type of email to send. Can be one of
      *                            'success', 'fail', 'critical'.
      * @param object $core_update The update offer that was attempted.
      * @param mixed  $result      The result for the core update. Can be WP_Error.
      */
     if ('manual' !== $type && !apply_filters('auto_core_update_send_email', true, $type, $core_update, $result)) {
         return;
     }
     switch ($type) {
         case 'success':
             // We updated.
             /* translators: 1: Site name, 2: WordPress version number. */
             $subject = __('[%1$s] Your site has updated to WordPress %2$s');
             break;
         case 'fail':
             // We tried to update but couldn't.
         // We tried to update but couldn't.
         case 'manual':
             // We can't update (and made no attempt).
             /* translators: 1: Site name, 2: WordPress version number. */
             $subject = __('[%1$s] WordPress %2$s is available. Please update!');
             break;
         case 'critical':
             // We tried to update, started to copy files, then things went wrong.
             /* translators: 1: Site name. */
             $subject = __('[%1$s] URGENT: Your site may be down due to a failed update');
             break;
         default:
             return;
     }
     // If the auto update is not to the latest version, say that the current version of WP is available instead.
     $version = 'success' === $type ? $core_update->current : $next_user_core_update->current;
     $subject = sprintf($subject, wp_specialchars_decode(get_option('blogname'), ENT_QUOTES), $version);
     $body = '';
     switch ($type) {
         case 'success':
             $body .= sprintf(__('Howdy! Your site at %1$s has been updated automatically to WordPress %2$s.'), home_url(), $core_update->current);
             $body .= "\n\n";
             if (!$newer_version_available) {
                 $body .= __('No further action is needed on your part.') . ' ';
             }
             // Can only reference the About screen if their update was successful.
             list($about_version) = explode('-', $core_update->current, 2);
             $body .= sprintf(__("For more on version %s, see the About WordPress screen:"), $about_version);
             $body .= "\n" . admin_url('about.php');
             if ($newer_version_available) {
                 $body .= "\n\n" . sprintf(__('WordPress %s is also now available.'), $next_user_core_update->current) . ' ';
                 $body .= __('Updating is easy and only takes a few moments:');
                 $body .= "\n" . network_admin_url('update-core.php');
             }
             break;
         case 'fail':
         case 'manual':
             $body .= sprintf(__('Please update your site at %1$s to WordPress %2$s.'), home_url(), $next_user_core_update->current);
             $body .= "\n\n";
             // Don't show this message if there is a newer version available.
             // Potential for confusion, and also not useful for them to know at this point.
             if ('fail' == $type && !$newer_version_available) {
                 $body .= __('We tried but were unable to update your site automatically.') . ' ';
             }
             $body .= __('Updating is easy and only takes a few moments:');
             $body .= "\n" . network_admin_url('update-core.php');
             break;
         case 'critical':
             if ($newer_version_available) {
                 $body .= sprintf(__('Your site at %1$s experienced a critical failure while trying to update WordPress to version %2$s.'), home_url(), $core_update->current);
             } else {
                 $body .= sprintf(__('Your site at %1$s experienced a critical failure while trying to update to the latest version of WordPress, %2$s.'), home_url(), $core_update->current);
             }
             $body .= "\n\n" . __("This means your site may be offline or broken. Don't panic; this can be fixed.");
             $body .= "\n\n" . __("Please check out your site now. It's possible that everything is working. If it says you need to update, you should do so:");
             $body .= "\n" . network_admin_url('update-core.php');
             break;
     }
     $critical_support = 'critical' === $type && !empty($core_update->support_email);
     if ($critical_support) {
         // Support offer if available.
         $body .= "\n\n" . sprintf(__("The WordPress team is willing to help you. Forward this email to %s and the team will work with you to make sure your site is working."), $core_update->support_email);
     } else {
         // Add a note about the support forums.
         $body .= "\n\n" . __('If you experience any issues or need support, the volunteers in the WordPress.org support forums may be able to help.');
         $body .= "\n" . __('https://wordpress.org/support/');
     }
     // Updates are important!
     if ($type != 'success' || $newer_version_available) {
         $body .= "\n\n" . __('Keeping your site updated is important for security. It also makes the internet a safer place for you and your readers.');
     }
     if ($critical_support) {
         $body .= " " . __("If you reach out to us, we'll also ensure you'll never have this problem again.");
     }
     // If things are successful and we're now on the latest, mention plugins and themes if any are out of date.
     if ($type == 'success' && !$newer_version_available && (get_plugin_updates() || get_theme_updates())) {
         $body .= "\n\n" . __('You also have some plugins or themes with updates available. Update them now:');
         $body .= "\n" . network_admin_url();
     }
     $body .= "\n\n" . __('The WordPress Team') . "\n";
     if ('critical' == $type && is_wp_error($result)) {
         $body .= "\n***\n\n";
         $body .= sprintf(__('Your site was running version %s.'), $GLOBALS['wp_version']);
         $body .= ' ' . __('We have some data that describes the error your site encountered.');
         $body .= ' ' . __('Your hosting company, support forum volunteers, or a friendly developer may be able to use this information to help you:');
         // If we had a rollback and we're still critical, then the rollback failed too.
         // Loop through all errors (the main WP_Error, the update result, the rollback result) for code, data, etc.
         if ('rollback_was_required' == $result->get_error_code()) {
             $errors = array($result, $result->get_error_data()->update, $result->get_error_data()->rollback);
         } else {
             $errors = array($result);
         }
         foreach ($errors as $error) {
             if (!is_wp_error($error)) {
                 continue;
             }
             $error_code = $error->get_error_code();
             $body .= "\n\n" . sprintf(__("Error code: %s"), $error_code);
             if ('rollback_was_required' == $error_code) {
                 continue;
             }
             if ($error->get_error_message()) {
                 $body .= "\n" . $error->get_error_message();
             }
             $error_data = $error->get_error_data();
             if ($error_data) {
                 $body .= "\n" . implode(', ', (array) $error_data);
             }
         }
         $body .= "\n";
     }
     $to = get_network_option('admin_email');
     $headers = '';
     $email = compact('to', 'subject', 'body', 'headers');
     /**
      * Filter the email sent following an automatic background core update.
      *
      * @since 3.7.0
      *
      * @param array $email {
      *     Array of email arguments that will be passed to wp_mail().
      *
      *     @type string $to      The email recipient. An array of emails
      *                            can be returned, as handled by wp_mail().
      *     @type string $subject The email's subject.
      *     @type string $body    The email message body.
      *     @type string $headers Any email headers, defaults to no headers.
      * }
      * @param string $type        The type of email being sent. Can be one of
      *                            'success', 'fail', 'manual', 'critical'.
      * @param object $core_update The update offer that was attempted.
      * @param mixed  $result      The result for the core update. Can be WP_Error.
      */
     $email = apply_filters('auto_core_update_email', $email, $type, $core_update, $result);
     wp_mail($email['to'], wp_specialchars_decode($email['subject']), $email['body'], $email['headers']);
 }
 /**
  *
  * @global string $status
  * @global type   $plugins
  * @global array  $totals
  * @global int    $page
  * @global string $orderby
  * @global string $order
  * @global string $s
  */
 public function prepare_items()
 {
     global $status, $plugins, $totals, $page, $orderby, $order, $s;
     wp_reset_vars(array('orderby', 'order', 's'));
     /**
      * Filter the full array of plugins to list in the Plugins list table.
      *
      * @since 3.0.0
      *
      * @see get_plugins()
      *
      * @param array $plugins An array of plugins to display in the list table.
      */
     $plugins = array('all' => apply_filters('all_plugins', get_plugins()), 'search' => array(), 'active' => array(), 'inactive' => array(), 'recently_activated' => array(), 'upgrade' => array(), 'mustuse' => array(), 'dropins' => array());
     $screen = $this->screen;
     if (!is_multisite() || $screen->in_admin('network') && current_user_can('manage_network_plugins')) {
         /**
          * Filter whether to display the advanced plugins list table.
          *
          * There are two types of advanced plugins - must-use and drop-ins -
          * which can be used in a single site or Multisite network.
          *
          * The $type parameter allows you to differentiate between the type of advanced
          * plugins to filter the display of. Contexts include 'mustuse' and 'dropins'.
          *
          * @since 3.0.0
          *
          * @param bool   $show Whether to show the advanced plugins for the specified
          *                     plugin type. Default true.
          * @param string $type The plugin type. Accepts 'mustuse', 'dropins'.
          */
         if (apply_filters('show_advanced_plugins', true, 'mustuse')) {
             $plugins['mustuse'] = get_mu_plugins();
         }
         /** This action is documented in wp-admin/includes/class-wp-plugins-list-table.php */
         if (apply_filters('show_advanced_plugins', true, 'dropins')) {
             $plugins['dropins'] = get_dropins();
         }
         if (current_user_can('update_plugins')) {
             $current = get_site_transient('update_plugins');
             foreach ((array) $plugins['all'] as $plugin_file => $plugin_data) {
                 if (isset($current->response[$plugin_file])) {
                     $plugins['all'][$plugin_file]['update'] = true;
                     $plugins['upgrade'][$plugin_file] = $plugins['all'][$plugin_file];
                 }
             }
         }
     }
     set_transient('plugin_slugs', array_keys($plugins['all']), DAY_IN_SECONDS);
     if ($screen->in_admin('network')) {
         $recently_activated = get_network_option('recently_activated', array());
     } else {
         $recently_activated = get_option('recently_activated', array());
     }
     foreach ($recently_activated as $key => $time) {
         if ($time + WEEK_IN_SECONDS < time()) {
             unset($recently_activated[$key]);
         }
     }
     if ($screen->in_admin('network')) {
         update_network_option('recently_activated', $recently_activated);
     } else {
         update_option('recently_activated', $recently_activated);
     }
     $plugin_info = get_site_transient('update_plugins');
     foreach ((array) $plugins['all'] as $plugin_file => $plugin_data) {
         // Extra info if known. array_merge() ensures $plugin_data has precedence if keys collide.
         if (isset($plugin_info->response[$plugin_file])) {
             $plugins['all'][$plugin_file] = $plugin_data = array_merge((array) $plugin_info->response[$plugin_file], $plugin_data);
             // Make sure that $plugins['upgrade'] also receives the extra info since it is used on ?plugin_status=upgrade
             if (isset($plugins['upgrade'][$plugin_file])) {
                 $plugins['upgrade'][$plugin_file] = $plugin_data = array_merge((array) $plugin_info->response[$plugin_file], $plugin_data);
             }
         } elseif (isset($plugin_info->no_update[$plugin_file])) {
             $plugins['all'][$plugin_file] = $plugin_data = array_merge((array) $plugin_info->no_update[$plugin_file], $plugin_data);
             // Make sure that $plugins['upgrade'] also receives the extra info since it is used on ?plugin_status=upgrade
             if (isset($plugins['upgrade'][$plugin_file])) {
                 $plugins['upgrade'][$plugin_file] = $plugin_data = array_merge((array) $plugin_info->no_update[$plugin_file], $plugin_data);
             }
         }
         // Filter into individual sections
         if (is_multisite() && !$screen->in_admin('network') && is_network_only_plugin($plugin_file) && !is_plugin_active($plugin_file)) {
             // On the non-network screen, filter out network-only plugins as long as they're not individually activated
             unset($plugins['all'][$plugin_file]);
         } elseif (!$screen->in_admin('network') && is_plugin_active_for_network($plugin_file)) {
             // On the non-network screen, filter out network activated plugins
             unset($plugins['all'][$plugin_file]);
         } elseif (!$screen->in_admin('network') && is_plugin_active($plugin_file) || $screen->in_admin('network') && is_plugin_active_for_network($plugin_file)) {
             // On the non-network screen, populate the active list with plugins that are individually activated
             // On the network-admin screen, populate the active list with plugins that are network activated
             $plugins['active'][$plugin_file] = $plugin_data;
         } else {
             if (isset($recently_activated[$plugin_file])) {
                 // Populate the recently activated list with plugins that have been recently activated
                 $plugins['recently_activated'][$plugin_file] = $plugin_data;
             }
             // Populate the inactive list with plugins that aren't activated
             $plugins['inactive'][$plugin_file] = $plugin_data;
         }
     }
     if ($s) {
         $status = 'search';
         $plugins['search'] = array_filter($plugins['all'], array($this, '_search_callback'));
     }
     $totals = array();
     foreach ($plugins as $type => $list) {
         $totals[$type] = count($list);
     }
     if (empty($plugins[$status]) && !in_array($status, array('all', 'search'))) {
         $status = 'all';
     }
     $this->items = array();
     foreach ($plugins[$status] as $plugin_file => $plugin_data) {
         // Translate, Don't Apply Markup, Sanitize HTML
         $this->items[$plugin_file] = _get_plugin_data_markup_translate($plugin_file, $plugin_data, false, true);
     }
     $total_this_page = $totals[$status];
     if (!$orderby) {
         $orderby = 'Name';
     } else {
         $orderby = ucfirst($orderby);
     }
     $order = strtoupper($order);
     uasort($this->items, array($this, '_order_callback'));
     $plugins_per_page = $this->get_items_per_page(str_replace('-', '_', $screen->id . '_per_page'), 999);
     $start = ($page - 1) * $plugins_per_page;
     if ($total_this_page > $plugins_per_page) {
         $this->items = array_slice($this->items, $start, $plugins_per_page);
     }
     $this->set_pagination_args(array('total_items' => $total_this_page, 'per_page' => $plugins_per_page));
 }
Ejemplo n.º 9
0
/**
 *
 * @param string $version
 * @param string $locale
 * @return bool
 */
function undismiss_core_update($version, $locale)
{
    $dismissed = get_network_option('dismissed_update_core');
    $key = $version . '|' . $locale;
    if (!isset($dismissed[$key])) {
        return false;
    }
    unset($dismissed[$key]);
    return update_network_option('dismissed_update_core', $dismissed);
}
Ejemplo n.º 10
0
require_once ABSPATH . 'wp-admin/admin-header.php';
if (!current_user_can('manage_network')) {
    wp_die(__('You do not have permission to access this page.'), 403);
}
echo '<div class="wrap">';
echo '<h1>' . __('Upgrade Network') . '</h1>';
$action = isset($_GET['action']) ? $_GET['action'] : 'show';
switch ($action) {
    case "upgrade":
        $n = isset($_GET['n']) ? intval($_GET['n']) : 0;
        if ($n < 5) {
            /**
             * @global string $wp_db_version
             */
            global $wp_db_version;
            update_network_option('wpmu_upgrade_site', $wp_db_version);
        }
        $blogs = $wpdb->get_results("SELECT blog_id FROM {$wpdb->blogs} WHERE site_id = '{$wpdb->siteid}' AND spam = '0' AND deleted = '0' AND archived = '0' ORDER BY registered DESC LIMIT {$n}, 5", ARRAY_A);
        if (empty($blogs)) {
            echo '<p>' . __('All done!') . '</p>';
            break;
        }
        echo "<ul>";
        foreach ((array) $blogs as $details) {
            switch_to_blog($details['blog_id']);
            $siteurl = site_url();
            $upgrade_url = admin_url('upgrade.php?step=upgrade_db');
            restore_current_blog();
            echo "<li>{$siteurl}</li>";
            $response = wp_remote_get($upgrade_url, array('timeout' => 120, 'httpversion' => '1.1'));
            if (is_wp_error($response)) {
 /**
  * Handle the request to update a network
  *
  * @since 2.0.0
  */
 private function handle_update_network()
 {
     // Unslash posted data for sanitization
     $posted = wp_unslash($_POST);
     // Cast
     $network_id = !empty($posted['network_id']) ? (int) $posted['network_id'] : 0;
     // Bail if invalid network
     if (!get_network($network_id)) {
         wp_die(esc_html__('Invalid network id.', 'wp-multi-network'));
     }
     // Title
     $network_title = isset($posted['title']) ? sanitize_text_field($posted['title']) : '';
     // Domain
     $network_domain = isset($posted['domain']) ? str_replace(' ', '', strtolower(sanitize_text_field($posted['domain']))) : '';
     // Punycode support
     $network_domain = Requests_IDNAEncoder::encode($network_domain);
     // Path
     $network_path = isset($posted['path']) ? str_replace(' ', '', strtolower(sanitize_text_field($posted['path']))) : '';
     // Bail if missing fields
     if (empty($network_title) || empty($network_domain) || empty($network_path)) {
         $this->handle_redirect(array('id' => $network_id, 'action' => 'edit_network', 'network_updated' => '0'));
     }
     // Update domain & path
     $updated = update_network($network_id, $network_domain, $network_path);
     $success = '0';
     // Maybe update network title
     if (!is_wp_error($updated)) {
         update_network_option($network_id, 'site_name', $network_title);
         $success = '1';
     }
     // Handle redirect
     $this->handle_redirect(array('id' => $network_id, 'action' => 'edit_network', 'network_updated' => $success));
 }
Ejemplo n.º 12
0
/**
 * Ajax handler for compression testing.
 *
 * @since 3.1.0
 */
function wp_ajax_wp_compression_test()
{
    if (!current_user_can('manage_options')) {
        wp_die(-1);
    }
    if (ini_get('zlib.output_compression') || 'ob_gzhandler' == ini_get('output_handler')) {
        update_network_option('can_compress_scripts', 0);
        wp_die(0);
    }
    if (isset($_GET['test'])) {
        header('Expires: Wed, 11 Jan 1984 05:00:00 GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: no-cache, must-revalidate, max-age=0');
        header('Pragma: no-cache');
        header('Content-Type: application/javascript; charset=UTF-8');
        $force_gzip = defined('ENFORCE_GZIP') && ENFORCE_GZIP;
        $test_str = '"wpCompressionTest Lorem ipsum dolor sit amet consectetuer mollis sapien urna ut a. Eu nonummy condimentum fringilla tempor pretium platea vel nibh netus Maecenas. Hac molestie amet justo quis pellentesque est ultrices interdum nibh Morbi. Cras mattis pretium Phasellus ante ipsum ipsum ut sociis Suspendisse Lorem. Ante et non molestie. Porta urna Vestibulum egestas id congue nibh eu risus gravida sit. Ac augue auctor Ut et non a elit massa id sodales. Elit eu Nulla at nibh adipiscing mattis lacus mauris at tempus. Netus nibh quis suscipit nec feugiat eget sed lorem et urna. Pellentesque lacus at ut massa consectetuer ligula ut auctor semper Pellentesque. Ut metus massa nibh quam Curabitur molestie nec mauris congue. Volutpat molestie elit justo facilisis neque ac risus Ut nascetur tristique. Vitae sit lorem tellus et quis Phasellus lacus tincidunt nunc Fusce. Pharetra wisi Suspendisse mus sagittis libero lacinia Integer consequat ac Phasellus. Et urna ac cursus tortor aliquam Aliquam amet tellus volutpat Vestibulum. Justo interdum condimentum In augue congue tellus sollicitudin Quisque quis nibh."';
        if (1 == $_GET['test']) {
            echo $test_str;
            wp_die();
        } elseif (2 == $_GET['test']) {
            if (!isset($_SERVER['HTTP_ACCEPT_ENCODING'])) {
                wp_die(-1);
            }
            if (false !== stripos($_SERVER['HTTP_ACCEPT_ENCODING'], 'deflate') && function_exists('gzdeflate') && !$force_gzip) {
                header('Content-Encoding: deflate');
                $out = gzdeflate($test_str, 1);
            } elseif (false !== stripos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') && function_exists('gzencode')) {
                header('Content-Encoding: gzip');
                $out = gzencode($test_str, 1);
            } else {
                wp_die(-1);
            }
            echo $out;
            wp_die();
        } elseif ('no' == $_GET['test']) {
            update_network_option('can_compress_scripts', 0);
        } elseif ('yes' == $_GET['test']) {
            update_network_option('can_compress_scripts', 1);
        }
    }
    wp_die(0);
}
Ejemplo n.º 13
0
/**
 * Deactivate a single plugin or multiple plugins.
 *
 * The deactivation hook is disabled by the plugin upgrader by using the $silent
 * parameter.
 *
 * @since 2.5.0
 *
 * @param string|array $plugins Single plugin or list of plugins to deactivate.
 * @param bool $silent Prevent calling deactivation hooks. Default is false.
 * @param mixed $network_wide Whether to deactivate the plugin for all sites in the network.
 * 	A value of null (the default) will deactivate plugins for both the site and the network.
 */
function deactivate_plugins($plugins, $silent = false, $network_wide = null)
{
    if (is_multisite()) {
        $network_current = get_network_option('active_sitewide_plugins', array());
    }
    $current = get_option('active_plugins', array());
    $do_blog = $do_network = false;
    foreach ((array) $plugins as $plugin) {
        $plugin = plugin_basename(trim($plugin));
        if (!is_plugin_active($plugin)) {
            continue;
        }
        $network_deactivating = false !== $network_wide && is_plugin_active_for_network($plugin);
        if (!$silent) {
            /**
             * Fires before a plugin is deactivated.
             *
             * If a plugin is silently deactivated (such as during an update),
             * this hook does not fire.
             *
             * @since 2.9.0
             *
             * @param string $plugin               Plugin path to main plugin file with plugin data.
             * @param bool   $network_deactivating Whether the plugin is deactivated for all sites in the network
             *                                     or just the current site. Multisite only. Default is false.
             */
            do_action('deactivate_plugin', $plugin, $network_deactivating);
        }
        if (false !== $network_wide) {
            if (is_plugin_active_for_network($plugin)) {
                $do_network = true;
                unset($network_current[$plugin]);
            } elseif ($network_wide) {
                continue;
            }
        }
        if (true !== $network_wide) {
            $key = array_search($plugin, $current);
            if (false !== $key) {
                $do_blog = true;
                unset($current[$key]);
            }
        }
        if (!$silent) {
            /**
             * Fires as a specific plugin is being deactivated.
             *
             * This hook is the "deactivation" hook used internally by
             * {@see register_deactivation_hook()}. The dynamic portion of the
             * hook name, `$plugin`, refers to the plugin basename.
             *
             * If a plugin is silently deactivated (such as during an update),
             * this hook does not fire.
             *
             * @since 2.0.0
             *
             * @param bool $network_deactivating Whether the plugin is deactivated for all sites in the network
             *                                   or just the current site. Multisite only. Default is false.
             */
            do_action('deactivate_' . $plugin, $network_deactivating);
            /**
             * Fires after a plugin is deactivated.
             *
             * If a plugin is silently deactivated (such as during an update),
             * this hook does not fire.
             *
             * @since 2.9.0
             *
             * @param string $plugin               Plugin basename.
             * @param bool   $network_deactivating Whether the plugin is deactivated for all sites in the network
             *                                     or just the current site. Multisite only. Default false.
             */
            do_action('deactivated_plugin', $plugin, $network_deactivating);
        }
    }
    if ($do_blog) {
        update_option('active_plugins', $current);
    }
    if ($do_network) {
        update_network_option('active_sitewide_plugins', $network_current);
    }
}
Ejemplo n.º 14
0
/**
 * Executes network-level upgrade routines.
 *
 * @since 3.0.0
 *
 * @global int   $wp_current_db_version
 * @global wpdb  $wpdb
 */
function upgrade_network()
{
    global $wp_current_db_version, $wpdb;
    // Always.
    if (is_main_network()) {
        /*
         * Deletes all expired transients. The multi-table delete syntax is used
         * to delete the transient record from table a, and the corresponding
         * transient_timeout record from table b.
         */
        $time = time();
        $sql = "DELETE a, b FROM {$wpdb->sitemeta} a, {$wpdb->sitemeta} b\n\t\t\tWHERE a.meta_key LIKE %s\n\t\t\tAND a.meta_key NOT LIKE %s\n\t\t\tAND b.meta_key = CONCAT( '_site_transient_timeout_', SUBSTRING( a.meta_key, 17 ) )\n\t\t\tAND b.meta_value < %d";
        $wpdb->query($wpdb->prepare($sql, $wpdb->esc_like('_site_transient_') . '%', $wpdb->esc_like('_site_transient_timeout_') . '%', $time));
    }
    // 2.8.
    if ($wp_current_db_version < 11549) {
        $wpmu_sitewide_plugins = get_network_option('wpmu_sitewide_plugins');
        $active_sitewide_plugins = get_network_option('active_sitewide_plugins');
        if ($wpmu_sitewide_plugins) {
            if (!$active_sitewide_plugins) {
                $sitewide_plugins = (array) $wpmu_sitewide_plugins;
            } else {
                $sitewide_plugins = array_merge((array) $active_sitewide_plugins, (array) $wpmu_sitewide_plugins);
            }
            update_network_option('active_sitewide_plugins', $sitewide_plugins);
        }
        delete_network_option('wpmu_sitewide_plugins');
        delete_network_option('deactivated_sitewide_plugins');
        $start = 0;
        while ($rows = $wpdb->get_results("SELECT meta_key, meta_value FROM {$wpdb->sitemeta} ORDER BY meta_id LIMIT {$start}, 20")) {
            foreach ($rows as $row) {
                $value = $row->meta_value;
                if (!@unserialize($value)) {
                    $value = stripslashes($value);
                }
                if ($value !== $row->meta_value) {
                    update_network_option($row->meta_key, $value);
                }
            }
            $start += 20;
        }
    }
    // 3.0
    if ($wp_current_db_version < 13576) {
        update_network_option('global_terms_enabled', '1');
    }
    // 3.3
    if ($wp_current_db_version < 19390) {
        update_network_option('initial_db_version', $wp_current_db_version);
    }
    if ($wp_current_db_version < 19470) {
        if (false === get_network_option('active_sitewide_plugins')) {
            update_network_option('active_sitewide_plugins', array());
        }
    }
    // 3.4
    if ($wp_current_db_version < 20148) {
        // 'allowedthemes' keys things by stylesheet. 'allowed_themes' keyed things by name.
        $allowedthemes = get_network_option('allowedthemes');
        $allowed_themes = get_network_option('allowed_themes');
        if (false === $allowedthemes && is_array($allowed_themes) && $allowed_themes) {
            $converted = array();
            $themes = wp_get_themes();
            foreach ($themes as $stylesheet => $theme_data) {
                if (isset($allowed_themes[$theme_data->get('Name')])) {
                    $converted[$stylesheet] = true;
                }
            }
            update_network_option('allowedthemes', $converted);
            delete_network_option('allowed_themes');
        }
    }
    // 3.5
    if ($wp_current_db_version < 21823) {
        update_network_option('ms_files_rewriting', '1');
    }
    // 3.5.2
    if ($wp_current_db_version < 24448) {
        $illegal_names = get_network_option('illegal_names');
        if (is_array($illegal_names) && count($illegal_names) === 1) {
            $illegal_name = reset($illegal_names);
            $illegal_names = explode(' ', $illegal_name);
            update_network_option('illegal_names', $illegal_names);
        }
    }
    // 4.2
    if ($wp_current_db_version < 31351 && $wpdb->charset === 'utf8mb4') {
        if (wp_should_upgrade_global_tables()) {
            $wpdb->query("ALTER TABLE {$wpdb->usermeta} DROP INDEX meta_key, ADD INDEX meta_key(meta_key(191))");
            $wpdb->query("ALTER TABLE {$wpdb->site} DROP INDEX domain, ADD INDEX domain(domain(140),path(51))");
            $wpdb->query("ALTER TABLE {$wpdb->sitemeta} DROP INDEX meta_key, ADD INDEX meta_key(meta_key(191))");
            $wpdb->query("ALTER TABLE {$wpdb->signups} DROP INDEX domain_path, ADD INDEX domain_path(domain(140),path(51))");
            $tables = $wpdb->tables('global');
            // sitecategories may not exist.
            if (!$wpdb->get_var("SHOW TABLES LIKE '{$tables['sitecategories']}'")) {
                unset($tables['sitecategories']);
            }
            foreach ($tables as $table) {
                maybe_convert_table_to_utf8mb4($table);
            }
        }
    }
    // 4.3
    if ($wp_current_db_version < 33055 && 'utf8mb4' === $wpdb->charset) {
        if (wp_should_upgrade_global_tables()) {
            $upgrade = false;
            $indexes = $wpdb->get_results("SHOW INDEXES FROM {$wpdb->signups}");
            foreach ($indexes as $index) {
                if ('domain_path' == $index->Key_name && 'domain' == $index->Column_name && 140 != $index->Sub_part) {
                    $upgrade = true;
                    break;
                }
            }
            if ($upgrade) {
                $wpdb->query("ALTER TABLE {$wpdb->signups} DROP INDEX domain_path, ADD INDEX domain_path(domain(140),path(51))");
            }
            $tables = $wpdb->tables('global');
            // sitecategories may not exist.
            if (!$wpdb->get_var("SHOW TABLES LIKE '{$tables['sitecategories']}'")) {
                unset($tables['sitecategories']);
            }
            foreach ($tables as $table) {
                maybe_convert_table_to_utf8mb4($table);
            }
        }
    }
}
Ejemplo n.º 15
0
/**
 * Update the network-wide user count.
 *
 * @since 3.7.0
 *
 * @global wpdb $wpdb
 */
function wp_update_network_user_counts()
{
    global $wpdb;
    $count = $wpdb->get_var("SELECT COUNT(ID) as c FROM {$wpdb->users} WHERE spam = '0' AND deleted = '0'");
    update_network_option('user_count', $count);
}
Ejemplo n.º 16
0
     check_admin_referer('edit-plugin_' . $file);
     $newcontent = wp_unslash($_POST['newcontent']);
     if (is_writeable($real_file)) {
         $f = fopen($real_file, 'w+');
         fwrite($f, $newcontent);
         fclose($f);
         $network_wide = is_plugin_active_for_network($file);
         // Deactivate so we can test it.
         if (is_plugin_active($file) || isset($_POST['phperror'])) {
             if (is_plugin_active($file)) {
                 deactivate_plugins($file, true);
             }
             if (!is_network_admin()) {
                 update_option('recently_activated', array($file => time()) + (array) get_option('recently_activated'));
             } else {
                 update_network_option('recently_activated', array($file => time()) + (array) get_network_option('recently_activated'));
             }
             wp_redirect(add_query_arg('_wpnonce', wp_create_nonce('edit-plugin-test_' . $file), "plugin-editor.php?file={$file}&liveupdate=1&scrollto={$scrollto}&networkwide=" . $network_wide));
             exit;
         }
         wp_redirect(self_admin_url("plugin-editor.php?file={$file}&a=te&scrollto={$scrollto}"));
     } else {
         wp_redirect(self_admin_url("plugin-editor.php?file={$file}&scrollto={$scrollto}"));
     }
     exit;
 default:
     if (isset($_GET['liveupdate'])) {
         check_admin_referer('edit-plugin-test_' . $file);
         $error = validate_plugin($file);
         if (is_wp_error($error)) {
             wp_die($error);
Ejemplo n.º 17
0
                require_once ABSPATH . 'wp-admin/admin-footer.php';
                exit;
            } else {
                $plugins_to_delete = count($plugins);
            }
            // endif verify-delete
            $delete_result = delete_plugins($plugins);
            set_transient('plugins_delete_result_' . $user_ID, $delete_result);
            //Store the result in a cache rather than a URL param due to object type & length
            wp_redirect(self_admin_url("plugins.php?deleted={$plugins_to_delete}&plugin_status={$status}&paged={$page}&s={$s}"));
            exit;
        case 'clear-recent-list':
            if (!is_network_admin()) {
                update_option('recently_activated', array());
            } else {
                update_network_option('recently_activated', array());
            }
            break;
    }
}
$wp_list_table->prepare_items();
wp_enqueue_script('plugin-install');
add_thickbox();
add_screen_option('per_page', array('default' => 999));
get_current_screen()->add_help_tab(array('id' => 'overview', 'title' => __('Overview'), 'content' => '<p>' . __('Plugins extend and expand the functionality of WordPress. Once a plugin is installed, you may activate it or deactivate it here.') . '</p>' . '<p>' . sprintf(__('You can find additional plugins for your site by using the <a href="%1$s">Plugin Browser/Installer</a> functionality or by browsing the <a href="%2$s" target="_blank">WordPress Plugin Directory</a> directly and installing new plugins manually. To manually install a plugin you generally just need to upload the plugin file into your %3$s directory. Once a plugin has been installed, you can activate it here.'), 'plugin-install.php', 'https://wordpress.org/plugins/', '<code>/wp-content/plugins</code>') . '</p>'));
get_current_screen()->add_help_tab(array('id' => 'compatibility-problems', 'title' => __('Troubleshooting'), 'content' => '<p>' . __('Most of the time, plugins play nicely with the core of WordPress and with other plugins. Sometimes, though, a plugin&#8217;s code will get in the way of another plugin, causing compatibility issues. If your site starts doing strange things, this may be the problem. Try deactivating all your plugins and re-activating them in various combinations until you isolate which one(s) caused the issue.') . '</p>' . '<p>' . sprintf(__('If something goes wrong with a plugin and you can&#8217;t use WordPress, delete or rename that file in the %s directory and it will be automatically deactivated.'), '<code>' . WP_PLUGIN_DIR . '</code>') . '</p>'));
get_current_screen()->set_help_sidebar('<p><strong>' . __('For more information:') . '</strong></p>' . '<p>' . __('<a href="https://codex.wordpress.org/Managing_Plugins#Plugin_Management" target="_blank">Documentation on Managing Plugins</a>') . '</p>' . '<p>' . __('<a href="https://wordpress.org/support/" target="_blank">Support Forums</a>') . '</p>');
$title = __('Plugins');
$parent_file = 'plugins.php';
require_once ABSPATH . 'wp-admin/admin-header.php';
$invalid = validate_active_plugins();
Ejemplo n.º 18
0
 /**
  * Constructor.
  *
  * @since 160524 Initial release.
  *
  * @param array            $instance_base Instance base.
  * @param array            $instance      Instance args.
  * @param Classes\App|null $Parent        Parent app (optional).
  */
 public function __construct(array $instance_base = [], array $instance = [], Classes\App $Parent = null)
 {
     # WordPress common properties.
     $this->Wp = $Parent ? $Parent->Wp : new Wp();
     # Define a few reflection-based properties.
     $this->Reflection = new \ReflectionClass($this);
     $this->class = $this->Reflection->getName();
     $this->namespace = $this->Reflection->getNamespaceName();
     $this->file = $this->Reflection->getFileName();
     $this->base_dir = dirname($this->file, 4);
     $this->base_dir_basename = basename($this->base_dir);
     $this->is_core = $this->class === self::class;
     # Establish specs & brand for parent constructor.
     $default_specs = ['§is_pro' => null, '§has_pro' => null, '§in_wp' => null, '§is_network_wide' => false, '§type' => '', '§file' => ''];
     $brand_defaults = ['©acronym' => '', '©name' => '', '©slug' => '', '©var' => '', '©short_slug' => '', '©short_var' => '', '§product_name' => '', '§product_slug' => '', '©text_domain' => '', '§domain' => '', '§domain_path' => '', '§domain_pro_path' => '', '§domain_short_var' => '', '§api_domain' => '', '§api_domain_path' => '', '§api_domain_short_var' => '', '§cdn_domain' => '', '§cdn_domain_path' => '', '§cdn_domain_short_var' => '', '§stats_domain' => '', '§stats_domain_path' => '', '§stats_domain_short_var' => ''];
     if ($this->is_core) {
         $Parent = null;
         // Core.
         $specs = array_merge($default_specs, ['§is_pro' => false, '§has_pro' => false, '§in_wp' => false, '§is_network_wide' => false, '§type' => 'plugin', '§file' => $this->base_dir . '/plugin.php'], $instance_base['§specs'] ?? [], $instance['§specs'] ?? []);
         $specs['§is_network_wide'] = $specs['§is_network_wide'] && $this->Wp->is_multisite;
         $brand = array_merge($brand_defaults, ['©acronym' => 'WPS Core', '©name' => 'WP Sharks Core', '©slug' => 'wp-sharks-core', '©var' => 'wp_sharks_core', '©short_slug' => 'wps-core', '©short_var' => 'wps_core', '§product_name' => 'WP Sharks Core', '§product_slug' => 'wp-sharks-core', '©text_domain' => 'wp-sharks-core', '§domain' => 'wpsharks.com', '§domain_path' => '/product/wp-sharks-core', '§domain_pro_path' => '', '§domain_short_var' => 'wps', '§api_domain' => 'api.wpsharks.com', '§api_domain_path' => '/', '§api_domain_short_var' => 'wps', '§cdn_domain' => 'cdn.wpsharks.com', '§cdn_domain_path' => '/', '§cdn_domain_short_var' => 'wps', '§stats_domain' => 'stats.wpsharks.io', '§stats_domain_path' => '/', '§stats_domain_short_var' => 'wps'], $instance_base['©brand'] ?? [], $instance['©brand'] ?? []);
     } else {
         if (!isset($GLOBALS[self::class])) {
             throw new Exception('Missing core instance.');
         }
         $Parent = $Parent ?? $GLOBALS[self::class];
         $specs = array_merge($default_specs, $instance_base['§specs'] ?? [], $instance['§specs'] ?? []);
         $specs['§is_pro'] = $specs['§is_pro'] ?? mb_stripos($this->namespace, '\\Pro\\') !== false;
         $specs['§has_pro'] = $specs['§is_pro'] ?: true;
         // Assume this is true.
         $specs['§in_wp'] = $specs['§is_pro'] ? false : $specs['§in_wp'] ?? false;
         $specs['§is_network_wide'] = $specs['§is_network_wide'] && $this->Wp->is_multisite;
         if (!$specs['§type'] || !$specs['§file']) {
             if (is_file($this->base_dir . '/plugin.php')) {
                 $specs['§type'] = 'plugin';
                 $specs['§file'] = $this->base_dir . '/plugin.php';
             } elseif (is_file($this->base_dir . '/style.css')) {
                 $specs['§type'] = 'theme';
                 $specs['§file'] = $this->base_dir . '/style.css';
             } elseif (is_file($this->base_dir . '/src/wp-content/mu-plugins/site.php')) {
                 $specs['§type'] = 'mu-plugin';
                 $specs['§file'] = $this->base_dir . '/src/wp-content/mu-plugins/site.php';
             } else {
                 // Hard failure in this unexpected case.
                 throw new Exception('Unable to determine `§type`/`§file`.');
             }
             // The app will need to give its §type/§file explicitly.
         }
         $brand = array_merge($brand_defaults, $instance_base['©brand'] ?? [], $instance['©brand'] ?? []);
         if (!$brand['©slug']) {
             // This is the basis for others.
             $brand['©slug'] = $Parent->c::nameToSlug($this->base_dir_basename);
             $brand['©slug'] = preg_replace('/[_\\-]+(?:lite|pro)/ui', '', $brand['©slug']);
         }
         $brand['©var'] = $brand['©var'] ?: $Parent->c::slugToVar($brand['©slug']);
         $brand['©name'] = $brand['©name'] ?: $Parent->c::slugToName($brand['©slug']);
         $brand['©acronym'] = $brand['©acronym'] ?: $Parent->c::nameToAcronym($brand['©name']);
         $brand['©short_slug'] = $brand['©short_slug'] ?: (strlen($brand['©slug']) <= 10 ? $brand['©slug'] : 's' . substr(md5($brand['©slug']), 0, 9));
         $brand['©short_var'] = $brand['©short_var'] ?: $Parent->c::slugToVar($brand['©short_slug']);
         $brand['§product_name'] = $brand['§product_name'] ?: $brand['©name'] . ($specs['§is_pro'] ? ' Pro' : '');
         $brand['§product_slug'] = $brand['§product_slug'] ?: $this->base_dir_basename;
         $brand['©text_domain'] = $brand['©text_domain'] ?: $brand['©slug'];
         if (!$brand['§domain'] || !$brand['§domain_path'] || !$brand['§domain_short_var']) {
             $brand['§domain'] = $Parent->Config->©brand['§domain'];
             $brand['§domain_path'] = '/product/' . $brand['§product_slug'];
             $brand['§domain_pro_path'] = $specs['§is_pro'] ? $brand['§domain_path'] : ($specs['§has_pro'] ? '/product/' . $brand['§product_slug'] . '-pro' : '');
             $brand['§domain_short_var'] = $Parent->Config->©brand['§domain_short_var'];
         }
         if ($this->Wp->debug) {
             if (preg_match('/(?:LITE|PRO)$/ui', $brand['©acronym'])) {
                 throw new Exception('Please remove `LITE|PRO` suffix from `©acronym`.');
             } elseif (preg_match('/\\s+(?:Lite|Pro)$/ui', $brand['©name'])) {
                 throw new Exception('Please remove `Lite|Pro` suffix from `©name`.');
                 //
             } elseif (!$Parent->c::isSlug($brand['©slug'])) {
                 throw new Exception('Please fix; `©slug` has invalid chars.');
             } elseif (preg_match('/[_\\-]+(?:lite|pro)$/ui', $brand['©slug'])) {
                 throw new Exception('Please remove `lite|pro` suffix from `©slug`.');
                 //
             } elseif (!$Parent->c::isVar($brand['©var'])) {
                 throw new Exception('Please fix; `©var` has invalid chars.');
             } elseif (preg_match('/[_\\-]+(?:lite|pro)$/ui', $brand['©var'])) {
                 throw new Exception('Please remove `lite|pro` suffix from `©var`.');
                 //
             } elseif (strlen($brand['©short_slug']) > 10) {
                 throw new Exception('Please fix; `©short_slug` is > 10 bytes.');
             } elseif (!$Parent->c::isSlug($brand['©short_slug'])) {
                 throw new Exception('Please fix; `©short_slug` has invalid chars.');
             } elseif (preg_match('/[_\\-]+(?:lite|pro)$/ui', $brand['©short_slug'])) {
                 throw new Exception('Please remove `lite|pro` suffix from `©short_slug`.');
                 //
             } elseif (strlen($brand['©short_var']) > 10) {
                 throw new Exception('Please fix; `©short_var` is > 10 bytes.');
             } elseif (!$Parent->c::isVar($brand['©short_var'])) {
                 throw new Exception('Please fix; `©short_var` has invalid chars.');
             } elseif (preg_match('/[_\\-]+(?:lite|pro)$/ui', $brand['©short_var'])) {
                 throw new Exception('Please remove `lite|pro` suffix from `©short_var`.');
                 //
             } elseif (!$Parent->c::isSlug($brand['©text_domain'])) {
                 throw new Exception('Please fix; `©text_domain` has invalid chars.');
                 //
             } elseif (!$Parent->c::isSlug($brand['§product_slug'])) {
                 throw new Exception('Please fix; `§product_slug` has invalid chars.');
             }
         }
     }
     # Collect additional WordPress config values.
     if (!($wp_app_salt_key = hash('sha256', $this->Wp->salt . $brand['©slug']))) {
         throw new Exception('Failed to generate a unique salt/key.');
     }
     if ($specs['§type'] === 'plugin') {
         if (!($wp_app_url_parts = parse_url(plugin_dir_url($specs['§file'])))) {
             throw new Exception('Failed to parse plugin dir URL parts.');
         }
     } elseif ($specs['§type'] === 'theme') {
         if (!($wp_app_url_parts = $this->Wp->template_directory_url_parts)) {
             throw new Exception('Failed to parse theme dir URL parts.');
         }
     } elseif ($specs['§type'] === 'mu-plugin') {
         if (!($wp_app_url_parts = $this->Wp->site_url_parts)) {
             throw new Exception('Failed to parse app URL parts.');
         }
     } else {
         // Unexpected application `§type` in this case.
         throw new Exception('Failed to parse URL for unexpected `§type`.');
     }
     $wp_app_url_base_path = rtrim($wp_app_url_parts['path'] ?? '', '/');
     $wp_app_url_base_path .= in_array($specs['§type'], ['theme', 'plugin'], true) ? '/src' : '';
     $wp_app_url_base_path .= '/';
     // Always; i.e., this is a directory location.
     # Build the core/default instance base.
     $default_instance_base = ['©use_server_cfgs' => false, '©debug' => ['©enable' => $this->Wp->debug, '©edge' => $this->Wp->debug_edge, '©log' => $this->Wp->debug_log, '©log_callback' => false, '©er_enable' => false, '©er_display' => false, '©er_assertions' => false], '©handle_throwables' => false, '©di' => ['©default_rule' => ['new_instances' => [Classes\SCore\Base\Widget::class, Classes\SCore\MenuPageForm::class, Classes\SCore\PostMetaBoxForm::class, Classes\SCore\WidgetForm::class]]], '©sub_namespace_map' => ['SCore' => ['©utils' => '§', '©facades' => 's']], '§specs' => $default_specs, '©brand' => $brand_defaults, '©urls' => ['©hosts' => ['©app' => $this->Wp->site_url_host, '©cdn' => 'cdn.' . $this->Wp->site_url_root_host, '©roots' => ['©app' => $this->Wp->site_url_root_host, '©cdn' => $this->Wp->site_url_root_host]], '©base_paths' => ['©app' => $wp_app_url_base_path, '©cdn' => '/'], '©cdn_filter_enable' => false, '©default_scheme' => $this->Wp->site_default_scheme, '©sig_key' => $wp_app_salt_key], '§setup' => ['§hook' => 'after_setup_theme', '§hook_priority' => 0, '§enable_hooks' => true, '§complete' => false], '©fs_paths' => ['©logs_dir' => $this->Wp->tmp_dir . '/.' . $this::CORE_CONTAINER_SLUG . '/' . $brand['©slug'] . '/logs', '©cache_dir' => $this->Wp->tmp_dir . '/.' . $this::CORE_CONTAINER_SLUG . '/' . $brand['©slug'] . '/cache', '§templates_theme_base_dir' => $this::CORE_CONTAINER_SLUG . '/' . $brand['©slug'], '©templates_dir' => $this->base_dir . '/src/includes/templates', '©routes_dir' => '', '©errors_dir' => '', '§mysql' => ['§tables_dir' => $this->base_dir . '/src/includes/mysql/tables', '§indexes_dir' => $this->base_dir . '/src/includes/mysql/indexes', '§triggers_dir' => $this->base_dir . '/src/includes/mysql/triggers']], '©encryption' => ['©key' => $wp_app_salt_key], '©cookies' => ['©encryption_key' => $wp_app_salt_key], '©hash_ids' => ['©hash_key' => $wp_app_salt_key], '©passwords' => ['©hash_key' => $wp_app_salt_key], '§conflicts' => ['§plugins' => [], '§themes' => [], '§deactivatable_plugins' => []], '§dependencies' => ['§plugins' => [], '§themes' => [], '§others' => []], '§caps' => ['§manage' => $specs['§is_network_wide'] && $this->Wp->is_multisite ? 'manage_network_plugins' : 'activate_plugins'], '§pro_option_keys' => [], '§default_options' => ['§for_version' => $this::VERSION, '§for_product_slug' => $brand['§product_slug'], '§license_key' => ''], '§options' => [], '§force_install' => false, '§uninstall' => false];
     # Automatically add lite/pro conflict to the array.
     if ($specs['§type'] === 'plugin') {
         // Only for plugins. Only one theme can be active at a time.
         $_lp_conflicting_name = $brand['©name'] . ($specs['§is_pro'] ? ' Lite' : ' Pro');
         $_lp_conflicting_slug = $brand['©slug'] . ($specs['§is_pro'] ? '' : '-pro');
         $default_instance_base['§conflicts']['§plugins'][$_lp_conflicting_slug] = $_lp_conflicting_name;
         $default_instance_base['§conflicts']['§deactivatable_plugins'][$_lp_conflicting_slug] = $_lp_conflicting_name;
     }
     # Merge `$default_instance_base` w/ `$instance_base` param.
     $instance_base = $this->mergeConfig($default_instance_base, $instance_base);
     $instance_base['§specs'] =& $specs;
     // Already established (in full) above.
     $instance_base['©brand'] =& $brand;
     // Already established (in full) above.
     # Give plugins/extensions a chance to filter `$instance`.
     $instance = apply_filters($brand['©var'] . '_instance', $instance, $instance_base);
     unset($instance['§specs'], $instance['©brand']);
     // Already established (in full) above.
     # Call parent app-constructor (i.e., websharks/core).
     parent::__construct($instance_base, $instance, $Parent);
     /* Post-construct sub-routines are run now -------------------------------------------------------------- */
     # Merge site owner options (highest precedence).
     if ($this->Config->§specs['§is_network_wide'] && $this->Wp->is_multisite) {
         if (!is_array($site_owner_options = get_network_option(null, $this->Config->©brand['©var'] . '_options'))) {
             update_network_option(null, $this->Config->©brand['©var'] . '_options', $site_owner_options = []);
         }
     } elseif (!is_array($site_owner_options = get_option($this->Config->©brand['©var'] . '_options'))) {
         update_option($this->Config->©brand['©var'] . '_options', $site_owner_options = []);
     }
     $this->Config->§options = $this->s::mergeOptions($this->Config->§default_options, $this->Config->§options);
     $this->Config->§options = $this->s::mergeOptions($this->Config->§options, $site_owner_options);
     $this->Config->§options = $this->s::applyFilters('options', $this->Config->§options);
     # Handle option transitions from one variation of the software to another; e.g., pro upgrade.
     if ($this->Config->§options['§for_product_slug'] !== $this->Config->©brand['§product_slug']) {
         $this->Config->§options['§for_product_slug'] = $this->Config->©brand['§product_slug'];
         $this->Config->§options['§license_key'] = '';
         // No longer applicable.
         if ($this->Config->§specs['§is_network_wide'] && $this->Wp->is_multisite) {
             update_network_option(null, $this->Config->©brand['©var'] . '_options', $this->Config->§options);
         } else {
             update_option($this->Config->©brand['©var'] . '_options', $this->Config->§options);
         }
         $this->Config->§force_install = !$this->Config->§uninstall;
         // Force reinstall (if not uninstalling).
     }
     # Sanity check; must be on (or after) `plugins_loaded` hook.
     # If uninstalling, must be on (or after) `init` hook.
     if (!did_action('plugins_loaded')) {
         throw new Exception('`plugins_loaded` action not done yet.');
     } elseif ($this->Config->§uninstall && !did_action('init')) {
         throw new Exception('`init` action not done yet.');
     }
     # Check for any known conflicts.
     if ($this->s::conflictsExist()) {
         return;
         // Stop here.
     }
     # Check for any unsatisfied dependencies.
     if ($this->s::dependenciesUnsatisfied()) {
         return;
         // Stop here.
     }
     # Add app instance to collection.
     if ($this->Parent && $this->Parent->is_core && !$this->Config->§uninstall) {
         // NOTE: If uninstalling, don't expose it to the parent/core.
         $this->Parent->s::addApp($this);
     }
     # Remaining routines are driven by setup hook.
     if ($this->Config->§uninstall || did_action($this->Config->§setup['§hook'])) {
         $this->onSetup();
         // Run setup immediately.
     } else {
         // Delay setup routines; i.e., attach to hook.
         add_action($this->Config->§setup['§hook'], [$this, 'onSetup'], $this->Config->§setup['§hook_priority']);
     }
 }
Ejemplo n.º 19
0
 /**
  * Get salt to add to hashes.
  *
  * Salts are created using secret keys. Secret keys are located in two places:
  * in the database and in the wp-config.php file. The secret key in the database
  * is randomly generated and will be appended to the secret keys in wp-config.php.
  *
  * The secret keys in wp-config.php should be updated to strong, random keys to maximize
  * security. Below is an example of how the secret key constants are defined.
  * Do not paste this example directly into wp-config.php. Instead, have a
  * {@link https://api.wordpress.org/secret-key/1.1/salt/ secret key created} just
  * for you.
  *
  *     define('AUTH_KEY',         ' Xakm<o xQy rw4EMsLKM-?!T+,PFF})H4lzcW57AF0U@N@< >M%G4Yt>f`z]MON');
  *     define('SECURE_AUTH_KEY',  'LzJ}op]mr|6+![P}Ak:uNdJCJZd>(Hx.-Mh#Tz)pCIU#uGEnfFz|f ;;eU%/U^O~');
  *     define('LOGGED_IN_KEY',    '|i|Ux`9<p-h$aFf(qnT:sDO:D1P^wZ$$/Ra@miTJi9G;ddp_<q}6H1)o|a +&JCM');
  *     define('NONCE_KEY',        '%:R{[P|,s.KuMltH5}cI;/k<Gx~j!f0I)m_sIyu+&NJZ)-iO>z7X>QYR0Z_XnZ@|');
  *     define('AUTH_SALT',        'eZyT)-Naw]F8CwA*VaW#q*|.)g@o}||wf~@C-YSt}(dh_r6EbI#A,y|nU2{B#JBW');
  *     define('SECURE_AUTH_SALT', '!=oLUTXh,QW=H `}`L|9/^4-3 STz},T(w}W<I`.JjPi)<Bmf1v,HpGe}T1:Xt7n');
  *     define('LOGGED_IN_SALT',   '+XSqHc;@Q*K_b|Z?NC[3H!!EONbh.n<+=uKR:>*c(u`g~EJBf#8u#R{mUEZrozmm');
  *     define('NONCE_SALT',       'h`GXHhD>SLWVfg1(1(N{;.V!MoE(SfbA_ksP@&`+AycHcAV$+?@3q+rxV{%^VyKT');
  *
  * Salting passwords helps against tools which has stored hashed values of
  * common dictionary strings. The added values makes it harder to crack.
  *
  * @since 2.5.0
  *
  * @link https://api.wordpress.org/secret-key/1.1/salt/ Create secrets for wp-config.php
  *
  * @staticvar array $cached_salts
  * @staticvar array $duplicated_keys
  *
  * @param string $scheme Authentication scheme (auth, secure_auth, logged_in, nonce)
  * @return string Salt value
  */
 function wp_salt($scheme = 'auth')
 {
     static $cached_salts = array();
     if (isset($cached_salts[$scheme])) {
         /**
          * Filter the WordPress salt.
          *
          * @since 2.5.0
          *
          * @param string $cached_salt Cached salt for the given scheme.
          * @param string $scheme      Authentication scheme. Values include 'auth',
          *                            'secure_auth', 'logged_in', and 'nonce'.
          */
         return apply_filters('salt', $cached_salts[$scheme], $scheme);
     }
     static $duplicated_keys;
     if (null === $duplicated_keys) {
         $duplicated_keys = array('put your unique phrase here' => true);
         foreach (array('AUTH', 'SECURE_AUTH', 'LOGGED_IN', 'NONCE', 'SECRET') as $first) {
             foreach (array('KEY', 'SALT') as $second) {
                 if (!defined("{$first}_{$second}")) {
                     continue;
                 }
                 $value = constant("{$first}_{$second}");
                 $duplicated_keys[$value] = isset($duplicated_keys[$value]);
             }
         }
     }
     $values = array('key' => '', 'salt' => '');
     if (defined('SECRET_KEY') && SECRET_KEY && empty($duplicated_keys[SECRET_KEY])) {
         $values['key'] = SECRET_KEY;
     }
     if ('auth' == $scheme && defined('SECRET_SALT') && SECRET_SALT && empty($duplicated_keys[SECRET_SALT])) {
         $values['salt'] = SECRET_SALT;
     }
     if (in_array($scheme, array('auth', 'secure_auth', 'logged_in', 'nonce'))) {
         foreach (array('key', 'salt') as $type) {
             $const = strtoupper("{$scheme}_{$type}");
             if (defined($const) && constant($const) && empty($duplicated_keys[constant($const)])) {
                 $values[$type] = constant($const);
             } elseif (!$values[$type]) {
                 $values[$type] = get_network_option("{$scheme}_{$type}");
                 if (!$values[$type]) {
                     $values[$type] = wp_generate_password(64, true, true);
                     update_network_option("{$scheme}_{$type}", $values[$type]);
                 }
             }
         }
     } else {
         if (!$values['key']) {
             $values['key'] = get_network_option('secret_key');
             if (!$values['key']) {
                 $values['key'] = wp_generate_password(64, true, true);
                 update_network_option('secret_key', $values['key']);
             }
         }
         $values['salt'] = hash_hmac('md5', $scheme, $values['key']);
     }
     $cached_salts[$scheme] = $values['key'] . $values['salt'];
     /** This filter is documented in wp-includes/pluggable.php */
     return apply_filters('salt', $cached_salts[$scheme], $scheme);
 }
/**
 * Initialize LaunchKey WordPress Plugin
 *
 * This function will perform the entire initialization for the plugin.  The initialization is encapsulated into
 * a funciton to protect against global variable collision.
 *
 * @since 1.0.0
 * Enclose plug-in initialization to protect against global variable corruption
 */
function launchkey_plugin_init()
{
    global $wpdb;
    /**
     * Register activation hooks for the plugin
     * @since 1.1.0
     */
    register_activation_hook(__FILE__, 'launchkey_create_tables');
    /**
     * Remove the scheduled cron
     * @since 1.1.0
     */
    register_deactivation_hook(__FILE__, 'launchkey_cron_remove');
    /**
     * @since 1.1.0
     * Add the cron hook and schedule if not scheduled
     */
    add_action('launchkey_cron_hook', 'launchkey_cron');
    if (!wp_next_scheduled('launchkey_cron_hook')) {
        wp_schedule_event(time(), 'hourly', 'launchkey_cron_hook');
    }
    /**
     * Language domain for the plugin
     */
    $language_domain = 'launchkey';
    /**
     * Register plugin text domain with language files
     *
     * @see load_plugin_textdomain
     * @link https://developer.wordpress.org/reference/hooks/plugins_loaded/
     */
    add_action('plugins_loaded', function () use($language_domain) {
        load_plugin_textdomain($language_domain, false, plugin_basename(__FILE__) . '/languages/');
    });
    /**
     * Create an AES encryption class for encryption/decryption of the secret options
     * @link https://docs.launchkey.com/glossary.html#term-aes
     */
    $crypt_aes = new \phpseclib\Crypt\AES();
    /**
     * Use an MD5 hash of the auth key as the crypto key.  The crypto key is used as it would normally affect all auth
     * procedures as it is used as a salt for passwords.  An md5 hash is used as it will be a constant value based on
     * the AUTH_KEY but guaranteed to be exactly thirty-two (32) characters as is needed by AES encryption.
     */
    $crypt_aes->setKey(md5(AUTH_KEY));
    // Create an options handler that will encrypt and decrypt the plugin options as necessary
    $options_handler = new LaunchKey_WP_Options($crypt_aes);
    /**
     * The pre_update_option_launchkey filter will process the "launchkey" option directly
     * before updating the data in the database.
     *
     * @since 1.0.0
     * @link https://developer.wordpress.org/reference/hooks/pre_update_option_option/
     * @see LaunchKey_WP_Options::pre_update_option_filter
     */
    add_filter('pre_update_option_launchkey', array($options_handler, 'pre_update_option_filter'));
    add_filter('pre_update_site_option_launchkey', array($options_handler, 'pre_update_option_filter'));
    /**
     * The pre_update_option_filter filter will process the "launchkey" option directly
     * before adding the data in the database.
     *
     * @since 1.0.0
     * @link https://developer.wordpress.org/reference/hooks/pre_update_option_option/
     * @see LaunchKey_WP_Options::pre_update_option_filter
     */
    add_filter('pre_add_option_launchkey', array($options_handler, 'pre_update_option_filter'));
    add_filter('pre_add_site_option_launchkey', array($options_handler, 'pre_update_option_filter'));
    /**
     * The option_launchkey filter will process the "launchkey" option directly
     * after retrieving the data from the database.
     *
     * @since 1.0.0
     * @link https://developer.wordpress.org/reference/hooks/option_option/
     * @see LaunchKey_WP_Options::post_get_option_filter
     */
    add_filter('option_launchkey', array($options_handler, 'post_get_option_filter'));
    add_filter('site_option_launchkey', array($options_handler, 'post_get_option_filter'));
    $is_multi_site = is_multisite() && is_plugin_active_for_network(plugin_basename(__FILE__));
    $options = $is_multi_site ? get_site_option(LaunchKey_WP_Admin::OPTION_KEY) : get_option(LaunchKey_WP_Admin::OPTION_KEY);
    /**
     * Handle upgrades if in the admin and not the latest version
     */
    if (is_admin() && launchkey_is_activated() && $options && $options[LaunchKey_WP_Options::OPTION_VERSION] < 1.1) {
        launchkey_create_tables();
    }
    /**
     * If the pre-1.0.0 option style was already used, create a 1.0.0 option and remove the old options.  They are
     * removed as the secret_key was stored plain text in the database.
     *
     * @since 1.0.0
     */
    if (get_option('launchkey_app_key') || get_option('launchkey_secret_key')) {
        $launchkey_options[LaunchKey_WP_Options::OPTION_ROCKET_KEY] = get_option('launchkey_app_key');
        $launchkey_options[LaunchKey_WP_Options::OPTION_SECRET_KEY] = get_option('launchkey_secret_key');
        $launchkey_options[LaunchKey_WP_Options::OPTION_SSL_VERIFY] = defined('LAUNCHKEY_SSLVERIFY') && LAUNCHKEY_SSLVERIFY || true;
        $launchkey_options[LaunchKey_WP_Options::OPTION_IMPLEMENTATION_TYPE] = LaunchKey_WP_Implementation_Type::OAUTH;
        $launchkey_options[LaunchKey_WP_Options::OPTION_LEGACY_OAUTH] = true;
        $updated = $is_multi_site ? update_network_option(LaunchKey_WP_Admin::OPTION_KEY, $launchkey_options) : update_option(LaunchKey_WP_Admin::OPTION_KEY, $launchkey_options);
        if ($updated) {
            delete_option('launchkey_app_key');
            delete_option('launchkey_secret_key');
        } else {
            throw new RuntimeException('Unable to upgrade LaunchKey meta-data.  Failed to save setting ' . LaunchKey_WP_Admin::OPTION_KEY);
        }
    } elseif (!$options) {
        $is_multi_site ? add_site_option(LaunchKey_WP_Admin::OPTION_KEY, array()) : add_option(LaunchKey_WP_Admin::OPTION_KEY, array());
        $options = $is_multi_site ? get_site_option(LaunchKey_WP_Admin::OPTION_KEY) : get_option(LaunchKey_WP_Admin::OPTION_KEY);
    }
    /**
     * Get the WP global facade
     * @see LaunchKey_WP_Global_Facade
     */
    $facade = new LaunchKey_WP_Global_Facade();
    /**
     * Create a templating object and point it at the correct directory for template files.
     *
     * @see LaunchKey_WP_Template
     */
    $template = new LaunchKey_WP_Template(__DIR__ . '/templates', $facade, $language_domain);
    // Prevent XXE Processing Vulnerability
    libxml_disable_entity_loader(true);
    // Get the plugin options to determine which authentication implementation should be utilized
    $logger = new LaunchKey_WP_Logger($facade);
    $launchkey_client = null;
    $client = null;
    // Only register the pieces that need to interact with LaunchKey if it's been configured
    if (LaunchKey_WP_Implementation_Type::SSO === $options[LaunchKey_WP_Options::OPTION_IMPLEMENTATION_TYPE] && !empty($options[LaunchKey_WP_Options::OPTION_SSO_ENTITY_ID])) {
        $container = new LaunchKey_WP_SAML2_Container($logger);
        SAML2_Compat_ContainerSingleton::setContainer($container);
        $securityKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type' => 'public'));
        $securityKey->loadKey($options[LaunchKey_WP_Options::OPTION_SSO_CERTIFICATE], false, true);
        $saml_response_service = new LaunchKey_WP_SAML2_Response_Service($securityKey, $facade);
        $saml_request_service = new LaunchKey_WP_SAML2_Request_Service($securityKey);
        $client = new LaunchKey_WP_SSO_Client($facade, $template, $options[LaunchKey_WP_Options::OPTION_SSO_ENTITY_ID], $saml_response_service, $saml_request_service, $wpdb, $options[LaunchKey_WP_Options::OPTION_SSO_LOGIN_URL], $options[LaunchKey_WP_Options::OPTION_SSO_LOGOUT_URL], $options[LaunchKey_WP_Options::OPTION_SSO_ERROR_URL], $is_multi_site);
    } elseif (LaunchKey_WP_Implementation_Type::OAUTH === $options[LaunchKey_WP_Options::OPTION_IMPLEMENTATION_TYPE] && !empty($options[LaunchKey_WP_Options::OPTION_SECRET_KEY])) {
        /**
         * If the implementation type is OAuth, use the OAuth client
         * @see LaunchKey_WP_OAuth_Client
         */
        $client = new LaunchKey_WP_OAuth_Client($facade, $template, $is_multi_site);
    } elseif (!empty($options[LaunchKey_WP_Options::OPTION_SECRET_KEY])) {
        $launchkey_client = \LaunchKey\SDK\Client::wpFactory($options[LaunchKey_WP_Options::OPTION_ROCKET_KEY], $options[LaunchKey_WP_Options::OPTION_SECRET_KEY], $options[LaunchKey_WP_Options::OPTION_PRIVATE_KEY], $options[LaunchKey_WP_Options::OPTION_SSL_VERIFY]);
        $client = new LaunchKey_WP_Native_Client($launchkey_client, $facade, $template, $language_domain, $is_multi_site);
        add_filter('init', function () use($facade) {
            wp_enqueue_script('launchkey-script', plugins_url('/public/launchkey-login.js', __FILE__), array('jquery'), '1.1.1', true);
        });
    }
    if ($client) {
        /**
         * Register the non-admin actions for authentication client.  These actions will handle all of the
         * authentication work for the plugin.
         *
         * @see LaunchKey_WP_Client::register_actions
         * @see LaunchKey_WP_OAuth_Client::register_actions
         * @see LaunchKey_WP_Native_Client::register_actions
         */
        $client->register_actions();
        /**
         * Create the a user profile object and register its actions.  These actions will handle all functionality
         * related to a user customizing their authentication related options.
         *
         * @see LaunchKey_WP_User_Profile
         */
        $profile = new LaunchKey_WP_User_Profile($facade, $template, $language_domain, $is_multi_site);
        $profile->register_actions();
        /**
         * Hideous workaround for the wp-login.php page not printing styles in the header like it should.
         *
         * @since 1.0.0
         */
        if (!has_action('login_enqueue_scripts', 'wp_print_styles')) {
            add_action('login_enqueue_scripts', 'wp_print_styles', 11);
        }
    }
    if (is_admin() || $is_multi_site && is_network_admin()) {
        /**
         * If we are in the admin, create an admin object and register its actions.  These actions
         * will manage setting of options and user management for the plugin.
         *
         * @see is_admin
         * @see LaunchKey_WP_Admin
         */
        $launchkey_admin = new LaunchKey_WP_Admin($facade, $template, $language_domain, $is_multi_site);
        $launchkey_admin->register_actions();
        $config_wizard = new LaunchKey_WP_Configuration_Wizard($facade, $launchkey_admin, $is_multi_site, $launchkey_client);
        $config_wizard->register_actions();
    }
    /**
     * Add a filter to enqueue styles for the plugin
     *
     * @since 1.0.0
     *
     * @see add_filter
     * @see wp_enqueue_style
     * @link https://developer.wordpress.org/reference/functions/add_filter/
     * @link https://developer.wordpress.org/reference/functions/wp_enqueue_style/
     */
    add_filter('init', function () use($facade) {
        wp_enqueue_style('launchkey-style', plugins_url('/public/launchkey.css', __FILE__), array(), '1.0.1', false);
    });
    /**
     * Handle activation when a "must use" plugin
     */
    if (launchkey_is_mu_plugin()) {
        $mu_activated_option = "launchkey_activated";
        if (!get_option($mu_activated_option)) {
            do_action("activate_" . plugin_basename(__FILE__));
            add_option($mu_activated_option, true);
        }
    }
}
 /**
  * Checks (and adapts) the current MultilingualPress installation.
  *
  * @return bool Whether or not MultilingualPress is installed properly.
  */
 private function check_installation()
 {
     $system_checker = static::$container['multilingualpress.system_checker'];
     $installation_check = $system_checker->check_installation();
     if (SystemChecker::PLUGIN_DEACTIVATED === $installation_check) {
         return false;
     }
     if (SystemChecker::INSTALLATION_OK === $installation_check) {
         $type_factory = static::$container['multilingualpress.type_factory'];
         $installed_version = $type_factory->create_version_number([get_network_option(null, $this->version_option)]);
         $current_version = $type_factory->create_version_number([static::$container['multilingualpress.properties']->version()]);
         switch ($system_checker->check_version($installed_version, $current_version)) {
             case SystemChecker::INSTALLATION_OK:
                 return true;
             case SystemChecker::NEEDS_INSTALLATION:
                 static::$container['multilingualpress.installer']->install();
                 break;
             case SystemChecker::NEEDS_UPGRADE:
                 static::$container['multilingualpress.network_plugin_deactivator']->deactivate_plugins(['disable-acf.php', 'mlp-wp-seo-compat.php']);
                 static::$container['multilingualpress.updater']->update($installed_version);
                 break;
         }
         update_network_option(null, $this->version_option, $current_version);
     }
     return true;
 }
Ejemplo n.º 22
0
/**
 * Update the value of an option that was already added for the current network.
 *
 * @since 2.8.0
 * @since 4.4.0 Modified into wrapper for update_network_option()
 *
 * @see update_network_option()
 *
 * @param string $option Name of option. Expected to not be SQL-escaped.
 * @param mixed  $value  Option value. Expected to not be SQL-escaped.
 * @return bool False if value was not updated. True if value was updated.
 */
function update_site_option($option, $value)
{
    return update_network_option(null, $option, $value);
}
Ejemplo n.º 23
0
 function update_global_option($option, $value, $autoload = null)
 {
     global $wpdb;
     $option = trim($option);
     if (empty($option)) {
         return false;
     }
     wp_protect_special_option($option);
     if (is_object($value)) {
         $value = clone $value;
     }
     $value = sanitize_option($option, $value);
     $old_value = get_global_option($option);
     /**
      * Filters a specific global option before its value is (maybe) serialized and updated.
      *
      * The dynamic portion of the hook name, `$option`, refers to the option name.
      *
      * @since 1.0.0
      *
      * @param mixed  $value     The new, unserialized option value.
      * @param mixed  $old_value The old option value.
      * @param string $option    Option name.
      */
     $value = apply_filters('pre_update_global_option_' . $option, $value, $old_value, $option);
     /**
      * Filters a global option before its value is (maybe) serialized and updated.
      *
      * @since 1.0.0
      *
      * @param mixed  $value     The new, unserialized option value.
      * @param string $option    Name of the option.
      * @param mixed  $old_value The old option value.
      */
     $value = apply_filters('pre_update_global_option', $value, $option, $old_value);
     // If the new and old values are the same, no need to update.
     if ($value === $old_value) {
         return false;
     }
     /** This filter is documented in wp-includes/option.php */
     if (apply_filters('default_global_option_' . $option, false, $option) === $old_value) {
         // Default setting for new options is 'yes'.
         if (null === $autoload) {
             $autoload = 'yes';
         }
         return add_global_option($option, $value, $autoload);
     }
     $serialized_value = maybe_serialize($value);
     /**
      * Fires immediately before a global option value is updated.
      *
      * @since 1.0.0
      *
      * @param string $option    Name of the option to update.
      * @param mixed  $old_value The old option value.
      * @param mixed  $value     The new option value.
      */
     do_action('update_global_option', $option, $old_value, $value);
     if (!is_multinetwork()) {
         $result = update_network_option(null, $option, $value, 'no');
         if (!$result) {
             return false;
         }
     } else {
         $update_args = array('option_value' => $serialized_value);
         if (null !== $autoload) {
             $update_args['autoload'] = 'no' === $autoload || false === $autoload ? 'no' : 'yes';
         }
         $result = $wpdb->update($wpdb->global_options, $update_args, array('option_name' => $option));
         if (!$result) {
             return false;
         }
         $notoptions = wp_cache_get('notoptions', 'global-options');
         if (is_array($notoptions) && isset($notoptions[$option])) {
             unset($notoptions[$option]);
             wp_cache_set('notoptions', $notoptions, 'global-options');
         }
         if (!wp_installing()) {
             $alloptions = wp_load_global_alloptions();
             if (isset($alloptions[$option])) {
                 $alloptions[$option] = $serialized_value;
                 wp_cache_set('alloptions', $alloptions, 'global-options');
             } else {
                 wp_cache_set($option, $serialized_value, 'global-options');
             }
         }
     }
     /**
      * Fires after the value of a specific global option has been successfully updated.
      *
      * The dynamic portion of the hook name, `$option`, refers to the option name.
      *
      * @since 1.0.0
      *
      * @param mixed  $old_value The old option value.
      * @param mixed  $value     The new option value.
      * @param string $option    Option name.
      */
     do_action("update_global_option_{$option}", $old_value, $value, $option);
     /**
      * Fires after the value of a global option has been successfully updated.
      *
      * @since 1.0.0
      *
      * @param string $option    Name of the updated option.
      * @param mixed  $old_value The old option value.
      * @param mixed  $value     The new option value.
      */
     do_action('updated_global_option', $option, $old_value, $value);
     return true;
 }
Ejemplo n.º 24
0
         $allowed_themes[$theme] = true;
     }
     update_network_option('allowedthemes', $allowed_themes);
     wp_safe_redirect(add_query_arg('enabled', count($themes), $referer));
     exit;
 case 'disable-selected':
     check_admin_referer('bulk-themes');
     $themes = isset($_POST['checked']) ? (array) $_POST['checked'] : array();
     if (empty($themes)) {
         wp_safe_redirect(add_query_arg('error', 'none', $referer));
         exit;
     }
     foreach ((array) $themes as $theme) {
         unset($allowed_themes[$theme]);
     }
     update_network_option('allowedthemes', $allowed_themes);
     wp_safe_redirect(add_query_arg('disabled', count($themes), $referer));
     exit;
 case 'update-selected':
     check_admin_referer('bulk-themes');
     if (isset($_GET['themes'])) {
         $themes = explode(',', $_GET['themes']);
     } elseif (isset($_POST['checked'])) {
         $themes = (array) $_POST['checked'];
     } else {
         $themes = array();
     }
     $title = __('Update Themes');
     $parent_file = 'themes.php';
     require_once ABSPATH . 'wp-admin/admin-header.php';
     echo '<div class="wrap">';
Ejemplo n.º 25
0
 /**
  * Add a new network
  *
  * @since 1.3
  *
  * @param array $args  {
  *     Array of arguments.
  *     @type string  $domain           Domain name for new network - for VHOST=no,
  *                                     this should be FQDN, otherwise domain only.
  *     @type string  $path             Path to root of network hierarchy - should
  *                                     be '/' unless WP is cohabiting with another
  *                                     product on a domain.
  *     @type string  $site_name        Name of the root blog to be created on
  *                                     the new network.
  *     @type integer $user_id          ID of the user to add as the site owner.
  *                                     Defaults to current user ID.
  *     @type array   $meta             Array of metadata to save to this network.
  *                                     Defaults to array( 'public' => false ).
  *     @type integer $clone_network    ID of network whose networkmeta values are
  *                                     to be copied - default NULL.
  *     @type array   $options_to_clone Override default network meta options to copy
  *                                     when cloning - default NULL.
  * }
  *
  * @return integer ID of newly created network
  */
 function add_network($args = array())
 {
     global $wpdb;
     // Backward compatibility with old method of passing arguments
     if (!is_array($args) || func_num_args() > 1) {
         _deprecated_argument(__METHOD__, '1.7.0', sprintf(__('Arguments passed to %1$s should be in an associative array. See the inline documentation at %2$s for more details.', 'wp-multi-network'), __METHOD__, __FILE__));
         // Juggle function parameters
         $func_args = func_get_args();
         $old_args_keys = array(0 => 'domain', 1 => 'path', 2 => 'site_name', 3 => 'clone_network', 4 => 'options_to_clone');
         // Reset array
         $args = array();
         // Rejig args
         foreach ($old_args_keys as $arg_num => $arg_key) {
             if (isset($func_args[$arg_num])) {
                 $args[$arg_key] = $func_args[$arg_num];
             }
         }
     }
     // Parse args
     $r = wp_parse_args($args, array('domain' => '', 'path' => '/', 'site_name' => __('New Network', 'wp-multi-network'), 'user_id' => get_current_user_id(), 'meta' => array('public' => get_option('blog_public', false)), 'clone_network' => false, 'options_to_clone' => array_keys(network_options_to_copy())));
     // Bail if no user with this ID
     if (empty($r['user_id']) || !get_userdata($r['user_id'])) {
         return new WP_Error('network_user', __('User does not exist.', 'wp-multi-network'));
     }
     // Permissive sanitization for super admin usage
     $r['domain'] = str_replace(' ', '', strtolower($r['domain']));
     $r['path'] = str_replace(' ', '', strtolower($r['path']));
     // Check for existing network
     $networks = get_networks(array('domain' => $r['domain'], 'path' => $r['path'], 'number' => '1'));
     // Bail if network already exists
     if (!empty($networks)) {
         return new WP_Error('network_exists', __('Network already exists.', 'wp-multi-network'));
     }
     // Insert new network
     $wpdb->insert($wpdb->site, array('domain' => $r['domain'], 'path' => $r['path']));
     $new_network_id = $wpdb->insert_id;
     // If network was created, create a blog for it too
     if (!empty($new_network_id)) {
         if (!defined('WP_INSTALLING')) {
             define('WP_INSTALLING', true);
         }
         // Switch to the new network so counts are properly bumped
         switch_to_network($new_network_id);
         // Ensure upload constants are envoked
         ms_upload_constants();
         // Create the site for the root of this network
         $new_blog_id = wpmu_create_blog($r['domain'], $r['path'], $r['site_name'], $r['user_id'], $r['meta'], $new_network_id);
         // Switch back to the current network, to avoid any issues
         restore_current_network();
         // Bail if blog could not be created
         if (is_wp_error($new_blog_id)) {
             return $new_blog_id;
         }
         /**
          * Fix upload_path for main sites on secondary networks
          * This applies only to new installs (WP 3.5+)
          */
         // Switch to network (if set & exists)
         if (defined('SITE_ID_CURRENT_SITE') && get_network(SITE_ID_CURRENT_SITE)) {
             $use_files_rewriting = get_network_option(SITE_ID_CURRENT_SITE, 'ms_files_rewriting');
         } else {
             $use_files_rewriting = get_site_option('ms_files_rewriting');
         }
         global $wp_version;
         // Create the upload_path and upload_url_path values
         if (empty($use_files_rewriting) && version_compare($wp_version, '3.7', '<')) {
             // WP_CONTENT_URL is locked to the current site and can't be overridden,
             //  so we have to replace the hostname the hard way
             $current_siteurl = get_option('siteurl');
             $new_siteurl = untrailingslashit(get_blogaddress_by_id($new_blog_id));
             $upload_url = str_replace($current_siteurl, $new_siteurl, WP_CONTENT_URL);
             $upload_url = $upload_url . '/uploads';
             $upload_dir = WP_CONTENT_DIR;
             if (0 === strpos($upload_dir, ABSPATH)) {
                 $upload_dir = substr($upload_dir, strlen(ABSPATH));
             }
             $upload_dir .= '/uploads';
             if (defined('MULTISITE')) {
                 $ms_dir = '/sites/' . $new_blog_id;
             } else {
                 $ms_dir = '/' . $new_blog_id;
             }
             $upload_dir .= $ms_dir;
             $upload_url .= $ms_dir;
             update_blog_option($new_blog_id, 'upload_path', $upload_dir);
             update_blog_option($new_blog_id, 'upload_url_path', $upload_url);
         }
     }
     // Clone network meta from an existing network.
     //
     // We currently use the _options() API to get cache integration for free,
     // but it may be better to read & write directly to $wpdb->sitemeta.
     if (!empty($r['clone_network']) && get_network($r['clone_network'])) {
         // Temporary array
         $options_cache = array();
         // Old network
         foreach ($r['options_to_clone'] as $option) {
             $options_cache[$option] = get_network_option($r['clone_network'], $option);
         }
         // New network
         foreach ($r['options_to_clone'] as $option) {
             // Skip if option isn't available to copy
             if (!isset($options_cache[$option])) {
                 continue;
             }
             // Fix for bug that prevents writing the ms_files_rewriting
             // value for new networks.
             if ('ms_files_rewriting' === $option) {
                 $wpdb->insert($wpdb->sitemeta, array('site_id' => $wpdb->siteid, 'meta_key' => $option, 'meta_value' => $options_cache[$option]));
             } else {
                 update_network_option($new_network_id, $option, $options_cache[$option]);
             }
         }
     }
     // Clean network cache
     clean_network_cache($new_network_id);
     do_action('add_network', $new_network_id, $r);
     return $new_network_id;
 }