Cleans up the expired tokens after writing
497016
protected function onAfterWrite() {
        parent::onAfterWrite();
        
        
        //Clean up the expired tokens
        $expiredTokens=KapostPreviewToken::get()->filter('Created:LessThan', date('Y-m-d H:i:s', strtotime('-'.KapostService::config()->preview_token_expiry.' minutes')));
        if($expiredTokens->count()>0) {
            foreach($expiredTokens as $token) {
                $token->delete();
            }
        }
    }
840097
public void purge() {
        long time = System.currentTimeMillis();
        if (time - latestWriteTime > expireMillis) {
            // Everything in the map is expired, clear all at once
            map.clear();
        } else {
            // Iterate and remove until the first non-expired token
            Iterator<Value> values = map.values().iterator();
            while (values.hasNext()) {
                if (time >= values.next().expire) {
                    values.remove();
                } else {
                    break;
                }
            }
        }
    }
421397
def clean_up(group, identifier, date):
    
    #log.error('exception raised, cleaning up files.')
    glob_pat = '{g}.{d}.mbox*'.format(g=group, d=date)
    for f in glob(glob_pat):
        #log.error('removing {f}'.format(f=f))
        try:
            os.remove(f)
        except OSError:
            continue
    glob_pat = '{id}_state.json'.format(id=identifier)
    for f in glob(glob_pat):
        #log.error('removing {f}'.format(f=f))
        try:
            os.remove(f)
        except OSError:
            continue
    return True
255555
def cleanup_full_hashes(self, keep_expired_for=(60 * 60 * 12)):
        """"""
        q = '''DELETE FROM full_hash WHERE expires_at < datetime(current_timestamp, '-{} SECONDS')
        '''
        log.info('Cleaning up full_hash entries expired more than {} seconds ago.'.format(keep_expired_for))
        with self.get_cursor() as dbc:
            dbc.execute(q.format(int(keep_expired_for)))
1107247
def cleanup(self):
        """"""
        keys = self.client.smembers(self.keys_container)
        for key in keys:
            entry = self.client.get(key)
            if entry:
                entry = pickle.loads(entry)
                if self._is_expired(entry, self.timeout):
                    self.delete_entry(key)
347237
protected function cleanupOldChunks()
    {
        if ($this->useChunks === false) {
            // We have no write access. Do nothing.
            return;
        }

        static $beenHere = false;

        // We only do this once.
        if ($beenHere === true) {
            return;
        }

        $beenHere = true;
        // Clean up leftover files.
        $chunkList = glob($this->chunkDir . '*.Krexx.tmp');
        if (empty($chunkList) === false) {
            $now = time();
            foreach ($chunkList as $file) {
                // We delete everything that is older than 15 minutes.
                if (($this->pool->fileService->filetime($file) + 900) < $now) {
                    $this->pool->fileService->deleteFile($file);
                }
            }
        }
    }
1028846
private function cleanup()
    {
        if (isset($this->collection[$this->id_info])) {
            foreach ($this->collection[$this->id_info] as $key => $val) {
                $expire = $this->getSessionInfo($key, 'expire');
                if ($expire === true) {
                    $this->setSessionInfo($key, 'expire', -1);
                } elseif ($expire == -1) {
                    $this->delete($key);
                }
            }
        }
    }
605354
public function cleanExpiredTokens($expiryTime)
    {
        foreach (glob($this->path.DIRECTORY_SEPARATOR."*".$this->suffix) as $file) {
            if (filemtime($file) < $expiryTime) {
                unlink($file);
            }
        }
    }
372469
def _strip(self, tokens, criteria, prop, rev=False):
        """"""
        num = len(tokens)
        res = []
        for i, token in enumerate(reversed(tokens) if rev else tokens):
            if criteria(token) and num > i + 1:
                res.insert(0, tokens.pop()) if rev else res.append(tokens.pop(0))
            else:
                break
        if res:
            self[prop] = self._clean(' '.join(res))
        return tokens
