summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/RegexFunctions/RegexFunctions.php
blob: 1fa34329c8e269689426231c4d1e5cd2b55f5e18 (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
<?php
/**
 * RegexFunctions extension -- Regular Expression parser functions
 *
 * @file
 * @ingroup Extensions
 * @author Ryan Schmidt
 * @license http://en.wikipedia.org/wiki/Public_domain Public domain
 * @link http://www.mediawiki.org/wiki/Extension:RegexFunctions Documentation
 */

if( !defined( 'MEDIAWIKI' ) ) {
	echo "This file is an extension of the MediaWiki software and cannot be used standalone\n";
	die( 1 );
}

// Extension credits that will show up on Special:Version
$wgExtensionCredits['parserhook'][] = array(
	'path' => __FILE__,
	'name' => 'RegexFunctions',
	'author' => 'Ryan Schmidt',
	'version' => '1.5.0',
	'descriptionmsg' => 'regexfunctions-desc',
	'url' => 'https://www.mediawiki.org/wiki/Extension:RegexFunctions',
);

$dir = dirname( __FILE__ ) . '/';
$wgMessagesDirs['RegexFunctions'] = __DIR__ . '/i18n';
$wgExtensionMessagesFiles['RegexFunctions'] = $dir . 'RegexFunctions.i18n.php';
$wgExtensionMessagesFiles['RegexFunctionsMagic'] = $dir . 'RegexFunctions.i18n.magic.php';

$wgHooks['ParserFirstCallInit'][] = 'ExtRegexFunctions::onParserFirstCallInit';
$wgHooks['ParserClearState'][] = 'ExtRegexFunctions::onParserClearState';

// default globals
// how many functions are allowed in a single page? Keep this at least above 3 for usability
$wgRegexFunctionsPerPage = 10;
// should we allow modifiers in the functions, e.g. the /i modifier for case-insensitive?
$wgRegexFunctionsAllowModifiers = true;
// should we allow internal options to be set (e.g. (?opts) or (?opts:some regex))
$wgRegexFunctionsAllowOptions = true;
// limit for rsplit and rreplace functions. -1 is unlimited
$wgRegexFunctionsLimit = -1;
// array of functions to disable, aka these functions cannot be used :)
$wgRegexFunctionsDisable = array();

class ExtRegexFunctions {
	private static $num = 0;
	private static $modifiers = array(
		'i', 'm', 's', 'x', 'A', 'D', 'S', 'U', 'X', 'J', 'u', 'e'
	);
	private static $options = array( 'i', 'm', 's', 'x', 'U', 'X', 'J' );

	public static function onParserFirstCallInit( $parser ) {
		$parser->setFunctionHook( 'rmatch', array( __CLASS__, 'rmatch' ) );
		$parser->setFunctionHook( 'rsplit', array( __CLASS__, 'rsplit' ) );
		$parser->setFunctionHook( 'rreplace', array( __CLASS__, 'rreplace' ) );
		return true;
	}

	public static function onParserClearState( $parser ) {
		self::$num = 0;
		return true;
	}

	public static function rmatch( &$parser, $string = '', $pattern = '', $return = '', $notfound = '', $offset = 0 ) {
		global $wgRegexFunctionsPerPage, $wgRegexFunctionsAllowModifiers, $wgRegexFunctionsDisable;
		if( in_array( 'rmatch', $wgRegexFunctionsDisable ) ) {
			return;
		}
		self::$num++;
		if( self::$num > $wgRegexFunctionsPerPage ) {
			return;
		}
		$pattern = self::sanitize(
			$pattern,
			$wgRegexFunctionsAllowModifiers
		);
		$num = preg_match(
			$pattern, $string, $matches, PREG_OFFSET_CAPTURE, (int) $offset
		);
		if ( $num === false ) {
			return;
		}
		if ( $num === 0 ) {
			if ( $notfound == '$0' ) {
				//Return the original string if specified to display it with $0.
				return $string;
			}
			return $notfound;
		}

		// change all backslashes to $
		$return = str_replace( '\\', '%$', $return );
		$return = preg_replace_callback(
			'/%?\$%?\$([0-9]+)/',
			function ( $_callbackMatches ) use ( $matches ) {
				return array_key_exists($_callbackMatches[1], $matches) ? $matches[$_callbackMatches[1]][1] : '';
			},
			$return
		);
		$return = preg_replace_callback(
			'/%?\$%?\$\{([0-9]+)\}/',
			function ( $_callbackMatches ) use ( $matches ) {
				return array_key_exists($_callbackMatches[1], $matches) ? $matches[$_callbackMatches[1]][1] : '';
			},
			$return
		);
		$return = preg_replace_callback(
			'/%?\$([0-9]+)/',
			function ( $_callbackMatches ) use ( $matches ) {
				return array_key_exists($_callbackMatches[1], $matches) ? $matches[$_callbackMatches[1]][0] : '';
			},
			$return
		);
		$return = preg_replace_callback(
			'/%?\$\{([0-9]+)\}/',
			function ( $_callbackMatches ) use ( $matches ) {
				return array_key_exists($_callbackMatches[1], $matches) ? $matches[$_callbackMatches[1]][0] : '';
			},
			$return
		);
		$return = str_replace( '%$', '\\', $return );

		return $return;
	}

	public static function rsplit( &$parser, $string = '', $pattern = '', $piece = 0 ) {
		global $wgRegexFunctionsPerPage, $wgRegexFunctionsAllowModifiers, $wgRegexFunctionsLimit, $wgRegexFunctionsDisable;
		if( in_array( 'rsplit', $wgRegexFunctionsDisable ) ) {
			return;
		}
		self::$num++;
		if( self::$num > $wgRegexFunctionsPerPage ) {
			return;
		}
		$pattern = self::sanitize(
			$pattern,
			$wgRegexFunctionsAllowModifiers
		);
		$res = preg_split( $pattern, $string, $wgRegexFunctionsLimit );
		$p = (int) $piece;
		// allow negative pieces to work from the end of the array
		if( $p < 0 ) {
			$p = $p + count( $res );
		}
		// sanitation for pieces that don't exist
		if( $p < 0 ) {
			$p = 0;
		}
		if( $p >= count( $res ) ) {
			$p = count( $res ) - 1;
		}
		return $res[$p];
	}

	public static function rreplace( &$parser, $string = '', $pattern = '', $replace = '' ) {
		global $wgRegexFunctionsPerPage, $wgRegexFunctionsAllowModifiers, $wgRegexFunctionsLimit, $wgRegexFunctionsDisable;
		if( in_array( 'rreplace', $wgRegexFunctionsDisable ) ) {
			return;
		}
		self::$num++;
		if( self::$num > $wgRegexFunctionsPerPage ) {
			return;
		}
		$pattern = self::sanitize(
			str_replace(chr(0), '', $pattern),
			$wgRegexFunctionsAllowModifiers
		);
		$res = preg_replace(
			$pattern,
			$replace,
			$string,
			$wgRegexFunctionsLimit
		);
		return $res;
	}

	// santizes a regex pattern
	private static function sanitize( $pattern, $m = false ) {
		if( preg_match( '/^\/(.*)([^\\\\])\/(.*?)$/', $pattern, $matches ) ) {
			$pat = preg_replace_callback(
				'/([^\\\\])?\(\?(.*\:)?(.*)\)/U',
				function ( $_callbackMatches ) {
					return "{$_callbackMatches[1]}(" . self::cleanupInternal( $_callbackMatches[2] ) . "{$_callbackMatches[3]})";
				},
				$matches[1] . $matches[2]
			);
			$ret = '/' . $pat . '/';
			if( $m ) {
				$mod = '';
				foreach( self::$modifiers as $val ) {
					if( strpos( $matches[3], $val ) !== false ) {
						$mod .= $val;
					}
				}
				$mod = str_replace( 'e', '', $mod ); //Get rid of eval modifier.
				$ret .= $mod;
			}
		} else {
			$pat = preg_replace_callback(
				'/([^\\\\])?\(\?(.*\:)?(.*)\)/U',
				function ( $_callbackMatches ) {
					return "{$_callbackMatches[1]}(" . self::cleanupInternal( $_callbackMatches[2] ) . "{$_callbackMatches[3]})";
				},
				$pattern
			);
			$pat = preg_replace( '!([^\\\\])/!', '$1\\/', $pat );
			$ret = '/' . $pat . '/';
		}
		return $ret;
	}

	// cleans up internal options, making sure they are valid
	private static function cleanupInternal( $str ) {
		global $wgRegexFunctionsAllowOptions;
		$ret = '';
		if ( !$wgRegexFunctionsAllowOptions ) {
			return '';
		}
		foreach ( self::$options as $opt ) {
			if( strpos( $str, $opt ) !== false ) {
				$ret .= $opt;
			}
		}
		return $ret;
	}
}