Passed
Push — master ( b2964c...05352e )
by MusikAnimal
11:27
created

nonAutomatedEditsAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 5
ccs 0
cts 0
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file contains only the AutomatedEditsController class.
4
 */
5
6
declare(strict_types=1);
7
8
namespace AppBundle\Controller;
9
10
use AppBundle\Helper\I18nHelper;
11
use AppBundle\Model\AutoEdits;
12
use AppBundle\Repository\AutoEditsRepository;
13
use Symfony\Component\DependencyInjection\ContainerInterface;
14
use Symfony\Component\HttpFoundation\JsonResponse;
15
use Symfony\Component\HttpFoundation\RedirectResponse;
16
use Symfony\Component\HttpFoundation\RequestStack;
17
use Symfony\Component\HttpFoundation\Response;
18
use Symfony\Component\Routing\Annotation\Route;
19
20
/**
21
 * This controller serves the AutomatedEdits tool.
22
 */
23
class AutomatedEditsController extends XtoolsController
24
{
25
    /** @var AutoEdits The AutoEdits instance. */
26
    protected $autoEdits;
27
28
    /** @var array Data that is passed to the view. */
29
    private $output;
30
31
    /**
32
     * Get the name of the tool's index route.
33
     * This is also the name of the associated model.
34
     * @return string
35
     * @codeCoverageIgnore
36
     */
37
    public function getIndexRoute(): string
38
    {
39
        return 'AutoEdits';
40
    }
41
42
    /**
43
     * AutomatedEditsController constructor.
44
     * @param RequestStack $requestStack
45
     * @param ContainerInterface $container
46
     * @param I18nHelper $i18n
47
     */
48 1
    public function __construct(RequestStack $requestStack, ContainerInterface $container, I18nHelper $i18n)
49
    {
50
        // This will cause the tool to redirect back to the index page, with an error,
51
        // if the user has too high of an edit count.
52 1
        $this->tooHighEditCountAction = $this->getIndexRoute();
53
54 1
        parent::__construct($requestStack, $container, $i18n);
55 1
    }
56
57
    /**
58
     * Display the search form.
59
     * @Route("/autoedits", name="AutoEdits")
60
     * @Route("/automatededits", name="AutoEditsLong")
61
     * @Route("/autoedits/index.php", name="AutoEditsIndexPhp")
62
     * @Route("/automatededits/index.php", name="AutoEditsLongIndexPhp")
63
     * @Route("/autoedits/{project}", name="AutoEditsProject")
64
     * @return Response
65
     */
66 1
    public function indexAction(): Response
67
    {
68
        // Redirect if at minimum project and username are provided.
69 1
        if (isset($this->params['project']) && isset($this->params['username'])) {
70
            // If 'tool' param is given, redirect to corresponding action.
71
            $tool = $this->request->query->get('tool');
72
73
            if ('all' === $tool) {
74
                unset($this->params['tool']);
75
                return $this->redirectToRoute('AutoEditsContributionsResult', $this->params);
76
            } elseif ('' != $tool && 'none' !== $tool) {
77
                $this->params['tool'] = $tool;
78
                return $this->redirectToRoute('AutoEditsContributionsResult', $this->params);
79
            } elseif ('none' === $tool) {
80
                unset($this->params['tool']);
81
            }
82
83
            // Otherwise redirect to the normal result action.
84
            return $this->redirectToRoute('AutoEditsResult', $this->params);
85
        }
86
87 1
        return $this->render('autoEdits/index.html.twig', array_merge([
88 1
            'xtPageTitle' => 'tool-autoedits',
89
            'xtSubtitle' => 'tool-autoedits-desc',
90
            'xtPage' => 'AutoEdits',
91
92
            // Defaults that will get overridden if in $this->params.
93
            'username' => '',
94
            'namespace' => 0,
95
            'start' => '',
96
            'end' => '',
97 1
        ], $this->params, ['project' => $this->project]));
98
    }
99
100
    /**
101
     * Set defaults, and instantiate the AutoEdits model. This is called at the top of every view action.
102
     * @codeCoverageIgnore
103
     */
104
    private function setupAutoEdits(): void
105
    {
106
        $tool = $this->request->query->get('tool', null);
107
        $useSandbox = (bool)$this->request->query->get('usesandbox', false);
108
109
        if ($useSandbox && !$this->request->getSession()->get('logged_in_user')) {
110
            $this->addFlashMessage('danger', 'auto-edits-logged-out');
111
            $useSandbox = false;
112
        }
113
114
        $autoEditsRepo = new AutoEditsRepository($useSandbox);
115
        $autoEditsRepo->setContainer($this->container);
116
117
        $misconfigured = $autoEditsRepo->getInvalidTools($this->project);
118
        $helpLink = "https://w.wiki/ppr";
119
        foreach ($misconfigured as $tool) {
120
            $this->addFlashMessage('warning', 'auto-edits-misconfiguration', [$tool, $helpLink]);
121
        }
122
123
        // Validate tool.
124
        // FIXME: instead of redirecting to index page, show result page listing all tools for that project,
125
        //  clickable to show edits by the user, etc.
126
        if ($tool && !isset($autoEditsRepo->getTools($this->project)[$tool])) {
127
            $this->throwXtoolsException(
128
                $this->getIndexRoute(),
129
                'auto-edits-unknown-tool',
130
                [$tool],
131
                'tool'
132
            );
133
        }
134
135
        $this->autoEdits = new AutoEdits(
136
            $this->project,
137
            $this->user,
138
            $this->namespace,
139
            $this->start,
140
            $this->end,
141
            $tool,
142
            $this->offset
143
        );
144
        $this->autoEdits->setRepository($autoEditsRepo);
145
146
        $this->output = [
147
            'xtPage' => 'AutoEdits',
148
            'xtTitle' => $this->user->getUsername(),
149
            'ae' => $this->autoEdits,
150
            'is_sub_request' => $this->isSubRequest,
151
        ];
152
    }
153
154
    /**
155
     * Display the results.
156
     * @Route(
157
     *     "/autoedits/{project}/{username}/{namespace}/{start}/{end}", name="AutoEditsResult",
158
     *     requirements={
159
     *         "namespace"="|all|\d+",
160
     *         "start"="|\d{4}-\d{2}-\d{2}",
161
     *         "end"="|\d{4}-\d{2}-\d{2}",
162
     *     },
163
     *     defaults={"namespace"=0, "start"=false, "end"=false}
164
     * )
165
     * @return Response
166
     * @codeCoverageIgnore
167
     */
168
    public function resultAction(): Response
169
    {
170
        // Will redirect back to index if the user has too high of an edit count.
171
        $this->setupAutoEdits();
172
173
        if (in_array('bot', $this->user->getUserRights($this->project))) {
174
            $this->addFlashMessage('warning', 'auto-edits-bot');
175
        }
176
177
        return $this->getFormattedResponse('autoEdits/result', $this->output);
178
    }
179
180
    /**
181
     * Get non-automated edits for the given user.
182
     * @Route(
183
     *   "/nonautoedits-contributions/{project}/{username}/{namespace}/{start}/{end}/{offset}",
184
     *   name="NonAutoEditsContributionsResult",
185
     *   requirements={
186
     *       "namespace"="|all|\d+",
187
     *       "start"="|\d{4}-\d{2}-\d{2}",
188
     *       "end"="|\d{4}-\d{2}-\d{2}",
189
     *       "offset"="\d*"
190
     *   },
191
     *   defaults={"namespace"=0, "start"=false, "end"=false, "offset"=0}
192
     * )
193
     * @return Response|RedirectResponse
194
     * @codeCoverageIgnore
195
     */
196
    public function nonAutomatedEditsAction(): Response
197
    {
198
        $this->setupAutoEdits();
199
200
        return $this->getFormattedResponse('autoEdits/nonautomated_edits', $this->output);
201
    }
202
203
    /**
204
     * Get automated edits for the given user using the given tool.
205
     * @Route(
206
     *   "/autoedits-contributions/{project}/{username}/{namespace}/{start}/{end}/{offset}",
207
     *   name="AutoEditsContributionsResult",
208
     *   requirements={
209
     *       "namespace"="|all|\d+",
210
     *       "start"="|\d{4}-\d{2}-\d{2}",
211
     *       "end"="|\d{4}-\d{2}-\d{2}",
212
     *       "offset"="\d*"
213
     *   },
214
     *   defaults={"namespace"=0, "start"=false, "end"=false, "offset"=0}
215
     * )
216
     * @return Response
217
     * @codeCoverageIgnore
218
     */
219
    public function automatedEditsAction(): Response
220
    {
221
        $this->setupAutoEdits();
222
223
        return $this->getFormattedResponse('autoEdits/automated_edits', $this->output);
224
    }
225
226
    /************************ API endpoints ************************/
227
228
    /**
229
     * Get a list of the automated tools and their regex/tags/etc.
230
     * @Route("/api/user/automated_tools/{project}", name="UserApiAutoEditsTools")
231
     * @Route("/api/project/automated_tools/{project}", name="ProjectApiAutoEditsTools")
232
     * @return JsonResponse
233
     * @codeCoverageIgnore
234
     */
235
    public function automatedToolsApiAction(): JsonResponse
236
    {
237
        $this->recordApiUsage('user/automated_tools');
238
239
        $aeh = $this->container->get('app.automated_edits_helper');
240
        return $this->getFormattedApiResponse($aeh->getTools($this->project));
241
    }
242
243
    /**
244
     * Count the number of automated edits the given user has made.
245
     * @Route(
246
     *   "/api/user/automated_editcount/{project}/{username}/{namespace}/{start}/{end}/{tools}",
247
     *   name="UserApiAutoEditsCount",
248
     *   requirements={
249
     *       "namespace"="|all|\d+",
250
     *       "start"="|\d{4}-\d{2}-\d{2}",
251
     *       "end"="|\d{4}-\d{2}-\d{2}"
252
     *   },
253
     *   defaults={"namespace"="all", "start"=false, "end"=false}
254
     * )
255
     * @param string $tools Non-blank to show which tools were used and how many times.
256
     * @return JsonResponse
257
     * @codeCoverageIgnore
258
     */
259
    public function automatedEditCountApiAction(string $tools = ''): JsonResponse
260
    {
261
        $this->recordApiUsage('user/automated_editcount');
262
263
        $this->setupAutoEdits();
264
265
        $ret = [
266
            'total_editcount' => $this->autoEdits->getEditCount(),
267
            'automated_editcount' => $this->autoEdits->getAutomatedCount(),
268
        ];
269
        $ret['nonautomated_editcount'] = $ret['total_editcount'] - $ret['automated_editcount'];
270
271
        if ('' != $tools) {
272
            $tools = $this->autoEdits->getToolCounts();
273
            $ret['automated_tools'] = $tools;
274
        }
275
276
        return $this->getFormattedApiResponse($ret);
277
    }
278
279
    /**
280
     * Get non-automated edits for the given user.
281
     * @Route(
282
     *   "/api/user/nonautomated_edits/{project}/{username}/{namespace}/{start}/{end}/{offset}",
283
     *   name="UserApiNonAutoEdits",
284
     *   requirements={
285
     *       "namespace"="|all|\d+",
286
     *       "start"="|\d{4}-\d{2}-\d{2}",
287
     *       "end"="|\d{4}-\d{2}-\d{2}",
288
     *       "offset"="\d*"
289
     *   },
290
     *   defaults={"namespace"=0, "start"=false, "end"=false, "offset"=0}
291
     * )
292
     * @return JsonResponse
293
     * @codeCoverageIgnore
294
     */
295
    public function nonAutomatedEditsApiAction(): JsonResponse
296
    {
297
        $this->recordApiUsage('user/nonautomated_edits');
298
299
        $this->setupAutoEdits();
300
301
        $ret = array_map(function ($rev) {
302
            return array_merge([
303
                'full_page_title' => $this->getPageFromNsAndTitle(
304
                    (int)$rev['page_namespace'],
305
                    $rev['page_title'],
306
                    true
307
                ),
308
            ], $rev);
309
        }, $this->autoEdits->getNonAutomatedEdits(true));
310
311
        return $this->getFormattedApiResponse(['nonautomated_edits' => $ret]);
312
    }
313
314
    /**
315
     * Get (semi-)automated edits for the given user, optionally using the given tool.
316
     * @Route(
317
     *   "/api/user/automated_edits/{project}/{username}/{namespace}/{start}/{end}/{offset}",
318
     *   name="UserApiAutoEdits",
319
     *   requirements={
320
     *       "namespace"="|all|\d+",
321
     *       "start"="|\d{4}-\d{2}-\d{2}",
322
     *       "end"="|\d{4}-\d{2}-\d{2}",
323
     *       "offset"="\d*"
324
     *   },
325
     *   defaults={"namespace"=0, "start"=false, "end"=false, "offset"=0}
326
     * )
327
     * @return Response
328
     * @codeCoverageIgnore
329
     */
330
    public function automatedEditsApiAction(): Response
331
    {
332
        $this->recordApiUsage('user/automated_edits');
333
334
        $this->setupAutoEdits();
335
336
        $ret = [];
337
338
        if ($this->autoEdits->getTool()) {
339
            $ret['tool'] = $this->autoEdits->getTool();
340
        }
341
342
        $ret['automated_edits'] = array_map(function ($rev) {
343
            return array_merge([
344
                'full_page_title' => $this->getPageFromNsAndTitle(
345
                    (int)$rev['page_namespace'],
346
                    $rev['page_title'],
347
                    true
348
                ),
349
            ], $rev);
350
        }, $this->autoEdits->getAutomatedEdits(true));
351
352
        return $this->getFormattedApiResponse($ret);
353
    }
354
}
355