Completed
Push — master ( 71718d...90a3d2 )
by Rain
04:31
created

RecaptchaPlugin::FilterAjaxResponse()   C

Complexity

Conditions 11
Paths 7

Size

Total Lines 33
Code Lines 16

Duplication

Lines 33
Ratio 100 %

Importance

Changes 0
Metric Value
cc 11
eloc 16
nc 7
nop 2
dl 33
loc 33
rs 5.2653
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
class RecaptchaPlugin extends \RainLoop\Plugins\AbstractPlugin
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
4
{
5
	/**
6
	 * @return void
7
	 */
8
	public function Init()
9
	{
10
		$this->UseLangs(true);
11
		
12
		$this->addJs('js/recaptcha.js');
13
		
14
		$this->addHook('ajax.action-pre-call', 'AjaxActionPreCall');
15
		$this->addHook('filter.ajax-response', 'FilterAjaxResponse');
16
17
		$this->addTemplate('templates/PluginLoginReCaptchaGroup.html');
18
		$this->addTemplateHook('Login', 'BottomControlGroup', 'PluginLoginReCaptchaGroup');
19
	}
20
	
21
	/**
22
	 * @return array
23
	 */
24
	public function configMapping()
25
	{
26
		return array(
27
			\RainLoop\Plugins\Property::NewInstance('public_key')->SetLabel('Public Key')
28
				->SetAllowedInJs(true)
29
				->SetDefaultValue(''),
30
			\RainLoop\Plugins\Property::NewInstance('private_key')->SetLabel('Private Key')
31
				->SetDefaultValue(''),
32
			\RainLoop\Plugins\Property::NewInstance('error_limit')->SetLabel('Limit')
33
				->SetType(\RainLoop\Enumerations\PluginPropertyType::SELECTION)
34
				->SetDefaultValue(array(0, 1, 2, 3, 4, 5))
35
				->SetDescription('')
36
		);
37
	}
38
39
	/**
40
	 * @return string
41
	 */
42
	private function getCaptchaCacherKey()
43
	{
44
		return 'Captcha/Login/'.\RainLoop\Utils::GetConnectionToken();
45
	}
46
47
	/**
48
	 * @return int
49
	 */
50 View Code Duplication
	private function getLimit()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
51
	{
52
		$iConfigLimit = $this->Config()->Get('plugin', 'error_limit', 0);
53
		if (0 < $iConfigLimit)
54
		{
55
			$oCacher = $this->Manager()->Actions()->Cacher();
56
			$sLimit = $oCacher && $oCacher->IsInited() ? $oCacher->Get($this->getCaptchaCacherKey()) : '0';
57
			
58
			if (0 < strlen($sLimit) && is_numeric($sLimit))
59
			{
60
				$iConfigLimit -= (int) $sLimit;
61
			}
62
		}
63
64
		return $iConfigLimit;
65
	}
66
67
	/**
68
	 * @return void
69
	 */
70 View Code Duplication
	public function FilterAppDataPluginSection($bAdmin, $bAuth, &$aData)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
71
	{
72
		if (!$bAdmin && !$bAuth && is_array($aData))
73
		{
74
			$aData['show_captcha_on_login'] = 1 > $this->getLimit();
75
		}
76
	}
77
78
	/**
79
	 * @param string $sAction
80
	 */
81
	public function AjaxActionPreCall($sAction)
0 ignored issues
show
Coding Style introduced by
AjaxActionPreCall uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
82
	{
83
		if ('Login' === $sAction && 0 >= $this->getLimit())
84
		{
85
			require_once __DIR__.'/recaptchalib.php';
86
87
			$oResp = recaptcha_check_answer(
88
				$this->Config()->Get('plugin', 'private_key', ''),
89
				isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
90
				$this->Manager()->Actions()->GetActionParam('RecaptchaChallenge', ''),
91
				$this->Manager()->Actions()->GetActionParam('RecaptchaResponse', '')
92
			);
93
94
			if (!$oResp || !isset($oResp->is_valid) || !$oResp->is_valid)
95
			{
96
				$this->Manager()->Actions()->Logger()->WriteDump($oResp);
97
				throw new \RainLoop\Exceptions\ClientException(\RainLoop\Notifications::CaptchaError);
98
			}
99
		}
100
	}
101
102
	/**
103
	 * @param string $sAction
104
	 * @param array $aResponseItem
105
	 */
106 View Code Duplication
	public function FilterAjaxResponse($sAction, &$aResponseItem)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
107
	{
108
		if ('Login' === $sAction && $aResponseItem && isset($aResponseItem['Result']))
0 ignored issues
show
Bug Best Practice introduced by
The expression $aResponseItem of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
109
		{
110
			$oCacher = $this->Manager()->Actions()->Cacher();
111
			$iConfigLimit = (int) $this->Config()->Get('plugin', 'error_limit', 0);
112
			$sKey = $this->getCaptchaCacherKey();
113
114
			if (0 < $iConfigLimit && $oCacher && $oCacher->IsInited())
115
			{
116
				if (false === $aResponseItem['Result'])
117
				{
118
					$iLimit = 0;
119
					$sLimut = $oCacher->Get($sKey);
120
					if (0 < strlen($sLimut) && is_numeric($sLimut))
121
					{
122
						$iLimit = (int) $sLimut;
123
					}
124
125
					$oCacher->Set($sKey, ++$iLimit);
126
127
					if ($iConfigLimit <= $iLimit)
128
					{
129
						$aResponseItem['Captcha'] = true;
130
					}
131
				}
132
				else
133
				{
134
					$oCacher->Delete($sKey);
135
				}
136
			}
137
		}
138
	}
139
}
140