summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/src/MediaWiki/Hooks/PersonalUrls.php
blob: 5af209bd70e7d40bb927ef0a8bf9f1de7320485e (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
<?php

namespace SMW\MediaWiki\Hooks;

use SkinTemplate;
use SMW\MediaWiki\JobQueue;

/**
 * @see https://www.mediawiki.org/wiki/Manual:Hooks/PersonalUrls
 *
 * @license GNU GPL v2+
 * @since 3.0
 *
 * @author mwjames
 */
class PersonalUrls extends HookHandler {

	/**
	 * @var SkinTemplate
	 */
	private $skin;

	/**
	 * @var JobQueue
	 */
	private $jobQueue;

	/**
	 * @since 3.0
	 *
	 * @param SkinTemplate $skin
	 * @param JobQueue $jobQueue
	 */
	public function __construct( SkinTemplate $skin, JobQueue $jobQueue ) {
		$this->skin = $skin;
		$this->jobQueue = $jobQueue;
	}

	/**
	 * @since 3.0
	 *
	 * @param array &$personalUrls
	 *
	 * @return true
	 */
	public function process( array &$personalUrls ) {

		$watchlist = $this->getOption( 'smwgJobQueueWatchlist', [] );

		if ( $this->getOption( 'prefs-jobqueue-watchlist' ) !== null && $watchlist !== [] ) {
			$this->addJobQueueWatchlist( $watchlist, $personalUrls );
		}

		return true;
	}

	private function addJobQueueWatchlist( $watchlist, &$personalUrls ) {

		$queue = [];

		foreach ( $watchlist as $job ) {
			$size = $this->jobQueue->getQueueSize( $job );

			if ( $size > 0 ) {
				$queue[$job] = $this->humanReadable( $size );
			}
		}

		$out = $this->skin->getOutput();
		$personalUrl = [];

		$out->addModules( 'ext.smw.personal' );
		$out->addJsConfigVars( 'smwgJobQueueWatchlist', $queue );

		$personalUrl['smw-jobqueue-watchlist'] = [
			'text'   => 'ⅉ [ ' . ( $queue === [] ? '0' : implode( ' | ', $queue ) ) . ' ]' ,
			'href'   => '#',
			'class'  => 'smw-personal-jobqueue-watchlist is-disabled',
			'active' => true
		];

		$keys = array_keys( $personalUrls );

		// Insert the link before the watchlist
		$personalUrls = $this->splice(
			$personalUrls,
			$personalUrl,
			array_search( 'watchlist', $keys )
		);
	}

	// https://stackoverflow.com/questions/1783089/array-splice-for-associative-arrays
	private function splice( $array, $values, $offset ) {
		return array_slice( $array, 0, $offset, true ) + $values + array_slice( $array, $offset, NULL, true );
	}

	private function humanReadable( $num, $decimals = 0 ) {

		if ( $num < 1000 ) {
			$num = number_format( $num );
		} else if ( $num < 1000000) {
			$num = number_format( $num / 1000, $decimals ) . 'K';
		} else {
			$num = number_format( $num / 1000000, $decimals ) . 'M';
		}

		return $num;
	}

}