Passed
Push — master ( 0cc399...87713c )
by Paul
04:04
created
plugin/Controllers/PublicController.php 1 patch
Indentation   +71 added lines, -71 removed lines patch added patch discarded remove patch
@@ -13,81 +13,81 @@
 block discarded – undo
13 13
 
14 14
 class PublicController extends Controller
15 15
 {
16
-    /**
17
-     * @return void
18
-     * @action wp_enqueue_scripts
19
-     */
20
-    public function enqueueAssets()
21
-    {
22
-        (new EnqueuePublicAssets())->handle();
23
-    }
16
+	/**
17
+	 * @return void
18
+	 * @action wp_enqueue_scripts
19
+	 */
20
+	public function enqueueAssets()
21
+	{
22
+		(new EnqueuePublicAssets())->handle();
23
+	}
24 24
 
25
-    /**
26
-     * @param string $tag
27
-     * @param string $handle
28
-     * @return string
29
-     * @filter script_loader_tag
30
-     */
31
-    public function filterEnqueuedScripts($tag, $handle)
32
-    {
33
-        $scripts = [Application::ID.'/google-recaptcha'];
34
-        if (in_array($handle, apply_filters('site-reviews/async-scripts', $scripts))) {
35
-            $tag = str_replace(' src=', ' async src=', $tag);
36
-        }
37
-        if (in_array($handle, apply_filters('site-reviews/defer-scripts', $scripts))) {
38
-            $tag = str_replace(' src=', ' defer src=', $tag);
39
-        }
40
-        return $tag;
41
-    }
25
+	/**
26
+	 * @param string $tag
27
+	 * @param string $handle
28
+	 * @return string
29
+	 * @filter script_loader_tag
30
+	 */
31
+	public function filterEnqueuedScripts($tag, $handle)
32
+	{
33
+		$scripts = [Application::ID.'/google-recaptcha'];
34
+		if (in_array($handle, apply_filters('site-reviews/async-scripts', $scripts))) {
35
+			$tag = str_replace(' src=', ' async src=', $tag);
36
+		}
37
+		if (in_array($handle, apply_filters('site-reviews/defer-scripts', $scripts))) {
38
+			$tag = str_replace(' src=', ' defer src=', $tag);
39
+		}
40
+		return $tag;
41
+	}
42 42
 
43
-    /**
44
-     * @return array
45
-     * @filter site-reviews/config/forms/submission-form
46
-     */
47
-    public function filterFieldOrder(array $config)
48
-    {
49
-        $order = (array) apply_filters('site-reviews/submission-form/order', array_keys($config));
50
-        return array_intersect_key(array_merge(array_flip($order), $config), $config);
51
-    }
43
+	/**
44
+	 * @return array
45
+	 * @filter site-reviews/config/forms/submission-form
46
+	 */
47
+	public function filterFieldOrder(array $config)
48
+	{
49
+		$order = (array) apply_filters('site-reviews/submission-form/order', array_keys($config));
50
+		return array_intersect_key(array_merge(array_flip($order), $config), $config);
51
+	}
52 52
 
53
-    /**
54
-     * @param string $view
55
-     * @return string
56
-     * @filter site-reviews/render/view
57
-     */
58
-    public function filterRenderView($view)
59
-    {
60
-        return glsr(Style::class)->filterView($view);
61
-    }
53
+	/**
54
+	 * @param string $view
55
+	 * @return string
56
+	 * @filter site-reviews/render/view
57
+	 */
58
+	public function filterRenderView($view)
59
+	{
60
+		return glsr(Style::class)->filterView($view);
61
+	}
62 62
 
63
-    /**
64
-     * @return void
65
-     * @action site-reviews/builder
66
-     */
67
-    public function modifyBuilder(Builder $instance)
68
-    {
69
-        call_user_func_array([glsr(Style::class), 'modifyField'], [$instance]);
70
-    }
63
+	/**
64
+	 * @return void
65
+	 * @action site-reviews/builder
66
+	 */
67
+	public function modifyBuilder(Builder $instance)
68
+	{
69
+		call_user_func_array([glsr(Style::class), 'modifyField'], [$instance]);
70
+	}
71 71
 
72
-    /**
73
-     * @return void
74
-     * @action wp_footer
75
-     */
76
-    public function renderSchema()
77
-    {
78
-        glsr(Schema::class)->render();
79
-    }
72
+	/**
73
+	 * @return void
74
+	 * @action wp_footer
75
+	 */
76
+	public function renderSchema()
77
+	{
78
+		glsr(Schema::class)->render();
79
+	}
80 80
 
81
-    /**
82
-     * @return CreateReview
83
-     */
84
-    public function routerSubmitReview(array $request)
85
-    {
86
-        $validated = glsr(ValidateReview::class)->validate($request);
87
-        $command = new CreateReview($validated->request);
88
-        if (empty($validated->error) && !$validated->recaptchaIsUnset) {
89
-            $this->execute($command);
90
-        }
91
-        return $command;
92
-    }
81
+	/**
82
+	 * @return CreateReview
83
+	 */
84
+	public function routerSubmitReview(array $request)
85
+	{
86
+		$validated = glsr(ValidateReview::class)->validate($request);
87
+		$command = new CreateReview($validated->request);
88
+		if (empty($validated->error) && !$validated->recaptchaIsUnset) {
89
+			$this->execute($command);
90
+		}
91
+		return $command;
92
+	}
93 93
 }
Please login to merge, or discard this patch.
plugin/Database/Cache.php 1 patch
Indentation   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -6,63 +6,63 @@
 block discarded – undo
6 6
 
7 7
 class Cache
8 8
 {
9
-    /**
10
-     * @return array
11
-     */
12
-    public function getCloudflareIps()
13
-    {
14
-        if (false === ($ipAddresses = get_transient(Application::ID.'_cloudflare_ips'))) {
15
-            $ipAddresses = array_fill_keys(['v4', 'v6'], []);
16
-            foreach (array_keys($ipAddresses) as $version) {
17
-                $url = 'https://www.cloudflare.com/ips-'.$version;
18
-                $response = wp_remote_get($url, ['sslverify' => false]);
19
-                if (is_wp_error($response)) {
20
-                    glsr_log()->error($response->get_error_message());
21
-                    continue;
22
-                }
23
-                if ('200' != ($statusCode = wp_remote_retrieve_response_code($response))) {
24
-                    glsr_log()->error('Unable to connect to '.$url.' ['.$statusCode.']');
25
-                    continue;
26
-                }
27
-                $ipAddresses[$version] = array_filter(
28
-                    (array) preg_split('/\R/', wp_remote_retrieve_body($response))
29
-                );
30
-            }
31
-            set_transient(Application::ID.'_cloudflare_ips', $ipAddresses, WEEK_IN_SECONDS);
32
-        }
33
-        return $ipAddresses;
34
-    }
9
+	/**
10
+	 * @return array
11
+	 */
12
+	public function getCloudflareIps()
13
+	{
14
+		if (false === ($ipAddresses = get_transient(Application::ID.'_cloudflare_ips'))) {
15
+			$ipAddresses = array_fill_keys(['v4', 'v6'], []);
16
+			foreach (array_keys($ipAddresses) as $version) {
17
+				$url = 'https://www.cloudflare.com/ips-'.$version;
18
+				$response = wp_remote_get($url, ['sslverify' => false]);
19
+				if (is_wp_error($response)) {
20
+					glsr_log()->error($response->get_error_message());
21
+					continue;
22
+				}
23
+				if ('200' != ($statusCode = wp_remote_retrieve_response_code($response))) {
24
+					glsr_log()->error('Unable to connect to '.$url.' ['.$statusCode.']');
25
+					continue;
26
+				}
27
+				$ipAddresses[$version] = array_filter(
28
+					(array) preg_split('/\R/', wp_remote_retrieve_body($response))
29
+				);
30
+			}
31
+			set_transient(Application::ID.'_cloudflare_ips', $ipAddresses, WEEK_IN_SECONDS);
32
+		}
33
+		return $ipAddresses;
34
+	}
35 35
 
36
-    /**
37
-     * @param string $metaKey
38
-     * @return array
39
-     */
40
-    public function getReviewCountsFor($metaKey)
41
-    {
42
-        $counts = wp_cache_get(Application::ID, $metaKey.'_count');
43
-        if (false === $counts) {
44
-            $counts = [];
45
-            $results = glsr(SqlQueries::class)->getReviewCountsFor($metaKey);
46
-            foreach ($results as $result) {
47
-                $counts[$result->name] = $result->num_posts;
48
-            }
49
-            wp_cache_set(Application::ID, $counts, $metaKey.'_count');
50
-        }
51
-        return $counts;
52
-    }
36
+	/**
37
+	 * @param string $metaKey
38
+	 * @return array
39
+	 */
40
+	public function getReviewCountsFor($metaKey)
41
+	{
42
+		$counts = wp_cache_get(Application::ID, $metaKey.'_count');
43
+		if (false === $counts) {
44
+			$counts = [];
45
+			$results = glsr(SqlQueries::class)->getReviewCountsFor($metaKey);
46
+			foreach ($results as $result) {
47
+				$counts[$result->name] = $result->num_posts;
48
+			}
49
+			wp_cache_set(Application::ID, $counts, $metaKey.'_count');
50
+		}
51
+		return $counts;
52
+	}
53 53
 
54
-    /**
55
-     * @return string
56
-     */
57
-    public function getRemotePostTest()
58
-    {
59
-        if (false === ($test = get_transient(Application::ID.'_remote_post_test'))) {
60
-            $response = wp_remote_post('https://api.wordpress.org/stats/php/1.0/');
61
-            $test = !is_wp_error($response) && in_array($response['response']['code'], range(200, 299))
62
-                ? 'Works'
63
-                : 'Does not work';
64
-            set_transient(Application::ID.'_remote_post_test', $test, WEEK_IN_SECONDS);
65
-        }
66
-        return $test;
67
-    }
54
+	/**
55
+	 * @return string
56
+	 */
57
+	public function getRemotePostTest()
58
+	{
59
+		if (false === ($test = get_transient(Application::ID.'_remote_post_test'))) {
60
+			$response = wp_remote_post('https://api.wordpress.org/stats/php/1.0/');
61
+			$test = !is_wp_error($response) && in_array($response['response']['code'], range(200, 299))
62
+				? 'Works'
63
+				: 'Does not work';
64
+			set_transient(Application::ID.'_remote_post_test', $test, WEEK_IN_SECONDS);
65
+		}
66
+		return $test;
67
+	}
68 68
 }
Please login to merge, or discard this patch.
plugin/Controllers/RebusifyController.php 1 patch
Indentation   +227 added lines, -227 removed lines patch added patch discarded remove patch
@@ -12,231 +12,231 @@
 block discarded – undo
12 12
 
13 13
 class RebusifyController extends Controller
