summaryrefslogtreecommitdiff
path: root/extensions/TimedMediaHandler/handlers/TextHandler/TextHandler.php
blob: 3c229d5f27420532b538d418f81d9e17a04f8e47 (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
<?php
/**
 * Timed Text handling for mediaWiki
 *
 * Timed text support is presently fairly limited. Unlike Ogg and WebM handlers,
 * timed text does not extend the TimedMediaHandler class.
 *
 * TODO On "new" timedtext language save purge all pages where file exists
 */


/**
 * Subclass ApiMain but query other db
 */
class ForeignApiQueryAllPages extends ApiQueryAllPages {
	public function __construct( $mDb, $query, $moduleName ) {
		global $wgTimedTextForeignNamespaces;

		$this->foreignDb = $mDb;

		$wikiID = $this->foreignDb->getWikiID();
		if ( isset( $wgTimedTextForeignNamespaces[ $wikiID ] ) ) {
			$this->foreignNs = $wgTimedTextForeignNamespaces[ $wikiID ];
		} else {
			$this->foreignNs = NS_TIMEDTEXT;
		}
		parent::__construct( $query, $moduleName, 'ap' );
	}

	protected function getDB() {
		return $this->foreignDb;
	}

	protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
		// foreignnNs might not be defined localy,
		// catch the undefined error here
		if ( $valueName == 'apnamespace'
			&& $value == $this->foreignNs
			&& $allowMultiple == false
		) {
			return $this->foreignNs;
		}
		return parent::parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues );
	}

	/**
	 * An alternative to titleToKey() that doesn't trim trailing spaces
	 *
	 *
	 * @FIXME: I'M A BIG HACK
	 *
	 * @param string $titlePart Title part with spaces
	 * @return string Title part with underscores
	 */
	public function titlePartToKey( $titlePart, $defaultNamespace = NS_MAIN ) {
		return substr( $this->titleToKey( $titlePart . 'x' ), 0, -1 );
	}
}

class TextHandler {
	var $remoteNs = null;//lazy init remote Namespace number

	/**
	 * @var File
	 */
	protected $file;

	function __construct( $file ){
		$this->file = $file;
	}

	/**
	 * Get the timed text tracks elements as an associative array
	 * @return array|mixed
	 */
	function getTracks(){
		if( $this->file->isLocal() ){
			return $this->getLocalTextSources();
		} elseif ( $this->file->getRepo() instanceof ForeignDBViaLBRepo ){
			return $this->getForeignDBTextSources();
		} else {
			return $this->getRemoteTextSources();
		}
	}

	/**
	 * @return bool|int|null
	 */
	function getTimedTextNamespace(){
		global $wgEnableLocalTimedText;
		if( $this->file->isLocal() ) {
			if ( $wgEnableLocalTimedText ) {
				return NS_TIMEDTEXT;
			} else {
				return false;
			}
		} elseif( $this->file->repo instanceof ForeignDBViaLBRepo ){
			global $wgTimedTextForeignNamespaces;
			$wikiID = $this->file->getRepo()->getSlaveDB()->getWikiID();
			if ( isset( $wgTimedTextForeignNamespaces[ $wikiID ] ) ) {
				return $wgTimedTextForeignNamespaces[ $wikiID ];
			}
			// failed to get namespace via ForeignDBViaLBRepo, return NS_TIMEDTEXT
			return NS_TIMEDTEXT;
		} else {
			if( $this->remoteNs !== null ){
				return $this->remoteNs;
			}
			// Get the namespace data from the image api repo:
			// fetchImageQuery query caches results
			$data = $this->file->getRepo()->fetchImageQuery( array(
				'meta' =>'siteinfo',
				'siprop' => 'namespaces'
			));

			if( isset( $data['query'] ) && isset( $data['query']['namespaces'] ) ){
				// get the ~last~ timed text namespace defined
				foreach( $data['query']['namespaces'] as $ns ){
					if( $ns['*'] == 'TimedText' ){
						$this->remoteNs = $ns['id'];
					}
				}
			}
			// Return the remote Ns
			return $this->remoteNs;
		}
	}

	/**
	 * @return array|bool
	 */
	function getTextPagesQuery(){
		$ns = $this->getTimedTextNamespace();
		if( $ns === false ){
			wfDebug("Repo: " . $this->file->repo->getName() . " does not have a TimedText namesapce \n");
			// No timed text namespace, don't try to look up timed text tracks
			return false;
		}
		return array(
			'action' => 'query',
			'list' => 'allpages',
			'apnamespace' => $ns,
			'aplimit' => 300,
			'apprefix' => $this->file->getTitle()->getDBkey()
		);
	}

