summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/includes/SMW_Infolink.php
blob: 18a37b30f17f8ba8510cb0b2300040b0b868988f (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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
<?php

use SMW\Site;

/**
 * This class mainly is a container to store URLs for the factbox in a
 * clean way. The class provides methods for creating source code for
 * realising them in wiki or html contexts.
 *
 * @license GNU GPL v2+
 * @since 1.0
 *
 * @author Markus Krötzsch
 * @author Jeroen De Dauw
 * @author mwjames
 */
class SMWInfolink {

	const LINK_UPPER_LENGTH_RESTRICTION = 2000;

	/**
	 * The actual link target.
	 *
	 * @var string
	 */
	protected $mTarget;

	/**
	 * The label for the link.
	 *
	 * @var string
	 */
	protected $mCaption;

	/**
	 * CSS class of a span to embedd the link into,
	 * or false if no extra style is required.
	 *
	 * @var mixed
	 */
	protected $mStyle;

	/**
	 * @var array
	 */
	private $linkAttributes = [];

	/**
	 * Indicates whether $target is a page name (true) or URL (false).
	 *
	 * @var boolean
	 */
	protected $mInternal;

	/**
	 * Array of parameters, format $name => $value, if any.
	 *
	 * @var array
	 */
	protected $mParams;

	/**
	 * @var boolean
	 */
	private $isRestricted = false;

	/**
	 * @var boolean
	 */
	private $isCompactLink = false;

	/**
	 * Create a new link to some internal page or to some external URL.
	 *
	 * @param boolean $internal Indicates whether $target is a page name (true) or URL (false).
	 * @param string $caption The label for the link.
	 * @param string $target The actual link target.
	 * @param mixed $style CSS class of a span to embedd the link into, or false if no extra style is required.
	 * @param array $params Array of parameters, format $name => $value, if any.
	 */
	public function __construct( $internal, $caption, $target, $style = false, array $params = [] ) {
		$this->mInternal = $internal;
		$this->mCaption = $caption;
		$this->mTarget = $target;
		$this->mStyle = $style;
		$this->mParams = $params;
		$this->setCompactLink( $GLOBALS['smwgCompactLinkSupport'] );
	}

	/**
	 * @since 3.0
	 *
	 * @param boolean $isRestricted
	 */
	public function isRestricted( $isRestricted ) {
		$this->isRestricted = (bool)$isRestricted;
	}

	/**
	 * @since 3.0
	 *
	 * @param boolean $isCompactLink
	 */
	public function setCompactLink( $isCompactLink = true ) {
		$this->isCompactLink = (bool)$isCompactLink;
	}

	/**
	 * Create a new link to an internal page $target.
	 * All parameters are mere strings as used by wiki users.
	 *
	 * @param string $caption The label for the link.
	 * @param string $target The actual link target.
	 * @param mixed $style CSS class of a span to embedd the link into, or false if no extra style is required.
	 * @param array $params Array of parameters, format $name => $value, if any.
	 *
	 * @return SMWInfolink
	 */
	public static function newInternalLink( $caption, $target, $style = false, array $params = [] ) {
		return new SMWInfolink( true, $caption, $target, $style, $params );
	}

	/**
	 * Create a new link to an external location $url.
	 *
	 * @param string $caption The label for the link.
	 * @param string $url The actual link target.
	 * @param mixed $style CSS class of a span to embedd the link into, or false if no extra style is required.
	 * @param array $params Array of parameters, format $name => $value, if any.
	 *
	 * @return SMWInfolink
	 */
	public static function newExternalLink( $caption, $url, $style = false, array $params = [] ) {
		return new SMWInfolink( false, $caption, $url, $style, $params );
	}

	/**
	 * Static function to construct links to property searches.
	 *
	 * @param string $caption The label for the link.
	 * @param string $propertyName
	 * @param string $propertyValue
	 * @param mixed $style CSS class of a span to embedd the link into, or false if no extra style is required.
	 *
	 * @return SMWInfolink
	 */
	public static function newPropertySearchLink( $caption, $propertyName, $propertyValue, $style = 'smwsearch' ) {
		global $wgContLang;

		$infolink = new SMWInfolink(
			true,
			$caption,
			$wgContLang->getNsText( NS_SPECIAL ) . ':SearchByProperty',
			$style,
			[ ':' . $propertyName, $propertyValue ] // `:` is marking that the link was auto-generated
		);

		// Link that reaches a length restriction will most likely cause a
		// "HTTP 414 "Request URI too long ..." therefore prevent a link creation
		if ( mb_strlen( $propertyName . $propertyValue ) > self::LINK_UPPER_LENGTH_RESTRICTION ) {
			$infolink->isRestricted( true );
		}

		return $infolink;
	}

	/**
	 * Static function to construct links to inverse property searches.
	 *
	 * @param string $caption The label for the link.
	 * @param string $subject
	 * @param string $propertyName
	 * @param mixed $style CSS class of a span to embed the link into, or false if no extra style is required.
	 *
	 * @return SMWInfolink
	 */
	public static function newInversePropertySearchLink( $caption, $subject, $propertyname, $style = false ) {
		global $wgContLang;
		return new SMWInfolink(
			true,
			$caption,
			$wgContLang->getNsText( NS_SPECIAL ) . ':PageProperty',
			$style,
			[ $subject . '::' . $propertyname ]
		);
	}

	/**
	 * Static function to construct links to the browsing special.
	 *
	 * @param string $caption The label for the link.
	 * @param string $titleText
	 * @param mixed $style CSS class of a span to embedd the link into, or false if no extra style is required.
	 *
	 * @return SMWInfolink
	 */
	public static function newBrowsingLink( $caption, $titleText, $style = 'smwbrowse' ) {
		global $wgContLang;
		return new SMWInfolink(
			true,
			$caption,
			$wgContLang->getNsText( NS_SPECIAL ) . ':Browse',
			$style,
			[ ':' . $titleText ]
		);
	}

	/**
	 * Set (or add) parameter values for an existing link.
	 *
	 * @param mixed $value
	 * @param mixed $key
	 */
	public function setParameter( $value, $key = false ) {
		if ( $key === false ) {
			$this->mParams[] = $value;
		} else {
			$this->mParams[$key] = $value;
		}
	}

	/**
	 * Get the value of some named parameter, or null if no parameter of
	 * that name exists.
	 */
	public function getParameter( $key ) {
		if ( array_key_exists( $key, $this->mParams ) ) {
			return $this->mParams[$key];
		} else {
			return null;
		}
	}

	/**
	 * Change the link text.
	 */
	public function setCaption( $caption ) {
		$this->mCaption = $caption;
	}

	/**
	 * Change the link's CSS class.
	 */
	public function setStyle( $style ) {
		$this->mStyle = $style;
	}

	/**
	 * Modify link attributes
	 *
	 * @since 3.0
	 *
	 * @param array $linkAttributes
	 */
	public function setLinkAttributes( array $linkAttributes ) {
		$this->linkAttributes = $linkAttributes;
	}

	/**
	 * Returns a suitable text string for displaying this link in HTML or wiki, depending
	 * on whether $outputformat is SMW_OUTPUT_WIKI or SMW_OUTPUT_HTML.
	 *
	 * The parameter $linker controls linking of values such as titles and should
	 * be some Linker object (for HTML output). Some default linker will be created
	 * if needed and not provided.
	 */
	public function getText( $outputformat, $linker = null ) {

		if ( $this->isRestricted ) {
			return '';
		}

		if ( $this->mStyle !== false ) {
			SMWOutputs::requireResource( 'ext.smw.style' );
			$start = "<span class=\"$this->mStyle\">";
			$end = '</span>';
		} else {
			$start = '';
			$end = '';
		}

		if ( $this->mInternal ) {
			if ( count( $this->mParams ) > 0 ) {

				$query = self::encodeParameters( $this->mParams );

				if ( $this->isCompactLink ) {
					$query = self::encodeCompactLink( $query );
				}

				$titletext = $this->mTarget . '/' . $query;
			} else {
				$titletext = $this->mTarget;
			}

			$title = Title::newFromText( $titletext );

			if ( $title !== null ) {
				if ( $outputformat == SMW_OUTPUT_WIKI ) {
					$link = "[[$titletext|$this->mCaption]]";
				} elseif ( $outputformat == SMW_OUTPUT_RAW ) {
					return $this->getURL();
				} else { // SMW_OUTPUT_HTML, SMW_OUTPUT_FILE
					$link = $this->getLinker( $linker )->link( $title, $this->mCaption, $this->linkAttributes );
				}
			} else {
				// Title creation failed, maybe illegal symbols or too long; make
				// a direct URL link (only possible if offending target parts belong
				// to some parameter that can be separated from title text, e.g.
				// as in Special:Bla/il<leg>al -> Special:Bla&p=il&lt;leg&gt;al)
				$title = Title::newFromText( $this->mTarget );

				// Just give up due to the title being bad, normally this would
				// indicate a software bug
				if ( $title === null ) {
					return '';
				}

				$query = self::encodeParameters( $this->mParams, $this->isCompactLink );

				if ( $outputformat == SMW_OUTPUT_WIKI ) {

					if ( $this->isCompactLink ) {
						$query = self::encodeCompactLink( $query, false );
					}

					$link = '[' . $title->getFullURL(  $query ) . " $this->mCaption]";
				} else { // SMW_OUTPUT_HTML, SMW_OUTPUT_FILE

					if ( $this->isCompactLink ) {
						$query = self::encodeCompactLink( $query, true );
					} else {
						// #511, requires an array
						$query = wfCgiToArray( $query );
					}

					$link = $this->getLinker( $linker )->link(
						$title,
						$this->mCaption,
						$this->linkAttributes,
						$query
					);
				}
			}
		} else {
			$target = $this->getURL();

			if ( $outputformat == SMW_OUTPUT_WIKI ) {
				$link = "[$target $this->mCaption]";
			} else { // SMW_OUTPUT_HTML, SMW_OUTPUT_FILE
				$link = '<a href="' . htmlspecialchars( $target ) . "\">$this->mCaption</a>";
			}
		}

		return $start . $link . $end;
	}

	/**
	 * Return hyperlink for this infolink in HTML format.
	 *
	 * @return string
	 */
	public function getHTML( $linker = null ) {
		return $this->getText( SMW_OUTPUT_HTML, $linker );
	}

	/**
	 * Return hyperlink for this infolink in wiki format.
	 *
	 * @return string
	 */
	public function getWikiText( $linker = null ) {
		return $this->getText( SMW_OUTPUT_WIKI, $linker );
	}

	/**
	 * Return a fully qualified URL that points to the link target (whether internal or not).
	 * This function might be used when the URL is needed outside normal links, e.g. in the HTML
	 * header or in some metadata file. For making normal links, getText() should be used.
	 *
	 * @return string
	 */
	public function getURL() {

		$query = self::encodeParameters( $this->mParams, $this->isCompactLink );

		if ( $this->isCompactLink && $query !== '' ) {
			$query = self::encodeCompactLink( $query, true );
		}

		if ( !$this->mInternal ) {
			return $this->buildTarget( $query );
		}

		$title = Title::newFromText( $this->mTarget );

		if ( $title !== null ) {
			return $title->getFullURL( $query );
		}

		// the title was bad, normally this would indicate a software bug
		return '';
	}

	/**
	 * @since 3.0
	 *
	 * @return string
	 */
	public function getLocalURL() {

		$query = self::encodeParameters( $this->mParams, $this->isCompactLink );

		if ( $this->isCompactLink && $query !== '' ) {
			$query = self::encodeCompactLink( $query, true );
		}

		if ( !$this->mInternal ) {
			return $this->buildTarget( $query );
		}

		$title = Title::newFromText( $this->mTarget );

		if ( $title !== null ) {
			return $title->getLocalURL( $query );
		}

		 // the title was bad, normally this would indicate a software bug
		return '';
	}

	/**
	 * Return a Linker object, using the parameter $linker if not null, and creatng a new one
	 * otherwise. $linker is usually a user skin object, while the fallback linker object is
	 * not customised to user settings.
	 *
	 * @return Linker
	 */
	protected function getLinker( &$linker = null ) {
		if ( is_null( $linker ) ) {
			$linker = new Linker;
		}
		return $linker;
	}

	/**
	 * Encode an array of parameters, formatted as $name => $value, to a parameter
	 * string that can be used for linking. If $forTitle is true (default), then the
	 * parameters are encoded for use in a MediaWiki page title (useful for making
	 * internal links to parameterised special pages), otherwise the parameters are
	 * encoded HTTP GET style. The parameter name "x" is used to collect parameters
	 * that do not have any string keys in GET, and hence "x" should never be used
	 * as a parameter name.
	 *
	 * The function SMWInfolink::decodeParameters() can be used to undo this encoding.
	 * It is strongly recommended to not create any code that depends on the concrete
	 * way of how parameters are encoded within this function, and to always use the
	 * respective encoding/decoding methods instead.
	 *
	 * @param array $params
	 * @param boolean $forTitle
	 */
	static public function encodeParameters( array $params, $forTitle = true ) {
		$result = '';

		if ( $forTitle ) {
			foreach ( $params as $name => $value ) {
				if ( is_string( $name ) && ( $name !== '' ) ) {
					$value = $name . '=' . $value;
				}
				// Escape certain problematic values. Use SMW-escape
				// (like URLencode but - instead of % to prevent double encoding by later MW actions)
				//
				/// : SMW's parameter separator, must not occur within params
				// - : used in SMW-encoding strings, needs escaping too
				// [ ] < > &lt; &gt; '' |: problematic in MW titles
				// & : sometimes problematic in MW titles ([[&amp;]] is OK, [[&test]] is OK, [[&test;]] is not OK)
				//     (Note: '&' in strings obtained during parsing already has &entities; replaced by
				//      UTF8 anyway)
				// ' ': are equivalent with '_' in MW titles, but are not equivalent in certain parameter values
				// "\n": real breaks not possible in [[...]]
				// "#": has special meaning in URLs, triggers additional MW escapes (using . for %)
				// '%': must be escaped to prevent any impact of double decoding when replacing -
				//      by % before urldecode
				// '?': if not escaped, strange effects were observed on some sites (printout and other
				//      parameters ignored without obvious cause); SMW-escaping is always save to do -- it just
				//      make URLs less readable
				//
				$value = str_replace(
					[ '-', '#', "\n", ' ', '/', '[', ']', '<', '>', '&lt;', '&gt;', '&amp;', '\'\'', '|', '&', '%', '?', '$', "\\", ";", "_" ],
					[ '-2D', '-23', '-0A', '-20', '-2F', '-5B', '-5D', '-3C', '-3E', '-3C', '-3E', '-26', '-27-27', '-7C', '-26', '-25', '-3F', '-24', '-5C', "-3B", "-5F" ],
					$value
				);

				if ( $result !== '' ) {
					$result .= '/';
				}

				$result .= $value;
			}
		} else { // Note: this requires to have HTTP compatible parameter names (ASCII)
			$q = []; // collect unlabelled query parameters here

			foreach ( $params as $name => $value ) {
				if ( is_string( $name ) && ( $name !== '' ) ) {
					$value = rawurlencode( $name ) . '=' . rawurlencode( $value );

					if ( $result !== '' ) {
						$result .= '&';
					}

					$result .= $value;
				} else {
					$q[] = $value;
				}
			}
			if ( count( $q ) > 0 ) { // prepend encoding for unlabelled parameters
				if ( $result !== '' ) {
					$result = '&' . $result;
				}
				$result = 'x=' . rawurlencode( self::encodeParameters( $q, true ) ) . $result;
			}
		}

		return $result;
	}

	/**
	 * Obtain an array of parameters from the parameters given to some HTTP service.
	 * In particular, this function performs all necessary decoding as may be needed, e.g.,
	 * to recover the proper parameter strings after encoding for use in wiki title names
	 * as done by SMWInfolink::encodeParameters().
	 *
	 * If $allparams is set to true, it is assumed that further data should be obtained
	 * from the global $wgRequest, and all given parameters are read.
	 *
	 * $titleparam is the string extracted by MediaWiki from special page calls of the
	 * form Special:Something/titleparam
	 * Note: it is assumed that the given $titleparam is already urldecoded, as is normal
	 * when getting such parameters from MediaWiki. SMW-escaped parameters largely prevent
	 * double decoding effects (i.e. there are no new "%" after one pass of urldecoding)
	 *
	 * The function SMWInfolink::encodeParameters() can be used to create a suitable
	 * encoding. It is strongly recommended to not create any code that depends on the
	 * concrete way of how parameters are encoded within this function, and to always use
	 * the respective encoding/decoding methods instead.
	 *
	 * @param string $titleParam
	 * @param boolean $allParams
	 */
	static public function decodeParameters( $titleParam = '', $allParams = false ) {
		global $wgRequest;

		$result = [];

		if ( $allParams ) {
			$result = $wgRequest->getValues();

			if ( array_key_exists( 'x', $result ) ) { // Considered to be part of the title param.
				if ( $titleParam !== '' ) {
					$titleParam .= '/';
				}
				$titleParam .= $result['x'];
				unset( $result['x'] );
			}
		}

		if ( is_array( $titleParam ) ) {
			return $titleParam;
		} elseif ( $titleParam !== '' ) {
			// unescape $p; escaping scheme: all parameters rawurlencoded, "-" and "/" urlencoded, all "%" replaced by "-", parameters then joined with /
			$ps = explode( '/', $titleParam ); // params separated by / here (compatible with wiki link syntax)

			foreach ( $ps as $p ) {
				if ( $p !== '' ) {
					$result[] = rawurldecode( str_replace( '-', '%', $p ) );
				}
			}
		}

		return $result;
	}

	/**
	 * @since 3.0
	 *
	 * @param string $value
	 *
	 * @return string|array
	 */
	public static function encodeCompactLink( $value, $compound = false ) {

		// Expect to gain on larger strings and set an identifier to
		// distinguish between compressed and non compressed
		if ( mb_strlen( $value ) > 150 ) {
			$value =  'c:' . gzdeflate( $value, 9 );
		}

		// https://en.wikipedia.org/wiki/Base64#URL_applications
		// The MW parser swallows `__` and transforms it into a simple `_`
		// hence we need to encode it once more
		$value = rtrim( str_replace( '__', '.', strtr( base64_encode( $value ), '+/', '-_' ) ), '=' );

		if ( $compound ) {
			return [ 'cl' => $value ];
		}

		return "cl:$value";
	}

	/**
	 * @since 3.0
	 *
	 * @param string $value
	 *
	 * @return string
	 */
	public static function decodeCompactLink( $value ) {

		if ( !is_string( $value ) || mb_substr( $value, 0, 3 ) !== 'cl:' ) {
			return $value;
		}

		$value = mb_substr( $value, 3 );

		$value = base64_decode(
			str_pad( strtr( str_replace( '.', '__', $value ), '-_', '+/' ), strlen( $value ) % 4, '=', STR_PAD_RIGHT )
		);

		// Compressed?
		if ( mb_substr( $value, 0, 2 ) === 'c:' ) {
			$val = @gzinflate( mb_substr( $value, 2 ) );

			// Guessing that MediaWiki swallowed the last `_`
			if ( $val === false ) {
				$val = @gzinflate( mb_substr( $value , 2 ) . '?' );
			}

			$value = $val;
		}

		// Normalize if nceessary for those that are "encoded for use in a
		// MediaWiki page title"
		if ( mb_substr( $value, 0, 2 ) === 'x=' ) {
			$value = str_replace( [ 'x=', '=-&' , '&', '%2F' ], [ '' , '=-2D&', '/', '/' ], $value );
		}

		return $value;
	}

	private function buildTarget( $query ) {

		$target = $this->mTarget;

		if ( count( $this->mParams ) > 0 ) {
			if ( strpos( Site::wikiurl(), '?' ) === false ) {
				$target = $this->mTarget . '?' . $query;
			} else {
				$target = $this->mTarget . '&' . $query;
			}
		}

		return $target;
	}

}