14 14
 {
15
-    protected $apiKey = 'settings.general.rebusify_serial';
16
-    protected $emailKey = 'settings.general.rebusify_email';
17
-    protected $enabledKey = 'settings.general.rebusify';
18
-    protected $rebusifyKey = '_glsr_rebusify';
19
-
20
-    /**
21
-     * @return array
22
-     * @filter site-reviews/settings/callback
23
-     */
24
-    public function filterSettingsCallback(array $settings)
25
-    {
26
-        if ('yes' !== Arr::get($settings, $this->enabledKey)) {
27
-            return $settings;
28
-        }
29
-        $isApiKeyModified = $this->isEmptyOrModified($this->apiKey, $settings);
30
-        $isEmailModified = $this->isEmptyOrModified($this->emailKey, $settings);
31
-        $isAccountVerified = glsr(OptionManager::class)->getWP($this->rebusifyKey, false);
32
-        if (!$isAccountVerified || $isApiKeyModified || $isEmailModified) {
33
-            $settings = $this->sanitizeRebusifySettings($settings);
34
-        }
35
-        return $settings;
36
-    }
37
-
38
-    /**
39
-     * @param string $template
40
-     * @return array
41
-     * @filter site-reviews/interpolate/partials/form/table-row-multiple
42
-     */
43
-    public function filterSettingsTableRow(array $context, $template, array $data)
44
-    {
45
-        if ($this->enabledKey !== Arr::get($data, 'field.path')) {
46
-            return $context;
47
-        }
48
-        $rebusifyProductType = glsr(OptionManager::class)->getWP($this->rebusifyKey);
49
-        if ('P' === $rebusifyProductType) {
50
-            return $context;
51
-        }
52
-        if ('F' === $rebusifyProductType && 'yes' === glsr_get_option('general.rebusify')) {
53
-            $button = $this->buildUpgradeButton();
54
-        } else {
55
-            $button = $this->buildCreateButton();
56
-        }
57
-        $context['field'].= $button;
58
-        return $context;
59
-    }
60
-
61
-    /**
62
-     * Triggered when a review is created.
63
-     * @return void
64
-     * @action site-reviews/review/created
65
-     */
66
-    public function onCreated(Review $review)
67
-    {
68
-        if (!$this->canPostReview($review)) {
69
-            return;
70
-        }
71
-        $rebusify = glsr(Rebusify::class)->sendReview($review);
72
-        if ($rebusify->success) {
73
-            glsr(Database::class)->set($review->ID, 'rebusify', $rebusify->review_id);
74
-        }
75
-    }
76
-
77
-    /**
78
-     * Triggered when a review is reverted to its original title/content/date_timestamp.
79
-     * @return void
80
-     * @action site-reviews/review/reverted
81
-     */
82
-    public function onReverted(Review $review)
83
-    {
84
-        if (!$this->canPostReview($review)) {
85
-            return;
86
-        }
87
-        $rebusify = glsr(Rebusify::class)->sendReview($review);
88
-        if ($rebusify->success) {
89
-            glsr(Database::class)->set($review->ID, 'rebusify', $rebusify->review_id);
90
-        }
91
-    }
92
-
93
-    /**
94
-     * Triggered when an existing review is updated.
95
-     * @return void
96
-     * @action site-reviews/review/saved
97
-     */
98
-    public function onSaved(Review $review)
99
-    {
100
-        if (!$this->canPostReview($review)) {
101
-            return;
102
-        }
103
-        $rebusify = glsr(Rebusify::class)->sendReview($review);
104
-        if ($rebusify->success) {
105
-            glsr(Database::class)->set($review->ID, 'rebusify', $rebusify->review_id);
106
-        }
107
-    }
108
-
109
-    /**
110
-     * Triggered when a review's response is added or updated.
111
-     * @param int $metaId
112
-     * @param int $postId
113
-     * @param string $metaKey
114
-     * @return void
115
-     * @action updated_postmeta
116
-     */
117
-    public function onUpdatedMeta($metaId, $postId, $metaKey)
118
-    {
119
-        $review = glsr_get_review($postId);
120
-        if (!$this->canPostResponse($review) || '_response' !== $metaKey) {
121
-            return;
122
-        }
123
-        $rebusify = glsr(Rebusify::class)->sendReviewResponse($review);
124
-        if ($rebusify->success) {
125
-            glsr(Database::class)->set($review->ID, 'rebusify_response', true);
126
-        }
127
-    }
128
-
129
-    /**
130
-     * @return string
131
-     */
132
-    protected function buildCreateButton()
133
-    {
134
-        return glsr(Builder::class)->a(__('Create Your Rebusify Account', 'site-reviews'), [
135
-            'class' => 'button',
136
-            'href' => Rebusify::WEB_URL,
137
-            'target' => '_blank',
138
-        ]);
139
-    }
140
-
141
-    /**
142
-     * @return string
143
-     */
144
-    protected function buildUpgradeButton()
145
-    {
146
-        $build = glsr(Builder::class);
147
-        $notice = $build->p(__('Free Rebusify accounts are limited to 500 blockchain transactions per year.', 'site-reviews'));
148
-        $button = $build->a(__('Upgrade Your Rebusify Plan', 'site-reviews'), [
149
-            'class' => 'button',
150
-            'href' => Rebusify::WEB_URL,
151
-            'target' => '_blank',
152
-        ]);
153
-        return $build->div($notice.$button, [
154
-            'class' => 'glsr-notice-inline notice inline notice-info',
155
-        ]);
156
-    }
157
-
158
-    /**
159
-     * @return bool
160
-     */
161
-    protected function canPostResponse(Review $review)
162
-    {
163
-        $requiredValues = [
164
-            glsr(Database::class)->get($review->ID, 'rebusify'),
165
-            $review->response,
166
-            $review->review_id,
167
-        ];
168
-        return $this->canProceed($review, 'rebusify_response')
169
-            && 'publish' === $review->status
170
-            && 3 === count(array_filter($requiredValues));
171
-    }
172
-
173
-    /**
174
-     * @return bool
175
-     */
176
-    protected function canPostReview(Review $review)
177
-    {
178
-        $requiredValues = [
179
-            $review->author,
180
-            $review->content,
181
-            $review->rating,
182
-            $review->review_id,
183
-            $review->title,
184
-        ];
185
-        return $this->canProceed($review)
186
-            && 'publish' === $review->status
187
-            && 5 === count(array_filter($requiredValues));
188
-    }
189
-
190
-    /**
191
-     * @param string $metaKey
192
-     * @return bool
193
-     */
194
-    protected function canProceed(Review $review, $metaKey = 'rebusify')
195
-    {
196
-        return glsr(OptionManager::class)->getBool($this->enabledKey)
197
-            && $this->isReviewPostId($review->ID)
198
-            && !$this->hasMetaKey($review, $metaKey);
199
-    }
200
-
201
-    /**
202
-     * @param string $metaKey
203
-     * @return bool
204
-     */
205
-    protected function hasMetaKey(Review $review, $metaKey = 'rebusify')
206
-    {
207
-        return '' !== glsr(Database::class)->get($review->ID, $metaKey);
208
-    }
209
-
210
-    /**
211
-     * @param string $key
212
-     * @return bool
213
-     */
214
-    protected function isEmptyOrModified($key, array $settings)
215
-    {
216
-        $oldValue = glsr_get_option($key);
217
-        $newValue = Arr::get($settings, $key);
218
-        return empty($newValue) || $newValue !== $oldValue;
219
-    }
220
-
221
-    /**
222
-     * @return array
223
-     */
224
-    protected function sanitizeRebusifySettings(array $settings)
225
-    {
226
-        $rebusify = glsr(Rebusify::class)->activateKey(
227
-            Arr::get($settings, $this->apiKey),
228
-            Arr::get($settings, $this->emailKey)
229
-        );
230
-        if ($rebusify->success) {
231
-            update_option($this->rebusifyKey, Arr::get($rebusify->response, 'producttype'));
232
-        } else {
233
-            delete_option($this->rebusifyKey);
234
-            $settings = Arr::set($settings, $this->enabledKey, 'no');
235
-            glsr(Notice::class)->addError(sprintf(
236
-                __('Your Rebusify account details could not be verified, please try again. %s', 'site-reviews'),
237
-                '('.$rebusify->message.')'
238
-            ));
239
-        }
240
-        return $settings;
241
-    }
15
+	protected $apiKey = 'settings.general.rebusify_serial';
16
+	protected $emailKey = 'settings.general.rebusify_email';
17
+	protected $enabledKey = 'settings.general.rebusify';
18
+	protected $rebusifyKey = '_glsr_rebusify';
19
+
20
+	/**
21
+	 * @return array
22
+	 * @filter site-reviews/settings/callback
23
+	 */
24
+	public function filterSettingsCallback(array $settings)
25
+	{
26
+		if ('yes' !== Arr::get($settings, $this->enabledKey)) {
27
+			return $settings;
28
+		}
29
+		$isApiKeyModified = $this->isEmptyOrModified($this->apiKey, $settings);
30
+		$isEmailModified = $this->isEmptyOrModified($this->emailKey, $settings);
31
+		$isAccountVerified = glsr(OptionManager::class)->getWP($this->rebusifyKey, false);
32
+		if (!$isAccountVerified || $isApiKeyModified || $isEmailModified) {
33
+			$settings = $this->sanitizeRebusifySettings($settings);
34
+		}
35
+		return $settings;
36
+	}
37
+
38
+	/**
39
+	 * @param string $template
40
+	 * @return array
41
+	 * @filter site-reviews/interpolate/partials/form/table-row-multiple
42
+	 */
43
+	public function filterSettingsTableRow(array $context, $template, array $data)
44
+	{
45
+		if ($this->enabledKey !== Arr::get($data, 'field.path')) {
46
+			return $context;
47
+		}
48
+		$rebusifyProductType = glsr(OptionManager::class)->getWP($this->rebusifyKey);
49
+		if ('P' === $rebusifyProductType) {
50
+			return $context;
51
+		}
52
+		if ('F' === $rebusifyProductType && 'yes' === glsr_get_option('general.rebusify')) {
53
+			$button = $this->buildUpgradeButton();
54
+		} else {
55
+			$button = $this->buildCreateButton();
56
+		}
57
+		$context['field'].= $button;
58
+		return $context;
59
+	}
60
+
61
+	/**
62
+	 * Triggered when a review is created.
63
+	 * @return void
64
+	 * @action site-reviews/review/created
65
+	 */
66
+	public function onCreated(Review $review)
67
+	{
68
+		if (!$this->canPostReview($review)) {
69
+			return;
70
+		}
71
+		$rebusify = glsr(Rebusify::class)->sendReview($review);
72
+		if ($rebusify->success) {
73
+			glsr(Database::class)->set($review->ID, 'rebusify', $rebusify->review_id);
74
+		}
75
+	}
76
+
77
+	/**
78
+	 * Triggered when a review is reverted to its original title/content/date_timestamp.
79
+	 * @return void
80
+	 * @action site-reviews/review/reverted
81
+	 */
82
+	public function onReverted(Review $review)
83
+	{
84
+		if (!$this->canPostReview($review)) {
85
+			return;
86
+		}
87
+		$rebusify = glsr(Rebusify::class)->sendReview($review);
88
+		if ($rebusify->success) {
89
+			glsr(Database::class)->set($review->ID, 'rebusify', $rebusify->review_id);
90
+		}
91
+	}
92
+
93
+	/**
94
+	 * Triggered when an existing review is updated.
95
+	 * @return void
96
+	 * @action site-reviews/review/saved
97
+	 */
98
+	public function onSaved(Review $review)
99
+	{
100
+		if (!$this->canPostReview($review)) {
101
+			return;
102
+		}
103
+		$rebusify = glsr(Rebusify::class)->sendReview($review);
104
+		if ($rebusify->success) {
105
+			glsr(Database::class)->set($review->ID, 'rebusify', $rebusify->review_id);
106
+		}
107
+	}
108
+
109
+	/**
110
+	 * Triggered when a review's response is added or updated.
111
+	 * @param int $metaId
112
+	 * @param int $postId
113
+	 * @param string $metaKey
114
+	 * @return void
115
+	 * @action updated_postmeta
116
+	 */
117
+	public function onUpdatedMeta($metaId, $postId, $metaKey)
118
+	{
119
+		$review = glsr_get_review($postId);
120
+		if (!$this->canPostResponse($review) || '_response' !== $metaKey) {
121
+			return;
122
+		}
123
+		$rebusify = glsr(Rebusify::class)->sendReviewResponse($review);
124
+		if ($rebusify->success) {
125
+			glsr(Database::class)->set($review->ID, 'rebusify_response', true);
126
+		}
127
+	}
128
+
129
+	/**
130
+	 * @return string
131
+	 */
132
+	protected function buildCreateButton()
133
+	{
134
+		return glsr(Builder::class)->a(__('Create Your Rebusify Account', 'site-reviews'), [
135
+			'class' => 'button',
136
+			'href' => Rebusify::WEB_URL,
137
+			'target' => '_blank',
138
+		]);
139
+	}
140
+
141
+	/**
142
+	 * @return string
143
+	 */
144
+	protected function buildUpgradeButton()
145
+	{
146
+		$build = glsr(Builder::class);
147
+		$notice = $build->p(__('Free Rebusify accounts are limited to 500 blockchain transactions per year.', 'site-reviews'));
148
+		$button = $build->a(__('Upgrade Your Rebusify Plan', 'site-reviews'), [
149
+			'class' => 'button',
150
+			'href' => Rebusify::WEB_URL,
151
+			'target' => '_blank',
152
+		]);
153
+		return $build->div($notice.$button, [
154
+			'class' => 'glsr-notice-inline notice inline notice-info',
155
+		]);
156
+	}
157
+
158
+	/**
159
+	 * @return bool
160
+	 */
161
+	protected function canPostResponse(Review $review)
162
+	{
163
+		$requiredValues = [
164
+			glsr(Database::class)->get($review->ID, 'rebusify'),
165
+			$review->response,
166
+			$review->review_id,
167
+		];
168
+		return $this->canProceed($review, 'rebusify_response')
169
+			&& 'publish' === $review->status
170
+			&& 3 === count(array_filter($requiredValues));
171
+	}
172
+
173
+	/**
174
+	 * @return bool
175
+	 */
176
+	protected function canPostReview(Review $review)
177
+	{
178
+		$requiredValues = [
179
+			$review->author,
180
+			$review->content,
181
+			$review->rating,
182
+			$review->review_id,
183
+			$review->title,
184
+		];
185
+		return $this->canProceed($review)
186
+			&& 'publish' === $review->status
187
+			&& 5 === count(array_filter($requiredValues));
188
+	}
189
+
190
+	/**
191
+	 * @param string $metaKey
192
+	 * @return bool
193
+	 */
194
+	protected function canProceed(Review $review, $metaKey = 'rebusify')
195
+	{
196
+		return glsr(OptionManager::class)->getBool($this->enabledKey)
197
+			&& $this->isReviewPostId($review->ID)
198
+			&& !$this->hasMetaKey($review, $metaKey);
199
+	}
200
+
201
+	/**
202
+	 * @param string $metaKey
203
+	 * @return bool
204
+	 */
205
+	protected function hasMetaKey(Review $review, $metaKey = 'rebusify')
206
+	{
207
+		return '' !== glsr(Database::class)->get($review->ID, $metaKey);
208
+	}
209
+
210
+	/**
211
+	 * @param string $key
212
+	 * @return bool
213
+	 */
214
+	protected function isEmptyOrModified($key, array $settings)
215
+	{
216
+		$oldValue = glsr_get_option($key);
217
+		$newValue = Arr::get($settings, $key);
218
+		return empty($newValue) || $newValue !== $oldValue;
219
+	}
220
+
221
+	/**
222
+	 * @return array
223
+	 */
224
+	protected function sanitizeRebusifySettings(array $settings)
225
+	{
226
+		$rebusify = glsr(Rebusify::class)->activateKey(
227
+			Arr::get($settings, $this->apiKey),
228
+			Arr::get($settings, $this->emailKey)
229
+		);
230
+		if ($rebusify->success) {
231
+			update_option($this->rebusifyKey, Arr::get($rebusify->response, 'producttype'));
232
+		} else {
233
+			delete_option($this->rebusifyKey);
234
+			$settings = Arr::set($settings, $this->enabledKey, 'no');
235
+			glsr(Notice::class)->addError(sprintf(
236
+				__('Your Rebusify account details could not be verified, please try again. %s', 'site-reviews'),
237
+				'('.$rebusify->message.')'
238
+			));
239
+		}
240
+		return $settings;
241
+	}
242 242
 }
Please login to merge, or discard this patch.
plugin/Defaults/CreateReviewDefaults.php 1 patch
Indentation   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -6,41 +6,41 @@
 block discarded – undo
6 6
 
7 7
 class CreateReviewDefaults extends Defaults
8 8
 {
9
-    /**
10
-     * @var array
11
-     */
12
-    protected $guarded = [
13
-        'assigned_to',
14
-        'content',
15
-        'date',
16
-        'pinned',
17
-        'response',
18
-        'review_id',
19
-        'review_type',
20
-        'title',
21
-    ];
9
+	/**
10
+	 * @var array
11
+	 */
12
+	protected $guarded = [
13
+		'assigned_to',
14
+		'content',
15
+		'date',
16
+		'pinned',
17
+		'response',
18
+		'review_id',
19
+		'review_type',
20
+		'title',
21
+	];
22 22
 
23
-    /**
24
-     * @return array
25
-     */
26
-    protected function defaults()
27
-    {
28
-        return [
29
-            'assigned_to' => '',
30
-            'author' => '',
31
-            'avatar' => '',
32
-            'content' => '',
33
-            'custom' => '',
34
-            'date' => '',
35
-            'email' => '',
36
-            'ip_address' => '',
37
-            'pinned' => false,
38
-            'rating' => '',
39
-            'response' => '',
40
-            'review_id' => md5(time().mt_rand()),
41
-            'review_type' => 'local',
42
-            'title' => '',
43
-            'url' => '',
44
-        ];
45
-    }
23
+	/**
24
+	 * @return array
25
+	 */
26
+	protected function defaults()
27
+	{
28
+		return [
29
+			'assigned_to' => '',
30
+			'author' => '',
31
+			'avatar' => '',
32
+			'content' => '',
33
+			'custom' => '',
34
+			'date' => '',
35
+			'email' => '',
36
+			'ip_address' => '',
37
+			'pinned' => false,
38
+			'rating' => '',
39
+			'response' => '',
40
+			'review_id' => md5(time().mt_rand()),
41
+			'review_type' => 'local',
42
+			'title' => '',
43
+			'url' => '',
44
+		];
45
+	}
46 46
 }
