Configure the session handler to use the Memcache API.
@param MemcacheContainer $memcacheContainer Optional, for mocking in tests
427956
public static function configure($memcacheContainer = null) {
    $handler = new MemcacheSessionHandler($memcacheContainer);

    session_set_save_handler($handler, true);

    /**
     * Set so that it is clear that Memcache is being used for session handling,
     * as retrieving session.save_handler just returns "user".
     */
    session_save_path("Memcache");
  }
1249383
public function getSetSessionHandlerMiddleware(ContainerInterface $container): SetSessionHandlerMiddleware
    {
        $handler = $container->get(SessionHandlerInterface::class);

        return new SetSessionHandlerMiddleware($handler);
    }
489449
public void set(long value) throws MemcachedException, InterruptedException, TimeoutException {
    this.memcachedClient.set(this.key, 0, String.valueOf(value));
  }
40262
public static function 
    {

        if (self::$memcached) {
            return;
        }

        self::$memcached = new \Memcached();

        foreach (self::$config['memcached']['servers'] as $server) {
            extract(array_merge(self::$memcachedServerDefaults, $server));

            self::$memcached->addServers($host, $port, $persistent, $weight, $timeout);
        }
    }
61082
public function init() {
        if (!extension_loaded('memcached')) {
            throw new exception('sessionhandlerproblem', 'error', '', null, 'memcached extension is not loaded');
        }
        $version = phpversion('memcached');
        if (!$version or version_compare($version, '2.0') < 0) {
            throw new exception('sessionhandlerproblem', 'error', '', null, 'memcached extension version must be at least 2.0');
        }
        if (empty($this->savepath)) {
            throw new exception('sessionhandlerproblem', 'error', '', null, '$CFG->session_memcached_save_path must be specified in config.php');
        }

        ini_set('session.save_handler', 'memcached');
        ini_set('session.save_path', $this->savepath);
        ini_set('memcached.sess_prefix', $this->prefix);
        ini_set('memcached.sess_locking', '1'); // Locking is required!
        ini_set('memcached.sess_lock_expire', $this->lockexpire);

        if (version_compare($version, '3.0.0-dev') >= 0) {
            // With memcached 3.x (PHP 7) we configure the max retries to make and the time to sleep between each retry.
            // There are two sleep config values, an initial and a max value.
            // After each attempt the memcached module adjusts the sleep value to be the lesser of the configured max
            // value, or 2X the previous value.
            // With default memcached.ini configs (5, 1s, 2s) the result is only 5 attempts to lock over 9 sec.
            // To mimic the behavior of the 2.2.x module so we get more attempts and much more frequently, config both
            // sleep values to the old default value of 150 msec (making it constant) and calculate number of retries
            // using the existing Moodle config $CFG->session_memcached_acquire_lock_timeout.
            // Doing this so admins configure session lock attempt timeout in familiar terms, and more straight-forward
            // to detect if lock attempt timeout has occurred in start().
            // If _min and _max values are not equal, the actual lock acquire timeout will not be the expected
            // configured value in $CFG->session_memcached_acquire_lock_timeout; this will cause session data loss when
            // failure to acquire the lock is not detected.
            ini_set('memcached.sess_lock_wait_min', $this->lockretrysleep);
            ini_set('memcached.sess_lock_wait_max', $this->lockretrysleep);
            ini_set('memcached.sess_lock_retries', (int)(($this->acquiretimeout * 1000) / $this->lockretrysleep) + 1);
        } else {
            // With memcached 2.2.x we configure max time to attempt lock, and accept default value (in memcached.ini)
            // for sleep time between each attempt (usually 150 msec), then memcached calculates the max number of
            // retries to make.
            ini_set('memcached.sess_lock_max_wait', $this->acquiretimeout);
        }

    }
526580
public function set(CacheKey $key, $value, $sessionLength = null) {

		if ($sessionLength == null) {
			$sessionLength = $this->timeThreshold;
		}

		apc_store ( $this->getKey($key) , $value , $sessionLength);
	}
1026154
protected function configureCluster(InputInterface $input, OutputInterface $output, array $cluster)
    {
        global $APPLICATION;

        if (!Loader::includeModule('cluster')) {
            throw new \Exception('Failed to load module "cluster"');
        }

        $memcache = new \CClusterMemcache;

        if (isset($cluster['memcache'])) {
            $output->writeln('   <comment>memcache</comment>');

            if (!is_array($cluster['memcache'])) {
                throw new \Exception('Server info must be an array');
            }

            $rsServers = $memcache->GetList();

            while ($server = $rsServers->Fetch()) {
                $memcache->Delete($server['ID']);
            }

            foreach ($cluster['memcache'] as $index => $server) {
                $serverId = $memcache->Add($server);

                if ($serverId && !$input->getOption('memcache-cold-start')) {
                    $memcache->Resume($serverId);
                } else {
                    $exception = $APPLICATION->GetException();
                    $message = 'Invalid memcache config with index ' . $index;

                    if ($exception->GetString()) {
                        $message = str_replace('<br>', "\n", $exception->GetString());
                    }

                    $output->writeln('<error>' . $message . '</error>');
                }
            }
        }
    }
