Exemplo n.º 1
0
function batcache_clear_url($url)
{
    global $batcache, $wp_object_cache;
    if (empty($url)) {
        return false;
    }
    if (0 === strpos($url, 'https://')) {
        $url = str_replace('https://', 'http://', $url);
    }
    if (0 !== strpos($url, 'http://')) {
        $url = 'http://' . $url;
    }
    $url_key = md5($url);
    wp_cache_add("{$url_key}_version", 0, $batcache->group);
    $retval = wp_cache_incr("{$url_key}_version", 1, $batcache->group);
    $batcache_no_remote_group_key = array_search($batcache->group, (array) $wp_object_cache->no_remote_groups);
    if (false !== $batcache_no_remote_group_key) {
        // The *_version key needs to be replicated remotely, otherwise invalidation won't work.
        // The race condition here should be acceptable.
        unset($wp_object_cache->no_remote_groups[$batcache_no_remote_group_key]);
        $retval = wp_cache_set("{$url_key}_version", $retval, $batcache->group);
        $wp_object_cache->no_remote_groups[$batcache_no_remote_group_key] = $batcache->group;
    }
    return $retval;
}
Exemplo n.º 2
0
function batcache_clear_url($url)
{
    global $batcache;
    if (empty($url)) {
        return false;
    }
    $url_key = md5($url);
    wp_cache_add("{$url_key}_version", 0, $batcache->group);
    return wp_cache_incr("{$url_key}_version", 1, $batcache->group);
}
Exemplo n.º 3
0
function wpcom_vip_login_limiter($username)
{
    $ip = preg_replace('/[^0-9a-fA-F:., ]/', '', $_SERVER['REMOTE_ADDR']);
    $key1 = $ip . '|' . $username;
    // IP + username
    $key2 = $ip;
    // IP only
    // Longer TTL when logging in as admin, which we don't allow on WP.com
    wp_cache_add($key1, 0, 'login_limit', 'admin' == $username ? HOUR_IN_SECONDS : MINUTE_IN_SECONDS * 5);
    wp_cache_add($key2, 0, 'login_limit', HOUR_IN_SECONDS);
    wp_cache_incr($key1, 1, 'login_limit');
    wp_cache_incr($key2, 1, 'login_limit');
}
 /**
  * Set a lock and limit how many concurrent jobs are permitted
  *
  * @param $lock     string  Lock name
  * @param $limit    int     Concurrency limit
  * @param $timeout  int     Timeout in seconds
  *
  * @return bool
  */
 public static function check_lock($lock, $limit = null, $timeout = null)
 {
     // Timeout, should a process die before its lock is freed
     if (!is_numeric($timeout)) {
         $timeout = LOCK_DEFULT_TIMEOUT_IN_MINUTES * \MINUTE_IN_SECONDS;
     }
     // Check for, and recover from, deadlock
     if (self::get_lock_timestamp($lock) < time() - $timeout) {
         self::reset_lock($lock);
         return true;
     }
     // Default limit for concurrent events
     if (!is_numeric($limit)) {
         $limit = LOCK_DEFAULT_LIMIT;
     }
     // Check if process can run
     if (self::get_lock_value($lock) >= $limit) {
         return false;
     } else {
         wp_cache_incr(self::get_key($lock));
         return true;
     }
 }
Exemplo n.º 5
0
 /**
  * Increment the number stored with group name as key.
  */
 public function flush_group_cache()
 {
     wp_cache_incr('current_key_index', 1, $this->group);
 }
/**
 * Increment the batcache group incrementor value, invalidating the cache.
 * @return false|int False on failure, the item's new value on success.
 */
function batcache_flush_all()
{
    return wp_cache_incr('cache_incrementors', 1, 'batcache');
}
Exemplo n.º 7
0
 /**
  * update_views_using_cache
  * 
  * 
  * @return 
  * @version 1.0.2
  * 
  */
 private static function update_views_using_cache($post_id, $force = false)
 {
     $times = wp_cache_get($post_id, __CLASS__);
     $meta = (int) get_post_meta($post_id, self::$post_meta_key, true) + (int) $times;
     /**
      * force to update db
      */
     if ($force) {
         $meta++;
         wp_cache_set($post_id, 0, __CLASS__, self::$expire);
         update_post_meta($post_id, self::$post_meta_key, $meta);
         /**
          * update cache
          */
     } else {
         /**
          * if views more than storage times, update db and reset cache
          */
         if ($times >= self::get_storage_times()) {
             $meta = $meta + $times + 1;
             update_post_meta($post_id, self::$post_meta_key, $meta);
             wp_cache_set($post_id, 0, __CLASS__, self::$expire);
             /**
              * update cache
              */
         } else {
             if ($times === false) {
                 wp_cache_set($post_id, 0, __CLASS__, self::$expire);
             }
             wp_cache_incr($post_id, 1, __CLASS__);
             $meta++;
         }
     }
     return $meta;
 }
Exemplo n.º 8
0
/**
 * Removes comment ID from the comment cache.
 *
 * @since 2.3.0
 * @package WordPress
 * @subpackage Cache
 *
 * @param int|array $ids Comment ID or array of comment IDs to remove from cache
 */
