Completed
Push — master ( 9a10b7...2f3758 )
by Sam
18:30
created

EditCounterRepository::getMonthCounts()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 30
Code Lines 24

Duplication

Lines 30
Ratio 100 %

Importance

Changes 0
Metric Value
dl 30
loc 30
rs 8.8571
c 0
b 0
f 0
cc 2
eloc 24
nc 2
nop 2
1
<?php
2
3
namespace Xtools;
4
5
use DateInterval;
6
use Mediawiki\Api\SimpleRequest;
7
8
class EditCounterRepository extends Repository
9
{
10
11
    /**
12
     * Get revision counts for the given user.
13
     * @param User $user The user.
14
     * @returns string[] With keys: 'deleted', 'live', 'total', 'first', 'last', '24h', '7d', '30d',
15
     * '365d', 'small', 'large', 'with_comments', and 'minor_edits'.
16
     */
17
    public function getRevisionCounts(Project $project, User $user)
18
    {
19
        // Set up cache.
20
        $cacheKey = 'revisioncounts.' . $project->getDatabaseName() . '.' . $user->getUsername();
21
        if ($this->cache->hasItem($cacheKey)) {
22
            return $this->cache->getItem($cacheKey)->get();
23
        }
24
25
        // Prepare the queries and execute them.
26
        $archiveTable = $this->getTableName($project->getDatabaseName(), 'archive');
27
        $revisionTable = $this->getTableName($project->getDatabaseName(), 'revision');
28
        $queries = [
29
            'deleted' => "SELECT COUNT(ar_id) FROM $archiveTable
30
                WHERE ar_user = :userId",
31
            'live' => "SELECT COUNT(rev_id) FROM $revisionTable
32
                WHERE rev_user = :userId",
33
            'day' => "SELECT COUNT(rev_id) FROM $revisionTable
34
                WHERE rev_user = :userId AND rev_timestamp >= DATE_SUB(NOW(), INTERVAL 1 DAY)",
35
            'week' => "SELECT COUNT(rev_id) FROM $revisionTable
36
                WHERE rev_user = :userId AND rev_timestamp >= DATE_SUB(NOW(), INTERVAL 1 WEEK)",
37
            'month' => "SELECT COUNT(rev_id) FROM $revisionTable
38
                WHERE rev_user = :userId AND rev_timestamp >= DATE_SUB(NOW(), INTERVAL 1 MONTH)",
39
            'year' => "SELECT COUNT(rev_id) FROM $revisionTable
40
                WHERE rev_user = :userId AND rev_timestamp >= DATE_SUB(NOW(), INTERVAL 1 YEAR)",
41
            'small' => "SELECT COUNT(rev_id) FROM $revisionTable
42
                WHERE rev_user = :userId AND rev_len < 20",
43
            'large' => "SELECT COUNT(rev_id) FROM $revisionTable
44
                WHERE rev_user = :userId AND rev_len > 1000",
45
            'with_comments' => "SELECT COUNT(rev_id) FROM $revisionTable
46
                WHERE rev_user = :userId AND rev_comment = ''",
47
            'minor' => "SELECT COUNT(rev_id) FROM $revisionTable
48
                WHERE rev_user = :userId AND rev_minor_edit = 1",
49
            'average_size' => "SELECT AVG(rev_len) FROM $revisionTable
50
                WHERE rev_user = :userId",
51
        ];
52
        $this->stopwatch->start($cacheKey);
53
        $revisionCounts = [];
54
        foreach ($queries as $varName => $query) {
55
            $resultQuery = $this->getProjectsConnection()->prepare($query);
56
            $userId = $user->getId($project);
57
            $resultQuery->bindParam("userId", $userId);
58
            $resultQuery->execute();
59
            $val = $resultQuery->fetchColumn();
60
            $revisionCounts[$varName] = $val ?: 0;
61
            $this->stopwatch->lap($cacheKey);
62
        }
63
64
        // Cache for 10 minutes, and return.
1 ignored issue
show
Unused Code Comprehensibility introduced by
36% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
65
        $this->stopwatch->stop($cacheKey);
66
        $cacheItem = $this->cache->getItem($cacheKey)
67
                ->set($revisionCounts)
68
                ->expiresAfter(new DateInterval('PT10M'));
69
        $this->cache->save($cacheItem);
70
71
        return $revisionCounts;
72
    }
73
74
    /**
75
     * Get the first and last revision dates (in MySQL YYYYMMDDHHMMSS format).
76
     * @return string[] With keys 'first' and 'last'.
77
     */
78
    public function getRevisionDates(Project $project, User $user)
79
    {
80
        // Set up cache.
81
        $cacheKey = 'revisiondates.' . $project->getDatabaseName() . '.' . $user->getUsername();
82
        if ($this->cache->hasItem($cacheKey)) {
83
            return $this->cache->getItem($cacheKey)->get();
84
        }
85
86
        $this->stopwatch->start($cacheKey);
87
        $revisionTable = $this->getTableName($project->getDatabaseName(), 'revision');
88
        $query = "(SELECT 'first' AS `key`, rev_timestamp AS `date` FROM $revisionTable
89
            WHERE rev_user = :userId ORDER BY rev_timestamp ASC LIMIT 1)
90
            UNION
91
            (SELECT 'last' AS `key`, rev_timestamp AS `date` FROM $revisionTable
92
            WHERE rev_user = :userId ORDER BY rev_timestamp DESC LIMIT 1)";
93
        $resultQuery = $this->getProjectsConnection()->prepare($query);
94
        $userId = $user->getId($project);
95
        $resultQuery->bindParam("userId", $userId);
96
        $resultQuery->execute();
97
        $result = $resultQuery->fetchAll();
98
        $revisionDates = [];
99
        foreach ($result as $res) {
100
            $revisionDates[$res['key']] = $res['date'];
101
        }
102
103
        // Cache for 10 minutes, and return.
1 ignored issue
show
Unused Code Comprehensibility introduced by
36% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
104
        $cacheItem = $this->cache->getItem($cacheKey)
105
                ->set($revisionDates)
106
                ->expiresAfter(new DateInterval('PT10M'));
107
        $this->cache->save($cacheItem);
108
        $this->stopwatch->stop($cacheKey);
109
        return $revisionDates;
110
    }
