Passed
Push — master ( a1ed3f...a64a0e )
by
unknown
05:21
created

ArticleInfo::anonPercentage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file contains only the ArticleInfo class.
4
 */
5
6
namespace Xtools;
7
8
use AppBundle\Helper\I18nHelper;
9
use DateTime;
10
use Symfony\Component\DependencyInjection\Container;
11
use Symfony\Component\DomCrawler\Crawler;
12
13
/**
14
 * An ArticleInfo provides statistics about a page on a project. This model does not
15
 * have a separate Repository because it needs to use individual SQL statements to
16
 * traverse the page's history, saving class instance variables along the way.
17
 */
18
class ArticleInfo extends Model
19
{
20
    /** @const string[] Domain names of wikis supported by WikiWho. */
21
    const TEXTSHARE_WIKIS = [
22
        'en.wikipedia.org',
23
        'de.wikipedia.org',
24
        'eu.wikipedia.org',
25
        'tr.wikipedia.org',
26
        'es.wikipedia.org',
27
    ];
28
29
    /** @var Container The application's DI container. */
30
    protected $container;
31
32
    /** @var Page The page. */
33
    protected $page;
34
35
    /** @var I18nHelper For i18n and l10n. */
36
    protected $i18n;
37
38
    /** @var false|int From what date to obtain records. */
39
    protected $startDate;
40
41
    /** @var false|int To what date to obtain records. */
42
    protected $endDate;
43
44
    /** @var int Number of revisions that belong to the page. */
45
    protected $numRevisions;
46
47
    /** @var int Maximum number of revisions to process, as configured. */
48
    protected $maxRevisions;
49
50
    /** @var int Number of revisions that were actually processed. */
51
    protected $numRevisionsProcessed;
52
53
    /**
54
     * Various statistics about editors to the page. These are not User objects
55
     * so as to preserve memory.
56
     * @var mixed[]
57
     */
58
    protected $editors;
59
60
    /** @var mixed[] The top 10 editors to the page by number of edits. */
61
    protected $topTenEditorsByEdits;
62
63
    /** @var mixed[] The top 10 editors to the page by added text. */
64
    protected $topTenEditorsByAdded;
65
66
    /** @var int Number of edits made by the top 10 editors. */
67
    protected $topTenCount;
68
69
    /** @var mixed[] Various statistics about bots that edited the page. */
70
    protected $bots;
71
72
    /** @var int Number of edits made to the page by bots. */
73
    protected $botRevisionCount;
74
75
    /** @var mixed[] Various counts about each individual year and month of the page's history. */
76
    protected $yearMonthCounts;
77
78
    /** @var string[] Localized labels for the years, to be used in the 'Year counts' chart. */
79
    protected $yearLabels = [];
80
81
    /** @var string[] Localized labels for the months, to be used in the 'Month counts' chart. */
82
    protected $monthLabels = [];
83
84
    /** @var Edit The first edit to the page. */
85
    protected $firstEdit;
86
87
    /** @var Edit The last edit to the page. */
88
    protected $lastEdit;
89
90
    /** @var Edit Edit that made the largest addition by number of bytes. */
91
    protected $maxAddition;
92
93
    /** @var Edit Edit that made the largest deletion by number of bytes. */
94
    protected $maxDeletion;
95
96
    /** @var int[] Number of in and outgoing links and redirects to the page. */
97
    protected $linksAndRedirects;
98
99
    /** @var string[] Assessments of the page (see Page::getAssessments). */
100
    protected $assessments;
101
102
    /**
103
     * Maximum number of edits that were created across all months. This is used as a comparison
104
     * for the bar charts in the months section.
105
     * @var int
106
     */
107
    protected $maxEditsPerMonth;
108
109
    /** @var string[] List of (semi-)automated tools that were used to edit the page. */
110
    protected $tools;
111
112
    /**
113
     * Total number of bytes added throughout the page's history. This is used as a comparison
114
     * when computing the top 10 editors by added text.
115
     * @var int
116
     */
117
    protected $addedBytes = 0;
118
119
    /** @var int Number of days between first and last edit. */
120
    protected $totalDays;
121
122
    /** @var int Number of minor edits to the page. */
123
    protected $minorCount = 0;
124
125
    /** @var int Number of anonymous edits to the page. */
126
    protected $anonCount = 0;
127
128
    /** @var int Number of automated edits to the page. */
129
    protected $automatedCount = 0;
130
131
    /** @var int Number of edits to the page that were reverted with the subsequent edit. */
132
    protected $revertCount = 0;
133
134
    /** @var int[] The "edits per <time>" counts. */
135
    protected $countHistory = [
136
        'day' => 0,
137
        'week' => 0,
138
        'month' => 0,
139
        'year' => 0
140
    ];
141
142
    /** @var string[] List of wikidata and Checkwiki errors. */
143
    protected $bugs;
144
145
    /** @var array List of editors and the percentage of the current content that they authored. */
146
    protected $textshares;
147
148
    /** @var array Number of categories, templates and files on the page. */
149
    protected $transclusionData;
150
151
    /**
152
     * ArticleInfo constructor.
153
     * @param Page $page The page to process.
154
     * @param Container $container The DI container.
155
     * @param false|int $start From what date to obtain records.
156
     * @param false|int $end To what date to obtain records.
157
     */
158 13
    public function __construct(Page $page, Container $container, $start = false, $end = false)
159
    {
160 13
        $this->page = $page;
161 13
        $this->container = $container;
162 13
        $this->startDate = $start;
163 13
        $this->endDate = $end;
164 13
    }
165
166
    /**
167
     * Make the I18nHelper accessible to ArticleInfo.
168
     * @param I18nHelper $i18n
169
     * @codeCoverageIgnore
170
     */
171
    public function setI18nHelper(I18nHelper $i18n)
172
    {
173
        $this->i18n = $i18n;
174
    }
175
176
    /**
177
     * Get date opening date range.
178
     * @return false|int
179
     */
180 1
    public function getStartDate()
181
    {
182 1
        return $this->startDate;
183
    }
184
185
    /**
186
     * Get date closing date range.
187
     * @return false|int
188
     */
189 1
    public function getEndDate()
190
    {
191 1
        return $this->endDate;
192
    }
193
194
    /**
195
     * Get the day of last date we should show in the month/year sections,
196
     * based on $this->endDate or the current date.
197
     * @return int As Unix timestamp.
198
     */
199 4
    private function getLastDay()
200
    {
201 4
        if ($this->endDate !== false) {
202
            return (new DateTime('@'.$this->endDate))
0 ignored issues
show
Bug introduced by
Are you sure $this->endDate of type integer|true can be used in concatenation? ( Ignorable by Annotation )

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

202
            return (new DateTime('@'./** @scrutinizer ignore-type */ $this->endDate))
Loading history...
203
                ->modify('last day of this month')
204
                ->getTimestamp();
205
        } else {
206 4
            return strtotime('last day of this month');
207
        }
208
    }
209
210
    /**
211
     * Has date range?
212
     * @return bool
213
     */
214 1
    public function hasDateRange()
215
    {
216 1
        return $this->startDate !== false || $this->endDate !== false;
217
    }
218
219
    /**
220
     * Return the start/end date values as associative array,
221
     * with YYYY-MM-DD as the date format. This is used mainly as
222
     * a helper to pass to the pageviews Twig macros.
223
     * @return array
224
     */
225 1
    public function getDateParams()
226
    {
227 1
        if (!$this->hasDateRange()) {
228
            return [];
229
        }
230
231
        $ret = [
232 1
            'start' => $this->firstEdit->getTimestamp()->format('Y-m-d'),
233 1
            'end' => $this->lastEdit->getTimestamp()->format('Y-m-d'),
234
        ];
235
236 1
        if ($this->startDate !== false) {
237 1
            $ret['start'] = date('Y-m-d', $this->startDate);
0 ignored issues
show
Bug introduced by
It seems like $this->startDate can also be of type true; however, parameter $timestamp of date() 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

237
            $ret['start'] = date('Y-m-d', /** @scrutinizer ignore-type */ $this->startDate);
Loading history...
238
        }
239 1
        if ($this->endDate !== false) {
240 1
            $ret['end'] = date('Y-m-d', $this->endDate);
241
        }
242
243 1
        return $ret;
244
    }
245
246
    /**
247
     * Shorthand to get the page's project.
248
     * @return Project
249
     * @codeCoverageIgnore
250
     */
251
    public function getProject()
252
    {
253
        return $this->page->getProject();
254
    }
255
256
    /**
257
     * Get the number of revisions belonging to the page.
258
     * @return int
259
     */
260 4
    public function getNumRevisions()
261
    {
262 4
        if (!isset($this->numRevisions)) {
263 4
            $this->numRevisions = $this->page->getNumRevisions(null, $this->startDate, $this->endDate);
264
        }
265 4
        return $this->numRevisions;
266
    }
267
268
    /**
269
     * Get the maximum number of revisions that we should process.
270
     * @return int
271
     */
272 3
    public function getMaxRevisions()
273
    {
274 3
        if (!isset($this->maxRevisions)) {
275 3
            $this->maxRevisions = (int) $this->container->getParameter('app.max_page_revisions');
276
        }
277 3
        return $this->maxRevisions;
278
    }
279
280
    /**
281
     * Get the number of revisions that are actually getting processed.
282
     * This goes by the app.max_page_revisions parameter, or the actual
283
     * number of revisions, whichever is smaller.
284
     * @return int
285
     */
286 6
    public function getNumRevisionsProcessed()
287
    {
288 6
        if (isset($this->numRevisionsProcessed)) {
289 4
            return $this->numRevisionsProcessed;
290
        }
291
292 2
        if ($this->tooManyRevisions()) {
293 1
            $this->numRevisionsProcessed = $this->getMaxRevisions();
294
        } else {
295 1
            $this->numRevisionsProcessed = $this->getNumRevisions();
296
        }
297
298 2
        return $this->numRevisionsProcessed;
299
    }
300
301
    /**
302
     * Are there more revisions than we should process, based on the config?
303
     * @return bool
304
     */
305 3
    public function tooManyRevisions()
306
    {
307 3
        return $this->getMaxRevisions() > 0 && $this->getNumRevisions() > $this->getMaxRevisions();
308
    }
309
310
    /**
311
     * Fetch and store all the data we need to show the ArticleInfo view.
312
     * @codeCoverageIgnore
313
     */
314
    public function prepareData()
315
    {
316
        $this->parseHistory();
317
        $this->setLogsEvents();
318
319
        // Bots need to be set before setting top 10 counts.
320
        $this->setBots();
321
322
        $this->setTopTenCounts();
323
    }
324
325
    /**
326
     * Get the number of editors that edited the page.
327
     * @return int
328
     */
329 1
    public function getNumEditors()
330
    {
331 1
        return count($this->editors);
332
    }
333
334
    /**
335
     * Get the number of bots that edited the page.
336
     * @return int
337
     */
338
    public function getNumBots()
339
    {
340
        return count($this->getBots());
341
    }
342
343
    /**
344
     * Get the number of days between the first and last edit.
345
     * @return int
346
     */
347 1
    public function getTotalDays()
348
    {
349 1
        if (isset($this->totalDays)) {
350 1
            return $this->totalDays;
351
        }
352 1
        $dateFirst = $this->firstEdit->getTimestamp();
353 1
        $dateLast = $this->lastEdit->getTimestamp();
354 1
        $interval = date_diff($dateLast, $dateFirst, true);
355 1
        $this->totalDays = $interval->format('%a');
0 ignored issues
show
Documentation Bug introduced by
The property $totalDays was declared of type integer, but $interval->format('%a') is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
356 1
        return $this->totalDays;
357
    }
358
359
    /**
360
     * Returns length of the page.
361
     * @return int
362
     */
363 1
    public function getLength()
364
    {
365 1
        if ($this->hasDateRange()) {
366 1
            return $this->lastEdit->getLength();
367
        }
368
369
        return $this->page->getLength();
370
    }
371
372
    /**
373
     * Get the average number of days between edits to the page.
374
     * @return double
375
     */
376 1
    public function averageDaysPerEdit()
377
    {
378 1
        return round($this->getTotalDays() / $this->getNumRevisionsProcessed(), 1);
379
    }
380
381
    /**
382
     * Get the average number of edits per day to the page.
383
     * @return double
384
     */
385 1
    public function editsPerDay()
386
    {
387 1
        $editsPerDay = $this->getTotalDays()
388 1
            ? $this->getNumRevisionsProcessed() / ($this->getTotalDays() / (365 / 12 / 24))
389 1
            : 0;
390 1
        return round($editsPerDay, 1);
391
    }
392
393
    /**
394
     * Get the average number of edits per month to the page.
395
     * @return double
396
     */
397 1
    public function editsPerMonth()
398
    {
399 1
        $editsPerMonth = $this->getTotalDays()
400 1
            ? $this->getNumRevisionsProcessed() / ($this->getTotalDays() / (365 / 12))
401 1
            : 0;
402 1
        return min($this->getNumRevisionsProcessed(), round($editsPerMonth, 1));
403
    }
404
405
    /**
406
     * Get the average number of edits per year to the page.
407
     * @return double
408
     */
409 1
    public function editsPerYear()
410
    {
411 1
        $editsPerYear = $this->getTotalDays()
412 1
            ? $this->getNumRevisionsProcessed() / ($this->getTotalDays() / 365)
413 1
            : 0;
414 1
        return min($this->getNumRevisionsProcessed(), round($editsPerYear, 1));
415
    }
416
417
    /**
418
     * Get the average number of edits per editor.
419
     * @return double
420
     */
421 1
    public function editsPerEditor()
422
    {
423 1
        return round($this->getNumRevisionsProcessed() / count($this->editors), 1);
424
    }
425
426
    /**
427
     * Get the percentage of minor edits to the page.
428
     * @return double
429
     */
430 1
    public function minorPercentage()
431
    {
432 1
        return round(
433 1
            ($this->minorCount / $this->getNumRevisionsProcessed()) * 100,
434 1
            1
435
        );
436
    }
437
438
    /**
439
     * Get the percentage of anonymous edits to the page.
440
     * @return double
441
     */
442 1
    public function anonPercentage()
443
    {
444 1
        return round(
445 1
            ($this->anonCount / $this->getNumRevisionsProcessed()) * 100,
446 1
            1
447
        );
448
    }
449
450
    /**
451
     * Get the percentage of edits made by the top 10 editors.
452
     * @return double
453
     */
454 1
    public function topTenPercentage()
455
    {
456 1
        return round(($this->topTenCount / $this->getNumRevisionsProcessed()) * 100, 1);
457
    }
458
459
    /**
460
     * Get the number of times the page has been viewed in the given timeframe.
461
     * If the ArticleInfo instance has a date range, it is used instead of the
462
     * value of the $latest parameter.
463
     * @param  int $latest Last N days.
464
     * @return int
465
     */
466
    public function getPageviews($latest)
467
    {
468
        if (!$this->hasDateRange()) {
469
            return $this->page->getLastPageviews($latest);
470
        }
471
472
        $daterange = $this->getDateParams();
473
        return $this->page->getPageviews($daterange['start'], $daterange['end']);
474
    }
475
476
    /**
477
     * Get the page assessments of the page.
478
     * @see https://www.mediawiki.org/wiki/Extension:PageAssessments
479
     * @return string[]|false False if unsupported.
480
     * @codeCoverageIgnore
481
     */
482
    public function getAssessments()
483
    {
484
        if (!is_array($this->assessments)) {
0 ignored issues
show
introduced by
The condition is_array($this->assessments) is always true.
Loading history...
485
            $this->assessments = $this->page
486
                ->getProject()
487
                ->getPageAssessments()
488
                ->getAssessments($this->page);
489
        }
490
        return $this->assessments;
491
    }
492
493
    /**
494
     * Get the number of automated edits made to the page.
495
     * @return int
496
     */
497 1
    public function getAutomatedCount()
498
    {
499 1
        return $this->automatedCount;
500
    }
501
502
    /**
503
     * Get the number of edits to the page that were reverted with the subsequent edit.
504
     * @return int
505
     */
506 1
    public function getRevertCount()
507
    {
508 1
        return $this->revertCount;
509
    }
510
511
    /**
512
     * Get the number of edits to the page made by logged out users.
513
     * @return int
514
     */
515 1
    public function getAnonCount()
516
    {
517 1
        return $this->anonCount;
518
    }
519
520
    /**
521
     * Get the number of minor edits to the page.
522
     * @return int
523
     */
524 1
    public function getMinorCount()
525
    {
526 1
        return $this->minorCount;
527
    }
528
529
    /**
530
     * Get the number of edits to the page made in the past day, week, month and year.
531
     * @return int[] With keys 'day', 'week', 'month' and 'year'.
532
     */
533
    public function getCountHistory()
534
    {
535
        return $this->countHistory;
536
    }
537
538
    /**
539
     * Get the number of edits to the page made by the top 10 editors.
540
     * @return int
541
     */
542 1
    public function getTopTenCount()
543
    {
544 1
        return $this->topTenCount;
545
    }
546
547
    /**
548
     * Get the first edit to the page.
549
     * @return Edit
550
     */
551 1
    public function getFirstEdit()
552
    {
553 1
        return $this->firstEdit;
554
    }
555
556
    /**
557
     * Get the last edit to the page.
558
     * @return Edit
559
     */
560 1
    public function getLastEdit()
561
    {
562 1
        return $this->lastEdit;
563
    }
564
565
    /**
566
     * Get the edit that made the largest addition to the page (by number of bytes).
567
     * @return Edit
568
     */
569 1
    public function getMaxAddition()
570
    {
571 1
        return $this->maxAddition;
572
    }
573
574
    /**
575
     * Get the edit that made the largest removal to the page (by number of bytes).
576
     * @return Edit
577
     */
578 1
    public function getMaxDeletion()
579
    {
580 1
        return $this->maxDeletion;
581
    }
582
583
    /**
584
     * Get the list of editors to the page, including various statistics.
585
     * @return mixed[]
586
     */
587 1
    public function getEditors()
588
    {
589 1
        return $this->editors;
590
    }
591
592
    /**
593
     * Get the list of the top editors to the page (by edits), including various statistics.
594
     * @return mixed[]
595
     */
596 1
    public function topTenEditorsByEdits()
597
    {
598 1
        return $this->topTenEditorsByEdits;
599
    }
600
601
    /**
602
     * Get the list of the top editors to the page (by added text), including various statistics.
603
     * @return mixed[]
604
     */
605 1
    public function topTenEditorsByAdded()
606
    {
607 1
        return $this->topTenEditorsByAdded;
608
    }
609
610
    /**
611
     * Get various counts about each individual year and month of the page's history.
612
     * @return mixed[]
613
     */
614 2
    public function getYearMonthCounts()
615
    {
616 2
        return $this->yearMonthCounts;
617
    }
618
619
    /**
620
     * Get the localized labels for the 'Year counts' chart.
621
     * @return string[]
622
     */
623
    public function getYearLabels()
624
    {
625
        return $this->yearLabels;
626
    }
627
628
    /**
629
     * Get the localized labels for the 'Month counts' chart.
630
     * @return string[]
631
     */
632
    public function getMonthLabels()
633
    {
634
        return $this->monthLabels;
635
    }
636
637
    /**
638
     * Get the maximum number of edits that were created across all months. This is used as a
639
     * comparison for the bar charts in the months section.
640
     * @return int
641
     */
642 1
    public function getMaxEditsPerMonth()
643
    {
644 1
        return $this->maxEditsPerMonth;
645
    }
646
647
    /**
648
     * Get a list of (semi-)automated tools that were used to edit the page, including
649
     * the number of times they were used, and a link to the tool's homepage.
650
     * @return mixed[]
651
     */
652 1
    public function getTools()
653
    {
654 1
        return $this->tools;
655
    }
656
657
    /**
658
     * Get the list of page's wikidata and Checkwiki errors.
659
     * @see Page::getErrors()
660
     * @return string[]
661
     */
662
    public function getBugs()
663
    {
664
        if (!is_array($this->bugs)) {
0 ignored issues
show
introduced by
The condition is_array($this->bugs) is always true.
Loading history...
665
            $this->bugs = $this->page->getErrors();
666
        }
667
        return $this->bugs;
668
    }
669
670
    /**
671
     * Get the number of wikidata nad CheckWiki errors.
672
     * @return int
673
     */
674
    public function numBugs()
675
    {
676
        return count($this->getBugs());
677
    }
678
679
    /**
680
     * Get the number of external links on the page.
681
     * @return int
682
     */
683 1
    public function linksExtCount()
684
    {
685 1
        return $this->getLinksAndRedirects()['links_ext_count'];
686
    }
687
688
    /**
689
     * Get the number of incoming links to the page.
690
     * @return int
691
     */
692 1
    public function linksInCount()
693
    {
694 1
        return $this->getLinksAndRedirects()['links_in_count'];
695
    }
696
697
    /**
698
     * Get the number of outgoing links from the page.
699
     * @return int
700
     */
701 1
    public function linksOutCount()
702
    {
703 1
        return $this->getLinksAndRedirects()['links_out_count'];
704
    }
705
706
    /**
707
     * Get the number of redirects to the page.
708
     * @return int
709
     */
710 1
    public function redirectsCount()
711
    {
712 1
        return $this->getLinksAndRedirects()['redirects_count'];
713
    }
714
715
    /**
716
     * Get the number of external, incoming and outgoing links, along with
717
     * the number of redirects to the page.
718
     * @return int
719
     * @codeCoverageIgnore
720
     */
721
    private function getLinksAndRedirects()
722
    {
723
        if (!is_array($this->linksAndRedirects)) {
0 ignored issues
show
introduced by
The condition is_array($this->linksAndRedirects) is always true.
Loading history...
724
            $this->linksAndRedirects = $this->page->countLinksAndRedirects();
725
        }
726
        return $this->linksAndRedirects;
727
    }
728
729
    /**
730
     * Parse the revision history, collecting our core statistics.
731
     * @return mixed[] Associative "master" array of metadata about the page.
732
     *
733
     * Untestable because it relies on getting a PDO statement. All the important
734
     * logic lives in other methods which are tested.
735
     * @codeCoverageIgnore
736
     */
737
    private function parseHistory()
738
    {
739
        if ($this->tooManyRevisions()) {
740
            $limit = $this->getMaxRevisions();
741
        } else {
742
            $limit = null;
743
        }
744
745
        // Third parameter is ignored if $limit is null.
746
        $revStmt = $this->page->getRevisionsStmt(
747
            null,
748
            $limit,
749
            $this->getNumRevisions(),
750
            $this->startDate,
751
            $this->endDate
752
        );
753
        $revCount = 0;
754
755
        /**
756
         * Data about previous edits so that we can use them as a basis for comparison.
757
         * @var Edit[]
758
         */
759
        $prevEdits = [
760
            // The previous Edit, used to discount content that was reverted.
761
            'prev' => null,
762
763
            // The SHA-1 of the edit *before* the previous edit. Used for more
764
            // accruate revert detection.
765
            'prevSha' => null,
766
767
            // The last edit deemed to be the max addition of content. This is kept track of
768
            // in case we find out the next edit was reverted (and was also a max edit),
769
            // in which case we'll want to discount it and use this one instead.
770
            'maxAddition' => null,
771
772
            // Same as with maxAddition, except the maximum amount of content deleted.
773
            // This is used to discount content that was reverted.
774
            'maxDeletion' => null,
775
        ];
776
777
        while ($rev = $revStmt->fetch()) {
778
            $edit = new Edit($this->page, $rev);
779
780
            if ($revCount === 0) {
781
                $this->firstEdit = $edit;
782
            }
783
784
            // Sometimes, with old revisions (2001 era), the revisions from 2002 come before 2001
785
            if ($edit->getTimestamp() < $this->firstEdit->getTimestamp()) {
786
                $this->firstEdit = $edit;
787
            }
788
789
            $prevEdits = $this->updateCounts($edit, $prevEdits);
790
791
            $revCount++;
792
        }
793
794
        $this->numRevisionsProcessed = $revCount;
795
796
        // Various sorts
797
        arsort($this->editors);
798
        ksort($this->yearMonthCounts);
799
        if ($this->tools) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->tools of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
800
            arsort($this->tools);
801
        }
802
    }