function clean_comment_cache($ids) {
	foreach ( (array) $ids as $id )
		wp_cache_delete($id, 'comment');

	if ( function_exists( 'wp_cache_incr' ) ) {
		wp_cache_incr( 'last_changed', 1, 'comment' );
	} else {
		$last_changed = wp_cache_get( 'last_changed', 'comment' );
		wp_cache_set( 'last_changed', $last_changed + 1, 'comment' );
	}
}
Exemplo n.º 9
0
 public function test_wp_cache_incr()
 {
     $key = rand_str();
     $this->assertFalse(wp_cache_incr($key));
     wp_cache_set($key, 0);
     wp_cache_incr($key);
     $this->assertEquals(1, wp_cache_get($key));
     wp_cache_incr($key, 2);
     $this->assertEquals(3, wp_cache_get($key));
 }
Exemplo n.º 10
0
 /**
  * Increment a value in the object cache.
  *
  * Errors if the value can't be incremented.
  *
  * ## OPTIONS
  *
  * <key>
  * : Cache key.
  *
  * [<offset>]
  * : The amount by which to increment the item's value. Default is 1.
  *
  * [<group>]
  * : Method for grouping data within the cache which allows the same key to be used across groups.
  *
  * ## EXAMPLES
  *
  *     # Increase cache value.
  *     $ wp cache incr my_key 2 my_group
  *     50
  */
 public function incr($args, $assoc_args)
 {
     $key = $args[0];
     $offset = \WP_CLI\Utils\get_flag_value($args, 1, 1);
     $group = \WP_CLI\Utils\get_flag_value($args, 2, '');
     $value = wp_cache_incr($key, $offset, $group);
     if (false === $value) {
         WP_CLI::error('The value was not incremented.');
     }
     WP_CLI::print_value($value, $assoc_args);
 }
Exemplo n.º 11
0
 /**
  * Count visit function.
  * 
  * @global object $wpdb
  * @param int $id
  * @return bool
  */
 private function count_visit($id)
 {
     global $wpdb;
     $cache_key_names = array();
     $using_object_cache = $this->using_object_cache();
     // get day, week, month and year
     $date = explode('-', date('W-d-m-Y', current_time('timestamp')));
     foreach (array(0 => $date[3] . $date[2] . $date[1], 1 => $date[3] . $date[0], 2 => $date[3] . $date[2], 3 => $date[3], 4 => 'total') as $type => $period) {
         if ($using_object_cache) {
             $cache_key = $id . self::CACHE_KEY_SEPARATOR . $type . self::CACHE_KEY_SEPARATOR . $period;
             wp_cache_add($cache_key, 0, self::GROUP);
             wp_cache_incr($cache_key, 1, self::GROUP);
             $cache_key_names[] = $cache_key;
         } else {
             // hit the db directly
             // @TODO: investigate queueing these queries on the 'shutdown' hook instead instead of running them instantly?
             $this->db_insert($id, $type, $period, 1);
         }
     }
     // update the list of cache keys to be flushed
     if ($using_object_cache && !empty($cache_key_names)) {
         $this->update_cached_keys_list_if_needed($cache_key_names);
     }
     do_action('pvc_after_count_visit', $id);
     return true;
 }
Exemplo n.º 12
0
 private function count_tax_visit($id)
 {
     global $wpdb;
     // get post id
     $id = (int) (empty($id) ? get_the_ID() : $id);
     if (empty($id)) {
         return;
     }
     $ips = Post_Views_Counter()->options['general']['exclude_ips'];
     // whether to count this ip
     if (!empty($ips) && filter_var(preg_replace('/[^0-9a-fA-F:., ]/', '', $_SERVER['REMOTE_ADDR']), FILTER_VALIDATE_IP) && in_array($_SERVER['REMOTE_ADDR'], $ips, true)) {
         return;
     }
     // get groups to check them faster
     $groups = Post_Views_Counter()->options['general']['exclude']['groups'];
     // whether to count this user
     if (is_user_logged_in()) {
         // exclude logged in users?
         if (in_array('users', $groups, true)) {
             return;
         } elseif (in_array('roles', $groups, true) && $this->is_user_role_excluded(Post_Views_Counter()->options['general']['exclude']['roles'])) {
             return;
         }
     } elseif (in_array('guests', $groups, true)) {
         return;
     }
     // whether to count robots
     if ($this->is_robot()) {
         return;
     }
     // cookie already existed?
     if ($this->cookie['exists']) {
         // post already viewed but not expired?
         if (in_array($id, array_keys($this->cookie['visited_posts']), true) && current_time('timestamp', true) < $this->cookie['visited_posts'][$id]) {
             // update cookie but do not count visit
             $this->save_cookie($id, $this->cookie, false);
             return;
         } else {
             // update cookie
             $this->save_cookie($id, $this->cookie);
         }
     } else {
         // set new cookie
         $this->save_cookie($id);
     }
     // count visit
     //$this->count_visit( $id );
     $cache_key_names = array();
     $using_object_cache = $this->using_object_cache();
     // get day, week, month and year
     $date = explode('-', date('W-d-m-Y', current_time('timestamp')));
     foreach (array(0 => $date[3] . $date[2] . $date[1], 1 => $date[3] . $date[0], 2 => $date[3] . $date[2], 3 => $date[3], 4 => 'total') as $type => $period) {
         if ($using_object_cache) {
             $cache_key = $id . self::CACHE_KEY_SEPARATOR . $type . self::CACHE_KEY_SEPARATOR . $period;
             wp_cache_add($cache_key, 0, self::GROUP);
             wp_cache_incr($cache_key, 1, self::GROUP);
             $cache_key_names[] = $cache_key;
         } else {
             // hit the db directly
             // @TODO: investigate queueing these queries on the 'shutdown' hook instead instead of running them instantly?
             $this->db_insert_tax($id, $type, $period, 1);
         }
     }
     // update the list of cache keys to be flushed
     if ($using_object_cache && !empty($cache_key_names)) {
         $this->update_cached_keys_list_if_needed($cache_key_names);
     }
     do_action('pvc_after_count_visit', $id);
     return true;
 }
