Passed
Push — master ( 782005...8964b9 )
by MusikAnimal
06:51
created

ArticleInfo::getBugs()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 6
ccs 0
cts 4
cp 0
crap 6
rs 9.4285
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))
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);
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->getAssessments();
486
        }
487
        return $this->assessments;
488
    }
489
490
    /**
491
     * Get the number of automated edits made to the page.
492
     * @return int
493
     */
494 1
    public function getAutomatedCount()
495
    {
496 1
        return $this->automatedCount;
497
    }
498
499
    /**
500
     * Get the number of edits to the page that were reverted with the subsequent edit.
501
     * @return int
502
     */
503 1
    public function getRevertCount()
504
    {
505 1
        return $this->revertCount;
506
    }
507
508
    /**
509
     * Get the number of edits to the page made by logged out users.
510
     * @return int
511
     */
512 1
    public function getAnonCount()
513
    {
514 1
        return $this->anonCount;
515
    }
516
517
    /**
518
     * Get the number of minor edits to the page.
519
     * @return int
520
     */
521 1
    public function getMinorCount()
522
    {
523 1
        return $this->minorCount;
524
    }
525
526
    /**
527
     * Get the number of edits to the page made in the past day, week, month and year.
528
     * @return int[] With keys 'day', 'week', 'month' and 'year'.
529
     */
530
    public function getCountHistory()
531
    {
532
        return $this->countHistory;
533
    }
534
535
    /**
536
     * Get the number of edits to the page made by the top 10 editors.
537
     * @return int
538
     */
539 1
    public function getTopTenCount()
540
    {
541 1
        return $this->topTenCount;
542
    }
543
544
    /**
545
     * Get the first edit to the page.
546
     * @return Edit
547
     */
548 1
    public function getFirstEdit()
549
    {
550 1
        return $this->firstEdit;
551
    }
552
553
    /**
554
     * Get the last edit to the page.
555
     * @return Edit
556
     */
557 1
    public function getLastEdit()
558
    {
559 1
        return $this->lastEdit;
560
    }
561
562
    /**
563
     * Get the edit that made the largest addition to the page (by number of bytes).
564
     * @return Edit
565
     */
566 1
    public function getMaxAddition()
567
    {
568 1
        return $this->maxAddition;
569
    }
570
571
    /**
572
     * Get the edit that made the largest removal to the page (by number of bytes).
573
     * @return Edit
574
     */
575 1
    public function getMaxDeletion()
576
    {
577 1
        return $this->maxDeletion;
578
    }
579
580
    /**
581
     * Get the list of editors to the page, including various statistics.
582
     * @return mixed[]
583
     */
584 1
    public function getEditors()
585
    {
586 1
        return $this->editors;
587
    }
588
589
    /**
590
     * Get the list of the top editors to the page (by edits), including various statistics.
591
     * @return mixed[]
592
     */
593 1
    public function topTenEditorsByEdits()
594
    {
595 1
        return $this->topTenEditorsByEdits;
596
    }
597
598
    /**
599
     * Get the list of the top editors to the page (by added text), including various statistics.
600
     * @return mixed[]
601
     */
602 1
    public function topTenEditorsByAdded()
603
    {
604 1
        return $this->topTenEditorsByAdded;
605
    }
606
607
    /**
608
     * Get various counts about each individual year and month of the page's history.
609
     * @return mixed[]
610
     */
611 2
    public function getYearMonthCounts()
612
    {
613 2
        return $this->yearMonthCounts;
614
    }
615
616
    /**
617
     * Get the localized labels for the 'Year counts' chart.
618
     * @return string[]
619
     */
620
    public function getYearLabels()
621
    {
622
        return $this->yearLabels;
623
    }
624
625
    /**
626
     * Get the localized labels for the 'Month counts' chart.
627
     * @return string[]
628
     */
629
    public function getMonthLabels()
630
    {
631
        return $this->monthLabels;
632
    }
633
634
    /**
635
     * Get the maximum number of edits that were created across all months. This is used as a
636
     * comparison for the bar charts in the months section.
637
     * @return int
638
     */
639 1
    public function getMaxEditsPerMonth()
640
    {
641 1
        return $this->maxEditsPerMonth;
642
    }
643
644
    /**
645
     * Get a list of (semi-)automated tools that were used to edit the page, including
646
     * the number of times they were used, and a link to the tool's homepage.
647
     * @return mixed[]
648
     */
649 1
    public function getTools()
650
    {
651 1
        return $this->tools;
652
    }
653
654
    /**
655
     * Get the list of page's wikidata and Checkwiki errors.
656
     * @see Page::getErrors()
657
     * @return string[]
658
     */
659
    public function getBugs()
