Passed
Push — master ( a5e435...83c7af )
by MusikAnimal
05:12
created

PagesRepository::getPagesCreated()   B

Complexity

Conditions 5
Paths 9

Size

Total Lines 50
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 28
nc 9
nop 7
dl 0
loc 50
rs 8.6315
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file contains only the PagesRepository class.
4
 */
5
6
namespace Xtools;
7
8
/**
9
 * An PagesRepository is responsible for retrieving information from the
10
 * databases for the Pages Created tool. It does not do any post-processing
11
 * of that data.
12
 * @codeCoverageIgnore
13
 */
14
class PagesRepository extends Repository
15
{
16
    /**
17
     * Count the number of pages created by a user.
18
     * @param Project $project
19
     * @param User $user
20
     * @param string|int $namespace Namespace ID or 'all'.
21
     * @param string $redirects One of 'noredirects', 'onlyredirects' or blank for both.
22
     * @param string $deleted One of 'live', 'deleted' or blank for both.
23
     * @return string[] Result of query, see below. Includes live and deleted pages.
24
     */
25
    public function countPagesCreated(
26
        Project $project,
27
        User $user,
28
        $namespace,
29
        $redirects,
30
        $deleted
31
    ) {
32
        $cacheKey = $this->getCacheKey(func_get_args(), 'num_user_pages_created');
33
        if ($this->cache->hasItem($cacheKey)) {
34
            return $this->cache->getItem($cacheKey)->get();
35
        }
36
37
        $conditions = [
38
            'paSelects' => '',
39
            'paSelectsArchive' => '',
40
            'paJoin' => '',
41
            'revPageGroupBy' => '',
42
        ];
43
        $conditions = array_merge(
44
            $conditions,
45
            $this->getNamespaceRedirectAndDeletedPagesConditions($namespace, $redirects),
46
            $this->getUserConditions($project, $user)
47
        );
48
49
        $sql = "SELECT namespace,
50
                    COUNT(page_title) AS count,
51
                    SUM(CASE WHEN type = 'arc' THEN 1 ELSE 0 END) AS deleted,
52
                    SUM(page_is_redirect) AS redirects
53
                FROM (".
54
                    $this->getPagesCreatedInnerSql($project, $conditions, $deleted)."
55
                ) a ".
56
                "GROUP BY namespace";
57
58
        $result = $this->executeProjectsQuery($sql)->fetchAll();
59
60
        // Cache and return.
61
        return $this->setCache($cacheKey, $result);
62
    }
63
64
    /**
65
     * Get pages created by a user.
66
     * @param Project $project
67
     * @param User $user
68
     * @param string|int $namespace Namespace ID or 'all'.
69
     * @param string $redirects One of 'noredirects', 'onlyredirects' or blank for both.
70
     * @param string $deleted One of 'live', 'deleted' or blank for both.
71
     * @param int|null $limit Number of results to return, or blank to return all.
72
     * @param int $offset Number of pages past the initial dataset. Used for pagination.
73
     * @return string[] Result of query, see below. Includes live and deleted pages.
74
     */
75
    public function getPagesCreated(
76
        Project $project,
77
        User $user,
78
        $namespace,
79
        $redirects,
80
        $deleted,
81
        $limit = 1000,
82
        $offset = 0
83
    ) {
84
        $cacheKey = $this->getCacheKey(func_get_args(), 'user_pages_created');
85
        if ($this->cache->hasItem($cacheKey)) {
86
            return $this->cache->getItem($cacheKey)->get();
87
        }
88
        $this->stopwatch->start($cacheKey, 'XTools');
89
90
        $conditions = [
91
            'paSelects' => '',
92
            'paSelectsArchive' => '',
93
            'paJoin' => '',
94
            'revPageGroupBy' => '',
95
        ];
96
97
        $conditions = array_merge(
98
            $conditions,
99
            $this->getNamespaceRedirectAndDeletedPagesConditions($namespace, $redirects),
100
            $this->getUserConditions($project, $user)
101
        );
102
103
        $pageAssessmentsTable = $project->getTableName('page_assessments');
104
105
        $hasPageAssessments = $this->isLabs() && $project->hasPageAssessments();
106
        if ($hasPageAssessments) {
107
            $conditions['paSelects'] = ', pa_class, pa_importance, pa_page_revision';
108
            $conditions['paSelectsArchive'] = ', NULL AS pa_class, NULL AS pa_page_id, '.
109
                'NULL AS pa_page_revision';
110
            $conditions['paJoin'] = "LEFT JOIN $pageAssessmentsTable ON rev_page = pa_page_id";
111
            $conditions['revPageGroupBy'] = 'GROUP BY rev_page';
112
        }
113
114
        $sql = "SELECT * FROM (".
115
                    $this->getPagesCreatedInnerSql($project, $conditions, $deleted)."
116
                ) a ".
117
                "ORDER BY rev_timestamp DESC
118
                ".(!empty($limit) ? "LIMIT $limit OFFSET $offset" : '');
119
120
        $result = $this->executeProjectsQuery($sql)->fetchAll();
121
122
        // Cache and return.
123
        $this->stopwatch->stop($cacheKey);
124
        return $this->setCache($cacheKey, $result);
125
    }