Exemplo n.º 13
0
 /**
  * Increment the cache key to gracefully invalidate Shopp specific caches
  *
  * @author Clifton Griffin
  * @since 1.4
  *
  * @return void
  */
 public static function invalidate_cache()
 {
     wp_cache_incr('shopp_cache_key');
     do_action('shopp_invalidate_cache');
 }
 /**
  * Cleanup sessions
  */
 public function cleanup_sessions()
 {
     global $wpdb;
     if (!defined('WP_SETUP_CONFIG') && !defined('WP_INSTALLING')) {
         // Delete expired sessions
         $wpdb->query($wpdb->prepare("DELETE FROM {$this->_table} WHERE session_expiry < %d", time()));
         // Invalidate cache
         wp_cache_incr('wc_session_prefix', 1, WC_SESSION_CACHE_GROUP);
     }
 }
 /**
  * Flush cache by incrementing current cache itteration
  */
 public static function flush()
 {
     wp_cache_incr(self::ITTR_KEY);
 }
Exemplo n.º 16
0
 /**
  * Clear the key used for wp_cache_get and wp_cache_set
  * Run this when options etc have been changed so fresh values are fetched upon next get
  */
 function clear_caches()
 {
     do_action("simple_fields_clear_caches");
     $prev_key = $this->ns_key;
     $this->ns_key = wp_cache_incr('simple_fields_namespace_key', 1, 'simple_fields');
     // this can consume lots of memory if we for example use set_value a lot because
     // it gets all field values and such and then increase the namespace key, bloating up the memory
     // kinda correct, but kinda too much memory
     // this is perhaps naughty, but will work: get all keys belonging to simple fields and just remove them
     global $wp_object_cache;
     if (isset($wp_object_cache->cache["simple_fields"])) {
         // cache exists for simple fields
         // remove all keys
         // This started getting error after updating to WP 4
         // https://wordpress.org/support/topic/notice-indirect-modification-of-overloaded-property-wp_object_cachecache
         // $wp_object_cache->cache["simple_fields"] = array();
         $cache = $wp_object_cache->cache;
         $cache['simple_fields'] = array();
         $wp_object_cache->cache = $cache;
     }
     if ($this->ns_key === FALSE) {
         // I really don't know why, but wp_cache_incr returns false...always or sometimes?
         // Manually update namespace key by one
         $this->ns_key = $prev_key + 1;
         wp_cache_set('simple_fields_namespace_key', $this->ns_key, 'simple_fields');
     }
     // echo "clear_key";var_dump($this->ns_key);
 }
 /**
  *
  * @param $url
  *
  * @return bool|false|int
  */
 public static function clear_url($url)
 {
     global $batcache, $wp_object_cache;
     $url = apply_filters('batcache_manager_link', $url);
     if (empty($url)) {
         return false;
     }
     do_action('batcache_manager_before_flush', $url);
     // Force to http
     $url = set_url_scheme($url, 'http');
     $url_key = md5($url);
     wp_cache_add("{$url_key}_version", 0, $batcache->group);
     $retval = wp_cache_incr("{$url_key}_version", 1, $batcache->group);
     $batcache_no_remote_group_key = array_search($batcache->group, (array) $wp_object_cache->no_remote_groups);
     if (false !== $batcache_no_remote_group_key) {
         // The *_version key needs to be replicated remotely, otherwise invalidation won't work.
         // The race condition here should be acceptable.
         unset($wp_object_cache->no_remote_groups[$batcache_no_remote_group_key]);
         $retval = wp_cache_set("{$url_key}_version", $retval, $batcache->group);
         $wp_object_cache->no_remote_groups[$batcache_no_remote_group_key] = $batcache->group;
     }
     do_action('batcache_manager_after_flush', $url, $retval);
     return $retval;
 }