866426
protected function initializeContainer()
    {
        $class = $this->getContainerClass();
        $cacheDir = $this->warmupDir ?: $this->getCacheDir();
        $cache = new ConfigCache($cacheDir.'/'.$class.'.php', $this->debug);
        $oldContainer = null;
        if ($fresh = $cache->isFresh()) {
            // Silence E_WARNING to ignore "include" failures - don't use "@" to prevent silencing fatal errors
            $errorLevel = error_reporting(\E_ALL ^ \E_WARNING);
            $fresh = $oldContainer = false;
            try {
                if (file_exists($cache->getPath()) && \is_object($this->container = include $cache->getPath())) {
                    $this->container->set('kernel', $this);
                    $oldContainer = $this->container;
                    $fresh = true;
                }
            } catch (\Throwable $e) {
            } catch (\Exception $e) {
            } finally {
                error_reporting($errorLevel);
            }
        }

        if ($fresh) {
            return;
        }

        if ($this->debug) {
            $collectedLogs = [];
            $previousHandler = \defined('PHPUNIT_COMPOSER_INSTALL');
            $previousHandler = $previousHandler ?: set_error_handler(function ($type, $message, $file, $line) use (&$collectedLogs, &$previousHandler) {
                if (E_USER_DEPRECATED !== $type && E_DEPRECATED !== $type) {
                    return $previousHandler ? $previousHandler($type, $message, $file, $line) : false;
                }

                if (isset($collectedLogs[$message])) {
                    ++$collectedLogs[$message]['count'];

                    return;
                }

                $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5);
                // Clean the trace by removing first frames added by the error handler itself.
                for ($i = 0; isset($backtrace[$i]); ++$i) {
                    if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) {
                        $backtrace = \array_slice($backtrace, 1 + $i);
                        break;
                    }
                }
                // Remove frames added by DebugClassLoader.
                for ($i = \count($backtrace) - 2; 0 < $i; --$i) {
                    if (DebugClassLoader::class === ($backtrace[$i]['class'] ?? null)) {
                        $backtrace = [$backtrace[$i + 1]];
                        break;
                    }
                }

                $collectedLogs[$message] = [
                    'type' => $type,
                    'message' => $message,
                    'file' => $file,
                    'line' => $line,
                    'trace' => [$backtrace[0]],
                    'count' => 1,
                ];
            });
        }

        try {
            $container = null;
            $container = $this->buildContainer();
            $container->compile();
        } finally {
            if ($this->debug && true !== $previousHandler) {
                restore_error_handler();

                file_put_contents($cacheDir.'/'.$class.'Deprecations.log', serialize(array_values($collectedLogs)));
                file_put_contents($cacheDir.'/'.$class.'Compiler.log', null !== $container ? implode("\n", $container->getCompiler()->getLog()) : '');
            }
        }

        if (null === $oldContainer && file_exists($cache->getPath())) {
            $errorLevel = error_reporting(\E_ALL ^ \E_WARNING);
            try {
                $oldContainer = include $cache->getPath();
            } catch (\Throwable $e) {
            } catch (\Exception $e) {
            } finally {
                error_reporting($errorLevel);
            }
        }
        $oldContainer = \is_object($oldContainer) ? new \ReflectionClass($oldContainer) : false;

        $this->dumpContainer($cache, $container, $class, $this->getContainerBaseClass());
        $this->container = require $cache->getPath();
        $this->container->set('kernel', $this);

        if ($oldContainer && \get_class($this->container) !== $oldContainer->name) {
            // Because concurrent requests might still be using them,
            // old container files are not removed immediately,
            // but on a next dump of the container.
            static $legacyContainers = [];
            $oldContainerDir = \dirname($oldContainer->getFileName());
            $legacyContainers[$oldContainerDir.'.legacy'] = true;
            foreach (glob(\dirname($oldContainerDir).\DIRECTORY_SEPARATOR.'*.legacy') as $legacyContainer) {
                if (!isset($legacyContainers[$legacyContainer]) && @unlink($legacyContainer)) {
                    (new Filesystem())->remove(substr($legacyContainer, 0, -7));
                }
            }

            touch($oldContainerDir.'.legacy');
        }

        if ($this->container->has('cache_warmer')) {
            $this->container->get('cache_warmer')->warmUp($this->container->getParameter('kernel.cache_dir'));
        }
    }
548862
private function connect()
	{
		// We want to only create the driver once.
		if ($this->driver)
		{
			return;
		}

		$pool = $this->options['memcache.pool'];

		if ($pool)
		{
			$this->driver = new \Memcached($pool);
		}
		else
		{
			$this->driver = new \Memcached;
		}

		$this->driver->setOption(\Memcached::OPT_COMPRESSION, $this->options['memcache.compress'] ?: false);
		$this->driver->setOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
		$serverList = $this->driver->getServerList();

		// If we are using a persistent pool we don't want to add the servers again.
		if (empty($serverList))
		{
			$servers = $this->options['memcache.servers'] ?: array();

			foreach ($servers as $server)
			{
				$this->driver->addServer($server->host, $server->port);
			}
		}
	}
