Passed
Push — master ( becd39...b8b862 )
by MusikAnimal
05:00
created

AutoEditsRepository::getHelper()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file contains only the AutoEditsRepository class.
4
 */
5
6
namespace Xtools;
7
8
use AppBundle\Helper\AutomatedEditsHelper;
9
use DateInterval;
10
use Symfony\Component\Config\Definition\Exception\Exception;
11
12
/**
13
 * AutoEditsRepository is responsible for retrieving data from the database
14
 * about the automated edits made by a user.
15
 * @codeCoverageIgnore
16
 */
17
class AutoEditsRepository extends UserRepository
18
{
19
    /** @var AutomatedEditsHelper Used for fetching the tool list and filtering it. */
20
    private $aeh;
21
22
    /**
23
     * Method to give the repository access to the AutomatedEditsHelper.
24
     */
25
    public function getHelper()
26
    {
27
        if (!isset($this->aeh)) {
28
            $this->aeh = $this->container->get('app.automated_edits_helper');
29
        }
30
        return $this->aeh;
31
    }
32
33
    /**
34
     * Get the number of edits this user made using semi-automated tools.
35
     * @param Project $project
36
     * @param User $user
37
     * @param string|int $namespace Namespace ID or 'all'
38
     * @param string $start Start date in a format accepted by strtotime()
39
     * @param string $end End date in a format accepted by strtotime()
40
     * @return int Result of query, see below.
41
     */
42
    public function countAutomatedEdits(Project $project, User $user, $namespace = 'all', $start = '', $end = '')
43
    {
44
        $cacheKey = $this->getCacheKey(func_get_args(), 'user_autoeditcount');
45
        if ($this->cache->hasItem($cacheKey)) {
46
            return $this->cache->getItem($cacheKey)->get();
47
        }
48
        $this->stopwatch->start($cacheKey, 'XTools');
49
50
        list($condBegin, $condEnd) = $this->getRevTimestampConditions($start, $end);
51
52
        // Get the combined regex and tags for the tools
53
        list($regex, $tags) = $this->getToolRegexAndTags($project);
54
55
        list($pageJoin, $condNamespace) = $this->getPageAndNamespaceSql($project, $namespace);
56
57
        $revisionTable = $project->getTableName('revision');
58
        $tagTable = $project->getTableName('change_tag');
59
        $tagJoin = '';
60
61
        // Build SQL for detecting autoedits via regex and/or tags
62
        $condTools = [];
63
        if ($regex != '') {
64
            $condTools[] = "rev_comment REGEXP $regex";
65
        }
66
        if ($tags != '') {
67
            $tagJoin = $tags != '' ? "LEFT OUTER JOIN $tagTable ON ct_rev_id = rev_id" : '';
68
            $condTools[] = "ct_tag IN ($tags)";
69
        }
70
        $condTool = 'AND (' . implode(' OR ', $condTools) . ')';
71
72
        $sql = "SELECT COUNT(DISTINCT(rev_id))
73
                FROM $revisionTable
74
                $pageJoin
75
                $tagJoin
76
                WHERE rev_user_text = :username
77
                $condTool
78
                $condNamespace
79
                $condBegin
80
                $condEnd";
81
82
        $resultQuery = $this->executeQuery($sql, $user, $namespace, $start, $end);
83
        $result = (int) $resultQuery->fetchColumn();
84
85
        // Cache and return.
86
        $this->stopwatch->stop($cacheKey);
87
        return $this->setCache($cacheKey, $result);
88
    }
89
90
    /**
91
     * Get non-automated contributions for the given user.
92
     * @param Project $project
93
     * @param User $user
94
     * @param string|int $namespace Namespace ID or 'all'
95
     * @param string $start Start date in a format accepted by strtotime()
96
     * @param string $end End date in a format accepted by strtotime()
97
     * @param int $offset Used for pagination, offset results by N edits
98
     * @return string[] Result of query, with columns 'page_title',
99
     *   'page_namespace', 'rev_id', 'timestamp', 'minor',
100
     *   'length', 'length_change', 'comment'
101
     */
102
    public function getNonAutomatedEdits(
103
        Project $project,
104
        User $user,
105
        $namespace = 'all',
106
        $start = '',
107
        $end = '',
108
        $offset = 0
109
    ) {
110
        $cacheKey = $this->getCacheKey(func_get_args(), 'user_nonautoedits');
111
        if ($this->cache->hasItem($cacheKey)) {
112
            return $this->cache->getItem($cacheKey)->get();
113
        }
114
        $this->stopwatch->start($cacheKey, 'XTools');
115
116
        list($condBegin, $condEnd) = $this->getRevTimestampConditions($start, $end, 'revs.');
117
118
        // Get the combined regex and tags for the tools
119
        list($regex, $tags) = $this->getToolRegexAndTags($project);
120
121
        $pageTable = $project->getTableName('page');
122
        $revisionTable = $project->getTableName('revision');
123
        $tagTable = $project->getTableName('change_tag');
124
        $condNamespace = $namespace === 'all' ? '' : 'AND page_namespace = :namespace';
125
        $tagJoin = $tags != '' ? "LEFT OUTER JOIN $tagTable ON (ct_rev_id = revs.rev_id)" : '';
126
        $condTag = $tags != '' ? "AND (ct_tag NOT IN ($tags) OR ct_tag IS NULL)" : '';
127
        $sql = "SELECT
128
                    page_title,
129
                    page_namespace,
130
                    revs.rev_id AS rev_id,
131
                    revs.rev_timestamp AS timestamp,
132
                    revs.rev_minor_edit AS minor,
133
                    revs.rev_len AS length,
134
                    (CAST(revs.rev_len AS SIGNED) - IFNULL(parentrevs.rev_len, 0)) AS length_change,
135
                    revs.rev_comment AS comment
136
                FROM $pageTable
137
                JOIN $revisionTable AS revs ON (page_id = revs.rev_page)
138
                LEFT JOIN $revisionTable AS parentrevs ON (revs.rev_parent_id = parentrevs.rev_id)
139
                $tagJoin
140
                WHERE revs.rev_user_text = :username
141
                AND revs.rev_timestamp > 0
142
                AND revs.rev_comment NOT RLIKE $regex
143
                $condTag
144
                $condBegin
145
                $condEnd
146
                $condNamespace
147
                GROUP BY revs.rev_id
148
                ORDER BY revs.rev_timestamp DESC
149
                LIMIT 50
150
                OFFSET $offset";
151
152
        $resultQuery = $this->executeQuery($sql, $user, $namespace, $start, $end);
153
        $result = $resultQuery->fetchAll();
154
155
        // Cache and return.
156
        $this->stopwatch->stop($cacheKey);
157
        return $this->setCache($cacheKey, $result);
158
    }
159
160
    /**
161
     * Get (semi-)automated contributions for the given user, and optionally for a given tool
162
     * @param Project $project
163
     * @param User $user
164
     * @param string|int $namespace Namespace ID or 'all'
165
     * @param string $start Start date in a format accepted by strtotime()
166
     * @param string $end End date in a format accepted by strtotime()
167
     * @param string|null $tool Only get edits made with this tool. Must match the keys in semi_automated.yml
168
     * @param int $offset Used for pagination, offset results by N edits
169
     * @return string[] Result of query, with columns 'page_title',
170
     *   'page_namespace', 'rev_id', 'timestamp', 'minor',
171
     *   'length', 'length_change', 'comment'
172
     */
173
    public function getAutomatedEdits(
174
        Project $project,
175
        User $user,
176
        $namespace = 'all',
177
        $start = '',
178
        $end = '',
179
        $tool = null,
180
        $offset = 0
181
    ) {
182
        $cacheKey = $this->getCacheKey(func_get_args(), 'user_autoedits');
183
        if ($this->cache->hasItem($cacheKey)) {
184
            return $this->cache->getItem($cacheKey)->get();
185
        }
186
        $this->stopwatch->start($cacheKey, 'XTools');
187
188
        list($condBegin, $condEnd) = $this->getRevTimestampConditions($start, $end, 'revs.');
189
190
        // Get the combined regex and tags for the tools
191
        list($regex, $tags) = $this->getToolRegexAndTags($project, $tool);
192
193
        $pageTable = $project->getTableName('page');
194
        $revisionTable = $project->getTableName('revision');
195
        $tagTable = $project->getTableName('change_tag');
196
        $condNamespace = $namespace === 'all' ? '' : 'AND page_namespace = :namespace';
197
        $tagJoin = $tags != '' ? "LEFT OUTER JOIN $tagTable ON (ct_rev_id = revs.rev_id)" : '';
198
        $condTag = $tags != '' ? "AND (ct_tag NOT IN ($tags) OR ct_tag IS NULL)" : '';
199
        $sql = "SELECT
200
                    page_title,
201
                    page_namespace,
202
                    revs.rev_id AS rev_id,
203
                    revs.rev_timestamp AS timestamp,
204
                    revs.rev_minor_edit AS minor,
205
                    revs.rev_len AS length,
206
                    (CAST(revs.rev_len AS SIGNED) - IFNULL(parentrevs.rev_len, 0)) AS length_change,
207
                    revs.rev_comment AS comment
208
                FROM $pageTable
209
                JOIN $revisionTable AS revs ON (page_id = revs.rev_page)
210
                LEFT JOIN $revisionTable AS parentrevs ON (revs.rev_parent_id = parentrevs.rev_id)
211
                $tagJoin
212
                WHERE revs.rev_user_text = :username
213
                AND revs.rev_timestamp > 0
214
                AND revs.rev_comment RLIKE $regex
215
                $condTag
216
                $condBegin
217
                $condEnd
218
                $condNamespace
219
                GROUP BY revs.rev_id
220
                ORDER BY revs.rev_timestamp DESC
221
                LIMIT 50
222
                OFFSET $offset";
223
224
        $resultQuery = $this->executeQuery($sql, $user, $namespace, $start, $end);
225
        $result = $resultQuery->fetchAll();
226
227
        // Cache and return.
228
        $this->stopwatch->stop($cacheKey);
229
        return $this->setCache($cacheKey, $result);
230
    }
231
232
    /**
233
     * Get counts of known automated tools used by the given user.
234
     * @param Project $project
235
     * @param User $user
236
     * @param string|int $namespace Namespace ID or 'all'.
237
     * @param string $start Start date in a format accepted by strtotime()
238
     * @param string $end End date in a format accepted by strtotime()
239
     * @return string[] Each tool that they used along with the count and link:
240
     *                  [
241
     *                      'Twinkle' => [
242
     *                          'count' => 50,
243
     *                          'link' => 'Wikipedia:Twinkle',
244
     *                      ],
245
     *                  ]
246
     */
247
    public function getToolCounts(
248
        Project $project,
249
        User $user,
250
        $namespace = 'all',
251
        $start = '',
252
        $end = ''
253
    ) {
254
        $cacheKey = $this->getCacheKey(func_get_args(), 'user_autotoolcounts');
255
        if ($this->cache->hasItem($cacheKey)) {
256
            return $this->cache->getItem($cacheKey)->get();
257
        }
258
        $this->stopwatch->start($cacheKey, 'XTools');
259
260
        $sql = $this->getAutomatedCountsSql($project, $namespace, $start, $end);
261
        $resultQuery = $this->executeQuery($sql, $user, $namespace, $start, $end);
262
263
        $tools = $this->getHelper()->getTools($project);
264
265
        // handling results
266
        $results = [];
267
268
        while ($row = $resultQuery->fetch()) {
269
            // Only track tools that they've used at least once
270
            $tool = $row['toolname'];
271
            if ($row['count'] > 0) {
272
                $results[$tool] = [
273
                    'link' => $tools[$tool]['link'],
274
                    'label' => isset($tools[$tool]['label'])
275
                        ? $tools[$tool]['label']
276
                        : $tool,
277
                    'count' => $row['count'],
278
                ];
279
            }
280
        }
281
282
        // Sort the array by count
283
        uasort($results, function ($a, $b) {
284
            return $b['count'] - $a['count'];
285
        });
286
287
        // Cache and return.
288
        $this->stopwatch->stop($cacheKey);
289
        return $this->setCache($cacheKey, $results);
290
    }
291
292
    /**
293
     * Get SQL for getting counts of known automated tools used by the given user.
294
     * @see self::getAutomatedCounts()
295
     * @param Project $project
296
     * @param string|int $namespace Namespace ID or 'all'.
297
     * @param string $start Start date in a format accepted by strtotime()
298
     * @param string $end End date in a format accepted by strtotime()
299
     * @return string The SQL.
300
     */
301
    private function getAutomatedCountsSql(Project $project, $namespace, $start, $end)
302
    {
303
        list($condBegin, $condEnd) = $this->getRevTimestampConditions($start, $end);
304
305
        // Load the semi-automated edit types.
306
        $tools = $this->getHelper()->getTools($project);
307
308
        // Create a collection of queries that we're going to run.
309
        $queries = [];
310
311
        $revisionTable = $project->getTableName('revision');
312
        $tagTable = $project->getTableName('change_tag');
313
314
        list($pageJoin, $condNamespace) = $this->getPageAndNamespaceSql($project, $namespace);
315
316
        $conn = $this->getProjectsConnection();
317
318
        foreach ($tools as $toolname => $values) {
319
            list($condTool, $tagJoin) = $this->getInnerAutomatedCountsSql($tagTable, $values);
0 ignored issues
show
Bug introduced by
$values of type string is incompatible with the type string[] expected by parameter $values of Xtools\AutoEditsReposito...nerAutomatedCountsSql(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

319
            list($condTool, $tagJoin) = $this->getInnerAutomatedCountsSql($tagTable, /** @scrutinizer ignore-type */ $values);
Loading history...
320
321
            $toolname = $conn->quote($toolname, \PDO::PARAM_STR);
322
323
            // Developer error, no regex or tag provided for this tool.
324
            if ($condTool === '') {
325
                throw new Exception("No regex or tag found for the tool $toolname. " .
326
                    "Please verify this entry in semi_automated.yml");
327
            }
328
329
            $queries[] .= "
330
                SELECT $toolname AS toolname, COUNT(rev_id) AS count
331
                FROM $revisionTable
332
                $pageJoin
333
                $tagJoin
334
                WHERE rev_user_text = :username
335
                AND $condTool
336
                $condNamespace
337
                $condBegin
338
                $condEnd";
339
        }
340
341
        // Combine to one big query.
342
        return implode(' UNION ', $queries);
343
    }
344
345
    /**
346
     * Get some of the inner SQL for self::getAutomatedCountsSql().
347
     * @param  string $tagTable Name of the `change_tag` table.
348
     * @param  string[] $values Values as defined in semi_automated.yml
349
     * @return string[] [Equality clause, JOIN clause]
350
     */
351
    private function getInnerAutomatedCountsSql($tagTable, $values)
352
    {
353
        $conn = $this->getProjectsConnection();
354
        $tagJoin = '';
355
        $condTool = '';
356
357
        if (isset($values['regex'])) {
358
            $regex = $conn->quote($values['regex'], \PDO::PARAM_STR);
359
            $condTool = "rev_comment REGEXP $regex";
360
        }
361
        if (isset($values['tag'])) {
362
            $tagJoin = "LEFT OUTER JOIN $tagTable ON ct_rev_id = rev_id";
363
            $tag = $conn->quote($values['tag'], \PDO::PARAM_STR);
364
365
            // Append to regex clause if already present.
366
            // Tags are more reliable but may not be present for edits made with
367
            //   older versions of the tool, before it started adding tags.
368
            if ($condTool === '') {
369
                $condTool = "ct_tag = $tag";
370
            } else {
371
                $condTool = '(' . $condTool . " OR ct_tag = $tag)";
372
            }
373
        }
374
375
        return [$condTool, $tagJoin];
376
    }
377
378
    /**
379
     * Get the combined regex and tags for all semi-automated tools,
380
     * or the given tool, ready to be used in a query.
381
     * @param Project $project
382
     * @param string|null $tool
383
     * @return string[] In the format:
384
     *    ['combined|regex', 'combined,tags']
385
     */
386
    private function getToolRegexAndTags(Project $project, $tool = null)
387
    {
388
        $conn = $this->getProjectsConnection();
389
        $tools = $this->getHelper()->getTools($project);
390
        $regexes = [];
391
        $tags = [];
392
393
        if ($tool != '') {
394
            $tools = [$tools[$tool]];
395
        }
396
397
        foreach ($tools as $tool => $values) {
398
            if (isset($values['regex'])) {
399
                $regexes[] = $values['regex'];
400
            }
401
            if (isset($values['tag'])) {
402
                $tags[] = $conn->quote($values['tag'], \PDO::PARAM_STR);
403
            }
404
        }
405
406
        return [
407
            $conn->quote(implode('|', $regexes), \PDO::PARAM_STR),
408
            implode(',', $tags),
409
        ];
410
    }
411
}
412