Exemplo n.º 18
0
Arquivo: cache.php Projeto: nb/wp-cli
 /**
  * Increment a value in the object cache.
  *
  * @synopsis <key> [<offset>] [<group>]
  */
 public function incr($args, $assoc_args)
 {
     $key = $args[0];
     $offset = isset($args[1]) ? $args[1] : 1;
     $group = isset($args[2]) ? $args[2] : '';
     $value = wp_cache_incr($key, $offset, $group);
     if (false === $value) {
         WP_CLI::error('The value was not incremented.');
         exit;
     }
     WP_CLI::print_value($value, $assoc_args);
 }
Exemplo n.º 19
0
 /**
  * Clear a cached URL
  *
  * @since 2.3.0
  *
  * @param string $url
  *
  * @return boolean
  */
 public static function clean_url($url = '')
 {
     // Bail if no URL
     if (empty($url)) {
         return false;
     }
     // Bail if no persistent output cache
     if (!function_exists('wp_output_cache')) {
         return false;
     }
     // Normalize the URL
     if (0 === strpos($url, 'https://')) {
         $url = str_replace('https://', 'http://', $url);
     }
     if (0 !== strpos($url, 'http://')) {
         $url = 'http://' . $url;
     }
     $url_key = md5($url);
     // Get cache objects
     $output_cache = wp_output_cache_init();
     $object_cache = wp_object_cache_init();
     // Bail if either cache is missing
     if (empty($output_cache) || empty($object_cache)) {
         return;
     }
     wp_cache_add("{$url_key}_version", 0, $output_cache->group);
     $retval = wp_cache_incr("{$url_key}_version", 1, $output_cache->group);
     $output_cache_no_remote_group_key = array_search($output_cache->group, (array) $object_cache->no_remote_groups);
     // The *_version key needs to be replicated remotely, otherwise invalidation won't work.
     // The race condition here should be acceptable.
     if (false !== $output_cache_no_remote_group_key) {
         unset($object_cache->no_remote_groups[$output_cache_no_remote_group_key]);
         $retval = wp_cache_set("{$url_key}_version", $retval, $output_cache->group);
         $object_cache->no_remote_groups[$output_cache_no_remote_group_key] = $output_cache->group;
     }
     return $retval;
 }