803
804
    /**
805
     * Update various counts based on the current edit.
806
     * @param  Edit   $edit
807
     * @param  Edit[] $prevEdits With 'prev', 'prevSha', 'maxAddition' and 'maxDeletion'
808
     * @return Edit[] Updated version of $prevEdits.
809
     */
810 4
    private function updateCounts(Edit $edit, $prevEdits)
811
    {
812
        // Update the counts for the year and month of the current edit.
813 4
        $this->updateYearMonthCounts($edit);
814
815
        // Update counts for the user who made the edit.
816 4
        $this->updateUserCounts($edit);
817
818
        // Update the year/month/user counts of anon and minor edits.
819 4
        $this->updateAnonMinorCounts($edit);
820
821
        // Update counts for automated tool usage, if applicable.
822 4
        $this->updateToolCounts($edit);
823
824
        // Increment "edits per <time>" counts
825 4
        $this->updateCountHistory($edit);
826
827
        // Update figures regarding content addition/removal, and the revert count.
828 4
        $prevEdits = $this->updateContentSizes($edit, $prevEdits);
829
830
        // Now that we've updated all the counts, we can reset
831
        // the prev and last edits, which are used for tracking.
832
        // But first, let's copy over the SHA of the actual previous edit
833
        // and put it in our $prevEdits['prev'], so that we'll know
834
        // that content added after $prevEdit['prev'] was reverted.
835 4
        if ($prevEdits['prev'] !== null) {
836 4
            $prevEdits['prevSha'] = $prevEdits['prev']->getSha();
837
        }
838 4
        $prevEdits['prev'] = $edit;
839 4
        $this->lastEdit = $edit;
840
841 4
        return $prevEdits;
842
    }
