3 use MediaWiki\Session\SessionManager;
5 abstract class CaptchaStore {
7 * Store the correct answer for a given captcha
9 * @param $info String the captcha result
11 abstract public function store( $index, $info );
14 * Retrieve the answer for a given captcha
15 * @param $index String
16 * @return String|false
18 abstract public function retrieve( $index );
21 * Delete a result once the captcha has been used, so it cannot be reused
24 abstract public function clear( $index );
27 * Whether this type of CaptchaStore needs cookies
30 abstract public function cookiesNeeded();
33 * The singleton instance
36 private static $instance;
39 * Get somewhere to store captcha data that will persist between requests
42 * @return CaptchaStore
44 final public static function get() {
45 if ( !self::$instance instanceof self ) {
46 global $wgCaptchaStorageClass;
47 if ( in_array( 'CaptchaStore', class_parents( $wgCaptchaStorageClass ) ) ) {
48 self::$instance = new $wgCaptchaStorageClass;
50 throw new Exception( "Invalid CaptchaStore class $wgCaptchaStorageClass" );
53 return self::$instance;
56 final public static function unsetInstanceForTests() {
57 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
58 throw new MWException( 'Cannot unset ' . __CLASS__ . ' instance in operation.' );
60 self::$instance = null;
64 * Protected constructor: no creating instances except through the factory method above
66 protected function __construct() {
70 class CaptchaSessionStore extends CaptchaStore {
71 protected function __construct() {
72 // Make sure the session is started
73 SessionManager::getGlobalSession()->persist();
76 function store( $index, $info ) {
77 SessionManager::getGlobalSession()->set( 'captcha' . $index, $info );
80 function retrieve( $index ) {
81 return SessionManager::getGlobalSession()->get( 'captcha' . $index, false );
84 function clear( $index ) {
85 SessionManager::getGlobalSession()->remove( 'captcha' . $index );
88 function cookiesNeeded() {
93 class CaptchaCacheStore extends CaptchaStore {
94 function store( $index, $info ) {
95 global $wgCaptchaSessionExpiration;
97 ObjectCache::getMainStashInstance()->set(
98 wfMemcKey( 'captcha', $index ),
100 $wgCaptchaSessionExpiration
104 function retrieve( $index ) {
105 $info = ObjectCache::getMainStashInstance()->get( wfMemcKey( 'captcha', $index ) );
113 function clear( $index ) {
114 ObjectCache::getMainStashInstance()->delete( wfMemcKey( 'captcha', $index ) );
117 function cookiesNeeded() {
122 class CaptchaHashStore extends CaptchaStore {
123 protected $data = [];
125 public function store( $index, $info ) {
126 $this->data[$index] = $info;
129 public function retrieve( $index ) {
130 if ( array_key_exists( $index, $this->data ) ) {
131 return $this->data[$index];
136 public function clear( $index ) {
137 unset( $this->data[$index] );
140 public function cookiesNeeded() {
144 public function clearAll() {