Passed
Push — master ( 3ef1df...dbf8d3 )
by MusikAnimal
05:29
created

UserRights::getRightsNames()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 0
dl 0
loc 10
ccs 0
cts 6
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file contains only the UserRights class.
4
 */
5
6
namespace Xtools;
7
8
use AppBundle\Helper\I18nHelper;
9
use DateInterval;
10
use Exception;
11
12
/**
13
 * An UserRights provides methods around parsing changes to a user's rights.
14
 */
15
class UserRights extends Model
16
{
17
    /** @var I18nHelper For i18n and l10n. */
18
    protected $i18n;
19
20
    /** @var string[] Rights changes, keyed by timestamp then 'added' and 'removed'. */
21
    protected $rightsChanges;
22
23
    /** @var string[] Localized names of the rights. */
24
    protected $rightsNames;
25
26
    /** @var string[] Global rights changes (log), keyed by timestamp then 'added' and 'removed'. */
27
    protected $globalRightsChanges;
28
29
    /** @var array The current and former rights of the user. */
30
    protected $rightsStates = [];
31
32
    /**
33
     * Get user rights changes of the given user.
34
     * @return string[] Keyed by timestamp then 'added' and 'removed'.
35
     */
36 1
    public function getRightsChanges()
37
    {
38 1
        if (isset($this->rightsChanges)) {
39 1
            return $this->rightsChanges;
40
        }
41
42 1
        $logData = $this->getRepository()
43 1
            ->getRightsChanges($this->project, $this->user);
44
45 1
        $this->rightsChanges = $this->processRightsChanges($logData);
46
47 1
        $acDate = $this->getAutoconfirmedTimestamp();
48 1
        if ($acDate !== false) {
49
            $this->rightsChanges[$acDate] = [
50
                'logId' => null,
51
                'admin' => null,
52
                'comment' => null,
53
                'added' => ['autoconfirmed'],
54
                'removed' => [],
55
                'automatic' => true,
56
                'type' => 'local',
57
            ];
58
            krsort($this->rightsChanges);
59
        }
60
61 1
        return $this->rightsChanges;
62
    }
63
64
    /**
65
     * Checks the user rights log to see whether the user is an admin
66
     * or used to be one.
67
     * @return string|false One of false (never an admin), 'current' or 'former'.
68
     */
69 1
    public function getAdminStatus()
70
    {
71 1
        $rightsStates = $this->getRightsStates();
72
73 1
        if (in_array('sysop', $rightsStates['local']['current'])) {
74 1
            return 'current';
75
        } elseif (in_array('sysop', $rightsStates['local']['former'])) {
76
            return 'former';
77
        } else {
78
            return false;
79
        }
80
    }
81
82
    /**
83
     * Get a list of the current and former rights of the user.
84
     * @return array With keys 'local' and 'global', each with keys 'current' and 'former'.
85
     */
86 1
    public function getRightsStates()
87
    {
88 1
        if (count($this->rightsStates) > 0) {
89 1
            return $this->rightsStates;
90
        }
91
92 1
        foreach (['local', 'global'] as $type) {
93 1
            list($currentRights, $rightsChanges) = $this->getCurrentRightsAndChanges($type);
94
95 1
            $former = [];
96
97
            // We'll keep track of added rights, which we'll later compare with the
98
            // current rights to ensure the list of former rights is complete.
99
            // This is because sometimes rights were removed but there mysteriously
100
            // is no log entry of it.
101 1
            $added = [];
102
103 1
            foreach ($rightsChanges as $change) {
104 1
                $former = array_diff(
105 1
                    array_merge($former, $change['removed']),
106 1
                    $change['added']
107
                );
108
109 1
                $added = array_unique(array_merge($added, $change['added']));
110
            }
111
112
            // Also tag on rights that were previously added but mysteriously
113
            // don't have a log entry for when they were removed.
114 1
            $former = array_merge(
115 1
                array_diff($added, $currentRights),
116 1
                $former
117
            );
118
119 1
            $this->rightsStates[$type] = [
120 1
                'current' => $currentRights,
121 1
                'former' => array_diff(array_unique($former), $currentRights),
122
            ];
123
        }
124
125 1
        return $this->rightsStates;
126
    }
127
128
    /**
129
     * Get a list of the current rights (of given type) and the log.
130
     * @param string $type 'local' or 'global'
131
     * @return array [string[] current rights, array rights changes].
132
     */
133 1
    private function getCurrentRightsAndChanges($type)
134
    {
135
        // Current rights are not fetched from the log because really old
136
        // log entries contained little or no metadata, and the rights
137
        // changes may be undetectable.
138 1
        if ($type === 'local') {
139 1
            $currentRights = $this->user->getUserRights($this->project);
140 1
            $rightsChanges = $this->getRightsChanges();
141
142 1
            if (false !== $this->getAutoconfirmedTimestamp()) {
143 1
                $currentRights[] = 'autoconfirmed';
144
            }
145
        } else {
146 1
            $currentRights = $this->user->getGlobalUserRights($this->project);
147 1
            $rightsChanges = $this->getGlobalRightsChanges();
148
        }
149
150 1
        return [$currentRights, $rightsChanges];
151
    }
152
153
    /**
154
     * Get a list of the current and former global rights of the user.
155
     * @return array With keys 'current' and 'former'.
156
     */
157
    public function getGlobalRightsStates()
158
    {
159
        return $this->getRightsStates()['global'];
160
    }
161
162
    /**
163
     * Get global user rights changes of the given user.
164
     * @return string[] Keyed by timestamp then 'added' and 'removed'.
165
     */
166 1
    public function getGlobalRightsChanges()
167
    {
168 1
        if (isset($this->globalRightsChanges)) {
169 1
            return $this->globalRightsChanges;
170
        }
171
172 1
        $logData = $this->getRepository()
173 1
            ->getGlobalRightsChanges($this->project, $this->user);
174
175 1
        $this->globalRightsChanges = $this->processRightsChanges($logData);
176
177 1
        return $this->globalRightsChanges;
178
    }
179
180
    /**
181
     * Get the localized names for the user groups, fetched from on-wiki system messages.
182
     * @return string[] Localized names keyed by database value.
183
     */
184
    public function getRightsNames()
185
    {
186
        if (isset($this->rightsNames)) {
187
            return $this->rightsNames;
188
        }
189
190
        $this->rightsNames = $this->getRepository()
191
            ->getRightsNames($this->project, $this->i18n->getLang());
192
193
        return $this->rightsNames;
194
    }
195
196
    /**
197
     * Get the localized translation for the given user right.
198
     * @param string $name The name of the right, such as 'sysop'.
199
     * @return string
200
     */
201
    public function getRightsName($name)
202
    {
203
        return isset($this->getRightsNames()[$name])
204
            ? $this->getRightsNames()[$name]
205
            : $name;
206
    }
207
208
    /**
209
     * Process the given rights changes, sorting an putting in a human-readable format.
210
     * @param array $logData As fetched with EditCounterRepository::getRightsChanges.
211
     * @return array
212
     */
213 1
    private function processRightsChanges($logData)
214
    {
215 1
        $rightsChanges = [];
216
217 1
        foreach ($logData as $row) {
218 1
            $unserialized = @unserialize($row['log_params']);
219 1
            if ($unserialized !== false) {
220 1
                $old = $unserialized['4::oldgroups'];
221 1
                $new = $unserialized['5::newgroups'];
222 1
                $added = array_diff($new, $old);
223 1
                $removed = array_diff($old, $new);
224
225 1
                $rightsChanges = $this->setAutoRemovals($rightsChanges, $row, $unserialized, $added);
226
            } else {
227
                // This is the old school format the most likely contains
228
                // the list of rights additions as a comma-separated list.
229
                try {
230 1
                    list($old, $new) = explode("\n", $row['log_params']);
231 1
                    $old = array_filter(array_map('trim', explode(',', $old)));
232 1
                    $new = array_filter(array_map('trim', explode(',', $new)));
233 1
                    $added = array_diff($new, $old);
234 1
                    $removed = array_diff($old, $new);
235
                } catch (Exception $e) {
236
                    // Really, really old school format that may be missing metadata
237
                    // altogether. Here we'll just leave $added and $removed empty.
238
                    $added = [];
239
                    $removed = [];
240
                }
241
            }
242
243
            // Remove '(none)'.
244 1
            if (in_array('(none)', $added)) {
245
                array_splice($added, array_search('(none)', $added), 1);
0 ignored issues
show
Bug introduced by
It seems like array_search('(none)', $added) can also be of type string and false; however, parameter $offset of array_splice() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

245
                array_splice($added, /** @scrutinizer ignore-type */ array_search('(none)', $added), 1);
Loading history...
246
            }
247 1
            if (in_array('(none)', $removed)) {
248
                array_splice($removed, array_search('(none)', $removed), 1);
249
            }
250
251 1
            $rightsChanges[$row['log_timestamp']] = [
252 1
                'logId' => $row['log_id'],
253 1
                'admin' => $row['log_action'] === 'autopromote' ? null : $row['log_user_text'],
254 1
                'comment' => $row['log_comment'],
255 1
                'added' => array_values($added),
256 1
                'removed' => array_values($removed),
257 1
                'automatic' => $row['log_action'] === 'autopromote',
258 1
                'type' => $row['type'],
259
            ];
260
        }
261
262 1
        krsort($rightsChanges);
263
264 1
        return $rightsChanges;
265
    }
266
267
    /**
268
     * Check the given log entry for rights changes that are set to automatically expire,
269
     * and add entries to $rightsChanges accordingly.
270
     * @param array $rightsChanges
271
     * @param array $row Log entry row from database.
272
     * @param array $params Unserialized log params.
273
     * @param string[] $added List of added user rights.
274
     * @return array Modified $rightsChanges.
275
     */
276 1
    private function setAutoRemovals($rightsChanges, $row, $params, $added)
277
    {
278 1
        foreach ($added as $index => $entry) {
279 1
            if (!isset($params['newmetadata'][$index]) ||
280 1
                !array_key_exists('expiry', $params['newmetadata'][$index]) ||
281 1
                empty($params['newmetadata'][$index]['expiry'])
282
            ) {
283 1
                continue;
284
            }
285
286 1
            $expiry = $params['newmetadata'][$index]['expiry'];
287
288 1
            if (isset($rightsChanges[$expiry]) && !in_array($entry, $rightsChanges[$expiry]['removed'])) {
289 1
                $rightsChanges[$expiry]['removed'][] = $entry;
290
            } else {
291 1
                $rightsChanges[$expiry] = [
292 1
                    'logId' => $row['log_id'],
293 1
                    'admin' => $row['log_user_text'],
294
                    'comment' => null,
295
                    'added' => [],
296 1
                    'removed' => [$entry],
297
                    'automatic' => true,
298 1
                    'type' => $row['type'],
299
                ];
300
            }
301
        }
302
303 1
        return $rightsChanges;
304
    }
305
306
    /**
307
     * Get the timestamp of when the user became autoconfirmed.
308
     * @return string|false YmdHis format, or false if date is in the future or if AC status could not be determined.
309
     */
310 1
    private function getAutoconfirmedTimestamp()
311
    {
312 1
        static $acTimestamp = null;
313 1
        if ($acTimestamp !== null) {
314
            return $acTimestamp;
315
        }
316
317 1
        $thresholds = $this->getRepository()->getAutoconfirmedAgeAndCount($this->project);
318
319
        // Happens for non-WMF installations, or if there is no autoconfirmed status.
320 1
        if (null === $thresholds) {
321 1
            return false;
322
        }
323
324
        $registrationDate = $this->user->getRegistrationDate($this->project);
325
326
        // Sometimes for old accounts the registration date is null, in which case
327
        // we won't attempt to find out when they were autoconfirmed.
328
        if (!is_a($registrationDate, 'DateTime')) {
0 ignored issues
show
Bug introduced by
It seems like $registrationDate can also be of type false; however, parameter $object of is_a() does only seem to accept object|string, maybe add an additional type check? ( Ignorable by Annotation )

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

328
        if (!is_a(/** @scrutinizer ignore-type */ $registrationDate, 'DateTime')) {
Loading history...
329
            return false;
330
        }
331
332
        $regDateImmutable = new \DateTimeImmutable(
333
            $registrationDate->format('YmdHis')
334
        );
335
336
        $acDate = $regDateImmutable->add(DateInterval::createFromDateString(
337
            $thresholds['wgAutoConfirmAge'].' seconds'
338
        ))->format('YmdHis');
339
340
        // If autoconfirmed date is in the future.
341
        if (strtotime($acDate) > time()) {
342
            return false;
343
        }
344
345
        // First check if they already had 10 edits made as of $acDate
346
        $editsByAcDate = $this->getRepository()->getNumEditsByTimestamp(
347
            $this->project,
348
            $this->user,
349
            $acDate
350
        );
351
352
        // If more than wgAutoConfirmCount, then $acDate is when they became autoconfirmed.
353
        if ($editsByAcDate >= $thresholds['wgAutoConfirmCount']) {
354
            return $acDate;
355
        }
356
357
        // Now check when the nth edit was made, where n is wgAutoConfirmCount.
358
        // This will be false if they still haven't made 10 edits.
359
        $acTimestamp = $this->getRepository()->getNthEditTimestamp(
360
            $this->project,
361
            $this->user,
362
            $registrationDate->format('YmdHis'),
363
            $thresholds['wgAutoConfirmCount']
364
        );
365
366
        return $acTimestamp;
367
    }
368
}
369