843
844
    /**
845
     * Update various figures about content sizes based on the given edit.
846
     * @param  Edit   $edit
847
     * @param  Edit[] $prevEdits With 'prev', 'prevSha', 'maxAddition' and 'maxDeletion'.
848
     * @return Edit[] Updated version of $prevEdits.
849
     */
850 4
    private function updateContentSizes(Edit $edit, $prevEdits)
851
    {
852
        // Check if it was a revert
853 4
        if ($this->isRevert($prevEdits, $edit)) {
854 4
            return $this->updateContentSizesRevert($prevEdits);
855
        } else {
856 4
            return $this->updateContentSizesNonRevert($edit, $prevEdits);
857
        }
858
    }
859
860
    /**
861
     * Is the given Edit a revert?
862
     * @param  Edit[] $prevEdits With 'prev', 'prevSha', 'maxAddition' and 'maxDeletion'.
863
     * @param  Edit $edit
864
     * @return bool
865
     */
866 4
    private function isRevert($prevEdits, $edit)
867
    {
868 4
        return $edit->getSha() === $prevEdits['prevSha'] || $edit->isRevert($this->container);
869
    }
870
871
    /**
872
     * Updates the figures on content sizes assuming the given edit was a revert of the previous one.
873
     * In such a case, we don't want to treat the previous edit as legit content addition or removal.
874
     * @param  Edit[] $prevEdits With 'prev', 'prevSha', 'maxAddition' and 'maxDeletion'.
875
     * @return Edit[] Updated version of $prevEdits, for tracking.
876
     */