63184
private function configCache(): ConfigCache
    {
        if (null === $this->configCache)
        {
            $this->configCache = new ConfigCache($this->getContainerClassPath(), $this->environment->isDebug());
        }

        return $this->configCache;
    }
1157671
protected void reconnect(MemcachedTCPSession session) {
    if (!this.client.isShutdown()) {
      // Prevent reconnecting repeatedly
      synchronized (session) {
        if (!session.isAllowReconnect()) {
          return;
        }
        session.setAllowReconnect(false);
      }
      MemcachedSession memcachedTCPSession = session;
      InetSocketAddressWrapper inetSocketAddressWrapper =
          memcachedTCPSession.getInetSocketAddressWrapper();
      this.client.getConnector().addToWatingQueue(
          new ReconnectRequest(inetSocketAddressWrapper, 0, this.client.getHealSessionInterval()));
    }
  }
599664
public static function configureContainer(LimoncelloContainerInterface $container): void
    {
        $container[CookieJarInterface::class] =
            function (PsrContainerInterface $container): CookieJarInterface {
                $settings = $container->get(SettingsProviderInterface::class)->get(CookieSettings::class);

                return new CookieJar(
                    $settings[CookieSettings::KEY_DEFAULT_PATH],
                    $settings[CookieSettings::KEY_DEFAULT_DOMAIN],
                    $settings[CookieSettings::KEY_DEFAULT_IS_SEND_ONLY_OVER_SECURE_CONNECTION],
                    $settings[CookieSettings::KEY_DEFAULT_IS_ACCESSIBLE_ONLY_THROUGH_HTTP],
                    $settings[CookieSettings::KEY_DEFAULT_IS_RAW]
                );
            };

        $container[CookieFunctionsInterface::class] =
            function (PsrContainerInterface $container): CookieFunctionsInterface {
                return new CookieFunctions();
            };
    }
1026831
public static function set($cacheloc, $cachekey, $cacheval, $expiresec=false)
    {
        $cacheloc = "cache_" . $cacheloc;
        if ( $cacheval === null || $cacheval === false ) {
            unset($_SESSION[$cacheloc]);
            return;
        }
        if ( $expiresec !== false ) $expiresec = time() + $expiresec;
        $_SESSION[$cacheloc] = array($cachekey, $cacheval, $expiresec);
    }
186329
protected function addMemcacheServers($cache, $servers)
    {
        $class = new \ReflectionClass($cache);
        $paramCount = $class->getMethod('addServer')->getNumberOfParameters();
        foreach ($servers as $server) {
            // $timeout is used for memcache versions that do not have $timeoutms parameter
            $timeout = (int) ($server->timeout / 1000) + (($server->timeout % 1000 > 0) ? 1 : 0);
            if ($paramCount === 9) {
                $cache->addServer(
                    $server->host,
                    $server->port,
                    $server->persistent,
                    $server->weight,
                    $timeout,
                    $server->retryInterval,
                    $server->status,
                    $server->failureCallback,
                    $server->timeout
                );
            } else {
                $cache->addServer(
                    $server->host,
                    $server->port,
                    $server->persistent,
                    $server->weight,
                    $timeout,
                    $server->retryInterval,
                    $server->status,
                    $server->failureCallback
                );
            }
        }
    }
42876
public function write($id, $data) {
    // TODO: Implement locking. b/7701850
    return $this->memcacheContainer->set(
        self::SESSION_PREFIX . $id, $data, $this->expire);
  }
97108
private function initializeMemCached()
    {
        $this->memcached = new \Memcached();

        // support multiple hosts using semicolon to separate hosts
        $hosts = explode(';', $this->host);

        // different ports for each hosts the same way
        $ports = explode(';', $this->port);

        if (count($ports) < 1) {
            $ports = array_fill(0, count($hosts), self::DEFAULT_PORT);
        } elseif (count($ports) === 1) {
            // if we have just one port, use it for all hosts
            $usedPort = $ports[0];
            $ports    = array_fill(0, count($hosts), $usedPort);
        }

        foreach ($hosts as $i => $host) {
            if (!isset($ports[$i])) {
                /*
                 * if we have a difference between the count of hosts and
                 * the count of ports, use the default port to fill the gap
                 */
                $ports[$i] = self::DEFAULT_PORT;
            }

            $this->memcached->addServer($host, $ports[$i]);
        }
    }
1186129
public function haveInMemcached($key, $value, $expiration = null)
    {
        switch (get_class($this->memcache)) {
            case 'Memcache':
                $this->assertTrue($this->memcache->set($key, $value, null, $expiration));
                break;
            case 'Memcached':
                $this->assertTrue($this->memcache->set($key, $value, $expiration));
                break;
        }
    }