summaryrefslogtreecommitdiff
blob: 2a9d7a5a0beb0df852811e81f7196ea299ec76f0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
<?php
/** \file
 * \brief Contains code for the ContributionScores Class (extends SpecialPage).
 */

use MediaWiki\MediaWikiServices;

/// Special page class for the Contribution Scores extension
/**
 * Special page that generates a list of wiki contributors based
 * on edit diversity (unique pages edited) and edit volume (total
 * number of edits.
 *
 * @ingroup Extensions
 * @author Tim Laqua <t.laqua@gmail.com>
 */
class ContributionScores extends IncludableSpecialPage {
	const CONTRIBUTIONSCORES_MAXINCLUDELIMIT = 50;

	public function __construct() {
		parent::__construct( 'ContributionScores' );
	}

	public static function onParserFirstCallInit( Parser $parser ) {
		$parser->setFunctionHook( 'cscore', [ self::class, 'efContributionScoresRender' ] );
	}

	public static function efContributionScoresRender( $parser, $usertext, $metric = 'score' ) {
		global $wgContribScoreDisableCache, $wgContribScoreUseRoughEditCount;

		if ( $wgContribScoreDisableCache ) {
			$parser->getOutput()->updateCacheExpiry( 0 );
		}

		$user = User::newFromName( $usertext );
		$dbr = wfGetDB( DB_REPLICA );

		if ( $user instanceof User && $user->isRegistered() ) {
			global $wgLang;
			$revVar = $wgContribScoreUseRoughEditCount ? 'user_editcount' : 'COUNT(rev_id)';

			$revWhere = ActorMigration::newMigration()->getWhere( $dbr, 'rev_user', $user );
			if ( $metric == 'score' ) {
				$row = $dbr->selectRow(
					[ 'revision' ] + $revWhere['tables'],
					[ 'wiki_rank' => "COUNT(DISTINCT rev_page)+SQRT($revVar-COUNT(DISTINCT rev_page))*2" ],
					$revWhere['conds'],
					__METHOD__,
					[],
					$revWhere['joins']
				);
				$output = $wgLang->formatNum( round( $row->wiki_rank, 0 ) );
			} elseif ( $metric == 'changes' ) {
				$row = $dbr->selectRow(
					[ 'revision' ] + $revWhere['tables'],
					[ 'rev_count' => $revVar ],
					$revWhere['conds'],
					__METHOD__,
					[],
					$revWhere['joins']
				);
				$output = $wgLang->formatNum( $row->rev_count );
			} elseif ( $metric == 'pages' ) {
				$row = $dbr->selectRow(
					[ 'revision' ] + $revWhere['tables'],
					[ 'page_count' => 'COUNT(DISTINCT rev_page)' ],
					$revWhere['conds'],
					__METHOD__,
					[],
					$revWhere['joins']
				);
				$output = $wgLang->formatNum( $row->page_count );
			} else {
				$output = wfMessage( 'contributionscores-invalidmetric' )->text();
			}
		} else {
			$output = wfMessage( 'contributionscores-invalidusername' )->text();
		}
		return $parser->insertStripItem( $output, $parser->mStripState );
	}