126
127
    /**
128
     * Get SQL fragments for the namespace and redirects,
129
     * to be used in self::getPagesCreatedInnerSql().
130
     * @param  string|int $namespace Namespace ID or 'all'.
131
     * @param  string $redirects One of 'noredirects', 'onlyredirects' or blank for both.
132
     * @return string[] With keys 'namespaceRev', 'namespaceArc' and 'redirects'
133
     */
134
    private function getNamespaceRedirectAndDeletedPagesConditions($namespace, $redirects)
135
    {
136
        $conditions = [
137
            'namespaceArc' => '',
138
            'namespaceRev' => '',
139
            'redirects' => ''
140
        ];
141
142
        if ($namespace !== 'all') {
143
            $conditions['namespaceRev'] = " AND page_namespace = '".intval($namespace)."' ";
144
            $conditions['namespaceArc'] = " AND ar_namespace = '".intval($namespace)."' ";
145
        }
146
147
        if ($redirects == 'onlyredirects') {
148
            $conditions['redirects'] = " AND page_is_redirect = '1' ";
149
        } elseif ($redirects == 'noredirects') {
150
            $conditions['redirects'] = " AND page_is_redirect = '0' ";
151
        }
152
153
        return $conditions;
154
    }
155
156
    /**
157
     * Get SQL fragments for rev_user or rev_user_text, depending on if the user is logged out.
158
     * Used in self::getPagesCreatedInnerSql().
159
     * @param  Project $project
160
     * @param  User $user
161
     * @return string[] Keys 'whereRev' and 'whereArc'.
162
     */
163
    private function getUserConditions(Project $project, User $user)
164
    {
165
        $username = $user->getUsername();
166
        $userId = $user->getId($project);
167
168
        if ($userId == 0) { // IP Editor or undefined username.
169
            return [
170
                'whereRev' => " rev_user_text = '$username' AND rev_user = '0' ",
171
                'whereArc' => " ar_user_text = '$username' AND ar_user = '0' ",
172
            ];
173
        } else {
174
            return [
175
                'whereRev' => " rev_user = '$userId' AND rev_timestamp > 1 ",
176
                'whereArc' => " ar_user = '$userId' AND ar_timestamp > 1 ",
177
            ];
178
        }
179
    }
180
181
    /**
182
     * Inner SQL for getting or counting pages created by the user.
183
     * @param  Project $project
184
     * @param  string[] $conditions Conditions for the SQL, must include 'paSelects',
185
     *     'paSelectsArchive', 'paJoin', 'whereRev', 'whereArc', 'namespaceRev', 'namespaceArc',
186
     *     'redirects' and 'revPageGroupBy'.
187
     * @param  string $deleted One of 'live', 'deleted' or blank for both.
188
     * @return string Raw SQL.
189
     */
190
    private function getPagesCreatedInnerSql(Project $project, $conditions, $deleted)
191
    {
192
        $pageTable = $project->getTableName('page');
193
        $revisionTable = $project->getTableName('revision');
194
        $archiveTable = $project->getTableName('archive');
195
        $logTable = $project->getTableName('logging', 'logindex');
196
197
        $revisionsSelect = "
198
            SELECT DISTINCT page_namespace AS namespace, 'rev' AS type, page_title AS page_title,
199
                page_len, page_is_redirect, rev_timestamp AS rev_timestamp, rev_user,
200
                rev_user_text AS username, rev_len, rev_id, NULL AS recreated ".$conditions['paSelects']."
201
            FROM $pageTable
202
            JOIN $revisionTable ON page_id = rev_page ".
203
            $conditions['paJoin']."
204
            WHERE ".$conditions['whereRev']."
205
                AND rev_parent_id = '0'".
206
                $conditions['namespaceRev'].
207
                $conditions['redirects'].
208
            $conditions['revPageGroupBy'];
209
210
        $archiveSelect = "
211
            SELECT ar_namespace AS namespace, 'arc' AS type, ar_title AS page_title,
212
                NULL AS page_len, '0' AS page_is_redirect, MIN(ar_timestamp) AS rev_timestamp,
213
                ar_user AS rev_user, ar_user_text AS username, ar_len AS rev_len, ar_rev_id AS rev_id,
214
                EXISTS(
215
                    SELECT 1 FROM $pageTable
216
                    WHERE page_namespace = ar_namespace
217
                    AND page_title = ar_title
218
                ) AS recreated
219
                ".$conditions['paSelectsArchive']."
220
            FROM $archiveTable
221
            LEFT JOIN $logTable ON log_namespace = ar_namespace AND log_title = ar_title
222
                AND log_user = ar_user AND (log_action = 'move' OR log_action = 'move_redir')
223
                AND log_type = 'move'
224
            WHERE ".$conditions['whereArc']."
225
                AND ar_parent_id = '0' ".
226
                $conditions['namespaceArc']."
227
                AND log_action IS NULL
228
            GROUP BY ar_namespace, ar_title";
229
230
        if ($deleted == 'live') {
231
            return $revisionsSelect;
232
        } elseif ($deleted == 'deleted') {
233
            return $archiveSelect;
234
        }
235
236
        return "($revisionsSelect) UNION ($archiveSelect)";
237
    }
238
}
239