660
    {
661
        if (!is_array($this->bugs)) {
0 ignored issues
show
introduced by
The condition is_array($this->bugs) is always true.
Loading history...
662
            $this->bugs = $this->page->getErrors();
663
        }
664
        return $this->bugs;
665
    }
666
667
    /**
668
     * Get the number of wikidata nad CheckWiki errors.
669
     * @return int
670
     */
671
    public function numBugs()
672
    {
673
        return count($this->getBugs());
674
    }
675
676
    /**
677
     * Get the number of external links on the page.
678
     * @return int
679
     */
680 1
    public function linksExtCount()
681
    {
682 1
        return $this->getLinksAndRedirects()['links_ext_count'];
683
    }
684
685
    /**
686
     * Get the number of incoming links to the page.
687
     * @return int
688
     */
689 1
    public function linksInCount()
690
    {
691 1
        return $this->getLinksAndRedirects()['links_in_count'];
692
    }
693
694
    /**
695
     * Get the number of outgoing links from the page.
696
     * @return int
697
     */
698 1
    public function linksOutCount()
699
    {
700 1
        return $this->getLinksAndRedirects()['links_out_count'];
701
    }
702
703
    /**
704
     * Get the number of redirects to the page.
705
     * @return int
706
     */
707 1
    public function redirectsCount()
708
    {
709 1
        return $this->getLinksAndRedirects()['redirects_count'];
710
    }
711
712
    /**
713
     * Get the number of external, incoming and outgoing links, along with
714
     * the number of redirects to the page.
715
     * @return int
716
     * @codeCoverageIgnore
717
     */
718
    private function getLinksAndRedirects()
719
    {
720
        if (!is_array($this->linksAndRedirects)) {
0 ignored issues
show
introduced by
The condition is_array($this->linksAndRedirects) is always true.
Loading history...
721
            $this->linksAndRedirects = $this->page->countLinksAndRedirects();
722
        }
723
        return $this->linksAndRedirects;
724
    }
725
726
    /**
727
     * Parse the revision history, collecting our core statistics.
728
     * @return mixed[] Associative "master" array of metadata about the page.
729
     *
730
     * Untestable because it relies on getting a PDO statement. All the important
731
     * logic lives in other methods which are tested.
732
     * @codeCoverageIgnore
733
     */
734
    private function parseHistory()
735
    {
736
        if ($this->tooManyRevisions()) {
737
            $limit = $this->getMaxRevisions();
738
        } else {
739
            $limit = null;
740
        }
741
742
        // Third parameter is ignored if $limit is null.
743
        $revStmt = $this->page->getRevisionsStmt(
744
            null,
745
            $limit,
746
            $this->getNumRevisions(),
747
            $this->startDate,
748
            $this->endDate
749
        );
750
        $revCount = 0;
751
752
        /**
753
         * Data about previous edits so that we can use them as a basis for comparison.
754
         * @var Edit[]
755
         */
756
        $prevEdits = [
757
            // The previous Edit, used to discount content that was reverted.
758
            'prev' => null,
759
760
            // The SHA-1 of the edit *before* the previous edit. Used for more
761
            // accruate revert detection.
762
            'prevSha' => null,
763
764
            // The last edit deemed to be the max addition of content. This is kept track of
765
            // in case we find out the next edit was reverted (and was also a max edit),
766
            // in which case we'll want to discount it and use this one instead.
767
            'maxAddition' => null,
768
769
            // Same as with maxAddition, except the maximum amount of content deleted.
770
            // This is used to discount content that was reverted.
771
            'maxDeletion' => null,
772
        ];
773
774
        while ($rev = $revStmt->fetch()) {
775
            $edit = new Edit($this->page, $rev);
776
777
            if ($revCount === 0) {
778
                $this->firstEdit = $edit;
779
            }
780
781
            // Sometimes, with old revisions (2001 era), the revisions from 2002 come before 2001
782
            if ($edit->getTimestamp() < $this->firstEdit->getTimestamp()) {
783
                $this->firstEdit = $edit;
784
            }
785
786
            $prevEdits = $this->updateCounts($edit, $prevEdits);
787
788
            $revCount++;
789
        }
790
791
        $this->numRevisionsProcessed = $revCount;
792
793
        // Various sorts
794
        arsort($this->editors);
795
        ksort($this->yearMonthCounts);
796
        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...
797
            arsort($this->tools);
798
        }
799
    }
800
801
    /**
802
     * Update various counts based on the current edit.
803
     * @param  Edit   $edit
804
     * @param  Edit[] $prevEdits With 'prev', 'prevSha', 'maxAddition' and 'maxDeletion'
805
     * @return Edit[] Updated version of $prevEdits.
806
     */
807 4
    private function updateCounts(Edit $edit, $prevEdits)