Exemplo n.º 20
0
 /**
  * Start page caching and hook into requests to complete it later
  *
  * @since 2.1.0
  *
  * @return void
  */
 protected function start()
 {
     // Bail if cookies indicate a cache-exempt visitor
     if (is_array($_COOKIE) && !empty($_COOKIE)) {
         $cookie_keys = array_keys($_COOKIE);
         foreach ($cookie_keys as $this->cookie) {
             if (!in_array($this->cookie, $this->noskip_cookies) && (substr($this->cookie, 0, 2) === 'wp' || substr($this->cookie, 0, 9) === 'wordpress' || substr($this->cookie, 0, 14) === 'comment_author')) {
                 return;
             }
         }
     }
     // Disabled
     if ($this->max_age < 1) {
         return;
     }
     // Necessary to prevent clients using cached version after login cookies
     // set. If this is a problem, comment it out and remove all
     // Last-Modified headers.
     header('Vary: Cookie', false);
     // Things that define a unique page.
     if (isset($_SERVER['QUERY_STRING'])) {
         parse_str($_SERVER['QUERY_STRING'], $this->query);
     }
     // Build different versions for HTTP/1.1 and HTTP/2.0
     if (isset($_SERVER['SERVER_PROTOCOL'])) {
         $this->unique['server_protocol'] = $_SERVER['SERVER_PROTOCOL'];
     }
     // Setup keys
     $this->keys = array('host' => $_SERVER['HTTP_HOST'], 'method' => $_SERVER['REQUEST_METHOD'], 'path' => ($this->pos = strpos($_SERVER['REQUEST_URI'], '?')) ? substr($_SERVER['REQUEST_URI'], 0, $this->pos) : $_SERVER['REQUEST_URI'], 'query' => $this->query, 'extra' => $this->unique, 'ssl' => $this->is_ssl());
     // Recreate the permalink from the URL
     $protocol = true === $this->keys['ssl'] ? 'https://' : 'http://';
     $this->permalink = $protocol . $this->keys['host'] . $this->keys['path'] . (isset($this->keys['query']['p']) ? "?p=" . $this->keys['query']['p'] : '');
     $this->url_key = md5($this->permalink);
     $this->url_version = (int) wp_cache_get("{$this->url_key}_version", $this->group);
     // Setup keys and variants
     $this->do_variants();
     $this->generate_keys();
     // Get the spider_cache
     $this->cache = wp_cache_get($this->key, $this->group);
     // Are we only caching frequently-requested pages?
     if ($this->seconds < 1 || $this->times < 2) {
         $this->do = true;
     } else {
         // No spider_cache item found, or ready to sample traffic again at
         // the end of the spider_cache life?
         if (!is_array($this->cache) || $this->started >= $this->cache['time'] + $this->max_age - $this->seconds) {
             wp_cache_add($this->req_key, 0, $this->group);
             $this->requests = wp_cache_incr($this->req_key, 1, $this->group);
             if ($this->requests >= $this->times) {
                 $this->do = true;
             } else {
                 $this->do = false;
             }
         }
     }
     // If the document has been updated and we are the first to notice, regenerate it.
     if ($this->do !== false && isset($this->cache['version']) && $this->cache['version'] < $this->url_version) {
         $this->genlock = wp_cache_add("{$this->url_key}_genlock", 1, $this->group, 10);
     }
     // Did we find a spider_cached page that hasn't expired?
     if (isset($this->cache['time']) && empty($this->genlock) && $this->started < $this->cache['time'] + $this->cache['max_age']) {
         // Issue redirect if cached and enabled
         if ($this->cache['redirect_status'] && $this->cache['redirect_location'] && $this->cache_redirects) {
             $status = $this->cache['redirect_status'];
             $location = $this->cache['redirect_location'];
             // From vars.php
             $is_IIS = strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS') !== false || strpos($_SERVER['SERVER_SOFTWARE'], 'ExpressionDevServer') !== false;
             $this->do_headers($this->headers);
             if (!empty($is_IIS)) {
                 header("Refresh: 0;url={$location}");
             } else {
                 if (php_sapi_name() !== 'cgi-fcgi') {
                     $texts = array(300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 306 => 'Reserved', 307 => 'Temporary Redirect');
                     $protocol = $_SERVER["SERVER_PROTOCOL"];
                     if ('HTTP/1.1' !== $protocol && 'HTTP/1.0' !== $protocol) {
                         $protocol = 'HTTP/1.0';
                     }
                     if (isset($texts[$status])) {
                         header("{$protocol} {$status} " . $texts[$status]);
                     } else {
                         header("{$protocol} 302 Found");
                     }
                 }
                 header("Location: {$location}");
             }
             exit;
         }
         // Respect ETags served with feeds.
         $three_oh_four = false;
         if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && isset($this->cache['headers']['ETag'][0]) && $_SERVER['HTTP_IF_NONE_MATCH'] == $this->cache['headers']['ETag'][0]) {
             $three_oh_four = true;
             // Respect If-Modified-Since.
         } elseif ($this->cache_control && isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
             $client_time = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
             if (isset($this->cache['headers']['Last-Modified'][0])) {
                 $cache_time = strtotime($this->cache['headers']['Last-Modified'][0]);
             } else {
                 $cache_time = $this->cache['time'];
             }
             if ($client_time >= $cache_time) {
                 $three_oh_four = true;
             }
         }
         // Use the spider_cache save time for Last-Modified so we can issue
         // "304 Not Modified" but don't clobber a cached Last-Modified header.
         if ($this->cache_control && !isset($this->cache['headers']['Last-Modified'][0])) {
             header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $this->cache['time']) . ' GMT', true);
             header('Cache-Control: max-age=' . ($this->cache['max_age'] - $this->started + $this->cache['time']) . ', must-revalidate', true);
         }
         // Add some debug info just before </head>
         if (true === $this->debug) {
             $this->add_debug_from_cache();
         }
         $this->do_headers($this->headers, $this->cache['headers']);
         // Bail if not modified
         if (true === $three_oh_four) {
             header("HTTP/1.1 304 Not Modified", true, 304);
             die;
         }
         // Set header if cached
         if (!empty($this->cache['status_header'])) {
             header($this->cache['status_header'], true);
         }
         // Have you ever heard a death rattle before?
         die($this->cache['output']);
     }
     // Didn't meet the minimum condition?
     if (empty($this->do) && empty($this->genlock)) {
         return;
     }
     global $wp_filter;
     // Headers and such
     $wp_filter['status_header'][10]['spider_cache'] = array('function' => array($this, 'status_header'), 'accepted_args' => 2);
     $wp_filter['wp_redirect_status'][10]['spider_cache'] = array('function' => array($this, 'redirect_status'), 'accepted_args' => 2);
     // Start the spidey-sense listening
     ob_start(array($this, 'ob'));
 }
Exemplo n.º 21
0
/**
 * @ignore
 * @private
 * @param unknown_type $group
 * @param unknown_type $key
 * @return Ambigous <false, number>|boolean
 */
function eventorganiser_clear_cache($group, $key = false)
{
    if ($key == false) {
        //If a key is not specified clear entire group by incrementing name space
        return wp_cache_incr('eventorganiser_' . $group . '_key');
    } elseif ($ns_key = wp_cache_get('eventorganiser_' . $group . '_key')) {
        //If key is specified - clear particular key from the group
        return wp_cache_delete("eo_" . $ns_key . "_" . $key, $group);
    }
}
$table_prefix = 'wp_';
define('DB_NAME', 'db_name');
define('DAY_IN_SECONDS', 600);
function bool_to_str($val)
{
    return ($val ? 'true' : 'false') . "\n";
}
require_once 'object-cache.php';
// test wp_cache_init();
wp_cache_init();
global $wp_object_cache;
echo "Cache object exist: " . bool_to_str($wp_object_cache instanceof WP_Object_Cache);
wp_cache_flush();
// test wp_cache_incr and wp_cache_get
wp_cache_incr('integer', 1, 'test-group');
wp_cache_incr('integer', 3, 'test-group');
$r = wp_cache_get('integer', 'test-group');
$rf = wp_cache_get('integer', 'test-group', true);
echo "wp_cache_incr force: " . bool_to_str($r == $rf);
echo "wp_cache_incr: " . bool_to_str($r == 4);
// test wp_cache_decr
wp_cache_decr('integer', 1, 'test-group');
wp_cache_decr('integer', 3, 'test-group');
wp_cache_decr('integer', 1, 'test-group');
$r = wp_cache_get('integer', 'test-group');
$rf = wp_cache_get('integer', 'test-group', true);
echo "wp_cache_decr force: " . bool_to_str($r == $rf);
echo "wp_cache_decr: " . bool_to_str($r == -1);
// test wp_cache_add
$true = wp_cache_add('key', 'value', 'test-group');
$false = wp_cache_add('integer', 'value', 'test-group');
Exemplo n.º 23
0
/**
 * Clear all transients cache for order data.
 *
 * @param int $post_id (default: 0)
 */