1192743
function harvest() {
  var q = "DELETE FROM tokens WHERE expires_at < now() AT TIME ZONE 'UTC'";
  db.getClient(function(err, client, done) {
    client.query(q, function(err) {
      if(err) {
        console.error(new Date);
        console.error(err.stack);
      }
      done(err);
    });
  });
}
64234
function clean()
    {
        try {
            $this->collection->drop();
        } catch (\Exception $e) {
            throw new exWriteError($e->getMessage(), $e->getCode(), $e);
        }
    }
949564
private void cleanup() {
		CacheEntry oldest = null;
		_count = 0;

		// Cleanup obsolete entries and find the oldest
		for (Map.Entry<String, CacheEntry> e : _cache.entrySet()) {
			String key = e.getKey();
			CacheEntry entry = e.getValue();
			// Remove obsolete entry
			if (entry.isExpired()) {
				_cache.remove(key);
			}
			// Count the remaining entry
			else {
				_count++;
				if (oldest == null || oldest.getExpiration() > entry.getExpiration())
					oldest = entry;
			}
		}

		// Remove the oldest if cache size exceeded maximum
		if (_count > _maxSize && oldest != null) {
			_cache.remove(oldest.getKey());
			_count--;
		}
	}
1168795
def expires_on(self):
    """"""
    timestamp = self._info.get('expirationTime', None)
    if timestamp is None:
      return None
    return _parser.Parser.parse_timestamp(timestamp)
575047
private function cleanExpired()
    {
        // 10% chance to clean the database of expired sessions
        if (mt_rand(1, 10) == 1) {
            $expiredTime = $this->now - $this->secondsUntilExpiration;
            $stmt = $this->db->prepare("DELETE FROM {$this->tableName} WHERE time_updated < {$expiredTime}");
            $stmt->execute();
        }
    }
506378
function stripToken(val, exp) {
    exp = exp || constants_2.TOKEN_ANY_EXP;
    return val.trim().replace(exp, '');
}
889396
public function clear()
    {
        $now = Carbon::now('UTC');

        ORM::for_table('files_downloads')
            ->where_lt('created_at', $now->subHours(SettingsFile::TOKENS_OLDER_THAN_HOURS))
            ->delete_many();
    }
47863
protected function cleanupCsrfTokens()
    {
        // Determine the expiration of the CSRF tokens.
        if (defined('CSRFTOKEN_EXPIRE')) {
            $expiry = intval(CSRFTOKEN_EXPIRE);
        } else {
            // We fall back on 3600 seconds if there is no default expiration time known.
            $expiry = 3600;
        }

        // Check if we have any tokens to clean.
        if (!isset($_SESSION) || !array_key_exists('csrftokens', $_SESSION) ||
            (is_array($_SESSION['csrftokens']) &&
                count($_SESSION['csrftokens']) === 0)
        ) {
            return; // No tokens to clean.
        }

        // Make sure $_SESSION['csrftokens'] is an array.
        if (!is_array($_SESSION['csrftokens'])) {
            // $_SESSION['csrftokens'] is not an array! Reset/initialize $_SESSION['csrftokens'].
            $_SESSION['csrftokens'] = [];
            // It makes no sense to continue here, as we just cleaned the entire CSRF token basket.
            // Return, because we are done here.
            return;
        }

        // Walk through all the tokens.
        foreach ($_SESSION['csrftokens'] as $key => $token) {
            // all tokens are dot-separated with a timestamp and the actual random token
            // we start throwing away tokens here which either do not match this formatting,
            // or have been generated longer than the expiration time we just determined.

            $explodedToken = explode('.', $token, 2);

            // check if the token has a valid formatting (includes a timestamp)
            if (count($explodedToken) !== 2 || !is_numeric($explodedToken[0])) {
                // Can't parse this token. This should not happen... get rid of it!
                unset($_SESSION['csrftokens'][$key]);
                continue;
            }

            // check if the token is expired.
            if ($explodedToken[0] < (time() - $expiry)) {
                // Expired token found. Get rid of it!
                unset($_SESSION['csrftokens'][$key]);
                continue;
            }
        }
    }