877 4
    private function updateContentSizesRevert($prevEdits)
878
    {
879 4
        $this->revertCount++;
880
881
        // Adjust addedBytes given this edit was a revert of the previous one.
882 4
        if ($prevEdits['prev'] && $prevEdits['prev']->getSize() > 0) {
883
            $this->addedBytes -= $prevEdits['prev']->getSize();
884
885
            // Also deduct from the user's individual added byte count.
886
            $username = $prevEdits['prev']->getUser()->getUsername();
887
            $this->editors[$username]['added'] -= $prevEdits['prev']->getSize();
888
        }
889
890
        // @TODO: Test this against an edit war (use your sandbox).
891
        // Also remove as max added or deleted, if applicable.
892 4
        if ($this->maxAddition && $prevEdits['prev']->getId() === $this->maxAddition->getId()) {
893
            $this->maxAddition = $prevEdits['maxAddition'];
894
            $prevEdits['maxAddition'] = $prevEdits['prev']; // In the event of edit wars.
895 4
        } elseif ($this->maxDeletion && $prevEdits['prev']->getId() === $this->maxDeletion->getId()) {
896 4
            $this->maxDeletion = $prevEdits['maxDeletion'];
897 4
            $prevEdits['maxDeletion'] = $prevEdits['prev']; // In the event of edit wars.
898
        }
899
900 4
        return $prevEdits;
901
    }