function wc_delete_shop_order_transients($post_id = 0)
{
    $post_id = absint($post_id);
    $transients_to_clear = array();
    // Clear report transients
    $reports = WC_Admin_Reports::get_reports();
    foreach ($reports as $report_group) {
        foreach ($report_group['reports'] as $report_key => $report) {
            $transients_to_clear[] = 'wc_report_' . $report_key;
        }
    }
    // clear API report transient
    $transients_to_clear[] = 'wc_admin_report';
    // Clear transients where we have names
    foreach ($transients_to_clear as $transient) {
        delete_transient($transient);
    }
    // Increments the transient version to invalidate cache
    WC_Cache_Helper::get_transient_version('orders', true);
    // Do the same for regular cache
    wp_cache_incr('wc_orders_cache_prefix', 1, 'orders');
    do_action('woocommerce_delete_shop_order_transients', $post_id);
}
Exemplo n.º 24
0
 /**
  * Increment a value in the object cache.
  *
  * @uses	wp_cache_incr
  *
  * @param 	array 			$args				Function arguments.
  * @param 	array 			$assoc_args			Function arguments with parameter key.
  * @return	void
  */
 public function incr($args, $assoc_args)
 {
     if (empty($args)) {
         WP_CLI::line('usage: wp cache incr <key> [offset] [group]');
         exit;
     }
     $key = $args[0];
     $offset = isset($args[1]) ? $args[1] : 1;
     $group = isset($args[2]) ? $args[2] : '';
     $value = wp_cache_incr($key, $offset, $group);
     if (false === $value) {
         WP_CLI::error('The value was not incremented.');
         exit;
     }
     WP_CLI::print_value($value, $assoc_args);
 }
Exemplo n.º 25
0
 /**
  * Clear the key used for wp_cache_get and wp_cache_set
  * Run this when options etc have been changed so fresh values are fetched upon next get
  */
 function clear_caches()
 {
     do_action("simple_fields_clear_caches");
     $prev_key = $this->ns_key;
     $this->ns_key = wp_cache_incr('simple_fields_namespace_key', 1, 'simple_fields');
     // this can consume lots of memory if we for example use set_value a lot because
     // it gets all field values and such and then increase the namespace key, bloating up the memory
     // kinda correct, but kinda too much memory
     // this is perhaps naughty, but will work: get all keys belonging to simple fields and just remove them
     global $wp_object_cache;
     if (isset($wp_object_cache->cache["simple_fields"])) {
         // cache exists for simple fields
         // remove all keys
         $wp_object_cache->cache["simple_fields"] = array();
     }
     if ($this->ns_key === FALSE) {
         // I really don't know why, but wp_cache_incr returns false...always or sometimes?
         // Manually update namespace key by one
         $this->ns_key = $prev_key + 1;
         wp_cache_set('simple_fields_namespace_key', $this->ns_key, 'simple_fields');
     }
     // echo "clear_key";var_dump($this->ns_key);
 }
 /**
  * Clear the key used for wp_cache_get and wp_cache_set
  * Run this when options etc have been changed so fresh values are fetched upon next get
  */
 function clear_caches()
 {
     $prev_key = $this->ns_key;
     $this->ns_key = wp_cache_incr('simple_fields_namespace_key', 1, 'simple_fields');
     if ($this->ns_key === FALSE) {
         // I really don't know why, but wp_cache_incr returns false...always or sometimes?
         // Manually update namespace key by one
         $this->ns_key = $prev_key + 1;
         wp_cache_set('simple_fields_namespace_key', $this->ns_key, 'simple_fields');
     }
     // echo "clear_key";var_dump($this->ns_key);
 }