Please login to merge, or discard this patch.
plugin/Modules/Validator/ValidateReview.php 1 patch
Indentation   +259 added lines, -259 removed lines patch added patch discarded remove patch
@@ -13,285 +13,285 @@
 block discarded – undo
13 13
 
14 14
 class ValidateReview
15 15
 {
16
-    const RECAPTCHA_ENDPOINT = 'https://www.google.com/recaptcha/api/siteverify';
16
+	const RECAPTCHA_ENDPOINT = 'https://www.google.com/recaptcha/api/siteverify';
17 17
 
18
-    const RECAPTCHA_DISABLED = 0;
19
-    const RECAPTCHA_EMPTY = 1;
20
-    const RECAPTCHA_FAILED = 2;
21
-    const RECAPTCHA_INVALID = 3;
22
-    const RECAPTCHA_VALID = 4;
18
+	const RECAPTCHA_DISABLED = 0;
19
+	const RECAPTCHA_EMPTY = 1;
20
+	const RECAPTCHA_FAILED = 2;
21
+	const RECAPTCHA_INVALID = 3;
22
+	const RECAPTCHA_VALID = 4;
23 23
 
24
-    const VALIDATION_RULES = [
25
-        'content' => 'required',
26
-        'email' => 'required|email',
27
-        'name' => 'required',
28
-        'rating' => 'required|number|between:1,5',
29
-        'terms' => 'accepted',
30
-        'title' => 'required',
31
-    ];
24
+	const VALIDATION_RULES = [
25
+		'content' => 'required',
26
+		'email' => 'required|email',
27
+		'name' => 'required',
28
+		'rating' => 'required|number|between:1,5',
29
+		'terms' => 'accepted',
30
+		'title' => 'required',
31
+	];
32 32
 
33
-    /**
34
-     * @var string|void
35
-     */
36
-    public $error;
33
+	/**
34
+	 * @var string|void
35
+	 */
36
+	public $error;
37 37
 
38
-    /**
39
-     * @var string
40
-     */
41
-    public $form_id;
38
+	/**
39
+	 * @var string
40
+	 */
41
+	public $form_id;
42 42
 
43
-    /**
44
-     * @var bool
45
-     */
46
-    public $recaptchaIsUnset = false;
43
+	/**
44
+	 * @var bool
45
+	 */
46
+	public $recaptchaIsUnset = false;
47 47
 
48
-    /**
49
-     * @var array
50
-     */
51
-    public $request;
48
+	/**
49
+	 * @var array
50
+	 */
51
+	public $request;
52 52
 
53
-    /**
54
-     * @var array
55
-     */
56
-    protected $options;
53
+	/**
54
+	 * @var array
55
+	 */
56
+	protected $options;
57 57
 
58
-    /**
59
-     * @return static
60
-     */
61
-    public function validate(array $request)
62
-    {
63
-        $request['ip_address'] = Helper::getIpAddress(); // required for Akismet and Blacklist validation
64
-        $this->form_id = $request['form_id'];
65
-        $this->options = glsr(OptionManager::class)->all();
66
-        $this->request = $this->validateRequest($request);
67
-        $this->validateCustom();
68
-        $this->validateHoneyPot();
69
-        $this->validateReviewLimits();
70
-        $this->validateBlacklist();
71
-        $this->validateAkismet();
72
-        $this->validateRecaptcha();
73
-        if (!empty($this->error)) {
74
-            $this->setSessionValues('message', $this->error);
75
-        }
76
-        return $this;
77
-    }
58
+	/**
59
+	 * @return static
60
+	 */
61
+	public function validate(array $request)
62
+	{
63
+		$request['ip_address'] = Helper::getIpAddress(); // required for Akismet and Blacklist validation
64
+		$this->form_id = $request['form_id'];
65
+		$this->options = glsr(OptionManager::class)->all();
66
+		$this->request = $this->validateRequest($request);
67
+		$this->validateCustom();
68
+		$this->validateHoneyPot();
69
+		$this->validateReviewLimits();
70
+		$this->validateBlacklist();
71
+		$this->validateAkismet();
72
+		$this->validateRecaptcha();
73
+		if (!empty($this->error)) {
74
+			$this->setSessionValues('message', $this->error);
75
+		}
76
+		return $this;
77
+	}
78 78
 
79
-    /**
80
-     * @param string $path
81
-     * @param mixed $fallback
82
-     * @return mixed
83
-     */
84
-    protected function getOption($path, $fallback = '')
85
-    {
86
-        return Arr::get($this->options, $path, $fallback);
87
-    }
79
+	/**
80
+	 * @param string $path
81
+	 * @param mixed $fallback
82
+	 * @return mixed
83
+	 */
84
+	protected function getOption($path, $fallback = '')
85
+	{
86
+		return Arr::get($this->options, $path, $fallback);
87
+	}
88 88
 
89
-    /**
90
-     * @return int
91
-     */
92
-    protected function getRecaptchaStatus()
93
-    {
94
-        if (!glsr(OptionManager::class)->isRecaptchaEnabled()) {
95
-            return static::RECAPTCHA_DISABLED;
96
-        }
97
-        if (empty($this->request['_recaptcha-token'])) {
98
-            return $this->request['_counter'] < intval(apply_filters('site-reviews/recaptcha/timeout', 5))
99
-                ? static::RECAPTCHA_EMPTY
100
-                : static::RECAPTCHA_FAILED;
101
-        }
102
-        return $this->getRecaptchaTokenStatus();
103
-    }
89
+	/**
90
+	 * @return int
91
+	 */
92
+	protected function getRecaptchaStatus()
93
+	{
94
+		if (!glsr(OptionManager::class)->isRecaptchaEnabled()) {
95
+			return static::RECAPTCHA_DISABLED;
96
+		}
97
+		if (empty($this->request['_recaptcha-token'])) {
98
+			return $this->request['_counter'] < intval(apply_filters('site-reviews/recaptcha/timeout', 5))
99
+				? static::RECAPTCHA_EMPTY
100
+				: static::RECAPTCHA_FAILED;
101
+		}
102
+		return $this->getRecaptchaTokenStatus();
103
+	}
104 104
 
105
-    /**
106
-     * @return int
107
-     */
108
-    protected function getRecaptchaTokenStatus()
109
-    {
110
-        $endpoint = add_query_arg([
111
-            'remoteip' => Helper::getIpAddress(),
112
-            'response' => $this->request['_recaptcha-token'],
113
-            'secret' => $this->getOption('settings.submissions.recaptcha.secret'),
114
-        ], static::RECAPTCHA_ENDPOINT);
115
-        if (is_wp_error($response = wp_remote_get($endpoint))) {
116
-            glsr_log()->error($response->get_error_message());
117
-            return static::RECAPTCHA_FAILED;
118
-        }
119
-        $response = json_decode(wp_remote_retrieve_body($response));
120
-        if (!empty($response->success)) {
121
-            return boolval($response->success)
122
-                ? static::RECAPTCHA_VALID
123
-                : static::RECAPTCHA_INVALID;
124
-        }
125
-        foreach ($response->{'error-codes'} as $error) {
126
-            glsr_log()->error('reCAPTCHA error: '.$error);
127
-        }
128
-        return static::RECAPTCHA_INVALID;
129
-    }
105
+	/**
106
+	 * @return int
107
+	 */
108
+	protected function getRecaptchaTokenStatus()
109
+	{
110
+		$endpoint = add_query_arg([
111
+			'remoteip' => Helper::getIpAddress(),
112
+			'response' => $this->request['_recaptcha-token'],
113
+			'secret' => $this->getOption('settings.submissions.recaptcha.secret'),
114
+		], static::RECAPTCHA_ENDPOINT);
115
+		if (is_wp_error($response = wp_remote_get($endpoint))) {
116
+			glsr_log()->error($response->get_error_message());
117
+			return static::RECAPTCHA_FAILED;
118
+		}
119
+		$response = json_decode(wp_remote_retrieve_body($response));
120
+		if (!empty($response->success)) {
121
+			return boolval($response->success)
122
+				? static::RECAPTCHA_VALID
123
+				: static::RECAPTCHA_INVALID;
124
+		}
125
+		foreach ($response->{'error-codes'} as $error) {
126
+			glsr_log()->error('reCAPTCHA error: '.$error);
127
+		}
128
+		return static::RECAPTCHA_INVALID;
129
+	}
130 130
 
131
-    /**
132
-     * @return array
133
-     */
134
-    protected function getValidationRules(array $request)
135
-    {
136
-        $rules = array_intersect_key(
137
-            apply_filters('site-reviews/validation/rules', static::VALIDATION_RULES, $request),
138
-            array_flip($this->getOption('settings.submissions.required', []))
139
-        );
140
-        $excluded = explode(',', Arr::get($request, 'excluded'));
141
-        return array_diff_key($rules, array_flip($excluded));
142
-    }
131
+	/**
132
+	 * @return array
133
+	 */
134
+	protected function getValidationRules(array $request)
135
+	{
136
+		$rules = array_intersect_key(
137
+			apply_filters('site-reviews/validation/rules', static::VALIDATION_RULES, $request),
138
+			array_flip($this->getOption('settings.submissions.required', []))
139
+		);
140
+		$excluded = explode(',', Arr::get($request, 'excluded'));
141
+		return array_diff_key($rules, array_flip($excluded));
142
+	}
143 143
 
144
-    /**
145
-     * @return bool
146
-     */
147
-    protected function isRequestValid(array $request)
148
-    {
149
-        $rules = $this->getValidationRules($request);
150
-        $errors = glsr(Validator::class)->validate($request, $rules);
151
-        if (empty($errors)) {
152
-            return true;
153
-        }
154
-        $this->error = __('Please fix the submission errors.', 'site-reviews');
155
-        $this->setSessionValues('errors', $errors);
156
-        $this->setSessionValues('values', $request);
157
-        return false;
158
-    }
144
+	/**
145
+	 * @return bool
146
+	 */
147
+	protected function isRequestValid(array $request)
148
+	{
149
+		$rules = $this->getValidationRules($request);
150
+		$errors = glsr(Validator::class)->validate($request, $rules);
151
+		if (empty($errors)) {
152
+			return true;
153
+		}
154
+		$this->error = __('Please fix the submission errors.', 'site-reviews');
155
+		$this->setSessionValues('errors', $errors);
156
+		$this->setSessionValues('values', $request);
157
+		return false;
158
+	}
159 159
 
160
-    protected function setError($message, $loggedMessage = '')
161
-    {
162
-        $this->setSessionValues('errors', [], $loggedMessage);
163
-        $this->error = $message;
164
-    }
160
+	protected function setError($message, $loggedMessage = '')
161
+	{
162
+		$this->setSessionValues('errors', [], $loggedMessage);
163
+		$this->error = $message;
164
+	}
165 165
 
166
-    /**
167
-     * @param string $type
168
-     * @param mixed $value
169
-     * @param string $loggedMessage
170
-     * @return void
171
-     */
172
-    protected function setSessionValues($type, $value, $loggedMessage = '')
173
-    {
174
-        glsr()->sessionSet($this->form_id.$type, $value);
175
-        if (!empty($loggedMessage)) {
176
-            glsr_log()->warning($loggedMessage)->debug($this->request);
177
-        }
178
-    }
166
+	/**
167
+	 * @param string $type
168
+	 * @param mixed $value
169
+	 * @param string $loggedMessage
170
+	 * @return void
171
+	 */
172
+	protected function setSessionValues($type, $value, $loggedMessage = '')
173
+	{
174
+		glsr()->sessionSet($this->form_id.$type, $value);
175
+		if (!empty($loggedMessage)) {
176
+			glsr_log()->warning($loggedMessage)->debug($this->request);
177
+		}
178
+	}
179 179
 
180
-    /**
181
-     * @return void
182
-     */
183
-    protected function validateAkismet()
184
-    {
185
-        if (!empty($this->error)) {
186
-            return;
187
-        }
188
-        if (glsr(Akismet::class)->isSpam($this->request)) {
189
-            $this->setError(__('This review has been flagged as possible spam and cannot be submitted.', 'site-reviews'),
190
-                'Akismet caught a spam submission (consider adding the IP address to the blacklist):'
191
-            );
192
-        }
193
-    }
180
+	/**
181
+	 * @return void
182
+	 */
183
+	protected function validateAkismet()
184
+	{
185
+		if (!empty($this->error)) {
186
+			return;
187
+		}
188
+		if (glsr(Akismet::class)->isSpam($this->request)) {
189
+			$this->setError(__('This review has been flagged as possible spam and cannot be submitted.', 'site-reviews'),
190
+				'Akismet caught a spam submission (consider adding the IP address to the blacklist):'
191
+			);
192
+		}
193
+	}
194 194
 
195
-    /**
196
-     * @return void
197
-     */
198
-    protected function validateBlacklist()
199
-    {
200
-        if (!empty($this->error)) {
201
-            return;
202
-        }
203
-        if (!glsr(Blacklist::class)->isBlacklisted($this->request)) {
204
-            return;
205
-        }
206
-        $blacklistAction = $this->getOption('settings.submissions.blacklist.action');
207
-        if ('reject' != $blacklistAction) {
208
-            $this->request['blacklisted'] = true;
209
-            return;
210
-        }
211
-        $this->setError(__('Your review cannot be submitted at this time.', 'site-reviews'),
212
-            'Blacklisted submission detected:'
213
-        );
214
-    }
195
+	/**
196
+	 * @return void
197
+	 */
198
+	protected function validateBlacklist()
199
+	{
200
+		if (!empty($this->error)) {
201
+			return;
202
+		}
203
+		if (!glsr(Blacklist::class)->isBlacklisted($this->request)) {
204
+			return;
205
+		}
206
+		$blacklistAction = $this->getOption('settings.submissions.blacklist.action');
207
+		if ('reject' != $blacklistAction) {
208
+			$this->request['blacklisted'] = true;
209
+			return;
210
+		}
211
+		$this->setError(__('Your review cannot be submitted at this time.', 'site-reviews'),
212
+			'Blacklisted submission detected:'
213
+		);
214
+	}
215 215
 
216
-    /**
217
-     * @return void
218
-     */
219
-    protected function validateCustom()
220
-    {
221
-        if (!empty($this->error)) {
222
-            return;
223
-        }
224
-        $validated = apply_filters('site-reviews/validate/custom', true, $this->request);
225
-        if (true === $validated) {
226
-            return;
227
-        }
228
-        $errorMessage = is_string($validated)
229
-            ? $validated
230
-            : __('The review submission failed. Please notify the site administrator.', 'site-reviews');
231
-        $this->setError($errorMessage);
232
-        $this->setSessionValues('values', $this->request);
233
-    }
216
+	/**
217
+	 * @return void
218
+	 */
219
+	protected function validateCustom()
220
+	{
221
+		if (!empty($this->error)) {
222
+			return;
223
+		}
224
+		$validated = apply_filters('site-reviews/validate/custom', true, $this->request);
225
+		if (true === $validated) {
226
+			return;
227
+		}
228
+		$errorMessage = is_string($validated)
229
+			? $validated
230
+			: __('The review submission failed. Please notify the site administrator.', 'site-reviews');
231
+		$this->setError($errorMessage);
232
+		$this->setSessionValues('values', $this->request);
233
+	}
234 234
 
235
-    /**
236
-     * @return void
237
-     */
238
-    protected function validateHoneyPot()
239
-    {
240
-        if (!empty($this->error)) {
241
-            return;
242
-        }
243
-        if (!empty($this->request['gotcha'])) {
244
-            $this->setError(__('The review submission failed. Please notify the site administrator.', 'site-reviews'),
245
-                'The Honeypot caught a bad submission:'
246
-            );
247
-        }
248
-    }
235
+	/**
236
+	 * @return void
237
+	 */
238
+	protected function validateHoneyPot()
239
+	{
240
+		if (!empty($this->error)) {
241
+			return;
242
+		}
243
+		if (!empty($this->request['gotcha'])) {
244
+			$this->setError(__('The review submission failed. Please notify the site administrator.', 'site-reviews'),
245
+				'The Honeypot caught a bad submission:'
246
+			);
247
+		}
248
+	}
249 249
 
250
-    /**
251
-     * @return void
252
-     */
253
-    protected function validateReviewLimits()
254
-    {
255
-        if (!empty($this->error)) {
256
-            return;
257
-        }
258
-        if (glsr(ReviewLimits::class)->hasReachedLimit($this->request)) {
259
-            $this->setError(__('You have already submitted a review.', 'site-reviews'));
260
-        }
261
-    }
250
+	/**
251
+	 * @return void
252
+	 */
253
+	protected function validateReviewLimits()
254
+	{
255
+		if (!empty($this->error)) {
256
+			return;
257
+		}
258
+		if (glsr(ReviewLimits::class)->hasReachedLimit($this->request)) {
259
+			$this->setError(__('You have already submitted a review.', 'site-reviews'));
260
+		}
261
+	}
262 262
 
263
-    /**
264
-     * @return void
265
-     */
266
-    protected function validateRecaptcha()
267
-    {
268
-        if (!empty($this->error)) {
269
-            return;
270
-        }
271
-        $status = $this->getRecaptchaStatus();
272
-        if (in_array($status, [static::RECAPTCHA_DISABLED, static::RECAPTCHA_VALID])) {
273
-            return;
274
-        }
275
-        if (static::RECAPTCHA_EMPTY === $status) {
276
-            $this->setSessionValues('recaptcha', 'unset');
277
-            $this->recaptchaIsUnset = true;
278
-            return;
279
-        }
280
-        $this->setSessionValues('recaptcha', 'reset');
281
-        $errors = [
282
-            static::RECAPTCHA_FAILED => __('The reCAPTCHA failed to load, please refresh the page and try again.', 'site-reviews'),
283
-            static::RECAPTCHA_INVALID => __('The reCAPTCHA verification failed, please try again.', 'site-reviews'),
284
-        ];
285
-        $this->setError($errors[$status]);
286
-    }
263
+	/**
264
+	 * @return void
265
+	 */
266
+	protected function validateRecaptcha()
267
+	{
268
+		if (!empty($this->error)) {
269
+			return;
270
+		}
271
+		$status = $this->getRecaptchaStatus();
272
+		if (in_array($status, [static::RECAPTCHA_DISABLED, static::RECAPTCHA_VALID])) {
273
+			return;
274
+		}
275
+		if (static::RECAPTCHA_EMPTY === $status) {
276
+			$this->setSessionValues('recaptcha', 'unset');
277
+			$this->recaptchaIsUnset = true;
278
+			return;
279
+		}
280
+		$this->setSessionValues('recaptcha', 'reset');
281
+		$errors = [
282
+			static::RECAPTCHA_FAILED => __('The reCAPTCHA failed to load, please refresh the page and try again.', 'site-reviews'),
283
+			static::RECAPTCHA_INVALID => __('The reCAPTCHA verification failed, please try again.', 'site-reviews'),
284
+		];
285
+		$this->setError($errors[$status]);
286
+	}
287 287
 
288
-    /**
289
-     * @return array
290
-     */
291
-    protected function validateRequest(array $request)
292
-    {
293
-        return $this->isRequestValid($request)
294
-            ? array_merge(glsr(ValidateReviewDefaults::class)->defaults(), $request)
295
-            : $request;
296
-    }
288
+	/**
289
+	 * @return array
290
+	 */
291
+	protected function validateRequest(array $request)
292
+	{
293
+		return $this->isRequestValid($request)
294
+			? array_merge(glsr(ValidateReviewDefaults::class)->defaults(), $request)
295
+			: $request;
296
+	}
297 297
 }