902
903
    /**
904
     * Updates the figures on content sizes assuming the given edit
905
     * was NOT a revert of the previous edit.
906
     * @param  Edit   $edit
907
     * @param  Edit[] $prevEdits With 'prev', 'prevSha', 'maxAddition' and 'maxDeletion'.
908
     * @return Edit[] Updated version of $prevEdits, for tracking.
909
     */
910 4
    private function updateContentSizesNonRevert(Edit $edit, $prevEdits)
911
    {
912 4
        $editSize = $this->getEditSize($edit, $prevEdits);
913
914
        // Edit was not a revert, so treat size > 0 as content added.
915 4
        if ($editSize > 0) {
916 4
            $this->addedBytes += $editSize;
917 4
            $this->editors[$edit->getUser()->getUsername()]['added'] += $editSize;
918
919
            // Keep track of edit with max addition.
920 4
            if (!$this->maxAddition || $editSize > $this->maxAddition->getSize()) {
921
                // Keep track of old maxAddition in case we find out the next $edit was reverted
922
                // (and was also a max edit), in which case we'll want to use this one ($edit).
923 4
                $prevEdits['maxAddition'] = $this->maxAddition;
924
925 4
                $this->maxAddition = $edit;
926
            }
927 4
        } elseif ($editSize < 0 && (!$this->maxDeletion || $editSize < $this->maxDeletion->getSize())) {
928
            // Keep track of old maxDeletion in case we find out the next edit was reverted
929
            // (and was also a max deletion), in which case we'll want to use this one.
930 4
            $prevEdits['maxDeletion'] = $this->maxDeletion;
931
932 4
            $this->maxDeletion = $edit;
933
        }
934
935 4
        return $prevEdits;
936
    }
937
938
    /**
939
     * Get the size of the given edit, based on the previous edit (if present).
940
     * We also don't return the actual edit size if last revision had a length of null.
941
     * This happens when the edit follows other edits that were revision-deleted.
942
     * @see T148857 for more information.
943
     * @todo Remove once T101631 is resolved.
944
     * @param  Edit   $edit
945
     * @param  Edit[] $prevEdits With 'prev', 'prevSha', 'maxAddition' and 'maxDeletion'.
946
     * @return Edit[] Updated version of $prevEdits, for tracking.
947
     */
948 4
    private function getEditSize(Edit $edit, $prevEdits)
949
    {
950 4
        if ($prevEdits['prev'] && $prevEdits['prev']->getLength() === null) {
0 ignored issues
show
introduced by
The condition $prevEdits['prev']->getLength() === null is always false.
Loading history...
951
            return 0;
952
        } else {
953 4
            return $edit->getSize();
954
        }
955
    }
956
957
    /**
958
     * Update counts of automated tool usage for the given edit.
959
     * @param Edit $edit
960
     */
961 4
    private function updateToolCounts(Edit $edit)
962
    {
963 4
        $automatedTool = $edit->getTool($this->container);
964
965 4
        if ($automatedTool === false) {
966
            // Nothing to do.
967 4
            return;
968
        }
969
970 4
        $editYear = $edit->getYear();
971 4
        $editMonth = $edit->getMonth();
972
973 4
        $this->automatedCount++;
974 4
        $this->yearMonthCounts[$editYear]['automated']++;
975 4
        $this->yearMonthCounts[$editYear]['months'][$editMonth]['automated']++;
976
977 4
        if (!isset($this->tools[$automatedTool['name']])) {
978 4
            $this->tools[$automatedTool['name']] = [
979 4
                'count' => 1,
980 4
                'link' => $automatedTool['link'],
981
            ];
982
        } else {
983
            $this->tools[$automatedTool['name']]['count']++;
984
        }
985 4
    }
986
987
    /**
988
     * Update various counts for the year and month of the given edit.
989
     * @param Edit $edit
990
     */
991 4
    private function updateYearMonthCounts(Edit $edit)
992
    {
993 4
        $editYear = $edit->getYear();
994 4
        $editMonth = $edit->getMonth();
995
996
        // Fill in the blank arrays for the year and 12 months if needed.
997 4
        if (!isset($this->yearMonthCounts[$editYear])) {
998 4
            $this->addYearMonthCountEntry($edit);
999
        }
1000
1001
        // Increment year and month counts for all edits
1002 4
        $this->yearMonthCounts[$editYear]['all']++;
1003 4
        $this->yearMonthCounts[$editYear]['months'][$editMonth]['all']++;
1004
        // This will ultimately be the size of the page by the end of the year
1005 4
        $this->yearMonthCounts[$editYear]['size'] = (int) $edit->getLength();
1006
1007
        // Keep track of which month had the most edits
1008 4
        $editsThisMonth = $this->yearMonthCounts[$editYear]['months'][$editMonth]['all'];
1009 4
        if ($editsThisMonth > $this->maxEditsPerMonth) {
1010 4
            $this->maxEditsPerMonth = $editsThisMonth;
1011
        }
1012 4
    }
