Passed
Push — dependabot/composer/php8/forta... ( 9a9f56...0ecb64 )
by
unknown
17:53 queued 14:02
created
includes/Pages/PageWelcomeTemplateManagement.php 2 patches
Indentation   +191 added lines, -191 removed lines patch added patch discarded remove patch
@@ -22,258 +22,258 @@
 block discarded – undo
22 22
 
23 23
 class PageWelcomeTemplateManagement extends InternalPageBase
24 24
 {
25
-    /**
26
-     * Main function for this page, when no specific actions are called.
27
-     * @return void
28
-     */
29
-    protected function main()
30
-    {
31
-        $database = $this->getDatabase();
32
-        $templateList = WelcomeTemplate::getAll($database, 1); // FIXME: domains
33
-        $preferenceManager = PreferenceManager::getForCurrent($database);
25
+	/**
26
+	 * Main function for this page, when no specific actions are called.
27
+	 * @return void
28
+	 */
29
+	protected function main()
30
+	{
31
+		$database = $this->getDatabase();
32
+		$templateList = WelcomeTemplate::getAll($database, 1); // FIXME: domains
33
+		$preferenceManager = PreferenceManager::getForCurrent($database);
34 34
 
35
-        $this->setHtmlTitle('Welcome Templates');
35
+		$this->setHtmlTitle('Welcome Templates');
36 36
 
37
-        $this->assignCSRFToken();
37
+		$this->assignCSRFToken();
38 38
 
39
-        $user = User::getCurrent($database);
39
+		$user = User::getCurrent($database);
40 40
 
41
-        $currentTemplate = $preferenceManager->getPreference(PreferenceManager::PREF_WELCOMETEMPLATE);
42
-        $this->assign('currentTemplate', $currentTemplate);
41
+		$currentTemplate = $preferenceManager->getPreference(PreferenceManager::PREF_WELCOMETEMPLATE);
42
+		$this->assign('currentTemplate', $currentTemplate);
43 43
 
44
-        $this->assign('canEdit', $this->barrierTest('edit', $user));
45
-        $this->assign('canAdd', $this->barrierTest('add', $user));
46
-        $this->assign('canSelect', $this->barrierTest('select', $user));
44
+		$this->assign('canEdit', $this->barrierTest('edit', $user));
45
+		$this->assign('canAdd', $this->barrierTest('add', $user));
46
+		$this->assign('canSelect', $this->barrierTest('select', $user));
47 47
 
48
-        $this->assign('templateList', $templateList);
49
-        $this->setTemplate('welcome-template/list.tpl');
50
-    }
48
+		$this->assign('templateList', $templateList);
49
+		$this->setTemplate('welcome-template/list.tpl');
50
+	}
51 51
 
52
-    /**
53
-     * Handles the requests for selecting a template to use.
54
-     *
55
-     * @throws ApplicationLogicException
56
-     */
57
-    protected function select()
58
-    {
59
-        // get rid of GETs
60
-        if (!WebRequest::wasPosted()) {
61
-            $this->redirect('welcomeTemplates');
62
-        }
52
+	/**
53
+	 * Handles the requests for selecting a template to use.
54
+	 *
55
+	 * @throws ApplicationLogicException
56
+	 */
57
+	protected function select()
58
+	{
59
+		// get rid of GETs
60
+		if (!WebRequest::wasPosted()) {
61
+			$this->redirect('welcomeTemplates');
62
+		}
63 63
 
64
-        $this->validateCSRFToken();
64
+		$this->validateCSRFToken();
65 65
 
66
-        $database = $this->getDatabase();
67
-        $user = User::getCurrent($database);
68
-        $preferenceManager = PreferenceManager::getForCurrent($database);
66
+		$database = $this->getDatabase();
67
+		$user = User::getCurrent($database);
68
+		$preferenceManager = PreferenceManager::getForCurrent($database);
69 69
 
70
-        if (WebRequest::postBoolean('disable')) {
71
-            $preferenceManager->setLocalPreference(PreferenceManager::PREF_WELCOMETEMPLATE, null);
70
+		if (WebRequest::postBoolean('disable')) {
71
+			$preferenceManager->setLocalPreference(PreferenceManager::PREF_WELCOMETEMPLATE, null);
72 72
 
73
-            SessionAlert::success('Disabled automatic user welcoming.');
74
-            $this->redirect('welcomeTemplates');
73
+			SessionAlert::success('Disabled automatic user welcoming.');
74
+			$this->redirect('welcomeTemplates');
75 75
 
76
-            return;
77
-        }
76
+			return;
77
+		}
78 78
 
79
-        $templateId = WebRequest::postInt('template');
80
-        /** @var false|WelcomeTemplate $template */
81
-        $template = WelcomeTemplate::getById($templateId, $database);
79
+		$templateId = WebRequest::postInt('template');
80
+		/** @var false|WelcomeTemplate $template */
81
+		$template = WelcomeTemplate::getById($templateId, $database);
82 82
 
83
-        if ($template === false || $template->isDeleted()) {
84
-            throw new ApplicationLogicException('Unknown template');
85
-        }
83
+		if ($template === false || $template->isDeleted()) {
84
+			throw new ApplicationLogicException('Unknown template');
85
+		}
86 86
 
87
-        $preferenceManager->setLocalPreference(PreferenceManager::PREF_WELCOMETEMPLATE, $template->getId());
87
+		$preferenceManager->setLocalPreference(PreferenceManager::PREF_WELCOMETEMPLATE, $template->getId());
88 88
 
89
-        SessionAlert::success("Updated selected welcome template for automatic welcoming.");
89
+		SessionAlert::success("Updated selected welcome template for automatic welcoming.");
90 90
 
91
-        $this->redirect('welcomeTemplates');
92
-    }
91
+		$this->redirect('welcomeTemplates');
92
+	}
93 93
 
94
-    /**
95
-     * Handles the requests for viewing a template.
96
-     *
97
-     * @throws ApplicationLogicException
98
-     */
99
-    protected function view()
100
-    {
101
-        $this->setHtmlTitle('View Welcome Template');
94
+	/**
95
+	 * Handles the requests for viewing a template.
96
+	 *
97
+	 * @throws ApplicationLogicException
98
+	 */
99
+	protected function view()
100
+	{
101
+		$this->setHtmlTitle('View Welcome Template');
102 102
 
103
-        $database = $this->getDatabase();
103
+		$database = $this->getDatabase();
104 104
 
105
-        $templateId = WebRequest::getInt('template');
105
+		$templateId = WebRequest::getInt('template');
106 106
 
107
-        /** @var false|WelcomeTemplate $template */
108
-        $template = WelcomeTemplate::getById($templateId, $database);
107
+		/** @var false|WelcomeTemplate $template */
108
+		$template = WelcomeTemplate::getById($templateId, $database);
109 109
 
110
-        if ($template === false) {
111
-            throw new ApplicationLogicException('Cannot find requested template');
112
-        }
110
+		if ($template === false) {
111
+			throw new ApplicationLogicException('Cannot find requested template');
112
+		}
113 113
 
114
-        $currentUser = User::getCurrent($database);
114
+		$currentUser = User::getCurrent($database);
115 115
 
116
-        // This includes a section header, because we use the "new section" API call.
117
-        $wikiText = "== " . $template->getSectionHeader() . "==\n" . $template->getBotCodeForWikiSave('Example User', $currentUser->getOnWikiName());
116
+		// This includes a section header, because we use the "new section" API call.
117
+		$wikiText = "== " . $template->getSectionHeader() . "==\n" . $template->getBotCodeForWikiSave('Example User', $currentUser->getOnWikiName());
118 118
 
119
-        $oauth = new OAuthUserHelper($currentUser, $database, $this->getOauthProtocolHelper(),
120
-            $this->getSiteConfiguration());
121
-        $mediaWikiHelper = new MediaWikiHelper($oauth, $this->getSiteConfiguration());
119
+		$oauth = new OAuthUserHelper($currentUser, $database, $this->getOauthProtocolHelper(),
120
+			$this->getSiteConfiguration());
121
+		$mediaWikiHelper = new MediaWikiHelper($oauth, $this->getSiteConfiguration());
122 122
 
123
-        $templateHtml = $mediaWikiHelper->getHtmlForWikiText($wikiText);
123
+		$templateHtml = $mediaWikiHelper->getHtmlForWikiText($wikiText);
124 124
         
125
-        // Add site to relevant links, since the MediaWiki parser returns, eg, `/wiki/Help:Introduction`
126
-        // and we want to link to <https://en.wikipedia.org/wiki/Help:Introduction> rather than
127
-        // <https://accounts.wmflabs.org/wiki/Help:Introduction>
128
-        // The code currently assumes that the template was parsed for enwiki, and will need to be
129
-        // updated once other wikis are supported.
130
-        $templateHtml = preg_replace('/(<a href=")(\/wiki\/)/', '$1//en.wikipedia.org$2', $templateHtml);
131
-
132
-        $this->assign('templateHtml', $templateHtml);
133
-        $this->assign('template', $template);
134
-        $this->setTemplate('welcome-template/view.tpl');
135
-    }
136
-
137
-    /**
138
-     * Handler for the add action to create a new welcome template
139
-     *
140
-     * @throws Exception
141
-     */
142
-    protected function add()
143
-    {
144
-        $this->assign('createmode', true);
125
+		// Add site to relevant links, since the MediaWiki parser returns, eg, `/wiki/Help:Introduction`
126
+		// and we want to link to <https://en.wikipedia.org/wiki/Help:Introduction> rather than
127
+		// <https://accounts.wmflabs.org/wiki/Help:Introduction>
128
+		// The code currently assumes that the template was parsed for enwiki, and will need to be
129
+		// updated once other wikis are supported.
130
+		$templateHtml = preg_replace('/(<a href=")(\/wiki\/)/', '$1//en.wikipedia.org$2', $templateHtml);
131
+
132
+		$this->assign('templateHtml', $templateHtml);
133
+		$this->assign('template', $template);
134
+		$this->setTemplate('welcome-template/view.tpl');
135
+	}
136
+
137
+	/**
138
+	 * Handler for the add action to create a new welcome template
139
+	 *
140
+	 * @throws Exception
141
+	 */
142
+	protected function add()
143
+	{
144
+		$this->assign('createmode', true);
145 145
 
146
-        if (WebRequest::wasPosted()) {
147
-            $this->validateCSRFToken();
148
-            $database = $this->getDatabase();
146
+		if (WebRequest::wasPosted()) {
147
+			$this->validateCSRFToken();
148
+			$database = $this->getDatabase();
149 149
 
150
-            $userCode = WebRequest::postString('usercode');
151
-            $botCode = WebRequest::postString('botcode');
150
+			$userCode = WebRequest::postString('usercode');
151
+			$botCode = WebRequest::postString('botcode');
152 152
 
153
-            $this->validate($userCode, $botCode);
153
+			$this->validate($userCode, $botCode);
154 154
 
155
-            $template = new WelcomeTemplate();
156
-            $template->setDatabase($database);
157
-            $template->setUserCode($userCode);
158
-            $template->setBotCode($botCode);
159
-            $template->setDomain(1); // FIXME: domains!
160
-            $template->save();
155
+			$template = new WelcomeTemplate();
156
+			$template->setDatabase($database);
157
+			$template->setUserCode($userCode);
158
+			$template->setBotCode($botCode);
159
+			$template->setDomain(1); // FIXME: domains!
160
+			$template->save();
161 161
 
162
-            Logger::welcomeTemplateCreated($database, $template);
162
+			Logger::welcomeTemplateCreated($database, $template);
163 163
 
164
-            $this->getNotificationHelper()->welcomeTemplateCreated($template);
164
+			$this->getNotificationHelper()->welcomeTemplateCreated($template);
165 165
 
166
-            SessionAlert::success("Template successfully created.");
166
+			SessionAlert::success("Template successfully created.");
167 167
 
168
-            $this->redirect('welcomeTemplates');
169
-        }
170
-        else {
171
-            $this->assignCSRFToken();
172
-            $this->assign('template', new WelcomeTemplate());
173
-            $this->setTemplate("welcome-template/edit.tpl");
174
-        }
175
-    }
168
+			$this->redirect('welcomeTemplates');
169
+		}
170
+		else {
171
+			$this->assignCSRFToken();
172
+			$this->assign('template', new WelcomeTemplate());
173
+			$this->setTemplate("welcome-template/edit.tpl");
174
+		}
175
+	}
176 176
 
177
-    /**
178
-     * Handler for editing templates
179
-     */
180
-    protected function edit()
181
-    {
182
-        $database = $this->getDatabase();
177
+	/**
178
+	 * Handler for editing templates
179
+	 */
180
+	protected function edit()
181
+	{
182
+		$database = $this->getDatabase();
183 183
 
184
-        $templateId = WebRequest::getInt('template');
184
+		$templateId = WebRequest::getInt('template');
185 185
 
186
-        /** @var false|WelcomeTemplate $template */
187
-        $template = WelcomeTemplate::getById($templateId, $database);
186
+		/** @var false|WelcomeTemplate $template */
187
+		$template = WelcomeTemplate::getById($templateId, $database);
188 188
 
189
-        if ($template === false) {
190
-            throw new ApplicationLogicException('Cannot find requested template');
191
-        }
189
+		if ($template === false) {
190
+			throw new ApplicationLogicException('Cannot find requested template');
191
+		}
192 192
 
193
-        if ($template->isDeleted()) {
194
-            throw new ApplicationLogicException('The specified template has been deleted');
195
-        }
193
+		if ($template->isDeleted()) {
194
+			throw new ApplicationLogicException('The specified template has been deleted');
195
+		}
196 196
 
197
-        $this->assign('createmode', false);
197
+		$this->assign('createmode', false);
198 198
 
199
-        if (WebRequest::wasPosted()) {
200
-            $this->validateCSRFToken();
199
+		if (WebRequest::wasPosted()) {
200
+			$this->validateCSRFToken();
201 201
 
202
-            $userCode = WebRequest::postString('usercode');
203
-            $botCode = WebRequest::postString('botcode');
202
+			$userCode = WebRequest::postString('usercode');
203
+			$botCode = WebRequest::postString('botcode');
204 204
 
205
-            $this->validate($userCode, $botCode);
205
+			$this->validate($userCode, $botCode);
206 206
 
207
-            $template->setUserCode($userCode);
208
-            $template->setBotCode($botCode);
209
-            $template->setUpdateVersion(WebRequest::postInt('updateversion'));
210
-            $template->save();
207
+			$template->setUserCode($userCode);
208
+			$template->setBotCode($botCode);
209
+			$template->setUpdateVersion(WebRequest::postInt('updateversion'));
210
+			$template->save();
211 211
 
212
-            Logger::welcomeTemplateEdited($database, $template);
212
+			Logger::welcomeTemplateEdited($database, $template);
213 213
 
214
-            SessionAlert::success("Template updated.");
214
+			SessionAlert::success("Template updated.");
215 215
 
216
-            $this->getNotificationHelper()->welcomeTemplateEdited($template);
216
+			$this->getNotificationHelper()->welcomeTemplateEdited($template);
217 217
 
218
-            $this->redirect('welcomeTemplates');
219
-        }
220
-        else {
221
-            $this->assignCSRFToken();
222
-            $this->assign('template', $template);
223
-            $this->setTemplate('welcome-template/edit.tpl');
224
-        }
225
-    }
218
+			$this->redirect('welcomeTemplates');
219
+		}
220
+		else {
221
+			$this->assignCSRFToken();
222
+			$this->assign('template', $template);
223
+			$this->setTemplate('welcome-template/edit.tpl');
224
+		}
225
+	}
226 226
 
227
-    protected function delete()
228
-    {
229
-        if (!WebRequest::wasPosted()) {
230
-            $this->redirect('welcomeTemplates');
231
-            return;
232
-        }
227
+	protected function delete()
228
+	{
229
+		if (!WebRequest::wasPosted()) {
230
+			$this->redirect('welcomeTemplates');
231
+			return;
232
+		}
233 233
 
234
-        $this->validateCSRFToken();
234
+		$this->validateCSRFToken();
235 235
 
236
-        $database = $this->getDatabase();
236
+		$database = $this->getDatabase();
237 237
 
238
-        $templateId = WebRequest::postInt('template');
239
-        $updateVersion = WebRequest::postInt('updateversion');
238
+		$templateId = WebRequest::postInt('template');
239
+		$updateVersion = WebRequest::postInt('updateversion');
240 240
 
241
-        /** @var false|WelcomeTemplate $template */
242
-        $template = WelcomeTemplate::getById($templateId, $database);
241
+		/** @var false|WelcomeTemplate $template */
242
+		$template = WelcomeTemplate::getById($templateId, $database);
243 243
 
244
-        if ($template === false || $template->isDeleted()) {
245
-            throw new ApplicationLogicException('Cannot find requested template');
246
-        }
244
+		if ($template === false || $template->isDeleted()) {
245
+			throw new ApplicationLogicException('Cannot find requested template');
246
+		}
247 247
 
248
-        // set the update version to the version sent by the client (optimisticly lock from initial page load)
249
-        $template->setUpdateVersion($updateVersion);
248
+		// set the update version to the version sent by the client (optimisticly lock from initial page load)
249
+		$template->setUpdateVersion($updateVersion);
250 250
 
251
-        $database
252
-            ->prepare("UPDATE userpreference SET value = NULL, updateversion = updateversion + 1 WHERE preference = :pref and value = :id;")
253
-            ->execute([
254
-                ':id'   => $templateId,
255
-                ':pref' => PreferenceManager::PREF_WELCOMETEMPLATE
256
-            ]);
251
+		$database
252
+			->prepare("UPDATE userpreference SET value = NULL, updateversion = updateversion + 1 WHERE preference = :pref and value = :id;")
253
+			->execute([
254
+				':id'   => $templateId,
255
+				':pref' => PreferenceManager::PREF_WELCOMETEMPLATE
256
+			]);
257 257
 
258
-        Logger::welcomeTemplateDeleted($database, $template);
258
+		Logger::welcomeTemplateDeleted($database, $template);
259 259
 
260
-        $template->delete();
260
+		$template->delete();
261 261
 
262
-        $this->redirect('welcomeTemplates');
262
+		$this->redirect('welcomeTemplates');
263 263
 
264
-        SessionAlert::success(
265
-            "Template deleted. Any users who were using this template have had automatic welcoming disabled.");
266
-        $this->getNotificationHelper()->welcomeTemplateDeleted($templateId);
267
-    }
264
+		SessionAlert::success(
265
+			"Template deleted. Any users who were using this template have had automatic welcoming disabled.");
266
+		$this->getNotificationHelper()->welcomeTemplateDeleted($templateId);
267
+	}
268 268
 
269
-    private function validate($userCode, $botCode)
270
-    {
271
-        if ($userCode === null) {
272
-            throw new ApplicationLogicException('User code cannot be null');
273
-        }
269
+	private function validate($userCode, $botCode)
270
+	{
271
+		if ($userCode === null) {
272
+			throw new ApplicationLogicException('User code cannot be null');
273
+		}
274 274
 
275
-        if ($botCode === null) {
276
-            throw new ApplicationLogicException('Bot code cannot be null');
277
-        }
278
-    }
275
+		if ($botCode === null) {
276
+			throw new ApplicationLogicException('Bot code cannot be null');
277
+		}
278
+	}
279 279
 }
