first commit

This commit is contained in:
2025-06-17 11:53:18 +02:00
commit 9f0f7ba12b
8804 changed files with 1369176 additions and 0 deletions

View File

@ -0,0 +1,116 @@
local volumes = [
{
name: "composer-cache",
path: "/tmp/composer-cache",
},
];
local hostvolumes = [
{
name: "composer-cache",
host: {path: "/tmp/composer-cache"}
},
];
local composer(phpversion, params) = {
name: "composer",
image: "joomlaprojects/docker-images:php" + phpversion,
volumes: volumes,
commands: [
"php -v",
"composer update " + params,
]
};
local phpunit(phpversion) = {
name: "PHPUnit",
image: "joomlaprojects/docker-images:php" + phpversion,
[if phpversion == "8.3" then "failure"]: "ignore",
commands: ["vendor/bin/phpunit"]
};
local pipeline(name, phpversion, params) = {
kind: "pipeline",
name: "PHP " + name,
volumes: hostvolumes,
steps: [
composer(phpversion, params),
phpunit(phpversion)
],
services: [
{
name: "memcached",
image: "memcached:alpine"
},
{
name:"redis",
image: "redis:alpine"
}
]
};
[
{
kind: "pipeline",
name: "Codequality",
volumes: hostvolumes,
steps: [
{
name: "composer",
image: "joomlaprojects/docker-images:php8.1",
volumes: volumes,
commands: [
"php -v",
"composer update"
]
},
{
name: "phpcs",
image: "joomlaprojects/docker-images:php8.1",
depends: [ "composer" ],
commands: [
"vendor/bin/phpcs --standard=ruleset.xml src/"
]
},
{
name: "phan",
image: "joomlaprojects/docker-images:php8.1-ast",
depends: [ "composer" ],
failure: "ignore",
commands: [
"vendor/bin/phan"
]
},
{
name: "phpstan",
image: "joomlaprojects/docker-images:php8.1",
depends: [ "composer" ],
failure: "ignore",
commands: [
"vendor/bin/phpstan analyse src",
]
},
{
name: "phploc",
image: "joomlaprojects/docker-images:php8.1",
depends: [ "composer" ],
failure: "ignore",
commands: [
"phploc src",
]
},
{
name: "phpcpd",
image: "joomlaprojects/docker-images:php8.1",
depends: [ "composer" ],
failure: "ignore",
commands: [
"phpcpd src",
]
}
]
},
pipeline("8.1 lowest", "8.1", "--prefer-stable --prefer-lowest"),
pipeline("8.1", "8.1", "--prefer-stable"),
pipeline("8.2", "8.2", "--prefer-stable"),
]

View File

@ -0,0 +1,130 @@
---
kind: pipeline
name: Codequality
steps:
- commands:
- php -v
- composer update
image: joomlaprojects/docker-images:php8.1
name: composer
volumes:
- name: composer-cache
path: /tmp/composer-cache
- commands:
- vendor/bin/phpcs --standard=ruleset.xml src/
depends:
- composer
image: joomlaprojects/docker-images:php8.1
name: phpcs
- commands:
- vendor/bin/phan
depends:
- composer
failure: ignore
image: joomlaprojects/docker-images:php8.1-ast
name: phan
- commands:
- vendor/bin/phpstan analyse src
depends:
- composer
failure: ignore
image: joomlaprojects/docker-images:php8.1
name: phpstan
- commands:
- phploc src
depends:
- composer
failure: ignore
image: joomlaprojects/docker-images:php8.1
name: phploc
- commands:
- phpcpd src
depends:
- composer
failure: ignore
image: joomlaprojects/docker-images:php8.1
name: phpcpd
volumes:
- host:
path: /tmp/composer-cache
name: composer-cache
---
kind: pipeline
name: PHP 8.1 lowest
services:
- image: memcached:alpine
name: memcached
- image: redis:alpine
name: redis
steps:
- commands:
- php -v
- composer update --prefer-stable --prefer-lowest
image: joomlaprojects/docker-images:php8.1
name: composer
volumes:
- name: composer-cache
path: /tmp/composer-cache
- commands:
- vendor/bin/phpunit
image: joomlaprojects/docker-images:php8.1
name: PHPUnit
volumes:
- host:
path: /tmp/composer-cache
name: composer-cache
---
kind: pipeline
name: PHP 8.1
services:
- image: memcached:alpine
name: memcached
- image: redis:alpine
name: redis
steps:
- commands:
- php -v
- composer update --prefer-stable
image: joomlaprojects/docker-images:php8.1
name: composer
volumes:
- name: composer-cache
path: /tmp/composer-cache
- commands:
- vendor/bin/phpunit
image: joomlaprojects/docker-images:php8.1
name: PHPUnit
volumes:
- host:
path: /tmp/composer-cache
name: composer-cache
---
kind: pipeline
name: PHP 8.2
services:
- image: memcached:alpine
name: memcached
- image: redis:alpine
name: redis
steps:
- commands:
- php -v
- composer update --prefer-stable
image: joomlaprojects/docker-images:php8.2
name: composer
volumes:
- name: composer-cache
path: /tmp/composer-cache
- commands:
- vendor/bin/phpunit
image: joomlaprojects/docker-images:php8.2
name: PHPUnit
volumes:
- host:
path: /tmp/composer-cache
name: composer-cache
---
kind: signature
hmac: 1c6bac6f08e700bf838ea12bf43aafe8fea392b1b77b1856ba0ff6e43fcde847
...

340
libraries/vendor/joomla/session/LICENSE vendored Normal file
View File

@ -0,0 +1,340 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Library General
Public License instead of this License.

View File