1013
1014
    /**
1015
     * Add a new entry to $this->yearMonthCounts for the given year,
1016
     * with blank values for each month. This called during self::parseHistory().
1017
     * @param Edit $edit
1018
     */
1019 4
    private function addYearMonthCountEntry(Edit $edit)
1020
    {
1021 4
        $this->yearLabels[] = $this->i18n->dateFormat($edit->getTimestamp(), 'yyyy');
1022 4
        $editYear = $edit->getYear();
1023
1024
        // Beginning of the month at 00:00:00.
1025 4
        $firstEditTime = mktime(0, 0, 0, (int) $this->firstEdit->getMonth(), 1, $this->firstEdit->getYear());
0 ignored issues
show
Bug introduced by
$this->firstEdit->getYear() of type string is incompatible with the type integer expected by parameter $year of mktime(). ( Ignorable by Annotation )

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

1025
        $firstEditTime = mktime(0, 0, 0, (int) $this->firstEdit->getMonth(), 1, /** @scrutinizer ignore-type */ $this->firstEdit->getYear());
Loading history...
1026
1027 4
        $this->yearMonthCounts[$editYear] = [
1028
            'all' => 0,
1029
            'minor' => 0,
1030
            'anon' => 0,
1031
            'automated' => 0,
1032
            'size' => 0, // Keep track of the size by the end of the year.
1033
            'events' => [],
1034
            'months' => [],
1035
        ];
1036
1037 4
        for ($i = 1; $i <= 12; $i++) {
1038 4
            $timeObj = mktime(0, 0, 0, $i, 1, $editYear);
1039
1040
            // Don't show zeros for months before the first edit or after the current month.
1041 4
            if ($timeObj < $firstEditTime || $timeObj > $this->getLastDay()) {
1042 4
                continue;
1043
            }
1044
1045 4
            $this->monthLabels[] = $this->i18n->dateFormat($timeObj, 'yyyy-MM');
1046 4
            $this->yearMonthCounts[$editYear]['months'][sprintf('%02d', $i)] = [
1047
                'all' => 0,
1048
                'minor' => 0,
1049
                'anon' => 0,
1050
                'automated' => 0,
1051
            ];
1052
        }
1053 4
    }
1054
1055
    /**
1056
     * Update the counts of anon and minor edits for year, month,
1057
     * and user of the given edit.
1058
     * @param Edit $edit
1059
     */
1060 4
    private function updateAnonMinorCounts(Edit $edit)
1061
    {
1062 4
        $editYear = $edit->getYear();
1063 4
        $editMonth = $edit->getMonth();
1064
1065
        // If anonymous, increase counts
1066 4
        if ($edit->isAnon()) {
1067 4
            $this->anonCount++;
1068 4
            $this->yearMonthCounts[$editYear]['anon']++;
1069 4
            $this->yearMonthCounts[$editYear]['months'][$editMonth]['anon']++;
1070
        }
1071
1072
        // If minor edit, increase counts
1073 4
        if ($edit->isMinor()) {
1074 4
            $this->minorCount++;
1075 4
            $this->yearMonthCounts[$editYear]['minor']++;
1076 4
            $this->yearMonthCounts[$editYear]['months'][$editMonth]['minor']++;
1077
        }
1078 4
    }
1079
1080
    /**
1081
     * Update various counts for the user of the given edit.
1082
     * @param Edit $edit
1083
     */
1084 4
    private function updateUserCounts(Edit $edit)
1085
    {
1086 4
        $username = $edit->getUser()->getUsername();
1087
1088
        // Initialize various user stats if needed.
1089 4
        if (!isset($this->editors[$username])) {
1090 4
            $this->editors[$username] = [
1091 4
                'all' => 0,
1092 4
                'minor' => 0,
1093 4
                'minorPercentage' => 0,
1094 4
                'first' => $edit->getTimestamp(),
1095 4
                'firstId' => $edit->getId(),
1096
                'last' => null,
1097
                'atbe' => null,
1098 4
                'added' => 0,
1099
            ];
1100
        }
1101
1102
        // Increment user counts
1103 4
        $this->editors[$username]['all']++;
1104 4
        $this->editors[$username]['last'] = $edit->getTimestamp();
1105 4
        $this->editors[$username]['lastId'] = $edit->getId();
1106
1107
        // Increment minor counts for this user
1108 4
        if ($edit->isMinor()) {
1109 4
            $this->editors[$username]['minor']++;
1110
        }
1111 4
    }
1112
1113
    /**
1114
     * Increment "edits per <time>" counts based on the given edit.
1115
     * @param Edit $edit
1116
     */
1117 4
    private function updateCountHistory(Edit $edit)
1118
    {
1119 4
        $editTimestamp = $edit->getTimestamp();
1120
1121 4
        if ($editTimestamp > new DateTime('-1 day')) {
1122
            $this->countHistory['day']++;
1123
        }
1124 4
        if ($editTimestamp > new DateTime('-1 week')) {
1125
            $this->countHistory['week']++;
1126
        }
1127 4
        if ($editTimestamp > new DateTime('-1 month')) {
1128
            $this->countHistory['month']++;
1129
        }
1130 4
        if ($editTimestamp > new DateTime('-1 year')) {
1131
            $this->countHistory['year']++;
1132
        }
1133 4
    }
1134
1135
    /**
1136
     * Get info about bots that edited the page.
1137
     * @return mixed[] Contains the bot's username, edit count to the page,
1138
     *   and whether or not they are currently a bot.
1139
     */
1140 1
    public function getBots()
1141
    {
1142 1
        return $this->bots;
1143
    }
1144
1145
    /**
1146
     * Set info about bots that edited the page. This is done as a private setter
1147
     * because we need this information when computing the top 10 editors,
1148
     * where we don't want to include bots.
1149
     */
1150
    private function setBots()
1151
    {
1152
        // Parse the botedits
1153
        $bots = [];
1154
        $botData = $this->getRepository()->getBotData($this->page, $this->startDate, $this->endDate);
1155
        while ($bot = $botData->fetch()) {
1156
            $bots[$bot['username']] = [
1157
                'count' => (int) $bot['count'],
1158
                'current' => $bot['current'] === 'bot',
1159
            ];
1160
        }
1161
1162
        // Sort by edit count.
1163
        uasort($bots, function ($a, $b) {
1164
            return $b['count'] - $a['count'];
1165
        });
1166
1167
        $this->bots = $bots;
1168
    }