808
    {
809
        // Update the counts for the year and month of the current edit.
810 4
        $this->updateYearMonthCounts($edit);
811
812
        // Update counts for the user who made the edit.
813 4
        $this->updateUserCounts($edit);
814
815
        // Update the year/month/user counts of anon and minor edits.
816 4
        $this->updateAnonMinorCounts($edit);
817
818
        // Update counts for automated tool usage, if applicable.
819 4
        $this->updateToolCounts($edit);
820
821
        // Increment "edits per <time>" counts
822 4
        $this->updateCountHistory($edit);
823
824
        // Update figures regarding content addition/removal, and the revert count.
825 4
        $prevEdits = $this->updateContentSizes($edit, $prevEdits);
826
827
        // Now that we've updated all the counts, we can reset
828
        // the prev and last edits, which are used for tracking.
829
        // But first, let's copy over the SHA of the actual previous edit
830
        // and put it in our $prevEdits['prev'], so that we'll know
831
        // that content added after $prevEdit['prev'] was reverted.
832 4
        if ($prevEdits['prev'] !== null) {
833 4
            $prevEdits['prevSha'] = $prevEdits['prev']->getSha();
834
        }
835 4
        $prevEdits['prev'] = $edit;
836 4
        $this->lastEdit = $edit;
837
838 4
        return $prevEdits;
839
    }
840
841
    /**
842
     * Update various figures about content sizes based on the given edit.
843
     * @param  Edit   $edit
844
     * @param  Edit[] $prevEdits With 'prev', 'prevSha', 'maxAddition' and 'maxDeletion'.
845
     * @return Edit[] Updated version of $prevEdits.
846
     */
847 4
    private function updateContentSizes(Edit $edit, $prevEdits)
848
    {
849
        // Check if it was a revert
850 4
        if ($this->isRevert($prevEdits, $edit)) {
851 4
            return $this->updateContentSizesRevert($prevEdits);
852
        } else {
853 4
            return $this->updateContentSizesNonRevert($edit, $prevEdits);
854
        }
855
    }
856
857
    /**
858
     * Is the given Edit a revert?
859
     * @param  Edit[] $prevEdits With 'prev', 'prevSha', 'maxAddition' and 'maxDeletion'.
860
     * @param  Edit $edit
861
     * @return bool
862
     */
863 4
    private function isRevert($prevEdits, $edit)
864
    {
865 4
        return $edit->getSha() === $prevEdits['prevSha'] || $edit->isRevert($this->container);
866
    }
867
868
    /**
869
     * Updates the figures on content sizes assuming the given edit was a revert of the previous one.
870
     * In such a case, we don't want to treat the previous edit as legit content addition or removal.
871
     * @param  Edit[] $prevEdits With 'prev', 'prevSha', 'maxAddition' and 'maxDeletion'.
872
     * @return Edit[] Updated version of $prevEdits, for tracking.
873
     */
874 4
    private function updateContentSizesRevert($prevEdits)
875
    {
876 4
        $this->revertCount++;
877
878
        // Adjust addedBytes given this edit was a revert of the previous one.
879 4
        if ($prevEdits['prev'] && $prevEdits['prev']->getSize() > 0) {
880
            $this->addedBytes -= $prevEdits['prev']->getSize();
881
882
            // Also deduct from the user's individual added byte count.
883
            $username = $prevEdits['prev']->getUser()->getUsername();
884
            $this->editors[$username]['added'] -= $prevEdits['prev']->getSize();
885
        }
886
887
        // @TODO: Test this against an edit war (use your sandbox).
888
        // Also remove as max added or deleted, if applicable.
889 4
        if ($this->maxAddition && $prevEdits['prev']->getId() === $this->maxAddition->getId()) {
890
            $this->maxAddition = $prevEdits['maxAddition'];
891
            $prevEdits['maxAddition'] = $prevEdits['prev']; // In the event of edit wars.
892 4
        } elseif ($this->maxDeletion && $prevEdits['prev']->getId() === $this->maxDeletion->getId()) {
893 4
            $this->maxDeletion = $prevEdits['maxDeletion'];
894 4
            $prevEdits['maxDeletion'] = $prevEdits['prev']; // In the event of edit wars.
895
        }
896
897 4
        return $prevEdits;
898
    }
899
900
    /**
901
     * Updates the figures on content sizes assuming the given edit
902
     * was NOT a revert of the previous edit.
903
     * @param  Edit   $edit
904
     * @param  Edit[] $prevEdits With 'prev', 'prevSha', 'maxAddition' and 'maxDeletion'.
905
     * @return Edit[] Updated version of $prevEdits, for tracking.
906
     */
907 4
    private function updateContentSizesNonRevert(Edit $edit, $prevEdits)
