summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/src/Exporter/Escaper.php
blob: ffbe97f9d41250ee51fa4ecbf2ee32ff62378f93 (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
<?php

namespace SMW\Exporter;

use SMW\DIWikiPage;

/**
 * @license GNU GPL v2+
 * @since 2.2
 *
 * @author Markus Krötzsch
 */
class Escaper {

	/**
	 * @since 2.2
	 *
	 * @param DIWikiPage $diWikiPage
	 *
	 * @return string
	 */
	static public function encodePage( DIWikiPage $diWikiPage ) {

		$localName = '';

		if ( $diWikiPage->getInterwiki() !== '' ) {
			$localName = $diWikiPage->getInterwiki() . ':';
		}

		if ( $diWikiPage->getNamespace() === SMW_NS_PROPERTY ) {
			$localName .= 'Property' . ':' . $diWikiPage->getDBkey();
		} elseif ( $diWikiPage->getNamespace() === NS_CATEGORY ) {
			$localName .= 'Category' . ':' . $diWikiPage->getDBkey();
		} elseif ( $diWikiPage->getNamespace() !== NS_MAIN ) {
			$localName .= str_replace( ' ', '_', $GLOBALS['wgContLang']->getNSText( $diWikiPage->getNamespace() ) ) . ':' . $diWikiPage->getDBkey();
		} else {
			$localName .= $diWikiPage->getDBkey();
		}

		return self::encodeUri( $localName );
	}

	/**
	 * @param string
	 *
	 * @return string
	 */
	static public function armorChars( $string ) {
		return str_replace( [ '/' ], [ '-2F' ], $string );
	}

	/**
	 * This function escapes symbols that might be problematic in XML in a uniform
	 * and injective way.
	 *
	 * @param string
	 *
	 * @return string
	 */
	static public function encodeUri( $uri ) {

		$uri = $GLOBALS['smwgExportResourcesAsIri'] ? $uri : wfUrlencode( $uri );

		$uri = str_replace(
			[ '-', ' ' ],
			[ '-2D', '_' ],
			$uri
		);

		$uri = str_replace(
			[ '*', ',' , ';', '<', '>', '(', ')', '[', ']', '{', '}', '\\', '$', '^', ':', '"', '#', '&', "'", '+', '!', '%' ],
			[ '-2A', '-2C', '-3B', '-3C', '-3E', '-28', '-29', '-5B', '-5D', '-7B', '-7D', '-5C', '-24', '-5E', '-3A', '-22', '-23', '-26', '-27', '-2B', '-21', '-' ],
			$uri
		);

		return $uri;
	}

	/**
	 * This function unescapes URIs generated with Escaper::decodeUri.
	 *
	 * @param string
	 *
	 * @return string
	 */
	static public function decodeUri( $uri ) {

		$uri = str_replace(
			[ '-2A', '-2C', '-3B', '-3C', '-3E', '-28', '-29', '-5B', '-5D', '-7B', '-7D', '-5C', '-24', '-5E', '-3A', '-22', '-23', '-26', '-27', '-2B', '-21', '-25', '-' ],
			[ '*', ',' , ';', '<', '>', '(', ')', '[', ']', '{', '}', '\\', '$', '^', ':', '"', '#', '&', "'", '+', '!', '%', '%' ],
			$uri
		);

		$uri = str_replace( '%2D', '-', $uri );

		return $uri;
	}

}