1169
1170
    /**
1171
     * Number of edits made to the page by current or former bots.
1172
     * @param string[] $bots Used only in unit tests, where we
1173
     *   supply mock data for the bots that will get processed.
1174
     * @return int
1175
     */
1176 2
    public function getBotRevisionCount($bots = null)
1177
    {
1178 2
        if (isset($this->botRevisionCount)) {
1179
            return $this->botRevisionCount;
1180
        }
1181
1182 2
        if ($bots === null) {
1183 1
            $bots = $this->getBots();
1184
        }
1185
1186 2
        $count = 0;
1187
1188 2
        foreach ($bots as $username => $data) {
1189 2
            $count += $data['count'];
1190
        }
1191
1192 2
        $this->botRevisionCount = $count;
1193 2
        return $count;
1194
    }
1195
1196
    /**
1197
     * Query for log events during each year of the article's history,
1198
     *   and set the results in $this->yearMonthCounts.
1199
     */
1200 1
    private function setLogsEvents()
1201
    {
1202 1
        $logData = $this->getRepository()->getLogEvents(
1203 1
            $this->page,
1204 1
            $this->startDate,
1205 1
            $this->endDate
1206
        );
1207
1208 1
        foreach ($logData as $event) {
1209 1
            $time = strtotime($event['timestamp']);
1210 1
            $year = date('Y', $time);
1211
1212 1
            if (!isset($this->yearMonthCounts[$year])) {
1213
                break;
1214
            }
1215
1216 1
            $yearEvents = $this->yearMonthCounts[$year]['events'];
1217
1218
            // Convert log type value to i18n key.
1219 1
            switch ($event['log_type']) {
1220 1
                case 'protect':
1221 1
                    $action = 'protections';
1222 1
                    break;
1223 1
                case 'delete':
1224 1
                    $action = 'deletions';
1225 1
                    break;
1226
                case 'move':
1227
                    $action = 'moves';
1228
                    break;
1229
                // count pending-changes protections along with normal protections.
1230
                case 'stable':
1231
                    $action = 'protections';
1232
                    break;
1233
            }
1234
1235 1
            if (empty($yearEvents[$action])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $action does not seem to be defined for all execution paths leading up to this point.
Loading history...
1236 1
                $yearEvents[$action] = 1;
1237
            } else {
1238
                $yearEvents[$action]++;
1239
            }
1240
1241 1
            $this->yearMonthCounts[$year]['events'] = $yearEvents;
1242
        }
1243 1
    }
1244
1245
    /**
1246
     * Set statistics about the top 10 editors by added text and number of edits.
1247
     * This is ran *after* parseHistory() since we need the grand totals first.
1248
     * Various stats are also set for each editor in $this->editors to be used in the charts.
1249
     * @return integer Number of edits
1250
     */
1251 4
    private function setTopTenCounts()
1252
    {
1253 4
        $topTenCount = $counter = 0;
1254 4
        $topTenEditors = [];
1255
1256 4
        foreach ($this->editors as $editor => $info) {
1257
            // Count how many users are in the top 10% by number of edits, excluding bots.
1258 4
            if ($counter < 10 && !in_array($editor, array_keys($this->bots))) {
1259 4
                $topTenCount += $info['all'];
1260 4
                $counter++;
1261
1262
                // To be used in the Top Ten charts.
1263 4
                $topTenEditors[] = [
1264 4
                    'label' => $editor,
1265 4
                    'value' => $info['all'],
1266
                    'percentage' => (
1267 4
                        100 * ($info['all'] / $this->getNumRevisionsProcessed())
1268
                    )
1269
                ];
1270
            }
1271
1272
            // Compute the percentage of minor edits the user made.
1273 4
            $this->editors[$editor]['minorPercentage'] = $info['all']
1274 4
                ? ($info['minor'] / $info['all']) * 100
1275
                : 0;
1276
1277 4
            if ($info['all'] > 1) {
1278
                // Number of seconds/days between first and last edit.
1279 4
                $secs = $info['last']->getTimestamp() - $info['first']->getTimestamp();
1280 4
                $days = $secs / (60 * 60 * 24);
1281
1282
                // Average time between edits (in days).
1283 4
                $this->editors[$editor]['atbe'] = $days / $info['all'];
1284
            }
1285
        }
1286
1287 4
        $this->topTenEditorsByEdits = $topTenEditors;
1288
1289
        // First sort editors array by the amount of text they added.
1290 4
        $topTenEditorsByAdded = $this->editors;
1291
        uasort($topTenEditorsByAdded, function ($a, $b) {
1292 4
            if ($a['added'] === $b['added']) {
1293 4
                return 0;
1294
            }
1295 4
            return $a['added'] > $b['added'] ? -1 : 1;
1296 4
        });
1297
1298
        // Then build a new array of top 10 editors by added text,
1299
        // in the data structure needed for the chart.
1300
        $this->topTenEditorsByAdded = array_map(function ($editor) {
1301 4
            $added = $this->editors[$editor]['added'];
1302
            return [
1303 4
                'label' => $editor,
1304 4
                'value' => $added,
1305
                'percentage' => (
1306 4
                    100 * ($added / $this->addedBytes)
1307
                )
1308
            ];
1309 4
        }, array_keys(array_slice($topTenEditorsByAdded, 0, 10, true)));
1310
1311 4
        $this->topTenCount = $topTenCount;
1312 4
    }
1313
1314
    /**
1315
     * Get authorship attribution from the WikiWho API.
1316
     * @see https://f-squared.org/wikiwho/
1317
     * @param  int $limit Max number of results.
1318
     * @return array
1319
     */
1320 1
    public function getTextshares($limit = null)
1321
    {
1322 1
        if (isset($this->textshares)) {
1323
            return $this->textshares;
1324
        }
1325
1326
        // TODO: check for failures. Should have a success:true
1327 1
        $ret = $this->getRepository()->getTextshares($this->page);
1328
1329
        // If revision can't be found, return error message.
1330 1
        if (!isset($ret['revisions'][0])) {
1331
            return [
1332
                'error' => isset($ret['Error']) ? $ret['Error'] : 'Unknown'
1333
            ];
1334
        }
1335
1336 1
        $revId = array_keys($ret['revisions'][0])[0];
1337 1
        $tokens = $ret['revisions'][0][$revId]['tokens'];
1338
1339 1
        list($counts, $totalCount, $userIds) = $this->countTokens($tokens);
1340 1
        $usernameMap = $this->getUsernameMap($userIds);
1341
1342 1
        if ($limit !== null) {
1343 1
            $countsToProcess = array_slice($counts, 0, $limit, true);
1344
        } else {
1345
            $countsToProcess = $counts;
1346
        }
1347
1348 1
        $textshares = [];
1349
1350
        // Loop through once more, creating an array with the user names (or IP address)
1351
        // as the key, and the count and percentage as the value.
1352 1
        foreach ($countsToProcess as $editor => $count) {
1353 1
            if (isset($usernameMap[$editor])) {
1354 1
                $index = $usernameMap[$editor];
1355
            } else {
1356 1
                $index = $editor;
1357
            }
1358 1
            $textshares[$index] = [
1359 1
                'count' => $count,
1360 1
                'percentage' => round(100 * ($count / $totalCount), 1)
1361
            ];
1362
        }
1363
1364 1
        $this->textshares = [
1365 1
            'list' => $textshares,
1366 1
            'totalAuthors' => count($counts),
1367 1
            'totalCount' => $totalCount,
1368
        ];
1369
1370 1
        return $this->textshares;
1371
    }