908
    {
909 4
        $editSize = $this->getEditSize($edit, $prevEdits);
910
911
        // Edit was not a revert, so treat size > 0 as content added.
912 4
        if ($editSize > 0) {
913 4
            $this->addedBytes += $editSize;
914 4
            $this->editors[$edit->getUser()->getUsername()]['added'] += $editSize;
915
916
            // Keep track of edit with max addition.
917 4
            if (!$this->maxAddition || $editSize > $this->maxAddition->getSize()) {
918
                // Keep track of old maxAddition in case we find out the next $edit was reverted
919
                // (and was also a max edit), in which case we'll want to use this one ($edit).
920 4
                $prevEdits['maxAddition'] = $this->maxAddition;
921
922 4
                $this->maxAddition = $edit;
923
            }
924 4
        } elseif ($editSize < 0 && (!$this->maxDeletion || $editSize < $this->maxDeletion->getSize())) {
925
            // Keep track of old maxDeletion in case we find out the next edit was reverted
926
            // (and was also a max deletion), in which case we'll want to use this one.
927 4
            $prevEdits['maxDeletion'] = $this->maxDeletion;
928
929 4
            $this->maxDeletion = $edit;
930
        }
931
932 4
        return $prevEdits;
933
    }
934
935
    /**
936
     * Get the size of the given edit, based on the previous edit (if present).
937
     * We also don't return the actual edit size if last revision had a length of null.
938
     * This happens when the edit follows other edits that were revision-deleted.
939
     * @see T148857 for more information.
940
     * @todo Remove once T101631 is resolved.
941
     * @param  Edit   $edit
942
     * @param  Edit[] $prevEdits With 'prev', 'prevSha', 'maxAddition' and 'maxDeletion'.
943
     * @return Edit[] Updated version of $prevEdits, for tracking.
944
     */
945 4
    private function getEditSize(Edit $edit, $prevEdits)
946
    {
947 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...
948
            return 0;
949
        } else {
950 4
            return $edit->getSize();
951
        }
952
    }
953
954
    /**
955
     * Update counts of automated tool usage for the given edit.
956
     * @param Edit $edit
957
     */
958 4
    private function updateToolCounts(Edit $edit)
959
    {
960 4
        $automatedTool = $edit->getTool($this->container);
961
962 4
        if ($automatedTool === false) {
963
            // Nothing to do.
964 4
            return;
965
        }
966
967 4
        $editYear = $edit->getYear();
968 4
        $editMonth = $edit->getMonth();
969
970 4
        $this->automatedCount++;
971 4
        $this->yearMonthCounts[$editYear]['automated']++;
972 4
        $this->yearMonthCounts[$editYear]['months'][$editMonth]['automated']++;
973
974 4
        if (!isset($this->tools[$automatedTool['name']])) {
975 4
            $this->tools[$automatedTool['name']] = [
976 4
                'count' => 1,
977 4
                'link' => $automatedTool['link'],
978
            ];
979
        } else {
980
            $this->tools[$automatedTool['name']]['count']++;
981
        }
982 4
    }
983
984
    /**
985
     * Update various counts for the year and month of the given edit.
986
     * @param Edit $edit
987
     */
988 4
    private function updateYearMonthCounts(Edit $edit)
989
    {
990 4
        $editYear = $edit->getYear();
991 4
        $editMonth = $edit->getMonth();
992
993
        // Fill in the blank arrays for the year and 12 months if needed.
994 4
        if (!isset($this->yearMonthCounts[$editYear])) {
995 4
            $this->addYearMonthCountEntry($edit);
996
        }
997
998
        // Increment year and month counts for all edits
999 4
        $this->yearMonthCounts[$editYear]['all']++;
1000 4
        $this->yearMonthCounts[$editYear]['months'][$editMonth]['all']++;
1001
        // This will ultimately be the size of the page by the end of the year
1002 4
        $this->yearMonthCounts[$editYear]['size'] = (int) $edit->getLength();
1003
1004
        // Keep track of which month had the most edits
1005 4
        $editsThisMonth = $this->yearMonthCounts[$editYear]['months'][$editMonth]['all'];
1006 4
        if ($editsThisMonth > $this->maxEditsPerMonth) {
1007 4
            $this->maxEditsPerMonth = $editsThisMonth;
1008
        }
1009 4
    }
1010
1011
    /**
1012
     * Add a new entry to $this->yearMonthCounts for the given year,
1013
     * with blank values for each month. This called during self::parseHistory().
1014
     * @param Edit $edit
1015
     */
1016 4
    private function addYearMonthCountEntry(Edit $edit)