Please login to merge, or discard this patch.
plugin/Modules/System.php 1 patch
Indentation   +351 added lines, -351 removed lines patch added patch discarded remove patch
@@ -12,377 +12,377 @@
 block discarded – undo
12 12
 
13 13
 class System
14 14
 {
15
-    const PAD = 40;
15
+	const PAD = 40;
16 16
 
17
-    /**
18
-     * @return string
19
-     */
20
-    public function __toString()
21
-    {
22
-        return $this->get();
23
-    }
17
+	/**
18
+	 * @return string
19
+	 */
20
+	public function __toString()
21
+	{
22
+		return $this->get();
23
+	}
24 24
 
25
-    /**
26
-     * @return string
27
-     */
28
-    public function get()
29
-    {
30
-        $details = [
31
-            'plugin' => 'Plugin Details',
32
-            'addon' => 'Addon Details',
33
-            'browser' => 'Browser Details',
34
-            'server' => 'Server Details',
35
-            'php' => 'PHP Configuration',
36
-            'wordpress' => 'WordPress Configuration',
37
-            'mu-plugin' => 'Must-Use Plugins',
38
-            'multisite-plugin' => 'Network Active Plugins',
39
-            'active-plugin' => 'Active Plugins',
40
-            'inactive-plugin' => 'Inactive Plugins',
41
-            'setting' => 'Plugin Settings',
42
-            'reviews' => 'Review Counts',
43
-        ];
44
-        $systemInfo = array_reduce(array_keys($details), function ($carry, $key) use ($details) {
45
-            $methodName = Helper::buildMethodName('get-'.$key.'-details');
46
-            if (method_exists($this, $methodName) && $systemDetails = $this->$methodName()) {
47
-                return $carry.$this->implode(
48
-                    strtoupper($details[$key]),
49
-                    apply_filters('site-reviews/system/'.$key, $systemDetails)
50
-                );
51
-            }
52
-            return $carry;
53
-        });
54
-        return trim($systemInfo);
55
-    }
25
+	/**
26
+	 * @return string
27
+	 */
28
+	public function get()
29
+	{
30
+		$details = [
31
+			'plugin' => 'Plugin Details',
32
+			'addon' => 'Addon Details',
33
+			'browser' => 'Browser Details',
34
+			'server' => 'Server Details',
35
+			'php' => 'PHP Configuration',
36
+			'wordpress' => 'WordPress Configuration',
37
+			'mu-plugin' => 'Must-Use Plugins',
38
+			'multisite-plugin' => 'Network Active Plugins',
39
+			'active-plugin' => 'Active Plugins',
40
+			'inactive-plugin' => 'Inactive Plugins',
41
+			'setting' => 'Plugin Settings',
42
+			'reviews' => 'Review Counts',
43
+		];
44
+		$systemInfo = array_reduce(array_keys($details), function ($carry, $key) use ($details) {
45
+			$methodName = Helper::buildMethodName('get-'.$key.'-details');
46
+			if (method_exists($this, $methodName) && $systemDetails = $this->$methodName()) {
47
+				return $carry.$this->implode(
48
+					strtoupper($details[$key]),
49
+					apply_filters('site-reviews/system/'.$key, $systemDetails)
50
+				);
51
+			}
52
+			return $carry;
53
+		});
54
+		return trim($systemInfo);
55
+	}
56 56
 
57
-    /**
58
-     * @return array
59
-     */
60
-    public function getActivePluginDetails()
61
-    {
62
-        $plugins = get_plugins();
63
-        $activePlugins = glsr(OptionManager::class)->getWP('active_plugins', [], 'array');
64
-        $inactive = array_diff_key($plugins, array_flip($activePlugins));
65
-        return $this->normalizePluginList(array_diff_key($plugins, $inactive));
66
-    }
57
+	/**
58
+	 * @return array
59
+	 */
60
+	public function getActivePluginDetails()
61
+	{
62
+		$plugins = get_plugins();
63
+		$activePlugins = glsr(OptionManager::class)->getWP('active_plugins', [], 'array');
64
+		$inactive = array_diff_key($plugins, array_flip($activePlugins));
65
+		return $this->normalizePluginList(array_diff_key($plugins, $inactive));
66
+	}
67 67
 
68
-    /**
69
-     * @return array
70
-     */
71
-    public function getAddonDetails()
72
-    {
73
-        $details = apply_filters('site-reviews/addon/system-info', []);
74
-        ksort($details);
75
-        return $details;
76
-    }
68
+	/**
69
+	 * @return array
70
+	 */
71
+	public function getAddonDetails()
72
+	{
73
+		$details = apply_filters('site-reviews/addon/system-info', []);
74
+		ksort($details);
75
+		return $details;
76
+	}
77 77
 
78
-    /**
79
-     * @return array
80
-     */
81
-    public function getBrowserDetails()
82
-    {
83
-        $browser = new Browser();
84
-        $name = esc_attr($browser->getName());
85
-        $userAgent = esc_attr($browser->getUserAgent()->getUserAgentString());
86
-        $version = esc_attr($browser->getVersion());
87
-        return [
88
-            'Browser Name' => sprintf('%s %s', $name, $version),
89
-            'Browser UA' => $userAgent,
90
-        ];
91
-    }
78
+	/**
79
+	 * @return array
80
+	 */
81
+	public function getBrowserDetails()
82
+	{
83
+		$browser = new Browser();
84
+		$name = esc_attr($browser->getName());
85
+		$userAgent = esc_attr($browser->getUserAgent()->getUserAgentString());
86
+		$version = esc_attr($browser->getVersion());
87
+		return [
88
+			'Browser Name' => sprintf('%s %s', $name, $version),
89
+			'Browser UA' => $userAgent,
90
+		];
91
+	}
92 92
 
93
-    /**
94
-     * @return array
95
-     */
96
-    public function getInactivePluginDetails()
97
-    {
98
-        $activePlugins = glsr(OptionManager::class)->getWP('active_plugins', [], 'array');
99
-        $inactivePlugins = $this->normalizePluginList(array_diff_key(get_plugins(), array_flip($activePlugins)));
100
-        $multisitePlugins = $this->getMultisitePluginDetails();
101
-        return empty($multisitePlugins)
102
-            ? $inactivePlugins
103
-            : array_diff($inactivePlugins, $multisitePlugins);
104
-    }
93
+	/**
94
+	 * @return array
95
+	 */
96
+	public function getInactivePluginDetails()
97
+	{
98
+		$activePlugins = glsr(OptionManager::class)->getWP('active_plugins', [], 'array');
99
+		$inactivePlugins = $this->normalizePluginList(array_diff_key(get_plugins(), array_flip($activePlugins)));
100
+		$multisitePlugins = $this->getMultisitePluginDetails();
101
+		return empty($multisitePlugins)
102
+			? $inactivePlugins
103
+			: array_diff($inactivePlugins, $multisitePlugins);
104
+	}
105 105
 
106
-    /**
107
-     * @return array
108
-     */
109
-    public function getMuPluginDetails()
110
-    {
111
-        if (empty($plugins = get_mu_plugins())) {
112
-            return [];
113
-        }
114
-        return $this->normalizePluginList($plugins);
115
-    }
106
+	/**
107
+	 * @return array
108
+	 */
109
+	public function getMuPluginDetails()
110
+	{
111
+		if (empty($plugins = get_mu_plugins())) {
112
+			return [];
113
+		}
114
+		return $this->normalizePluginList($plugins);
115
+	}
116 116
 
117
-    /**
118
-     * @return array
119
-     */
120
-    public function getMultisitePluginDetails()
121
-    {
122
-        $activePlugins = (array) get_site_option('active_sitewide_plugins', []);
123
-        if (!is_multisite() || empty($activePlugins)) {
124
-            return [];
125
-        }
126
-        return $this->normalizePluginList(array_intersect_key(get_plugins(), $activePlugins));
127
-    }
117
+	/**
118
+	 * @return array
119
+	 */
120
+	public function getMultisitePluginDetails()
121
+	{
122
+		$activePlugins = (array) get_site_option('active_sitewide_plugins', []);
123
+		if (!is_multisite() || empty($activePlugins)) {
124
+			return [];
125
+		}
126
+		return $this->normalizePluginList(array_intersect_key(get_plugins(), $activePlugins));
127
+	}
128 128
 
129
-    /**
130
-     * @return array
131
-     */
132
-    public function getPhpDetails()
133
-    {
134
-        $displayErrors = $this->getINI('display_errors', null)
135
-            ? 'On ('.$this->getINI('display_errors').')'
136
-            : 'N/A';
137
-        $intlSupport = extension_loaded('intl')
138
-            ? phpversion('intl')
139
-            : 'false';
140
-        return [
141
-            'cURL' => var_export(function_exists('curl_init'), true),
142
-            'Default Charset' => $this->getINI('default_charset'),
143
-            'Display Errors' => $displayErrors,
144
-            'fsockopen' => var_export(function_exists('fsockopen'), true),
145
-            'Intl' => $intlSupport,
146
-            'IPv6' => var_export(defined('AF_INET6'), true),
147
-            'Max Execution Time' => $this->getINI('max_execution_time'),
148
-            'Max Input Nesting Level' => $this->getINI('max_input_nesting_level'),
149
-            'Max Input Vars' => $this->getINI('max_input_vars'),
150
-            'Memory Limit' => $this->getINI('memory_limit'),
151
-            'Post Max Size' => $this->getINI('post_max_size'),
152
-            'Sendmail Path' => $this->getINI('sendmail_path'),
153
-            'Session Cookie Path' => esc_html($this->getINI('session.cookie_path')),
154
-            'Session Name' => esc_html($this->getINI('session.name')),
155
-            'Session Save Path' => esc_html($this->getINI('session.save_path')),
156
-            'Session Use Cookies' => var_export(wp_validate_boolean($this->getINI('session.use_cookies', false)), true),
157
-            'Session Use Only Cookies' => var_export(wp_validate_boolean($this->getINI('session.use_only_cookies', false)), true),
158
-            'Upload Max Filesize' => $this->getINI('upload_max_filesize'),
159
-        ];
160
-    }
129
+	/**
130
+	 * @return array
131
+	 */
132
+	public function getPhpDetails()
133
+	{
134
+		$displayErrors = $this->getINI('display_errors', null)
135
+			? 'On ('.$this->getINI('display_errors').')'
136
+			: 'N/A';
137
+		$intlSupport = extension_loaded('intl')
138
+			? phpversion('intl')
139
+			: 'false';
140
+		return [
141
+			'cURL' => var_export(function_exists('curl_init'), true),
142
+			'Default Charset' => $this->getINI('default_charset'),
143
+			'Display Errors' => $displayErrors,
144
+			'fsockopen' => var_export(function_exists('fsockopen'), true),
145
+			'Intl' => $intlSupport,
146
+			'IPv6' => var_export(defined('AF_INET6'), true),
147
+			'Max Execution Time' => $this->getINI('max_execution_time'),
148
+			'Max Input Nesting Level' => $this->getINI('max_input_nesting_level'),
149
+			'Max Input Vars' => $this->getINI('max_input_vars'),
150
+			'Memory Limit' => $this->getINI('memory_limit'),
151
+			'Post Max Size' => $this->getINI('post_max_size'),
152
+			'Sendmail Path' => $this->getINI('sendmail_path'),
153
+			'Session Cookie Path' => esc_html($this->getINI('session.cookie_path')),
154
+			'Session Name' => esc_html($this->getINI('session.name')),
155
+			'Session Save Path' => esc_html($this->getINI('session.save_path')),
156
+			'Session Use Cookies' => var_export(wp_validate_boolean($this->getINI('session.use_cookies', false)), true),
157
+			'Session Use Only Cookies' => var_export(wp_validate_boolean($this->getINI('session.use_only_cookies', false)), true),
158
+			'Upload Max Filesize' => $this->getINI('upload_max_filesize'),
159
+		];
160
+	}
161 161
 
162
-    /**
163
-     * @return array
164
-     */
165
-    public function getReviewsDetails()
166
-    {
167
-        $counts = glsr(CountsManager::class)->getCounts();
168
-        $counts = Arr::flattenArray($counts);
169
-        array_walk($counts, function (&$ratings) use ($counts) {
170
-            if (!is_array($ratings)) {
171
-                glsr_log()
172
-                    ->error('$ratings is not an array, possibly due to incorrectly imported reviews.')
173
-                    ->debug($ratings)
174
-                    ->debug($counts);
175
-                return;
176
-            }
177
-            $ratings = array_sum($ratings).' ('.implode(', ', $ratings).')';
178
-        });
179
-        ksort($counts);
180
-        return $counts;
181
-    }
162
+	/**
163
+	 * @return array
164
+	 */
165
+	public function getReviewsDetails()
166
+	{
167
+		$counts = glsr(CountsManager::class)->getCounts();
168
+		$counts = Arr::flattenArray($counts);
169
+		array_walk($counts, function (&$ratings) use ($counts) {
170
+			if (!is_array($ratings)) {
171
+				glsr_log()
172
+					->error('$ratings is not an array, possibly due to incorrectly imported reviews.')
173
+					->debug($ratings)
174
+					->debug($counts);
175
+				return;
176
+			}
177
+			$ratings = array_sum($ratings).' ('.implode(', ', $ratings).')';
178
+		});
179
+		ksort($counts);
180
+		return $counts;
181
+	}
182 182
 
183
-    /**
184
-     * @return array
185
-     */
186
-    public function getServerDetails()
187
-    {
188
-        global $wpdb;
189
-        return [
190
-            'Host Name' => $this->getHostName(),
191
-            'MySQL Version' => $wpdb->db_version(),
192
-            'PHP Version' => PHP_VERSION,
193
-            'Server Software' => filter_input(INPUT_SERVER, 'SERVER_SOFTWARE'),
194
-        ];
195
-    }
183
+	/**
184
+	 * @return array
185
+	 */
186
+	public function getServerDetails()
187
+	{
188
+		global $wpdb;
189
+		return [
190
+			'Host Name' => $this->getHostName(),
191
+			'MySQL Version' => $wpdb->db_version(),
192
+			'PHP Version' => PHP_VERSION,
193
+			'Server Software' => filter_input(INPUT_SERVER, 'SERVER_SOFTWARE'),
194
+		];
195
+	}
196 196
 
197
-    /**
198
-     * @return array
199
-     */
200
-    public function getSettingDetails()
201
-    {
202
-        $settings = glsr(OptionManager::class)->get('settings', []);
203
-        $settings = Arr::flattenArray($settings, true);
204
-        $settings = $this->purgeSensitiveData($settings);
205
-        ksort($settings);
206
-        $details = [];
207
-        foreach ($settings as $key => $value) {
208
-            if (Str::startsWith('strings', $key) && Str::endsWith('id', $key)) {
209
-                continue;
210
-            }
211
-            $value = htmlspecialchars(trim(preg_replace('/\s\s+/', '\\n', $value)), ENT_QUOTES, 'UTF-8');
212
-            $details[$key] = $value;
213
-        }
214
-        return $details;
215
-    }
197
+	/**
198
+	 * @return array
199
+	 */
200
+	public function getSettingDetails()
201
+	{
202
+		$settings = glsr(OptionManager::class)->get('settings', []);
203
+		$settings = Arr::flattenArray($settings, true);
204
+		$settings = $this->purgeSensitiveData($settings);
205
+		ksort($settings);
206
+		$details = [];
207
+		foreach ($settings as $key => $value) {
208
+			if (Str::startsWith('strings', $key) && Str::endsWith('id', $key)) {
209
+				continue;
210
+			}
211
+			$value = htmlspecialchars(trim(preg_replace('/\s\s+/', '\\n', $value)), ENT_QUOTES, 'UTF-8');
212
+			$details[$key] = $value;
213
+		}
214
+		return $details;
215
+	}
216 216
 
217
-    /**
218
-     * @return array
219
-     */
220
-    public function getPluginDetails()
221
-    {
222
-        return [
223
-            'Console level' => glsr(Console::class)->humanLevel(),
224
-            'Console size' => glsr(Console::class)->humanSize('0'),
225
-            'Last Rating Count' => date_i18n('Y-m-d H:i', glsr(OptionManager::class)->get('last_review_count')),
226
-            'Version (current)' => glsr()->version,
227
-            'Version (previous)' => glsr(OptionManager::class)->get('version_upgraded_from'),
228
-        ];
229
-    }
217
+	/**
218
+	 * @return array
219
+	 */
220
+	public function getPluginDetails()
221
+	{
222
+		return [
223
+			'Console level' => glsr(Console::class)->humanLevel(),
224
+			'Console size' => glsr(Console::class)->humanSize('0'),
225
+			'Last Rating Count' => date_i18n('Y-m-d H:i', glsr(OptionManager::class)->get('last_review_count')),
226
+			'Version (current)' => glsr()->version,
227
+			'Version (previous)' => glsr(OptionManager::class)->get('version_upgraded_from'),
228
+		];
229
+	}
230 230
 
231
-    /**
232
-     * @return array
233
-     */
234
-    public function getWordpressDetails()
235
-    {
236
-        global $wpdb;
237
-        $theme = wp_get_theme();
238
-        return [
239
-            'Active Theme' => sprintf('%s v%s', (string) $theme->Name, (string) $theme->Version),
240
-            'Email Domain' => substr(strrchr(glsr(OptionManager::class)->getWP('admin_email'), '@'), 1),
241
-            'Home URL' => home_url(),
242
-            'Language' => get_locale(),
243
-            'Memory Limit' => WP_MEMORY_LIMIT,
244
-            'Multisite' => var_export(is_multisite(), true),
245
-            'Page For Posts ID' => glsr(OptionManager::class)->getWP('page_for_posts'),
246
-            'Page On Front ID' => glsr(OptionManager::class)->getWP('page_on_front'),
247
-            'Permalink Structure' => glsr(OptionManager::class)->getWP('permalink_structure', 'default'),
248
-            'Post Stati' => implode(', ', get_post_stati()),
249
-            'Remote Post' => glsr(Cache::class)->getRemotePostTest(),
250
-            'Show On Front' => glsr(OptionManager::class)->getWP('show_on_front'),
251
-            'Site URL' => site_url(),
252
-            'Timezone' => glsr(OptionManager::class)->getWP('timezone_string', $this->getINI('date.timezone').' (PHP)'),
253
-            'Version' => get_bloginfo('version'),
254
-            'WP Debug' => var_export(defined('WP_DEBUG'), true),
255
-            'WP Max Upload Size' => size_format(wp_max_upload_size()),
256
-            'WP Memory Limit' => WP_MEMORY_LIMIT,
257
-        ];
258
-    }
231
+	/**
232
+	 * @return array
233
+	 */
234
+	public function getWordpressDetails()
235
+	{
236
+		global $wpdb;
237
+		$theme = wp_get_theme();
238
+		return [
239
+			'Active Theme' => sprintf('%s v%s', (string) $theme->Name, (string) $theme->Version),
240
+			'Email Domain' => substr(strrchr(glsr(OptionManager::class)->getWP('admin_email'), '@'), 1),
241
+			'Home URL' => home_url(),
242
+			'Language' => get_locale(),
243
+			'Memory Limit' => WP_MEMORY_LIMIT,
244
+			'Multisite' => var_export(is_multisite(), true),
245
+			'Page For Posts ID' => glsr(OptionManager::class)->getWP('page_for_posts'),
246
+			'Page On Front ID' => glsr(OptionManager::class)->getWP('page_on_front'),
247
+			'Permalink Structure' => glsr(OptionManager::class)->getWP('permalink_structure', 'default'),
248
+			'Post Stati' => implode(', ', get_post_stati()),
249
+			'Remote Post' => glsr(Cache::class)->getRemotePostTest(),
250
+			'Show On Front' => glsr(OptionManager::class)->getWP('show_on_front'),
251
+			'Site URL' => site_url(),
252
+			'Timezone' => glsr(OptionManager::class)->getWP('timezone_string', $this->getINI('date.timezone').' (PHP)'),
253
+			'Version' => get_bloginfo('version'),
254
+			'WP Debug' => var_export(defined('WP_DEBUG'), true),
255
+			'WP Max Upload Size' => size_format(wp_max_upload_size()),
256
+			'WP Memory Limit' => WP_MEMORY_LIMIT,
257
+		];
258
+	}
259 259
 
260
-    /**
261
-     * @return string
262
-     */
263
-    protected function detectWebhostProvider()
264
-    {
265
-        $checks = [
266
-            '.accountservergroup.com' => 'Site5',
267
-            '.gridserver.com' => 'MediaTemple Grid',
268
-            '.inmotionhosting.com' => 'InMotion Hosting',
269
-            '.ovh.net' => 'OVH',
270
-            '.pair.com' => 'pair Networks',
271
-            '.stabletransit.com' => 'Rackspace Cloud',
272
-            '.stratoserver.net' => 'STRATO',
273
-            '.sysfix.eu' => 'SysFix.eu Power Hosting',
274
-            'bluehost.com' => 'Bluehost',
275
-            'DH_USER' => 'DreamHost',
276
-            'Flywheel' => 'Flywheel',
277
-            'ipagemysql.com' => 'iPage',
278
-            'ipowermysql.com' => 'IPower',
279
-            'localhost:/tmp/mysql5.sock' => 'ICDSoft',
280
-            'mysqlv5' => 'NetworkSolutions',
281
-            'PAGELYBIN' => 'Pagely',
282
-            'secureserver.net' => 'GoDaddy',
283
-            'WPE_APIKEY' => 'WP Engine',
284
-        ];
285
-        foreach ($checks as $key => $value) {
286
-            if (!$this->isWebhostCheckValid($key)) {
287
-                continue;
288
-            }
289
-            return $value;
290
-        }
291
-        return implode(',', array_filter([DB_HOST, filter_input(INPUT_SERVER, 'SERVER_NAME')]));
292
-    }
260
+	/**
261
+	 * @return string
262
+	 */
263
+	protected function detectWebhostProvider()
264
+	{
265
+		$checks = [
266
+			'.accountservergroup.com' => 'Site5',
267
+			'.gridserver.com' => 'MediaTemple Grid',
268
+			'.inmotionhosting.com' => 'InMotion Hosting',
269
+			'.ovh.net' => 'OVH',
270
+			'.pair.com' => 'pair Networks',
271
+			'.stabletransit.com' => 'Rackspace Cloud',
272
+			'.stratoserver.net' => 'STRATO',
273
+			'.sysfix.eu' => 'SysFix.eu Power Hosting',
274
+			'bluehost.com' => 'Bluehost',
275
+			'DH_USER' => 'DreamHost',
276
+			'Flywheel' => 'Flywheel',
277
+			'ipagemysql.com' => 'iPage',
278
+			'ipowermysql.com' => 'IPower',
279
+			'localhost:/tmp/mysql5.sock' => 'ICDSoft',
280
+			'mysqlv5' => 'NetworkSolutions',
281
+			'PAGELYBIN' => 'Pagely',
282
+			'secureserver.net' => 'GoDaddy',
283
+			'WPE_APIKEY' => 'WP Engine',
284
+		];
285
+		foreach ($checks as $key => $value) {
286
+			if (!$this->isWebhostCheckValid($key)) {
287
+				continue;
288
+			}
289
+			return $value;
290
+		}
291
+		return implode(',', array_filter([DB_HOST, filter_input(INPUT_SERVER, 'SERVER_NAME')]));
292
+	}
293 293
 
294
-    /**
295
-     * @return string
296
-     */
297
-    protected function getHostName()
298
-    {
299
-        return sprintf('%s (%s)',
300
-            $this->detectWebhostProvider(),
301
-            Helper::getIpAddress()
302
-        );
303
-    }
294
+	/**
295
+	 * @return string
296
+	 */
297
+	protected function getHostName()
298
+	{
299
+		return sprintf('%s (%s)',
300
+			$this->detectWebhostProvider(),
301
+			Helper::getIpAddress()
302
+		);
303
+	}
304 304
 
305
-    protected function getINI($name, $disabledValue = 'ini_get() is disabled.')
306
-    {
307
-        return function_exists('ini_get')
308
-            ? ini_get($name)
309
-            : $disabledValue;
310
-    }
305
+	protected function getINI($name, $disabledValue = 'ini_get() is disabled.')
306
+	{
307
+		return function_exists('ini_get')
308
+			? ini_get($name)
309
+			: $disabledValue;
310
+	}
311 311
 
312
-    /**
313
-     * @return array
314
-     */
315
-    protected function getWordpressPlugins()
316
-    {
317
-        $plugins = get_plugins();
318
-        $activePlugins = glsr(OptionManager::class)->getWP('active_plugins', [], 'array');
319
-        $inactive = $this->normalizePluginList(array_diff_key($plugins, array_flip($activePlugins)));
320
-        $active = $this->normalizePluginList(array_diff_key($plugins, $inactive));
321
-        return $active + $inactive;
322
-    }
312
+	/**
313
+	 * @return array
314
+	 */
315
+	protected function getWordpressPlugins()
316
+	{
317
+		$plugins = get_plugins();
318
+		$activePlugins = glsr(OptionManager::class)->getWP('active_plugins', [], 'array');
319
+		$inactive = $this->normalizePluginList(array_diff_key($plugins, array_flip($activePlugins)));
320
+		$active = $this->normalizePluginList(array_diff_key($plugins, $inactive));
321
+		return $active + $inactive;
322
+	}
323 323
 
324
-    /**
325
-     * @param string $title
326
-     * @return string
327
-     */
328
-    protected function implode($title, array $details)
329
-    {
330
-        $strings = ['['.$title.']'];
331
-        $padding = max(array_map('strlen', array_keys($details)));
332
-        $padding = max([$padding, static::PAD]);
333
-        foreach ($details as $key => $value) {
334
-            $strings[] = is_string($key)
335
-                ? sprintf('%s : %s', str_pad($key, $padding, '.'), $value)
336
-                : ' - '.$value;
337
-        }
338
-        return implode(PHP_EOL, $strings).PHP_EOL.PHP_EOL;
339
-    }
324
+	/**
325
+	 * @param string $title
326
+	 * @return string
327
+	 */
328
+	protected function implode($title, array $details)
329
+	{
330
+		$strings = ['['.$title.']'];
331
+		$padding = max(array_map('strlen', array_keys($details)));
332
+		$padding = max([$padding, static::PAD]);
333
+		foreach ($details as $key => $value) {
334
+			$strings[] = is_string($key)
335
+				? sprintf('%s : %s', str_pad($key, $padding, '.'), $value)
336
+				: ' - '.$value;
337
+		}
338
+		return implode(PHP_EOL, $strings).PHP_EOL.PHP_EOL;
339
+	}
340 340
 
341
-    /**
342
-     * @param string $key
343
-     * @return bool
344
-     */
345
-    protected function isWebhostCheckValid($key)
346
-    {
347
-        return defined($key)
348
-            || filter_input(INPUT_SERVER, $key)
349
-            || Str::contains(filter_input(INPUT_SERVER, 'SERVER_NAME'), $key)
350
-            || Str::contains(DB_HOST, $key)
351
-            || Str::contains(php_uname(), $key);
352
-    }
341
+	/**
342
+	 * @param string $key
343
+	 * @return bool
344
+	 */
345
+	protected function isWebhostCheckValid($key)
346
+	{
347
+		return defined($key)
348
+			|| filter_input(INPUT_SERVER, $key)
349
+			|| Str::contains(filter_input(INPUT_SERVER, 'SERVER_NAME'), $key)
350
+			|| Str::contains(DB_HOST, $key)
351
+			|| Str::contains(php_uname(), $key);
352
+	}
353 353
 
354
-    /**
355
-     * @return array
356
-     */
357
-    protected function normalizePluginList(array $plugins)
358
-    {
359
-        $plugins = array_map(function ($plugin) {
360
-            return sprintf('%s v%s', Arr::get($plugin, 'Name'), Arr::get($plugin, 'Version'));
361
-        }, $plugins);
362
-        natcasesort($plugins);
363
-        return array_flip($plugins);
364
-    }
354
+	/**
355
+	 * @return array
356
+	 */
357
+	protected function normalizePluginList(array $plugins)
358
+	{
359
+		$plugins = array_map(function ($plugin) {
360
+			return sprintf('%s v%s', Arr::get($plugin, 'Name'), Arr::get($plugin, 'Version'));
361
+		}, $plugins);
362
+		natcasesort($plugins);
363
+		return array_flip($plugins);
364
+	}
365 365
 
366
-    /**
367
-     * @return array
368
-     */
369
-    protected function purgeSensitiveData(array $settings)
370
-    {
371
-        $keys = [
372
-            'general.rebusify_serial',
373
-            'licenses.',
374
-            'submissions.recaptcha.key',
375
-            'submissions.recaptcha.secret',
376
-        ];
377
-        array_walk($settings, function (&$value, $setting) use ($keys) {
378
-            foreach ($keys as $key) {
379
-                if (!Str::startsWith($key, $setting) || empty($value)) {
380
-                    continue;
381
-                }
382
-                $value = str_repeat('•', 13);
383
-                return;
384
-            }
385
-        });
386
-        return $settings;
387
-    }
366
+	/**
367
+	 * @return array
368
+	 */
369
+	protected function purgeSensitiveData(array $settings)
370
+	{
371
+		$keys = [
372
+			'general.rebusify_serial',
373
+			'licenses.',
374
+			'submissions.recaptcha.key',
375
+			'submissions.recaptcha.secret',
376
+		];
377
+		array_walk($settings, function (&$value, $setting) use ($keys) {
378
+			foreach ($keys as $key) {
379
+				if (!Str::startsWith($key, $setting) || empty($value)) {
380
+					continue;
381
+				}
382
+				$value = str_repeat('•', 13);
383
+				return;
384
+			}
385
+		});
386
+		return $settings;
387
+	}
388 388
 }