1372
1373
    /**
1374
     * Get a map of user IDs to usernames, given the IDs.
1375
     * @param  int[] $userIds
1376
     * @return array IDs as keys, usernames as values.
1377
     */
1378 1
    private function getUsernameMap($userIds)
1379
    {
1380 1
        $userIdsNames = $this->getRepository()->getUsernamesFromIds(
1381 1
            $this->page->getProject(),
1382 1
            $userIds
1383
        );
1384
1385 1
        $usernameMap = [];
1386 1
        foreach ($userIdsNames as $userIdName) {
1387 1
            $usernameMap[$userIdName['user_id']] = $userIdName['user_name'];
1388
        }
1389
1390 1
        return $usernameMap;
1391
    }
1392
1393
    /**
1394
     * Get counts of token lengths for each author. Used in self::getTextshares()
1395
     * @param  array $tokens
1396
     * @return array [counts by user, total count, IDs of accounts]
1397
     */
1398 1
    private function countTokens($tokens)
1399
    {
1400 1
        $counts = [];
1401 1
        $userIds = [];
1402 1
        $totalCount = 0;
1403
1404
        // Loop through the tokens, keeping totals (token length) for each author.
1405 1
        foreach ($tokens as $token) {
1406 1
            $editor = $token['editor'];
1407
1408
            // IPs are prefixed with '0|', otherwise it's the user ID.
1409 1
            if (substr($editor, 0, 2) === '0|') {
1410 1
                $editor = substr($editor, 2);
1411
            } else {
1412 1
                $userIds[] = $editor;
1413
            }
1414
1415 1
            if (!isset($counts[$editor])) {
1416 1
                $counts[$editor] = 0;
1417
            }
1418
1419 1
            $counts[$editor] += strlen($token['str']);
1420 1
            $totalCount += strlen($token['str']);
1421
        }
1422
1423
        // Sort authors by count.
1424 1
        arsort($counts);
1425
1426 1
        return [$counts, $totalCount, $userIds];
1427
    }
1428
1429
    /**
1430
     * Get a list of wikis supported by WikiWho.
1431
     * @return string[]
1432
     * @codeCoverageIgnore
1433
     */
1434
    public function getTextshareWikis()
1435
    {
1436
        return self::TEXTSHARE_WIKIS;
1437
    }
1438
1439
    /**
1440
     * Get prose and reference information.
1441
     * @return array With keys 'characters', 'words', 'references', 'unique_references'
1442
     */
1443 1
    public function getProseStats()
1444
    {
1445 1
        $datetime = $this->endDate !== false ? new DateTime('@'.$this->endDate) : null;
0 ignored issues
show
Bug introduced by
Are you sure $this->endDate of type integer|true can be used in concatenation? ( Ignorable by Annotation )

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

1445
        $datetime = $this->endDate !== false ? new DateTime('@'./** @scrutinizer ignore-type */ $this->endDate) : null;
Loading history...
1446 1
        $html = $this->page->getHTMLContent($datetime);
1447
1448 1
        $crawler = new Crawler($html);
1449
1450 1
        list($chars, $words) = $this->countCharsAndWords($crawler, '#mw-content-text p');
1451
1452 1
        $refs = $crawler->filter('#mw-content-text .reference');
1453 1
        $refContent = [];
1454
        $refs->each(function ($ref) use (&$refContent) {
1455 1
            $refContent[] = $ref->text();
1456 1
        });
1457 1
        $uniqueRefs = count(array_unique($refContent));
1458
1459 1
        $sections = count($crawler->filter('#mw-content-text .mw-headline'));
1460
1461
        return [
1462 1
            'characters' => $chars,
1463 1
            'words' => $words,
1464 1
            'references' => $refs->count(),
1465 1
            'unique_references' => $uniqueRefs,
1466 1
            'sections' => $sections,
1467
        ];
1468
    }
1469
1470
    /**
1471
     * Count the number of characters and words of the plain text
1472
     * within the DOM element matched by the given selector.
1473
     * @param  Crawler $crawler
1474
     * @param  string $selector HTML selector.
1475
     * @return array [num chars, num words]
1476
     */
1477 1
    private function countCharsAndWords($crawler, $selector)
1478
    {
1479 1
        $totalChars = 0;
1480 1
        $totalWords = 0;
1481 1
        $paragraphs = $crawler->filter($selector);
1482 1
        $paragraphs->each(function ($node) use (&$totalChars, &$totalWords) {
1483 1
            $text = preg_replace('/\[\d+\]/', '', trim($node->text()));
1484 1
            $totalChars += strlen($text);
1485 1
            $totalWords += count(explode(' ', $text));
1486 1
        });
1487
1488 1
        return [$totalChars, $totalWords];
1489
    }
1490
1491
    /**
1492
     * Fetch transclusion data (categories, templates and files)
1493
     * that are on the page.
1494
     * @return array With keys 'categories', 'templates' and 'files'.
1495
     */
1496 1
    private function getTransclusionData()
1497
    {
1498 1
        if (!is_array($this->transclusionData)) {
0 ignored issues
show
introduced by
The condition is_array($this->transclusionData) is always true.
Loading history...
1499 1
            $this->transclusionData = $this->getRepository()
1500 1
                ->getTransclusionData($this->page);
1501
        }
1502 1
        return $this->transclusionData;
1503
    }
1504
1505
    /**
1506
     * Get the number of categories that are on the page.
1507
     * @return int
1508
     */
1509 1
    public function getNumCategories()
1510
    {
1511 1
        return $this->getTransclusionData()['categories'];
1512
    }
1513
1514
    /**
1515
     * Get the number of templates that are on the page.
1516
     * @return int
1517
     */
1518 1
    public function getNumTemplates()
1519
    {
1520 1
        return $this->getTransclusionData()['templates'];
1521
    }
1522
1523
    /**
1524
     * Get the number of files that are on the page.
1525
     * @return int
1526
     */
1527 1
    public function getNumFiles()
1528
    {
1529 1
        return $this->getTransclusionData()['files'];
1530
    }
1531
}
1532