1017
    {
1018 4
        $this->yearLabels[] = $this->i18n->dateFormat($edit->getTimestamp(), 'yyyy');
1019 4
        $editYear = $edit->getYear();
1020
1021
        // Beginning of the month at 00:00:00.
1022 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

1022
        $firstEditTime = mktime(0, 0, 0, (int) $this->firstEdit->getMonth(), 1, /** @scrutinizer ignore-type */ $this->firstEdit->getYear());
Loading history...
1023
1024 4
        $this->yearMonthCounts[$editYear] = [
1025
            'all' => 0,
1026
            'minor' => 0,
1027
            'anon' => 0,
1028
            'automated' => 0,
1029
            'size' => 0, // Keep track of the size by the end of the year.
1030
            'events' => [],
1031
            'months' => [],
1032
        ];
1033
1034 4
        for ($i = 1; $i <= 12; $i++) {
1035 4
            $timeObj = mktime(0, 0, 0, $i, 1, $editYear);
1036
1037
            // Don't show zeros for months before the first edit or after the current month.
1038 4
            if ($timeObj < $firstEditTime || $timeObj > $this->getLastDay()) {
1039 4
                continue;
1040
            }
1041
1042 4
            $this->monthLabels[] = $this->i18n->dateFormat($timeObj, 'yyyy-MM');
1043 4
            $this->yearMonthCounts[$editYear]['months'][sprintf('%02d', $i)] = [
1044
                'all' => 0,
1045
                'minor' => 0,
1046
                'anon' => 0,
1047
                'automated' => 0,
1048
            ];
1049
        }
1050 4
    }
1051
1052
    /**
1053
     * Update the counts of anon and minor edits for year, month,
1054
     * and user of the given edit.
1055
     * @param Edit $edit
1056
     */
1057 4
    private function updateAnonMinorCounts(Edit $edit)
1058
    {
1059 4
        $editYear = $edit->getYear();
1060 4
        $editMonth = $edit->getMonth();
1061
1062
        // If anonymous, increase counts
1063 4
        if ($edit->isAnon()) {
1064 4
            $this->anonCount++;
1065 4
            $this->yearMonthCounts[$editYear]['anon']++;
1066 4
            $this->yearMonthCounts[$editYear]['months'][$editMonth]['anon']++;
1067
        }
1068
1069
        // If minor edit, increase counts
1070 4
        if ($edit->isMinor()) {
1071 4
            $this->minorCount++;
1072 4
            $this->yearMonthCounts[$editYear]['minor']++;
1073 4
            $this->yearMonthCounts[$editYear]['months'][$editMonth]['minor']++;
1074
        }
1075 4
    }
1076
1077
    /**
1078
     * Update various counts for the user of the given edit.
1079
     * @param Edit $edit
1080
     */
1081 4
    private function updateUserCounts(Edit $edit)
1082
    {
1083 4
        $username = $edit->getUser()->getUsername();
1084
1085
        // Initialize various user stats if needed.
1086 4
        if (!isset($this->editors[$username])) {
1087 4
            $this->editors[$username] = [
1088 4
                'all' => 0,
1089 4
                'minor' => 0,
1090 4
                'minorPercentage' => 0,
1091 4
                'first' => $edit->getTimestamp(),
1092 4
                'firstId' => $edit->getId(),
1093
                'last' => null,
1094
                'atbe' => null,
1095 4
                'added' => 0,
1096
            ];
1097
        }
1098
1099
        // Increment user counts
1100 4
        $this->editors[$username]['all']++;
1101 4
        $this->editors[$username]['last'] = $edit->getTimestamp();
1102 4
        $this->editors[$username]['lastId'] = $edit->getId();
1103
1104
        // Increment minor counts for this user
1105 4
        if ($edit->isMinor()) {
1106 4
            $this->editors[$username]['minor']++;
1107
        }
1108 4
    }
1109
1110
    /**
1111
     * Increment "edits per <time>" counts based on the given edit.
1112
     * @param Edit $edit
1113
     */
1114 4
    private function updateCountHistory(Edit $edit)
1115
    {
1116 4
        $editTimestamp = $edit->getTimestamp();
1117
1118 4
        if ($editTimestamp > new DateTime('-1 day')) {
1119
            $this->countHistory['day']++;
1120
        }
1121 4
        if ($editTimestamp > new DateTime('-1 week')) {
1122
            $this->countHistory['week']++;
1123
        }
1124 4
        if ($editTimestamp > new DateTime('-1 month')) {
1125
            $this->countHistory['month']++;
1126
        }
1127 4
        if ($editTimestamp > new DateTime('-1 year')) {
1128
            $this->countHistory['year']++;
1129
        }
1130 4
    }
1131
1132
    /**
1133
     * Get info about bots that edited the page.
1134
     * @return mixed[] Contains the bot's username, edit count to the page,
1135
     *   and whether or not they are currently a bot.
1136
     */
1137 1
    public function getBots()
1138
    {
1139 1
        return $this->bots;
1140
    }
