Completed
Pull Request — master (#19)
by Helpful
02:47
created
code/AkismetField.php 1 patch
Indentation   +180 added lines, -180 removed lines patch added patch discarded remove patch
@@ -8,206 +8,206 @@
 block discarded – undo
8 8
  */
9 9
 class AkismetField extends FormField
10 10
 {
11
-    /**
12
-     * @var array
13
-     */
14
-    private $fieldMapping = array();
11
+	/**
12
+	 * @var array
13
+	 */
14
+	private $fieldMapping = array();
15 15
 
16
-    /**
17
-     *
18
-     * @var boolean
19
-     */
20
-    protected $isSpam = null;
16
+	/**
17
+	 *
18
+	 * @var boolean
19
+	 */
20
+	protected $isSpam = null;
21 21
     
22
-    /**
23
-     * Get the nested confirmation checkbox field
24
-     * 
25
-     * @return CheckboxField
26
-     */
27
-    protected function confirmationField()
28
-    {
29
-        // Check if confirmation is required
30
-        $requireConfirmation = Config::inst()->get('AkismetSpamProtector', 'require_confirmation');
31
-        if (empty($requireConfirmation)) {
32
-            return null;
33
-        }
22
+	/**
23
+	 * Get the nested confirmation checkbox field
24
+	 * 
25
+	 * @return CheckboxField
26
+	 */
27
+	protected function confirmationField()
28
+	{
29
+		// Check if confirmation is required
30
+		$requireConfirmation = Config::inst()->get('AkismetSpamProtector', 'require_confirmation');
31
+		if (empty($requireConfirmation)) {
32
+			return null;
33
+		}
34 34
         
35
-        // If confirmation is required then return a checkbox
36
-        return CheckboxField::create(
37
-            $this->getName(),
38
-            _t('AkismetField.NOTIFICATION', 'I understand that, and give consent to, having this content submitted to '
39
-                . 'a third party for automated spam detection')
40
-        )
41
-            ->setError($this->Message(), $this->MessageType())
42
-            ->setForm($this->getForm());
43
-    }
35
+		// If confirmation is required then return a checkbox
36
+		return CheckboxField::create(
37
+			$this->getName(),
38
+			_t('AkismetField.NOTIFICATION', 'I understand that, and give consent to, having this content submitted to '
39
+				. 'a third party for automated spam detection')
40
+		)
41
+			->setError($this->Message(), $this->MessageType())
42
+			->setForm($this->getForm());
43
+	}
44 44
     
45
-    public function Field($properties = array())
46
-    {
47
-        $checkbox = $this->confirmationField();
48
-        if ($checkbox) {
49
-            return $checkbox->Field($properties);
50
-        }
51
-    }
45
+	public function Field($properties = array())
46
+	{
47
+		$checkbox = $this->confirmationField();
48
+		if ($checkbox) {
49
+			return $checkbox->Field($properties);
50
+		}
51
+	}
52 52
     
53
-    public function FieldHolder($properties = array())
54
-    {
55
-        $checkbox = $this->confirmationField();
56
-        if ($checkbox) {
57
-            return $checkbox->FieldHolder($properties);
58
-        }
59
-    }
53
+	public function FieldHolder($properties = array())
54
+	{
55
+		$checkbox = $this->confirmationField();
56
+		if ($checkbox) {
57
+			return $checkbox->FieldHolder($properties);
58
+		}
59
+	}
60 60
     
61
-    /**
62
-     * @return array
63
-     */
64
-    public function getSpamMappedData()
65
-    {
66
-        if (empty($this->fieldMapping)) {
67
-            return null;
68
-        }
61
+	/**
62
+	 * @return array
63
+	 */
64
+	public function getSpamMappedData()
65
+	{
66
+		if (empty($this->fieldMapping)) {
67
+			return null;
68
+		}
69 69
         
70
-        $result = array();
71
-        $data = $this->form->getData();
70
+		$result = array();
71
+		$data = $this->form->getData();
72 72
 
73
-        foreach ($this->fieldMapping as $fieldName => $mappedName) {
74
-            $result[$mappedName] = (isset($data[$fieldName])) ? $data[$fieldName] : null;
75
-        }
73
+		foreach ($this->fieldMapping as $fieldName => $mappedName) {
74
+			$result[$mappedName] = (isset($data[$fieldName])) ? $data[$fieldName] : null;
75
+		}
76 76
 
77
-        return $result;
78
-    }
77
+		return $result;
78
+	}
79 79
     
80
-    /**
81
-     * This function first gets values from mapped fields and then check these values against
82
-     * Mollom web service and then notify callback object with the spam checking result.
83
-     * @param Validator $validator
84
-     * @return 	boolean		- true when Mollom confirms that the submission is ham (not spam)
85
-     *						- false when Mollom confirms that the submission is spam 
86
-     * 						- false when Mollom say 'unsure'. 
87
-     *						  In this case, 'mollom_captcha_requested' session is set to true 
88
-     *       				  so that Field() knows it's time to display captcha 			
89
-     */
90
-    public function validate($validator)
91
-    {
80
+	/**
81
+	 * This function first gets values from mapped fields and then check these values against
82
+	 * Mollom web service and then notify callback object with the spam checking result.
83
+	 * @param Validator $validator
84
+	 * @return 	boolean		- true when Mollom confirms that the submission is ham (not spam)
85
+	 *						- false when Mollom confirms that the submission is spam 
86
+	 * 						- false when Mollom say 'unsure'. 
87
+	 *						  In this case, 'mollom_captcha_requested' session is set to true 
88
+	 *       				  so that Field() knows it's time to display captcha 			
89
+	 */
90
+	public function validate($validator)
91
+	{
92 92
         
93
-        // Check that, if necessary, the user has given permission to check for spam
94
-        $requireConfirmation = Config::inst()->get('AkismetSpamProtector', 'require_confirmation');
95
-        if ($requireConfirmation && !$this->Value()) {
96
-            $validator->validationError(
97
-                $this->name,
98
-                _t(
99
-                    'AkismetField.NOTIFICATIONREQUIRED',
100
-                    'You must give consent to submit this content to spam detection'
101
-                ),
102
-                "error"
103
-            );
104
-            return false;
105
-        }
93
+		// Check that, if necessary, the user has given permission to check for spam
94
+		$requireConfirmation = Config::inst()->get('AkismetSpamProtector', 'require_confirmation');
95
+		if ($requireConfirmation && !$this->Value()) {
96
+			$validator->validationError(
97
+				$this->name,
98
+				_t(
99
+					'AkismetField.NOTIFICATIONREQUIRED',
100
+					'You must give consent to submit this content to spam detection'
101
+				),
102
+				"error"
103
+			);
104
+			return false;
105
+		}
106 106
         
107
-        // Check result
108
-        $isSpam = $this->getIsSpam();
109
-        if (!$isSpam) {
110
-            return true;
111
-        }
107
+		// Check result
108
+		$isSpam = $this->getIsSpam();
109
+		if (!$isSpam) {
110
+			return true;
111
+		}
112 112
 
113
-        // Save error message
114
-        $errorMessage = _t(
115
-            'AkismetField.SPAM',
116
-            "Your submission has been rejected because it was treated as spam."
117
-        );
113
+		// Save error message
114
+		$errorMessage = _t(
115
+			'AkismetField.SPAM',
116
+			"Your submission has been rejected because it was treated as spam."
117
+		);
118 118
 
119
-        // If spam should be allowed, let it pass and save it for later
120
-        if (Config::inst()->get('AkismetSpamProtector', 'save_spam')) {
121
-            // In order to save spam but still display the spam message, we must mock a form message
122
-            // without failing the validation
123
-            $errors = array(array(
124
-                'fieldName' => $this->name,
125
-                'message' => $errorMessage,
126
-                'messageType' => 'error',
127
-            ));
128
-            $formName = $this->getForm()->FormName();
129
-            Session::set("FormInfo.{$formName}.errors", $errors);
130
-            return true;
131
-        } else {
132
-            // Mark as spam
133
-            $validator->validationError($this->name, $errorMessage, "error");
134
-            return false;
135
-        }
136
-    }
119
+		// If spam should be allowed, let it pass and save it for later
120
+		if (Config::inst()->get('AkismetSpamProtector', 'save_spam')) {
121
+			// In order to save spam but still display the spam message, we must mock a form message
122
+			// without failing the validation
123
+			$errors = array(array(
124
+				'fieldName' => $this->name,
125
+				'message' => $errorMessage,
126
+				'messageType' => 'error',
127
+			));
128
+			$formName = $this->getForm()->FormName();
129
+			Session::set("FormInfo.{$formName}.errors", $errors);
130
+			return true;
131
+		} else {
132
+			// Mark as spam
133
+			$validator->validationError($this->name, $errorMessage, "error");
134
+			return false;
135
+		}
136
+	}
137 137
 
138
-    /**
139
-     * Determine if this field is spam or not
140
-     *
141
-     * @return boolean
142
-     */
143
-    public function getIsSpam()
144
-    {
145
-        // Prevent multiple API calls
146
-        if ($this->isSpam !== null) {
147
-            return $this->isSpam;
148
-        }
138
+	/**
139
+	 * Determine if this field is spam or not
140
+	 *
141
+	 * @return boolean
142
+	 */
143
+	public function getIsSpam()
144
+	{
145
+		// Prevent multiple API calls
146
+		if ($this->isSpam !== null) {
147
+			return $this->isSpam;
148
+		}
149 149
 
150
-        // Check bypass permission
151
-        $permission = Config::inst()->get('AkismetSpamProtector', 'bypass_permission');
152
-        if ($permission && Permission::check($permission)) {
153
-            return false;
154
-        }
150
+		// Check bypass permission
151
+		$permission = Config::inst()->get('AkismetSpamProtector', 'bypass_permission');
152
+		if ($permission && Permission::check($permission)) {
153
+			return false;
154
+		}
155 155
 
156
-        // if the user has logged and there's no force check on member
157
-        $bypassMember = Config::inst()->get('AkismetSpamProtector', 'bypass_members');
158
-        if ($bypassMember && Member::currentUser()) {
159
-            return false;
160
-        }
156
+		// if the user has logged and there's no force check on member
157
+		$bypassMember = Config::inst()->get('AkismetSpamProtector', 'bypass_members');
158
+		if ($bypassMember && Member::currentUser()) {
159
+			return false;
160
+		}
161 161
 
162
-        // Map input fields to spam fields
163
-        $mappedData = $this->getSpamMappedData();
164
-        $content = isset($mappedData['body']) ? $mappedData['body'] : null;
165
-        $author = isset($mappedData['authorName']) ? $mappedData['authorName'] : null;
166
-        $email = isset($mappedData['authorMail']) ? $mappedData['authorMail'] : null;
167
-        $url = isset($mappedData['authorUrl']) ? $mappedData['authorUrl'] : null;
162
+		// Map input fields to spam fields
163
+		$mappedData = $this->getSpamMappedData();
164
+		$content = isset($mappedData['body']) ? $mappedData['body'] : null;
165
+		$author = isset($mappedData['authorName']) ? $mappedData['authorName'] : null;
166
+		$email = isset($mappedData['authorMail']) ? $mappedData['authorMail'] : null;
167
+		$url = isset($mappedData['authorUrl']) ? $mappedData['authorUrl'] : null;
168 168
 
169
-        // Check result
170
-        $api = AkismetSpamProtector::api();
171
-        $this->isSpam = $api && $api->isSpam($content, $author, $email, $url);
172
-        return $this->isSpam;
173
-    }
169
+		// Check result
170
+		$api = AkismetSpamProtector::api();
171
+		$this->isSpam = $api && $api->isSpam($content, $author, $email, $url);
172
+		return $this->isSpam;
173
+	}
174 174
     
175
-    /**
176
-     * Get the fields to map spam protection too
177
-     *
178
-     * @return array Associative array of Field Names, where the indexes of the array are
179
-     * the field names of the form and the values are the standard spamprotection
180
-     * fields used by the protector
181
-     */
182
-    public function getFieldMapping()
183
-    {
184
-        return $this->fieldMapping;
185
-    }
175
+	/**
176
+	 * Get the fields to map spam protection too
177
+	 *
178
+	 * @return array Associative array of Field Names, where the indexes of the array are
179
+	 * the field names of the form and the values are the standard spamprotection
180
+	 * fields used by the protector
181
+	 */
182
+	public function getFieldMapping()
183
+	{
184
+		return $this->fieldMapping;
185
+	}
186 186
 
187
-    /**
188
-     * Set the fields to map spam protection too
189
-     *
190
-     * @param array $fieldMapping array of Field Names, where the indexes of the array are
191
-     * the field names of the form and the values are the standard spamprotection
192
-     * fields used by the protector
193
-     * @return self
194
-     */
195
-    public function setFieldMapping($fieldMapping)
196
-    {
197
-        $this->fieldMapping = $fieldMapping;
198
-        return $this;
199
-    }
187
+	/**
188
+	 * Set the fields to map spam protection too
189
+	 *
190
+	 * @param array $fieldMapping array of Field Names, where the indexes of the array are
191
+	 * the field names of the form and the values are the standard spamprotection
192
+	 * fields used by the protector
193
+	 * @return self
194
+	 */
195
+	public function setFieldMapping($fieldMapping)
196
+	{
197
+		$this->fieldMapping = $fieldMapping;
198
+		return $this;
199
+	}
200 200
 
201
-    /**
202
-     * Allow spam flag to be saved to the underlying data record
203
-     *
204
-     * @param \DataObjectInterface $record
205
-     */
206
-    public function saveInto(\DataObjectInterface $record)
207
-    {
208
-        if (Config::inst()->get('AkismetSpamProtector', 'save_spam')) {
209
-            $dataValue = $this->getIsSpam() ? 1 : 0;
210
-            $record->setCastedField($this->name, $dataValue);
211
-        }
212
-    }
201
+	/**
202
+	 * Allow spam flag to be saved to the underlying data record
203
+	 *
204
+	 * @param \DataObjectInterface $record
205
+	 */
206
+	public function saveInto(\DataObjectInterface $record)
207
+	{
208
+		if (Config::inst()->get('AkismetSpamProtector', 'save_spam')) {
209
+			$dataValue = $this->getIsSpam() ? 1 : 0;
210
+			$record->setCastedField($this->name, $dataValue);
211
+		}
212
+	}
213 213
 }
Please login to merge, or discard this patch.
code/AkismetSpamProtector.php 1 patch
Indentation   +104 added lines, -104 removed lines patch added patch discarded remove patch
@@ -8,122 +8,122 @@
 block discarded – undo
8 8
  */
9 9
 class AkismetSpamProtector implements SpamProtector
10 10
 {
11
-    /**
12
-     * Set this to your API key
13
-     * 
14
-     * @var string
15
-     * @config
16
-     */
17
-    private static $api_key = null;
11
+	/**
12
+	 * Set this to your API key
13
+	 * 
14
+	 * @var string
15
+	 * @config
16
+	 */
17
+	private static $api_key = null;
18 18
 
19
-    /**
20
-     * Permission required to bypass check
21
-     *
22
-     * @var string
23
-     * @config
24
-     */
25
-    private static $bypass_permission = 'ADMIN';
19
+	/**
20
+	 * Permission required to bypass check
21
+	 *
22
+	 * @var string
23
+	 * @config
24
+	 */
25
+	private static $bypass_permission = 'ADMIN';
26 26
 
27
-    /**
28
-     * Set to try to bypass check for all logged in users
29
-     *
30
-     * @var boolean
31
-     * @config
32
-     */
33
-    private static $bypass_members = false;
27
+	/**
28
+	 * Set to try to bypass check for all logged in users
29
+	 *
30
+	 * @var boolean
31
+	 * @config
32
+	 */
33
+	private static $bypass_members = false;
34 34
 
35
-    /**
36
-     * IMPORTANT: If you are operating in a country (such as Germany) that has content transmission disclosure
37
-     * requirements, set this to true in order to require a user prompt prior to submission of user data
38
-     * to the Akismet servers
39
-     *
40
-     * @var boolean
41
-     * @config
42
-     */
43
-    private static $require_confirmation = false;
35
+	/**
36
+	 * IMPORTANT: If you are operating in a country (such as Germany) that has content transmission disclosure
37
+	 * requirements, set this to true in order to require a user prompt prior to submission of user data
38
+	 * to the Akismet servers
39
+	 *
40
+	 * @var boolean
41
+	 * @config
42
+	 */
43
+	private static $require_confirmation = false;
44 44
 
45
-    /**
46
-     * Set to true to disable spam errors, instead saving this field to the dataobject with the spam
47
-     * detection as a flag. This will disable validation errors when spam is encountered.
48
-     * The flag will be saved to the same field specified by the 'name' option in enableSpamProtection()
49
-     *
50
-     * @var boolean
51
-     * @config
52
-     */
53
-    private static $save_spam = false;
45
+	/**
46
+	 * Set to true to disable spam errors, instead saving this field to the dataobject with the spam
47
+	 * detection as a flag. This will disable validation errors when spam is encountered.
48
+	 * The flag will be saved to the same field specified by the 'name' option in enableSpamProtection()
49
+	 *
50
+	 * @var boolean
51
+	 * @config
52
+	 */
53
+	private static $save_spam = false;
54 54
     
55
-    /**
56
-     * @var array
57
-     */
58
-    private $fieldMapping = array();
55
+	/**
56
+	 * @var array
57
+	 */
58
+	private $fieldMapping = array();
59 59
     
60
-    /**
61
-     * Overridden API key
62
-     *
63
-     * @var string
64
-     */
65
-    protected static $_api_key = null;
60
+	/**
61
+	 * Overridden API key
62
+	 *
63
+	 * @var string
64
+	 */
65
+	protected static $_api_key = null;
66 66
     
67
-    /**
68
-     * Set the API key
69
-     * 
70
-     * @param string $key
71
-     */
72
-    public static function set_api_key($key)
73
-    {
74
-        self::$_api_key = $key;
75
-    }
67
+	/**
68
+	 * Set the API key
69
+	 * 
70
+	 * @param string $key
71
+	 */
72
+	public static function set_api_key($key)
73
+	{
74
+		self::$_api_key = $key;
75
+	}
76 76
     
77
-    /**
78
-     * Get the API key
79
-     * 
80
-     * @return string
81
-     */
82
-    protected static function get_api_key()
83
-    {
84
-        if (self::$_api_key) {
85
-            return self::$_api_key;
86
-        }
77
+	/**
78
+	 * Get the API key
79
+	 * 
80
+	 * @return string
81
+	 */
82
+	protected static function get_api_key()
83
+	{
84
+		if (self::$_api_key) {
85
+			return self::$_api_key;
86
+		}
87 87
         
88
-        // Check config
89
-        $key = Config::inst()->get('AkismetSpamProtector', 'api_key');
90
-        if (!empty($key)) {
91
-            return $key;
92
-        }
88
+		// Check config
89
+		$key = Config::inst()->get('AkismetSpamProtector', 'api_key');
90
+		if (!empty($key)) {
91
+			return $key;
92
+		}
93 93
         
94
-        // Check environment
95
-        if (defined('SS_AKISMET_API_KEY')) {
96
-            return SS_AKISMET_API_KEY;
97
-        }
98
-    }
94
+		// Check environment
95
+		if (defined('SS_AKISMET_API_KEY')) {
96
+			return SS_AKISMET_API_KEY;
97
+		}
98
+	}
99 99
     
100
-    /**
101
-     * Retrieves Akismet API object singleton, or null if not configured
102
-     * 
103
-     * @return AkismetService
104
-     */
105
-    public static function api()
106
-    {
107
-        // Get API key and URL
108
-        $key = self::get_api_key();
109
-        if (empty($key)) {
110
-            user_error("AkismetSpamProtector is incorrectly configured. Please specify an API key.", E_USER_WARNING);
111
-            return null;
112
-        }
113
-        $url = Director::protocolAndHost();
100
+	/**
101
+	 * Retrieves Akismet API object singleton, or null if not configured
102
+	 * 
103
+	 * @return AkismetService
104
+	 */
105
+	public static function api()
106
+	{
107
+		// Get API key and URL
108
+		$key = self::get_api_key();
109
+		if (empty($key)) {
110
+			user_error("AkismetSpamProtector is incorrectly configured. Please specify an API key.", E_USER_WARNING);
111
+			return null;
112
+		}
113
+		$url = Director::protocolAndHost();
114 114
         
115
-        // Generate API object
116
-        return Injector::inst()->get('AkismetService', true, array($key, $url));
117
-    }
115
+		// Generate API object
116
+		return Injector::inst()->get('AkismetService', true, array($key, $url));
117
+	}
118 118
     
119
-    public function getFormField($name = null, $title = null, $value = null, $form = null, $rightTitle = null)
120
-    {
121
-        return AkismetField::create($name, $title, $value, $form, $rightTitle)
122
-            ->setFieldMapping($this->fieldMapping);
123
-    }
119
+	public function getFormField($name = null, $title = null, $value = null, $form = null, $rightTitle = null)
120
+	{
121
+		return AkismetField::create($name, $title, $value, $form, $rightTitle)
122
+			->setFieldMapping($this->fieldMapping);
123
+	}
124 124
 
125
-    public function setFieldMapping($fieldMapping)
126
-    {
127
-        $this->fieldMapping = $fieldMapping;
128
-    }
125
+	public function setFieldMapping($fieldMapping)
126
+	{
127
+		$this->fieldMapping = $fieldMapping;
128
+	}
129 129
 }
Please login to merge, or discard this patch.
code/config/AkismetConfig.php 1 patch
Indentation   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -5,12 +5,12 @@
 block discarded – undo
5 5
  */
6 6
 class AkismetConfig extends DataExtension
7 7
 {
8
-    private static $db = array(
9
-        'AkismetKey' => 'Varchar'
10
-    );
8
+	private static $db = array(
9
+		'AkismetKey' => 'Varchar'
10
+	);
11 11
 
12
-    public function updateCMSFields(FieldList $fields)
13
-    {
14
-        $fields->addFieldToTab('Root.Akismet', new PasswordField('AkismetKey', 'Akismet Key'));
15
-    }
12
+	public function updateCMSFields(FieldList $fields)
13
+	{
14
+		$fields->addFieldToTab('Root.Akismet', new PasswordField('AkismetKey', 'Akismet Key'));
15
+	}
16 16
 }
Please login to merge, or discard this patch.
code/config/AkismetProcessor.php 1 patch
Indentation   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -5,54 +5,54 @@
 block discarded – undo
5 5
  */
6 6
 class AkismetProcessor implements RequestFilter
7 7
 {
8
-    public function postRequest(SS_HTTPRequest $request, SS_HTTPResponse $response, DataModel $model)
9
-    {
10
-    }
11
-
12
-    public function preRequest(SS_HTTPRequest $request, Session $session, DataModel $model)
13
-    {
14
-        // Skip if database isn't ready
15
-        if (!$this->isDBReady()) {
16
-            return;
17
-        }
18
-
19
-        // Skip if SiteConfig doesn't have this extension
20
-        if (!SiteConfig::has_extension('AkismetConfig')) {
21
-            return;
22
-        }
23
-
24
-        // Check if key exists
25
-        $akismetKey = SiteConfig::current_site_config()->AkismetKey;
26
-        if ($akismetKey) {
27
-            AkismetSpamProtector::set_api_key($akismetKey);
28
-        }
29
-    }
30
-
31
-    /**
32
-     * Make sure the DB is ready before accessing siteconfig db field
33
-     *
34
-     * @return bool
35
-     */
36
-    protected function isDBReady()
37
-    {
38
-        if (!DB::isActive()) {
39
-            return false;
40
-        }
41
-
42
-        // Require table
43
-        if (!DB::getConn()->hasTable('SiteConfig')) {
44
-            return false;
45
-        }
46
-
47
-        // Ensure siteconfig has all fields necessary
48
-        $dbFields = DB::fieldList('SiteConfig');
49
-        if (empty($dbFields)) {
50
-            return false;
51
-        }
52
-
53
-        // Ensure that SiteConfig has all fields
54
-        $objFields = DataObject::database_fields('SiteConfig', false);
55
-        $missingFields = array_diff_key($objFields, $dbFields);
56
-        return empty($missingFields);
57
-    }
8
+	public function postRequest(SS_HTTPRequest $request, SS_HTTPResponse $response, DataModel $model)
9
+	{
10
+	}
11
+
12
+	public function preRequest(SS_HTTPRequest $request, Session $session, DataModel $model)
13
+	{
14
+		// Skip if database isn't ready
15
+		if (!$this->isDBReady()) {
16
+			return;
17
+		}
18
+
19
+		// Skip if SiteConfig doesn't have this extension
20
+		if (!SiteConfig::has_extension('AkismetConfig')) {
21
+			return;
22
+		}
23
+
24
+		// Check if key exists
25
+		$akismetKey = SiteConfig::current_site_config()->AkismetKey;
26
+		if ($akismetKey) {
27
+			AkismetSpamProtector::set_api_key($akismetKey);
28
+		}
29
+	}
30
+
31
+	/**
32
+	 * Make sure the DB is ready before accessing siteconfig db field
33
+	 *
34
+	 * @return bool
35
+	 */
36
+	protected function isDBReady()
37
+	{
38
+		if (!DB::isActive()) {
39
+			return false;
40
+		}
41
+
42
+		// Require table
43
+		if (!DB::getConn()->hasTable('SiteConfig')) {
44
+			return false;
45
+		}
46
+
47
+		// Ensure siteconfig has all fields necessary
48
+		$dbFields = DB::fieldList('SiteConfig');
49
+		if (empty($dbFields)) {
50
+			return false;
51
+		}
52
+
53
+		// Ensure that SiteConfig has all fields
54
+		$objFields = DataObject::database_fields('SiteConfig', false);
55
+		$missingFields = array_diff_key($objFields, $dbFields);
56
+		return empty($missingFields);
57
+	}
58 58
 }
Please login to merge, or discard this patch.
code/service/AkismetService.php 1 patch
Indentation   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -5,35 +5,35 @@
 block discarded – undo
5 5
  */
6 6
 interface AkismetService
7 7
 {
8
-    /**
9
-     * Check if the comment is spam or not
10
-     * This is basically the core of everything. This call takes a number of
11
-     * arguments and characteristics about the submitted content and then
12
-     * returns a thumbs up or thumbs down.
13
-     * Almost everything is optional, but performance can drop dramatically if
14
-     * you exclude certain elements.
15
-     * REMARK: If you are having trouble triggering you can send
16
-     * "viagra-test-123" as the author and it will trigger a true response,
17
-     * always.
18
-     *
19
-     * @param string[optional] $content   The content that was submitted.
20
-     * @param string[optional] $author    The name.
21
-     * @param string[optional] $email     The email address.
22
-     * @param string[optional] $url       The URL.
23
-     * @param string[optional] $permalink The permanent location of the entry
24
-     *                                    the comment was submitted to.
25
-     * @param string[optional] $type The type, can be blank, comment,
26
-     *                                    trackback, pingback, or a made up
27
-     *                                    value like "registration".
28
-     * @return bool If the comment is spam true will be
29
-     *                                    returned, otherwise false.
30
-     */
31
-    public function isSpam(
32
-        $content,
33
-        $author = null,
34
-        $email = null,
35
-        $url = null,
36
-        $permalink = null,
37
-        $type = null
38
-    );
8
+	/**
9
+	 * Check if the comment is spam or not
10
+	 * This is basically the core of everything. This call takes a number of
11
+	 * arguments and characteristics about the submitted content and then
12
+	 * returns a thumbs up or thumbs down.
13
+	 * Almost everything is optional, but performance can drop dramatically if
14
+	 * you exclude certain elements.
15
+	 * REMARK: If you are having trouble triggering you can send
16
+	 * "viagra-test-123" as the author and it will trigger a true response,
17
+	 * always.
18
+	 *
19
+	 * @param string[optional] $content   The content that was submitted.
20
+	 * @param string[optional] $author    The name.
21
+	 * @param string[optional] $email     The email address.
22
+	 * @param string[optional] $url       The URL.
23
+	 * @param string[optional] $permalink The permanent location of the entry
24
+	 *                                    the comment was submitted to.
25
+	 * @param string[optional] $type The type, can be blank, comment,
26
+	 *                                    trackback, pingback, or a made up
27
+	 *                                    value like "registration".
28
+	 * @return bool If the comment is spam true will be
29
+	 *                                    returned, otherwise false.
30
+	 */
31
+	public function isSpam(
32
+		$content,
33
+		$author = null,
34
+		$email = null,
35
+		$url = null,
36
+		$permalink = null,
37
+		$type = null
38
+	);
39 39
 }
Please login to merge, or discard this patch.
tests/AkismetTest.php 2 patches
Indentation   +189 added lines, -189 removed lines patch added patch discarded remove patch
@@ -2,211 +2,211 @@
 block discarded – undo
2 2
 
3 3
 class AkismetTest extends FunctionalTest
4 4
 {
5
-    protected $extraDataObjects = array('AkismetTest_Submission');
6
-
7
-    protected $usesDatabase = true;
8
-
9
-    protected $requiredExtensions = array(
10
-        'SiteConfig' => array('AkismetConfig')
11
-    );
12
-
13
-    public function setUp()
14
-    {
15
-        parent::setUp();
16
-        Injector::nest();
17
-        Injector::inst()->unregisterAllObjects();
18
-
19
-        // Mock service
20
-        Config::nest();
21
-        Config::inst()->update('Injector', 'AkismetService', 'AkismetTest_Service');
22
-        Config::inst()->update('AkismetSpamProtector', 'api_key', 'dummykey');
23
-        AkismetSpamProtector::set_api_key(null);
24
-
25
-        // Reset options to reasonable default
26
-        Config::inst()->remove('AkismetSpamProtector', 'save_spam');
27
-        Config::inst()->remove('AkismetSpamProtector', 'require_confirmation');
28
-        Config::inst()->remove('AkismetSpamProtector', 'bypass_members');
29
-        Config::inst()->update('AkismetSpamProtector', 'bypass_permission', 'ADMIN');
30
-    }
31
-
32
-    public function tearDown()
33
-    {
34
-        Config::unnest();
35
-        Injector::unnest();
36
-        parent::tearDown();
37
-    }
38
-
39
-    public function testSpamDetectionForm()
40
-    {
5
+	protected $extraDataObjects = array('AkismetTest_Submission');
6
+
7
+	protected $usesDatabase = true;
8
+
9
+	protected $requiredExtensions = array(
10
+		'SiteConfig' => array('AkismetConfig')
11
+	);
12
+
13
+	public function setUp()
14
+	{
15
+		parent::setUp();
16
+		Injector::nest();
17
+		Injector::inst()->unregisterAllObjects();
18
+
19
+		// Mock service
20
+		Config::nest();
21
+		Config::inst()->update('Injector', 'AkismetService', 'AkismetTest_Service');
22
+		Config::inst()->update('AkismetSpamProtector', 'api_key', 'dummykey');
23
+		AkismetSpamProtector::set_api_key(null);
24
+
25
+		// Reset options to reasonable default
26
+		Config::inst()->remove('AkismetSpamProtector', 'save_spam');
27
+		Config::inst()->remove('AkismetSpamProtector', 'require_confirmation');
28
+		Config::inst()->remove('AkismetSpamProtector', 'bypass_members');
29
+		Config::inst()->update('AkismetSpamProtector', 'bypass_permission', 'ADMIN');
30
+	}
31
+
32
+	public function tearDown()
33
+	{
34
+		Config::unnest();
35
+		Injector::unnest();
36
+		parent::tearDown();
37
+	}
38
+
39
+	public function testSpamDetectionForm()
40
+	{
41 41
         
42
-        // Test "nice" setting
43
-        $result = $this->post('AkismetTest_Controller/Form', array(
44
-            'Name' => 'person',
45
-            'Email' => '[email protected]',
46
-            'Content' => 'what a nice comment',
47
-            'action_doSubmit' => 'Submit',
48
-        ));
49
-
50
-        $this->assertContains('Thanks for your submission, person', $result->getBody());
51
-        $saved = AkismetTest_Submission::get()->last();
52
-        $this->assertNotEmpty($saved);
53
-        $this->assertEquals('person', $saved->Name);
54
-        $this->assertEquals('[email protected]', $saved->Email);
55
-        $this->assertEquals('what a nice comment', $saved->Content);
56
-        $this->assertEquals(false, (bool)$saved->IsSpam);
57
-        $saved->delete();
58
-
59
-        // Test failed setting
60
-        $result = $this->post('AkismetTest_Controller/Form', array(
61
-            'Name' => 'spam',
62
-            'Email' => '[email protected]',
63
-            'Content' => 'spam',
64
-            'action_doSubmit' => 'Submit',
65
-        ));
66
-
67
-        $errorMessage = _t(
68
-            'AkismetField.SPAM',
69
-            "Your submission has been rejected because it was treated as spam."
70
-        );
71
-        $this->assertContains($errorMessage, $result->getBody());
72
-        $saved = AkismetTest_Submission::get()->last();
73
-        $this->assertEmpty($saved);
74
-    }
75
-
76
-    public function testSaveSpam()
77
-    {
78
-        Config::inst()->update('AkismetSpamProtector', 'save_spam', 'true');
79
-
80
-        // Test "nice" setting
81
-        $result = $this->post('AkismetTest_Controller/Form', array(
82
-            'Name' => 'person',
83
-            'Email' => '[email protected]',
84
-            'Content' => 'what a nice comment',
85
-            'action_doSubmit' => 'Submit',
86
-        ));
87
-
88
-        $this->assertContains('Thanks for your submission, person', $result->getBody());
89
-        $saved = AkismetTest_Submission::get()->last();
90
-        $this->assertNotEmpty($saved);
91
-        $this->assertEquals('person', $saved->Name);
92
-        $this->assertEquals('[email protected]', $saved->Email);
93
-        $this->assertEquals('what a nice comment', $saved->Content);
94
-        $this->assertEquals(false, (bool)$saved->IsSpam);
95
-        $saved->delete();
96
-
97
-        // Test failed setting
98
-        $result = $this->post('AkismetTest_Controller/Form', array(
99
-            'Name' => 'spam',
100
-            'Email' => '[email protected]',
101
-            'Content' => 'spam',
102
-            'action_doSubmit' => 'Submit',
103
-        ));
104
-
105
-        $errorMessage = _t(
106
-            'AkismetField.SPAM',
107
-            "Your submission has been rejected because it was treated as spam."
108
-        );
109
-        $this->assertContains($errorMessage, $result->getBody());
110
-        $saved = AkismetTest_Submission::get()->last();
111
-        $this->assertNotEmpty($saved);
112
-        $this->assertEquals('spam', $saved->Name);
113
-        $this->assertEquals('[email protected]', $saved->Email);
114
-        $this->assertEquals('spam', $saved->Content);
115
-        $this->assertEquals(true, (bool)$saved->IsSpam);
116
-    }
117
-
118
-    /**
119
-     * Test that the request processor can safely activate when able (and only then)
120
-     */
121
-    public function testProcessor()
122
-    {
123
-        $siteconfig = SiteConfig::current_site_config();
124
-        $siteconfig->write();
125
-
126
-        // Test assignment via request filter
127
-        $processor = new AkismetTest_TestProcessor();
128
-        $this->assertTrue($processor->publicIsDBReady());
129
-
130
-        // Remove AkismetKey field
131
-        DB::query('ALTER TABLE "SiteConfig" DROP COLUMN "AkismetKey"');
132
-        $this->assertFalse($processor->publicIsDBReady());
133
-    }
42
+		// Test "nice" setting
43
+		$result = $this->post('AkismetTest_Controller/Form', array(
44
+			'Name' => 'person',
45
+			'Email' => '[email protected]',
46
+			'Content' => 'what a nice comment',
47
+			'action_doSubmit' => 'Submit',
48
+		));
49
+
50
+		$this->assertContains('Thanks for your submission, person', $result->getBody());
51
+		$saved = AkismetTest_Submission::get()->last();
52
+		$this->assertNotEmpty($saved);
53
+		$this->assertEquals('person', $saved->Name);
54
+		$this->assertEquals('[email protected]', $saved->Email);
55
+		$this->assertEquals('what a nice comment', $saved->Content);
56
+		$this->assertEquals(false, (bool)$saved->IsSpam);
57
+		$saved->delete();
58
+
59
+		// Test failed setting
60
+		$result = $this->post('AkismetTest_Controller/Form', array(
61
+			'Name' => 'spam',
62
+			'Email' => '[email protected]',
63
+			'Content' => 'spam',
64
+			'action_doSubmit' => 'Submit',
65
+		));
66
+
67
+		$errorMessage = _t(
68
+			'AkismetField.SPAM',
69
+			"Your submission has been rejected because it was treated as spam."
70
+		);
71
+		$this->assertContains($errorMessage, $result->getBody());
72
+		$saved = AkismetTest_Submission::get()->last();
73
+		$this->assertEmpty($saved);
74
+	}
75
+
76
+	public function testSaveSpam()
77
+	{
78
+		Config::inst()->update('AkismetSpamProtector', 'save_spam', 'true');
79
+
80
+		// Test "nice" setting
81
+		$result = $this->post('AkismetTest_Controller/Form', array(
82
+			'Name' => 'person',
83
+			'Email' => '[email protected]',
84
+			'Content' => 'what a nice comment',
85
+			'action_doSubmit' => 'Submit',
86
+		));
87
+
88
+		$this->assertContains('Thanks for your submission, person', $result->getBody());
89
+		$saved = AkismetTest_Submission::get()->last();
90
+		$this->assertNotEmpty($saved);
91
+		$this->assertEquals('person', $saved->Name);
92
+		$this->assertEquals('[email protected]', $saved->Email);
93
+		$this->assertEquals('what a nice comment', $saved->Content);
94
+		$this->assertEquals(false, (bool)$saved->IsSpam);
95
+		$saved->delete();
96
+
97
+		// Test failed setting
98
+		$result = $this->post('AkismetTest_Controller/Form', array(
99
+			'Name' => 'spam',
100
+			'Email' => '[email protected]',
101
+			'Content' => 'spam',
102
+			'action_doSubmit' => 'Submit',
103
+		));
104
+
105
+		$errorMessage = _t(
106
+			'AkismetField.SPAM',
107
+			"Your submission has been rejected because it was treated as spam."
108
+		);
109
+		$this->assertContains($errorMessage, $result->getBody());
110
+		$saved = AkismetTest_Submission::get()->last();
111
+		$this->assertNotEmpty($saved);
112
+		$this->assertEquals('spam', $saved->Name);
113
+		$this->assertEquals('[email protected]', $saved->Email);
114
+		$this->assertEquals('spam', $saved->Content);
115
+		$this->assertEquals(true, (bool)$saved->IsSpam);
116
+	}
117
+
118
+	/**
119
+	 * Test that the request processor can safely activate when able (and only then)
120
+	 */
121
+	public function testProcessor()
122
+	{
123
+		$siteconfig = SiteConfig::current_site_config();
124
+		$siteconfig->write();
125
+
126
+		// Test assignment via request filter
127
+		$processor = new AkismetTest_TestProcessor();
128
+		$this->assertTrue($processor->publicIsDBReady());
129
+
130
+		// Remove AkismetKey field
131
+		DB::query('ALTER TABLE "SiteConfig" DROP COLUMN "AkismetKey"');
132
+		$this->assertFalse($processor->publicIsDBReady());
133
+	}
134 134
 }
135 135
 
136 136
 class AkismetTest_Submission extends DataObject implements TestOnly
137 137
 {
138
-    private static $db = array(
139
-        'Name' => 'Varchar',
140
-        'Email' => 'Varchar',
141
-        'Content' => 'Text',
142
-        'IsSpam' => 'Boolean',
143
-    );
144
-
145
-    private static $default_sort = 'ID';
138
+	private static $db = array(
139
+		'Name' => 'Varchar',
140
+		'Email' => 'Varchar',
141
+		'Content' => 'Text',
142
+		'IsSpam' => 'Boolean',
143
+	);
144
+
145
+	private static $default_sort = 'ID';
146 146
 }
147 147
 
148 148
 class AkismetTest_Controller extends Controller implements TestOnly
149 149
 {
150
-    private static $allowed_actions = array(
151
-        'Form'
152
-    );
153
-
154
-    public function Form()
155
-    {
156
-        $fields = new FieldList(
157
-            new TextField('Name'),
158
-            new EmailField('Email'),
159
-            new TextareaField('Content')
160
-        );
161
-        $actions = new FieldList(new FormAction('doSubmit', 'Submit'));
162
-        $validator = new RequiredFields('Name', 'Content');
163
-        $form = new Form($this, 'Form', $fields, $actions, $validator);
164
-
165
-        $form->enableSpamProtection(array(
166
-            'protector' => 'AkismetSpamProtector',
167
-            'name' => 'IsSpam',
168
-            'mapping' => array(
169
-                'Content' => 'body',
170
-                'Name' => 'authorName',
171
-                'Email' => 'authorMail',
172
-            )
173
-        ));
174
-
175
-        // Because we don't want to be testing this
176
-        $form->disableSecurityToken();
177
-        return $form;
178
-    }
179
-
180
-    public function doSubmit($data, Form $form)
181
-    {
182
-        $item = new AkismetTest_Submission();
183
-        $form->saveInto($item);
184
-        $item->write();
185
-        $form->sessionMessage('Thanks for your submission, '. $data['Name'], 'good');
186
-        return $this->redirect($this->Link());
187
-    }
150
+	private static $allowed_actions = array(
151
+		'Form'
152
+	);
153
+
154
+	public function Form()
155
+	{
156
+		$fields = new FieldList(
157
+			new TextField('Name'),
158
+			new EmailField('Email'),
159
+			new TextareaField('Content')
160
+		);
161
+		$actions = new FieldList(new FormAction('doSubmit', 'Submit'));
162
+		$validator = new RequiredFields('Name', 'Content');
163
+		$form = new Form($this, 'Form', $fields, $actions, $validator);
164
+
165
+		$form->enableSpamProtection(array(
166
+			'protector' => 'AkismetSpamProtector',
167
+			'name' => 'IsSpam',
168
+			'mapping' => array(
169
+				'Content' => 'body',
170
+				'Name' => 'authorName',
171
+				'Email' => 'authorMail',
172
+			)
173
+		));
174
+
175
+		// Because we don't want to be testing this
176
+		$form->disableSecurityToken();
177
+		return $form;
178
+	}
179
+
180
+	public function doSubmit($data, Form $form)
181
+	{
182
+		$item = new AkismetTest_Submission();
183
+		$form->saveInto($item);
184
+		$item->write();
185
+		$form->sessionMessage('Thanks for your submission, '. $data['Name'], 'good');
186
+		return $this->redirect($this->Link());
187
+	}
188 188
 }
189 189
 
190 190
 class AkismetTest_Service implements TestOnly, AkismetService
191 191
 {
192
-    public function __construct($apiKey, $url)
193
-    {
194
-        if ($apiKey !== 'dummykey') {
195
-            throw new Exception("Invalid key");
196
-        }
197
-    }
192
+	public function __construct($apiKey, $url)
193
+	{
194
+		if ($apiKey !== 'dummykey') {
195
+			throw new Exception("Invalid key");
196
+		}
197
+	}
198 198
     
199
-    public function isSpam($content, $author = null, $email = null, $url = null, $permalink = null, $type = null)
200
-    {
201
-        // This dummy service only checks the content
202
-        return $content === 'spam';
203
-    }
199
+	public function isSpam($content, $author = null, $email = null, $url = null, $permalink = null, $type = null)
200
+	{
201
+		// This dummy service only checks the content
202
+		return $content === 'spam';
203
+	}
204 204
 }
205 205
 
206 206
 class AkismetTest_TestProcessor extends AkismetProcessor implements TestOnly
207 207
 {
208
-    public function publicIsDBReady()
209
-    {
210
-        return $this->isDBReady();
211
-    }
208
+	public function publicIsDBReady()
209
+	{
210
+		return $this->isDBReady();
211
+	}
212 212
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -53,7 +53,7 @@  discard block
 block discarded – undo
53 53
         $this->assertEquals('person', $saved->Name);
54 54
         $this->assertEquals('[email protected]', $saved->Email);
55 55
         $this->assertEquals('what a nice comment', $saved->Content);
56
-        $this->assertEquals(false, (bool)$saved->IsSpam);
56
+        $this->assertEquals(false, (bool) $saved->IsSpam);
57 57
         $saved->delete();
58 58
 
59 59
         // Test failed setting
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
         $this->assertEquals('person', $saved->Name);
92 92
         $this->assertEquals('[email protected]', $saved->Email);
93 93
         $this->assertEquals('what a nice comment', $saved->Content);
94
-        $this->assertEquals(false, (bool)$saved->IsSpam);
94
+        $this->assertEquals(false, (bool) $saved->IsSpam);
95 95
         $saved->delete();
96 96
 
97 97
         // Test failed setting
@@ -112,7 +112,7 @@  discard block
 block discarded – undo
112 112
         $this->assertEquals('spam', $saved->Name);
113 113
         $this->assertEquals('[email protected]', $saved->Email);
114 114
         $this->assertEquals('spam', $saved->Content);
115
-        $this->assertEquals(true, (bool)$saved->IsSpam);
115
+        $this->assertEquals(true, (bool) $saved->IsSpam);
116 116
     }
117 117
 
118 118
     /**
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
         $item = new AkismetTest_Submission();
183 183
         $form->saveInto($item);
184 184
         $item->write();
185
-        $form->sessionMessage('Thanks for your submission, '. $data['Name'], 'good');
185
+        $form->sessionMessage('Thanks for your submission, ' . $data['Name'], 'good');
186 186
         return $this->redirect($this->Link());
187 187
     }
188 188
 }
Please login to merge, or discard this patch.