	/**
	 * @return array|mixed
	 */
	function getRemoteTextSources(){
		global $wgMemc;
		// Use descriptionCacheExpiry as our expire for timed text tracks info
		if ( $this->file->getRepo()->descriptionCacheExpiry > 0 ) {
			wfDebug("Attempting to get text tracks from cache...");
			$key = $this->file->getRepo()->getLocalCacheKey( 'RemoteTextTracks', 'url', $this->file->getName() );
			$obj = $wgMemc->get($key);
			if ($obj) {
				wfDebug("success!\n");
				return $obj;
			}
			wfDebug("miss\n");
		}
		wfDebug("Get text tracks from remote api \n");
		$query = $this->getTextPagesQuery();

		// Error in getting timed text namespace return empty array;
		if( $query === false ){
			return array();
		}
		$data = $this->file->getRepo()->fetchImageQuery( $query );
		$textTracks = $this->getTextTracksFromData( $data );
		if ( $data && $this->file->repo->descriptionCacheExpiry > 0 ) {
			$wgMemc->set( $key, $textTracks, $this->file->repo->descriptionCacheExpiry );
		}
		return $textTracks;
	}

	/**
	 * @return array
	 */
	function getLocalTextSources(){
		global $wgEnableLocalTimedText;
		if ( $wgEnableLocalTimedText ) {
			// Init $this->textTracks
			$params = new FauxRequest( $this->getTextPagesQuery() );
			$api = new ApiMain( $params );
			$api->execute();
			if ( defined( 'ApiResult::META_CONTENT' ) ) {
				$data = $api->getResult()->getResultData( null, array( 'Strip' => 'all' ) );
			} else {
				$data = $api->getResultData();
			}
			wfDebug(print_r($data, true));
			// Get the list of language Names
			return $this->getTextTracksFromData( $data );
		} else {
			return array();
		}
	}

	/**
	 * @return array|mixed
	 */
	function getForeignDBTextSources(){
		// Init $this->textTracks
		$params = new FauxRequest( $this->getTextPagesQuery() );
		$api = new ApiMain( $params );
		$api->profileIn();
		$query = new ApiQuery( $api, 'foo', 'bar' );
		$query->profileIn();
		$module = new ForeignApiQueryAllPages( $this->file->getRepo()->getSlaveDB(), $query, 'allpages' );
		$module->profileIn();
		$module->execute();
		$module->profileOut();
		$query->profileOut();
		$api->profileOut();

		if ( defined( 'ApiResult::META_CONTENT' ) ) {
			$data = $module->getResult()->getResultData( null, array( 'Strip' => 'all' ) );
		} else {
			$data = $module->getResultData();
		}
		// Get the list of language Names
		return $this->getTextTracksFromData( $data );
	}

	/**
	 * @param $data
	 * @return array
	 */
	function getTextTracksFromData( $data ){
		$textTracks = array();
		$providerName = $this->file->repo->getName();
		// commons is called shared in production. normalize it to wikimediacommons
		if( $providerName == 'shared' ){
			$providerName = 'wikimediacommons';
		}
		// Provider name should be the same as the interwiki map
		// @@todo more testing with this:

		$langNames = Language::fetchLanguageNames( null, 'mw' );
		if( $data['query'] && $data['query']['allpages'] ){
			foreach( $data['query']['allpages'] as $page ){
				$subTitle = Title::newFromText( $page['title'] ) ;
				$tileParts = explode( '.', $page['title'] );
				if( count( $tileParts) >= 3 ){
					$timedTextExtension = array_pop( $tileParts );
					$languageKey = array_pop( $tileParts );
					$contentType = $this->getContentType( $timedTextExtension );
				} else {
					continue;
				}
				// If there is no valid language continue:
				if( !isset( $langNames[ $languageKey ] ) ){
					continue;
				}
				$namespacePrefix = "TimedText:";
				$textTracks[] = array(
					'kind' => 'subtitles',
					'data-mwtitle' => $namespacePrefix . $subTitle->getDBkey(),
					'data-mwprovider' => $providerName,
					'type' => $contentType,
					// @todo Should eventually add special entry point and output proper WebVTT format:
					// http://www.whatwg.org/specs/web-apps/current-work/webvtt.html
					'src' => $this->getFullURL( $page['title'], $contentType ),
					'srclang' =>  $languageKey,
					'data-dir' => Language::factory( $languageKey )->getDir(),
					'label' => wfMessage('timedmedia-subtitle-language',
						$langNames[ $languageKey ],
						$languageKey )->text()
				);
			}
		}
		return $textTracks;
	}

	function getContentType( $timedTextExtension ) {
		if ( $timedTextExtension === 'srt' ) {
			return 'text/x-srt';
		} else if ( $timedTextExtension === 'vtt' ) {
			return 'text/vtt';
		}
		return '';
	}

	function getFullURL( $pageTitle, $contentType ){
		if( $this->file->isLocal() ) {
			$subTitle =  Title::newFromText( $pageTitle ) ;
			return $subTitle->getFullURL( array(
				'action' => 'raw',
				'ctype' => $contentType
			));
		//} elseif( $this->file->repo instanceof ForeignDBViaLBRepo ){
		} else {
			$query = 'title=' . wfUrlencode( $pageTitle ) . '&';
			$query .= wfArrayToCgi( array(
				'action' => 'raw',
				'ctype' => $contentType
			) );
			// Note: This will return false if scriptDirUrl is not set for repo.
			return $this->file->repo->makeUrl( $query );
		}
	}
}