	/**
	 * Function fetch Contribution Scores data from database
	 *
	 * @param int $days Days in the past to run report for
	 * @param int $limit Maximum number of users to return (default 50)
	 * @return array Data including the requested Contribution Scores.
	 */
	public static function getContributionScoreData( $days, $limit ) {
		global $wgContribScoreIgnoreBots, $wgContribScoreIgnoreBlockedUsers, $wgContribScoreIgnoreUsernames,
			$wgContribScoreUseRoughEditCount;

		$dbr = wfGetDB( DB_REPLICA );

		$revQuery = ActorMigration::newMigration()->getJoin( 'rev_user' );
		$revQuery['tables'] = array_merge( [ 'revision' ], $revQuery['tables'] );

		$revUser = $revQuery['fields']['rev_user'];
		$revUsername = $revQuery['fields']['rev_user_text'];

		$sqlWhere = [];

		if ( $days > 0 ) {
			$date = time() - ( 60 * 60 * 24 * $days );
			$sqlWhere[] = 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $date ) );
		}

		$sqlVars = [
			'rev_user'   => $revUser,
			'page_count' => 'COUNT(DISTINCT rev_page)'
		];
		if ( $wgContribScoreUseRoughEditCount ) {
			$revQuery['tables'][] = 'user';
			$revQuery['joins']['user'] = [ 'LEFT JOIN', [ "$revUser != 0", "user_id = $revUser" ] ];
			$sqlVars['rev_count'] = 'user_editcount';
		} else {
			$sqlVars['rev_count'] = 'COUNT(rev_id)';
		}

		if ( $wgContribScoreIgnoreBlockedUsers ) {
			$sqlWhere[] = "{$revUser} NOT IN " .
				$dbr->buildSelectSubquery( 'ipblocks', 'ipb_user', 'ipb_user <> 0', __METHOD__ );
		}

		if ( $wgContribScoreIgnoreBots ) {
			$sqlWhere[] = "{$revUser} NOT IN " .
				$dbr->buildSelectSubquery( 'user_groups', 'ug_user', [
					'ug_group' => 'bot',
					'ug_expiry IS NULL OR ug_expiry >= ' . $dbr->addQuotes( $dbr->timestamp() )
				], __METHOD__ );
		}

		if ( count( $wgContribScoreIgnoreUsernames ) ) {
			$listIgnoredUsernames = $dbr->makeList( $wgContribScoreIgnoreUsernames );
			$sqlWhere[] = "{$revUsername} NOT IN ($listIgnoredUsernames)";
		}

		if ( $dbr->unionSupportsOrderAndLimit() ) {
			$order = [
				'GROUP BY' => 'rev_user',
				'ORDER BY' => 'page_count DESC',
				'LIMIT' => $limit
			];
		} else {
			$order = [ 'GROUP BY' => 'rev_user' ];
		}

		$sqlMostPages = $dbr->selectSQLText(
			$revQuery['tables'],
			$sqlVars,
			$sqlWhere,
			__METHOD__,
			$order,
			$revQuery['joins']
		);

		if ( $dbr->unionSupportsOrderAndLimit() ) {
			$order['ORDER BY'] = 'rev_count DESC';
		}

		$sqlMostRevs = $dbr->selectSQLText(
			$revQuery['tables'],
			$sqlVars,
			$sqlWhere,
			__METHOD__,
			$order,
			$revQuery['joins']
		);

		$sqlMostPagesOrRevs = $dbr->unionQueries( [ $sqlMostPages, $sqlMostRevs ], false );
		$res = $dbr->select(
			[
				'u' => 'user',
				's' => new Wikimedia\Rdbms\Subquery( $sqlMostPagesOrRevs ),
			],
			[
				'user_id',
				'user_name',
				'user_real_name',
				'page_count',
				'rev_count',
				'wiki_rank' => 'page_count+SQRT(rev_count-page_count)*2',
			],
			[],
			__METHOD__,
			[
				'ORDER BY' => 'wiki_rank DESC',
				'GROUP BY' => 'user_name',
				'LIMIT' => $limit,
			],
			[
				's' => [
					'JOIN',
					'user_id=rev_user'
				]
			]
		);
		$ret = iterator_to_array( $res );
		return $ret;
	}

	/// Generates a "Contribution Scores" table for a given LIMIT and date range

	/**
	 * Function generates Contribution Scores tables in HTML format (not wikiText)
	 *
	 * @param int $days Days in the past to run report for
	 * @param int $limit Maximum number of users to return (default 50)
	 * @param string|null $title The title of the table
	 * @param array $options array of options (default none; nosort/notools)
	 * @return string Html Table representing the requested Contribution Scores.
	 */
	function genContributionScoreTable( $days, $limit, $title = null, $options = 'none' ) {
		global $wgContribScoresUseRealName, $wgContribScoreCacheTTL;

		$opts = explode( ',', strtolower( $options ) );

		$sortable = in_array( 'nosort', $opts ) ? '' : ' sortable';

		$output = "<table class=\"wikitable contributionscores plainlinks{$sortable}\" >\n" .
			"<tr class='header'>\n" .
			Html::element( 'th', [], $this->msg( 'contributionscores-rank' )->text() ) .
			Html::element( 'th', [], $this->msg( 'contributionscores-score' )->text() ) .
			Html::element( 'th', [], $this->msg( 'contributionscores-pages' )->text() ) .
			Html::element( 'th', [], $this->msg( 'contributionscores-changes' )->text() ) .
			Html::element( 'th', [], $this->msg( 'contributionscores-username' )->text() );

		$cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
		$data = $cache->getWithSetCallback(
			$cache->makeKey( 'contributionscores', 'data-' . (string)$days ),
			$wgContribScoreCacheTTL * 60,
			function () use ( $days ) {
				// Use max limit, as limit doesn't matter with performance.
				// Avoid purge multiple times since limit on transclusion can be vary.
				return self::getContributionScoreData( $days, self::CONTRIBUTIONSCORES_MAXINCLUDELIMIT );
			} );

		$lang = $this->getLanguage();

		$altrow = '';
		$user_rank = 1;

		foreach ( $data as $row ) {
			if ( $user_rank > $limit ) {
				break;
			}

			// Use real name if option used and real name present.
			if ( $wgContribScoresUseRealName && $row->user_real_name !== '' ) {
				$userLink = Linker::userLink(
					$row->user_id,
					$row->user_name,
					$row->user_real_name
				);
			} else {
				$userLink = Linker::userLink(
					$row->user_id,
					$row->user_name
				);
			}

			$output .= Html::closeElement( 'tr' );
			$output .= "<tr class='{$altrow}'>\n" .
				"<td class='content' style='padding-right:10px;text-align:right;'>" .
				$lang->formatNum( $user_rank ) .
				"\n</td><td class='content' style='padding-right:10px;text-align:right;'>" .
				$lang->formatNum( round( $row->wiki_rank, 0 ) ) .
				"\n</td><td class='content' style='padding-right:10px;text-align:right;'>" .
				$lang->formatNum( $row->page_count ) .
				"\n</td><td class='content' style='padding-right:10px;text-align:right;'>" .
				$lang->formatNum( $row->rev_count ) .
				"\n</td><td class='content'>" .
				$userLink;

			# Option to not display user tools
			if ( !in_array( 'notools', $opts ) ) {
				$output .= Linker::userToolLinks( $row->user_id, $row->user_name );
			}

			$output .= Html::closeElement( 'td' ) . "\n";

			if ( $altrow == '' && empty( $sortable ) ) {
				$altrow = 'odd ';
			} else {
				$altrow = '';
			}

			$user_rank++;
		}
		$output .= Html::closeElement( 'tr' );
		$output .= Html::closeElement( 'table' );

		// Transcluded on a normal wiki page.
		if ( !empty( $title ) ) {
			$output = Html::rawElement( 'table',
				[
					'style' => 'border-spacing: 0; padding: 0',
					'class' => 'contributionscores-wrapper',
					'lang' => htmlspecialchars( $lang->getCode() ),
					'dir' => $lang->getDir()
				],
				"\n" .
				"<tr>\n" .
				"<td style='padding: 0px;'>{$title}</td>\n" .
				"</tr>\n" .
				"<tr>\n" .
				"<td style='padding: 0px;'>{$output}</td>\n" .
				"</tr>\n"
			);
		}

		return $output;
	}

	function execute( $par ) {
		$this->setHeaders();

		if ( $this->including() ) {
			$this->showInclude( $par );
		} else {
			$this->showPage();
		}

		return true;
	}

	/**
	 * Called when being included on a normal wiki page.
	 * Cache is disabled so it can depend on the user language.
	 * @param string|null $par A subpage give to the special page
	 */
	function showInclude( $par ) {
		$days = null;
		$limit = null;
		$options = 'none';

		if ( !empty( $par ) ) {
			$params = explode( '/', $par );

			$limit = intval( $params[0] );

			if ( isset( $params[1] ) ) {
				$days = intval( $params[1] );
			}

			if ( isset( $params[2] ) ) {
				$options = $params[2];
			}
		}

		if ( empty( $limit ) || $limit < 1 || $limit > self::CONTRIBUTIONSCORES_MAXINCLUDELIMIT ) {
			$limit = 10;
		}
		if ( $days === null || $days < 0 ) {
			$days = 7;
		}

		if ( $days > 0 ) {
			$reportTitle = $this->msg( 'contributionscores-days' )->numParams( $days )->text();
		} else {
			$reportTitle = $this->msg( 'contributionscores-allrevisions' )->text();
		}
		$reportTitle .= ' ' . $this->msg( 'contributionscores-top' )->numParams( $limit )->text();
		$title = Xml::element( 'h4',
				[ 'class' => 'contributionscores-title' ],
				$reportTitle
			) . "\n";
		$this->getOutput()->addHTML( $this->genContributionScoreTable(
			$days,
			$limit,
			$title,
			$options
		) );
	}

	/**
	 * Show the special page
	 */
	function showPage() {
		global $wgContribScoreReports;

		if ( !is_array( $wgContribScoreReports ) ) {
			$wgContribScoreReports = [
				[ 7, 50 ],
				[ 30, 50 ],
				[ 0, 50 ]
			];
		}

		$out = $this->getOutput();
		$out->addWikiMsg( 'contributionscores-info' );

		foreach ( $wgContribScoreReports as $scoreReport ) {
			list( $days, $revs ) = $scoreReport;
			if ( $days > 0 ) {
				$reportTitle = $this->msg( 'contributionscores-days' )->numParams( $days )->text();
			} else {
				$reportTitle = $this->msg( 'contributionscores-allrevisions' )->text();
			}
			$reportTitle .= ' ' . $this->msg( 'contributionscores-top' )->numParams( $revs )->text();
			$title = Xml::element( 'h2',
					[ 'class' => 'contributionscores-title' ],
					$reportTitle
				) . "\n";
			$out->addHTML( $title );
			$out->addHTML( $this->genContributionScoreTable( $days, $revs ) );
		}
	}

	public function maxIncludeCacheTime() {
		global $wgContribScoreDisableCache, $wgContribScoreCacheTTL;
		return $wgContribScoreDisableCache ? 0 : $wgContribScoreCacheTTL;
	}

	/**
	 * @inheritDoc
	 */
	protected function getGroupName() {
		return 'wiki';
	}
}