PageRenderTime 36ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/concrete/src/Session/SessionFactory.php

http://github.com/concrete5/concrete5
PHP | 378 lines | 206 code | 41 blank | 131 comment | 21 complexity | ca04bf5ec42451ef45dd6f700a707726 MD5 | raw file
Possible License(s): MIT, LGPL-2.1, MPL-2.0-no-copyleft-exception, BSD-3-Clause
  1. <?php
  2. namespace Concrete\Core\Session;
  3. use Concrete\Core\Application\Application;
  4. use Concrete\Core\Database\Connection\Connection;
  5. use Concrete\Core\Http\Request;
  6. use Concrete\Core\Session\Storage\Handler\NativeFileSessionHandler;
  7. use Illuminate\Support\Str;
  8. use Memcached;
  9. use Symfony\Component\HttpFoundation\Session\Session as SymfonySession;
  10. use Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcachedSessionHandler;
  11. use Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler;
  12. use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
  13. use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
  14. use Concrete\Core\Session\Storage\Handler\RedisSessionHandler;
  15. use Redis;
  16. use RedisArray;
  17. /**
  18. * Class SessionFactory
  19. * Base concrete5 session factory.
  20. *
  21. * To add custom handlers, extend this class and for a handler named "custom_test"
  22. * create a protected method `getCustomTestHandler`
  23. */
  24. class SessionFactory implements SessionFactoryInterface
  25. {
  26. protected $app;
  27. /**
  28. * The request object
  29. * We needed a reference to this object so that we could assign the session object to it.
  30. * Instead we are using the $app container to resolve the request at the time the session is created.
  31. * This makes testing a little harder, but ensures we apply the session object to the most accurate request instance.
  32. * Ideally neither would be required, as the operation creating the session would manage associating the two.
  33. *
  34. * @var \Concrete\Core\Session\Request
  35. *
  36. * @deprecated
  37. */
  38. protected $request;
  39. /**
  40. * SessionFactory constructor.
  41. *
  42. * @param \Concrete\Core\Application\Application $app
  43. * @param \Concrete\Core\Http\Request $request @deprecated, will be removed
  44. */
  45. public function __construct(Application $app, Request $request)
  46. {
  47. $this->app = $app;
  48. $this->request = $request;
  49. }
  50. /**
  51. * Create a new symfony session object
  52. * This method MUST NOT start the session.
  53. *
  54. * @return \Symfony\Component\HttpFoundation\Session\Session
  55. *
  56. * @throws \Illuminate\Contracts\Container\BindingResolutionException
  57. */
  58. public function createSession()
  59. {
  60. $config = $this->app['config']['concrete.session'];
  61. $storage = $this->getSessionStorage($config);
  62. // We have to use "build" here because we have bound this classname to this factory method
  63. $session = $this->app->build(SymfonySession::class, [$storage]);
  64. $session->setName(array_get($config, 'name'));
  65. /* @TODO Remove this call. We should be able to set this against the request somewhere much higher than this */
  66. /* At the very least we should have an observer that can track the session status and set this */
  67. $this->app->make(\Concrete\Core\Http\Request::class)->setSession($session);
  68. return $session;
  69. }
  70. /**
  71. * Create and return a newly built file session handler.
  72. *
  73. * @param array $config The `concrete.session` config item
  74. *
  75. * @return \Concrete\Core\Session\Storage\Handler\NativeFileSessionHandler
  76. */
  77. protected function getFileHandler(array $config)
  78. {
  79. return $this->app->make(NativeFileSessionHandler::class, [
  80. array_get($config, 'save_path'),
  81. ]);
  82. }
  83. /**
  84. * Create a new database session handler to handle session.
  85. *
  86. * @param array $config The `concrete.session` config item
  87. *
  88. * @return \Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler
  89. */
  90. protected function getDatabaseHandler(array $config)
  91. {
  92. return $this->app->make(PdoSessionHandler::class, [
  93. $this->app->make(Connection::class)->getWrappedConnection(),
  94. [
  95. 'db_table' => 'Sessions',
  96. 'db_id_col' => 'sessionID',
  97. 'db_data_col' => 'sessionValue',
  98. 'db_time_col' => 'sessionTime',
  99. 'db_lifetime_col' => 'sessionLifeTime',
  100. 'lock_mode' => PdoSessionHandler::LOCK_ADVISORY,
  101. ],
  102. ]);
  103. }
  104. /**
  105. * Return a built Memcached session handler.
  106. *
  107. * @param array $config The `concrete.session` config item
  108. *
  109. * @return \Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcachedSessionHandler
  110. */
  111. protected function getMemcachedHandler(array $config)
  112. {
  113. // Create new memcached instance
  114. $memcached = $this->app->make(Memcached::class, [
  115. 'CCM_SESSION',
  116. null,
  117. ]);
  118. $servers = array_get($config, 'servers', []);
  119. // Add missing servers
  120. foreach ($this->newMemcachedServers($memcached, $servers) as $server) {
  121. $memcached->addServer(
  122. array_get($server, 'host'),
  123. array_get($server, 'port'),
  124. array_get($server, 'weight')
  125. );
  126. }
  127. // Return a newly built handler
  128. return $this->app->make(MemcachedSessionHandler::class, [
  129. $memcached,
  130. ['prefix' => array_get($config, 'name') ?: 'CCM_SESSION'],
  131. ]);
  132. }
  133. /**
  134. * Return the default session handler.
  135. *
  136. * @param array $config The `concrete.session` config item
  137. *
  138. * @return \Concrete\Core\Session\Storage\Handler\NativeFileSessionHandler
  139. */
  140. protected function getDefaultHandler(array $config)
  141. {
  142. return $this->getFileHandler($config);
  143. }
  144. /**
  145. * Get a session storage object based on configuration.
  146. *
  147. * @param array $config
  148. *
  149. * @return \Symfony\Component\HttpFoundation\Session\Storage\SessionStorageInterface
  150. */
  151. private function getSessionStorage(array $config)
  152. {
  153. $app = $this->app;
  154. // If we're running through command line, just early return an in-memory storage
  155. if ($app->isRunThroughCommandLineInterface()) {
  156. return $app->make(MockArraySessionStorage::class);
  157. }
  158. // Resolve the handler based on config
  159. $handler = $this->getSessionHandler($config);
  160. $storage = $app->make(NativeSessionStorage::class, [[], $handler]);
  161. // Initialize the storage with some options
  162. $options = array_get($config, 'cookie', []) + [
  163. 'gc_maxlifetime' => (int) array_get($config, 'max_lifetime') ?: (int) ini_get('session.gc_maxlifetime') ?: 7200,
  164. 'gc_probability' => (int) array_get($config, 'gc_probability') ?: (int) ini_get('session.gc_probability') ?: 1,
  165. 'gc_divisor' => (int) array_get($config, 'gc_divisor') ?: (int) ini_get('session.gc_divisor') ?: 100,
  166. ];
  167. if (array_get($options, 'cookie_path', false) === false) {
  168. $options['cookie_path'] = $app['app_relative_path'] . '/';
  169. }
  170. $storage->setOptions($options);
  171. return $app->make(Storage\LoggedStorage::class, [$storage]);
  172. }
  173. /**
  174. * Get a new session handler.
  175. *
  176. * @param array $config The config from our config repository
  177. *
  178. * @return \SessionHandlerInterface
  179. *
  180. * @throws \RuntimeException When a configured handler does not exist
  181. */
  182. private function getSessionHandler(array $config)
  183. {
  184. $handler = array_get($config, 'handler', 'default');
  185. // Build handler using a matching method "get{Type}Handler"
  186. $method = Str::camel("get_{$handler}_handler");
  187. if (method_exists($this, $method)) {
  188. return $this->{$method}($config);
  189. }
  190. /*
  191. * @todo Change this to return an exception if an unsupported handler is configured. This makes it easier to get
  192. * configuration dialed in properly
  193. */
  194. //throw new \RuntimeException(t('Unsupported session handler "%s"', $handler));
  195. // Return the default session handler by default
  196. return $this->getSessionHandler(['handler' => 'default'] + $config);
  197. }
  198. /**
  199. * Generator for only returning hosts that aren't already added to the memcache instance.
  200. *
  201. * @param \Memcached $memcached
  202. * @param array $servers The servers as described in config
  203. *
  204. * @return \Generator|string[] [ $host, $port, $weight ]
  205. */
  206. private function newMemcachedServers(Memcached $memcached, array $servers)
  207. {
  208. $serverIndex = [];
  209. $existingServers = $memcached->getServerList();
  210. foreach ($existingServers as $server) {
  211. $serverIndex[$server['host'] . ':' . $server['port']] = true;
  212. }
  213. foreach ($servers as $configServer) {
  214. $server = [
  215. 'host' => array_get($configServer, 'host', ''),
  216. 'port' => array_get($configServer, 'port', 11211),
  217. 'weight' => array_get($configServer, 'weight', 0),
  218. ];
  219. if (!isset($serverIndex[$server['host'] . ':' . $server['port']])) {
  220. yield $server;
  221. }
  222. }
  223. }
  224. /**
  225. * Return a built Redis session handler.
  226. *
  227. * @param array $config The `concrete.session` config item
  228. *
  229. * @return \Concrete\Core\Session\Storage\Handler\RedisSessionHandler
  230. */
  231. protected function getRedisHandler(array $config)
  232. {
  233. $options = array_get($config, 'redis', []);
  234. // In case anyone puts the servers under redis configuration - similar to how we handle cache
  235. $servers = array_get($options, 'servers', []);
  236. if (empty($servers)) {
  237. $servers = array_get($config, 'servers', []);
  238. }
  239. $redis = $this->getRedisInstance($servers);
  240. if (!empty($options['database'])) {
  241. $redis->select((int) $options['database']);
  242. }
  243. // In case of anyone setting prefix on the redis server directly
  244. // Similar to how we do it on cache
  245. $prefix = array_get($options, 'prefix', 'CCM_SESSION');
  246. // We pass the prefix to the Redis Handler when we build it
  247. return $this->app->make(RedisSessionHandler::class, [$redis, ['prefix' => array_get($config, 'name') ?: $prefix]]);
  248. }
  249. /**
  250. * Decides whether to return a Redis Instance or RedisArray Instance depending on the number of servers passed to it.
  251. *
  252. * @param array $servers The `concrete.session.servers` or `concrete.session.redis.servers` config item
  253. *
  254. * @return \Redis | \RedisArray
  255. */
  256. private function getRedisInstance(array $servers)
  257. {
  258. if (count($servers) == 1) {
  259. // If we only have one server in our array then we just reconnect to it
  260. $server = $servers[0];
  261. $redis = $this->app->make(Redis::class);
  262. if (isset($server['socket']) && $server['socket']) {
  263. $redis->connect($server['socket']);
  264. } else {
  265. $host = array_get($server, 'host', '');
  266. $port = array_get($server, 'port', 6379);
  267. $ttl = array_get($server, 'ttl', 0.5);
  268. // Check for both server/host - fallback due to cache using server
  269. $host = !empty($host) ? $host : array_get($server, 'server', '127.0.0.1');
  270. $redis->connect($host, $port, $ttl);
  271. }
  272. // Authorisation is handled by just a password
  273. if (isset($server['password'])) {
  274. $redis->auth($server['password']);
  275. }
  276. } else {
  277. $serverArray = [];
  278. $ttl = 0.5;
  279. $password = null;
  280. foreach ($this->getRedisServers($servers) as $server) {
  281. $serverString = $server['server'];
  282. if (isset($server['port'])) {
  283. $serverString .= ':' . $server['port'];
  284. }
  285. // We can only use one ttl for connection timeout so use the last set ttl
  286. // isset allows for 0 - unlimited
  287. if (isset($server['ttl'])) {
  288. $ttl = $server['ttl'];
  289. }
  290. if (isset($server['password'])) {
  291. $password = $server['password'];
  292. }
  293. $serverArray[] = $serverString;
  294. }
  295. $options = ['connect_timeout' => $ttl];
  296. if ($password !== null) {
  297. $options['auth'] = $password;
  298. }
  299. $redis = $this->app->make(RedisArray::class, [$serverArray, $options]);
  300. }
  301. return $redis;
  302. }
  303. /**
  304. * Generator for Redis Array.
  305. *
  306. * @param array $servers The `concrete.session.servers` or `concrete.session.redis.servers` config item
  307. *
  308. * @return \Generator| string[] [ $server, $port, $ttl ]
  309. */
  310. private function getRedisServers(array $servers)
  311. {
  312. if (!empty($servers)) {
  313. foreach ($servers as $server) {
  314. if (isset($server['socket'])) {
  315. $server = [
  316. 'server' => array_get($server, 'socket', ''),
  317. 'ttl' => array_get($server, 'ttl', null),
  318. 'password' => array_get($server, 'password', null),
  319. ];
  320. } else {
  321. $host = array_get($server, 'host', '');
  322. // Check for both server/host - fallback due to cache using server
  323. $host = !empty($host) ?: array_get($server, 'server', '127.0.0.1');
  324. $server = [
  325. 'server' => $host,
  326. 'port' => array_get($server, 'port', 11211),
  327. 'ttl' => array_get($server, 'ttl', null),
  328. 'password' => array_get($server, 'password', null),
  329. ];
  330. }
  331. yield $server;
  332. }
  333. } else {
  334. yield ['server' => '127.0.0.1', 'port' => '6379', 'ttl' => 0.5];
  335. }
  336. }
  337. }