Exemplo n.º 27
0
$batcache->permalink = 'http://' . $batcache->keys['host'] . $batcache->keys['path'] . (isset($batcache->keys['query']['p']) ? "?p=" . $batcache->keys['query']['p'] : '');
$batcache->url_key = md5($batcache->permalink);
$batcache->url_version = (int) wp_cache_get("{$batcache->url_key}_version", $batcache->group);
$batcache->configure_groups();
$batcache->do_variants();
$batcache->generate_keys();
// Get the batcache
$batcache->cache = wp_cache_get($batcache->key, $batcache->group);
// Are we only caching frequently-requested pages?
if ($batcache->seconds < 1 || $batcache->times < 2) {
    $batcache->do = true;
} else {
    // No batcache item found, or ready to sample traffic again at the end of the batcache life?
    if (!is_array($batcache->cache) || time() >= $batcache->cache['time'] + $batcache->max_age - $batcache->seconds) {
        wp_cache_add($batcache->req_key, 0, $batcache->group);
        $batcache->requests = wp_cache_incr($batcache->req_key, 1, $batcache->group);
        if ($batcache->requests >= $batcache->times) {
            $batcache->do = true;
        } else {
            $batcache->do = false;
        }
    }
}
// If the document has been updated and we are the first to notice, regenerate it.
if ($batcache->do !== false && isset($batcache->cache['version']) && $batcache->cache['version'] < $batcache->url_version) {
    $batcache->genlock = wp_cache_add("{$batcache->url_key}_genlock", 1, $batcache->group, 10);
}
// Temporary: remove after 2010-11-12. I added max_age to the cache. This upgrades older caches on the fly.
if (!isset($batcache->cache['max_age'])) {
    $batcache->cache['max_age'] = $batcache->max_age;
}
Exemplo n.º 28
0
 /**
  * If the blog post is cross-posted, and comments are redirected from phpBB,
  * this catches posted comments and sends them to the forum
  */
 function post_comment($postID)
 {
     global $phpbb_root_path, $phpEx, $phpbbForum, $auth, $user, $db;
     if (!$this->is_working()) {
         return;
     }
     $wpUserID = 0;
     if ($wpUser = wp_get_current_user()) {
         $wpUserID = $u->ID;
     }
     $requireNameEmail = get_option('require_name_email');
     $fStateChanged = $phpbbForum->foreground();
     $dets = $this->get_xposted_details($postID);
     if (!$dets) {
         $phpbbForum->restore_state($fStateChanged);
         return;
     }
     $isValidEmail = true;
     $guestPosting = false;
     if ($phpbbForum->user_logged_in()) {
         $username = $phpbbForum->get_username();
         $website = $phpbbForum->get_userdata('user_website');
         $email = $phpbbForum->get_userdata('user_email');
     } else {
         $guestPosting = true;
         $username = strip_tags(stripslashes(request_var('author', 'Anonymous')));
         $website = request_var('url', '');
         $email = request_var('email', '');
         if ($email) {
             // use wordpress to sanitize email
             $phpbbForum->background();
             $isValidEmail = is_email($email);
             $phpbbForum->foreground();
         }
         $username = wpu_find_next_avail_name($username, 'phpbb');
     }
     if (empty($dets['topic_approved'])) {
         $phpbbForum->restore_state($fStateChanged);
         wp_die($phpbbForum->lang['ITEM_LOCKED']);
     }
     if ($dets['topic_status'] == ITEM_LOCKED) {
         $phpbbForum->restore_state($fStateChanged);
         wp_die($phpbbForum->lang['TOPIC_LOCKED']);
     }
     if ($dets['forum_id'] == 0) {
         // global announcement
         if (!$auth->acl_getf_global('f_wpu_xpost_comment')) {
             $phpbbForum->restore_state($fStateChanged);
             wp_die(__('You do not have permission to respond to this announcement', 'wp-united'));
         }
     } else {
         if (!$auth->acl_get('f_wpu_xpost_comment', $dets['forum_id'])) {
             $phpbbForum->restore_state($fStateChanged);
             wp_die(__('You do not have permission to comment in this forum', 'wp-united'));
         }
     }
     $content = isset($_POST['comment']) ? trim($_POST['comment']) : null;
     if (empty($content)) {
         $phpbbForum->restore_state($fStateChanged);
         wp_die(__('Error: Please type a comment!', 'wp-united'));
     }
     // taken from wp-comment-post.php, native WP translation of strings
     if ($requireNameEmail && $guestPosting) {
         if (6 > strlen($email) || '' == $username) {
             wp_die(__('<strong>ERROR</strong>: please fill in the required fields (name, email).', 'wp-united'));
         } elseif (!$isValidEmail) {
             wp_die(__('<strong>ERROR</strong>: please enter a valid email address.', 'wp-united'));
         }
     }
     $commentParent = (int) request_var('comment_parent', 0);
     // create a wordpress comment and run some checks on it
     // send comment thru akismet, other spam filtering, if user is logged out
     $phpbbForum->background();
     $commentData = array('comment_post_ID' => $postID, 'comment_author' => $username, 'comment_author_email' => $email, 'comment_author_url' => $website, 'comment_parent' => $commentParent, 'comment_type' => '', 'user_ID' => $wpUserID);
     $checkSpam = $this->get_setting('xpostspam');
     $checkSpam = !empty($checkSpam);
     if ($guestPosting && $checkSpam) {
         $commentData = apply_filters('preprocess_comment', $commentData);
     }
     $commentData = array_merge($commentData, array('comment_author_IP' => preg_replace('/[^0-9a-fA-F:., ]/', '', $_SERVER['REMOTE_ADDR']), 'comment_agent' => substr($_SERVER['HTTP_USER_AGENT'], 0, 254), 'comment_date' => current_time('mysql'), 'comment_date_gmt' => current_time('mysql', 1), 'comment_karma' => 0));
     $forceModeration = false;
     $overrideApproval = false;
     if ($guestPosting && $checkSpam) {
         $commentData['comment_approved'] = wp_allow_comment($commentData);
         if (!$commentData['comment_approved'] || $commentData['comment_approved'] == 'spam') {
             $forceModeration = true;
         } else {
             // if the comment has passed checks, and we are overriding phpBB approval settings
             if ($this->get_setting('xpostspam') == 'all') {
                 $overrideApproval = true;
             }
         }
     }
     $phpbbForum->foreground();
     wpu_html_to_bbcode($content);
     $content = utf8_normalize_nfc($content);
     $uid = $poll = $bitfield = $options = '';
     generate_text_for_storage($content, $uid, $bitfield, $options, true, true, true);
     require_once $phpbb_root_path . 'includes/functions_posting.' . $phpEx;
     $subject = $dets['post_subject'];
     $data = array('forum_id' => $dets['forum_id'], 'topic_id' => $dets['topic_id'], 'icon_id' => false, 'enable_bbcode' => true, 'enable_smilies' => true, 'enable_urls' => true, 'enable_sig' => true, 'message' => $content, 'message_md5' => md5($content), 'bbcode_bitfield' => $bitfield, 'bbcode_uid' => $uid, 'post_edit_locked' => 0, 'notify_set' => false, 'notify' => false, 'post_time' => 0, 'forum_name' => '', 'enable_indexing' => true, 'topic_title' => $subject, 'post_approved' => 1, 'poster_ip' => '');
     if ($forceModeration) {
         $data['force_approved_state'] = false;
     } else {
         if ($overrideApproval) {
             $data['force_approved_state'] = true;
         }
     }
     $postUrl = submit_post('reply', $subject, $username, POST_NORMAL, $poll, $data);
     // update threading and guest post user data
     if ($postUrl !== false) {
         if ($commentParent || $guestPosting) {
             $sql = 'UPDATE ' . POSTS_TABLE . " SET \n\t\t\t\t\t\tpost_wpu_xpost_parent = {$commentParent}, \n\t\t\t\t\t\tpost_wpu_xpost_meta1 = '" . $db->sql_escape($website) . "', \n\t\t\t\t\t\tpost_wpu_xpost_meta2 = '" . $db->sql_escape($email) . "' \n\t\t\t\t\t\tWHERE post_id = " . (int) $data['post_id'];
             $db->sql_query($sql);
         }
     }
     $commentData = array_merge($commentData, array('comment_ID' => $data['post_id'] + $this->integComments->get_id_offset()));
     $wpComment = (object) $commentData;
     $phpbbForum->restore_state($fStateChanged);
     //set comment cookie
     do_action('set_comment_cookies', $wpComment, $wpUser);
     //prime the comment cache
     if (function_exists('wp_cache_incr')) {
         wp_cache_incr('last_changed', 1, 'comment');
     } else {
         $last_changed = wp_cache_get('last_changed', 'comment');
         wp_cache_set('last_changed', $last_changed + 1, 'comment');
     }
     /**
      * Redirect back to WP if we can.
      * NOTE: if the comment was the first on a new page, this will redirect to the old page, rather than the new
      * one. 
      * @todo: increment page var if necessary, or remove it if comment order is reversed, by adding hidden field with # of comments
      */
     if (!empty($_POST['redirect_to'])) {
         $location = $_POST['redirect_to'] . '#comment-' . $wpComment->comment_ID;
     } else {
         if (!empty($_POST['wpu-comment-redirect'])) {
             $location = urldecode($_POST['wpu-comment-redirect']);
         }
     }
     $location = apply_filters('comment_post_redirect', $location, $wpComment);
     wp_safe_redirect($location);
     exit;
 }
 /**
  * Increment group cache prefix (invalidates cache).
  * @param  string $group
  */
 public static function incr_cache_prefix($group)
 {
     wp_cache_incr('wc_' . $group . '_cache_prefix', 1, $group);
 }
 /**
  * Flushes the cache by incrementing the cache group
  */
 function flush_cache()
 {
     // Cache flushes have been disabled
     if (!$this->do_flush_cache) {
         return;
     }
     // Bail on post preview
     if (is_admin() && isset($_POST['wp-preview']) && 'dopreview' == $_POST['wp-preview']) {
         return;
     }
     // Bail on autosave
     if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
         return;
     }
     // We already flushed once this page load, and have not put anything into the cache since.
     // OTHER processes may have put something into the cache!  In theory, this could cause stale caches.
     // We do this since clean_post_cache() (which fires the action this method attaches to) is called RECURSIVELY for all descendants.
     //		if ( !$this->need_to_flush_cache )
     //			return;
     $this->cache_incr = wp_cache_incr('advanced_post_cache', 1, 'cache_incrementors');
     if (10 < strlen($this->cache_incr)) {
         wp_cache_set('advanced_post_cache', 0, 'cache_incrementors');
         $this->cache_incr = 0;
     }
     $this->cache_group = $this->CACHE_GROUP_PREFIX . $this->cache_incr;
     $this->need_to_flush_cache = false;
 }