1141
1142
    /**
1143
     * Set info about bots that edited the page. This is done as a private setter
1144
     * because we need this information when computing the top 10 editors,
1145
     * where we don't want to include bots.
1146
     */
1147
    private function setBots()
1148
    {
1149
        // Parse the botedits
1150
        $bots = [];
1151
        $botData = $this->getRepository()->getBotData($this->page, $this->startDate, $this->endDate);
1152
        while ($bot = $botData->fetch()) {
1153
            $bots[$bot['username']] = [
1154
                'count' => (int) $bot['count'],
1155
                'current' => $bot['current'] === 'bot',
1156
            ];
1157
        }
1158
1159
        // Sort by edit count.
1160
        uasort($bots, function ($a, $b) {
1161
            return $b['count'] - $a['count'];
1162
        });
1163
1164
        $this->bots = $bots;
1165
    }
1166
1167
    /**
1168
     * Number of edits made to the page by current or former bots.
1169
     * @param string[] $bots Used only in unit tests, where we
1170
     *   supply mock data for the bots that will get processed.
1171
     * @return int
1172
     */
1173 2
    public function getBotRevisionCount($bots = null)
1174
    {
1175 2
        if (isset($this->botRevisionCount)) {
1176
            return $this->botRevisionCount;
1177
        }
1178
1179 2
        if ($bots === null) {
1180 1
            $bots = $this->getBots();
1181
        }
1182
1183 2
        $count = 0;
1184
1185 2
        foreach ($bots as $username => $data) {
1186 2
            $count += $data['count'];
1187
        }
1188
1189 2
        $this->botRevisionCount = $count;
1190 2
        return $count;
1191
    }
1192
1193
    /**
1194
     * Query for log events during each year of the article's history,
1195
     *   and set the results in $this->yearMonthCounts.
1196
     */
1197 1
    private function setLogsEvents()
1198
    {
1199 1
        $logData = $this->getRepository()->getLogEvents(
0 ignored issues
show
Bug introduced by
The method getLogEvents() does not exist on Xtools\Repository. Did you maybe mean getLog()? ( Ignorable by Annotation )

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

1199
        $logData = $this->getRepository()->/** @scrutinizer ignore-call */ getLogEvents(

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...
1200 1
            $this->page,
1201 1
            $this->startDate,
1202 1
            $this->endDate
1203
        );
1204
1205 1
        foreach ($logData as $event) {
1206 1
            $time = strtotime($event['timestamp']);
1207 1
            $year = date('Y', $time);
1208
1209 1
            if (!isset($this->yearMonthCounts[$year])) {
1210
                break;
1211
            }
1212
1213 1
            $yearEvents = $this->yearMonthCounts[$year]['events'];
1214
1215
            // Convert log type value to i18n key.
1216 1
            switch ($event['log_type']) {
1217 1
                case 'protect':
1218 1
                    $action = 'protections';
1219 1
                    break;
1220 1
                case 'delete':
1221 1
                    $action = 'deletions';
1222 1
                    break;
1223
                case 'move':
1224
                    $action = 'moves';
1225
                    break;
1226
                // count pending-changes protections along with normal protections.
1227
                case 'stable':
1228
                    $action = 'protections';
1229
                    break;
1230
            }
1231
1232 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...
1233 1
                $yearEvents[$action] = 1;
1234
            } else {
1235
                $yearEvents[$action]++;
1236
            }
1237
1238 1
            $this->yearMonthCounts[$year]['events'] = $yearEvents;
1239
        }
1240 1
    }
1241
1242
    /**
1243
     * Set statistics about the top 10 editors by added text and number of edits.
1244
     * This is ran *after* parseHistory() since we need the grand totals first.
1245
     * Various stats are also set for each editor in $this->editors to be used in the charts.
1246
     * @return integer Number of edits
1247
     */
1248 4
    private function setTopTenCounts()