111
112
    /**
113
     * Get page counts for the given user, both for live and deleted pages/revisions.
114
     * @param Project $project The project.
115
     * @param User $user The user.
116
     * @return int[] With keys: edited-live, edited-deleted, created-live, created-deleted.
117
     */
118
    public function getPageCounts(Project $project, User $user)
119
    {
120
        // Set up cache.
121
        $cacheKey = 'pagecounts.'.$project->getDatabaseName().'.'.$user->getUsername();
122
        if ($this->cache->hasItem($cacheKey)) {
123
            return $this->cache->getItem($cacheKey)->get();
124
        }
125
        $this->stopwatch->start($cacheKey, 'XTools');
126
127
        // Build and execute query.
128
        $revisionTable = $this->getTableName($project->getDatabaseName(), 'revision');
129
        $archiveTable = $this->getTableName($project->getDatabaseName(), 'archive');
130
        $resultQuery = $this->getProjectsConnection()->prepare("
131
            (SELECT 'edited-live' AS source, COUNT(DISTINCT rev_page) AS value
132
                FROM $revisionTable
133
                WHERE rev_user_text=:username)
134
            UNION
135
            (SELECT 'edited-deleted' AS source, COUNT(DISTINCT ar_page_id) AS value
136
                FROM $archiveTable
137
                WHERE ar_user_text=:username)
138
            UNION
139
            (SELECT 'created-live' AS source, COUNT(DISTINCT rev_page) AS value
140
                FROM $revisionTable
141
                WHERE rev_user_text=:username AND rev_parent_id=0)
142
            UNION
143
            (SELECT 'created-deleted' AS source, COUNT(DISTINCT ar_page_id) AS value
144
                FROM $archiveTable
145
                WHERE ar_user_text=:username AND ar_parent_id=0)
146
            ");
147
        $username = $user->getUsername();
148
        $resultQuery->bindParam("username", $username);
149
        $resultQuery->execute();
150
        $results = $resultQuery->fetchAll();
151
152
        $pageCounts = array_combine(
153
            array_map(function ($e) {
154
                return $e['source'];
155
            }, $results),
156
            array_map(function ($e) {
157
                return $e['value'];
158
            }, $results)
159
        );
160
161
        // Cache for 10 minutes, and return.
1 ignored issue
show
Unused Code Comprehensibility introduced by
36% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
162
        $cacheItem = $this->cache->getItem($cacheKey)
163
            ->set($pageCounts)
164
            ->expiresAfter(new DateInterval('PT10M'));
165
        $this->cache->save($cacheItem);
166
        $this->stopwatch->stop($cacheKey);
167
        return $pageCounts;
168
    }
169
170
    /**
171
     * Get log totals for a user.
172
     * @param Project $project The project.
173
     * @param User $user The user.
174
     * @return integer[] Keys are "<log>-<action>" strings, values are counts.
175
     */
176
    public function getLogCounts(Project $project, User $user)
177
    {
178
        // Set up cache.
179
        $cacheKey = 'logcounts.'.$project->getDatabaseName().'.'.$user->getUsername();
180
        if ($this->cache->hasItem($cacheKey)) {
181
            return $this->cache->getItem($cacheKey)->get();
182
        }
183
        $this->stopwatch->start($cacheKey, 'XTools');
184
185
        // Query.
186
        $sql = "SELECT CONCAT(log_type, '-', log_action) AS source, COUNT(log_id) AS value
187
            FROM " . $this->getTableName($project->getDatabaseName(), 'logging') . "
188
            WHERE log_user = :userId
189
            GROUP BY log_type, log_action";
190
        $resultQuery = $this->getProjectsConnection()->prepare($sql);
191
        $userId = $user->getId($project);
192
        $resultQuery->bindParam('userId', $userId);
193
        $resultQuery->execute();
194
        $results = $resultQuery->fetchAll();
195
        $logCounts = array_combine(
196
            array_map(function ($e) {
197
                return $e['source'];
198
            }, $results),
199
            array_map(function ($e) {
200
                return $e['value'];
201
            }, $results)
202
        );
203
204
        // Make sure there is some value for each of the wanted counts.
205
        $requiredCounts = [
206
            'thanks-thank',
207
            'review-approve',
208
            'patrol-patrol',
209
            'block-block',
210
            'block-unblock',
211
            'protect-protect',
212
            'protect-unprotect',
213
            'move-move',
214
            'delete-delete',
215
            'delete-revision',
216
            'delete-restore',
217
            'import-import',
218
            'upload-upload',
219
            'upload-overwrite',
220
        ];
221
        foreach ($requiredCounts as $req) {
222
            if (!isset($logCounts[$req])) {
223
                $logCounts[$req] = 0;
224
            }
225
        }
226
227
        // Add Commons upload count, if applicable.
228
        $logCounts['files_uploaded_commons'] = 0;
229
        if ($this->isLabs()) {
230
            $sql = "SELECT COUNT(log_id) FROM commonswiki_p.logging_userindex
231
                WHERE log_type = 'upload' AND log_action = 'upload' AND log_user = :userId";
232
            $resultQuery = $this->getProjectsConnection()->prepare($sql);
233
            $resultQuery->bindParam('userId', $userId);
234
            $resultQuery->execute();
235
            $logCounts['files_uploaded_commons'] = $resultQuery->fetchColumn();
236
        }
237
238
        // Cache for 10 minutes, and return.
1 ignored issue
show
Unused Code Comprehensibility introduced by
36% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
239
        $cacheItem = $this->cache->getItem($cacheKey)
240
            ->set($logCounts)
241
            ->expiresAfter(new DateInterval('PT10M'));
242
        $this->cache->save($cacheItem);
243
        $this->stopwatch->stop($cacheKey);
244
245
        return $logCounts;
0 ignored issues
show
Best Practice introduced by
The expression return $logCounts; seems to be an array, but some of its elements' types (boolean) are incompatible with the return type documented by Xtools\EditCounterRepository::getLogCounts of type integer[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
246
    }
247
248
    /**
249
     * Get a user's total edit count on one or more project.
250
     * Requires the CentralAuth extension to be installed on the project.
251
     *
252
     * @param string $username The username.
0 ignored issues
show
Bug introduced by
There is no parameter named $username. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
253
     * @param Project $project The project to start from.
254
     * @return mixed[]|boolean Array of total edit counts, or false if none could be found.
255
     */
256
    public function getRevisionCountsAllProjects(User $user, Project $project)
257
    {
258
        // Set up cache and stopwatch.
259
        $cacheKey = 'globalRevisionCounts.'.$user->getUsername();
260
        if ($this->cache->hasItem($cacheKey)) {
261
            return $this->cache->getItem($cacheKey)->get();
262
        }
263
        $this->stopwatch->start($cacheKey, 'XTools');
264
265
        $api = $this->getMediawikiApi($project);
266
        $params = [
267
            'meta' => 'globaluserinfo',
268
            'guiprop' => 'editcount|merged',
269
            'guiuser' => $user->getUsername(),
270
        ];
271
        $query = new SimpleRequest('query', $params);
272
        $result = $api->getRequest($query);
273
        $out = [];
274
        if (isset($result['query']['globaluserinfo']['merged'])) {
275
            foreach ($result['query']['globaluserinfo']['merged'] as $merged) {
276
                $proj = ProjectRepository::getProject($merged['wiki'], $this->container);
277
                $out[] = [
278
                    'project' => $proj,
279
                    'total' => $merged['editcount'],
280
                ];
281
            }
282
        }
283
        if (empty($out)) {
284
            $out = $this->getRevisionCountsAllProjectsNoCentralAuth($user, $project, $cacheKey);
285
        }
286
287
        // Cache for 10 minutes, and return.
1 ignored issue
show
Unused Code Comprehensibility introduced by
36% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
288
        $cacheItem = $this->cache->getItem($cacheKey)
289
            ->set($out)
290
            ->expiresAfter(new DateInterval('PT10M'));
291
        $this->cache->save($cacheItem);
292
        $this->stopwatch->stop($cacheKey);
293
294
        return $out;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $out; (array) is incompatible with the return type documented by Xtools\EditCounterReposi...visionCountsAllProjects of type array|boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
295
    }
296
297
    /**
298
     * Get total edit counts for the top 10 projects for this user.
299
     * @param string $username The username.
0 ignored issues
show
Bug introduced by
There is no parameter named $username. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
300
     * @return string[] Elements are arrays with 'dbName', 'url', 'name', and 'total'.
301
     */
302
    protected function getRevisionCountsAllProjectsNoCentralAuth(
303
        User $user,
304
        Project $project,
305
        $stopwatchName
306
    ) {
307
        $allProjects = $project->getRepository()->getAll();
1 ignored issue
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Xtools\Repository as the method getAll() does only exist in the following sub-classes of Xtools\Repository: Xtools\ProjectRepository. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
308
        $topEditCounts = [];
309
        foreach ($allProjects as $projectMeta) {
310
            $revisionTableName = $this->getTableName($projectMeta['dbName'], 'revision');
311
            $sql = "SELECT COUNT(rev_id) FROM $revisionTableName WHERE rev_user_text=:username";
312
            $stmt = $this->getProjectsConnection()->prepare($sql);
313
            $stmt->bindParam("username", $user->getUsername());
0 ignored issues
show
Bug introduced by
$user->getUsername() cannot be passed to bindparam() as the parameter $variable expects a reference.
Loading history...
314
            $stmt->execute();
315
            $total = (int)$stmt->fetchColumn();
316
            $project = ProjectRepository::getProject($projectMeta['dbName'], $this->container);
317
            $topEditCounts[] = [
318
                'project' => $project,
319
                'total' => $total,
320
            ];
321
            $this->stopwatch->lap($stopwatchName);
322
        }
323
        return $topEditCounts;
324
    }
325
326
    /**
327
     * Get the given user's total edit counts per namespace on the given project.
328
     * @param Project $project The project.
329
     * @param User $user The user.
330
     * @return integer[] Array keys are namespace IDs, values are the edit counts.
331
     */
332
    public function getNamespaceTotals(Project $project, User $user)
333
    {
334
        $revisionTable = $this->getTableName($project->getDatabaseName(), 'revision');
335
        $pageTable = $this->getTableName($project->getDatabaseName(), 'page');
336
        $sql = "SELECT page_namespace, COUNT(rev_id) AS total
337
            FROM $revisionTable r JOIN $pageTable p on r.rev_page = p.page_id
338
            WHERE r.rev_user = :id
339
            GROUP BY page_namespace";
340
        $resultQuery = $this->getProjectsConnection()->prepare($sql);
341
        $userId = $user->getId($project);
342
        $resultQuery->bindParam(":id", $userId);
343
        $resultQuery->execute();
344
        $results = $resultQuery->fetchAll();
345
        $namespaceTotals = array_combine(array_map(function ($e) {
346
            return $e['page_namespace'];
347
        }, $results), array_map(function ($e) {
348
            return $e['total'];
349
        }, $results));
350
        return $namespaceTotals;
351
    }
352
353
    /**
354
     * Get this user's most recent 10 edits across all projects.
355
     * @param string $username The username.
356
     * @param integer $topN The number of items to return.
357
     * @param integer $days The number of days to search from each wiki.
358
     * @return string[]
359
     */
360
    public function getRecentGlobalContribs($username, $projects = [], $topN = 10, $days = 30)
361
    {
362
        $allRevisions = [];
363
        foreach ($this->labsHelper->getProjectsInfo($projects) as $project) {
364
            $cacheKey = "globalcontribs.{$project['dbName']}.$username";
365
            if ($this->cacheHas($cacheKey)) {
0 ignored issues
show
Bug introduced by
The method cacheHas() does not seem to exist on object<Xtools\EditCounterRepository>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
366
                $revisions = $this->cacheGet($cacheKey);
0 ignored issues
show
Bug introduced by
The method cacheGet() does not seem to exist on object<Xtools\EditCounterRepository>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
367
            } else {
368
                $sql =
369
                    "SELECT rev_id, rev_timestamp, UNIX_TIMESTAMP(rev_timestamp) AS unix_timestamp, " .
370
                    " rev_minor_edit, rev_deleted, rev_len, rev_parent_id, rev_comment, " .
371
                    " page_title, page_namespace " . " FROM " .
372
                    $this->labsHelper->getTable('revision', $project['dbName']) . "    JOIN " .
0 ignored issues
show
Bug introduced by
The property labsHelper does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
373
                    $this->labsHelper->getTable('page', $project['dbName']) .
374
                    "    ON (rev_page = page_id)" .
375
                    " WHERE rev_timestamp > NOW() - INTERVAL $days DAY AND rev_user_text LIKE :username" .
376
                    " ORDER BY rev_timestamp DESC" . " LIMIT 10";
377
                $resultQuery = $this->replicas->prepare($sql);
0 ignored issues
show
Bug introduced by
The property replicas does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
378
                $resultQuery->bindParam(":username", $username);
379
                $resultQuery->execute();
380
                $revisions = $resultQuery->fetchAll();
381
                $this->cacheSave($cacheKey, $revisions, 'PT15M');
0 ignored issues
show
Bug introduced by
The method cacheSave() does not seem to exist on object<Xtools\EditCounterRepository>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
382
            }
383
            if (count($revisions) === 0) {
384
                continue;
385
            }
386
            $revsWithProject = array_map(function (&$item) use ($project) {
387
                $item['project_name'] = $project['wikiName'];
388
                $item['project_url'] = $project['url'];
389
                $item['project_db_name'] = $project['dbName'];
390
                $item['rev_time_formatted'] = date('Y-m-d H:i', $item['unix_timestamp']);
391
392
                return $item;
393
            }, $revisions);
394
            $allRevisions = array_merge($allRevisions, $revsWithProject);
395
        }
396
        usort($allRevisions, function ($a, $b) {
397
            return $b['rev_timestamp'] - $a['rev_timestamp'];
398
        });
399
400
        return array_slice($allRevisions, 0, $topN);
401
    }
402
403
    /**
404
     * Get data for a bar chart of monthly edit totals per namespace.
405
     * @param string $username The username.
0 ignored issues
show
Bug introduced by
There is no parameter named $username. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
406
     * @return string[]
407
     */
408 View Code Duplication
    public function getMonthCounts(Project $project, User $user)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
409
    {
410
        $username = $user->getUsername();
411
        $cacheKey = "monthcounts.$username";
412
        if ($this->cache->hasItem($cacheKey)) {
413
            return $this->cache->getItem($cacheKey)->get();
414
        }
415
416
        $revisionTable = $this->getTableName($project->getDatabaseName(), 'revision');
417
        $pageTable = $this->getTableName($project->getDatabaseName(), 'page');
418
        $sql =
419
            "SELECT " . "     YEAR(rev_timestamp) AS `year`," .
420
            "     MONTH(rev_timestamp) AS `month`," . "     page_namespace," .
421
            "     COUNT(rev_id) AS `count` "
422
            . " FROM $revisionTable    JOIN $pageTable ON (rev_page = page_id)" .
423
            " WHERE rev_user_text = :username" .
424
            " GROUP BY YEAR(rev_timestamp), MONTH(rev_timestamp), page_namespace " .
425
            " ORDER BY rev_timestamp DESC";
426
        $resultQuery = $this->getProjectsConnection()->prepare($sql);
427
        $resultQuery->bindParam(":username", $username);
428
        $resultQuery->execute();
429
        $totals = $resultQuery->fetchAll();
430
        
431
        $cacheItem = $this->cache->getItem($cacheKey);
432
        $cacheItem->expiresAfter(new DateInterval('PT10M'));
433
        $cacheItem->set($totals);
434
        $this->cache->save($cacheItem);
435
436
        return $totals;
437
    }
438
439
    /**
440
     * Get yearly edit totals for this user, grouped by namespace.
441
     * @param string $username
0 ignored issues
show
Bug introduced by
There is no parameter named $username. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
442
     * @return string[] ['<namespace>' => ['<year>' => 'total', ... ], ... ]
443
     */
444 View Code Duplication
    public function getYearCounts(Project $project, User $user)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
445
    {
446
        $username = $user->getUsername();
447
        $cacheKey = "yearcounts.$username";
448
        if ($this->cache->hasItem($cacheKey)) {
449
            return $this->cache->getItem($cacheKey)->get();
450
        }
451
452
        $revisionTable = $this->getTableName($project->getDatabaseName(), 'revision');
453
        $pageTable = $this->getTableName($project->getDatabaseName(), 'page');
454
        $sql = "SELECT "
455
            . "     SUBSTR(CAST(rev_timestamp AS CHAR(4)), 1, 4) AS `year`,"
456
            . "     page_namespace,"
457
            . "     COUNT(rev_id) AS `count` "
458
            . " FROM $revisionTable    JOIN $pageTable ON (rev_page = page_id)"
459
            . " WHERE rev_user_text = :username"
460
            . " GROUP BY SUBSTR(CAST(rev_timestamp AS CHAR(4)), 1, 4), page_namespace "
461
            . " ORDER BY rev_timestamp DESC ";
462
        $resultQuery = $this->getProjectsConnection()->prepare($sql);
463
        $resultQuery->bindParam(":username", $username);
464
        $resultQuery->execute();
465
        $totals = $resultQuery->fetchAll();
466
467
        $cacheItem = $this->cache->getItem($cacheKey);
468
        $cacheItem->set($totals);
469
        $cacheItem->expiresAfter(new DateInterval('P10M'));
470
        $this->cache->save($cacheItem);
471
472
        return $totals;
473
    }
474
475
    /**
476
     * Get data for the timecard chart, with totals grouped by day and to the nearest two-hours.
477
     * @param Project $project
478
     * @param User $user
479
     * @return string[]
480
     */
481
    public function getTimeCard(Project $project, User $user)
482
    {
483
        $username = $user->getUsername();
484
        $cacheKey = "timecard.".$username;
485
        if ($this->cache->hasItem($cacheKey)) {
486
            return $this->cache->getItem($cacheKey)->get();
487
        }
488
489
        $hourInterval = 2;
490
        $xCalc = "ROUND(HOUR(rev_timestamp)/$hourInterval) * $hourInterval";
491
        $revisionTable = $this->getTableName($project->getDatabaseName(), 'revision');
492
        $sql = "SELECT "
493
            . "     DAYOFWEEK(rev_timestamp) AS `y`, "
494
            . "     $xCalc AS `x`, "
495
            . "     COUNT(rev_id) AS `r` "
496
            . " FROM $revisionTable"
497
            . " WHERE rev_user_text = :username"
498
            . " GROUP BY DAYOFWEEK(rev_timestamp), $xCalc ";
499
        $resultQuery = $this->getProjectsConnection()->prepare($sql);
500
        $resultQuery->bindParam(":username", $username);
501
        $resultQuery->execute();
502
        $totals = $resultQuery->fetchAll();
503
        // Scale the radii: get the max, then scale each radius.
504
        // This looks inefficient, but there's a max of 72 elements in this array.
505
        $max = 0;
506
        foreach ($totals as $total) {
507
            $max = max($max, $total['r']);
508
        }
509
        foreach ($totals as &$total) {
510
            $total['r'] = round($total['r'] / $max * 100);
511
        }
512
        $cacheItem = $this->cache->getItem($cacheKey);
513
        $cacheItem->expiresAfter(new DateInterval('PT10M'));
514
        $cacheItem->set($totals);
515
        $this->cache->save($cacheItem);
516
517
        return $totals;
518
    }
519
520
    /**
521
     * Get a summary of automated edits made by the given user in their last 1000 edits.
522
     * Will cache the result for 10 minutes.
523
     * @param User $user The user.
524
     * @return integer[] Array of edit counts, keyed by all tool names from
525
     * app/config/semi_automated.yml
526
     * @TODO this is broke
527
     */
528
    public function countAutomatedRevisions(Project $project, User $user)
529
    {
530
        $userId = $user->getId($project);
531
        $cacheKey = "automatedEdits.".$project->getDatabaseName().'.'.$userId;
532
        if ($this->cache->hasItem($cacheKey)) {
533
            $this->log->debug("Using cache for $cacheKey");
534
            return $this->cache->getItem($cacheKey)->get();
535
        }
536
537
        // Get the most recent 1000 edit summaries.
538
        $revisionTable = $this->getTableName($project->getDatabaseName(), 'revision');
539
        $sql = "SELECT rev_comment FROM $revisionTable
540
            WHERE rev_user=:userId ORDER BY rev_timestamp DESC LIMIT 1000";
541
        $resultQuery = $this->getProjectsConnection()->prepare($sql);
542
        $resultQuery->bindParam("userId", $userId);
543
        $resultQuery->execute();
544
        $results = $resultQuery->fetchAll();
545
        $out = [];
546
        foreach ($results as $result) {
547
            $toolName = $this->getTool($result['rev_comment']);
0 ignored issues
show
Bug introduced by
The method getTool() does not exist on Xtools\EditCounterRepository. Did you maybe mean getToolsConnection()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
548
            if ($toolName) {
549
                if (!isset($out[$toolName])) {
550
                    $out[$toolName] = 0;
551
                }
552
                $out[$toolName]++;
553
            }
554
        }
555
        arsort($out);
556
557
        // Cache for 10 minutes.
558
        $this->log->debug("Saving $cacheKey to cache", [$out]);
559
        $this->cacheSave($cacheKey, $out, 'PT10M');
0 ignored issues
show
Bug introduced by
The method cacheSave() does not seem to exist on object<Xtools\EditCounterRepository>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
560
561
        return $out;
562
    }
563
}
564