@ -0,0 +1,6 @@
CREATE TABLE IF NOT EXISTS `#__session` (
`session_id` VARBINARY(128) NOT NULL,
`time` INTEGER UNSIGNED NOT NULL,
`data` BLOB NOT NULL,
PRIMARY KEY (`session_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

View File

@ -0,0 +1,6 @@
CREATE TABLE "#__session" (
"session_id" VARCHAR(128) NOT NULL,
"time" INTEGER NOT NULL,
"data" BYTEA NOT NULL,
PRIMARY KEY ("session_id")
);

View File

@ -0,0 +1,6 @@
CREATE TABLE `#__session` (
`session_id` TEXT NOT NULL,
`time` INTEGER NOT NULL,
`data` BLOB NOT NULL,
CONSTRAINT `idx_session` PRIMARY KEY (`session_id`)
);

View File

@ -0,0 +1,9 @@
CREATE TABLE [#__session] (
[session_id] VARCHAR(128) NOT NULL,
[time] INTEGER NOT NULL,
[data] VARBINARY(MAX) NOT NULL,
CONSTRAINT [PK_#__session_session_id] PRIMARY KEY CLUSTERED
(
[session_id] ASC
) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY];

View File

@ -0,0 +1,109 @@
<?php
/**
* Part of the Joomla Framework Session Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Session\Command;
use Joomla\Console\Command\AbstractCommand;
use Joomla\Database\DatabaseInterface;
use Joomla\Session\Exception\CreateSessionTableException;
use Joomla\Session\Exception\UnsupportedDatabaseDriverException;
use Joomla\Session\Handler\DatabaseHandler;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
/**
* Command used to create the session database table.
*
* @since 2.0.0
*/
class CreateSessionTableCommand extends AbstractCommand
{
/**
* The default command name
*
* @var string
* @since 2.0.0
*/
protected static $defaultName = 'session:create-table';
/**
* Database connector
*
* @var DatabaseInterface
* @since 2.0.0
*/
private $db;
/**
* Instantiate the command.
*
* @param DatabaseInterface $db Database connector
*
* @since 2.0.0
*/
public function __construct(DatabaseInterface $db)
{
$this->db = $db;
parent::__construct();
}
/**
* Configure the command.
*
* @return void
*
* @since 2.0.0
*/
protected function configure(): void
{
$this->setDescription('Creates the session database table if not already present');
}
/**
* Internal function to execute the command.
*
* @param InputInterface $input The input to inject into the command.
* @param OutputInterface $output The output to inject into the command.
*
* @return integer The command exit code
*
* @since 2.0.0
*/
protected function doExecute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$io->title('Create Session Table');
// Check if the table exists
if (\in_array($this->db->replacePrefix('#__session'), $this->db->getTableList())) {
$io->success('The session table already exists.');
return 0;
}
try {
(new DatabaseHandler($this->db))->createDatabaseTable();
} catch (UnsupportedDatabaseDriverException $exception) {
$io->error($exception->getMessage());
return 1;
} catch (CreateSessionTableException $exception) {
$io->error(\sprintf('The session table could not be created: %s', $exception->getMessage()));
return 1;
}
$io->success('The session table has been created.');
return 0;
}
}

View File

@ -0,0 +1,19 @@
<?php
/**
* Part of the Joomla Framework Session Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Session\Exception;
/**
* Exception thrown when the database session table cannot be created
*
* @since 2.0.0
*/
class CreateSessionTableException extends \RuntimeException
{
}

View File

@ -0,0 +1,19 @@
<?php
/**
* Part of the Joomla Framework Session Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Session\Exception;
/**
* Exception thrown when a session validator fails
*
* @since 2.0.0
*/
class InvalidSessionException extends \RuntimeException
{
}

View File

@ -0,0 +1,19 @@
<?php
/**
* Part of the Joomla Framework Session Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Session\Exception;
/**
* Exception thrown when the database driver is unsupported
*
* @since 2.0.0
*/
class UnsupportedDatabaseDriverException extends \UnexpectedValueException
{
}

View File

@ -0,0 +1,150 @@
<?php
/**
* Part of the Joomla Framework Session Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Session\Handler;
use Joomla\Session\HandlerInterface;
/**
* APCu session storage handler
*
* @since 2.0.0
*/
class ApcuHandler implements HandlerInterface
{
/**
* Session ID prefix to avoid naming conflicts
*
* @var string
* @since 2.0.0
*/
private $prefix;
/**
* Constructor
*
* @param array $options Associative array of options to configure the handler
*
* @since 2.0.0
*/
public function __construct(array $options = [])
{
// Namespace our session IDs to avoid potential conflicts
$this->prefix = $options['prefix'] ?? 'jfw';
}
/**
* Close the session
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
#[\ReturnTypeWillChange]
public function close()
{
return true;
}
/**
* Destroy a session
*
* @param string $session_id The session ID being destroyed
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
public function destroy(string $id): bool
{
// The apcu_delete function returns false if the id does not exist
return apcu_delete($this->prefix . $id) || !apcu_exists($this->prefix . $id);
}
/**
* Cleanup old sessions
*
* @param integer $maxlifetime Sessions that have not updated for the last maxlifetime seconds will be removed
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
#[\ReturnTypeWillChange]
public function gc($maxlifetime)
{
return true;
}
/**
* Test to see if the HandlerInterface is available
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
public static function isSupported(): bool
{
$supported = \extension_loaded('apcu') && ini_get('apc.enabled');
// If on the CLI interface, the `apc.enable_cli` option must also be enabled
if ($supported && PHP_SAPI === 'cli') {
$supported = ini_get('apc.enable_cli');
}
return (bool) $supported;
}
/**
* Initialize session
*
* @param string $save_path The path where to store/retrieve the session
* @param string $session_id The session id
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
#[\ReturnTypeWillChange]
public function open($save_path, $session_id)
{
return true;
}
/**
* Read session data
*
* @param string $session_id The session id to read data for
*
* @return string The session data
*
* @since 2.0.0
*/
#[\ReturnTypeWillChange]
public function read($session_id)
{
return (string) apcu_fetch($this->prefix . $session_id);
}
/**
* Write session data
*
* @param string $session_id The session id
* @param string $session_data The encoded session data
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
#[\ReturnTypeWillChange]
public function write($session_id, $session_data)
{
return apcu_store($this->prefix . $session_id, $session_data, ini_get('session.gc_maxlifetime'));
}
}

View File

@ -0,0 +1,308 @@
<?php
/**
* Part of the Joomla Framework Session Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Session\Handler;
use Joomla\Database\DatabaseDriver;
use Joomla\Database\DatabaseInterface;
use Joomla\Database\Exception\ExecutionFailureException;
use Joomla\Database\ParameterType;
use Joomla\Session\Exception\CreateSessionTableException;
use Joomla\Session\Exception\UnsupportedDatabaseDriverException;
use Joomla\Session\HandlerInterface;
/**
* Database session storage handler
*
* @since 2.0.0
*/
class DatabaseHandler implements HandlerInterface
{
/**
* Database connector
*
* @var DatabaseInterface
* @since 2.0.0
*/
private $db;
/**
* Flag whether gc() has been called
*
* @var boolean
* @since 2.0.0
*/
private $gcCalled = false;
/**
* Lifetime for garbage collection
*
* @var integer
* @since 2.0.0
*/
private $gcLifetime;
/**
* Constructor
*
* @param DatabaseInterface $db Database connector
*
* @since 2.0.0
*/
public function __construct(DatabaseInterface $db)
{
$this->db = $db;
}
/**
* Close the session
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
#[\ReturnTypeWillChange]
public function close()
{
if ($this->gcCalled) {
$query = $this->db->getQuery(true)
->delete($this->db->quoteName('#__session'))
->where($this->db->quoteName('time') . ' < ?')
->bind(1, $this->gcLifetime, ParameterType::INTEGER);
// Remove expired sessions from the database.
$this->db->setQuery($query)->execute();
$this->gcCalled = false;
$this->gcLifetime = null;
}
$this->db->disconnect();
return true;
}
/**
* Creates the session database table
*
* @return boolean
*
* @since 2.0.0
* @throws CreateSessionTableException
* @throws UnsupportedDatabaseDriverException
*/
public function createDatabaseTable(): bool
{
switch ($this->db->getName()) {
case 'mysql':
case 'mysqli':
$filename = 'mysql.sql';
break;
case 'postgresql':
$filename = 'pgsql.sql';
break;
case 'sqlsrv':
case 'sqlazure':
$filename = 'sqlsrv.sql';
break;
case 'sqlite':
$filename = 'sqlite.sql';
break;
default:
throw new UnsupportedDatabaseDriverException(sprintf('The %s database driver is not supported.', $this->db->getName()));
}
$path = \dirname(__DIR__, 2) . '/meta/sql/' . $filename;
if (!is_readable($path)) {
throw new CreateSessionTableException(
sprintf('Database schema could not be read from %s. Please ensure the file exists and is readable.', $path)
);
}
$queries = DatabaseDriver::splitSql(file_get_contents($path));
foreach ($queries as $query) {
$query = trim($query);
if ($query !== '') {
try {
$this->db->setQuery($query)->execute();
} catch (ExecutionFailureException $exception) {
throw new CreateSessionTableException('Failed to create the session table.', 0, $exception);
}
}
}
return true;
}
/**
* Destroy a session
*
* @param string $session_id The session ID being destroyed
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
public function destroy(string $id): bool
{
try {
$query = $this->db->getQuery(true)
->delete($this->db->quoteName('#__session'))
->where($this->db->quoteName('session_id') . ' = ' . $this->db->quote($id));
// Remove a session from the database.
$this->db->setQuery($query)->execute();
return true;
} catch (\Exception $e) {
return false;
}
}
/**
* Cleanup old sessions
*
* @param integer $maxlifetime Sessions that have not updated for the last maxlifetime seconds will be removed
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
#[\ReturnTypeWillChange]
public function gc($maxlifetime)
{
// We'll delay garbage collection until the session is closed to prevent potential issues mid-cycle
$this->gcLifetime = time() - $maxlifetime;
$this->gcCalled = true;
return true;
}
/**
* Test to see if the HandlerInterface is available
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
public static function isSupported(): bool
{
return interface_exists(DatabaseInterface::class);
}
/**
* Initialize session
*
* @param string $save_path The path where to store/retrieve the session
* @param string $session_id The session id
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
#[\ReturnTypeWillChange]
public function open($save_path, $session_id)
{
$this->db->connect();
return true;
}
/**
* Read session data
*
* @param string $session_id The session id to read data for
*
* @return string The session data
*
* @since 2.0.0
*/
#[\ReturnTypeWillChange]
public function read($session_id)
{
try {
// Get the session data from the database table.
$query = $this->db->getQuery(true)
->select($this->db->quoteName('data'))
->from($this->db->quoteName('#__session'))
->where($this->db->quoteName('session_id') . ' = ?')
->bind(1, $session_id);
$this->db->setQuery($query);
return (string) $this->db->loadResult();
} catch (\Exception $e) {
return '';
}
}
/**
* Write session data
*
* @param string $session_id The session id
* @param string $session_data The encoded session data
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
#[\ReturnTypeWillChange]
public function write($session_id, $session_data)
{
try {
// Figure out if a row exists for the session ID
$query = $this->db->getQuery(true)
->select($this->db->quoteName('session_id'))
->from($this->db->quoteName('#__session'))
->where($this->db->quoteName('session_id') . ' = ?')
->bind(1, $session_id);
$idExists = $this->db->setQuery($query)->loadResult();
$query = $this->db->getQuery(true);
$time = time();
if ($idExists) {
$query->update($this->db->quoteName('#__session'))
->set($this->db->quoteName('data') . ' = ?')
->set($this->db->quoteName('time') . ' = ?')
->where($this->db->quoteName('session_id') . ' = ?')
->bind(1, $session_data)
->bind(2, $time, ParameterType::INTEGER)
->bind(3, $session_id);
} else {
$query->insert($this->db->quoteName('#__session'))
->columns([$this->db->quoteName('data'), $this->db->quoteName('time'), $this->db->quoteName('session_id')])
->values('?, ?, ?')
->bind(1, $session_data)
->bind(2, $time, ParameterType::INTEGER)
->bind(3, $session_id);
}
// Try to insert the session data in the database table.
$this->db->setQuery($query)->execute();
return true;
} catch (\Exception $e) {
return false;
}
}
}

View File

@ -0,0 +1,83 @@
<?php
/**
* Part of the Joomla Framework Session Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Session\Handler;
use Joomla\Session\HandlerInterface;
/**
* Filesystem session storage handler
*
* @since 2.0.0
*/
class FilesystemHandler extends \SessionHandler implements HandlerInterface
{
/**
* Constructor
*
* @param string $path Path of directory to save session files. Leave null to use the PHP configured path.
*
* @since 2.0.0
* @throws \InvalidArgumentException
* @throws \RuntimeException
*/
public function __construct(string $path = '')
{
$pathConfig = ini_get('session.save_path');
// If the paths are empty, then we can't use this handler
if (empty($path) && empty($pathConfig)) {
throw new \InvalidArgumentException('Invalid argument $path');
}
// If path is empty or equal to the the PHP configured path, set only the handler and use the PHP path directly
if (empty($path) || $path === $pathConfig) {
if (!headers_sent()) {
ini_set('session.save_handler', 'files');
}
return;
}
$baseDir = $path;
if ($count = substr_count($path, ';')) {
if ($count > 2) {
throw new \InvalidArgumentException(sprintf('Invalid argument $path "%s"', $path));
}
// Characters after the last semi-colon are the path
$baseDir = ltrim(strrchr($path, ';'), ';');
}
// Create the directory if it doesn't exist
if (!is_dir($baseDir)) {
if (!mkdir($baseDir, 0755)) {
throw new \RuntimeException(sprintf('Could not create session directory "%s"', $baseDir));
}
}
if (!headers_sent()) {
ini_set('session.save_path', $path);
ini_set('session.save_handler', 'files');
}
}
/**
* Test to see if the HandlerInterface is available
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
public static function isSupported(): bool
{
return true;
}
}

View File

@ -0,0 +1,169 @@
<?php
/**
* Part of the Joomla Framework Session Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Session\Handler;
use Joomla\Session\HandlerInterface;
/**
* Memcached session storage handler
*
* @since 2.0.0
*/
class MemcachedHandler implements HandlerInterface
{
/**
* Memcached driver
*
* @var \Memcached
* @since 2.0.0
*/
private $memcached;
/**
* Session ID prefix to avoid naming conflicts
*
* @var string
* @since 2.0.0
*/
private $prefix;
/**
* Time to live in seconds
*
* @var integer
* @since 2.0.0
*/
private $ttl;
/**
* Constructor
*
* @param \Memcached $memcached A Memcached instance
* @param array $options Associative array of options to configure the handler
*
* @since 2.0.0
*/
public function __construct(\Memcached $memcached, array $options = [])
{
$this->memcached = $memcached;
// Set the default time-to-live based on the Session object's default configuration
$this->ttl = isset($options['ttl']) ? (int) $options['ttl'] : 900;
// Namespace our session IDs to avoid potential conflicts
$this->prefix = $options['prefix'] ?? 'jfw';
}
/**
* Close the session
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
#[\ReturnTypeWillChange]
public function close()
{
return true;
}
/**
* Destroy a session
*
* @param string $session_id The session ID being destroyed
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
public function destroy(string $id): bool
{
return $this->memcached->delete($this->prefix . $id);
}
/**
* Cleanup old sessions
*
* @param integer $maxlifetime Sessions that have not updated for the last maxlifetime seconds will be removed
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
#[\ReturnTypeWillChange]
public function gc($maxlifetime)
{
// Memcached manages garbage collection on its own
return true;
}
/**
* Test to see if the HandlerInterface is available
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
public static function isSupported(): bool
{
/*
* GAE and HHVM have both had instances where Memcached the class was defined but no extension was loaded.
* If the class is there, we can assume it works.
*/
return class_exists('Memcached');
}
/**
* Initialize session
*
* @param string $save_path The path where to store/retrieve the session
* @param string $session_id The session id
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
#[\ReturnTypeWillChange]
public function open($save_path, $session_id)
{
return true;
}
/**
* Read session data
*
* @param string $session_id The session id to read data for
*
* @return string The session data
*
* @since 2.0.0
*/
#[\ReturnTypeWillChange]
public function read($session_id)
{
return $this->memcached->get($this->prefix . $session_id) ?: '';
}
/**
* Write session data
*
* @param string $session_id The session id
* @param string $session_data The encoded session data
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
#[\ReturnTypeWillChange]
public function write($session_id, $session_data)
{
return $this->memcached->set($this->prefix . $session_id, $session_data, time() + $this->ttl);
}
}

View File

@ -0,0 +1,172 @@
<?php
/**
* Part of the Joomla Framework Session Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Session\Handler;
use Joomla\Session\HandlerInterface;
/**
* Redis session storage handler
*
* @since 2.0.0
*/
class RedisHandler implements HandlerInterface
{
/**
* Session ID prefix to avoid naming conflicts
*
* @var string
* @since 2.0.0
*/
private $prefix;
/**
* Redis driver
*
* @var \Redis
* @since 2.0.0
*/
private $redis;
/**
* Time to live in seconds
*
* @var integer
* @since 2.0.0
*/
private $ttl;
/**
* Constructor
*
* @param \Redis $redis A Redis instance
* @param array $options Associative array of options to configure the handler
*
* @since 2.0.0
*/
public function __construct(\Redis $redis, array $options = [])
{
$this->redis = $redis;
// Set the default time-to-live based on the Session object's default configuration
$this->ttl = isset($options['ttl']) ? (int) $options['ttl'] : 900;
// Namespace our session IDs to avoid potential conflicts
$this->prefix = $options['prefix'] ?? 'jfw';
}
/**
* Close the session
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
#[\ReturnTypeWillChange]
public function close()
{
// No need to close the connection to Redis server manually.
return true;
}
/**
* Destroy a session, called automatically when running session_regenerate_id().
*
* @param integer $session_id The session ID being destroyed
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
public function destroy(string $id): bool
{
$this->redis->del($this->prefix . $id);
// Session callback must have a return value of type bool when session_regenerate_id() is called.
return true;
}
/**
* Cleanup old sessions
*
* @param integer $maxlifetime Sessions that have not updated for the last maxlifetime seconds will be removed
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
#[\ReturnTypeWillChange]
public function gc($maxlifetime)
{
return true;
}
/**
* Test to see if the HandlerInterface is available
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
public static function isSupported(): bool
{
return \extension_loaded('redis') && class_exists('Redis');
}
/**
* Initialize session
*
* @param string $save_path The path where to store/retrieve the session
* @param string $session_id The session id
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
#[\ReturnTypeWillChange]
public function open($save_path, $session_id)
{
return true;
}
/**
* Read session data
*
* @param string $session_id The session id to read data for
*
* @return string The session data
*
* @since 2.0.0
*/
#[\ReturnTypeWillChange]
public function read($session_id)
{
return $this->redis->get($this->prefix . $session_id) ?: '';
}
/**
* Write session data
*
* @param string $session_id The session id
* @param string $session_data The encoded session data
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
#[\ReturnTypeWillChange]
public function write($session_id, $session_data)
{
if ($this->ttl > 0) {
return $this->redis->setex($this->prefix . $session_id, $this->ttl, $session_data);
}
return $this->redis->set($this->prefix . $session_id, $session_data);
}
}

View File

@ -0,0 +1,44 @@
<?php
/**
* Part of the Joomla Framework Session Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Session\Handler;
use Joomla\Session\HandlerInterface;
/**
* Wincache session storage handler
*
* @since 2.0.0
*/
class WincacheHandler extends \SessionHandler implements HandlerInterface
{
/**
* Constructor
*
* @since 2.0.0
*/
public function __construct()
{
if (!headers_sent()) {
ini_set('session.save_handler', 'wincache');
}
}
/**
* Test to see if the HandlerInterface is available
*
* @return boolean True on success, false otherwise
*
* @since 2.0.0
*/
public static function isSupported(): bool
{
return \extension_loaded('wincache') && \function_exists('wincache_ucache_get') && !strcmp(ini_get('wincache.ucenabled'), '1');
}
}

View File

@ -0,0 +1,27 @@
<?php
/**
* Part of the Joomla Framework Session Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Session;
/**
* Interface defining Joomla! session handlers
*
* @since 2.0.0
*/
interface HandlerInterface extends \SessionHandlerInterface
{
/**
* Test to see if the HandlerInterface is available.
*
* @return boolean True on success, false otherwise.
*
* @since 2.0.0
*/
public static function isSupported(): bool;
}

View File

@ -0,0 +1,762 @@
<?php
/**
* Part of the Joomla Framework Session Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Session;
use Joomla\Event\DispatcherAwareInterface;
use Joomla\Event\DispatcherAwareTrait;
use Joomla\Event\DispatcherInterface;
/**
* Class for managing HTTP sessions
*
* Provides access to session-state values as well as session-level settings and lifetime management methods.
* Based on the standard PHP session handling mechanism it provides more advanced features such as expire timeouts.
*
* @since 1.0
*/
class Session implements SessionInterface, DispatcherAwareInterface
{
use DispatcherAwareTrait;
/**
* Internal session state.
*
* @var string
* @since 1.0
*/
protected $state = SessionState::INACTIVE;
/**
* Maximum age of unused session in seconds.
*
* @var integer
* @since 1.0
*/
protected $expire = 900;
/**
* The session store object.
*
* @var StorageInterface
* @since 1.0
*/
protected $store;
/**
* Container holding session validators.
*
* @var ValidatorInterface[]
* @since 2.0.0
*/
protected $sessionValidators = [];
/**
* Constructor
*
* @param StorageInterface $store A StorageInterface implementation.
* @param DispatcherInterface $dispatcher DispatcherInterface for the session to use.
* @param array $options Optional parameters. Supported keys include:
* - name: The session name
* - id: The session ID
* - expire: The session lifetime in seconds
*
* @since 1.0
*/
public function __construct(StorageInterface $store = null, DispatcherInterface $dispatcher = null, array $options = [])
{
$this->store = $store ?: new Storage\NativeStorage(new Handler\FilesystemHandler());
if ($dispatcher) {
$this->setDispatcher($dispatcher);
}
$this->setOptions($options);
$this->setState(SessionState::INACTIVE);
}
/**
* Adds a validator to the session
*
* @param ValidatorInterface $validator The session validator
*
* @return void
*
* @since 2.0.0
*/
public function addValidator(ValidatorInterface $validator): void
{
$this->sessionValidators[] = $validator;
}
/**
* Get expiration time in seconds
*
* @return integer The session expiration time in seconds
*
* @since 1.0
*/
public function getExpire()
{
return $this->expire;
}
/**
* Get current state of session
*
* @return string The session state
*
* @since 1.0
*/
public function getState()
{
return $this->state;
}
/**
* Get a session token.
*
* Tokens are used to secure forms from spamming attacks. Once a token has been generated the system will check the request to see if
* it is present, if not it will invalidate the session.
*
* @param boolean $forceNew If true, forces a new token to be created
*
* @return string
*
* @since 1.0
*/
public function getToken($forceNew = false)
{
// Ensure the session token exists and create it if necessary
if (!$this->has('session.token') || $forceNew) {
$this->set('session.token', $this->createToken());
}
return $this->get('session.token');
}
/**
* Check if the session has the given token.
*
* @param string $token Hashed token to be verified
* @param boolean $forceExpire If true, expires the session
*
* @return boolean
*
* @since 1.0
*/
public function hasToken($token, $forceExpire = true)
{
$result = $this->get('session.token') === $token;
if (!$result && $forceExpire) {
$this->setState(SessionState::EXPIRED);
}
return $result;
}
/**
* Retrieve an external iterator.
*
* @return \ArrayIterator Return an ArrayIterator of $_SESSION.
*
* @since 1.0
*/
#[\ReturnTypeWillChange]
public function getIterator()
{
return new \ArrayIterator($this->all());
}
/**
* Get session name
*
* @return string The session name
*
* @since 1.0
*/
public function getName()
{
return $this->store->getName();
}
/**
* Set the session name
*
* @param string $name The session name
*
* @return $this
*
* @since 2.0.0
*/
public function setName(string $name)
{
$this->store->setName($name);
return $this;
}
/**
* Get session id
*
* @return string The session id
*
* @since 1.0
*/
public function getId()
{
return $this->store->getId();
}
/**
* Set the session ID
*
* @param string $id The session ID
*
* @return $this
*
* @since 2.0.0
*/
public function setId(string $id)
{
$this->store->setId($id);
return $this;
}
/**
* Check if the session is active
*
* @return boolean
*
* @since 1.0
*/
public function isActive()
{
if ($this->getState() === SessionState::ACTIVE) {
return $this->store->isActive();
}
return false;
}
/**
* Check whether this session is currently created
*
* @return boolean
*
* @since 1.0
*/
public function isNew()
{
$counter = $this->get('session.counter');
return $counter === 1;
}
/**
* Check if the session is started
*
* @return boolean
*
* @since 2.0.0
*/
public function isStarted(): bool
{
return $this->store->isStarted();
}
/**
* Get data from the session store
*
* @param string $name Name of a variable
* @param mixed $default Default value of a variable if not set
*
* @return mixed Value of a variable
*
* @since 1.0
*/
public function get($name, $default = null)
{
if (!$this->isActive()) {
$this->start();
}
return $this->store->get($name, $default);
}
/**
* Set data into the session store.
*
* @param string $name Name of a variable.
* @param mixed $value Value of a variable.
*
* @return mixed Old value of a variable.
*
* @since 1.0
*/
public function set($name, $value = null)
{
if (!$this->isActive()) {
$this->start();
}
return $this->store->set($name, $value);
}
/**
* Check whether data exists in the session store
*
* @param string $name Name of variable
*
* @return boolean True if the variable exists
*
* @since 1.0
*/
public function has($name)
{
if (!$this->isActive()) {
$this->start();
}
return $this->store->has($name);
}
/**
* Unset a variable from the session store
*
* @param string $name Name of variable
*
* @return mixed The value from session or NULL if not set
*
* @since 2.0.0
*/
public function remove(string $name)
{
if (!$this->isActive()) {
$this->start();
}
return $this->store->remove($name);
}
/**
* Clears all variables from the session store
*
* @return void
*
* @since 1.0
*/
public function clear()
{
if (!$this->isActive()) {
$this->start();
}
$this->store->clear();
}
/**
* Retrieves all variables from the session store
*
* @return array
*
* @since 2.0.0
*/
public function all(): array
{
if (!$this->isActive()) {
$this->start();
}
return $this->store->all();
}
/**
* Start a session.
*
* @return void
*
* @since 1.0
*/
public function start()
{
if ($this->isStarted()) {
return;
}
$this->store->start();
$this->setState(SessionState::ACTIVE);
// Initialise the session
$this->setCounter();
$this->setTimers();
// Perform security checks
if (!$this->validate()) {
// If the session isn't valid because it expired try to restart it or destroy it.
if ($this->getState() === SessionState::EXPIRED) {
$this->restart();
} else {
$this->destroy();
}
}
if ($this->dispatcher) {
if (!empty($this->dispatcher->getListeners('onAfterSessionStart'))) {
trigger_deprecation(
'joomla/session',
'2.0.0',
'The `onAfterSessionStart` event is deprecated and will be removed in 3.0, use the %s::START event instead.',
SessionEvents::class
);
// Dispatch deprecated event
$this->dispatcher->dispatch('onAfterSessionStart', new SessionEvent('onAfterSessionStart', $this));
}
// Dispatch new event
$this->dispatcher->dispatch(SessionEvents::START, new SessionEvent(SessionEvents::START, $this));
}
}
/**
* Frees all session variables and destroys all data registered to a session
*
* This method resets the $_SESSION variable and destroys all of the data associated
* with the current session in its storage (file or DB). It forces new session to be
* started after this method is called.
*
* @return boolean
*
* @see session_destroy()
* @see session_unset()
* @since 1.0
*/
public function destroy()
{
// Session was already destroyed
if ($this->getState() === SessionState::DESTROYED) {
return true;
}
$this->clear();
$this->fork(true);
$this->setState(SessionState::DESTROYED);
return true;
}
/**
* Restart an expired or locked session.
*
* @return boolean True on success
*
* @see destroy
* @since 1.0
*/
public function restart()
{
// Backup existing session data
$data = $this->all();
$this->destroy();
if ($this->getState() !== SessionState::DESTROYED) {
// @TODO :: generated error here
return false;
}
// Restart the session
$this->store->start();
$this->setState(SessionState::ACTIVE);
// Initialise the session
$this->setCounter();
$this->setTimers();
// Restore the data
foreach ($data as $key => $value) {
$this->set($key, $value);
}
// If the restarted session cannot be validated then it will be destroyed
if (!$this->validate(true)) {
$this->destroy();
}
if ($this->dispatcher) {
if (!empty($this->dispatcher->getListeners('onAfterSessionRestart'))) {
trigger_deprecation(
'joomla/session',
'2.0.0',
'The `onAfterSessionRestart` event is deprecated and will be removed in 3.0, use the %s::RESTART event instead.',
SessionEvents::class
);
// Dispatch deprecated event
$this->dispatcher->dispatch('onAfterSessionRestart', new SessionEvent('onAfterSessionRestart', $this));
}
// Dispatch new event
$this->dispatcher->dispatch(SessionEvents::RESTART, new SessionEvent(SessionEvents::RESTART, $this));
}
return true;
}
/**
* Create a new session and copy variables from the old one
*
* @param boolean $destroy Whether to delete the old session or leave it to garbage collection.
*
* @return boolean True on success
*
* @since 1.0
*/
public function fork($destroy = false)
{
$result = $this->store->regenerate($destroy);
if ($result) {
$this->setTimers();
}
return $result;
}
/**
* Writes session data and ends session
*
* Session data is usually stored after your script terminated without the need
* to call {@link Session::close()}, but as session data is locked to prevent concurrent
* writes only one script may operate on a session at any time. When using
* framesets together with sessions you will experience the frames loading one
* by one due to this locking. You can reduce the time needed to load all the
* frames by ending the session as soon as all changes to session variables are
* done.
*
* @return void
*
* @see session_write_close()
* @since 1.0
*/
public function close()
{
$this->store->close();
$this->setState(SessionState::CLOSED);
}
/**
* Perform session data garbage collection
*
* @return integer|boolean Number of deleted sessions on success or boolean false on failure or if the function is unsupported
*
* @see session_gc()
* @since 2.0.0
*/
public function gc()
{
if (!$this->isActive()) {
$this->start();
}
return $this->store->gc();
}
/**
* Aborts the current session
*
* @return boolean
*
* @see session_abort()
* @since 2.0.0
*/
public function abort(): bool
{
if (!$this->isActive()) {
return true;
}
return $this->store->abort();
}
/**
* Create a token string
*
* @return string
*
* @since 1.3.1
*/
protected function createToken(): string
{
/*
* We are returning a 32 character string.
* The bin2hex() function will double the length of the hexadecimal value returned by random_bytes(),
* so generate the token from a 16 byte random value
*/
return bin2hex(random_bytes(16));
}
/**
* Set counter of session usage
*
* @return boolean True on success
*
* @since 1.0
*/
protected function setCounter()
{
$counter = $this->get('session.counter', 0);
$counter++;
$this->set('session.counter', $counter);
return true;
}
/**
* Set the session expiration
*
* @param integer $expire Maximum age of unused session in seconds
*
* @return $this
*
* @since 1.3.0
*/
protected function setExpire($expire)
{
$this->expire = $expire;
return $this;
}
/**
* Set the session state
*
* @param string $state Internal state
*
* @return $this
*
* @since 1.3.0
*/
protected function setState($state)
{
$this->state = $state;
return $this;
}
/**
* Set the session timers
*
* @return boolean True on success
*
* @since 1.0
*/
protected function setTimers()
{
if (!$this->has('session.timer.start')) {
$start = time();
$this->set('session.timer.start', $start);
$this->set('session.timer.last', $start);
$this->set('session.timer.now', $start);
}
$this->set('session.timer.last', $this->get('session.timer.now'));
$this->set('session.timer.now', time());
return true;
}
/**
* Set additional session options
*
* @param array $options List of parameter
*
* @return boolean True on success
*
* @since 1.0
*/
protected function setOptions(array $options)
{
// Set name
if (isset($options['name'])) {
$this->setName($options['name']);
}
// Set id
if (isset($options['id'])) {
$this->setId($options['id']);
}
// Set expire time
if (isset($options['expire'])) {
$this->setExpire($options['expire']);
}
// Sync the session maxlifetime
if (!headers_sent()) {
ini_set('session.gc_maxlifetime', $this->getExpire());
}
return true;
}
/**
* Do some checks for security reasons
*
* If one check fails, session data has to be cleaned.
*
* @param boolean $restart Reactivate session
*
* @return boolean True on success
*
* @see http://shiflett.org/articles/the-truth-about-sessions
* @since 1.0
*/
protected function validate($restart = false)
{
// Allow to restart a session
if ($restart) {
$this->setState(SessionState::ACTIVE);
}
// Check if session has expired
if ($this->expire) {
$curTime = $this->get('session.timer.now', 0);
$maxTime = $this->get('session.timer.last', 0) + $this->expire;
// Empty session variables
if ($maxTime < $curTime) {
$this->setState(SessionState::EXPIRED);
return false;
}
}
try {
foreach ($this->sessionValidators as $validator) {
$validator->validate($restart);
}
} catch (Exception\InvalidSessionException $e) {
$this->setState(SessionState::ERROR);
return false;
}
return true;
}
}

View File

@ -0,0 +1,55 @@
<?php
/**
* Part of the Joomla Framework Session Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Session;
use Joomla\Event\Event;
/**
* Class representing a Session event
*
* @since 2.0.0
*/
class SessionEvent extends Event
{
/**
* SessionInterface object for this event
*
* @var SessionInterface
* @since 2.0.0
*/
private $session;
/**
* Constructor.
*
* @param string $name The event name.
* @param SessionInterface $session The SessionInterface object for this event.
*
* @since 2.0.0
*/
public function __construct(string $name, SessionInterface $session)
{
parent::__construct($name);
$this->session = $session;
}
/**
* Retrieve the SessionInterface object attached to this event.
*
* @return SessionInterface
*
* @since 2.0.0
*/
public function getSession(): SessionInterface
{
return $this->session;
}
}

View File

@ -0,0 +1,47 @@
<?php
/**
* Part of the Joomla Framework Session Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Session;
/**
* Class defining the events dispatched by the session API
*
* @since 2.0.0
*/
final class SessionEvents
{
/**
* Private constructor to prevent instantiation of this class
*
* @since 2.0.0
*/
private function __construct()
{
}
/**
* Session event which is dispatched after the session has been started.
*
* Listeners to this event receive a `Joomla\Session\SessionEvent` object.
*
* @var string
* @since 2.0.0
*/
public const START = 'session.start';
/**
* Session event which is dispatched after the session has been restarted.
*
* Listeners to this event receive a `Joomla\Session\SessionEvent` object.
*
* @var string
* @since 2.0.0
*/
public const RESTART = 'session.restart';
}

View File

@ -0,0 +1,265 @@
<?php
/**
* Part of the Joomla Framework Session Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Session;
/**
* Interface defining a Joomla! Session object
*
* @since 2.0.0
*/
interface SessionInterface extends \IteratorAggregate
{
/**
* Get expiration time in seconds
*
* @return integer The session expiration time in seconds
*
* @since 2.0.0
*/
public function getExpire();
/**
* Get the session name
*
* @return string The session name
*
* @since 2.0.0
*/
public function getName();
/**
* Set the session name
*
* @param string $name The session name
*
* @return $this
*
* @since 2.0.0
*/
public function setName(string $name);
/**
* Get the session ID
*
* @return string The session ID
*
* @since 2.0.0
*/
public function getId();
/**
* Set the session ID
*
* @param string $id The session ID
*
* @return $this
*
* @since 2.0.0
*/
public function setId(string $id);
/**
* Check if the session is active
*
* @return boolean
*
* @since 2.0.0
*/
public function isActive();
/**
* Check whether this session is newly created
*
* @return boolean
*
* @since 2.0.0
*/
public function isNew();
/**
* Check if the session is started
*
* @return boolean
*
* @since 2.0.0
*/
public function isStarted();
/**
* Get a session token.
*
* Tokens are used to secure forms from spamming attacks. Once a token has been generated the system will check the request to see if
* it is present, if not it will invalidate the session.
*
* @param boolean $forceNew If true, forces a new token to be created
*
* @return string
*
* @since 2.0.0
*/
public function getToken($forceNew = false);
/**
* Check if the session has the given token.
*
* @param string $token Hashed token to be verified
* @param boolean $forceExpire If true, expires the session
*
* @return boolean
*
* @since 2.0.0
*/
public function hasToken($token, $forceExpire = true);
/**
* Get data from the session store
*
* @param string $name Name of a variable
* @param mixed $default Default value of a variable if not set
*
* @return mixed Value of a variable
*
* @since 2.0.0
*/
public function get($name, $default = null);
/**
* Set data into the session store
*
* @param string $name Name of a variable.
* @param mixed $value Value of a variable.
*
* @return mixed Old value of a variable.
*
* @since 2.0.0
*/
public function set($name, $value = null);
/**
* Check whether data exists in the session store
*
* @param string $name Name of variable
*
* @return boolean True if the variable exists
*
* @since 2.0.0
*/
public function has($name);
/**
* Unset a variable from the session store
*
* @param string $name Name of variable
*
* @return mixed The value from session or NULL if not set
*
* @since 2.0.0
*/
public function remove(string $name);
/**
* Clears all variables from the session store
*
* @return void
*
* @since 2.0.0
*/
public function clear();
/**
* Retrieves all variables from the session store
*
* @return array
*
* @since 2.0.0
*/
public function all(): array;
/**
* Start a session
*
* @return void
*
* @since 2.0.0
*/
public function start();
/**
* Frees all session variables and destroys all data registered to a session
*
* This method resets the $_SESSION variable and destroys all of the data associated
* with the current session in its storage (file or DB). It forces new session to be
* started after this method is called. It does not unset the session cookie.
*
* @return boolean
*
* @see session_destroy()
* @see session_unset()
* @since 2.0.0
*/
public function destroy();
/**
* Restart an expired or locked session
*
* @return boolean True on success
*
* @see destroy
* @since 2.0.0
*/
public function restart();
/**
* Create a new session and copy variables from the old one
*
* @return boolean
*
* @since 2.0.0
*/
public function fork();
/**
* Writes session data and ends session
*
* Session data is usually stored after your script terminated without the need
* to call SessionInterface::close(), but as session data is locked to prevent concurrent
* writes only one script may operate on a session at any time. When using
* framesets together with sessions you will experience the frames loading one
* by one due to this locking. You can reduce the time needed to load all the
* frames by ending the session as soon as all changes to session variables are
* done.
*
* @return void
*
* @see session_write_close()
* @since 2.0.0
*/
public function close();
/**
* Perform session data garbage collection
*
* @return integer|boolean Number of deleted sessions on success or boolean false on failure or if the function is unsupported
*
* @see session_gc()
* @since 2.0.0
*/
public function gc();
/**
* Aborts the current session
*
* @return boolean
*
* @see session_abort()
* @since 2.0.0
*/
public function abort(): bool;
}

View File

@ -0,0 +1,88 @@
<?php
/**
* Part of the Joomla Framework Session Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Session;
/**
* Class defining the various states of a session
*
* @since 2.0.0
*/
final class SessionState
{
/**
* Private constructor to prevent instantiation of this class
*
* @since 2.0.0
*/
private function __construct()
{
}
/**
* State indicating the session is active.
*
* A `SessionInterface` instance should be in this state once the session has started.
*
* @var string
* @since 2.0.0
*/
public const ACTIVE = 'active';
/**
* State indicating the session is closed.
*
* A `SessionInterface` instance should be in this state after calling the `close()` method.
*
* @var string
* @since 2.0.0
*/
public const CLOSED = 'closed';
/**
* State indicating the session is destroyed.
*
* A `SessionInterface` instance should be in this state after calling the `destroy()` method.
*
* @var string
* @since 2.0.0
*/
public const DESTROYED = 'destroyed';
/**
* State indicating the session is in an error state.
*
* A `SessionInterface` instance should be in this state if the session cannot be validated after being started.
*
* @var string
* @since 2.0.0
*/
public const ERROR = 'error';
/**
* State indicating the session is expired.
*
* A `SessionInterface` instance should be in this state if the session has passed the allowed lifetime.
* A `SessionInterface` instance may be in this state if validating a session token fails.
*
* @var string
* @since 2.0.0
*/
public const EXPIRED = 'expired';
/**
* State indicating the session is inactive.
*
* A `SessionInterface` instance should begin in this state.
*
* @var string
* @since 2.0.0
*/
public const INACTIVE = 'inactive';
}

View File

@ -0,0 +1,467 @@
<?php
/**
* Part of the Joomla Framework Session Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Session\Storage;
use Joomla\Session\HandlerInterface;
use Joomla\Session\StorageInterface;
/**
* Base class providing a session store
*
* @since 2.0.0
*/
class NativeStorage implements StorageInterface
{
/**
* Flag if the session is active
*
* @var boolean
* @since 2.0.0
*/
private $active = false;
/**
* Internal flag identifying whether the session has been closed
*
* @var boolean
* @since 2.0.0
*/
private $closed = false;
/**
* Session save handler
*
* @var \SessionHandlerInterface
* @since 2.0.0
*/
private $handler;
/**
* Internal flag identifying whether the session has been started
*
* @var boolean
* @since 2.0.0
*/
private $started = false;
/**
* Constructor
*
* @param \SessionHandlerInterface $handler Session save handler
* @param array $options Session options
*
* @since 1.0
*/
public function __construct(?\SessionHandlerInterface $handler = null, array $options = [])
{
// Disable transparent sid support and default use cookies
$options += [
'use_cookies' => 1,
'use_trans_sid' => 0,
];
if (!headers_sent()) {
session_cache_limiter('none');
}
session_register_shutdown();
$this->setOptions($options);
$this->setHandler($handler);
}
/**
* Retrieves all variables from the session store
*
* @return array
*
* @since 2.0.0
*/
public function all(): array
{
return $_SESSION;
}
/**
* Clears all variables from the session store
*
* @return void
*
* @since 2.0.0
*/
public function clear(): void
{
$_SESSION = [];
}
/**
* Writes session data and ends session
*
* @return void
*
* @see session_write_close()
* @since 2.0.0
*/
public function close(): void
{
session_write_close();
$this->closed = true;
$this->started = false;
}
/**
* Perform session data garbage collection
*
* @return integer|boolean Number of deleted sessions on success or boolean false on failure or if the function is unsupported
*
* @see session_gc()
* @since 2.0.0
*/
public function gc()
{
if (!$this->isStarted()) {
$this->start();
}
return session_gc();
}
/**
* Aborts the current session
*
* @return boolean
*
* @see session_abort()
* @since 2.0.0
*/
public function abort(): bool
{
if (!$this->isStarted()) {
return true;
}
return session_abort();
}
/**
* Get data from the session store
*
* @param string $name Name of a variable
* @param mixed $default Default value of a variable if not set
*
* @return mixed Value of a variable
*
* @since 2.0.0
*/
public function get(string $name, $default)
{
if (!$this->isStarted()) {
$this->start();
}
if (isset($_SESSION[$name])) {
return $_SESSION[$name];
}
return $default;
}
/**
* Gets the save handler instance
*
* @return \SessionHandlerInterface|null
*
* @since 2.0.0
*/
public function getHandler(): ?\SessionHandlerInterface
{
return $this->handler;
}
/**
* Get the session ID
*
* @return string The session ID
*
* @since 2.0.0
*/
public function getId(): string
{
return session_id();
}
/**
* Get the session name
*
* @return string The session name
*
* @since 2.0.0
*/
public function getName(): string
{
return session_name();
}
/**
* Check whether data exists in the session store
*
* @param string $name Name of variable
*
* @return boolean
*
* @since 2.0.0
*/
public function has(string $name): bool
{
if (!$this->isStarted()) {
$this->start();
}
return isset($_SESSION[$name]);
}
/**
* Check if the session is active
*
* @return boolean
*
* @since 2.0.0
*/
public function isActive(): bool
{
return $this->active = session_status() === \PHP_SESSION_ACTIVE;
}
/**
* Check if the session is started
*
* @return boolean
*
* @since 2.0.0
*/
public function isStarted(): bool
{
return $this->started;
}
/**
* Unset a variable from the session store
*
* @param string $name Name of variable
*
* @return mixed The value from session or NULL if not set
*
* @since 2.0.0
*/
public function remove(string $name)
{
if (!$this->isStarted()) {
$this->start();
}
$old = $_SESSION[$name] ?? null;
unset($_SESSION[$name]);
return $old;
}
/**
* Regenerates the session ID that represents this storage.
*
* This method must invoke session_regenerate_id($destroy) unless this interface is used for a storage object designed for unit
* or functional testing where a real PHP session would interfere with testing.
*
* @param boolean $destroy Destroy session when regenerating?
*
* @return boolean True on success
*
* @see session_regenerate_id()
* @since 2.0.0
*/
public function regenerate(bool $destroy = false): bool
{
if (headers_sent() || !$this->isActive()) {
return false;
}
return session_regenerate_id($destroy);
}
/**
* Set data into the session store
*
* @param string $name Name of a variable
* @param mixed $value Value of a variable
*
* @return mixed Old value of a variable
*
* @since 2.0.0
*/
public function set(string $name, $value = null)
{
if (!$this->isStarted()) {
$this->start();
}
$old = $_SESSION[$name] ?? null;
$_SESSION[$name] = $value;
return $old;
}
/**
* Registers session save handler as a PHP session handler
*
* @param \SessionHandlerInterface $handler The save handler to use
*
* @return $this
*
* @since 2.0.0
* @throws \RuntimeException
*/
public function setHandler(?\SessionHandlerInterface $handler = null): self
{
// If the handler is an instance of our HandlerInterface, check whether it is supported
if ($handler instanceof HandlerInterface) {
if (!$handler::isSupported()) {
throw new \RuntimeException(
sprintf(
'The "%s" handler is not supported in this environment.',
\get_class($handler)
)
);
}
}
$this->handler = $handler;
if (!headers_sent() && !$this->isActive()) {
session_set_save_handler($this->handler, false);
}
return $this;
}
/**
* Set the session ID
*
* @param string $id The session ID
*
* @return $this
*
* @since 2.0.0
* @throws \LogicException
*/
public function setId(string $id)
{
if ($this->isActive()) {
throw new \LogicException('Cannot change the ID of an active session');
}
session_id($id);
return $this;
}
/**
* Set the session name
*
* @param string $name The session name
*
* @return $this
*
* @since 2.0.0
* @throws \LogicException
*/
public function setName(string $name)
{
if ($this->isActive()) {
throw new \LogicException('Cannot change the name of an active session');
}
session_name($name);
return $this;
}
/**
* Sets session.* ini variables.
*
* For convenience we omit 'session.' from the beginning of the keys.
* Explicitly ignores other ini keys.
*
* @param array $options Session ini directives array(key => value).
*
* @return $this
*
* @note Based on \Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage::setOptions()
* @see http://php.net/session.configuration
* @since 2.0.0
*/
public function setOptions(array $options): self
{
if (headers_sent() || $this->isActive()) {
return $this;
}
$validOptions = array_flip(
[
'cache_limiter', 'cache_expire', 'cookie_domain', 'cookie_httponly', 'cookie_lifetime', 'cookie_path', 'cookie_secure', 'gc_divisor',
'gc_maxlifetime', 'gc_probability', 'lazy_write', 'name', 'referer_check', 'serialize_handler', 'use_strict_mode', 'use_cookies',
'use_only_cookies', 'use_trans_sid', 'upload_progress.enabled', 'upload_progress.cleanup', 'upload_progress.prefix',
'upload_progress.name', 'upload_progress.freq', 'upload_progress.min-freq', 'url_rewriter.tags', 'sid_length',
'sid_bits_per_character', 'trans_sid_hosts', 'trans_sid_tags',
]
);
foreach ($options as $key => $value) {
if (isset($validOptions[$key])) {
ini_set('session.' . $key, $value);
}
}
return $this;
}
/**
* Start a session
*
* @return void
*
* @since 2.0.0
*/
public function start(): void
{
if ($this->isStarted()) {
return;
}
if ($this->isActive()) {
throw new \RuntimeException('Failed to start the session: already started by PHP.');
}
if (ini_get('session.use_cookies') && headers_sent($file, $line)) {
throw new \RuntimeException(
sprintf('Failed to start the session because headers have already been sent by "%s" at line %d.', $file, $line)
);
}
if (!session_start()) {
throw new \RuntimeException('Failed to start the session');
}
$this->isActive();
$this->closed = false;
$this->started = true;
}
}

View File

@ -0,0 +1,372 @@
<?php
/**
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Session\Storage;
use Joomla\Session\StorageInterface;
/**
* Session storage object that stores objects in Runtime memory. This is designed for use in CLI Apps, including
* unit testing applications in PHPUnit.
*
* @since 2.0.0
*/
class RuntimeStorage implements StorageInterface
{
/**
* Flag if the session is active
*
* @var boolean
* @since 2.0.0
*/
private $active = false;
/**
* Internal flag identifying whether the session has been closed
*
* @var boolean
* @since 2.0.0
*/
private $closed = false;
/**
* Internal data store
*
* @var array
* @since 2.0.0
*/
private $data = [];
/**
* Session ID
*
* @var string
* @since 2.0.0
*/
private $id = '';
/**
* Session Name
*
* @var string
* @since 2.0.0
*/
private $name = 'MockSession';
/**
* Internal flag identifying whether the session has been started
*
* @var boolean
* @since 2.0.0
*/
private $started = false;
/**
* Retrieves all variables from the session store
*
* @return array
*/
public function all(): array
{
return $this->data;
}
/**
* Clears all variables from the session store
*
* @return void
*
* @since 2.0.0
*/
public function clear(): void
{
$this->data = [];
}
/**
* Writes session data and ends session
*
* @return void
*
* @see session_write_close()
* @since 2.0.0
*/
public function close(): void
{
$this->closed = true;
$this->started = false;
}
/**
* Perform session data garbage collection
*
* @return integer|boolean Number of deleted sessions on success or boolean false on failure or if the function is unsupported
*
* @see session_gc()
* @since 2.0.0
*/
public function gc()
{
return 0;
}
/**
* Aborts the current session
*
* @return boolean
*
* @see session_abort()
* @since 2.0.0
*/
public function abort(): bool
{
$this->closed = true;
$this->started = false;
return true;
}
/**
* Generates a session ID
*
* @return string
*
* @since 2.0.0
*/
private function generateId(): string
{
return hash('sha256', uniqid(mt_rand()));
}
/**
* Get data from the session store
*
* @param string $name Name of a variable
* @param mixed $default Default value of a variable if not set
*
* @return mixed Value of a variable
*
* @since 2.0.0
*/
public function get(string $name, $default)
{
if (!$this->isStarted()) {
$this->start();
}
if (isset($this->data[$name])) {
return $this->data[$name];
}
return $default;
}
/**
* Get the session ID
*
* @return string The session ID
*
* @since 2.0.0
*/
public function getId(): string
{
return $this->id;
}
/**
* Get the session name
*
* @return string The session name
*
* @since 2.0.0
*/
public function getName(): string
{
return $this->name;
}
/**
* Check whether data exists in the session store
*
* @param string $name Name of variable
*
* @return boolean
*
* @since 2.0.0
*/
public function has(string $name): bool
{
if (!$this->isStarted()) {
$this->start();
}
return isset($this->data[$name]);
}
/**
* Check if the session is active
*
* @return boolean
*
* @since 2.0.0
*/
public function isActive(): bool
{
return $this->active = $this->started;
}
/**
* Check if the session is started
*
* @return boolean
*
* @since 2.0.0
*/
public function isStarted(): bool
{
return $this->started;
}
/**
* Unset a variable from the session store
*
* @param string $name Name of variable
*
* @return mixed The value from session or NULL if not set
*
* @since 2.0.0
*/
public function remove(string $name)
{
if (!$this->isStarted()) {
$this->start();
}
$old = $this->data[$name] ?? null;
unset($this->data[$name]);
return $old;
}
/**
* Regenerates the session ID that represents this storage.
*
* This method must invoke session_regenerate_id($destroy) unless this interface is used for a storage object designed for unit
* or functional testing where a real PHP session would interfere with testing.
*
* @param boolean $destroy Destroy session when regenerating?
*
* @return boolean True on success
*
* @see session_regenerate_id()
* @since 2.0.0
*/
public function regenerate(bool $destroy = false): bool
{
if (!$this->isActive()) {
return false;
}
if ($destroy) {
$this->id = $this->generateId();
}
return true;
}
/**
* Set data into the session store
*
* @param string $name Name of a variable
* @param mixed $value Value of a variable
*
* @return mixed Old value of a variable
*
* @since 2.0.0
*/
public function set(string $name, $value = null)
{
if (!$this->isStarted()) {
$this->start();
}
$old = $this->data[$name] ?? null;
$this->data[$name] = $value;
return $old;
}
/**
* Set the session ID
*
* @param string $id The session ID
*
* @return $this
*
* @since 2.0.0
* @throws \LogicException
*/
public function setId(string $id)
{
if ($this->isActive()) {
throw new \LogicException('Cannot change the ID of an active session');
}
$this->id = $id;
return $this;
}
/**
* Set the session name
*
* @param string $name The session name
*
* @return $this
*
* @since 2.0.0
* @throws \LogicException
*/
public function setName(string $name)
{
if ($this->isActive()) {
throw new \LogicException('Cannot change the name of an active session');
}
$this->name = $name;
return $this;
}
/**
* Start a session
*
* @return void
*
* @since 2.0.0
*/
public function start(): void
{
if ($this->isStarted()) {
return;
}
if ($this->isActive()) {
throw new \RuntimeException('Failed to start the session: already started by PHP.');
}
if (empty($this->id)) {
$this->setId($this->generateId());
}
$this->closed = false;
$this->started = true;
$this->isActive();
}
}

View File

@ -0,0 +1,194 @@
<?php
/**
* Part of the Joomla Framework Session Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Session;
/**
* Interface defining a Joomla! session storage object
*
* @since 2.0.0
*/
interface StorageInterface
{
/**
* Get the session name
*
* @return string The session name
*
* @since 2.0.0
*/
public function getName(): string;
/**
* Set the session name
*
* @param string $name The session name
*
* @return $this
*
* @since 2.0.0
*/
public function setName(string $name);
/**
* Get the session ID
*
* @return string The session ID
*
* @since 2.0.0
*/
public function getId(): string;
/**
* Set the session ID
*
* @param string $id The session ID
*
* @return $this
*
* @since 2.0.0
*/
public function setId(string $id);
/**
* Check if the session is active
*
* @return boolean
*
* @since 2.0.0
*/
public function isActive(): bool;
/**
* Check if the session is started
*
* @return boolean
*
* @since 2.0.0
*/
public function isStarted(): bool;
/**
* Get data from the session store
*
* @param string $name Name of a variable
* @param mixed $default Default value of a variable if not set
*
* @return mixed Value of a variable
*
* @since 2.0.0
*/
public function get(string $name, $default);
/**
* Set data into the session store
*
* @param string $name Name of a variable
* @param mixed $value Value of a variable
*
* @return mixed Old value of a variable
*
* @since 2.0.0
*/
public function set(string $name, $value);
/**
* Check whether data exists in the session store
*
* @param string $name Name of variable
*
* @return boolean
*
* @since 2.0.0
*/
public function has(string $name): bool;
/**
* Unset a variable from the session store
*
* @param string $name Name of variable
*
* @return mixed The value from session or NULL if not set
*
* @since 2.0.0
*/
public function remove(string $name);
/**
* Clears all variables from the session store
*
* @return void
*
* @since 2.0.0
*/
public function clear(): void;
/**
* Retrieves all variables from the session store
*
* @return array
*
* @since 2.0.0
*/
public function all(): array;
/**
* Start a session
*
* @return void
*
* @since 2.0.0
*/
public function start(): void;
/**
* Regenerates the session ID that represents this storage.
*
* This method must invoke session_regenerate_id($destroy) unless this interface is used for a storage object designed for unit
* or functional testing where a real PHP session would interfere with testing.
*
* @param boolean $destroy Destroy session when regenerating?
*
* @return boolean True on success
*
* @see session_regenerate_id()
* @since 2.0.0
*/
public function regenerate(bool $destroy = false): bool;
/**
* Writes session data and ends session
*
* @return void
*
* @see session_write_close()
* @since 2.0.0
*/
public function close(): void;
/**
* Perform session data garbage collection
*
* @return integer|boolean Number of deleted sessions on success or boolean false on failure or if the function is unsupported
*
* @see session_gc()
* @since 2.0.0
*/
public function gc();
/**
* Aborts the current session
*
* @return boolean
*
* @see session_abort()
* @since 2.0.0
*/
public function abort(): bool;
}

View File

@ -0,0 +1,84 @@
<?php
/**
* Part of the Joomla Framework Session Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Session\Validator;
use Joomla\Input\Input;
use Joomla\Session\Exception\InvalidSessionException;
use Joomla\Session\SessionInterface;
use Joomla\Session\ValidatorInterface;
use Joomla\Utilities\IpHelper;
/**
* Interface for validating a part of the session
*
* @since 2.0.0
*/
class AddressValidator implements ValidatorInterface
{
/**
* The Input object.
*
* @var Input
* @since 2.0.0
*/
private $input;
/**
* The session object.
*
* @var SessionInterface
* @since 2.0.0
*/
private $session;
/**
* Constructor
*
* @param Input $input The input object
* @param SessionInterface $session DispatcherInterface for the session to use.
*
* @since 2.0.0
*/
public function __construct(Input $input, SessionInterface $session)
{
$this->input = $input;
$this->session = $session;
}
/**
* Validates the session
*
* @param boolean $restart Flag if the session should be restarted
*
* @return void
*
* @since 2.0.0
* @throws InvalidSessionException
*/
public function validate(bool $restart = false): void
{
if ($restart) {
$this->session->set('session.client.address', null);
}
$remoteAddr = IpHelper::getIp();
// Check for client address
if (!empty($remoteAddr) && filter_var($remoteAddr, FILTER_VALIDATE_IP) !== false) {
$ip = $this->session->get('session.client.address');
if ($ip === null) {
$this->session->set('session.client.address', $remoteAddr);
} elseif ($remoteAddr !== $ip) {
throw new InvalidSessionException('Invalid client IP');
}
}
}
}

View File

@ -0,0 +1,75 @@
<?php
/**
* Part of the Joomla Framework Session Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Session\Validator;
use Joomla\Input\Input;
use Joomla\Session\SessionInterface;
use Joomla\Session\ValidatorInterface;
/**
* Interface for validating a part of the session
*
* @since 2.0.0
*/
class ForwardedValidator implements ValidatorInterface
{
/**
* The Input object.
*
* @var Input
* @since 2.0.0
*/
private $input;
/**
* The session object.
*
* @var SessionInterface
* @since 2.0.0
*/
private $session;
/**
* Constructor
*
* @param Input $input The input object
* @param SessionInterface $session DispatcherInterface for the session to use.
*
* @since 2.0.0
*/
public function __construct(Input $input, SessionInterface $session)
{
$this->input = $input;
$this->session = $session;
}
/**
* Validates the session
*
* @param boolean $restart Flag if the session should be restarted
*
* @return void
*
* @since 2.0.0
*/
public function validate(bool $restart = false): void
{
if ($restart) {
$this->session->set('session.client.forwarded', null);
}
$xForwardedFor = $this->input->server->getString('HTTP_X_FORWARDED_FOR', '');
// Record proxy forwarded for in the session in case we need it later
if (!empty($xForwardedFor) && filter_var($xForwardedFor, FILTER_VALIDATE_IP) !== false) {
$this->session->set('session.client.forwarded', $xForwardedFor);
}
}
}

View File

@ -0,0 +1,30 @@
<?php
/**
* Part of the Joomla Framework Session Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Session;
/**
* Interface for validating a part of the session
*
* @since 2.0.0
*/
interface ValidatorInterface
{
/**
* Validates the session
*
* @param boolean $restart Flag if the session should be restarted
*
* @return void
*
* @since 2.0.0
* @throws Exception\InvalidSessionException
*/
public function validate(bool $restart = false): void;
}