1249
    {
1250 4
        $topTenCount = $counter = 0;
1251 4
        $topTenEditors = [];
1252
1253 4
        foreach ($this->editors as $editor => $info) {
1254
            // Count how many users are in the top 10% by number of edits, excluding bots.
1255 4
            if ($counter < 10 && !in_array($editor, array_keys($this->bots))) {
1256 4
                $topTenCount += $info['all'];
1257 4
                $counter++;
1258
1259
                // To be used in the Top Ten charts.
1260 4
                $topTenEditors[] = [
1261 4
                    'label' => $editor,
1262 4
                    'value' => $info['all'],
1263
                    'percentage' => (
1264 4
                        100 * ($info['all'] / $this->getNumRevisionsProcessed())
1265
                    )
1266
                ];
1267
            }
1268
1269
            // Compute the percentage of minor edits the user made.
1270 4
            $this->editors[$editor]['minorPercentage'] = $info['all']
1271 4
                ? ($info['minor'] / $info['all']) * 100
1272
                : 0;
1273
1274 4
            if ($info['all'] > 1) {
1275
                // Number of seconds/days between first and last edit.
1276 4
                $secs = $info['last']->getTimestamp() - $info['first']->getTimestamp();
1277 4
                $days = $secs / (60 * 60 * 24);
1278
1279
                // Average time between edits (in days).
1280 4
                $this->editors[$editor]['atbe'] = $days / $info['all'];
1281
            }
1282
        }
1283
1284 4
        $this->topTenEditorsByEdits = $topTenEditors;
1285
1286
        // First sort editors array by the amount of text they added.
1287 4
        $topTenEditorsByAdded = $this->editors;
1288
        uasort($topTenEditorsByAdded, function ($a, $b) {
1289 4
            if ($a['added'] === $b['added']) {
1290 4
                return 0;
1291
            }
1292 4
            return $a['added'] > $b['added'] ? -1 : 1;
1293 4
        });
1294
1295
        // Then build a new array of top 10 editors by added text,
1296
        // in the data structure needed for the chart.
1297
        $this->topTenEditorsByAdded = array_map(function ($editor) {
1298 4
            $added = $this->editors[$editor]['added'];
1299
            return [
1300 4
                'label' => $editor,
1301 4
                'value' => $added,
1302
                'percentage' => (
1303 4
                    100 * ($added / $this->addedBytes)
1304
                )
1305
            ];
1306 4
        }, array_keys(array_slice($topTenEditorsByAdded, 0, 10)));
1307
1308 4
        $this->topTenCount = $topTenCount;
1309 4
    }
1310
1311
    /**
1312
     * Get authorship attribution from the WikiWho API.
1313
     * @see https://f-squared.org/wikiwho/
1314
     * @param  int $limit Max number of results.
1315
     * @return array
1316
     */
1317 1
    public function getTextshares($limit = null)
1318
    {
1319 1
        if (isset($this->textshares)) {
1320
            return $this->textshares;
1321
        }
1322
1323
        // TODO: check for failures. Should have a success:true
1324 1
        $ret = $this->getRepository()->getTextshares($this->page);
1325
1326
        // If revision can't be found, return error message.
1327 1
        if (!isset($ret['revisions'][0])) {
1328
            return [
1329
                'error' => isset($ret['Error']) ? $ret['Error'] : 'Unknown'
1330
            ];
1331
        }
1332
1333 1
        $revId = array_keys($ret['revisions'][0])[0];
1334 1
        $tokens = $ret['revisions'][0][$revId]['tokens'];
1335
1336 1
        list($counts, $totalCount, $userIds) = $this->countTokens($tokens);
1337 1
        $usernameMap = $this->getUsernameMap($userIds);
1338
1339 1
        if ($limit !== null) {
1340 1
            $countsToProcess = array_slice($counts, 0, $limit, true);
1341
        } else {
1342
            $countsToProcess = $counts;
1343
        }
1344
1345 1
        $textshares = [];
1346
1347
        // Loop through once more, creating an array with the user names (or IP address)
1348
        // as the key, and the count and percentage as the value.
1349 1
        foreach ($countsToProcess as $editor => $count) {
1350 1
            if (isset($usernameMap[$editor])) {
1351 1
                $index = $usernameMap[$editor];
1352
            } else {
1353 1
                $index = $editor;
1354
            }
1355 1
            $textshares[$index] = [
1356 1
                'count' => $count,
1357 1
                'percentage' => round(100 * ($count / $totalCount), 1)
1358
            ];
1359
        }
1360
1361 1
        $this->textshares = [
1362 1
            'list' => $textshares,
1363 1
            'totalAuthors' => count($counts),
1364 1
            'totalCount' => $totalCount,
1365
        ];
1366
1367 1
        return $this->textshares;
1368
    }
1369
1370
    /**
1371
     * Get a map of user IDs to usernames, given the IDs.
1372
     * @param  int[] $userIds
1373
     * @return array IDs as keys, usernames as values.
1374
     */
1375 1
    private function getUsernameMap($userIds)
1376
    {
1377 1
        $userIdsNames = $this->getRepository()->getUsernamesFromIds(
1378 1
            $this->page->getProject(),
1379 1
            $userIds
1380
        );
1381
1382 1
        $usernameMap = [];
1383 1
        foreach ($userIdsNames as $userIdName) {
1384 1
            $usernameMap[$userIdName['user_id']] = $userIdName['user_name'];
1385
        }
1386
1387 1
        return $usernameMap;
1388
    }
1389
1390
    /**
1391
     * Get counts of token lengths for each author. Used in self::getTextshares()
1392
     * @param  array $tokens
1393
     * @return array [counts by user, total count, IDs of accounts]
1394
     */
1395 1
    private function countTokens($tokens)