Please login to merge, or discard this patch.
Braces   +2 added lines, -4 removed lines patch added patch discarded remove patch
@@ -166,8 +166,7 @@  discard block
 block discarded – undo
166 166
             SessionAlert::success("Template successfully created.");
167 167
 
168 168
             $this->redirect('welcomeTemplates');
169
-        }
170
-        else {
169
+        } else {
171 170
             $this->assignCSRFToken();
172 171
             $this->assign('template', new WelcomeTemplate());
173 172
             $this->setTemplate("welcome-template/edit.tpl");
@@ -216,8 +215,7 @@  discard block
 block discarded – undo
216 215
             $this->getNotificationHelper()->welcomeTemplateEdited($template);
217 216
 
218 217
             $this->redirect('welcomeTemplates');
219
-        }
220
-        else {
218
+        } else {
221 219
             $this->assignCSRFToken();
222 220
             $this->assign('template', $template);
223 221
             $this->setTemplate('welcome-template/edit.tpl');
Please login to merge, or discard this patch.
includes/Pages/PageXffDemo.php 1 patch
Indentation   +132 added lines, -132 removed lines patch added patch discarded remove patch
@@ -13,136 +13,136 @@
 block discarded – undo
13 13
 
14 14
 class PageXffDemo extends InternalPageBase
15 15
 {
16
-    use RequestData;
17
-
18
-    /**
19
-     * @inheritDoc
20
-     */
21
-    protected function main()
22
-    {
23
-        $this->setTemplate('xffdemo.tpl');
24
-
25
-        // requestHasForwardedIp == false
26
-        // requestProxyData
27
-        // requestRealIp == proxy
28
-        // requestForwardedIp == xff header
29
-        // forwardedOrigin  == top of the chain, assuming xff is trusted
30
-
31
-
32
-        $this->assign('demo2', [
33
-            [
34
-                'trust' => true,
35
-                'trustedlink' => true,
36
-                'ip' => '172.16.0.164',
37
-                'routable' => false,
38
-
39
-            ], [
40
-                'trust' => true,
41
-                'ip' => '198.51.100.123',
42
-                'routable' => true,
43
-                'rdns' => 'trustedproxy.example.com',
44
-
45
-            ], [
46
-                'trust' => true,
47
-                'ip' => '192.0.2.1',
48
-                'routable' => true,
49
-                'rdns' => 'client.users.example.org',
50
-                'location' => [
51
-                    'cityName' => 'San Francisco',
52
-                    'regionName' => 'California',
53
-                    'countryName' => 'United States'
54
-                ],
55
-                'showlinks' => true
56
-            ]
57
-        ]);
58
-
59
-        $this->assign('demo3', [
60
-            [
61
-                'trust' => true,
62
-                'trustedlink' => true,
63
-                'ip' => '172.16.0.164',
64
-                'routable' => false,
65
-
66
-            ], [
67
-                'trust' => false,
68
-                'ip' => '198.51.100.234',
69
-                'routable' => true,
70
-                'rdns' => 'sketchyproxy.example.com',
71
-                'showlinks' => true
72
-
73
-            ], [
74
-                'trust' => false,
75
-                'ip' => '192.0.2.1',
76
-                'routable' => true,
77
-                'rdns' => 'client.users.example.org',
78
-                'location' => [
79
-                    'cityName' => 'San Francisco',
80
-                    'regionName' => 'California',
81
-                    'countryName' => 'United States'
82
-                ],
83
-                'showlinks' => true
84
-            ]
85
-        ]);
86
-
87
-        $this->assign('demo4', [
88
-            [
89
-                'trust' => true,
90
-                'trustedlink' => true,
91
-                'ip' => '172.16.0.164',
92
-                'routable' => false,
93
-
94
-            ], [
95
-                'trust' => true,
96
-                'ip' => '198.51.100.123',
97
-                'routable' => true,
98
-                'rdns' => 'trustedproxy.example.com',
99
-            ], [
100
-                'trust' => false,
101
-                'ip' => '198.51.100.234',
102
-                'routable' => true,
103
-                'rdns' => 'sketchyproxy.example.com',
104
-                'showlinks' => true
105
-            ], [
106
-                'trust' => false,
107
-                'trustedlink' => true,
108
-                'ip' => '198.51.100.124',
109
-                'routable' => true,
110
-                'rdns' => 'trustedproxy2.example.com',
111
-                'showlinks' => true
112
-            ], [
113
-                'trust' => false,
114
-                'ip' => '192.0.2.1',
115
-                'routable' => true,
116
-                'rdns' => 'client.users.example.org',
117
-                'location' => [
118
-                    'cityName' => 'San Francisco',
119
-                    'regionName' => 'California',
120
-                    'countryName' => 'United States'
121
-                ],
122
-                'showlinks' => true
123
-            ]
124
-        ]);
125
-
126
-        $this->assign('demo1', [
127
-            [
128
-                'trust' => true,
129
-                'trustedlink' => true,
130
-                'ip' => '172.16.0.164',
131
-                'routable' => false,
132
-
133
-            ], [
134
-                'trust' => true,
135
-                'trustedlink' => true,
136
-                'ip' => '192.0.2.1',
137
-                'routable' => true,
138
-                'rdns' => 'client.users.example.org',
139
-                'location' => [
140
-                    'cityName' => 'San Francisco',
141
-                    'regionName' => 'California',
142
-                    'countryName' => 'United States'
143
-                ],
144
-                'showlinks' => true
145
-            ]
146
-        ]);
147
-    }
16
+	use RequestData;
17
+
18
+	/**
19
+	 * @inheritDoc
20
+	 */
21
+	protected function main()
22
+	{
23
+		$this->setTemplate('xffdemo.tpl');
24
+
25
+		// requestHasForwardedIp == false
26
+		// requestProxyData
27
+		// requestRealIp == proxy
28
+		// requestForwardedIp == xff header
29
+		// forwardedOrigin  == top of the chain, assuming xff is trusted
30
+
31
+
32
+		$this->assign('demo2', [
33
+			[
34
+				'trust' => true,
35
+				'trustedlink' => true,
36
+				'ip' => '172.16.0.164',
37
+				'routable' => false,
38
+
39
+			], [
40
+				'trust' => true,
41
+				'ip' => '198.51.100.123',
42
+				'routable' => true,
43
+				'rdns' => 'trustedproxy.example.com',
44
+
45
+			], [
46
+				'trust' => true,
47
+				'ip' => '192.0.2.1',
48
+				'routable' => true,
49
+				'rdns' => 'client.users.example.org',
50
+				'location' => [
51
+					'cityName' => 'San Francisco',
52
+					'regionName' => 'California',
53
+					'countryName' => 'United States'
54
+				],
55
+				'showlinks' => true
56
+			]
57
+		]);
58
+
59
+		$this->assign('demo3', [
60
+			[
61
+				'trust' => true,
62
+				'trustedlink' => true,
63
+				'ip' => '172.16.0.164',
64
+				'routable' => false,
65
+
66
+			], [
67
+				'trust' => false,
68
+				'ip' => '198.51.100.234',
69
+				'routable' => true,
70
+				'rdns' => 'sketchyproxy.example.com',
71
+				'showlinks' => true
72
+
73
+			], [
74
+				'trust' => false,
75
+				'ip' => '192.0.2.1',
76
+				'routable' => true,
77
+				'rdns' => 'client.users.example.org',
78
+				'location' => [
79
+					'cityName' => 'San Francisco',
80
+					'regionName' => 'California',
81
+					'countryName' => 'United States'
82
+				],
83
+				'showlinks' => true
84
+			]
85
+		]);
86
+
87
+		$this->assign('demo4', [
88
+			[
89
+				'trust' => true,
90
+				'trustedlink' => true,
91
+				'ip' => '172.16.0.164',
92
+				'routable' => false,
93
+
94
+			], [
95
+				'trust' => true,
96
+				'ip' => '198.51.100.123',
97
+				'routable' => true,
98
+				'rdns' => 'trustedproxy.example.com',
99
+			], [
100
+				'trust' => false,
101
+				'ip' => '198.51.100.234',
102
+				'routable' => true,
103
+				'rdns' => 'sketchyproxy.example.com',
104
+				'showlinks' => true
105
+			], [
106
+				'trust' => false,
107
+				'trustedlink' => true,
108
+				'ip' => '198.51.100.124',
109
+				'routable' => true,
110
+				'rdns' => 'trustedproxy2.example.com',
111
+				'showlinks' => true
112
+			], [
113
+				'trust' => false,
114
+				'ip' => '192.0.2.1',
115
+				'routable' => true,
116
+				'rdns' => 'client.users.example.org',
117
+				'location' => [
118
+					'cityName' => 'San Francisco',
119
+					'regionName' => 'California',
120
+					'countryName' => 'United States'
121
+				],
122
+				'showlinks' => true
123
+			]
124
+		]);
125
+
126
+		$this->assign('demo1', [
127
+			[
128
+				'trust' => true,
129
+				'trustedlink' => true,
130
+				'ip' => '172.16.0.164',
131
+				'routable' => false,
132
+
133
+			], [
134
+				'trust' => true,
135
+				'trustedlink' => true,
136
+				'ip' => '192.0.2.1',
137
+				'routable' => true,
138
+				'rdns' => 'client.users.example.org',
139
+				'location' => [
140
+					'cityName' => 'San Francisco',
141
+					'regionName' => 'California',
142
+					'countryName' => 'United States'
143
+				],
144
+				'showlinks' => true
145
+			]
146
+		]);
147
+	}
148 148
 }
Please login to merge, or discard this patch.
includes/Pages/PageErrorLogViewer.php 2 patches
Indentation   +123 added lines, -123 removed lines patch added patch discarded remove patch
@@ -14,127 +14,127 @@
 block discarded – undo
14 14
 
15 15
 class PageErrorLogViewer extends InternalPageBase
16 16
 {
17
-    /**
18
-     * @inheritDoc
19
-     */
20
-    protected function main()
21
-    {
22
-        $this->setHtmlTitle('Exception viewer');
23
-
24
-        $user = User::getCurrent($this->getDatabase());
25
-        $this->assign('canView', $this->barrierTest('view', $user));
26
-        $this->assign('canRemove', $this->barrierTest('remove', $user));
27
-
28
-        // Get the list of exception logs from the error log directory
29
-        $errorLogDirectory = $this->getSiteConfiguration()->getErrorLog();
30
-        $files = scandir($errorLogDirectory);
31
-
32
-        // Exclude the files we know should be there
33
-        $filteredFiles = array_filter($files, function($file) {
34
-            return !in_array($file, ['.', '..', 'README.md']);
35
-        });
36
-
37
-        $exceptionDetails = array_map(function($item) use ($errorLogDirectory) {
38
-            $filename = realpath($errorLogDirectory) . DIRECTORY_SEPARATOR . $item;
39
-
40
-            return [
41
-                'id'   => str_replace('.log', '', $item),
42
-                'date' => date('Y-m-d H:i:s', filemtime($filename)),
43
-                'data' => str_replace($this->getSiteConfiguration()->getFilePath(), '.',
44
-                    unserialize(file_get_contents($filename))),
45
-            ];
46
-        }, $filteredFiles);
47
-
48
-        $this->assign('exceptionEntries', $exceptionDetails);
49
-        $this->setTemplate('errorlog/main.tpl');
50
-    }
51
-
52
-    protected function view()
53
-    {
54
-        $this->setHtmlTitle('Exception viewer');
55
-
56
-        $requestedErrorId = WebRequest::getString('id');
57
-        $safeFilename = $this->safetyCheck($requestedErrorId);
58
-
59
-        if ($safeFilename === false) {
60
-            $this->redirect('errorLog');
61
-
62
-            return;
63
-        }
64
-
65
-        // note: at this point we've done sufficient sanity checks that we can be confident this value is safe to echo
66
-        // back to the user.
67
-        $this->assign('id', $requestedErrorId);
68
-        $this->assign('date', date('Y-m-d H:i:s', filemtime($safeFilename)));
69
-
70
-        $data = unserialize(file_get_contents($safeFilename));
71
-        $this->assign('server', $data['server']);
72
-        $this->assign('get', $data['get']);
73
-        $this->assign('post', $data['post']);
74
-
75
-        $this->assign('globalHandler', $data['globalHandler']);
76
-
77
-        $exceptionList = [];
78
-        $current = $data;
79
-        do {
80
-            $ex = [
81
-                'exception' => $current['exception'],
82
-                'message'   => str_replace($this->getSiteConfiguration()->getFilePath(), '.', $current['message']),
83
-                'stack'     => str_replace($this->getSiteConfiguration()->getFilePath(), '.', $current['stack']),
84
-            ];
85
-            $exceptionList[] = $ex;
86
-
87
-            $current = $current['previous'];
88
-        }
89
-        while ($current !== null);
90
-
91
-        $this->assign('exceptionList', $exceptionList);
92
-
93
-        $this->setTemplate('errorlog/details.tpl');
94
-    }
95
-
96
-    public function remove()
97
-    {
98
-        $safeFilename = $this->safetyCheck(WebRequest::getString('id'));
99
-
100
-        if ($safeFilename === false) {
101
-            $this->redirect('errorLog');
102
-
103
-            return;
104
-        }
105
-
106
-        unlink($safeFilename);
107
-
108
-        $this->redirect('errorLog');
109
-
110
-        return;
111
-    }
112
-
113
-    /**
114
-     * @param string|null $requestedErrorId
115
-     *
116
-     * @return bool|string
117
-     */
118
-    protected function safetyCheck(?string $requestedErrorId)
119
-    {
120
-        if ($requestedErrorId === null) {
121
-            return false;
122
-        }
123
-
124
-        // security - only allow hex-encoded filenames, as this is what is generated.
125
-        // This is prefixed with the configured directory. Path traversal is protected against due to . and / not being
126
-        // part of the hex character set.
127
-        if (!preg_match('/^[a-f0-9]{40}$/', $requestedErrorId)) {
128
-            return false;
129
-        }
130
-
131
-        $errorLogDirectory = $this->getSiteConfiguration()->getErrorLog();
132
-        $filename = realpath($errorLogDirectory) . DIRECTORY_SEPARATOR . $requestedErrorId . '.log';
133
-
134
-        if (!file_exists($filename)) {
135
-            return false;
136
-        }
137
-
138
-        return $filename;
139
-    }
17
+	/**
18
+	 * @inheritDoc
19
+	 */
20
+	protected function main()
21
+	{
22
+		$this->setHtmlTitle('Exception viewer');
23
+
24
+		$user = User::getCurrent($this->getDatabase());
25
+		$this->assign('canView', $this->barrierTest('view', $user));
26
+		$this->assign('canRemove', $this->barrierTest('remove', $user));
27
+
28
+		// Get the list of exception logs from the error log directory
29
+		$errorLogDirectory = $this->getSiteConfiguration()->getErrorLog();
30
+		$files = scandir($errorLogDirectory);
31
+
32
+		// Exclude the files we know should be there
33
+		$filteredFiles = array_filter($files, function($file) {
34
+			return !in_array($file, ['.', '..', 'README.md']);
35
+		});
36
+
37
+		$exceptionDetails = array_map(function($item) use ($errorLogDirectory) {
38
+			$filename = realpath($errorLogDirectory) . DIRECTORY_SEPARATOR . $item;
39
+
40
+			return [
41
+				'id'   => str_replace('.log', '', $item),
42
+				'date' => date('Y-m-d H:i:s', filemtime($filename)),
43
+				'data' => str_replace($this->getSiteConfiguration()->getFilePath(), '.',
44
+					unserialize(file_get_contents($filename))),
45
+			];
46
+		}, $filteredFiles);
47
+
48
+		$this->assign('exceptionEntries', $exceptionDetails);
49
+		$this->setTemplate('errorlog/main.tpl');
50
+	}
51
+
52
+	protected function view()
53
+	{
54
+		$this->setHtmlTitle('Exception viewer');
55
+
56
+		$requestedErrorId = WebRequest::getString('id');
57
+		$safeFilename = $this->safetyCheck($requestedErrorId);
58
+
59
+		if ($safeFilename === false) {
60
+			$this->redirect('errorLog');
61
+
62
+			return;
63
+		}
64
+
65
+		// note: at this point we've done sufficient sanity checks that we can be confident this value is safe to echo
66
+		// back to the user.
67
+		$this->assign('id', $requestedErrorId);
68
+		$this->assign('date', date('Y-m-d H:i:s', filemtime($safeFilename)));
69
+
70
+		$data = unserialize(file_get_contents($safeFilename));
71
+		$this->assign('server', $data['server']);
72
+		$this->assign('get', $data['get']);
73
+		$this->assign('post', $data['post']);
74
+
75
+		$this->assign('globalHandler', $data['globalHandler']);
76
+
77
+		$exceptionList = [];
78
+		$current = $data;
79
+		do {
80
+			$ex = [
81
+				'exception' => $current['exception'],
82
+				'message'   => str_replace($this->getSiteConfiguration()->getFilePath(), '.', $current['message']),
83
+				'stack'     => str_replace($this->getSiteConfiguration()->getFilePath(), '.', $current['stack']),
84
+			];
85
+			$exceptionList[] = $ex;
86
+
87
+			$current = $current['previous'];
88
+		}
89
+		while ($current !== null);
90
+
91
+		$this->assign('exceptionList', $exceptionList);
92
+
93
+		$this->setTemplate('errorlog/details.tpl');
94
+	}
95
+
96
+	public function remove()
97
+	{
98
+		$safeFilename = $this->safetyCheck(WebRequest::getString('id'));
99
+
100
+		if ($safeFilename === false) {
101
+			$this->redirect('errorLog');
102
+
103
+			return;
104
+		}
105
+
106
+		unlink($safeFilename);
107
+
108
+		$this->redirect('errorLog');
109
+
110
+		return;
111
+	}
112
+
113
+	/**
114
+	 * @param string|null $requestedErrorId
115
+	 *
116
+	 * @return bool|string
117
+	 */
118
+	protected function safetyCheck(?string $requestedErrorId)
119
+	{
120
+		if ($requestedErrorId === null) {
121
+			return false;
122
+		}
123
+
124
+		// security - only allow hex-encoded filenames, as this is what is generated.
125
+		// This is prefixed with the configured directory. Path traversal is protected against due to . and / not being
126
+		// part of the hex character set.
127
+		if (!preg_match('/^[a-f0-9]{40}$/', $requestedErrorId)) {
128
+			return false;
129
+		}
130
+
131
+		$errorLogDirectory = $this->getSiteConfiguration()->getErrorLog();
132
+		$filename = realpath($errorLogDirectory) . DIRECTORY_SEPARATOR . $requestedErrorId . '.log';
133
+
134
+		if (!file_exists($filename)) {
135
+			return false;
136
+		}
137
+
138
+		return $filename;
139
+	}
140 140
 }
141 141
\ No newline at end of file
Please login to merge, or discard this patch.
Braces   +4 added lines, -2 removed lines patch added patch discarded remove patch
@@ -30,11 +30,13 @@
 block discarded – undo
30 30
         $files = scandir($errorLogDirectory);
31 31
 
32 32
         // Exclude the files we know should be there
33
-        $filteredFiles = array_filter($files, function($file) {
33
+        $filteredFiles = array_filter($files, function($file)
34
+        {
34 35
             return !in_array($file, ['.', '..', 'README.md']);
35 36
         });
36 37
 
37
-        $exceptionDetails = array_map(function($item) use ($errorLogDirectory) {
38
+        $exceptionDetails = array_map(function($item) use ($errorLogDirectory)
39
+        {
38 40
             $filename = realpath($errorLogDirectory) . DIRECTORY_SEPARATOR . $item;
39 41
 
40 42
             return [
Please login to merge, or discard this patch.
includes/Pages/PageMain.php 2 patches
Braces   +2 added lines, -1 removed lines patch added patch discarded remove patch
@@ -187,7 +187,8 @@
 block discarded – undo
187 187
 
188 188
         // FIXME: domains!
189 189
         $requestQueues = RequestQueue::getAllQueues($database);
190
-        $queuesById = array_reduce($requestQueues, function($result, RequestQueue $item) {
190
+        $queuesById = array_reduce($requestQueues, function($result, RequestQueue $item)
191
+        {
191 192
             $result[$item->getId()] = $item;
192 193
             return $result;
193 194
         }, array());
Please login to merge, or discard this patch.
Indentation   +183 added lines, -183 removed lines patch added patch discarded remove patch
@@ -23,69 +23,69 @@  discard block
 block discarded – undo
23 23
 
24 24
 class PageMain extends InternalPageBase
25 25
 {
26
-    use RequestListData;
27
-
28
-    /**
29
-     * Main function for this page, when no actions are called.
30
-     */
31
-    protected function main()
32
-    {
33
-        $this->assignCSRFToken();
34
-
35
-        $config = $this->getSiteConfiguration();
36
-        $database = $this->getDatabase();
37
-        $currentUser = User::getCurrent($database);
38
-        $preferencesManager = PreferenceManager::getForCurrent($database);
39
-
40
-        // general template configuration
41
-        // FIXME: domains!
42
-        $defaultQueue = RequestQueue::getDefaultQueue($database, 1);
43
-        $this->assign('defaultRequestState', $defaultQueue->getApiName());
44
-        $this->assign('requestLimitShowOnly', $config->getMiserModeLimit());
45
-
46
-        $seeAllRequests = $this->barrierTest('seeAllRequests', $currentUser, PageViewRequest::class);
47
-
48
-        list($defaultSort, $defaultSortDirection) = WebRequest::requestListDefaultSort();
49
-        $this->assign('defaultSort', $defaultSort);
50
-        $this->assign('defaultSortDirection', $defaultSortDirection);
51
-        $showQueueHelp = $preferencesManager->getPreference(PreferenceManager::PREF_QUEUE_HELP) ?? true;
52
-        $this->assign('showQueueHelp', $showQueueHelp);
53
-
54
-        // Fetch request data
55
-        $requestSectionData = array();
56
-        if ($seeAllRequests) {
57
-            $this->setupStatusSections($database, $config, $requestSectionData);
58
-            $this->setupHospitalQueue($database, $config, $requestSectionData);
59
-            $this->setupJobQueue($database, $config, $requestSectionData);
60
-        }
61
-        $this->setupLastFiveClosedData($database, $seeAllRequests);
62
-
63
-        // Assign data to template
64
-        $this->assign('requestSectionData', $requestSectionData);
65
-
66
-        $this->setTemplate('mainpage/mainpage.tpl');
67
-    }
68
-
69
-    /**
70
-     * @param PdoDatabase $database
71
-     * @param bool        $seeAllRequests
72
-     *
73
-     * @internal param User $currentUser
74
-     */
75
-    private function setupLastFiveClosedData(PdoDatabase $database, $seeAllRequests)
76
-    {
77
-        $config = $this->getSiteConfiguration();
78
-        $this->assign('showLastFive', $seeAllRequests);
79
-        if (!$seeAllRequests) {
80
-            return;
81
-        }
82
-
83
-        $queryExcludeDropped = "";
84
-        if ($config->getEmailConfirmationEnabled()) {
85
-            $queryExcludeDropped = "AND request.emailConfirm = 'Confirmed'";
86
-        }
87
-
88
-        $query = <<<SQL
26
+	use RequestListData;
27
+
28
+	/**
29
+	 * Main function for this page, when no actions are called.
30
+	 */
31
+	protected function main()
32
+	{
33
+		$this->assignCSRFToken();
34
+
35
+		$config = $this->getSiteConfiguration();
36
+		$database = $this->getDatabase();
37
+		$currentUser = User::getCurrent($database);
38
+		$preferencesManager = PreferenceManager::getForCurrent($database);
39
+
40
+		// general template configuration
41
+		// FIXME: domains!
42
+		$defaultQueue = RequestQueue::getDefaultQueue($database, 1);
43
+		$this->assign('defaultRequestState', $defaultQueue->getApiName());
44
+		$this->assign('requestLimitShowOnly', $config->getMiserModeLimit());
45
+
46
+		$seeAllRequests = $this->barrierTest('seeAllRequests', $currentUser, PageViewRequest::class);
47
+
48
+		list($defaultSort, $defaultSortDirection) = WebRequest::requestListDefaultSort();
49
+		$this->assign('defaultSort', $defaultSort);
50
+		$this->assign('defaultSortDirection', $defaultSortDirection);
51
+		$showQueueHelp = $preferencesManager->getPreference(PreferenceManager::PREF_QUEUE_HELP) ?? true;
52
+		$this->assign('showQueueHelp', $showQueueHelp);
53
+
54
+		// Fetch request data
55
+		$requestSectionData = array();
56
+		if ($seeAllRequests) {
57
+			$this->setupStatusSections($database, $config, $requestSectionData);
58
+			$this->setupHospitalQueue($database, $config, $requestSectionData);
59
+			$this->setupJobQueue($database, $config, $requestSectionData);
60
+		}
61
+		$this->setupLastFiveClosedData($database, $seeAllRequests);
62
+
63
+		// Assign data to template
64
+		$this->assign('requestSectionData', $requestSectionData);
65
+
66
+		$this->setTemplate('mainpage/mainpage.tpl');
67
+	}
68
+
69
+	/**
70
+	 * @param PdoDatabase $database
71
+	 * @param bool        $seeAllRequests
72
+	 *
73
+	 * @internal param User $currentUser
74
+	 */
75
+	private function setupLastFiveClosedData(PdoDatabase $database, $seeAllRequests)
76
+	{
77
+		$config = $this->getSiteConfiguration();
78
+		$this->assign('showLastFive', $seeAllRequests);
79
+		if (!$seeAllRequests) {
80
+			return;
81
+		}
82
+
83
+		$queryExcludeDropped = "";
84
+		if ($config->getEmailConfirmationEnabled()) {
85
+			$queryExcludeDropped = "AND request.emailConfirm = 'Confirmed'";
86
+		}
87
+
88
+		$query = <<<SQL
89 89
 		SELECT request.id, request.name, request.updateversion
90 90
 		FROM request /* PageMain::main() */
91 91
 		JOIN log ON log.objectid = request.id AND log.objecttype = 'Request'
@@ -95,124 +95,124 @@  discard block
 block discarded – undo
95 95
 		LIMIT 5;
96 96
 SQL;
97 97
 
98
-        $statement = $database->prepare($query);
99
-        $statement->execute();
100
-
101
-        $last5result = $statement->fetchAll(PDO::FETCH_ASSOC);
102
-
103
-        $this->assign('lastFive', $last5result);
104
-    }
105
-
106
-    /**
107
-     * @param PdoDatabase       $database
108
-     * @param SiteConfiguration $config
109
-     * @param                   $requestSectionData
110
-     */
111
-    private function setupHospitalQueue(
112
-        PdoDatabase $database,
113
-        SiteConfiguration $config,
114
-        &$requestSectionData
115
-    ) {
116
-        // FIXME: domains!
117
-        $search = RequestSearchHelper::get($database, 1)
118
-            ->limit($config->getMiserModeLimit())
119
-            ->excludingStatus('Closed')
120
-            ->isHospitalised();
121
-
122
-        if ($config->getEmailConfirmationEnabled()) {
123
-            $search->withConfirmedEmail();
124
-        }
125
-
126
-        /** @var Request[] $results */
127
-        $results = $search->getRecordCount($requestCount)->fetch();
128
-
129
-        if ($requestCount > 0) {
130
-            $requestSectionData['Hospital - Requests failed auto-creation'] = array(
131
-                'requests' => $this->prepareRequestData($results),
132
-                'total'    => $requestCount,
133
-                'api'      => 'hospital',
134
-                'type'     => 'hospital',
135
-                'special'  => 'Job Queue',
136
-                'help'     => 'This queue lists all the requests which have been attempted to be created in the background, but for which this has failed for one reason or another. Check the job queue to find the error. Requests here may need to be created manually, or it may be possible to re-queue the request for auto-creation by the tool, or it may have been created already. Use your own technical discretion here.',
137
-                'showAll'  => false
138
-            );
139
-        }
140
-    }
141
-
142
-    /**
143
-     * @param PdoDatabase       $database
144
-     * @param SiteConfiguration $config
145
-     * @param                   $requestSectionData
146
-     */
147
-    private function setupJobQueue(
148
-        PdoDatabase $database,
149
-        SiteConfiguration $config,
150
-        &$requestSectionData
151
-    ) {
152
-        // FIXME: domains!
153
-        $search = RequestSearchHelper::get($database, 1)
154
-            ->limit($config->getMiserModeLimit())
155
-            ->byStatus(RequestStatus::JOBQUEUE);
156
-
157
-        if ($config->getEmailConfirmationEnabled()) {
158
-            $search->withConfirmedEmail();
159
-        }
160
-
161
-        /** @var Request[] $results */
162
-        $results = $search->getRecordCount($requestCount)->fetch();
163
-
164
-        if ($requestCount > 0) {
165
-            $requestSectionData['Requests queued in the Job Queue'] = array(
166
-                'requests' => $this->prepareRequestData($results),
167
-                'total'    => $requestCount,
168
-                'api'      => 'JobQueue',
169
-                'type'     => 'JobQueue',
170
-                'special'  => 'Job Queue',
171
-                'help'     => 'This section lists all the requests which are currently waiting to be created by the tool. Requests should automatically disappear from here within a few minutes.',
172
-                'showAll'  => false
173
-            );
174
-        }
175
-    }
176
-
177
-    /**
178
-     * @param PdoDatabase       $database
179
-     * @param SiteConfiguration $config
180
-     * @param                   $requestSectionData
181
-     */
182
-    private function setupStatusSections(
183
-        PdoDatabase $database,
184
-        SiteConfiguration $config,
185
-        &$requestSectionData
186
-    ) {
187
-        // FIXME: domains!
188
-        $search = RequestSearchHelper::get($database, 1)->limit($config->getMiserModeLimit());
189
-        $search->byStatus(RequestStatus::OPEN);
190
-
191
-        if ($config->getEmailConfirmationEnabled()) {
192
-            $search->withConfirmedEmail();
193
-        }
194
-
195
-        // FIXME: domains!
196
-        $requestQueues = RequestQueue::getAllQueues($database);
197
-        $queuesById = array_reduce($requestQueues, function($result, RequestQueue $item) {
198
-            $result[$item->getId()] = $item;
199
-            return $result;
200
-        }, array());
201
-
202
-        $requestsByQueue = $search->fetchByQueue(array_keys($queuesById));
203
-
204
-        foreach ($requestsByQueue as $queueId => $queueData) {
205
-            if ($queueData['count'] > 0 || $queuesById[$queueId]->isEnabled()) {
206
-                $requestSectionData[$queuesById[$queueId]->getHeader()] = array(
207
-                    'requests' => $this->prepareRequestData($queueData['data']),
208
-                    'total'    => $queueData['count'],
209
-                    'api'      => $queuesById[$queueId]->getApiName(),
210
-                    'type'     => $queueId,
211
-                    'special'  => null,
212
-                    'help'     => $queuesById[$queueId]->getHelp(),
213
-                    'showAll'  => true
214
-                );
215
-            }
216
-        }
217
-    }
98
+		$statement = $database->prepare($query);
99
+		$statement->execute();
100
+
101
+		$last5result = $statement->fetchAll(PDO::FETCH_ASSOC);
102
+
103
+		$this->assign('lastFive', $last5result);
104
+	}
105
+
106
+	/**
107
+	 * @param PdoDatabase       $database
108
+	 * @param SiteConfiguration $config
109
+	 * @param                   $requestSectionData
110
+	 */
111
+	private function setupHospitalQueue(
112
+		PdoDatabase $database,
113
+		SiteConfiguration $config,
114
+		&$requestSectionData
115
+	) {
116
+		// FIXME: domains!
117
+		$search = RequestSearchHelper::get($database, 1)
118
+			->limit($config->getMiserModeLimit())
119
+			->excludingStatus('Closed')
120
+			->isHospitalised();
121
+
122
+		if ($config->getEmailConfirmationEnabled()) {
123
+			$search->withConfirmedEmail();
124
+		}
125
+
126
+		/** @var Request[] $results */
127
+		$results = $search->getRecordCount($requestCount)->fetch();
128
+
129
+		if ($requestCount > 0) {
130
+			$requestSectionData['Hospital - Requests failed auto-creation'] = array(
131
+				'requests' => $this->prepareRequestData($results),
132
+				'total'    => $requestCount,
133
+				'api'      => 'hospital',
134
+				'type'     => 'hospital',
135
+				'special'  => 'Job Queue',
136
+				'help'     => 'This queue lists all the requests which have been attempted to be created in the background, but for which this has failed for one reason or another. Check the job queue to find the error. Requests here may need to be created manually, or it may be possible to re-queue the request for auto-creation by the tool, or it may have been created already. Use your own technical discretion here.',
137
+				'showAll'  => false
138
+			);
139
+		}
140
+	}
141
+
142
+	/**
143
+	 * @param PdoDatabase       $database
144
+	 * @param SiteConfiguration $config
145
+	 * @param                   $requestSectionData
146
+	 */
147
+	private function setupJobQueue(
148
+		PdoDatabase $database,
149
+		SiteConfiguration $config,
150
+		&$requestSectionData
151
+	) {
152
+		// FIXME: domains!
153
+		$search = RequestSearchHelper::get($database, 1)
154
+			->limit($config->getMiserModeLimit())
155
+			->byStatus(RequestStatus::JOBQUEUE);
156
+
157
+		if ($config->getEmailConfirmationEnabled()) {
158
+			$search->withConfirmedEmail();
159
+		}
160
+
161
+		/** @var Request[] $results */
162
+		$results = $search->getRecordCount($requestCount)->fetch();
163
+
164
+		if ($requestCount > 0) {
165
+			$requestSectionData['Requests queued in the Job Queue'] = array(
166
+				'requests' => $this->prepareRequestData($results),
167
+				'total'    => $requestCount,
168
+				'api'      => 'JobQueue',
169
+				'type'     => 'JobQueue',
170
+				'special'  => 'Job Queue',
171
+				'help'     => 'This section lists all the requests which are currently waiting to be created by the tool. Requests should automatically disappear from here within a few minutes.',
172
+				'showAll'  => false
173
+			);
174
+		}
175
+	}
176
+
177
+	/**
178
+	 * @param PdoDatabase       $database
179
+	 * @param SiteConfiguration $config
180
+	 * @param                   $requestSectionData
181
+	 */
182
+	private function setupStatusSections(
183
+		PdoDatabase $database,
184
+		SiteConfiguration $config,
185
+		&$requestSectionData
186
+	) {
187
+		// FIXME: domains!
188
+		$search = RequestSearchHelper::get($database, 1)->limit($config->getMiserModeLimit());
189
+		$search->byStatus(RequestStatus::OPEN);
190
+
191
+		if ($config->getEmailConfirmationEnabled()) {
192
+			$search->withConfirmedEmail();
193
+		}
194
+
195
+		// FIXME: domains!
196
+		$requestQueues = RequestQueue::getAllQueues($database);
197
+		$queuesById = array_reduce($requestQueues, function($result, RequestQueue $item) {
198
+			$result[$item->getId()] = $item;
199
+			return $result;
200
+		}, array());
201
+
202
+		$requestsByQueue = $search->fetchByQueue(array_keys($queuesById));
203
+
204
+		foreach ($requestsByQueue as $queueId => $queueData) {
205
+			if ($queueData['count'] > 0 || $queuesById[$queueId]->isEnabled()) {
206
+				$requestSectionData[$queuesById[$queueId]->getHeader()] = array(
207
+					'requests' => $this->prepareRequestData($queueData['data']),
208
+					'total'    => $queueData['count'],
209
+					'api'      => $queuesById[$queueId]->getApiName(),
210
+					'type'     => $queueId,
211
+					'special'  => null,
212
+					'help'     => $queuesById[$queueId]->getHelp(),
213
+					'showAll'  => true
214
+				);
215
+			}
216
+		}
217
+	}
218 218
 }
Please login to merge, or discard this patch.
includes/Pages/PageViewRequest.php 2 patches
Braces   +3 added lines, -6 removed lines patch added patch discarded remove patch
@@ -136,8 +136,7 @@  discard block
 block discarded – undo
136 136
                 $this->setTemplate('view-request/main-with-checkuser-data.tpl');
137 137
                 $this->setupCheckUserData($request);
138 138
             }
139
-        }
140
-        else {
139
+        } else {
141 140
             $this->setTemplate('view-request/main.tpl');
142 141
         }
143 142
     }
@@ -151,8 +150,7 @@  discard block
 block discarded – undo
151 150
         if ($request->getStatus() === RequestStatus::CLOSED) {
152 151
             if ($request->getWasCreated()) {
153 152
                 $statusSymbol = self::STATUS_SYMBOL_ACCEPTED;
154
-            }
155
-            else {
153
+            } else {
156 154
                 $statusSymbol = self::STATUS_SYMBOL_REJECTED;
157 155
             }
158 156
         }
@@ -304,8 +302,7 @@  discard block
 block discarded – undo
304 302
                         'jobId'    => $job->getId(),
305 303
                         'jobDesc'  => JobQueue::getTaskDescriptions()[$job->getTask()],
306 304
                     );
307
-                }
308
-                else {
305
+                } else {
309 306
                     $requestLogs[] = array(
310 307
                         'type'     => 'log',
311 308
                         'security' => 'user',
Please login to merge, or discard this patch.
Indentation   +375 added lines, -375 removed lines patch added patch discarded remove patch
@@ -33,380 +33,380 @@
 block discarded – undo
33 33
 
34 34
 class PageViewRequest extends InternalPageBase
35 35
 {
36
-    use RequestData;
36
+	use RequestData;
37 37
 
38
-    const STATUS_SYMBOL_OPEN = '&#927';
39
-    const STATUS_SYMBOL_ACCEPTED = '&#x2611';
40
-    const STATUS_SYMBOL_REJECTED = '&#x2612';
41
-
42
-    /**
43
-     * Main function for this page, when no specific actions are called.
44
-     * @throws ApplicationLogicException
45
-     */
46
-    protected function main()
47
-    {
48
-        // set up csrf protection
49
-        $this->assignCSRFToken();
50
-
51
-        // get some useful objects
52
-        $database = $this->getDatabase();
53
-        $request = $this->getRequest($database, WebRequest::getInt('id'));
54
-        $config = $this->getSiteConfiguration();
55
-        $currentUser = User::getCurrent($database);
56
-
57
-        /** @var Domain $domain */
58
-        $domain = Domain::getById($request->getDomain(), $this->getDatabase());
59
-        $this->assign('mediawikiScriptPath', $domain->getWikiArticlePath());
60
-
61
-        // Shows a page if the email is not confirmed.
62
-        if ($request->getEmailConfirm() !== 'Confirmed') {
63
-            // Show a banner if the user can manually confirm the request
64
-            $viewConfirm = $this->barrierTest(RoleConfigurationBase::MAIN, $currentUser, PageManuallyConfirm::class);
65
-
66
-            // If the request is purged, there's nothing to confirm!
67
-            if ($request->getEmail() === $this->getSiteConfiguration()->getDataClearEmail()) {
68
-                $viewConfirm = false;
69
-            }
70
-
71
-            // Render
72
-            $this->setTemplate("view-request/not-confirmed.tpl");
73
-            $this->assign("requestId", $request->getId());
74
-            $this->assign("requestVersion", $request->getUpdateVersion());
75
-            $this->assign('canViewConfirmButton', $viewConfirm);
76
-
77
-            // Make sure to return, to prevent the leaking of other information.
78
-            return;
79
-        }
80
-
81
-        $this->setupBasicData($request, $config);
82
-
83
-        $this->setupUsernameData($request);
84
-
85
-        $this->setupTitle($request);
86
-
87
-        $this->setupReservationDetails($request->getReserved(), $database, $currentUser);
88
-        $this->setupGeneralData($database);
89
-
90
-        $this->assign('requestDataCleared', false);
91
-        if ($request->getEmail() === $this->getSiteConfiguration()->getDataClearEmail()) {
92
-            $this->assign('requestDataCleared', true);
93
-        }
94
-
95
-        $allowedPrivateData = $this->isAllowedPrivateData($request, $currentUser);
96
-
97
-        $this->setupCreationTypes($currentUser);
98
-
99
-        $this->setupLogData($request, $database, $allowedPrivateData);
100
-
101
-        $this->addJs("/api.php?action=templates&targetVariable=templateconfirms");
102
-
103
-        $this->assign('showRevealLink', false);
104
-        if ($request->getReserved() === $currentUser->getId() ||
105
-            $this->barrierTest('alwaysSeeHash', $currentUser, 'RequestData')
106
-        ) {
107
-            $this->assign('showRevealLink', true);
108
-            $this->assign('revealHash', $request->getRevealHash());
109
-        }
110
-
111
-        $this->assign('canSeeRelatedRequests', false);
112
-        if ($allowedPrivateData || $this->barrierTest('seeRelatedRequests', $currentUser, 'RequestData')) {
113
-            $this->setupRelatedRequests($request, $config, $database);
114
-        }
115
-
116
-        $this->assign('canCreateLocalAccount', $this->barrierTest('createLocalAccount', $currentUser, 'RequestData'));
117
-
118
-        $closureDate = $request->getClosureDate();
119
-        $date = new DateTime();
120
-        $date->modify("-7 days");
121
-        if ($request->getStatus() == "Closed" && $closureDate < $date) {
122
-            $this->assign('isOldRequest', true);
123
-        }
124
-        $this->assign('canResetOldRequest', $this->barrierTest('reopenOldRequest', $currentUser, 'RequestData'));
125
-        $this->assign('canResetPurgedRequest', $this->barrierTest('reopenClearedRequest', $currentUser, 'RequestData'));
126
-
127
-        $this->assign('requestEmailSent', $request->getEmailSent());
128
-
129
-        if ($allowedPrivateData) {
130
-            $this->assign('manualCreationUrl', $this->getCreationUrl($domain));
131
-
132
-            $this->setTemplate('view-request/main-with-data.tpl');
133
-            $this->setupPrivateData($request, $config);
134
-            $this->assign('canSetBan', $this->barrierTest('set', $currentUser, PageBan::class));
135
-            $this->assign('canSeeCheckuserData', $this->barrierTest('seeUserAgentData', $currentUser, 'RequestData'));
136
-
137
-            if ($this->barrierTest('seeUserAgentData', $currentUser, 'RequestData')) {
138
-                $this->setTemplate('view-request/main-with-checkuser-data.tpl');
139
-                $this->setupCheckUserData($request);
140
-            }
141
-        }
142
-        else {
143
-            $this->setTemplate('view-request/main.tpl');
144
-        }
145
-    }
146
-
147
-    /**
148
-     * @param Request $request
149
-     */
150
-    protected function setupTitle(Request $request)
151
-    {
152
-        $statusSymbol = self::STATUS_SYMBOL_OPEN;
153
-        if ($request->getStatus() === RequestStatus::CLOSED) {
154
-            if ($request->getWasCreated()) {
155
-                $statusSymbol = self::STATUS_SYMBOL_ACCEPTED;
156
-            }
157
-            else {
158
-                $statusSymbol = self::STATUS_SYMBOL_REJECTED;
159
-            }
160
-        }
161
-
162
-        $this->setHtmlTitle($statusSymbol . ' #' . $request->getId());
163
-    }
164
-
165
-    /**
166
-     * Sets up data unrelated to the request, such as the email template information
167
-     *
168
-     * @param PdoDatabase $database
169
-     */
170
-    protected function setupGeneralData(PdoDatabase $database)
171
-    {
172
-        $this->assign('createAccountReason', 'Requested account at [[WP:ACC]], request #');
173
-
174
-        // FIXME: domains
175
-        /** @var Domain $domain */
176
-        $domain = Domain::getById(1, $database);
177
-        $this->assign('defaultRequestState', RequestQueue::getDefaultQueue($database, 1)->getApiName());
178
-        $this->assign('activeRequestQueues', RequestQueue::getEnabledQueues($database));
179
-
180
-        /** @var EmailTemplate $createdTemplate */
181
-        $createdTemplate = EmailTemplate::getById($domain->getDefaultClose(), $database);
182
-
183
-        $this->assign('createdHasJsQuestion', $createdTemplate->getJsquestion() != '');
184
-        $this->assign('createdId', $createdTemplate->getId());
185
-        $this->assign('createdName', $createdTemplate->getName());
186
-
187
-        $preferenceManager = PreferenceManager::getForCurrent($database);
188
-        $skipJsAborts = $preferenceManager->getPreference(PreferenceManager::PREF_SKIP_JS_ABORT);
189
-        $preferredCreationMode = (int)$preferenceManager->getPreference(PreferenceManager::PREF_CREATION_MODE);
190
-        $this->assign('skipJsAborts', $skipJsAborts);
191
-        $this->assign('preferredCreationMode', $preferredCreationMode);
192
-
193
-        $createReasons = EmailTemplate::getActiveNonpreloadTemplates(
194
-            EmailTemplate::ACTION_CREATED,
195
-            $database,
196
-            $domain->getId(),
197
-            $domain->getDefaultClose());
198
-        $this->assign("createReasons", $createReasons);
199
-
200
-        $declineReasons = EmailTemplate::getActiveNonpreloadTemplates(
201
-            EmailTemplate::ACTION_NOT_CREATED,
202
-            $database,
203
-            $domain->getId());
204
-        $this->assign("declineReasons", $declineReasons);
205
-
206
-        $allCreateReasons = EmailTemplate::getAllActiveTemplates(
207
-            EmailTemplate::ACTION_CREATED,
208
-            $database,
209
-            $domain->getId());
210
-        $this->assign("allCreateReasons", $allCreateReasons);
211
-
212
-        $allDeclineReasons = EmailTemplate::getAllActiveTemplates(
213
-            EmailTemplate::ACTION_NOT_CREATED,
214
-            $database,
215
-            $domain->getId());
216
-        $this->assign("allDeclineReasons", $allDeclineReasons);
217
-
218
-        $allOtherReasons = EmailTemplate::getAllActiveTemplates(
219
-            false,
220
-            $database,
221
-            $domain->getId());
222
-        $this->assign("allOtherReasons", $allOtherReasons);
223
-    }
224
-
225
-    private function setupLogData(Request $request, PdoDatabase $database, bool $allowedPrivateData)
226
-    {
227
-        $currentUser = User::getCurrent($database);
228
-
229
-        $logs = LogHelper::getRequestLogsWithComments($request->getId(), $database, $this->getSecurityManager());
230
-        $requestLogs = array();
231
-
232
-        /** @var User[] $nameCache */
233
-        $nameCache = array();
234
-
235
-        $editableComments = $this->barrierTest('editOthers', $currentUser, PageEditComment::class);
236
-
237
-        $canFlag = $this->barrierTest(RoleConfigurationBase::MAIN, $currentUser, PageFlagComment::class);
238
-        $canUnflag = $this->barrierTest('unflag', $currentUser, PageFlagComment::class);
239
-
240
-        /** @var Log|Comment $entry */
241
-        foreach ($logs as $entry) {
242
-            // both log and comment have a 'user' field
243
-            if (!array_key_exists($entry->getUser(), $nameCache)) {
244
-                $entryUser = User::getById($entry->getUser(), $database);
245
-                $nameCache[$entry->getUser()] = $entryUser;
246
-            }
247
-
248
-            if ($entry instanceof Comment) {
249
-                // Determine if the comment contains private information.
250
-                // Private defined as flagged or restricted visibility, but only when the user isn't allowed
251
-                // to see private data
252
-                $commentIsRestricted =
253
-                    ($entry->getFlagged()
254
-                        || $entry->getVisibility() == 'admin' || $entry->getVisibility() == 'checkuser')
255
-                    && !$allowedPrivateData;
256
-
257
-                // Only allow comment editing if the user is able to edit comments or this is the user's own comment,
258
-                // but only when they're allowed to see the comment itself.
259
-                $commentIsEditable = ($editableComments || $entry->getUser() == $currentUser->getId())
260
-                    && !$commentIsRestricted;
261
-
262
-                // Flagging/unflagging can only be done if you can see the comment
263
-                $canFlagThisComment = $canFlag
264
-                    && (
265
-                        (!$entry->getFlagged() && !$commentIsRestricted)
266
-                        || ($entry->getFlagged() && $canUnflag && $commentIsEditable)
267
-                    );
268
-
269
-                $requestLogs[] = array(
270
-                    'type'          => 'comment',
271
-                    'security'      => $entry->getVisibility(),
272
-                    'user'          => $entry->getVisibility() == 'requester' ? $request->getName() : $nameCache[$entry->getUser()]->getUsername(),
273
-                    'userid'        => $entry->getUser() == -1 ? null : $entry->getUser(),
274
-                    'entry'         => null,
275
-                    'time'          => $entry->getTime(),
276
-                    'canedit'       => $commentIsEditable,
277
-                    'id'            => $entry->getId(),
278
-                    'comment'       => $entry->getComment(),
279
-                    'flagged'       => $entry->getFlagged(),
280
-                    'canflag'       => $canFlagThisComment,
281
-                    'updateversion' => $entry->getUpdateVersion(),
282
-                    'edited'        => $entry->getEdited(),
283
-                    'hidden'        => $commentIsRestricted
284
-                );
285
-            }
286
-
287
-            if ($entry instanceof Log) {
288
-                $invalidUserId = $entry->getUser() === -1 || $entry->getUser() === 0;
289
-                $entryUser = $invalidUserId ? User::getCommunity() : $nameCache[$entry->getUser()];
290
-
291
-                $entryComment = $entry->getComment();
292
-
293
-                if ($entry->getAction() === 'JobIssueRequest' || $entry->getAction() === 'JobCompletedRequest') {
294
-                    $data = unserialize($entry->getComment());
295
-                    /** @var JobQueue $job */
296
-                    $job = JobQueue::getById($data['job'], $database);
297
-                    $requestLogs[] = array(
298
-                        'type'     => 'joblog',
299
-                        'security' => 'user',
300
-                        'userid'   => $entry->getUser() == -1 ? null : $entry->getUser(),
301
-                        'user'     => $entryUser->getUsername(),
302
-                        'entry'    => LogHelper::getLogDescription($entry),
303
-                        'time'     => $entry->getTimestamp(),
304
-                        'canedit'  => false,
305
-                        'id'       => $entry->getId(),
306
-                        'jobId'    => $job->getId(),
307
-                        'jobDesc'  => JobQueue::getTaskDescriptions()[$job->getTask()],
308
-                    );
309
-                }
310
-                else {
311
-                    $requestLogs[] = array(
312
-                        'type'     => 'log',
313
-                        'security' => 'user',
314
-                        'userid'   => $entry->getUser() == -1 ? null : $entry->getUser(),
315
-                        'user'     => $entryUser->getUsername(),
316
-                        'entry'    => LogHelper::getLogDescription($entry),
317
-                        'time'     => $entry->getTimestamp(),
318
-                        'canedit'  => false,
319
-                        'id'       => $entry->getId(),
320
-                        'comment'  => $entryComment,
321
-                    );
322
-                }
323
-            }
324
-        }
325
-
326
-        $this->addJs("/api.php?action=users&targetVariable=typeaheaddata");
327
-
328
-        $this->assign("requestLogs", $requestLogs);
329
-    }
330
-
331
-    /**
332
-     * @param Request $request
333
-     */
334
-    protected function setupUsernameData(Request $request)
335
-    {
336
-        $blacklistData = $this->getBlacklistHelper()->isBlacklisted($request->getName());
337
-
338
-        $this->assign('requestIsBlacklisted', $blacklistData !== false);
339
-        $this->assign('requestBlacklist', $blacklistData);
340
-
341
-        try {
342
-            $spoofs = $this->getAntiSpoofProvider()->getSpoofs($request->getName());
343
-        }
344
-        catch (Exception $ex) {
345
-            $spoofs = $ex->getMessage();
346
-        }
347
-
348
-        $this->assign("spoofs", $spoofs);
349
-    }
350
-
351
-    private function setupCreationTypes(User $user)
352
-    {
353
-        $this->assign('allowWelcomeSkip', false);
354
-        $this->assign('forceWelcomeSkip', false);
355
-
356
-        $database = $this->getDatabase();
357
-        $preferenceManager = PreferenceManager::getForCurrent($database);
358
-
359
-        $oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
360
-
361
-        $welcomeTemplate = $preferenceManager->getPreference(PreferenceManager::PREF_WELCOMETEMPLATE);
362
-
363
-        if ($welcomeTemplate != null) {
364
-            $this->assign('allowWelcomeSkip', true);
365
-
366
-            if (!$oauth->canWelcome()) {
367
-                $this->assign('forceWelcomeSkip', true);
368
-            }
369
-        }
370
-
371
-        // test credentials
372
-        $canManualCreate = $this->barrierTest(PreferenceManager::CREATION_MANUAL, $user, 'RequestCreation');
373
-        $canOauthCreate = $this->barrierTest(PreferenceManager::CREATION_OAUTH, $user, 'RequestCreation');
374
-        $canBotCreate = $this->barrierTest(PreferenceManager::CREATION_BOT, $user, 'RequestCreation');
375
-
376
-        $this->assign('canManualCreate', $canManualCreate);
377
-        $this->assign('canOauthCreate', $canOauthCreate);
378
-        $this->assign('canBotCreate', $canBotCreate);
379
-
380
-        // show/hide the type radio buttons
381
-        $creationHasChoice = count(array_filter([$canManualCreate, $canOauthCreate, $canBotCreate])) > 1;
382
-
383
-        $creationModePreference = $preferenceManager->getPreference(PreferenceManager::PREF_CREATION_MODE);
384
-        if (!$this->barrierTest($creationModePreference, $user, 'RequestCreation')) {
385
-            // user is not allowed to use their default. Force a choice.
386
-            $creationHasChoice = true;
387
-        }
388
-
389
-        $this->assign('creationHasChoice', $creationHasChoice);
390
-
391
-        // determine problems in creation types
392
-        $this->assign('botProblem', false);
393
-        if ($canBotCreate && $this->getSiteConfiguration()->getCreationBotPassword() === null) {
394
-            $this->assign('botProblem', true);
395
-        }
396
-
397
-        $this->assign('oauthProblem', false);
398
-        if ($canOauthCreate && !$oauth->canCreateAccount()) {
399
-            $this->assign('oauthProblem', true);
400
-        }
401
-    }
402
-
403
-    private function getCreationUrl(Domain $domain): string
404
-    {
405
-        $template = $this->getSiteConfiguration()->getCreateAccountLink();
406
-
407
-        $template = str_replace('{articlePath}', $domain->getWikiArticlePath(), $template);
408
-        $template = str_replace('{wikiId}', $domain->getShortName(), $template);
409
-
410
-        return $template;
411
-    }
38
+	const STATUS_SYMBOL_OPEN = '&#927';
39
+	const STATUS_SYMBOL_ACCEPTED = '&#x2611';
40
+	const STATUS_SYMBOL_REJECTED = '&#x2612';
41
+
42
+	/**
43
+	 * Main function for this page, when no specific actions are called.
44
+	 * @throws ApplicationLogicException
45
+	 */
46
+	protected function main()
47
+	{
48
+		// set up csrf protection
49
+		$this->assignCSRFToken();
50
+
51
+		// get some useful objects
52
+		$database = $this->getDatabase();
53
+		$request = $this->getRequest($database, WebRequest::getInt('id'));
54
+		$config = $this->getSiteConfiguration();
55
+		$currentUser = User::getCurrent($database);
56
+
57
+		/** @var Domain $domain */
58
+		$domain = Domain::getById($request->getDomain(), $this->getDatabase());
59
+		$this->assign('mediawikiScriptPath', $domain->getWikiArticlePath());
60
+
61
+		// Shows a page if the email is not confirmed.
62
+		if ($request->getEmailConfirm() !== 'Confirmed') {
63
+			// Show a banner if the user can manually confirm the request
64
+			$viewConfirm = $this->barrierTest(RoleConfigurationBase::MAIN, $currentUser, PageManuallyConfirm::class);
65
+
66
+			// If the request is purged, there's nothing to confirm!
67
+			if ($request->getEmail() === $this->getSiteConfiguration()->getDataClearEmail()) {
68
+				$viewConfirm = false;
69
+			}
70
+
71
+			// Render
72
+			$this->setTemplate("view-request/not-confirmed.tpl");
73
+			$this->assign("requestId", $request->getId());
74
+			$this->assign("requestVersion", $request->getUpdateVersion());
75
+			$this->assign('canViewConfirmButton', $viewConfirm);
76
+
77
+			// Make sure to return, to prevent the leaking of other information.
78
+			return;
79
+		}
80
+
81
+		$this->setupBasicData($request, $config);
82
+
83
+		$this->setupUsernameData($request);
84
+
85
+		$this->setupTitle($request);
86
+
87
+		$this->setupReservationDetails($request->getReserved(), $database, $currentUser);
88
+		$this->setupGeneralData($database);
89
+
90
+		$this->assign('requestDataCleared', false);
91
+		if ($request->getEmail() === $this->getSiteConfiguration()->getDataClearEmail()) {
92
+			$this->assign('requestDataCleared', true);
93
+		}
94
+
95
+		$allowedPrivateData = $this->isAllowedPrivateData($request, $currentUser);
96
+
97
+		$this->setupCreationTypes($currentUser);
98
+
99
+		$this->setupLogData($request, $database, $allowedPrivateData);
100
+
101
+		$this->addJs("/api.php?action=templates&targetVariable=templateconfirms");
102
+
103
+		$this->assign('showRevealLink', false);
104
+		if ($request->getReserved() === $currentUser->getId() ||
105
+			$this->barrierTest('alwaysSeeHash', $currentUser, 'RequestData')
106
+		) {
107
+			$this->assign('showRevealLink', true);
108
+			$this->assign('revealHash', $request->getRevealHash());
109
+		}
110
+
111
+		$this->assign('canSeeRelatedRequests', false);
112
+		if ($allowedPrivateData || $this->barrierTest('seeRelatedRequests', $currentUser, 'RequestData')) {
113
+			$this->setupRelatedRequests($request, $config, $database);
114
+		}
115
+
116
+		$this->assign('canCreateLocalAccount', $this->barrierTest('createLocalAccount', $currentUser, 'RequestData'));
117
+
118
+		$closureDate = $request->getClosureDate();
119
+		$date = new DateTime();
120
+		$date->modify("-7 days");
121
+		if ($request->getStatus() == "Closed" && $closureDate < $date) {
122
+			$this->assign('isOldRequest', true);
123
+		}
124
+		$this->assign('canResetOldRequest', $this->barrierTest('reopenOldRequest', $currentUser, 'RequestData'));
125
+		$this->assign('canResetPurgedRequest', $this->barrierTest('reopenClearedRequest', $currentUser, 'RequestData'));
126
+
127
+		$this->assign('requestEmailSent', $request->getEmailSent());
128
+
129
+		if ($allowedPrivateData) {
130
+			$this->assign('manualCreationUrl', $this->getCreationUrl($domain));
131
+
132
+			$this->setTemplate('view-request/main-with-data.tpl');
133
+			$this->setupPrivateData($request, $config);
134
+			$this->assign('canSetBan', $this->barrierTest('set', $currentUser, PageBan::class));
135
+			$this->assign('canSeeCheckuserData', $this->barrierTest('seeUserAgentData', $currentUser, 'RequestData'));
136
+
137
+			if ($this->barrierTest('seeUserAgentData', $currentUser, 'RequestData')) {
138
+				$this->setTemplate('view-request/main-with-checkuser-data.tpl');
139
+				$this->setupCheckUserData($request);
140
+			}
141
+		}
142
+		else {
143
+			$this->setTemplate('view-request/main.tpl');
144
+		}
145
+	}
146
+
147
+	/**
148
+	 * @param Request $request
149
+	 */
150
+	protected function setupTitle(Request $request)
151
+	{
152
+		$statusSymbol = self::STATUS_SYMBOL_OPEN;
153
+		if ($request->getStatus() === RequestStatus::CLOSED) {
154
+			if ($request->getWasCreated()) {
155
+				$statusSymbol = self::STATUS_SYMBOL_ACCEPTED;
156
+			}
157
+			else {
158
+				$statusSymbol = self::STATUS_SYMBOL_REJECTED;
159
+			}
160
+		}
161
+
162
+		$this->setHtmlTitle($statusSymbol . ' #' . $request->getId());
163
+	}
164
+
165
+	/**
166
+	 * Sets up data unrelated to the request, such as the email template information
167
+	 *
168
+	 * @param PdoDatabase $database
169
+	 */
170
+	protected function setupGeneralData(PdoDatabase $database)
171
+	{
172
+		$this->assign('createAccountReason', 'Requested account at [[WP:ACC]], request #');
173
+
174
+		// FIXME: domains
175
+		/** @var Domain $domain */
176
+		$domain = Domain::getById(1, $database);
177
+		$this->assign('defaultRequestState', RequestQueue::getDefaultQueue($database, 1)->getApiName());
178
+		$this->assign('activeRequestQueues', RequestQueue::getEnabledQueues($database));
179
+
180
+		/** @var EmailTemplate $createdTemplate */
181
+		$createdTemplate = EmailTemplate::getById($domain->getDefaultClose(), $database);
182
+
183
+		$this->assign('createdHasJsQuestion', $createdTemplate->getJsquestion() != '');
184
+		$this->assign('createdId', $createdTemplate->getId());
185
+		$this->assign('createdName', $createdTemplate->getName());
186
+
187
+		$preferenceManager = PreferenceManager::getForCurrent($database);
188
+		$skipJsAborts = $preferenceManager->getPreference(PreferenceManager::PREF_SKIP_JS_ABORT);
189
+		$preferredCreationMode = (int)$preferenceManager->getPreference(PreferenceManager::PREF_CREATION_MODE);
190
+		$this->assign('skipJsAborts', $skipJsAborts);
191
+		$this->assign('preferredCreationMode', $preferredCreationMode);
192
+
193
+		$createReasons = EmailTemplate::getActiveNonpreloadTemplates(
194
+			EmailTemplate::ACTION_CREATED,
195
+			$database,
196
+			$domain->getId(),
197
+			$domain->getDefaultClose());
198
+		$this->assign("createReasons", $createReasons);
199
+
200
+		$declineReasons = EmailTemplate::getActiveNonpreloadTemplates(
201
+			EmailTemplate::ACTION_NOT_CREATED,
202
+			$database,
203
+			$domain->getId());
204
+		$this->assign("declineReasons", $declineReasons);
205
+
206
+		$allCreateReasons = EmailTemplate::getAllActiveTemplates(
207
+			EmailTemplate::ACTION_CREATED,
208
+			$database,
209
+			$domain->getId());
210
+		$this->assign("allCreateReasons", $allCreateReasons);
211
+
212
+		$allDeclineReasons = EmailTemplate::getAllActiveTemplates(
213
+			EmailTemplate::ACTION_NOT_CREATED,
214
+			$database,
215
+			$domain->getId());
216
+		$this->assign("allDeclineReasons", $allDeclineReasons);
217
+
218
+		$allOtherReasons = EmailTemplate::getAllActiveTemplates(
219
+			false,
220
+			$database,
221
+			$domain->getId());
222
+		$this->assign("allOtherReasons", $allOtherReasons);
223
+	}
224
+
225
+	private function setupLogData(Request $request, PdoDatabase $database, bool $allowedPrivateData)
226
+	{
227
+		$currentUser = User::getCurrent($database);
228
+
229
+		$logs = LogHelper::getRequestLogsWithComments($request->getId(), $database, $this->getSecurityManager());
230
+		$requestLogs = array();
231
+
232
+		/** @var User[] $nameCache */
233
+		$nameCache = array();
234
+
235
+		$editableComments = $this->barrierTest('editOthers', $currentUser, PageEditComment::class);
236
+
237
+		$canFlag = $this->barrierTest(RoleConfigurationBase::MAIN, $currentUser, PageFlagComment::class);
238
+		$canUnflag = $this->barrierTest('unflag', $currentUser, PageFlagComment::class);
239
+
240
+		/** @var Log|Comment $entry */
241
+		foreach ($logs as $entry) {
242
+			// both log and comment have a 'user' field
243
+			if (!array_key_exists($entry->getUser(), $nameCache)) {
244
+				$entryUser = User::getById($entry->getUser(), $database);
245
+				$nameCache[$entry->getUser()] = $entryUser;
246
+			}
247
+
248
+			if ($entry instanceof Comment) {
249
+				// Determine if the comment contains private information.
250
+				// Private defined as flagged or restricted visibility, but only when the user isn't allowed
251
+				// to see private data
252
+				$commentIsRestricted =
253
+					($entry->getFlagged()
254
+						|| $entry->getVisibility() == 'admin' || $entry->getVisibility() == 'checkuser')
255
+					&& !$allowedPrivateData;
256
+
257
+				// Only allow comment editing if the user is able to edit comments or this is the user's own comment,
258
+				// but only when they're allowed to see the comment itself.
259
+				$commentIsEditable = ($editableComments || $entry->getUser() == $currentUser->getId())
260
+					&& !$commentIsRestricted;
261
+
262
+				// Flagging/unflagging can only be done if you can see the comment
263
+				$canFlagThisComment = $canFlag
264
+					&& (
265
+						(!$entry->getFlagged() && !$commentIsRestricted)
266
+						|| ($entry->getFlagged() && $canUnflag && $commentIsEditable)
267
+					);
268
+
269
+				$requestLogs[] = array(
270
+					'type'          => 'comment',
271
+					'security'      => $entry->getVisibility(),
272
+					'user'          => $entry->getVisibility() == 'requester' ? $request->getName() : $nameCache[$entry->getUser()]->getUsername(),
273
+					'userid'        => $entry->getUser() == -1 ? null : $entry->getUser(),
274
+					'entry'         => null,
275
+					'time'          => $entry->getTime(),
276
+					'canedit'       => $commentIsEditable,
277
+					'id'            => $entry->getId(),
278
+					'comment'       => $entry->getComment(),
279
+					'flagged'       => $entry->getFlagged(),
280
+					'canflag'       => $canFlagThisComment,
281
+					'updateversion' => $entry->getUpdateVersion(),
282
+					'edited'        => $entry->getEdited(),
283
+					'hidden'        => $commentIsRestricted
284
+				);
285
+			}
286
+
287
+			if ($entry instanceof Log) {
288
+				$invalidUserId = $entry->getUser() === -1 || $entry->getUser() === 0;
289
+				$entryUser = $invalidUserId ? User::getCommunity() : $nameCache[$entry->getUser()];
290
+
291
+				$entryComment = $entry->getComment();
292
+
293
+				if ($entry->getAction() === 'JobIssueRequest' || $entry->getAction() === 'JobCompletedRequest') {
294
+					$data = unserialize($entry->getComment());
295
+					/** @var JobQueue $job */
296
+					$job = JobQueue::getById($data['job'], $database);
297
+					$requestLogs[] = array(
298
+						'type'     => 'joblog',
299
+						'security' => 'user',
300
+						'userid'   => $entry->getUser() == -1 ? null : $entry->getUser(),
301
+						'user'     => $entryUser->getUsername(),
302
+						'entry'    => LogHelper::getLogDescription($entry),
303
+						'time'     => $entry->getTimestamp(),
304
+						'canedit'  => false,
305
+						'id'       => $entry->getId(),
306
+						'jobId'    => $job->getId(),
307
+						'jobDesc'  => JobQueue::getTaskDescriptions()[$job->getTask()],
308
+					);
309
+				}
310
+				else {
311
+					$requestLogs[] = array(
312
+						'type'     => 'log',
313
+						'security' => 'user',
314
+						'userid'   => $entry->getUser() == -1 ? null : $entry->getUser(),
315
+						'user'     => $entryUser->getUsername(),
316
+						'entry'    => LogHelper::getLogDescription($entry),
317
+						'time'     => $entry->getTimestamp(),
318
+						'canedit'  => false,
319
+						'id'       => $entry->getId(),
320
+						'comment'  => $entryComment,
321
+					);
322
+				}
323
+			}
324
+		}
325
+
326
+		$this->addJs("/api.php?action=users&targetVariable=typeaheaddata");
327
+
328
+		$this->assign("requestLogs", $requestLogs);
329
+	}
330
+
331
+	/**
332
+	 * @param Request $request
333
+	 */
334
+	protected function setupUsernameData(Request $request)
335
+	{
336
+		$blacklistData = $this->getBlacklistHelper()->isBlacklisted($request->getName());
337
+
338
+		$this->assign('requestIsBlacklisted', $blacklistData !== false);
339
+		$this->assign('requestBlacklist', $blacklistData);
340
+
341
+		try {
342
+			$spoofs = $this->getAntiSpoofProvider()->getSpoofs($request->getName());
343
+		}
344
+		catch (Exception $ex) {
345
+			$spoofs = $ex->getMessage();
346
+		}
347
+
348
+		$this->assign("spoofs", $spoofs);
349
+	}
350
+
351
+	private function setupCreationTypes(User $user)
352
+	{
353
+		$this->assign('allowWelcomeSkip', false);
354
+		$this->assign('forceWelcomeSkip', false);
355
+
356
+		$database = $this->getDatabase();
357
+		$preferenceManager = PreferenceManager::getForCurrent($database);
358
+
359
+		$oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
360
+
361
+		$welcomeTemplate = $preferenceManager->getPreference(PreferenceManager::PREF_WELCOMETEMPLATE);
362
+
363
+		if ($welcomeTemplate != null) {
364
+			$this->assign('allowWelcomeSkip', true);
365
+
366
+			if (!$oauth->canWelcome()) {
367
+				$this->assign('forceWelcomeSkip', true);
368
+			}
369
+		}
370
+
371
+		// test credentials
372
+		$canManualCreate = $this->barrierTest(PreferenceManager::CREATION_MANUAL, $user, 'RequestCreation');
373
+		$canOauthCreate = $this->barrierTest(PreferenceManager::CREATION_OAUTH, $user, 'RequestCreation');
374
+		$canBotCreate = $this->barrierTest(PreferenceManager::CREATION_BOT, $user, 'RequestCreation');
375
+
376
+		$this->assign('canManualCreate', $canManualCreate);
377
+		$this->assign('canOauthCreate', $canOauthCreate);
378
+		$this->assign('canBotCreate', $canBotCreate);
379
+
380
+		// show/hide the type radio buttons
381
+		$creationHasChoice = count(array_filter([$canManualCreate, $canOauthCreate, $canBotCreate])) > 1;
382
+
383
+		$creationModePreference = $preferenceManager->getPreference(PreferenceManager::PREF_CREATION_MODE);
384
+		if (!$this->barrierTest($creationModePreference, $user, 'RequestCreation')) {
385
+			// user is not allowed to use their default. Force a choice.
386
+			$creationHasChoice = true;
387
+		}
388
+
389
+		$this->assign('creationHasChoice', $creationHasChoice);
390
+
391
+		// determine problems in creation types
392
+		$this->assign('botProblem', false);
393
+		if ($canBotCreate && $this->getSiteConfiguration()->getCreationBotPassword() === null) {
394
+			$this->assign('botProblem', true);
395
+		}
396
+
397
+		$this->assign('oauthProblem', false);
398
+		if ($canOauthCreate && !$oauth->canCreateAccount()) {
399
+			$this->assign('oauthProblem', true);
400
+		}
401
+	}
402
+
403
+	private function getCreationUrl(Domain $domain): string
404
+	{
405
+		$template = $this->getSiteConfiguration()->getCreateAccountLink();
406
+
407
+		$template = str_replace('{articlePath}', $domain->getWikiArticlePath(), $template);
408
+		$template = str_replace('{wikiId}', $domain->getShortName(), $template);
409
+
410
+		return $template;
411
+	}
412 412
 }
Please login to merge, or discard this patch.
includes/Pages/PageExpandedRequestList.php 1 patch
Indentation   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -18,59 +18,59 @@
 block discarded – undo
18 18
 
19 19
 class PageExpandedRequestList extends InternalPageBase
20 20
 {
21
-    use RequestListData;
21
+	use RequestListData;
22 22
 
23
-    /**
24
-     * Main function for this page, when no specific actions are called.
25
-     * @return void
26
-     * @todo This is very similar to the PageMain code, we could probably generalise this somehow
27
-     */
28
-    protected function main()
29
-    {
30
-        if (WebRequest::getString('queue') === null) {
31
-            $this->redirect('');
32
-            return;
33
-        }
23
+	/**
24
+	 * Main function for this page, when no specific actions are called.
25
+	 * @return void
26
+	 * @todo This is very similar to the PageMain code, we could probably generalise this somehow
27
+	 */
28
+	protected function main()
29
+	{
30
+		if (WebRequest::getString('queue') === null) {
31
+			$this->redirect('');
32
+			return;
33
+		}
34 34
 
35
-        $database = $this->getDatabase();
35
+		$database = $this->getDatabase();
36 36
 
37
-        // FIXME: domains
38
-        $queue = RequestQueue::getByApiName($database, WebRequest::getString('queue'), 1);
37
+		// FIXME: domains
38
+		$queue = RequestQueue::getByApiName($database, WebRequest::getString('queue'), 1);
39 39
 
40
-        if ($queue === false) {
41
-            $this->redirect('');
42
-            return;
43
-        }
40
+		if ($queue === false) {
41
+			$this->redirect('');
42
+			return;
43
+		}
44 44
 
45
-        /** @var SiteConfiguration $config */
46
-        $config = $this->getSiteConfiguration();
45
+		/** @var SiteConfiguration $config */
46
+		$config = $this->getSiteConfiguration();
47 47
 
48
-        $this->assignCSRFToken();
48
+		$this->assignCSRFToken();
49 49
 
50
-        $this->assign('queuehelp', $queue->getHelp());
50
+		$this->assign('queuehelp', $queue->getHelp());
51 51
 
52
-        // FIXME: domains
53
-        $search = RequestSearchHelper::get($database, 1);
54
-        $search->byStatus(RequestStatus::OPEN);
52
+		// FIXME: domains
53
+		$search = RequestSearchHelper::get($database, 1);
54
+		$search->byStatus(RequestStatus::OPEN);
55 55
 
56
-        list($defaultSort, $defaultSortDirection) = WebRequest::requestListDefaultSort();
57
-        $this->assign('defaultSort', $defaultSort);
58
-        $this->assign('defaultSortDirection', $defaultSortDirection);
56
+		list($defaultSort, $defaultSortDirection) = WebRequest::requestListDefaultSort();
57
+		$this->assign('defaultSort', $defaultSort);
58
+		$this->assign('defaultSortDirection', $defaultSortDirection);
59 59
 
60
-        if ($config->getEmailConfirmationEnabled()) {
61
-            $search->withConfirmedEmail();
62
-        }
60
+		if ($config->getEmailConfirmationEnabled()) {
61
+			$search->withConfirmedEmail();
62
+		}
63 63
 
64
-        $queuesById = [$queue->getId() => $queue];
65
-        $requestsByQueue = $search->fetchByQueue(array_keys($queuesById));
66
-        $requestData = $requestsByQueue[$queue->getId()];
64
+		$queuesById = [$queue->getId() => $queue];
65
+		$requestsByQueue = $search->fetchByQueue(array_keys($queuesById));
66
+		$requestData = $requestsByQueue[$queue->getId()];
67 67
 
68
-        $this->assign('requests', $this->prepareRequestData($requestData['data']));
69
-        $this->assign('totalRequests', $requestData['count']);
70
-        $this->assign('header', $queue->getHeader());
71
-        $this->assign('requestLimitShowOnly', $config->getMiserModeLimit());
68
+		$this->assign('requests', $this->prepareRequestData($requestData['data']));
69
+		$this->assign('totalRequests', $requestData['count']);
70
+		$this->assign('header', $queue->getHeader());
71
+		$this->assign('requestLimitShowOnly', $config->getMiserModeLimit());
72 72
 
73
-        $this->setHtmlTitle('{$header|escape}{if $totalRequests > 0} [{$totalRequests|escape}]{/if}');
74
-        $this->setTemplate('mainpage/expandedrequestlist.tpl');
75
-    }
73
+		$this->setHtmlTitle('{$header|escape}{if $totalRequests > 0} [{$totalRequests|escape}]{/if}');
74
+		$this->setTemplate('mainpage/expandedrequestlist.tpl');
75
+	}
76 76
 }
Please login to merge, or discard this patch.
includes/Pages/PageFlagComment.php 2 patches
Indentation   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -19,67 +19,67 @@
 block discarded – undo
19 19
 
20 20
 class PageFlagComment extends InternalPageBase
21 21
 {
22
-    /**
23
-     * @inheritDoc
24
-     */
25
-    protected function main()
26
-    {
27
-        if (!WebRequest::wasPosted()) {
28
-            throw new ApplicationLogicException('This page does not support GET methods.');
29
-        }
22
+	/**
23
+	 * @inheritDoc
24
+	 */
25
+	protected function main()
26
+	{
27
+		if (!WebRequest::wasPosted()) {
28
+			throw new ApplicationLogicException('This page does not support GET methods.');
29
+		}
30 30
 
31
-        $this->validateCSRFToken();
31
+		$this->validateCSRFToken();
32 32
 
33
-        $flagState = WebRequest::postInt('flag');
34
-        $commentId = WebRequest::postInt('comment');
35
-        $updateVersion = WebRequest::postInt('updateversion');
33
+		$flagState = WebRequest::postInt('flag');
34
+		$commentId = WebRequest::postInt('comment');
35
+		$updateVersion = WebRequest::postInt('updateversion');
36 36
 
37
-        if ($flagState !== 0 && $flagState !== 1) {
38
-            throw new ApplicationLogicException('Flag status not valid');
39
-        }
37
+		if ($flagState !== 0 && $flagState !== 1) {
38
+			throw new ApplicationLogicException('Flag status not valid');
39
+		}
40 40
 
41
-        $database = $this->getDatabase();
41
+		$database = $this->getDatabase();
42 42
 
43
-        /** @var Comment|false $comment */
44
-        $comment = Comment::getById($commentId, $database);
45
-        if ($comment === false) {
46
-            throw new ApplicationLogicException('Unknown comment');
47
-        }
43
+		/** @var Comment|false $comment */
44
+		$comment = Comment::getById($commentId, $database);
45
+		if ($comment === false) {
46
+			throw new ApplicationLogicException('Unknown comment');
47
+		}
48 48
 
49
-        $currentUser = User::getCurrent($database);
49
+		$currentUser = User::getCurrent($database);
50 50
 
51
-        if ($comment->getFlagged() && !$this->barrierTest('unflag', $currentUser)) {
52
-            // user isn't allowed to unflag comments
53
-            throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
54
-        }
51
+		if ($comment->getFlagged() && !$this->barrierTest('unflag', $currentUser)) {
52
+			// user isn't allowed to unflag comments
53
+			throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
54
+		}
55 55
 
56
-        /** @var Request $request */
57
-        $request = Request::getById($comment->getRequest(), $database);
56
+		/** @var Request $request */
57
+		$request = Request::getById($comment->getRequest(), $database);
58 58
 
59
-        if ($comment->getFlagged()
60
-            && !$this->barrierTest('alwaysSeePrivateData', $currentUser, 'RequestData')
61
-            && $request->getReserved() !== $currentUser->getId()
62
-        ) {
63
-            // can't unflag if you can't see it.
64
-            throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
65
-        }
59
+		if ($comment->getFlagged()
60
+			&& !$this->barrierTest('alwaysSeePrivateData', $currentUser, 'RequestData')
61
+			&& $request->getReserved() !== $currentUser->getId()
62
+		) {
63
+			// can't unflag if you can't see it.
64
+			throw new AccessDeniedException($this->getSecurityManager(), $this->getDomainAccessManager());
65
+		}
66 66
 
67
-        $comment->setFlagged($flagState == 1);
68
-        $comment->setUpdateVersion($updateVersion);
69
-        $comment->save();
67
+		$comment->setFlagged($flagState == 1);
68
+		$comment->setUpdateVersion($updateVersion);
69
+		$comment->save();
70 70
 
71
-        if ($flagState === 1) {
72
-            Logger::flaggedComment($database, $comment, $request->getDomain());
73
-        }
74
-        else {
75
-            Logger::unflaggedComment($database, $comment, $request->getDomain());
76
-        }
71
+		if ($flagState === 1) {
72
+			Logger::flaggedComment($database, $comment, $request->getDomain());
73
+		}
74
+		else {
75
+			Logger::unflaggedComment($database, $comment, $request->getDomain());
76
+		}
77 77
 
78
-        if (WebRequest::postString('return') == 'list') {
79
-            $this->redirect('flaggedComments');
80
-        }
81
-        else {
82
-            $this->redirect('viewRequest', null, ['id' => $comment->getRequest()]);
83
-        }
84
-    }
78
+		if (WebRequest::postString('return') == 'list') {
79
+			$this->redirect('flaggedComments');
80
+		}
81
+		else {
82
+			$this->redirect('viewRequest', null, ['id' => $comment->getRequest()]);
83
+		}
84
+	}
85 85
 }
86 86
\ No newline at end of file
Please login to merge, or discard this patch.
Braces   +2 added lines, -4 removed lines patch added patch discarded remove patch
@@ -70,15 +70,13 @@
 block discarded – undo
70 70
 
71 71
         if ($flagState === 1) {
72 72
             Logger::flaggedComment($database, $comment, $request->getDomain());
73
-        }
74
-        else {
73
+        } else {
75 74
             Logger::unflaggedComment($database, $comment, $request->getDomain());
76 75
         }
77 76
 
78 77
         if (WebRequest::postString('return') == 'list') {
79 78
             $this->redirect('flaggedComments');
80
-        }
81
-        else {
79
+        } else {
82 80
             $this->redirect('viewRequest', null, ['id' => $comment->getRequest()]);
83 81
         }
84 82
     }
Please login to merge, or discard this patch.
includes/Pages/PageLog.php 2 patches
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -44,8 +44,7 @@
 block discarded – undo
44 44
             $userObj = User::getByUsername($filterUser, $database);
45 45
             if ($userObj !== false) {
46 46
                 $logSearch->byUser($userObj->getId());
47
-            }
48
-            else {
47
+            } else {
49 48
                 $logSearch->byUser(-1);
50 49
             }
51 50
         }
Please login to merge, or discard this patch.
Indentation   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -18,64 +18,64 @@
 block discarded – undo
18 18
 
19 19
 class PageLog extends PagedInternalPageBase
20 20
 {
21
-    /**
22
-     * Main function for this page, when no specific actions are called.
23
-     */
24
-    protected function main()
25
-    {
26
-        $this->setHtmlTitle('Logs');
27
-
28
-        $filterUser = WebRequest::getString('filterUser');
29
-        $filterAction = WebRequest::getString('filterAction');
30
-        $filterObjectType = WebRequest::getString('filterObjectType');
31
-        $filterObjectId = WebRequest::getInt('filterObjectId');
32
-
33
-        $database = $this->getDatabase();
34
-
35
-        if (!array_key_exists($filterObjectType, LogHelper::getObjectTypes())) {
36
-            $filterObjectType = null;
37
-        }
38
-
39
-        $this->addJs("/api.php?action=users&all=true&targetVariable=typeaheaddata");
40
-
41
-        // FIXME: domains
42
-        $logSearch = LogSearchHelper::get($database, 1);
43
-
44
-        if ($filterUser !== null) {
45
-            $userObj = User::getByUsername($filterUser, $database);
46
-            if ($userObj !== false) {
47
-                $logSearch->byUser($userObj->getId());
48
-            }
49
-            else {
50
-                $logSearch->byUser(-1);
51
-            }
52
-        }
53
-        if ($filterAction !== null) {
54
-            $logSearch->byAction($filterAction);
55
-        }
56
-        if ($filterObjectType !== null) {
57
-            $logSearch->byObjectType($filterObjectType);
58
-        }
59
-        if ($filterObjectId !== null) {
60
-            $logSearch->byObjectId($filterObjectId);
61
-        }
62
-
63
-        $this->setSearchHelper($logSearch);
64
-        $this->setupLimits();
65
-
66
-        /** @var Log[] $logs */
67
-        $logs = $logSearch->getRecordCount($count)->fetch();
68
-
69
-        list($users, $logData) = LogHelper::prepareLogsForTemplate($logs, $database, $this->getSiteConfiguration(), $this->getSecurityManager());
70
-
71
-        $this->setupPageData($count, array('filterUser' => $filterUser, 'filterAction' => $filterAction, 'filterObjectType' => $filterObjectType, 'filterObjectId' => $filterObjectId));
72
-
73
-        $this->assign("logs", $logData);
74
-        $this->assign("users", $users);
75
-
76
-        $this->assign('allLogActions', LogHelper::getLogActions($this->getDatabase()));
77
-        $this->assign('allObjectTypes', LogHelper::getObjectTypes());
78
-
79
-        $this->setTemplate("logs/main.tpl");
80
-    }
21
+	/**
22
+	 * Main function for this page, when no specific actions are called.
23
+	 */
24
+	protected function main()
25
+	{
26
+		$this->setHtmlTitle('Logs');
27
+
28
+		$filterUser = WebRequest::getString('filterUser');
29
+		$filterAction = WebRequest::getString('filterAction');
30
+		$filterObjectType = WebRequest::getString('filterObjectType');
31
+		$filterObjectId = WebRequest::getInt('filterObjectId');
32
+
33
+		$database = $this->getDatabase();
34
+
35
+		if (!array_key_exists($filterObjectType, LogHelper::getObjectTypes())) {
36
+			$filterObjectType = null;
37
+		}
38
+
39
+		$this->addJs("/api.php?action=users&all=true&targetVariable=typeaheaddata");
40
+
41
+		// FIXME: domains
42
+		$logSearch = LogSearchHelper::get($database, 1);
43
+
44
+		if ($filterUser !== null) {
45
+			$userObj = User::getByUsername($filterUser, $database);
46
+			if ($userObj !== false) {
47
+				$logSearch->byUser($userObj->getId());
48
+			}
49
+			else {
50
+				$logSearch->byUser(-1);
51
+			}
52
+		}
53
+		if ($filterAction !== null) {
54
+			$logSearch->byAction($filterAction);
55
+		}
56
+		if ($filterObjectType !== null) {
57
+			$logSearch->byObjectType($filterObjectType);
58
+		}
59
+		if ($filterObjectId !== null) {
60
+			$logSearch->byObjectId($filterObjectId);
61
+		}
62
+
63
+		$this->setSearchHelper($logSearch);
64
+		$this->setupLimits();
65
+
66
+		/** @var Log[] $logs */
67
+		$logs = $logSearch->getRecordCount($count)->fetch();
68
+
69
+		list($users, $logData) = LogHelper::prepareLogsForTemplate($logs, $database, $this->getSiteConfiguration(), $this->getSecurityManager());
70
+
71
+		$this->setupPageData($count, array('filterUser' => $filterUser, 'filterAction' => $filterAction, 'filterObjectType' => $filterObjectType, 'filterObjectId' => $filterObjectId));
72
+
73
+		$this->assign("logs", $logData);
74
+		$this->assign("users", $users);
75
+
76
+		$this->assign('allLogActions', LogHelper::getLogActions($this->getDatabase()));
77
+		$this->assign('allObjectTypes', LogHelper::getObjectTypes());
78
+
79
+		$this->setTemplate("logs/main.tpl");
80
+	}
81 81
 }
Please login to merge, or discard this patch.
includes/Pages/PageListFlaggedComments.php 2 patches
Braces   +5 added lines, -10 removed lines patch added patch discarded remove patch
@@ -61,28 +61,23 @@
 block discarded – undo
61 61
 
62 62
                 if ($request->getReserved() === $currentUser->getId()) {
63 63
                     $data['hiddenText'] = false;
64
-                }
65
-                else {
64
+                } else {
66 65
                     $data['hiddenText'] = true;
67 66
                 }
68 67
             }
69 68
 
70 69
             if ($object->getVisibility() == 'requester' || $object->getVisibility() == 'user') {
71 70
                 $data['hidden'] = false;
72
-            }
73
-            elseif ($object->getVisibility() == 'admin') {
71
+            } elseif ($object->getVisibility() == 'admin') {
74 72
                 if ($seeRestrictedComments) {
75 73
                     $data['hidden'] = false;
76
-                }
77
-                else {
74
+                } else {
78 75
                     $data['hidden'] = true;
79 76
                 }
80
-            }
81
-            elseif ($object->getVisibility() == 'checkuser') {
77
+            } elseif ($object->getVisibility() == 'checkuser') {
82 78
                 if ($seeCheckuserComments) {
83 79
                     $data['hidden'] = false;
84
-                }
85
-                else {
80
+                } else {
86 81
                     $data['hidden'] = true;
87 82
                 }
88 83
             }
Please login to merge, or discard this patch.
Indentation   +108 added lines, -108 removed lines patch added patch discarded remove patch
@@ -18,112 +18,112 @@
 block discarded – undo
18 18
 
19 19
 class PageListFlaggedComments extends InternalPageBase
20 20
 {
21
-    /**
22
-     * @inheritDoc
23
-     */
24
-    protected function main()
25
-    {
26
-        $this->setHtmlTitle('Flagged comments');
27
-        $this->setTemplate('flagged-comments.tpl');
28
-
29
-        $database = $this->getDatabase();
30
-        $this->assignCSRFToken();
31
-
32
-        /** @var Comment[] $commentObjects */
33
-        $commentObjects = Comment::getFlaggedComments($database, 1); // FIXME: domains
34
-        $comments = [];
35
-
36
-        $currentUser = User::getCurrent($database);
37
-
38
-        $seeRestrictedComments = $this->barrierTest('seeRestrictedComments', $currentUser, 'RequestData');
39
-        $seeCheckuserComments = $this->barrierTest('seeCheckuserComments', $currentUser, 'RequestData');
40
-        $alwaysSeePrivateData = $this->barrierTest('alwaysSeePrivateData', $currentUser, 'RequestData');
41
-
42
-        foreach ($commentObjects as $object) {
43
-            $data = [
44
-                'visibility'    => $object->getVisibility(),
45
-                'hidden'        => false,
46
-                'hiddenText'    => false,
47
-            ];
48
-
49
-            if (!$alwaysSeePrivateData) {
50
-                // tl;dr: This is a stupid configuration, but let's account for it anyway.
51
-                //
52
-                // Flagged comments are treated as private data. If you don't have the privilege
53
-                // RequestData::alwaysSeePrivateData, then we can't show you the content of the comments here.
54
-                // This page is forced to degrade into basically a list of requests, seriously hampering the usefulness
55
-                // of this page. Still, we need to handle the case where we have access to this page, but not access
56
-                // to private data.
57
-                // At the time of writing, this case does not exist in the current role configuration, but for the role
58
-                // configuration to be free of assumptions, we need this code.
59
-
60
-                /** @var Request $request */
61
-                $request = Request::getById($object->getRequest(), $database);
62
-
63
-                if ($request->getReserved() === $currentUser->getId()) {
64
-                    $data['hiddenText'] = false;
65
-                }
66
-                else {
67
-                    $data['hiddenText'] = true;
68
-                }
69
-            }
70
-
71
-            if ($object->getVisibility() == 'requester' || $object->getVisibility() == 'user') {
72
-                $data['hidden'] = false;
73
-            }
74
-            elseif ($object->getVisibility() == 'admin') {
75
-                if ($seeRestrictedComments) {
76
-                    $data['hidden'] = false;
77
-                }
78
-                else {
79
-                    $data['hidden'] = true;
80
-                }
81
-            }
82
-            elseif ($object->getVisibility() == 'checkuser') {
83
-                if ($seeCheckuserComments) {
84
-                    $data['hidden'] = false;
85
-                }
86
-                else {
87
-                    $data['hidden'] = true;
88
-                }
89
-            }
90
-
91
-            $this->copyCommentData($object, $data, $database);
92
-
93
-            $comments[] = $data;
94
-        }
95
-
96
-        $this->assign('comments', $comments);
97
-        $this->assign('seeRestrictedComments', $seeRestrictedComments);
98
-        $this->assign('seeCheckuserComments', $seeCheckuserComments);
99
-
100
-        $this->assign('editOthersComments', $this->barrierTest('editOthers', $currentUser, PageEditComment::class));
101
-        $this->assign('editComments', $this->barrierTest(RoleConfigurationBase::MAIN, $currentUser, PageEditComment::class));
102
-        $this->assign('canUnflag', $this->barrierTest('unflag', $currentUser, PageFlagComment::class) && $this->barrierTest(RoleConfigurationBase::MAIN, $currentUser, PageFlagComment::class));
103
-    }
104
-
105
-    private function copyCommentData(Comment $object, array &$data, PdoDatabase $database): void
106
-    {
107
-        if ($data['hidden']) {
108
-            // All details hidden, so don't copy anything.
109
-            return;
110
-        }
111
-
112
-        /** @var Request $request */
113
-        $request = Request::getById($object->getRequest(), $database);
114
-
115
-        if (!$data['hiddenText']) {
116
-            // Comment text is hidden, but presence of the comment is visible.
117
-            $data['comment'] = $object->getComment();
118
-        }
119
-
120
-        $data['id'] = $object->getId();
121
-        $data['updateversion'] = $object->getUpdateVersion();
122
-        $data['time'] = $object->getTime();
123
-        $data['requestid'] = $object->getRequest();
124
-        $data['request'] = $request->getName();
125
-        $data['requeststatus'] = $request->getStatus();
126
-        $data['userid'] = $object->getUser();
127
-        $data['user'] = User::getById($object->getUser(), $database)->getUsername();
128
-    }
21
+	/**
22
+	 * @inheritDoc
23
+	 */
24
+	protected function main()
25
+	{
26
+		$this->setHtmlTitle('Flagged comments');
27
+		$this->setTemplate('flagged-comments.tpl');
28
+
29
+		$database = $this->getDatabase();
30
+		$this->assignCSRFToken();
31
+
32
+		/** @var Comment[] $commentObjects */
33
+		$commentObjects = Comment::getFlaggedComments($database, 1); // FIXME: domains
34
+		$comments = [];
35
+
36
+		$currentUser = User::getCurrent($database);
37
+
38
+		$seeRestrictedComments = $this->barrierTest('seeRestrictedComments', $currentUser, 'RequestData');
39
+		$seeCheckuserComments = $this->barrierTest('seeCheckuserComments', $currentUser, 'RequestData');
40
+		$alwaysSeePrivateData = $this->barrierTest('alwaysSeePrivateData', $currentUser, 'RequestData');
41
+
42
+		foreach ($commentObjects as $object) {
43
+			$data = [
44
+				'visibility'    => $object->getVisibility(),
45
+				'hidden'        => false,
46
+				'hiddenText'    => false,
47
+			];
48
+
49
+			if (!$alwaysSeePrivateData) {
50
+				// tl;dr: This is a stupid configuration, but let's account for it anyway.
51
+				//
52
+				// Flagged comments are treated as private data. If you don't have the privilege
53
+				// RequestData::alwaysSeePrivateData, then we can't show you the content of the comments here.
54
+				// This page is forced to degrade into basically a list of requests, seriously hampering the usefulness
55
+				// of this page. Still, we need to handle the case where we have access to this page, but not access
56
+				// to private data.
57
+				// At the time of writing, this case does not exist in the current role configuration, but for the role
58
+				// configuration to be free of assumptions, we need this code.
59
+
60
+				/** @var Request $request */
61
+				$request = Request::getById($object->getRequest(), $database);
62
+
63
+				if ($request->getReserved() === $currentUser->getId()) {
64
+					$data['hiddenText'] = false;
65
+				}
66
+				else {
67
+					$data['hiddenText'] = true;
68
+				}
69
+			}
70
+
71
+			if ($object->getVisibility() == 'requester' || $object->getVisibility() == 'user') {
72
+				$data['hidden'] = false;
73
+			}
74
+			elseif ($object->getVisibility() == 'admin') {
75
+				if ($seeRestrictedComments) {
76
+					$data['hidden'] = false;
77
+				}
78
+				else {
79
+					$data['hidden'] = true;
80
+				}
81
+			}
82
+			elseif ($object->getVisibility() == 'checkuser') {
83
+				if ($seeCheckuserComments) {
84
+					$data['hidden'] = false;
85
+				}
86
+				else {
87
+					$data['hidden'] = true;
88
+				}
89
+			}
90
+
91
+			$this->copyCommentData($object, $data, $database);
92
+
93
+			$comments[] = $data;
94
+		}
95
+
96
+		$this->assign('comments', $comments);
97
+		$this->assign('seeRestrictedComments', $seeRestrictedComments);
98
+		$this->assign('seeCheckuserComments', $seeCheckuserComments);
99
+
100
+		$this->assign('editOthersComments', $this->barrierTest('editOthers', $currentUser, PageEditComment::class));
101
+		$this->assign('editComments', $this->barrierTest(RoleConfigurationBase::MAIN, $currentUser, PageEditComment::class));
102
+		$this->assign('canUnflag', $this->barrierTest('unflag', $currentUser, PageFlagComment::class) && $this->barrierTest(RoleConfigurationBase::MAIN, $currentUser, PageFlagComment::class));
103
+	}
104
+
105
+	private function copyCommentData(Comment $object, array &$data, PdoDatabase $database): void
106
+	{
107
+		if ($data['hidden']) {
108
+			// All details hidden, so don't copy anything.
109
+			return;
110
+		}
111
+
112
+		/** @var Request $request */
113
+		$request = Request::getById($object->getRequest(), $database);
114
+
115
+		if (!$data['hiddenText']) {
116
+			// Comment text is hidden, but presence of the comment is visible.
117
+			$data['comment'] = $object->getComment();
118
+		}
119
+
120
+		$data['id'] = $object->getId();
121
+		$data['updateversion'] = $object->getUpdateVersion();
122
+		$data['time'] = $object->getTime();
123
+		$data['requestid'] = $object->getRequest();
124
+		$data['request'] = $request->getName();
125
+		$data['requeststatus'] = $request->getStatus();
126
+		$data['userid'] = $object->getUser();
127
+		$data['user'] = User::getById($object->getUser(), $database)->getUsername();
128
+	}
129 129
 }
130 130
\ No newline at end of file
Please login to merge, or discard this patch.