Please login to merge, or discard this patch.
plugin/Helper.php 1 patch
Indentation   +114 added lines, -114 removed lines patch added patch discarded remove patch
@@ -8,124 +8,124 @@
 block discarded – undo
8 8
 
9 9
 class Helper
10 10
 {
11
-    /**
12
-     * @param string $name
13
-     * @param string $path
14
-     * @return string
15
-     */
16
-    public static function buildClassName($name, $path = '')
17
-    {
18
-        $className = Str::camelCase($name);
19
-        $path = ltrim(str_replace(__NAMESPACE__, '', $path), '\\');
20
-        return !empty($path)
21
-            ? __NAMESPACE__.'\\'.$path.'\\'.$className
22
-            : $className;
23
-    }
11
+	/**
12
+	 * @param string $name
13
+	 * @param string $path
14
+	 * @return string
15
+	 */
16
+	public static function buildClassName($name, $path = '')
17
+	{
18
+		$className = Str::camelCase($name);
19
+		$path = ltrim(str_replace(__NAMESPACE__, '', $path), '\\');
20
+		return !empty($path)
21
+			? __NAMESPACE__.'\\'.$path.'\\'.$className
22
+			: $className;
23
+	}
24 24
 
25
-    /**
26
-     * @param string $name
27
-     * @param string $prefix
28
-     * @return string
29
-     */
30
-    public static function buildMethodName($name, $prefix = '')
31
-    {
32
-        return lcfirst($prefix.static::buildClassName($name));
33
-    }
25
+	/**
26
+	 * @param string $name
27
+	 * @param string $prefix
28
+	 * @return string
29
+	 */
30
+	public static function buildMethodName($name, $prefix = '')
31
+	{
32
+		return lcfirst($prefix.static::buildClassName($name));
33
+	}
34 34
 
35
-    /**
36
-     * @param string $name
37
-     * @return string
38
-     */
39
-    public static function buildPropertyName($name)
40
-    {
41
-        return lcfirst(static::buildClassName($name));
42
-    }
35
+	/**
36
+	 * @param string $name
37
+	 * @return string
38
+	 */
39
+	public static function buildPropertyName($name)
40
+	{
41
+		return lcfirst(static::buildClassName($name));
42
+	}
43 43
 
44
-    /**
45
-     * @param string $cast
46
-     * @param mixed $value
47
-     * @return mixed
48
-     */
49
-    public static function castTo($cast = '', $value)
50
-    {
51
-        switch ($cast) {
52
-            case 'array':
53
-                return (array) $value;
54
-            case 'bool':
55
-            case 'boolean':
56
-                return filter_var($value, FILTER_VALIDATE_BOOLEAN);
57
-            case 'float':
58
-                return (float) filter_var($value, FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);
59
-            case 'int':
60
-            case 'integer':
61
-                return (int) filter_var($value, FILTER_VALIDATE_INT);
62
-            case 'object':
63
-                return (object) (array) $value;
64
-            case 'str':
65
-            case 'string':
66
-                if (is_object($value) && in_array('__toString', get_class_methods($value))) {
67
-                    return (string) $value->__toString();
68
-                }
69
-                if (is_array($value) || is_object($value)) {
70
-                    return serialize($value);
71
-                }
72
-                return (string) $value;
73
-            default:
74
-                return $value;
75
-        }
76
-    }
44
+	/**
45
+	 * @param string $cast
46
+	 * @param mixed $value
47
+	 * @return mixed
48
+	 */
49
+	public static function castTo($cast = '', $value)
50
+	{
51
+		switch ($cast) {
52
+			case 'array':
53
+				return (array) $value;
54
+			case 'bool':
55
+			case 'boolean':
56
+				return filter_var($value, FILTER_VALIDATE_BOOLEAN);
57
+			case 'float':
58
+				return (float) filter_var($value, FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);
59
+			case 'int':
60
+			case 'integer':
61
+				return (int) filter_var($value, FILTER_VALIDATE_INT);
62
+			case 'object':
63
+				return (object) (array) $value;
64
+			case 'str':
65
+			case 'string':
66
+				if (is_object($value) && in_array('__toString', get_class_methods($value))) {
67
+					return (string) $value->__toString();
68
+				}
69
+				if (is_array($value) || is_object($value)) {
70
+					return serialize($value);
71
+				}
72
+				return (string) $value;
73
+			default:
74
+				return $value;
75
+		}
76
+	}
77 77
 
78
-    /**
79
-     * @param string $key
80
-     * @return mixed
81
-     */
82
-    public static function filterInput($key, array $request = [])
83
-    {
84
-        if (isset($request[$key])) {
85
-            return $request[$key];
86
-        }
87
-        $variable = filter_input(INPUT_POST, $key);
88
-        if (is_null($variable) && isset($_POST[$key])) {
89
-            $variable = $_POST[$key];
90
-        }
91
-        return $variable;
92
-    }
78
+	/**
79
+	 * @param string $key
80
+	 * @return mixed
81
+	 */
82
+	public static function filterInput($key, array $request = [])
83
+	{
84
+		if (isset($request[$key])) {
85
+			return $request[$key];
86
+		}
87
+		$variable = filter_input(INPUT_POST, $key);
88
+		if (is_null($variable) && isset($_POST[$key])) {
89
+			$variable = $_POST[$key];
90
+		}
91
+		return $variable;
92
+	}
93 93
 
94
-    /**
95
-     * @param string $key
96
-     * @return array
97
-     */
98
-    public static function filterInputArray($key)
99
-    {
100
-        $variable = filter_input(INPUT_POST, $key, FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
101
-        if (empty($variable) && !empty($_POST[$key]) && is_array($_POST[$key])) {
102
-            $variable = $_POST[$key];
103
-        }
104
-        return (array) $variable;
105
-    }
94
+	/**
95
+	 * @param string $key
96
+	 * @return array
97
+	 */
98
+	public static function filterInputArray($key)
99
+	{
100
+		$variable = filter_input(INPUT_POST, $key, FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
101
+		if (empty($variable) && !empty($_POST[$key]) && is_array($_POST[$key])) {
102
+			$variable = $_POST[$key];
103
+		}
104
+		return (array) $variable;
105
+	}
106 106
 
107
-    /**
108
-     * @return string
109
-     */
110
-    public static function getIpAddress()
111
-    {
112
-        $whitelist = [];
113
-        $isUsingCloudflare = !empty(filter_input(INPUT_SERVER, 'CF-Connecting-IP'));
114
-        if (apply_filters('site-reviews/whip/whitelist/cloudflare', $isUsingCloudflare)) {
115
-            $cloudflareIps = glsr(Cache::class)->getCloudflareIps();
116
-            $whitelist[Whip::CLOUDFLARE_HEADERS] = [Whip::IPV4 => $cloudflareIps['v4']];
117
-            if (defined('AF_INET6')) {
118
-                $whitelist[Whip::CLOUDFLARE_HEADERS][Whip::IPV6] = $cloudflareIps['v6'];
119
-            }
120
-        }
121
-        $whitelist = apply_filters('site-reviews/whip/whitelist', $whitelist);
122
-        $methods = apply_filters('site-reviews/whip/methods', Whip::ALL_METHODS);
123
-        $whip = new Whip($methods, $whitelist);
124
-        do_action_ref_array('site-reviews/whip', [$whip]);
125
-        if (false !== ($clientAddress = $whip->getValidIpAddress())) {
126
-            return (string) $clientAddress;
127
-        }
128
-        glsr_log()->error('Unable to detect IP address.');
129
-        return 'unknown';
130
-    }
107
+	/**
108
+	 * @return string
109
+	 */
110
+	public static function getIpAddress()
111
+	{
112
+		$whitelist = [];
113
+		$isUsingCloudflare = !empty(filter_input(INPUT_SERVER, 'CF-Connecting-IP'));
114
+		if (apply_filters('site-reviews/whip/whitelist/cloudflare', $isUsingCloudflare)) {
115
+			$cloudflareIps = glsr(Cache::class)->getCloudflareIps();
116
+			$whitelist[Whip::CLOUDFLARE_HEADERS] = [Whip::IPV4 => $cloudflareIps['v4']];
117
+			if (defined('AF_INET6')) {
118
+				$whitelist[Whip::CLOUDFLARE_HEADERS][Whip::IPV6] = $cloudflareIps['v6'];
119
+			}
120
+		}
121
+		$whitelist = apply_filters('site-reviews/whip/whitelist', $whitelist);
122
+		$methods = apply_filters('site-reviews/whip/methods', Whip::ALL_METHODS);
123
+		$whip = new Whip($methods, $whitelist);
124
+		do_action_ref_array('site-reviews/whip', [$whip]);
125
+		if (false !== ($clientAddress = $whip->getValidIpAddress())) {
126
+			return (string) $clientAddress;
127
+		}
128
+		glsr_log()->error('Unable to detect IP address.');
129
+		return 'unknown';
130
+	}
131 131
 }
Please login to merge, or discard this patch.
plugin/Defaults/ValidateReviewDefaults.php 1 patch
Indentation   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -6,22 +6,22 @@
 block discarded – undo
6 6
 
7 7
 class ValidateReviewDefaults extends Defaults
8 8
 {
9
-    /**
10
-     * @return array
11
-     */
12
-    protected function defaults()
13
-    {
14
-        return [
15
-            'assign_to' => '',
16
-            'category' => '',
17
-            'content' => '',
18
-            'email' => '',
19
-            'form_id' => '',
20
-            'ip_address' => '',
21
-            'name' => '',
22
-            'rating' => '0',
23
-            'terms' => '',
24
-            'title' => '',
25
-        ];
26
-    }
9
+	/**
10
+	 * @return array
11
+	 */
12
+	protected function defaults()
13
+	{
14
+		return [
15
+			'assign_to' => '',
16
+			'category' => '',
17
+			'content' => '',
18
+			'email' => '',
19
+			'form_id' => '',
20
+			'ip_address' => '',
21
+			'name' => '',
22
+			'rating' => '0',
23
+			'terms' => '',
24
+			'title' => '',
25
+		];
26
+	}
27 27
 }
Please login to merge, or discard this patch.
plugin/Modules/Console.php 1 patch
Indentation   +433 added lines, -433 removed lines patch added patch discarded remove patch
@@ -10,437 +10,437 @@
 block discarded – undo
10 10
 
11 11
 class Console
12 12
 {
13
-    const DEBUG = 0;      // Detailed debug information
14
-    const INFO = 1;       // Interesting events
15
-    const NOTICE = 2;     // Normal but significant events
16
-    const WARNING = 4;    // Exceptional occurrences that are not errors
17
-    const ERROR = 8;      // Runtime errors that do not require immediate action
18
-    const CRITICAL = 16;  // Critical conditions
19
-    const ALERT = 32;     // Action must be taken immediately
20
-    const EMERGENCY = 64; // System is unusable
21
-
22
-    protected $file;
23
-    protected $log;
24
-    protected $logOnceKey = 'glsr_log_once';
25
-
26
-    public function __construct()
27
-    {
28
-        $this->file = glsr()->path('console.log');
29
-        $this->log = file_exists($this->file)
30
-            ? file_get_contents($this->file)
31
-            : '';
32
-        $this->reset();
33
-    }
34
-
35
-    /**
36
-     * @return string
37
-     */
38
-    public function __toString()
39
-    {
40
-        return $this->get();
41
-    }
42
-
43
-    /**
44
-     * Action must be taken immediately
45
-     * Example: Entire website down, database unavailable, etc. This should trigger the SMS alerts and wake you up.
46
-     * @param mixed $message
47
-     * @param array $context
48
-     * @return static
49
-     */
50
-    public function alert($message, array $context = [])
51
-    {
52
-        return $this->log(static::ALERT, $message, $context);
53
-    }
54
-
55
-    /**
56
-     * @return void
57
-     */
58
-    public function clear()
59
-    {
60
-        $this->log = '';
61
-        file_put_contents($this->file, $this->log);
62
-    }
63
-
64
-    /**
65
-     * Critical conditions
66
-     * Example: Application component unavailable, unexpected exception.
67
-     * @param mixed $message
68
-     * @param array $context
69
-     * @return static
70
-     */
71
-    public function critical($message, array $context = [])
72
-    {
73
-        return $this->log(static::CRITICAL, $message, $context);
74
-    }
75
-
76
-    /**
77
-     * Detailed debug information.
78
-     * @param mixed $message
79
-     * @param array $context
80
-     * @return static
81
-     */
82
-    public function debug($message, array $context = [])
83
-    {
84
-        return $this->log(static::DEBUG, $message, $context);
85
-    }
86
-
87
-    /**
88
-     * System is unusable.
89
-     * @param mixed $message
90
-     * @param array $context
91
-     * @return static
92
-     */
93
-    public function emergency($message, array $context = [])
94
-    {
95
-        return $this->log(static::EMERGENCY, $message, $context);
96
-    }
97
-
98
-    /**
99
-     * Runtime errors that do not require immediate action but should typically be logged and monitored.
100
-     * @param mixed $message
101
-     * @param array $context
102
-     * @return static
103
-     */
104
-    public function error($message, array $context = [])
105
-    {
106
-        return $this->log(static::ERROR, $message, $context);
107
-    }
108
-
109
-    /**
110
-     * @return string
111
-     */
112
-    public function get()
113
-    {
114
-        return empty($this->log)
115
-            ? __('Console is empty', 'site-reviews')
116
-            : $this->log;
117
-    }
118
-
119
-    /**
120
-     * @return int
121
-     */
122
-    public function getLevel()
123
-    {
124
-        return intval(apply_filters('site-reviews/console/level', static::INFO));
125
-    }
126
-
127
-    /**
128
-     * @return array
129
-     */
130
-    public function getLevels()
131
-    {
132
-        $constants = (new ReflectionClass(__CLASS__))->getConstants();
133
-        return array_map('strtolower', array_flip($constants));
134
-    }
135
-
136
-    /**
137
-     * @return string
138
-     */
139
-    public function humanLevel()
140
-    {
141
-        $level = $this->getLevel();
142
-        return sprintf('%s (%d)', strtoupper(Arr::get($this->getLevels(), $level, 'unknown')), $level);
143
-    }
144
-
145
-    /**
146
-     * @param string|null $valueIfEmpty
147
-     * @return string
148
-     */
149
-    public function humanSize($valueIfEmpty = null)
150
-    {
151
-        $bytes = $this->size();
152
-        if (empty($bytes) && is_string($valueIfEmpty)) {
153
-            return $valueIfEmpty;
154
-        }
155
-        $exponent = floor(log(max($bytes, 1), 1024));
156
-        return round($bytes / pow(1024, $exponent), 2).' '.['bytes', 'KB', 'MB', 'GB'][$exponent];
157
-    }
158
-
159
-    /**
160
-     * Interesting events
161
-     * Example: User logs in, SQL logs.
162
-     * @param mixed $message
163
-     * @param array $context
164
-     * @return static
165
-     */
166
-    public function info($message, array $context = [])
167
-    {
168
-        return $this->log(static::INFO, $message, $context);
169
-    }
170
-
171
-    /**
172
-     * @param int $level
173
-     * @param mixed $message
174
-     * @param array $context
175
-     * @param string $backtraceLine
176
-     * @return static
177
-     */
178
-    public function log($level, $message, $context = [], $backtraceLine = '')
179
-    {
180
-        if (empty($backtraceLine)) {
181
-            $backtraceLine = $this->getBacktraceLine();
182
-        }
183
-        if ($this->canLogEntry($level, $backtraceLine)) {
184
-            $levelName = Arr::get($this->getLevels(), $level);
185
-            $context = Arr::consolidateArray($context);
186
-            $backtraceLine = $this->normalizeBacktraceLine($backtraceLine);
187
-            $message = $this->interpolate($message, $context);
188
-            $entry = $this->buildLogEntry($levelName, $message, $backtraceLine);
189
-            file_put_contents($this->file, $entry.PHP_EOL, FILE_APPEND | LOCK_EX);
190
-            apply_filters('console', $message, $levelName, $backtraceLine); // Show in Blackbar plugin if installed
191
-            $this->reset();
192
-        }
193
-        return $this;
194
-    }
195
-
196
-    /**
197
-     * @return void
198
-     */
199
-    public function logOnce()
200
-    {
201
-        $once = Arr::consolidateArray(glsr()->{$this->logOnceKey});
202
-        $levels = $this->getLevels();
203
-        foreach ($once as $entry) {
204
-            $levelName = Arr::get($entry, 'level');
205
-            if (!in_array($levelName, $levels)) {
206
-                continue;
207
-            }
208
-            $level = Arr::get(array_flip($levels), $levelName);
209
-            $message = Arr::get($entry, 'message');
210
-            $backtraceLine = Arr::get($entry, 'backtrace');
211
-            $this->log($level, $message, [], $backtraceLine);
212
-        }
213
-        glsr()->{$this->logOnceKey} = [];
214
-    }
215
-
216
-    /**
217
-     * Normal but significant events.
218
-     * @param mixed $message
219
-     * @param array $context
220
-     * @return static
221
-     */
222
-    public function notice($message, array $context = [])
223
-    {
224
-        return $this->log(static::NOTICE, $message, $context);
225
-    }
226
-
227
-    /**
228
-     * @param string $levelName
229
-     * @param string $handle
230
-     * @param mixed $data
231
-     * @return void
232
-     */
233
-    public function once($levelName, $handle, $data)
234
-    {
235
-        $once = Arr::consolidateArray(glsr()->{$this->logOnceKey});
236
-        $filtered = array_filter($once, function ($entry) use ($levelName, $handle) {
237
-            return Arr::get($entry, 'level') == $levelName
238
-                && Arr::get($entry, 'handle') == $handle;
239
-        });
240
-        if (!empty($filtered)) {
241
-            return;
242
-        }
243
-        $once[] = [
244
-            'backtrace' => $this->getBacktraceLineFromData($data),
245
-            'handle' => $handle,
246
-            'level' => $levelName,
247
-            'message' => '[RECURRING] '.$this->getMessageFromData($data),
248
-        ];
249
-        glsr()->{$this->logOnceKey} = $once;
250
-    }
251
-
252
-    /**
253
-     * @return int
254
-     */
255
-    public function size()
256
-    {
257
-        return file_exists($this->file)
258
-            ? filesize($this->file)
259
-            : 0;
260
-    }
261
-
262
-    /**
263
-     * Exceptional occurrences that are not errors
264
-     * Example: Use of deprecated APIs, poor use of an API, undesirable things that are not necessarily wrong.
265
-     * @param mixed $message
266
-     * @param array $context
267
-     * @return static
268
-     */
269
-    public function warning($message, array $context = [])
270
-    {
271
-        return $this->log(static::WARNING, $message, $context);
272
-    }
273
-
274
-    /**
275
-     * @param array $backtrace
276
-     * @param int $index
277
-     * @return string
278
-     */
279
-    protected function buildBacktraceLine($backtrace, $index)
280
-    {
281
-        return sprintf('%s:%s',
282
-            Arr::get($backtrace, $index.'.file'), // realpath
283
-            Arr::get($backtrace, $index.'.line')
284
-        );
285
-    }
286
-
287
-    /**
288
-     * @param string $levelName
289
-     * @param mixed $message
290
-     * @param string $backtraceLine
291
-     * @return string
292
-     */
293
-    protected function buildLogEntry($levelName, $message, $backtraceLine = '')
294
-    {
295
-        return sprintf('[%s] %s [%s] %s',
296
-            current_time('mysql'),
297
-            strtoupper($levelName),
298
-            $backtraceLine,
299
-            $message
300
-        );
301
-    }
302
-
303
-    /**
304
-     * @param int $level
305
-     * @return bool
306
-     */
307
-    protected function canLogEntry($level, $backtraceLine)
308
-    {
309
-        $levelExists = array_key_exists($level, $this->getLevels());
310
-        if (!Str::contains($backtraceLine, glsr()->path())) {
311
-            return $levelExists; // ignore level restriction if triggered outside of the plugin
312
-        }
313
-        return $levelExists && $level >= $this->getLevel();
314
-    }
315
-
316
-    /**
317
-     * @return void|string
318
-     */
319
-    protected function getBacktraceLine()
320
-    {
321
-        $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 6);
322
-        $search = array_search('glsr_log', glsr_array_column($backtrace, 'function'));
323
-        if (false !== $search) {
324
-            return $this->buildBacktraceLine($backtrace, (int) $search);
325
-        }
326
-        $search = array_search('log', glsr_array_column($backtrace, 'function'));
327
-        if (false !== $search) {
328
-            $index = '{closure}' == Arr::get($backtrace, ($search + 2).'.function')
329
-                ? $search + 4
330
-                : $search + 1;
331
-            return $this->buildBacktraceLine($backtrace, $index);
332
-        }
333
-        return 'Unknown';
334
-    }
335
-
336
-    /**
337
-     * @param mixed $data
338
-     * @return string
339
-     */
340
-    protected function getBacktraceLineFromData($data)
341
-    {
342
-        $backtrace = $data instanceof Throwable
343
-            ? $data->getTrace()
344
-            : debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
345
-        return $this->buildBacktraceLine($backtrace, 0);
346
-    }
347
-
348
-    /**
349
-     * @param mixed $data
350
-     * @return string
351
-     */
352
-    protected function getMessageFromData($data)
353
-    {
354
-        return $data instanceof Throwable
355
-            ? $this->normalizeThrowableMessage($data->getMessage())
356
-            : print_r($data, 1);
357
-    }
358
-
359
-    /**
360
-     * Interpolates context values into the message placeholders.
361
-     * @param mixed $message
362
-     * @param array $context
363
-     * @return string
364
-     */
365
-    protected function interpolate($message, $context = [])
366
-    {
367
-        if ($this->isObjectOrArray($message) || !is_array($context)) {
368
-            return print_r($message, true);
369
-        }
370
-        $replace = [];
371
-        foreach ($context as $key => $value) {
372
-            $replace['{'.$key.'}'] = $this->normalizeValue($value);
373
-        }
374
-        return strtr($message, $replace);
375
-    }
376
-
377
-    /**
378
-     * @param mixed $value
379
-     * @return bool
380
-     */
381
-    protected function isObjectOrArray($value)
382
-    {
383
-        return is_object($value) || is_array($value);
384
-    }
385
-
386
-    /**
387
-     * @param string $backtraceLine
388
-     * @return string
389
-     */
390
-    protected function normalizeBacktraceLine($backtraceLine)
391
-    {
392
-        $search = [
393
-            glsr()->path('plugin/'),
394
-            glsr()->path('plugin/', false),
395
-            trailingslashit(glsr()->path()),
396
-            trailingslashit(glsr()->path('', false)),
397
-            WP_CONTENT_DIR,
398
-            ABSPATH,
399
-        ];
400
-        return str_replace(array_unique($search), '', $backtraceLine);
401
-    }
402
-
403
-    /**
404
-     * @param string $message
405
-     * @return string
406
-     */
407
-    protected function normalizeThrowableMessage($message)
408
-    {
409
-        $calledIn = strpos($message, ', called in');
410
-        return false !== $calledIn
411
-            ? substr($message, 0, $calledIn)
412
-            : $message;
413
-    }
414
-
415
-    /**
416
-     * @param mixed $value
417
-     * @return string
418
-     */
419
-    protected function normalizeValue($value)
420
-    {
421
-        if ($value instanceof DateTime) {
422
-            $value = $value->format('Y-m-d H:i:s');
423
-        } elseif ($this->isObjectOrArray($value)) {
424
-            $value = json_encode($value);
425
-        }
426
-        return (string) $value;
427
-    }
428
-
429
-    /**
430
-     * @return void
431
-     */
432
-    protected function reset()
433
-    {
434
-        if ($this->size() <= pow(1024, 2) / 8) {
435
-            return;
436
-        }
437
-        $this->clear();
438
-        file_put_contents(
439
-            $this->file,
440
-            $this->buildLogEntry(
441
-                static::NOTICE,
442
-                __('Console was automatically cleared (128 KB maximum size)', 'site-reviews')
443
-            )
444
-        );
445
-    }
13
+	const DEBUG = 0;      // Detailed debug information
14
+	const INFO = 1;       // Interesting events
15
+	const NOTICE = 2;     // Normal but significant events
16
+	const WARNING = 4;    // Exceptional occurrences that are not errors
17
+	const ERROR = 8;      // Runtime errors that do not require immediate action
18
+	const CRITICAL = 16;  // Critical conditions
19
+	const ALERT = 32;     // Action must be taken immediately
20
+	const EMERGENCY = 64; // System is unusable
21
+
22
+	protected $file;
23
+	protected $log;
24
+	protected $logOnceKey = 'glsr_log_once';
25
+
26
+	public function __construct()
27
+	{
28
+		$this->file = glsr()->path('console.log');
29
+		$this->log = file_exists($this->file)
30
+			? file_get_contents($this->file)
31
+			: '';
32
+		$this->reset();
33
+	}
34
+
35
+	/**
36
+	 * @return string
37
+	 */
38
+	public function __toString()
39
+	{
40
+		return $this->get();
41
+	}
42
+
43
+	/**
44
+	 * Action must be taken immediately
45
+	 * Example: Entire website down, database unavailable, etc. This should trigger the SMS alerts and wake you up.
46
+	 * @param mixed $message
47
+	 * @param array $context
48
+	 * @return static
49
+	 */
50
+	public function alert($message, array $context = [])
51
+	{
52
+		return $this->log(static::ALERT, $message, $context);
53
+	}
54
+
55
+	/**
56
+	 * @return void
57
+	 */
58
+	public function clear()
59
+	{
60
+		$this->log = '';
61
+		file_put_contents($this->file, $this->log);
62
+	}
63
+
64
+	/**
65
+	 * Critical conditions
66
+	 * Example: Application component unavailable, unexpected exception.
67
+	 * @param mixed $message
68
+	 * @param array $context
69
+	 * @return static
70
+	 */
71
+	public function critical($message, array $context = [])
72
+	{
73
+		return $this->log(static::CRITICAL, $message, $context);
74
+	}
75
+
76
+	/**
77
+	 * Detailed debug information.
78
+	 * @param mixed $message
79
+	 * @param array $context
80
+	 * @return static
81
+	 */
82
+	public function debug($message, array $context = [])
83
+	{
84
+		return $this->log(static::DEBUG, $message, $context);
85
+	}
86
+
87
+	/**
88
+	 * System is unusable.
89
+	 * @param mixed $message
90
+	 * @param array $context
91
+	 * @return static
92
+	 */
93
+	public function emergency($message, array $context = [])
94
+	{
95
+		return $this->log(static::EMERGENCY, $message, $context);
96
+	}
97
+
98
+	/**
99
+	 * Runtime errors that do not require immediate action but should typically be logged and monitored.
100
+	 * @param mixed $message
101
+	 * @param array $context
102
+	 * @return static
103
+	 */
104
+	public function error($message, array $context = [])
105
+	{
106
+		return $this->log(static::ERROR, $message, $context);
107
+	}
108
+
109
+	/**
110
+	 * @return string
111
+	 */
112
+	public function get()
113
+	{
114
+		return empty($this->log)
115
+			? __('Console is empty', 'site-reviews')
116
+			: $this->log;
117
+	}
118
+
119
+	/**
120
+	 * @return int
121
+	 */
122
+	public function getLevel()
123
+	{
124
+		return intval(apply_filters('site-reviews/console/level', static::INFO));
125
+	}
126
+
127
+	/**
128
+	 * @return array
129
+	 */
130
+	public function getLevels()
131
+	{
132
+		$constants = (new ReflectionClass(__CLASS__))->getConstants();
133
+		return array_map('strtolower', array_flip($constants));
134
+	}
135
+
136
+	/**
137
+	 * @return string
138
+	 */
139
+	public function humanLevel()
140
+	{
141
+		$level = $this->getLevel();
142
+		return sprintf('%s (%d)', strtoupper(Arr::get($this->getLevels(), $level, 'unknown')), $level);
143
+	}
144
+
145
+	/**
146
+	 * @param string|null $valueIfEmpty
147
+	 * @return string
148
+	 */
149
+	public function humanSize($valueIfEmpty = null)
150
+	{
151
+		$bytes = $this->size();
152
+		if (empty($bytes) && is_string($valueIfEmpty)) {
153
+			return $valueIfEmpty;
154
+		}
155
+		$exponent = floor(log(max($bytes, 1), 1024));
156
+		return round($bytes / pow(1024, $exponent), 2).' '.['bytes', 'KB', 'MB', 'GB'][$exponent];
157
+	}
158
+
159
+	/**
160
+	 * Interesting events
161
+	 * Example: User logs in, SQL logs.
162
+	 * @param mixed $message
163
+	 * @param array $context
164
+	 * @return static
165
+	 */
166
+	public function info($message, array $context = [])
167
+	{
168
+		return $this->log(static::INFO, $message, $context);
169
+	}
170
+
171
+	/**
172
+	 * @param int $level
173
+	 * @param mixed $message
174
+	 * @param array $context
175
+	 * @param string $backtraceLine
176
+	 * @return static
177
+	 */
178
+	public function log($level, $message, $context = [], $backtraceLine = '')
179
+	{
180
+		if (empty($backtraceLine)) {
181
+			$backtraceLine = $this->getBacktraceLine();
182
+		}
183
+		if ($this->canLogEntry($level, $backtraceLine)) {
184
+			$levelName = Arr::get($this->getLevels(), $level);
185
+			$context = Arr::consolidateArray($context);
186
+			$backtraceLine = $this->normalizeBacktraceLine($backtraceLine);
187
+			$message = $this->interpolate($message, $context);
188
+			$entry = $this->buildLogEntry($levelName, $message, $backtraceLine);
189
+			file_put_contents($this->file, $entry.PHP_EOL, FILE_APPEND | LOCK_EX);
190
+			apply_filters('console', $message, $levelName, $backtraceLine); // Show in Blackbar plugin if installed
191
+			$this->reset();
192
+		}
193
+		return $this;
194
+	}
195
+
196
+	/**
197
+	 * @return void
198
+	 */
199
+	public function logOnce()
200
+	{
201
+		$once = Arr::consolidateArray(glsr()->{$this->logOnceKey});
202
+		$levels = $this->getLevels();
203
+		foreach ($once as $entry) {
204
+			$levelName = Arr::get($entry, 'level');
205
+			if (!in_array($levelName, $levels)) {
206
+				continue;
207
+			}
208
+			$level = Arr::get(array_flip($levels), $levelName);
209
+			$message = Arr::get($entry, 'message');
210
+			$backtraceLine = Arr::get($entry, 'backtrace');
211
+			$this->log($level, $message, [], $backtraceLine);
212
+		}
213
+		glsr()->{$this->logOnceKey} = [];
214
+	}
215
+
216
+	/**
217
+	 * Normal but significant events.
218
+	 * @param mixed $message
219
+	 * @param array $context
220
+	 * @return static
221
+	 */
222
+	public function notice($message, array $context = [])
223
+	{
224
+		return $this->log(static::NOTICE, $message, $context);
225
+	}
226
+
227
+	/**
228
+	 * @param string $levelName
229
+	 * @param string $handle
230
+	 * @param mixed $data
231
+	 * @return void
232
+	 */
233
+	public function once($levelName, $handle, $data)
234
+	{
235
+		$once = Arr::consolidateArray(glsr()->{$this->logOnceKey});
236
+		$filtered = array_filter($once, function ($entry) use ($levelName, $handle) {
237
+			return Arr::get($entry, 'level') == $levelName
238
+				&& Arr::get($entry, 'handle') == $handle;
239
+		});
240
+		if (!empty($filtered)) {
241
+			return;
242
+		}
243
+		$once[] = [
244
+			'backtrace' => $this->getBacktraceLineFromData($data),
245
+			'handle' => $handle,
246
+			'level' => $levelName,
247
+			'message' => '[RECURRING] '.$this->getMessageFromData($data),
248
+		];
249
+		glsr()->{$this->logOnceKey} = $once;
250
+	}
251
+
252
+	/**
253
+	 * @return int
254
+	 */
255
+	public function size()
256
+	{
257
+		return file_exists($this->file)
258
+			? filesize($this->file)
259
+			: 0;
260
+	}
261
+
262
+	/**
263
+	 * Exceptional occurrences that are not errors
264
+	 * Example: Use of deprecated APIs, poor use of an API, undesirable things that are not necessarily wrong.
265
+	 * @param mixed $message
266
+	 * @param array $context
267
+	 * @return static
268
+	 */
269
+	public function warning($message, array $context = [])
270
+	{
271
+		return $this->log(static::WARNING, $message, $context);
272
+	}
273
+
274
+	/**
275
+	 * @param array $backtrace
276
+	 * @param int $index
277
+	 * @return string
278
+	 */
279
+	protected function buildBacktraceLine($backtrace, $index)
280
+	{
281
+		return sprintf('%s:%s',
282
+			Arr::get($backtrace, $index.'.file'), // realpath
283
+			Arr::get($backtrace, $index.'.line')
284
+		);
285
+	}
286
+
287
+	/**
288
+	 * @param string $levelName
289
+	 * @param mixed $message
290
+	 * @param string $backtraceLine
291
+	 * @return string
292
+	 */
293
+	protected function buildLogEntry($levelName, $message, $backtraceLine = '')
294
+	{
295
+		return sprintf('[%s] %s [%s] %s',
296
+			current_time('mysql'),
297
+			strtoupper($levelName),
298
+			$backtraceLine,
299
+			$message
300
+		);
301
+	}
302
+
303
+	/**
304
+	 * @param int $level
305
+	 * @return bool
306
+	 */
307
+	protected function canLogEntry($level, $backtraceLine)
308
+	{
309
+		$levelExists = array_key_exists($level, $this->getLevels());
310
+		if (!Str::contains($backtraceLine, glsr()->path())) {
311
+			return $levelExists; // ignore level restriction if triggered outside of the plugin
312
+		}
313
+		return $levelExists && $level >= $this->getLevel();
314
+	}
315
+
316
+	/**
317
+	 * @return void|string
318
+	 */
319
+	protected function getBacktraceLine()
320
+	{
321
+		$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 6);
322
+		$search = array_search('glsr_log', glsr_array_column($backtrace, 'function'));
323
+		if (false !== $search) {
324
+			return $this->buildBacktraceLine($backtrace, (int) $search);
325
+		}
326
+		$search = array_search('log', glsr_array_column($backtrace, 'function'));
327
+		if (false !== $search) {
328
+			$index = '{closure}' == Arr::get($backtrace, ($search + 2).'.function')
329
+				? $search + 4
330
+				: $search + 1;
331
+			return $this->buildBacktraceLine($backtrace, $index);
332
+		}
333
+		return 'Unknown';
334
+	}
335
+
336
+	/**
337
+	 * @param mixed $data
338
+	 * @return string
339
+	 */
340
+	protected function getBacktraceLineFromData($data)
341
+	{
342
+		$backtrace = $data instanceof Throwable
343
+			? $data->getTrace()
344
+			: debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
345
+		return $this->buildBacktraceLine($backtrace, 0);
346
+	}
347
+
348
+	/**
349
+	 * @param mixed $data
350
+	 * @return string
351
+	 */
352
+	protected function getMessageFromData($data)
353
+	{
354
+		return $data instanceof Throwable
355
+			? $this->normalizeThrowableMessage($data->getMessage())
356
+			: print_r($data, 1);
357
+	}
358
+
359
+	/**
360
+	 * Interpolates context values into the message placeholders.
361
+	 * @param mixed $message
362
+	 * @param array $context
363
+	 * @return string
364
+	 */
365
+	protected function interpolate($message, $context = [])
366
+	{
367
+		if ($this->isObjectOrArray($message) || !is_array($context)) {
368
+			return print_r($message, true);
369
+		}
370
+		$replace = [];
371
+		foreach ($context as $key => $value) {
372
+			$replace['{'.$key.'}'] = $this->normalizeValue($value);
373
+		}
374
+		return strtr($message, $replace);
375
+	}
376
+
377
+	/**
378
+	 * @param mixed $value
379
+	 * @return bool
380
+	 */
381
+	protected function isObjectOrArray($value)
382
+	{
383
+		return is_object($value) || is_array($value);
384
+	}
385
+
386
+	/**
387
+	 * @param string $backtraceLine
388
+	 * @return string
389
+	 */
390
+	protected function normalizeBacktraceLine($backtraceLine)
391
+	{
392
+		$search = [
393
+			glsr()->path('plugin/'),
394
+			glsr()->path('plugin/', false),
395
+			trailingslashit(glsr()->path()),
396
+			trailingslashit(glsr()->path('', false)),
397
+			WP_CONTENT_DIR,
398
+			ABSPATH,
399
+		];
400
+		return str_replace(array_unique($search), '', $backtraceLine);
401
+	}
402
+
403
+	/**
404
+	 * @param string $message
405
+	 * @return string
406
+	 */
407
+	protected function normalizeThrowableMessage($message)
408
+	{
409
+		$calledIn = strpos($message, ', called in');
410
+		return false !== $calledIn
411
+			? substr($message, 0, $calledIn)
412
+			: $message;
413
+	}
414
+
415
+	/**
416
+	 * @param mixed $value
417
+	 * @return string
418
+	 */
419
+	protected function normalizeValue($value)
420
+	{
421
+		if ($value instanceof DateTime) {
422
+			$value = $value->format('Y-m-d H:i:s');
423
+		} elseif ($this->isObjectOrArray($value)) {
424
+			$value = json_encode($value);
425
+		}
426
+		return (string) $value;
427
+	}
428
+
429
+	/**
430
+	 * @return void
431
+	 */
432
+	protected function reset()
433
+	{
434
+		if ($this->size() <= pow(1024, 2) / 8) {
435
+			return;
436
+		}
437
+		$this->clear();
438
+		file_put_contents(
439
+			$this->file,
440
+			$this->buildLogEntry(
441
+				static::NOTICE,
442
+				__('Console was automatically cleared (128 KB maximum size)', 'site-reviews')
443
+			)
444
+		);
445
+	}
446 446
 }
Please login to merge, or discard this patch.