1396
    {
1397 1
        $counts = [];
1398 1
        $userIds = [];
1399 1
        $totalCount = 0;
1400
1401
        // Loop through the tokens, keeping totals (token length) for each author.
1402 1
        foreach ($tokens as $token) {
1403 1
            $editor = $token['editor'];
1404
1405
            // IPs are prefixed with '0|', otherwise it's the user ID.
1406 1
            if (substr($editor, 0, 2) === '0|') {
1407 1
                $editor = substr($editor, 2);
1408
            } else {
1409 1
                $userIds[] = $editor;
1410
            }
1411
1412 1
            if (!isset($counts[$editor])) {
1413 1
                $counts[$editor] = 0;
1414
            }
1415
1416 1
            $counts[$editor] += strlen($token['str']);
1417 1
            $totalCount += strlen($token['str']);
1418
        }
1419
1420
        // Sort authors by count.
1421 1
        arsort($counts);
1422
1423 1
        return [$counts, $totalCount, $userIds];
1424
    }
1425
1426
    /**
1427
     * Get a list of wikis supported by WikiWho.
1428
     * @return string[]
1429
     * @codeCoverageIgnore
1430
     */
1431
    public function getTextshareWikis()
1432
    {
1433
        return self::TEXTSHARE_WIKIS;
1434
    }
1435
1436
    /**
1437
     * Get prose and reference information.
1438
     * @return array With keys 'characters', 'words', 'references', 'unique_references'
1439
     */
1440 1
    public function getProseStats()
1441
    {
1442 1
        $datetime = $this->endDate !== false ? new DateTime('@'.$this->endDate) : null;
1443 1
        $html = $this->page->getHTMLContent($datetime);
1444
1445 1
        $crawler = new Crawler($html);
1446
1447 1
        list($chars, $words) = $this->countCharsAndWords($crawler, '#mw-content-text p');
1448
1449 1
        $refs = $crawler->filter('#mw-content-text .reference');
1450 1
        $refContent = [];
1451
        $refs->each(function ($ref) use (&$refContent) {
1452 1
            $refContent[] = $ref->text();
1453 1
        });
1454 1
        $uniqueRefs = count(array_unique($refContent));
1455
1456 1
        $sections = count($crawler->filter('#mw-content-text .mw-headline'));
1457
1458
        return [
1459 1
            'characters' => $chars,
1460 1
            'words' => $words,
1461 1
            'references' => $refs->count(),
1462 1
            'unique_references' => $uniqueRefs,
1463 1
            'sections' => $sections,
1464
        ];
1465
    }
1466
1467
    /**
1468
     * Count the number of characters and words of the plain text
1469
     * within the DOM element matched by the given selector.
1470
     * @param  Crawler $crawler
1471
     * @param  string $selector HTML selector.
1472
     * @return array [num chars, num words]
1473
     */
1474 1
    private function countCharsAndWords($crawler, $selector)
1475
    {
1476 1
        $totalChars = 0;
1477 1
        $totalWords = 0;
1478 1
        $paragraphs = $crawler->filter($selector);
1479 1
        $paragraphs->each(function ($node) use (&$totalChars, &$totalWords) {
1480 1
            $text = preg_replace('/\[\d+\]/', '', trim($node->text()));
1481 1
            $totalChars += strlen($text);
1482 1
            $totalWords += count(explode(' ', $text));
1483 1
        });
1484
1485 1
        return [$totalChars, $totalWords];
1486
    }
1487
1488
    /**
1489
     * Fetch transclusion data (categories, templates and files)
1490
     * that are on the page.
1491
     * @return array With keys 'categories', 'templates' and 'files'.
1492
     */
1493 1
    private function getTransclusionData()
1494
    {
1495 1
        if (!is_array($this->transclusionData)) {
0 ignored issues
show
introduced by
The condition is_array($this->transclusionData) is always true.
Loading history...
1496 1
            $this->transclusionData = $this->getRepository()
1497 1
                ->getTransclusionData($this->page);
1498
        }
1499 1
        return $this->transclusionData;
1500
    }
1501
1502
    /**
1503
     * Get the number of categories that are on the page.
1504
     * @return int
1505
     */
1506 1
    public function getNumCategories()
1507
    {
1508 1
        return $this->getTransclusionData()['categories'];
1509
    }
1510
1511
    /**
1512
     * Get the number of templates that are on the page.
1513
     * @return int
1514
     */
1515 1
    public function getNumTemplates()
1516
    {
1517 1
        return $this->getTransclusionData()['templates'];
1518
    }
1519
1520
    /**
1521
     * Get the number of files that are on the page.
1522
     * @return int
1523
     */
1524 1
    public function getNumFiles()
1525
    {
1526 1
        return $this->getTransclusionData()['files'];
1527
    }
1528
}
1529