From bd71db3ed627ac25209d73ab4e87ece3896930c5 Mon Sep 17 00:00:00 2001 From: gnosygnu Date: Mon, 27 Apr 2020 08:39:30 -0400 Subject: [PATCH] Xomw: Add more implementation near statelessFetchTemplate [#632] --- .../src/gplx/xowa/mediawiki/XophpString_.java | 31 +- .../includes/Revision/XomwRevisionRecord.java | 30 +- .../includes/XomwGlobalFunctions.java | 6486 ++++++++--------- .../xowa/mediawiki/includes/XomwRevision.java | 360 +- .../xowa/mediawiki/includes/XomwTitle.java | 2939 ++++---- .../xowa/mediawiki/includes/XomwTitleOld.java | 2 +- .../includes/content/XomwAbstractContent.java | 15 +- .../includes/content/XomwContent.java | 2 +- .../includes/linkers/XomwLinkTarget.java | 176 +- .../includes/parsers/XomwParser.java | 36 +- 10 files changed, 4825 insertions(+), 5252 deletions(-) diff --git a/400_xowa/src/gplx/xowa/mediawiki/XophpString_.java b/400_xowa/src/gplx/xowa/mediawiki/XophpString_.java index 0bc04fca1..fe8015e2c 100644 --- a/400_xowa/src/gplx/xowa/mediawiki/XophpString_.java +++ b/400_xowa/src/gplx/xowa/mediawiki/XophpString_.java @@ -1,18 +1,18 @@ -/* -XOWA: the XOWA Offline Wiki Application -Copyright (C) 2012-2017 gnosygnu@gmail.com - -XOWA is licensed under the terms of the General Public License (GPL) Version 3, -or alternatively under the terms of the Apache License Version 2.0. - -You may use XOWA according to either of these licenses as is most appropriate -for your project on a case-by-case basis. - -The terms of each license can be found in the source code repository: - -GPLv3 License: https://github.com/gnosygnu/xowa/blob/master/LICENSE-GPLv3.txt -Apache License: https://github.com/gnosygnu/xowa/blob/master/LICENSE-APACHE2.txt -*/ +/* +XOWA: the XOWA Offline Wiki Application +Copyright (C) 2012-2017 gnosygnu@gmail.com + +XOWA is licensed under the terms of the General Public License (GPL) Version 3, +or alternatively under the terms of the Apache License Version 2.0. + +You may use XOWA according to either of these licenses as is most appropriate +for your project on a case-by-case basis. + +The terms of each license can be found in the source code repository: + +GPLv3 License: https://github.com/gnosygnu/xowa/blob/master/LICENSE-GPLv3.txt +Apache License: https://github.com/gnosygnu/xowa/blob/master/LICENSE-APACHE2.txt +*/ package gplx.xowa.mediawiki; import gplx.*; import gplx.xowa.*; import gplx.core.btries.*; import gplx.core.intls.*; @@ -23,6 +23,7 @@ public class XophpString_ implements XophpCallbackOwner { public static final String False = null; public static boolean is_true (String s) {return s != null;} // handles code like "if ($var)" where var is an Object; public static boolean is_false(String s) {return s == null;} + public static boolean is_null(String s) {return s == null;} public static boolean eq(String lhs, String rhs) {return String_.Eq(lhs, rhs);} public static boolean eq_not(String lhs, String rhs) {return !String_.Eq(lhs, rhs);} diff --git a/400_xowa/src/gplx/xowa/mediawiki/includes/Revision/XomwRevisionRecord.java b/400_xowa/src/gplx/xowa/mediawiki/includes/Revision/XomwRevisionRecord.java index c0f1dbc23..e5c906297 100644 --- a/400_xowa/src/gplx/xowa/mediawiki/includes/Revision/XomwRevisionRecord.java +++ b/400_xowa/src/gplx/xowa/mediawiki/includes/Revision/XomwRevisionRecord.java @@ -14,7 +14,7 @@ import gplx.xowa.mediawiki.includes.XomwTitleOld; * @since 1.31 * @since 1.32 Renamed from MediaWiki\Storage\RevisionRecord */ -abstract class XomwRevisionRecord { +public abstract class XomwRevisionRecord { // RevisionRecord deletion constants public static final int DELETED_TEXT = 1; @@ -232,20 +232,20 @@ abstract class XomwRevisionRecord { // public function getInheritedSlots() { // return new RevisionSlots( this.mSlots->getInheritedSlots() ); // } -// -// /** -// * Get revision ID. Depending on the concrete subclass, this may return null if -// * the revision ID is not known (e.g. because the revision does not yet exist -// * in the database). -// * -// * MCR migration note: this replaces Revision::getId -// * -// * @return int|null -// */ -// public function getId() { -// return this.mId; -// } -// + + /** + * Get revision ID. Depending on the concrete subclass, this may return null if + * the revision ID is not known (e.g. because the revision does not yet exist + * in the database). + * + * MCR migration note: this replaces Revision::getId + * + * @return int|null + */ + public int getId() { + return this.mId; + } + // /** // * Get parent revision ID (the original previous page revision). // * If there is no parent revision, this returns 0. diff --git a/400_xowa/src/gplx/xowa/mediawiki/includes/XomwGlobalFunctions.java b/400_xowa/src/gplx/xowa/mediawiki/includes/XomwGlobalFunctions.java index ecc7d8c5e..aa8a764b8 100644 --- a/400_xowa/src/gplx/xowa/mediawiki/includes/XomwGlobalFunctions.java +++ b/400_xowa/src/gplx/xowa/mediawiki/includes/XomwGlobalFunctions.java @@ -1,3702 +1,3246 @@ -/* -XOWA: the XOWA Offline Wiki Application -Copyright (C) 2012-2017 gnosygnu@gmail.com - -XOWA is licensed under the terms of the General Public License (GPL) Version 3, -or alternatively under the terms of the Apache License Version 2.0. - -You may use XOWA according to either of these licenses as is most appropriate -for your project on a case-by-case basis. - -The terms of each license can be found in the source code repository: - -GPLv3 License: https://github.com/gnosygnu/xowa/blob/master/LICENSE-GPLv3.txt -Apache License: https://github.com/gnosygnu/xowa/blob/master/LICENSE-APACHE2.txt -*/ -package gplx.xowa.mediawiki.includes; import gplx.*; import gplx.xowa.*; import gplx.xowa.mediawiki.*; -import gplx.core.btries.*; -import gplx.langs.htmls.encoders.*; -import gplx.xowa.mediawiki.includes.parsers.*; -/** -* Global functions used everywhere. +/* +XOWA: the XOWA Offline Wiki Application +Copyright (C) 2012-2020 gnosygnu@gmail.com + +XOWA is licensed under the terms of the General Public License (GPL) Version 3, +or alternatively under the terms of the Apache License Version 2.0. + +You may use XOWA according to either of these licenses as is most appropriate +for your project on a case-by-case basis. + +The terms of each license can be found in the source code repository: + +GPLv3 License: https://github.com/gnosygnu/xowa/blob/master/LICENSE-GPLv3.txt +Apache License: https://github.com/gnosygnu/xowa/blob/master/LICENSE-APACHE2.txt */ +package gplx.xowa.mediawiki.includes; + +import gplx.xowa.mediawiki.XomwEnv; + +// MW.SRC:1.33.1 +// XO.NOTE:MW lists functions individually; XO aggregates under XomwGlobalFunctions class public class XomwGlobalFunctions { -// // Hide compatibility functions from Doxygen -// /// @cond -// /** -// * Compatibility functions -// * -// * We support PHP 5.5.9 and up. -// * Re-implementations of newer functions or functions in non-standard -// * PHP extensions may be included here. -// */ -// -// // hash_equals function only exists in PHP >= 5.6.0 -// // https://secure.php.net/hash_equals -// if (!function_exists('hash_equals')) { -// /** -// * Check whether a user-provided String is equal to a fixed-length secret String -// * without revealing bytes of the secret String through timing differences. -// * -// * The usual way to compare strings (PHP's === operator or the underlying memcmp() -// * function in C) is to compare corresponding bytes and stop at the first difference, -// * which would take longer for a partial match than for a complete mismatch. This -// * is not secure when one of the strings (e.g. an HMAC or token) must remain secret -// * and the other may come from an attacker. Statistical analysis of timing measurements -// * over many requests may allow the attacker to guess the String's bytes one at a time -// * (and check his guesses) even if the timing differences are extremely small. -// * -// * When making such a security-sensitive comparison, it is essential that the sequence -// * in which instructions are executed and memory locations are accessed not depend on -// * the secret String's value. HOWEVER, for simplicity, we do not attempt to minimize -// * the inevitable leakage of the String's length. That is generally known anyway as -// * a chararacteristic of the hash function used to compute the secret value. -// * -// * Longer explanation: http://www.emerose.com/timing-attacks-explained -// * -// * @codeCoverageIgnore -// * @param String $known_string Fixed-length secret String to compare against -// * @param String $user_string User-provided String -// * @return boolean True if the strings are the same, false otherwise -// */ -// function hash_equals($known_string, $user_string) { -// // Strict type checking as in PHP's native implementation -// if (!is_string($known_string)) { -// trigger_error('hash_equals(): Expected known_string to be a String, ' . -// gettype($known_string) . ' given', E_USER_WARNING); -// -// return false; -// } -// -// if (!is_string($user_string)) { -// trigger_error('hash_equals(): Expected user_string to be a String, ' . -// gettype($user_string) . ' given', E_USER_WARNING); -// -// return false; -// } -// -// $known_string_len = strlen($known_string); -// if ($known_string_len !== strlen($user_string)) { -// return false; -// } -// -// $result = 0; -// for ($i = 0; $i < $known_string_len; $i++) { -// $result |= ord($known_string[$i]) ^ ord($user_string[$i]); -// } -// -// return ($result === 0); -// } -// } -// /// @endcond -// -// /** -// * Load an extension -// * -// * This queues an extension to be loaded through -// * the ExtensionRegistry system. -// * -// * @param String $ext Name of the extension to load -// * @param String|null $path Absolute path of where to find the extension.json file -// * @since 1.25 -// */ -// function wfLoadExtension($ext, $path = null) { -// if (!$path) { -// global $wgExtensionDirectory; -// $path = "$wgExtensionDirectory/$ext/extension.json"; -// } -// ExtensionRegistry::getInstance()->queue($path); -// } -// -// /** -// * Load multiple extensions at once -// * -// * Same as wfLoadExtension, but more efficient if you -// * are loading multiple extensions. -// * -// * If you want to specify custom paths, you should interact with -// * ExtensionRegistry directly. -// * -// * @see wfLoadExtension -// * @param String[] $exts Array of extension names to load -// * @since 1.25 -// */ -// function wfLoadExtensions(array $exts) { +// /** +// * Load an extension +// * +// * This queues an extension to be loaded through +// * the ExtensionRegistry system. +// * +// * @param string $ext Name of the extension to load +// * @param string|null $path Absolute path of where to find the extension.json file +// * @since 1.25 +// */ +// function wfLoadExtension($ext, $path = null) { +// if (!$path) { // global $wgExtensionDirectory; -// $registry = ExtensionRegistry::getInstance(); -// foreach ($exts as $ext) { -// $registry->queue("$wgExtensionDirectory/$ext/extension.json"); -// } +// $path = "$wgExtensionDirectory/$ext/extension.json"; // } +// ExtensionRegistry::getInstance().queue($path); +// } // -// /** -// * Load a skin -// * -// * @see wfLoadExtension -// * @param String $skin Name of the extension to load -// * @param String|null $path Absolute path of where to find the skin.json file -// * @since 1.25 -// */ -// function wfLoadSkin($skin, $path = null) { -// if (!$path) { -// global $wgStyleDirectory; -// $path = "$wgStyleDirectory/$skin/skin.json"; -// } -// ExtensionRegistry::getInstance()->queue($path); +// /** +// * Load multiple extensions at once +// * +// * Same as wfLoadExtension, but more efficient if you +// * are loading multiple extensions. +// * +// * If you want to specify custom paths, you should interact with +// * ExtensionRegistry directly. +// * +// * @see wfLoadExtension +// * @param string[] $exts Array of extension names to load +// * @since 1.25 +// */ +// function wfLoadExtensions(array $exts) { +// global $wgExtensionDirectory; +// $registry = ExtensionRegistry::getInstance(); +// foreach ($exts as $ext) { +// $registry.queue("$wgExtensionDirectory/$ext/extension.json"); // } +// } // -// /** -// * Load multiple skins at once -// * -// * @see wfLoadExtensions -// * @param String[] $skins Array of extension names to load -// * @since 1.25 -// */ -// function wfLoadSkins(array $skins) { +// /** +// * Load a skin +// * +// * @see wfLoadExtension +// * @param string $skin Name of the extension to load +// * @param string|null $path Absolute path of where to find the skin.json file +// * @since 1.25 +// */ +// function wfLoadSkin($skin, $path = null) { +// if (!$path) { // global $wgStyleDirectory; -// $registry = ExtensionRegistry::getInstance(); -// foreach ($skins as $skin) { -// $registry->queue("$wgStyleDirectory/$skin/skin.json"); -// } +// $path = "$wgStyleDirectory/$skin/skin.json"; // } +// ExtensionRegistry::getInstance().queue($path); +// } // -// /** -// * Like array_diff($a, $b) except that it works with two-dimensional arrays. -// * @param array $a -// * @param array $b -// * @return array -// */ -// function wfArrayDiff2($a, $b) { -// return array_udiff($a, $b, 'wfArrayDiff2_cmp'); +// /** +// * Load multiple skins at once +// * +// * @see wfLoadExtensions +// * @param string[] $skins Array of extension names to load +// * @since 1.25 +// */ +// function wfLoadSkins(array $skins) { +// global $wgStyleDirectory; +// $registry = ExtensionRegistry::getInstance(); +// foreach ($skins as $skin) { +// $registry.queue("$wgStyleDirectory/$skin/skin.json"); // } +// } // -// /** -// * @param array|String $a -// * @param array|String $b -// * @return int -// */ -// function wfArrayDiff2_cmp($a, $b) { -// if (is_string($a) && is_string($b)) { -// return strcmp($a, $b); -// } elseif (count($a) !== count($b)) { -// return count($a) < count($b) ? -1 : 1; -// } else { -// reset($a); -// reset($b); -// while ((list(, $valueA) = each($a)) && (list(, $valueB) = each($b))) { -// $cmp = strcmp($valueA, $valueB); -// if ($cmp !== 0) { -// return $cmp; -// } +// /** +// * Like array_diff($a, $b) except that it works with two-dimensional arrays. +// * @param array $a +// * @param array $b +// * @return array +// */ +// function wfArrayDiff2($a, $b) { +// return array_udiff($a, $b, 'wfArrayDiff2_cmp'); +// } +// +// /** +// * @param array|string $a +// * @param array|string $b +// * @return int +// */ +// function wfArrayDiff2_cmp($a, $b) { +// if (is_string($a) && is_string($b)) { +// return strcmp($a, $b); +// } elseif (count($a) !== count($b)) { +// return count($a) <=> count($b); +// } else { +// reset($a); +// reset($b); +// while (key($a) !== null && key($b) !== null) { +// $valueA = current($a); +// $valueB = current($b); +// $cmp = strcmp($valueA, $valueB); +// if ($cmp !== 0) { +// return $cmp; // } -// return 0; +// next($a); +// next($b); // } +// return 0; // } +// } // -// /** -// * Appends to second array if $value differs from that in $default -// * -// * @param String|int $key -// * @param mixed $value -// * @param mixed $default -// * @param array $changed Array to alter -// * @throws MWException -// */ -// function wfAppendToArrayIfNotDefault($key, $value, $default, &$changed) { -// if (is_null($changed)) { -// throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null'); -// } -// if ($default[$key] !== $value) { -// $changed[$key] = $value; -// } +// /** +// * @deprecated since 1.32, use array_filter() with ARRAY_FILTER_USE_BOTH directly +// * +// * @param array $arr +// * @param callable $callback Will be called with the array value and key (in that order) and +// * should return a bool which will determine whether the array element is kept. +// * @return array +// */ +// function wfArrayFilter(array $arr, callable $callback) { +// wfDeprecated(__FUNCTION__, '1.32'); +// return array_filter($arr, $callback, ARRAY_FILTER_USE_BOTH); +// } +// +// /** +// * @deprecated since 1.32, use array_filter() with ARRAY_FILTER_USE_KEY directly +// * +// * @param array $arr +// * @param callable $callback Will be called with the array key and should return a bool which +// * will determine whether the array element is kept. +// * @return array +// */ +// function wfArrayFilterByKey(array $arr, callable $callback) { +// wfDeprecated(__FUNCTION__, '1.32'); +// return array_filter($arr, $callback, ARRAY_FILTER_USE_KEY); +// } +// +// /** +// * Appends to second array if $value differs from that in $default +// * +// * @param string|int $key +// * @param mixed $value +// * @param mixed $default +// * @param array &$changed Array to alter +// * @throws MWException +// */ +// function wfAppendToArrayIfNotDefault($key, $value, $default, &$changed) { +// if (is_null($changed)) { +// throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null'); // } +// if ($default[$key] !== $value) { +// $changed[$key] = $value; +// } +// } // -// /** -// * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal -// * e.g. -// * wfMergeErrorArrays( -// * [ [ 'x' ] ], -// * [ [ 'x', '2' ] ], -// * [ [ 'x' ] ], -// * [ [ 'y' ] ] -// * ); -// * returns: -// * [ -// * [ 'x', '2' ], -// * [ 'x' ], -// * [ 'y' ] -// * ] -// * -// * @param array $array1,... -// * @return array -// */ -// function wfMergeErrorArrays(/*...*/) { -// $args = func_get_args(); -// $out = []; -// foreach ($args as $errors) { -// foreach ($errors as $params) { -// $originalParams = $params; -// if ($params[0] instanceof MessageSpecifier) { -// $msg = $params[0]; -// $params = array_merge([ $msg->getKey() ], $msg->getParams()); -// } -// # @todo FIXME: Sometimes get nested arrays for $params, -// # which leads to E_NOTICEs -// $spec = implode("\t", $params); -// $out[$spec] = $originalParams; +// /** +// * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal +// * e.g. +// * wfMergeErrorArrays( +// * [ [ 'x' ] ], +// * [ [ 'x', '2' ] ], +// * [ [ 'x' ] ], +// * [ [ 'y' ] ] +// * ); +// * returns: +// * [ +// * [ 'x', '2' ], +// * [ 'x' ], +// * [ 'y' ] +// * ] +// * +// * @param array ...$args +// * @return array +// */ +// function wfMergeErrorArrays(...$args) { +// $out = []; +// foreach ($args as $errors) { +// foreach ($errors as $params) { +// $originalParams = $params; +// if ($params[0] instanceof MessageSpecifier) { +// $msg = $params[0]; +// $params = array_merge([ $msg.getKey() ], $msg.getParams()); // } +// # @todo FIXME: Sometimes get nested arrays for $params, +// # which leads to E_NOTICEs +// $spec = implode("\t", $params); +// $out[$spec] = $originalParams; // } -// return array_values($out); // } +// return array_values($out); +// } // -// /** -// * Insert array into another array after the specified *KEY* -// * -// * @param array $array The array. -// * @param array $insert The array to insert. -// * @param mixed $after The key to insert after -// * @return array -// */ -// function wfArrayInsertAfter(array $array, array $insert, $after) { -// // Find the offset of the element to insert after. -// $keys = array_keys($array); -// $offsetByKey = array_flip($keys); +// /** +// * Insert array into another array after the specified *KEY* +// * +// * @param array $array The array. +// * @param array $insert The array to insert. +// * @param mixed $after The key to insert after. Callers need to make sure the key is set. +// * @return array +// */ +// function wfArrayInsertAfter(array $array, array $insert, $after) { +// // Find the offset of the element to insert after. +// $keys = array_keys($array); +// $offsetByKey = array_flip($keys); // -// $offset = $offsetByKey[$after]; +// $offset = $offsetByKey[$after]; // -// // Insert at the specified offset -// $before = array_slice($array, 0, $offset + 1, true); -// $after = array_slice($array, $offset + 1, count($array) - $offset, true); +// // Insert at the specified offset +// $before = array_slice($array, 0, $offset + 1, true); +// $after = array_slice($array, $offset + 1, count($array) - $offset, true); // -// $output = $before + $insert + $after; +// $output = $before + $insert + $after; // -// return $output; +// return $output; +// } +// +// /** +// * Recursively converts the parameter (an object) to an array with the same data +// * +// * @param object|array $objOrArray +// * @param bool $recursive +// * @return array +// */ +// function wfObjectToArray($objOrArray, $recursive = true) { +// $array = []; +// if (is_object($objOrArray)) { +// $objOrArray = get_object_vars($objOrArray); // } -// -// /** -// * Recursively converts the parameter (an Object) to an array with the same data -// * -// * @param Object|array $objOrArray -// * @param boolean $recursive -// * @return array -// */ -// function wfObjectToArray($objOrArray, $recursive = true) { -// $array = []; -// if (is_object($objOrArray)) { -// $objOrArray = get_object_vars($objOrArray); -// } -// foreach ($objOrArray as $key => $value) { -// if ($recursive && (is_object($value) || is_array($value))) { -// $value = wfObjectToArray($value); -// } -// -// $array[$key] = $value; +// foreach ($objOrArray as $key => $value) { +// if ($recursive && (is_object($value) || is_array($value))) { +// $value = wfObjectToArray($value); // } // -// return $array; +// $array[$key] = $value; // } // -// /** -// * Get a random decimal value between 0 and 1, in a way -// * not likely to give duplicate values for any realistic -// * number of articles. -// * -// * @note This is designed for use in relation to Special:RandomPage -// * and the page_random database field. -// * -// * @return String -// */ -// function wfRandom() { -// // The maximum random value is "only" 2^31-1, so get two random -// // values to reduce the chance of dupes -// $max = mt_getrandmax() + 1; -// $rand = number_format((mt_rand() * $max + mt_rand()) / $max / $max, 12, '.', ''); -// return $rand; -// } +// return $array; +// } // -// /** -// * Get a random String containing a number of pseudo-random hex characters. -// * -// * @note This is not secure, if you are trying to generate some sort -// * of token please use MWCryptRand instead. -// * -// * @param int $length The length of the String to generate -// * @return String -// * @since 1.20 -// */ -// function wfRandomString($length = 32) { -// $str = ''; -// for ($n = 0; $n < $length; $n += 7) { -// $str .= sprintf('%07x', mt_rand() & 0xfffffff); -// } -// return substr($str, 0, $length); +// /** +// * Get a random decimal value in the domain of [0, 1), in a way +// * not likely to give duplicate values for any realistic +// * number of articles. +// * +// * @note This is designed for use in relation to Special:RandomPage +// * and the page_random database field. +// * +// * @return string +// */ +// function wfRandom() { +// // The maximum random value is "only" 2^31-1, so get two random +// // values to reduce the chance of dupes +// $max = mt_getrandmax() + 1; +// $rand = number_format((mt_rand() * $max + mt_rand()) / $max / $max, 12, '.', ''); +// return $rand; +// } +// +// /** +// * Get a random string containing a number of pseudo-random hex characters. +// * +// * @note This is not secure, if you are trying to generate some sort +// * of token please use MWCryptRand instead. +// * +// * @param int $length The length of the string to generate +// * @return string +// * @since 1.20 +// */ +// function wfRandomString($length = 32) { +// $str = ''; +// for ($n = 0; $n < $length; $n += 7) { +// $str .= sprintf('%07x', mt_rand() & 0xfffffff); // } - +// return substr($str, 0, $length); +// } +// /** - * We want some things to be included as literal characters in our title URLs - * for prettiness, which urlencode encodes by default. According to RFC 1738, - * all of the following should be safe: - * - * ;:@&=$-_.+!*'(), - * - * RFC 1738 says ~ is unsafe, however RFC 3986 considers it an unreserved - * character which should not be encoded. More importantly, google chrome - * always converts %7E back to ~, and converting it in this function can - * cause a redirect loop (T105265). - * - * But + is not safe because it's used to indicate a space; &= are only safe in - * paths and not in queries (and we don't distinguish here); ' seems kind of - * scary; and urlencode() doesn't touch -_. to begin with. Plus, although / - * is reserved, we don't care. So the list we unescape is: - * - * ;:@$!*(),/~ - * - * However, IIS7 redirects fail when the url contains a colon (see T24709), - * so no fancy : for IIS7. - * - * %2F in the page titles seems to fatally break for some reason. - * - * @param String $s - * @return String - */ - public static byte[] wfUrlencode(byte[] s) { - if (s == null) { - // $needle = null; - return Bry_.Empty; - } + * We want some things to be included as literal characters in our title URLs + * for prettiness, which urlencode encodes by default. According to RFC 1738, + * all of the following should be safe: + * + * ;:@&=$-_.+!*'(), + * + * RFC 1738 says ~ is unsafe, however RFC 3986 considers it an unreserved + * character which should not be encoded. More importantly, google chrome + * always converts %7E back to ~, and converting it in this function can + * cause a redirect loop (T105265). + * + * But + is not safe because it's used to indicate a space; &= are only safe in + * paths and not in queries (and we don't distinguish here); ' seems kind of + * scary; and urlencode() doesn't touch -_. to begin with. Plus, although / + * is reserved, we don't care. So the list we unescape is: + * + * ;:@$!*(),/~ + * + * However, IIS7 redirects fail when the url contains a colon (see T24709), + * so no fancy : for IIS7. + * + * %2F in the page titles seems to fatally break for some reason. + * + * @param string $s + * @return string + */ + public static byte[] wfUrlencode(byte[] s) {return s;} + public static String wfUrlencode(String s) { +// static $needle; +// +// if (is_null($s)) { +// // Reset $needle for testing. +// $needle = null; +// return ''; +// } +// +// if (is_null($needle)) { +// $needle = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' ]; +// if (!isset($_SERVER['SERVER_SOFTWARE']) || +// (strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7') === false) +// ) { +// $needle[] = '%3A'; +// } +// } +// +// $s = urlencode($s); +// $s = str_ireplace( +// $needle, +// [ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ], +// $s +// ); - // SKIP: handled directly in Gfo_url_encode - // if (needle == null) { - // needle = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' ]; - // if (!isset($_SERVER['SERVER_SOFTWARE']) || - // (strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7') === false) - // ) { - // $needle[] = '%3A'; - // } - // } - // - // $s = urlencode($s); - // $s = str_ireplace( - // $needle, - // [ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ], - // $s - // ); - - return Gfo_url_encoder_.Mw_wfUrlencode.Encode(s); +// return $s; + return null; } - -// /** -// * This function takes one or two arrays as input, and returns a CGI-style String, e.g. -// * "days=7&limit=100". Options in the first array override options in the second. -// * Options set to null or false will not be output. -// * -// * @param array $array1 (String|Array) -// * @param array|null $array2 (String|Array) -// * @param String $prefix -// * @return String -// */ -// function wfArrayToCgi($array1, $array2 = null, $prefix = '') { -// if (!is_null($array2)) { -// $array1 = $array1 + $array2; -// } // -// $cgi = ''; -// foreach ($array1 as $key => $value) { -// if (!is_null($value) && $value !== false) { -// if ($cgi != '') { -// $cgi .= '&'; -// } -// if ($prefix !== '') { -// $key = $prefix . "[$key]"; -// } -// if (is_array($value)) { -// $firstTime = true; -// foreach ($value as $k => $v) { -// $cgi .= $firstTime ? '' : '&'; -// if (is_array($v)) { -// $cgi .= wfArrayToCgi($v, null, $key . "[$k]"); -// } else { -// $cgi .= urlencode($key . "[$k]") . '=' . urlencode($v); -// } -// $firstTime = false; +// /** +// * This function takes one or two arrays as input, and returns a CGI-style string, e.g. +// * "days=7&limit=100". Options in the first array override options in the second. +// * Options set to null or false will not be output. +// * +// * @param array $array1 (String|Array) +// * @param array|null $array2 (String|Array) +// * @param string $prefix +// * @return string +// */ +// function wfArrayToCgi($array1, $array2 = null, $prefix = '') { +// if (!is_null($array2)) { +// $array1 = $array1 + $array2; +// } +// +// $cgi = ''; +// foreach ($array1 as $key => $value) { +// if (!is_null($value) && $value !== false) { +// if ($cgi != '') { +// $cgi .= '&'; +// } +// if ($prefix !== '') { +// $key = $prefix . "[$key]"; +// } +// if (is_array($value)) { +// $firstTime = true; +// foreach ($value as $k => $v) { +// $cgi .= $firstTime ? '' : '&'; +// if (is_array($v)) { +// $cgi .= wfArrayToCgi($v, null, $key . "[$k]"); +// } else { +// $cgi .= urlencode($key . "[$k]") . '=' . urlencode($v); // } -// } else { -// if (is_object($value)) { -// $value = $value->__toString(); -// } -// $cgi .= urlencode($key) . '=' . urlencode($value); -// } -// } -// } -// return $cgi; -// } -// -// /** -// * This is the logical opposite of wfArrayToCgi(): it accepts a query String as -// * its argument and returns the same String in array form. This allows compatibility -// * with legacy functions that accept raw query strings instead of nice -// * arrays. Of course, keys and values are urldecode()d. -// * -// * @param String $query Query String -// * @return String[] Array version of input -// */ -// function wfCgiToArray($query) { -// if (isset($query[0]) && $query[0] == '?') { -// $query = substr($query, 1); -// } -// $bits = explode('&', $query); -// $ret = []; -// foreach ($bits as $bit) { -// if ($bit === '') { -// continue; -// } -// if (strpos($bit, '=') === false) { -// // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does) -// $key = $bit; -// $value = ''; -// } else { -// list($key, $value) = explode('=', $bit); -// } -// $key = urldecode($key); -// $value = urldecode($value); -// if (strpos($key, '[') !== false) { -// $keys = array_reverse(explode('[', $key)); -// $key = array_pop($keys); -// $temp = $value; -// foreach ($keys as $k) { -// $k = substr($k, 0, -1); -// $temp = [ $k => $temp ]; -// } -// if (isset($ret[$key])) { -// $ret[$key] = array_merge($ret[$key], $temp); -// } else { -// $ret[$key] = $temp; +// $firstTime = false; // } // } else { -// $ret[$key] = $value; +// if (is_object($value)) { +// $value = $value.__toString(); +// } +// $cgi .= urlencode($key) . '=' . urlencode($value); // } // } -// return $ret; // } +// return $cgi; +// } // -// /** -// * Append a query String to an existing URL, which may or may not already -// * have query String parameters already. If so, they will be combined. -// * -// * @param String $url -// * @param String|String[] $query String or associative array -// * @return String -// */ -// function wfAppendQuery($url, $query) { -// if (is_array($query)) { -// $query = wfArrayToCgi($query); -// } -// if ($query != '') { -// // Remove the fragment, if there is one -// $fragment = false; -// $hashPos = strpos($url, '#'); -// if ($hashPos !== false) { -// $fragment = substr($url, $hashPos); -// $url = substr($url, 0, $hashPos); -// } -// -// // Add parameter -// if (false === strpos($url, '?')) { -// $url .= '?'; -// } else { -// $url .= '&'; -// } -// $url .= $query; -// -// // Put the fragment back -// if ($fragment !== false) { -// $url .= $fragment; -// } -// } -// return $url; +// /** +// * This is the logical opposite of wfArrayToCgi(): it accepts a query string as +// * its argument and returns the same string in array form. This allows compatibility +// * with legacy functions that accept raw query strings instead of nice +// * arrays. Of course, keys and values are urldecode()d. +// * +// * @param string $query Query string +// * @return string[] Array version of input +// */ +// function wfCgiToArray($query) { +// if (isset($query[0]) && $query[0] == '?') { +// $query = substr($query, 1); // } -// -// /** -// * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer -// * is correct. -// * -// * The meaning of the PROTO_* constants is as follows: -// * PROTO_HTTP: Output a URL starting with http:// -// * PROTO_HTTPS: Output a URL starting with https:// -// * PROTO_RELATIVE: Output a URL starting with // (protocol-relative URL) -// * PROTO_CURRENT: Output a URL starting with either http:// or https:// , depending -// * on which protocol was used for the current incoming request -// * PROTO_CANONICAL: For URLs without a domain, like /w/index.php , use $wgCanonicalServer. -// * For protocol-relative URLs, use the protocol of $wgCanonicalServer -// * PROTO_INTERNAL: Like PROTO_CANONICAL, but uses $wgInternalServer instead of $wgCanonicalServer -// * -// * @todo this won't work with current-path-relative URLs -// * like "subdir/foo.html", etc. -// * -// * @param String $url Either fully-qualified or a local path + query -// * @param String $defaultProto One of the PROTO_* constants. Determines the -// * protocol to use if $url or $wgServer is protocol-relative -// * @return String|false Fully-qualified URL, current-path-relative URL or false if -// * no valid URL can be constructed -// */ -// function wfExpandUrl($url, $defaultProto = PROTO_CURRENT) { -// global $wgServer, $wgCanonicalServer, $wgInternalServer, $wgRequest, -// $wgHttpsPort; -// if ($defaultProto === PROTO_CANONICAL) { -// $serverUrl = $wgCanonicalServer; -// } elseif ($defaultProto === PROTO_INTERNAL && $wgInternalServer !== false) { -// // Make $wgInternalServer fall back to $wgServer if not set -// $serverUrl = $wgInternalServer; +// $bits = explode('&', $query); +// $ret = []; +// foreach ($bits as $bit) { +// if ($bit === '') { +// continue; +// } +// if (strpos($bit, '=') === false) { +// // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does) +// $key = $bit; +// $value = ''; // } else { -// $serverUrl = $wgServer; -// if ($defaultProto === PROTO_CURRENT) { -// $defaultProto = $wgRequest->getProtocol() . '://'; -// } +// list($key, $value) = explode('=', $bit); // } -// -// // Analyze $serverUrl to obtain its protocol -// $bits = wfParseUrl($serverUrl); -// $serverHasProto = $bits && $bits['scheme'] != ''; -// -// if ($defaultProto === PROTO_CANONICAL || $defaultProto === PROTO_INTERNAL) { -// if ($serverHasProto) { -// $defaultProto = $bits['scheme'] . '://'; +// $key = urldecode($key); +// $value = urldecode($value); +// if (strpos($key, '[') !== false) { +// $keys = array_reverse(explode('[', $key)); +// $key = array_pop($keys); +// $temp = $value; +// foreach ($keys as $k) { +// $k = substr($k, 0, -1); +// $temp = [ $k => $temp ]; +// } +// if (isset($ret[$key])) { +// $ret[$key] = array_merge($ret[$key], $temp); // } else { -// // $wgCanonicalServer or $wgInternalServer doesn't have a protocol. -// // This really isn't supposed to happen. Fall back to HTTP in this -// // ridiculous case. -// $defaultProto = PROTO_HTTP; +// $ret[$key] = $temp; +// } +// } else { +// $ret[$key] = $value; +// } +// } +// return $ret; +// } +// +// /** +// * Append a query string to an existing URL, which may or may not already +// * have query string parameters already. If so, they will be combined. +// * +// * @param string $url +// * @param string|string[] $query String or associative array +// * @return string +// */ +// function wfAppendQuery($url, $query) { +// if (is_array($query)) { +// $query = wfArrayToCgi($query); +// } +// if ($query != '') { +// // Remove the fragment, if there is one +// $fragment = false; +// $hashPos = strpos($url, '#'); +// if ($hashPos !== false) { +// $fragment = substr($url, $hashPos); +// $url = substr($url, 0, $hashPos); +// } +// +// // Add parameter +// if (strpos($url, '?') === false) { +// $url .= '?'; +// } else { +// $url .= '&'; +// } +// $url .= $query; +// +// // Put the fragment back +// if ($fragment !== false) { +// $url .= $fragment; +// } +// } +// return $url; +// } +// +// /** +// * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer +// * is correct. +// * +// * The meaning of the PROTO_* constants is as follows: +// * PROTO_HTTP: Output a URL starting with http:// +// * PROTO_HTTPS: Output a URL starting with https:// +// * PROTO_RELATIVE: Output a URL starting with // (protocol-relative URL) +// * PROTO_CURRENT: Output a URL starting with either http:// or https:// , depending +// * on which protocol was used for the current incoming request +// * PROTO_CANONICAL: For URLs without a domain, like /w/index.php , use $wgCanonicalServer. +// * For protocol-relative URLs, use the protocol of $wgCanonicalServer +// * PROTO_INTERNAL: Like PROTO_CANONICAL, but uses $wgInternalServer instead of $wgCanonicalServer +// * +// * @todo this won't work with current-path-relative URLs +// * like "subdir/foo.html", etc. +// * +// * @param string $url Either fully-qualified or a local path + query +// * @param string|int|null $defaultProto One of the PROTO_* constants. Determines the +// * protocol to use if $url or $wgServer is protocol-relative +// * @return string|false Fully-qualified URL, current-path-relative URL or false if +// * no valid URL can be constructed +// */ +// function wfExpandUrl($url, $defaultProto = PROTO_CURRENT) { +// global $wgServer, $wgCanonicalServer, $wgInternalServer, $wgRequest, +// $wgHttpsPort; +// if ($defaultProto === PROTO_CANONICAL) { +// $serverUrl = $wgCanonicalServer; +// } elseif ($defaultProto === PROTO_INTERNAL && $wgInternalServer !== false) { +// // Make $wgInternalServer fall back to $wgServer if not set +// $serverUrl = $wgInternalServer; +// } else { +// $serverUrl = $wgServer; +// if ($defaultProto === PROTO_CURRENT) { +// $defaultProto = $wgRequest.getProtocol() . '://'; +// } +// } +// +// // Analyze $serverUrl to obtain its protocol +// $bits = wfParseUrl($serverUrl); +// $serverHasProto = $bits && $bits['scheme'] != ''; +// +// if ($defaultProto === PROTO_CANONICAL || $defaultProto === PROTO_INTERNAL) { +// if ($serverHasProto) { +// $defaultProto = $bits['scheme'] . '://'; +// } else { +// // $wgCanonicalServer or $wgInternalServer doesn't have a protocol. +// // This really isn't supposed to happen. Fall back to HTTP in this +// // ridiculous case. +// $defaultProto = PROTO_HTTP; +// } +// } +// +// $defaultProtoWithoutSlashes = substr($defaultProto, 0, -2); +// +// if (substr($url, 0, 2) == '//') { +// $url = $defaultProtoWithoutSlashes . $url; +// } elseif (substr($url, 0, 1) == '/') { +// // If $serverUrl is protocol-relative, prepend $defaultProtoWithoutSlashes, +// // otherwise leave it alone. +// if ($serverHasProto) { +// $url = $serverUrl . $url; +// } else { +// // If an HTTPS URL is synthesized from a protocol-relative $wgServer, allow the +// // user to override the port number (T67184) +// if ($defaultProto === PROTO_HTTPS && $wgHttpsPort != 443) { +// if (isset($bits['port'])) { +// throw new Exception('A protocol-relative $wgServer may not contain a port number'); +// } +// $url = $defaultProtoWithoutSlashes . $serverUrl . ':' . $wgHttpsPort . $url; +// } else { +// $url = $defaultProtoWithoutSlashes . $serverUrl . $url; +// } +// } +// } +// +// $bits = wfParseUrl($url); +// +// if ($bits && isset($bits['path'])) { +// $bits['path'] = wfRemoveDotSegments($bits['path']); +// return wfAssembleUrl($bits); +// } elseif ($bits) { +// # No path to expand +// return $url; +// } elseif (substr($url, 0, 1) != '/') { +// # URL is a relative path +// return wfRemoveDotSegments($url); +// } +// +// # Expanded URL is not valid. +// return false; +// } +// +// /** +// * Get the wiki's "server", i.e. the protocol and host part of the URL, with a +// * protocol specified using a PROTO_* constant as in wfExpandUrl() +// * +// * @since 1.32 +// * @param string|int|null $proto One of the PROTO_* constants. +// * @return string The URL +// */ +// function wfGetServerUrl($proto) { +// $url = wfExpandUrl('/', $proto); +// return substr($url, 0, -1); +// } +// +// /** +// * This function will reassemble a URL parsed with wfParseURL. This is useful +// * if you need to edit part of a URL and put it back together. +// * +// * This is the basic structure used (brackets contain keys for $urlParts): +// * [scheme][delimiter][user]:[pass]@[host]:[port][path]?[query]#[fragment] +// * +// * @todo Need to integrate this into wfExpandUrl (see T34168) +// * +// * @since 1.19 +// * @param array $urlParts URL parts, as output from wfParseUrl +// * @return string URL assembled from its component parts +// */ +// function wfAssembleUrl($urlParts) { +// $result = ''; +// +// if (isset($urlParts['delimiter'])) { +// if (isset($urlParts['scheme'])) { +// $result .= $urlParts['scheme']; +// } +// +// $result .= $urlParts['delimiter']; +// } +// +// if (isset($urlParts['host'])) { +// if (isset($urlParts['user'])) { +// $result .= $urlParts['user']; +// if (isset($urlParts['pass'])) { +// $result .= ':' . $urlParts['pass']; +// } +// $result .= '@'; +// } +// +// $result .= $urlParts['host']; +// +// if (isset($urlParts['port'])) { +// $result .= ':' . $urlParts['port']; +// } +// } +// +// if (isset($urlParts['path'])) { +// $result .= $urlParts['path']; +// } +// +// if (isset($urlParts['query'])) { +// $result .= '?' . $urlParts['query']; +// } +// +// if (isset($urlParts['fragment'])) { +// $result .= '#' . $urlParts['fragment']; +// } +// +// return $result; +// } +// +// /** +// * Remove all dot-segments in the provided URL path. For example, +// * '/a/./b/../c/' becomes '/a/c/'. For details on the algorithm, please see +// * RFC3986 section 5.2.4. +// * +// * @todo Need to integrate this into wfExpandUrl (see T34168) +// * +// * @since 1.19 +// * +// * @param string $urlPath URL path, potentially containing dot-segments +// * @return string URL path with all dot-segments removed +// */ +// function wfRemoveDotSegments($urlPath) { +// $output = ''; +// $inputOffset = 0; +// $inputLength = strlen($urlPath); +// +// while ($inputOffset < $inputLength) { +// $prefixLengthOne = substr($urlPath, $inputOffset, 1); +// $prefixLengthTwo = substr($urlPath, $inputOffset, 2); +// $prefixLengthThree = substr($urlPath, $inputOffset, 3); +// $prefixLengthFour = substr($urlPath, $inputOffset, 4); +// $trimOutput = false; +// +// if ($prefixLengthTwo == './') { +// # Step A, remove leading "./" +// $inputOffset += 2; +// } elseif ($prefixLengthThree == '../') { +// # Step A, remove leading "../" +// $inputOffset += 3; +// } elseif (($prefixLengthTwo == '/.') && ($inputOffset + 2 == $inputLength)) { +// # Step B, replace leading "/.$" with "/" +// $inputOffset += 1; +// $urlPath[$inputOffset] = '/'; +// } elseif ($prefixLengthThree == '/./') { +// # Step B, replace leading "/./" with "/" +// $inputOffset += 2; +// } elseif ($prefixLengthThree == '/..' && ($inputOffset + 3 == $inputLength)) { +// # Step C, replace leading "/..$" with "/" and +// # remove last path component in output +// $inputOffset += 2; +// $urlPath[$inputOffset] = '/'; +// $trimOutput = true; +// } elseif ($prefixLengthFour == '/../') { +// # Step C, replace leading "/../" with "/" and +// # remove last path component in output +// $inputOffset += 3; +// $trimOutput = true; +// } elseif (($prefixLengthOne == '.') && ($inputOffset + 1 == $inputLength)) { +// # Step D, remove "^.$" +// $inputOffset += 1; +// } elseif (($prefixLengthTwo == '..') && ($inputOffset + 2 == $inputLength)) { +// # Step D, remove "^..$" +// $inputOffset += 2; +// } else { +// # Step E, move leading path segment to output +// if ($prefixLengthOne == '/') { +// $slashPos = strpos($urlPath, '/', $inputOffset + 1); +// } else { +// $slashPos = strpos($urlPath, '/', $inputOffset); +// } +// if ($slashPos === false) { +// $output .= substr($urlPath, $inputOffset); +// $inputOffset = $inputLength; +// } else { +// $output .= substr($urlPath, $inputOffset, $slashPos - $inputOffset); +// $inputOffset += $slashPos - $inputOffset; // } // } // -// $defaultProtoWithoutSlashes = substr($defaultProto, 0, -2); +// if ($trimOutput) { +// $slashPos = strrpos($output, '/'); +// if ($slashPos === false) { +// $output = ''; +// } else { +// $output = substr($output, 0, $slashPos); +// } +// } +// } // -// if (substr($url, 0, 2) == '//') { -// $url = $defaultProtoWithoutSlashes . $url; -// } elseif (substr($url, 0, 1) == '/') { -// // If $serverUrl is protocol-relative, prepend $defaultProtoWithoutSlashes, -// // otherwise leave it alone. -// $url = ($serverHasProto ? '' : $defaultProtoWithoutSlashes) . $serverUrl . $url; +// return $output; +// } +// +// /** +// * Returns a regular expression of url protocols +// * +// * @param bool $includeProtocolRelative If false, remove '//' from the returned protocol list. +// * DO NOT USE this directly, use wfUrlProtocolsWithoutProtRel() instead +// * @return string +// */ +// function wfUrlProtocols($includeProtocolRelative = true) { +// global $wgUrlProtocols; +// +// // Cache return values separately based on $includeProtocolRelative +// static $withProtRel = null, $withoutProtRel = null; +// $cachedValue = $includeProtocolRelative ? $withProtRel : $withoutProtRel; +// if (!is_null($cachedValue)) { +// return $cachedValue; +// } +// +// // Support old-style $wgUrlProtocols strings, for backwards compatibility +// // with LocalSettings files from 1.5 +// if (is_array($wgUrlProtocols)) { +// $protocols = []; +// foreach ($wgUrlProtocols as $protocol) { +// // Filter out '//' if !$includeProtocolRelative +// if ($includeProtocolRelative || $protocol !== '//') { +// $protocols[] = preg_quote($protocol, '/'); +// } // } // -// $bits = wfParseUrl($url); +// $retval = implode('|', $protocols); +// } else { +// // Ignore $includeProtocolRelative in this case +// // This case exists for pre-1.6 compatibility, and we can safely assume +// // that '//' won't appear in a pre-1.6 config because protocol-relative +// // URLs weren't supported until 1.18 +// $retval = $wgUrlProtocols; +// } // -// // ensure proper port for HTTPS arrives in URL -// // https://phabricator.wikimedia.org/T67184 -// if ($defaultProto === PROTO_HTTPS && $wgHttpsPort != 443) { -// $bits['port'] = $wgHttpsPort; -// } +// // Cache return value +// if ($includeProtocolRelative) { +// $withProtRel = $retval; +// } else { +// $withoutProtRel = $retval; +// } +// return $retval; +// } // -// if ($bits && isset($bits['path'])) { -// $bits['path'] = wfRemoveDotSegments($bits['path']); -// return wfAssembleUrl($bits); -// } elseif ($bits) { -// # No path to expand -// return $url; -// } elseif (substr($url, 0, 1) != '/') { -// # URL is a relative path -// return wfRemoveDotSegments($url); -// } +// /** +// * Like wfUrlProtocols(), but excludes '//' from the protocol list. Use this if +// * you need a regex that matches all URL protocols but does not match protocol- +// * relative URLs +// * @return string +// */ +// function wfUrlProtocolsWithoutProtRel() { +// return wfUrlProtocols(false); +// } // -// # Expanded URL is not valid. +// /** +// * parse_url() work-alike, but non-broken. Differences: +// * +// * 1) Does not raise warnings on bad URLs (just returns false). +// * 2) Handles protocols that don't use :// (e.g., mailto: and news:, as well as +// * protocol-relative URLs) correctly. +// * 3) Adds a "delimiter" element to the array (see (2)). +// * 4) Verifies that the protocol is on the $wgUrlProtocols whitelist. +// * 5) Rejects some invalid URLs that parse_url doesn't, e.g. the empty string or URLs starting with +// * a line feed character. +// * +// * @param string $url A URL to parse +// * @return string[]|bool Bits of the URL in an associative array, or false on failure. +// * Possible fields: +// * - scheme: URI scheme (protocol), e.g. 'http', 'mailto'. Lowercase, always present, but can +// * be an empty string for protocol-relative URLs. +// * - delimiter: either '://', ':' or '//'. Always present. +// * - host: domain name / IP. Always present, but could be an empty string, e.g. for file: URLs. +// * - user: user name, e.g. for HTTP Basic auth URLs such as http://user:pass@example.com/ +// * Missing when there is no username. +// * - pass: password, same as above. +// * - path: path including the leading /. Will be missing when empty (e.g. 'http://example.com') +// * - query: query string (as a string; see wfCgiToArray() for parsing it), can be missing. +// * - fragment: the part after #, can be missing. +// */ +// function wfParseUrl($url) { +// global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php +// +// // Protocol-relative URLs are handled really badly by parse_url(). It's so +// // bad that the easiest way to handle them is to just prepend 'http:' and +// // strip the protocol out later. +// $wasRelative = substr($url, 0, 2) == '//'; +// if ($wasRelative) { +// $url = "http:$url"; +// } +// Wikimedia\suppressWarnings(); +// $bits = parse_url($url); +// Wikimedia\restoreWarnings(); +// // parse_url() returns an array without scheme for some invalid URLs, e.g. +// // parse_url("%0Ahttp://example.com") == [ 'host' => '%0Ahttp', 'path' => 'example.com' ] +// if (!$bits || !isset($bits['scheme'])) { // return false; // } // -// /** -// * This function will reassemble a URL parsed with wfParseURL. This is useful -// * if you need to edit part of a URL and put it back together. -// * -// * This is the basic structure used (brackets contain keys for $urlParts): -// * [scheme][delimiter][user]:[pass]@[host]:[port][path]?[query]#[fragment] -// * -// * @todo Need to integrate this into wfExpandUrl (see T34168) -// * -// * @since 1.19 -// * @param array $urlParts URL parts, as output from wfParseUrl -// * @return String URL assembled from its component parts -// */ -// function wfAssembleUrl($urlParts) { -// $result = ''; +// // parse_url() incorrectly handles schemes case-sensitively. Convert it to lowercase. +// $bits['scheme'] = strtolower($bits['scheme']); // -// if (isset($urlParts['delimiter'])) { -// if (isset($urlParts['scheme'])) { -// $result .= $urlParts['scheme']; -// } -// -// $result .= $urlParts['delimiter']; +// // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it +// if (in_array($bits['scheme'] . '://', $wgUrlProtocols)) { +// $bits['delimiter'] = '://'; +// } elseif (in_array($bits['scheme'] . ':', $wgUrlProtocols)) { +// $bits['delimiter'] = ':'; +// // parse_url detects for news: and mailto: the host part of an url as path +// // We have to correct this wrong detection +// if (isset($bits['path'])) { +// $bits['host'] = $bits['path']; +// $bits['path'] = ''; // } -// -// if (isset($urlParts['host'])) { -// if (isset($urlParts['user'])) { -// $result .= $urlParts['user']; -// if (isset($urlParts['pass'])) { -// $result .= ':' . $urlParts['pass']; -// } -// $result .= '@'; -// } -// -// $result .= $urlParts['host']; -// -// if (isset($urlParts['port'])) { -// $result .= ':' . $urlParts['port']; -// } -// } -// -// if (isset($urlParts['path'])) { -// $result .= $urlParts['path']; -// } -// -// if (isset($urlParts['query'])) { -// $result .= '?' . $urlParts['query']; -// } -// -// if (isset($urlParts['fragment'])) { -// $result .= '#' . $urlParts['fragment']; -// } -// -// return $result; +// } else { +// return false; // } // -// /** -// * Remove all dot-segments in the provided URL path. For example, -// * '/a/./b/../c/' becomes '/a/c/'. For details on the algorithm, please see -// * RFC3986 section 5.2.4. -// * -// * @todo Need to integrate this into wfExpandUrl (see T34168) -// * -// * @param String $urlPath URL path, potentially containing dot-segments -// * @return String URL path with all dot-segments removed -// */ -// function wfRemoveDotSegments($urlPath) { -// $output = ''; -// $inputOffset = 0; -// $inputLength = strlen($urlPath); +// /* Provide an empty host for eg. file:/// urls (see T30627) */ +// if (!isset($bits['host'])) { +// $bits['host'] = ''; // -// while ($inputOffset < $inputLength) { -// $prefixLengthOne = substr($urlPath, $inputOffset, 1); -// $prefixLengthTwo = substr($urlPath, $inputOffset, 2); -// $prefixLengthThree = substr($urlPath, $inputOffset, 3); -// $prefixLengthFour = substr($urlPath, $inputOffset, 4); -// $trimOutput = false; -// -// if ($prefixLengthTwo == './') { -// # Step A, remove leading "./" -// $inputOffset += 2; -// } elseif ($prefixLengthThree == '../') { -// # Step A, remove leading "../" -// $inputOffset += 3; -// } elseif (($prefixLengthTwo == '/.') && ($inputOffset + 2 == $inputLength)) { -// # Step B, replace leading "/.$" with "/" -// $inputOffset += 1; -// $urlPath[$inputOffset] = '/'; -// } elseif ($prefixLengthThree == '/./') { -// # Step B, replace leading "/./" with "/" -// $inputOffset += 2; -// } elseif ($prefixLengthThree == '/..' && ($inputOffset + 3 == $inputLength)) { -// # Step C, replace leading "/..$" with "/" and -// # remove last path component in output -// $inputOffset += 2; -// $urlPath[$inputOffset] = '/'; -// $trimOutput = true; -// } elseif ($prefixLengthFour == '/../') { -// # Step C, replace leading "/../" with "/" and -// # remove last path component in output -// $inputOffset += 3; -// $trimOutput = true; -// } elseif (($prefixLengthOne == '.') && ($inputOffset + 1 == $inputLength)) { -// # Step D, remove "^.$" -// $inputOffset += 1; -// } elseif (($prefixLengthTwo == '..') && ($inputOffset + 2 == $inputLength)) { -// # Step D, remove "^..$" -// $inputOffset += 2; -// } else { -// # Step E, move leading path segment to output -// if ($prefixLengthOne == '/') { -// $slashPos = strpos($urlPath, '/', $inputOffset + 1); -// } else { -// $slashPos = strpos($urlPath, '/', $inputOffset); -// } -// if ($slashPos === false) { -// $output .= substr($urlPath, $inputOffset); -// $inputOffset = $inputLength; -// } else { -// $output .= substr($urlPath, $inputOffset, $slashPos - $inputOffset); -// $inputOffset += $slashPos - $inputOffset; -// } -// } -// -// if ($trimOutput) { -// $slashPos = strrpos($output, '/'); -// if ($slashPos === false) { -// $output = ''; -// } else { -// $output = substr($output, 0, $slashPos); -// } -// } -// } -// -// return $output; -// } -// -// /** -// * Returns a regular expression of url protocols -// * -// * @param boolean $includeProtocolRelative If false, remove '//' from the returned protocol list. -// * DO NOT USE this directly, use wfUrlProtocolsWithoutProtRel() instead -// * @return String -// */ -// function wfUrlProtocols($includeProtocolRelative = true) { -// global $wgUrlProtocols; -// -// // Cache return values separately based on $includeProtocolRelative -// static $withProtRel = null, $withoutProtRel = null; -// $cachedValue = $includeProtocolRelative ? $withProtRel : $withoutProtRel; -// if (!is_null($cachedValue)) { -// return $cachedValue; -// } -// -// // Support old-style $wgUrlProtocols strings, for backwards compatibility -// // with LocalSettings files from 1.5 -// if (is_array($wgUrlProtocols)) { -// $protocols = []; -// foreach ($wgUrlProtocols as $protocol) { -// // Filter out '//' if !$includeProtocolRelative -// if ($includeProtocolRelative || $protocol !== '//') { -// $protocols[] = preg_quote($protocol, '/'); -// } -// } -// -// $retval = implode('|', $protocols); -// } else { -// // Ignore $includeProtocolRelative in this case -// // This case exists for pre-1.6 compatibility, and we can safely assume -// // that '//' won't appear in a pre-1.6 config because protocol-relative -// // URLs weren't supported until 1.18 -// $retval = $wgUrlProtocols; -// } -// -// // Cache return value -// if ($includeProtocolRelative) { -// $withProtRel = $retval; -// } else { -// $withoutProtRel = $retval; -// } -// return $retval; -// } -// -// /** -// * Like wfUrlProtocols(), but excludes '//' from the protocol list. Use this if -// * you need a regex that matches all URL protocols but does not match protocol- -// * relative URLs -// * @return String -// */ -// function wfUrlProtocolsWithoutProtRel() { -// return wfUrlProtocols(false); -// } -// -// /** -// * parse_url() work-alike, but non-broken. Differences: -// * -// * 1) Does not raise warnings on bad URLs (just returns false). -// * 2) Handles protocols that don't use :// (e.g., mailto: and news:, as well as -// * protocol-relative URLs) correctly. -// * 3) Adds a "delimiter" element to the array, either '://', ':' or '//' (see (2)). -// * -// * @param String $url A URL to parse -// * @return String[]|boolean Bits of the URL in an associative array, per PHP docs, false on failure -// */ -// function wfParseUrl($url) { -// global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php -// -// // Protocol-relative URLs are handled really badly by parse_url(). It's so -// // bad that the easiest way to handle them is to just prepend 'http:' and -// // strip the protocol out later. -// $wasRelative = substr($url, 0, 2) == '//'; -// if ($wasRelative) { -// $url = "http:$url"; -// } -// MediaWiki\suppressWarnings(); -// $bits = parse_url($url); -// MediaWiki\restoreWarnings(); -// // parse_url() returns an array without scheme for some invalid URLs, e.g. -// // parse_url("%0Ahttp://example.com") == [ 'host' => '%0Ahttp', 'path' => 'example.com' ] -// if (!$bits || !isset($bits['scheme'])) { -// return false; -// } -// -// // parse_url() incorrectly handles schemes case-sensitively. Convert it to lowercase. -// $bits['scheme'] = strtolower($bits['scheme']); -// -// // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it -// if (in_array($bits['scheme'] . '://', $wgUrlProtocols)) { -// $bits['delimiter'] = '://'; -// } elseif (in_array($bits['scheme'] . ':', $wgUrlProtocols)) { -// $bits['delimiter'] = ':'; -// // parse_url detects for news: and mailto: the host part of an url as path -// // We have to correct this wrong detection -// if (isset($bits['path'])) { -// $bits['host'] = $bits['path']; -// $bits['path'] = ''; +// // See T47069 +// if (isset($bits['path'])) { +// /* parse_url loses the third / for file:///c:/ urls (but not on variants) */ +// if (substr($bits['path'], 0, 1) !== '/') { +// $bits['path'] = '/' . $bits['path']; // } // } else { -// return false; +// $bits['path'] = ''; // } -// -// /* Provide an empty host for eg. file:/// urls (see T30627) */ -// if (!isset($bits['host'])) { -// $bits['host'] = ''; -// -// // See T47069 -// if (isset($bits['path'])) { -// /* parse_url loses the third / for file:///c:/ urls (but not on variants) */ -// if (substr($bits['path'], 0, 1) !== '/') { -// $bits['path'] = '/' . $bits['path']; -// } -// } else { -// $bits['path'] = ''; -// } -// } -// -// // If the URL was protocol-relative, fix scheme and delimiter -// if ($wasRelative) { -// $bits['scheme'] = ''; -// $bits['delimiter'] = '//'; -// } -// return $bits; // } // -// /** -// * Take a URL, make sure it's expanded to fully qualified, and replace any -// * encoded non-ASCII Unicode characters with their UTF-8 original forms -// * for more compact display and legibility for local audiences. -// * -// * @todo handle punycode domains too -// * -// * @param String $url -// * @return String -// */ -// function wfExpandIRI($url) { -// return preg_replace_callback( -// '/((?:%[89A-F][0-9A-F])+)/i', -// 'wfExpandIRI_callback', -// wfExpandUrl($url) +// // If the URL was protocol-relative, fix scheme and delimiter +// if ($wasRelative) { +// $bits['scheme'] = ''; +// $bits['delimiter'] = '//'; +// } +// return $bits; +// } +// +// /** +// * Take a URL, make sure it's expanded to fully qualified, and replace any +// * encoded non-ASCII Unicode characters with their UTF-8 original forms +// * for more compact display and legibility for local audiences. +// * +// * @todo handle punycode domains too +// * +// * @param string $url +// * @return string +// */ +// function wfExpandIRI($url) { +// return preg_replace_callback( +// '/((?:%[89A-F][0-9A-F])+)/i', +// function (array $matches) { +// return urldecode($matches[1]); +// }, +// wfExpandUrl($url) +// ); +// } +// +// /** +// * Make URL indexes, appropriate for the el_index field of externallinks. +// * +// * @deprecated since 1.33, use LinkFilter::makeIndexes() instead +// * @param string $url +// * @return array +// */ +// function wfMakeUrlIndexes($url) { +// wfDeprecated(__FUNCTION__, '1.33'); +// return LinkFilter::makeIndexes($url); +// } +// +// /** +// * Check whether a given URL has a domain that occurs in a given set of domains +// * @param string $url +// * @param array $domains Array of domains (strings) +// * @return bool True if the host part of $url ends in one of the strings in $domains +// */ +// function wfMatchesDomainList($url, $domains) { +// $bits = wfParseUrl($url); +// if (is_array($bits) && isset($bits['host'])) { +// $host = '.' . $bits['host']; +// foreach ((array)$domains as $domain) { +// $domain = '.' . $domain; +// if (substr($host, -strlen($domain)) === $domain) { +// return true; +// } +// } +// } +// return false; +// } +// +// /** +// * Sends a line to the debug log if enabled or, optionally, to a comment in output. +// * In normal operation this is a NOP. +// * +// * Controlling globals: +// * $wgDebugLogFile - points to the log file +// * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output. +// * $wgDebugComments - if on, some debug items may appear in comments in the HTML output. +// * +// * @since 1.25 support for additional context data +// * +// * @param string $text +// * @param string|bool $dest Destination of the message: +// * - 'all': both to the log and HTML (debug toolbar or HTML comments) +// * - 'private': excluded from HTML output +// * For backward compatibility, it can also take a boolean: +// * - true: same as 'all' +// * - false: same as 'private' +// * @param array $context Additional logging context data +// */ +// function wfDebug($text, $dest = 'all', array $context = []) { +// global $wgDebugRawPage, $wgDebugLogPrefix; +// global $wgDebugTimestamps; +// +// if (!$wgDebugRawPage && wfIsDebugRawPage()) { +// return; +// } +// +// $text = trim($text); +// +// if ($wgDebugTimestamps) { +// $context['seconds_elapsed'] = sprintf( +// '%6.4f', +// microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'] +// ); +// $context['memory_used'] = sprintf( +// '%5.1fM', +// (memory_get_usage(true) / (1024 * 1024)) // ); // } // -// /** -// * Private callback for wfExpandIRI -// * @param array $matches -// * @return String -// */ -// function wfExpandIRI_callback($matches) { -// return urldecode($matches[1]); +// if ($wgDebugLogPrefix !== '') { +// $context['prefix'] = $wgDebugLogPrefix; // } +// $context['private'] = ($dest === false || $dest === 'private'); // -// /** -// * Make URL indexes, appropriate for the el_index field of externallinks. -// * -// * @param String $url -// * @return array -// */ -// function wfMakeUrlIndexes($url) { -// $bits = wfParseUrl($url); +// $logger = LoggerFactory::getInstance('wfDebug'); +// $logger.debug($text, $context); +// } // -// // Reverse the labels in the hostname, convert to lower case -// // For emails reverse domainpart only -// if ($bits['scheme'] == 'mailto') { -// $mailparts = explode('@', $bits['host'], 2); -// if (count($mailparts) === 2) { -// $domainpart = strtolower(implode('.', array_reverse(explode('.', $mailparts[1])))); -// } else { -// // No domain specified, don't mangle it -// $domainpart = ''; -// } -// $reversedHost = $domainpart . '@' . $mailparts[0]; -// } else { -// $reversedHost = strtolower(implode('.', array_reverse(explode('.', $bits['host'])))); -// } -// // Add an extra dot to the end -// // Why? Is it in wrong place in mailto links? -// if (substr($reversedHost, -1, 1) !== '.') { -// $reversedHost .= '.'; -// } -// // Reconstruct the pseudo-URL -// $prot = $bits['scheme']; -// $index = $prot . $bits['delimiter'] . $reversedHost; -// // Leave out user and password. Add the port, path, query and fragment -// if (isset($bits['port'])) { -// $index .= ':' . $bits['port']; -// } -// if (isset($bits['path'])) { -// $index .= $bits['path']; -// } else { -// $index .= '/'; -// } -// if (isset($bits['query'])) { -// $index .= '?' . $bits['query']; -// } -// if (isset($bits['fragment'])) { -// $index .= '#' . $bits['fragment']; -// } -// -// if ($prot == '') { -// return [ "http:$index", "https:$index" ]; -// } else { -// return [ $index ]; -// } -// } -// -// /** -// * Check whether a given URL has a domain that occurs in a given set of domains -// * @param String $url URL -// * @param array $domains Array of domains (strings) -// * @return boolean True if the host part of $url ends in one of the strings in $domains -// */ -// function wfMatchesDomainList($url, $domains) { -// $bits = wfParseUrl($url); -// if (is_array($bits) && isset($bits['host'])) { -// $host = '.' . $bits['host']; -// foreach ((array)$domains as $domain) { -// $domain = '.' . $domain; -// if (substr($host, -strlen($domain)) === $domain) { -// return true; -// } -// } -// } -// return false; -// } -// -// /** -// * Sends a line to the debug log if enabled or, optionally, to a comment in output. -// * In normal operation this is a NOP. -// * -// * Controlling globals: -// * $wgDebugLogFile - points to the log file -// * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output. -// * $wgDebugComments - if on, some debug items may appear in comments in the HTML output. -// * -// * @since 1.25 support for additional context data -// * -// * @param String $text -// * @param String|boolean $dest Destination of the message: -// * - 'all': both to the log and HTML (debug toolbar or HTML comments) -// * - 'private': excluded from HTML output -// * For backward compatibility, it can also take a boolean: -// * - true: same as 'all' -// * - false: same as 'private' -// * @param array $context Additional logging context data -// */ -// function wfDebug($text, $dest = 'all', array $context = []) { -// global $wgDebugRawPage, $wgDebugLogPrefix; -// global $wgDebugTimestamps, $wgRequestTime; -// -// if (!$wgDebugRawPage && wfIsDebugRawPage()) { -// return; -// } -// -// $text = trim($text); -// -// if ($wgDebugTimestamps) { -// $context['seconds_elapsed'] = sprintf( -// '%6.4f', -// microtime(true) - $wgRequestTime -// ); -// $context['memory_used'] = sprintf( -// '%5.1fM', -// (memory_get_usage(true) / (1024 * 1024)) -// ); -// } -// -// if ($wgDebugLogPrefix !== '') { -// $context['prefix'] = $wgDebugLogPrefix; -// } -// $context['private'] = ($dest === false || $dest === 'private'); -// -// $logger = LoggerFactory::getInstance('wfDebug'); -// $logger->debug($text, $context); -// } -// -// /** -// * Returns true if debug logging should be suppressed if $wgDebugRawPage = false -// * @return boolean -// */ -// function wfIsDebugRawPage() { -// static $cache; -// if ($cache !== null) { -// return $cache; -// } -// # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet -// if ((isset($_GET['action']) && $_GET['action'] == 'raw') -// || ( -// isset($_SERVER['SCRIPT_NAME']) -// && substr($_SERVER['SCRIPT_NAME'], -8) == 'load.php' -// ) -// ) { -// $cache = true; -// } else { -// $cache = false; -// } +// /** +// * Returns true if debug logging should be suppressed if $wgDebugRawPage = false +// * @return bool +// */ +// function wfIsDebugRawPage() { +// static $cache; +// if ($cache !== null) { // return $cache; // } -// -// /** -// * Send a line giving PHP memory usage. -// * -// * @param boolean $exact Print exact byte values instead of kibibytes (default: false) -// */ -// function wfDebugMem($exact = false) { -// $mem = memory_get_usage(); -// if (!$exact) { -// $mem = floor($mem / 1024) . ' KiB'; -// } else { -// $mem .= ' B'; -// } -// wfDebug("Memory usage: $mem\n"); -// } -// -// /** -// * Send a line to a supplementary debug log file, if configured, or main debug -// * log if not. -// * -// * To configure a supplementary log file, set $wgDebugLogGroups[$logGroup] to -// * a String filename or an associative array mapping 'destination' to the -// * desired filename. The associative array may also contain a 'sample' key -// * with an integer value, specifying a sampling factor. Sampled log events -// * will be emitted with a 1 in N random chance. -// * -// * @since 1.23 support for sampling log messages via $wgDebugLogGroups. -// * @since 1.25 support for additional context data -// * @since 1.25 sample behavior dependent on configured $wgMWLoggerDefaultSpi -// * -// * @param String $logGroup -// * @param String $text -// * @param String|boolean $dest Destination of the message: -// * - 'all': both to the log and HTML (debug toolbar or HTML comments) -// * - 'private': only to the specific log if set in $wgDebugLogGroups and -// * discarded otherwise -// * For backward compatibility, it can also take a boolean: -// * - true: same as 'all' -// * - false: same as 'private' -// * @param array $context Additional logging context data -// */ -// function wfDebugLog( -// $logGroup, $text, $dest = 'all', array $context = [] +// // Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet +// // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals +// if ((isset($_GET['action']) && $_GET['action'] == 'raw') +// || ( +// isset($_SERVER['SCRIPT_NAME']) +// && substr($_SERVER['SCRIPT_NAME'], -8) == 'load.php' +// ) // ) { -// $text = trim($text); +// $cache = true; +// } else { +// $cache = false; +// } +// return $cache; +// } // -// $logger = LoggerFactory::getInstance($logGroup); -// $context['private'] = ($dest === false || $dest === 'private'); -// $logger->info($text, $context); +// /** +// * Send a line giving PHP memory usage. +// * +// * @param bool $exact Print exact byte values instead of kibibytes (default: false) +// */ +// function wfDebugMem($exact = false) { +// $mem = memory_get_usage(); +// if (!$exact) { +// $mem = floor($mem / 1024) . ' KiB'; +// } else { +// $mem .= ' B'; +// } +// wfDebug("Memory usage: $mem\n"); +// } +// +// /** +// * Send a line to a supplementary debug log file, if configured, or main debug +// * log if not. +// * +// * To configure a supplementary log file, set $wgDebugLogGroups[$logGroup] to +// * a string filename or an associative array mapping 'destination' to the +// * desired filename. The associative array may also contain a 'sample' key +// * with an integer value, specifying a sampling factor. Sampled log events +// * will be emitted with a 1 in N random chance. +// * +// * @since 1.23 support for sampling log messages via $wgDebugLogGroups. +// * @since 1.25 support for additional context data +// * @since 1.25 sample behavior dependent on configured $wgMWLoggerDefaultSpi +// * +// * @param string $logGroup +// * @param string $text +// * @param string|bool $dest Destination of the message: +// * - 'all': both to the log and HTML (debug toolbar or HTML comments) +// * - 'private': only to the specific log if set in $wgDebugLogGroups and +// * discarded otherwise +// * For backward compatibility, it can also take a boolean: +// * - true: same as 'all' +// * - false: same as 'private' +// * @param array $context Additional logging context data +// */ +// function wfDebugLog( +// $logGroup, $text, $dest = 'all', array $context = [] +// ) { +// $text = trim($text); +// +// $logger = LoggerFactory::getInstance($logGroup); +// $context['private'] = ($dest === false || $dest === 'private'); +// $logger.info($text, $context); +// } +// +// /** +// * Log for database errors +// * +// * @since 1.25 support for additional context data +// * +// * @param string $text Database error message. +// * @param array $context Additional logging context data +// */ +// function wfLogDBError($text, array $context = []) { +// $logger = LoggerFactory::getInstance('wfLogDBError'); +// $logger.error(trim($text), $context); +// } +// +// /** +// * Throws a warning that $function is deprecated +// * +// * @param string $function Function that is deprecated. +// * @param string|bool $version Version of MediaWiki that the function +// * was deprecated in (Added in 1.19). +// * @param string|bool $component Component to which the function belongs. +// * If false, it is assumed the function is in MediaWiki core (Added in 1.19). +// * @param int $callerOffset How far up the call stack is the original +// * caller. 2 = function that called the function that called +// * wfDeprecated (Added in 1.20). +// */ +// function wfDeprecated($function, $version = false, $component = false, $callerOffset = 2) { +// MWDebug::deprecated($function, $version, $component, $callerOffset + 1); +// } +// +// /** +// * Send a warning either to the debug log or in a PHP error depending on +// * $wgDevelopmentWarnings. To log warnings in production, use wfLogWarning() instead. +// * +// * @param string $msg Message to send +// * @param int $callerOffset Number of items to go back in the backtrace to +// * find the correct caller (1 = function calling wfWarn, ...) +// * @param int $level PHP error level; defaults to E_USER_NOTICE; +// * only used when $wgDevelopmentWarnings is true +// */ +// function wfWarn($msg, $callerOffset = 1, $level = E_USER_NOTICE) { +// MWDebug::warning($msg, $callerOffset + 1, $level, 'auto'); +// } +// +// /** +// * Send a warning as a PHP error and the debug log. This is intended for logging +// * warnings in production. For logging development warnings, use WfWarn instead. +// * +// * @param string $msg Message to send +// * @param int $callerOffset Number of items to go back in the backtrace to +// * find the correct caller (1 = function calling wfLogWarning, ...) +// * @param int $level PHP error level; defaults to E_USER_WARNING +// */ +// function wfLogWarning($msg, $callerOffset = 1, $level = E_USER_WARNING) { +// MWDebug::warning($msg, $callerOffset + 1, $level, 'production'); +// } +// +// /** +// * @todo document +// * @todo Move logic to MediaWiki.php +// */ +// function wfLogProfilingData() { +// global $wgDebugLogGroups, $wgDebugRawPage; +// +// $context = RequestContext::getMain(); +// $request = $context.getRequest(); +// +// $profiler = Profiler::instance(); +// $profiler.setContext($context); +// $profiler.logData(); +// +// // Send out any buffered statsd metrics as needed +// MediaWiki::emitBufferedStatsdData( +// MediaWikiServices::getInstance().getStatsdDataFactory(), +// $context.getConfig() +// ); +// +// // Profiling must actually be enabled... +// if ($profiler instanceof ProfilerStub) { +// return; // } // -// /** -// * Log for database errors -// * -// * @since 1.25 support for additional context data -// * -// * @param String $text Database error message. -// * @param array $context Additional logging context data -// */ -// function wfLogDBError($text, array $context = []) { -// $logger = LoggerFactory::getInstance('wfLogDBError'); -// $logger->error(trim($text), $context); +// if (isset($wgDebugLogGroups['profileoutput']) +// && $wgDebugLogGroups['profileoutput'] === false +// ) { +// // Explicitly disabled +// return; +// } +// if (!$wgDebugRawPage && wfIsDebugRawPage()) { +// return; // } // -// /** -// * Throws a warning that $function is deprecated -// * -// * @param String $function -// * @param String|boolean $version Version of MediaWiki that the function -// * was deprecated in (Added in 1.19). -// * @param String|boolean $component Added in 1.19. -// * @param int $callerOffset How far up the call stack is the original -// * caller. 2 = function that called the function that called -// * wfDeprecated (Added in 1.20) -// * -// * @return null -// */ -// function wfDeprecated($function, $version = false, $component = false, $callerOffset = 2) { -// MWDebug::deprecated($function, $version, $component, $callerOffset + 1); +// $ctx = [ 'elapsed' => $request.getElapsedTime() ]; +// if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { +// $ctx['forwarded_for'] = $_SERVER['HTTP_X_FORWARDED_FOR']; +// } +// if (!empty($_SERVER['HTTP_CLIENT_IP'])) { +// $ctx['client_ip'] = $_SERVER['HTTP_CLIENT_IP']; +// } +// if (!empty($_SERVER['HTTP_FROM'])) { +// $ctx['from'] = $_SERVER['HTTP_FROM']; +// } +// if (isset($ctx['forwarded_for']) || +// isset($ctx['client_ip']) || +// isset($ctx['from'])) { +// $ctx['proxy'] = $_SERVER['REMOTE_ADDR']; // } // -// /** -// * Send a warning either to the debug log or in a PHP error depending on -// * $wgDevelopmentWarnings. To log warnings in production, use wfLogWarning() instead. -// * -// * @param String $msg Message to send -// * @param int $callerOffset Number of items to go back in the backtrace to -// * find the correct caller (1 = function calling wfWarn, ...) -// * @param int $level PHP error level; defaults to E_USER_NOTICE; -// * only used when $wgDevelopmentWarnings is true -// */ -// function wfWarn($msg, $callerOffset = 1, $level = E_USER_NOTICE) { -// MWDebug::warning($msg, $callerOffset + 1, $level, 'auto'); +// // Don't load $wgUser at this late stage just for statistics purposes +// // @todo FIXME: We can detect some anons even if it is not loaded. +// // See User::getId() +// $user = $context.getUser(); +// $ctx['anon'] = $user.isItemLoaded('id') && $user.isAnon(); +// +// // Command line script uses a FauxRequest object which does not have +// // any knowledge about an URL and throw an exception instead. +// try { +// $ctx['url'] = urldecode($request.getRequestURL()); +// } catch (Exception $ignored) { +// // no-op // } // -// /** -// * Send a warning as a PHP error and the debug log. This is intended for logging -// * warnings in production. For logging development warnings, use WfWarn instead. -// * -// * @param String $msg Message to send -// * @param int $callerOffset Number of items to go back in the backtrace to -// * find the correct caller (1 = function calling wfLogWarning, ...) -// * @param int $level PHP error level; defaults to E_USER_WARNING -// */ -// function wfLogWarning($msg, $callerOffset = 1, $level = E_USER_WARNING) { -// MWDebug::warning($msg, $callerOffset + 1, $level, 'production'); +// $ctx['output'] = $profiler.getOutput(); +// +// $log = LoggerFactory::getInstance('profileoutput'); +// $log.info("Elapsed: {elapsed}; URL: <{url}>\n{output}", $ctx); +// } +// +// /** +// * Increment a statistics counter +// * +// * @param string $key +// * @param int $count +// * @return void +// */ +// function wfIncrStats($key, $count = 1) { +// $stats = MediaWikiServices::getInstance().getStatsdDataFactory(); +// $stats.updateCount($key, $count); +// } +// +// /** +// * Check whether the wiki is in read-only mode. +// * +// * @return bool +// */ +// function wfReadOnly() { +// return MediaWikiServices::getInstance().getReadOnlyMode() +// .isReadOnly(); +// } +// +// /** +// * Check if the site is in read-only mode and return the message if so +// * +// * This checks wfConfiguredReadOnlyReason() and the main load balancer +// * for replica DB lag. This may result in DB connection being made. +// * +// * @return string|bool String when in read-only mode; false otherwise +// */ +// function wfReadOnlyReason() { +// return MediaWikiServices::getInstance().getReadOnlyMode() +// .getReason(); +// } +// +// /** +// * Get the value of $wgReadOnly or the contents of $wgReadOnlyFile. +// * +// * @return string|bool String when in read-only mode; false otherwise +// * @since 1.27 +// */ +// function wfConfiguredReadOnlyReason() { +// return MediaWikiServices::getInstance().getConfiguredReadOnlyMode() +// .getReason(); +// } +// +// /** +// * Return a Language object from $langcode +// * +// * @param Language|string|bool $langcode Either: +// * - a Language object +// * - code of the language to get the message for, if it is +// * a valid code create a language for that language, if +// * it is a string but not a valid code then make a basic +// * language object +// * - a boolean: if it's false then use the global object for +// * the current user's language (as a fallback for the old parameter +// * functionality), or if it is true then use global object +// * for the wiki's content language. +// * @return Language +// */ +// function wfGetLangObj($langcode = false) { +// # Identify which language to get or create a language object for. +// # Using is_object here due to Stub objects. +// if (is_object($langcode)) { +// # Great, we already have the object (hopefully)! +// return $langcode; // } // -// /** -// * Log to a file without getting "file size exceeded" signals. -// * -// * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will -// * send lines to the specified port, prefixed by the specified prefix and a space. -// * @since 1.25 support for additional context data -// * -// * @param String $text -// * @param String $file Filename -// * @param array $context Additional logging context data -// * @throws MWException -// * @deprecated since 1.25 Use \MediaWiki\Logger\LegacyLogger::emit or UDPTransport -// */ -// function wfErrorLog($text, $file, array $context = []) { -// wfDeprecated(__METHOD__, '1.25'); -// $logger = LoggerFactory::getInstance('wfErrorLog'); -// $context['destination'] = $file; -// $logger->info(trim($text), $context); +// global $wgLanguageCode; +// if ($langcode === true || $langcode === $wgLanguageCode) { +// # $langcode is the language code of the wikis content language object. +// # or it is a boolean and value is true +// return MediaWikiServices::getInstance().getContentLanguage(); // } // -// /** -// * @todo document -// */ -// function wfLogProfilingData() { -// global $wgDebugLogGroups, $wgDebugRawPage; -// -// $context = RequestContext::getMain(); -// $request = $context->getRequest(); -// -// $profiler = Profiler::instance(); -// $profiler->setContext($context); -// $profiler->logData(); -// -// $config = $context->getConfig(); -// if ($config->get('StatsdServer')) { -// try { -// $statsdServer = explode(':', $config->get('StatsdServer')); -// $statsdHost = $statsdServer[0]; -// $statsdPort = isset($statsdServer[1]) ? $statsdServer[1] : 8125; -// $statsdSender = new SocketSender($statsdHost, $statsdPort); -// $statsdClient = new SamplingStatsdClient($statsdSender, true, false); -// $statsdClient->setSamplingRates($config->get('StatsdSamplingRates')); -// $statsdClient->send($context->getStats()->getBuffer()); -// } catch (Exception $ex) { -// MWExceptionHandler::logException($ex); -// } -// } -// -// # Profiling must actually be enabled... -// if ($profiler instanceof ProfilerStub) { -// return; -// } -// -// if (isset($wgDebugLogGroups['profileoutput']) -// && $wgDebugLogGroups['profileoutput'] === false -// ) { -// // Explicitly disabled -// return; -// } -// if (!$wgDebugRawPage && wfIsDebugRawPage()) { -// return; -// } -// -// $ctx = [ 'elapsed' => $request->getElapsedTime() ]; -// if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { -// $ctx['forwarded_for'] = $_SERVER['HTTP_X_FORWARDED_FOR']; -// } -// if (!empty($_SERVER['HTTP_CLIENT_IP'])) { -// $ctx['client_ip'] = $_SERVER['HTTP_CLIENT_IP']; -// } -// if (!empty($_SERVER['HTTP_FROM'])) { -// $ctx['from'] = $_SERVER['HTTP_FROM']; -// } -// if (isset($ctx['forwarded_for']) || -// isset($ctx['client_ip']) || -// isset($ctx['from'])) { -// $ctx['proxy'] = $_SERVER['REMOTE_ADDR']; -// } -// -// // Don't load $wgUser at this late stage just for statistics purposes -// // @todo FIXME: We can detect some anons even if it is not loaded. -// // See User::getId() -// $user = $context->getUser(); -// $ctx['anon'] = $user->isItemLoaded('id') && $user->isAnon(); -// -// // Command line script uses a FauxRequest Object which does not have -// // any knowledge about an URL and throw an exception instead. -// try { -// $ctx['url'] = urldecode($request->getRequestURL()); -// } catch (Exception $ignored) { -// // no-op -// } -// -// $ctx['output'] = $profiler->getOutput(); -// -// $log = LoggerFactory::getInstance('profileoutput'); -// $log->info("Elapsed: {elapsed}; URL: <{url}>\n{output}", $ctx); +// global $wgLang; +// if ($langcode === false || $langcode === $wgLang.getCode()) { +// # $langcode is the language code of user language object. +// # or it was a boolean and value is false +// return $wgLang; // } // -// /** -// * Increment a statistics counter -// * -// * @param String $key -// * @param int $count -// * @return void -// */ -// function wfIncrStats($key, $count = 1) { -// $stats = RequestContext::getMain()->getStats(); -// $stats->updateCount($key, $count); +// $validCodes = array_keys(Language::fetchLanguageNames()); +// if (in_array($langcode, $validCodes)) { +// # $langcode corresponds to a valid language. +// return Language::factory($langcode); // } // -// /** -// * Check whether the wiki is in read-only mode. -// * -// * @return boolean -// */ -// function wfReadOnly() { -// return wfReadOnlyReason() !== false; -// } -// -// /** -// * Check if the site is in read-only mode and return the message if so -// * -// * This checks wfConfiguredReadOnlyReason() and the main load balancer -// * for replica DB lag. This may result in DB connection being made. -// * -// * @return String|boolean String when in read-only mode; false otherwise -// */ -// function wfReadOnlyReason() { -// $readOnly = wfConfiguredReadOnlyReason(); -// if ($readOnly !== false) { -// return $readOnly; -// } -// -// static $lbReadOnly = null; -// if ($lbReadOnly === null) { -// // Callers use this method to be aware that data presented to a user -// // may be very stale and thus allowing submissions can be problematic. -// $lbReadOnly = wfGetLB()->getReadOnlyReason(); -// } -// -// return $lbReadOnly; -// } -// -// /** -// * Get the value of $wgReadOnly or the contents of $wgReadOnlyFile. -// * -// * @return String|boolean String when in read-only mode; false otherwise -// * @since 1.27 -// */ -// function wfConfiguredReadOnlyReason() { -// global $wgReadOnly, $wgReadOnlyFile; -// -// if ($wgReadOnly === null) { -// // Set $wgReadOnly for faster access next time -// if (is_file($wgReadOnlyFile) && filesize($wgReadOnlyFile) > 0) { -// $wgReadOnly = file_get_contents($wgReadOnlyFile); -// } else { -// $wgReadOnly = false; -// } -// } -// -// return $wgReadOnly; -// } -// -// /** -// * Return a Language Object from $langcode -// * -// * @param Language|String|boolean $langcode Either: -// * - a Language Object -// * - code of the language to get the message for, if it is -// * a valid code create a language for that language, if -// * it is a String but not a valid code then make a basic -// * language Object -// * - a boolean: if it's false then use the global Object for -// * the current user's language (as a fallback for the old parameter -// * functionality), or if it is true then use global Object -// * for the wiki's content language. -// * @return Language -// */ -// function wfGetLangObj($langcode = false) { -// # Identify which language to get or create a language Object for. -// # Using is_object here due to Stub objects. -// if (is_object($langcode)) { -// # Great, we already have the Object (hopefully)! -// return $langcode; -// } -// -// global $wgContLang, $wgLanguageCode; -// if ($langcode === true || $langcode === $wgLanguageCode) { -// # $langcode is the language code of the wikis content language Object. -// # or it is a boolean and value is true -// return $wgContLang; -// } -// -// global $wgLang; -// if ($langcode === false || $langcode === $wgLang->getCode()) { -// # $langcode is the language code of user language Object. -// # or it was a boolean and value is false -// return $wgLang; -// } -// -// $validCodes = array_keys(Language::fetchLanguageNames()); -// if (in_array($langcode, $validCodes)) { -// # $langcode corresponds to a valid language. -// return Language::factory($langcode); -// } -// -// # $langcode is a String, but not a valid language code; use content language. +// # $langcode is a string, but not a valid language code; use content language. // wfDebug("Invalid language code passed to wfGetLangObj, falling back to content language.\n"); -// return $wgContLang; -// } +// return MediaWikiServices::getInstance().getContentLanguage(); +// } /** - * This is the function for getting translated interface messages. - * - * @see Message class for documentation how to use them. - * @see https://www.mediawiki.org/wiki/Manual:Messages_API - * - * This function replaces all old wfMsg* functions. - * - * @param String|String[]|MessageSpecifier $key Message key, or array of keys, or a MessageSpecifier - * @param mixed $... Normal message parameters - * @return Message - * - * @since 1.17 - * - * @see Message::__construct - */ - public static XomwMessage wfMessage(XomwEnv env, String key) { -// function wfMessage($key /*...*/) { -// $message = new Message($key); - -// // We call Message::params() to reduce code duplication -// $params = func_get_args(); -// array_shift($params); -// if ($params) { -// call_user_func_array([ $message, 'params' ], $params); -// } - + * This is the function for getting translated interface messages. + * + * @see Message class for documentation how to use them. + * @see https://www.mediawiki.org/wiki/Manual:Messages_API + * + * This function replaces all old wfMsg* functions. + * + * @param string|string[]|MessageSpecifier $key Message key, or array of keys, or a MessageSpecifier + * @param string|string[] ...$params Normal message parameters + * @return Message + * + * @since 1.17 + * + * @see Message::__construct + */ + public static XomwMessage wfMessage(XomwEnv env, String key, String... params) { +// $message = new Message($key); +// +// // We call Message::params() to reduce code duplication +// if ($params) { +// $message.params(...$params); +// } +// +// return $message; return env.Message_mgr().Get_by_str(key); } + +// /** +// * This function accepts multiple message keys and returns a message instance +// * for the first message which is non-empty. If all messages are empty then an +// * instance of the first message key is returned. +// * +// * @param string ...$keys Message keys +// * @return Message +// * +// * @since 1.18 +// * +// * @see Message::newFallbackSequence +// */ +// function wfMessageFallback(...$keys) { +// return Message::newFallbackSequence(...$keys); +// } // -// /** -// * This function accepts multiple message keys and returns a message instance -// * for the first message which is non-empty. If all messages are empty then an -// * instance of the first message key is returned. -// * -// * @param String|String... $keys,... Message keys -// * @return Message -// * -// * @since 1.18 -// * -// * @see Message::newFallbackSequence -// */ -// function wfMessageFallback(/*...*/) { -// $args = func_get_args(); -// return call_user_func_array('Message::newFallbackSequence', $args); +// /** +// * Replace message parameter keys on the given formatted output. +// * +// * @param string $message +// * @param array $args +// * @return string +// * @private +// */ +// function wfMsgReplaceArgs($message, $args) { +// # Fix windows line-endings +// # Some messages are split with explode("\n", $msg) +// $message = str_replace("\r", '', $message); +// +// // Replace arguments +// if (is_array($args) && $args) { +// if (is_array($args[0])) { +// $args = array_values($args[0]); +// } +// $replacementKeys = []; +// foreach ($args as $n => $param) { +// $replacementKeys['$' . ($n + 1)] = $param; +// } +// $message = strtr($message, $replacementKeys); // } // -// /** -// * Replace message parameter keys on the given formatted output. -// * -// * @param String $message -// * @param array $args -// * @return String -// * @private -// */ -// function wfMsgReplaceArgs($message, $args) { -// # Fix windows line-endings -// # Some messages are split with explode("\n", $msg) -// $message = str_replace("\r", '', $message); +// return $message; +// } // -// // Replace arguments -// if (is_array($args) && $args) { -// if (is_array($args[0])) { -// $args = array_values($args[0]); -// } -// $replacementKeys = []; -// foreach ($args as $n => $param) { -// $replacementKeys['$' . ($n + 1)] = $param; -// } -// $message = strtr($message, $replacementKeys); +// /** +// * Fetch server name for use in error reporting etc. +// * Use real server name if available, so we know which machine +// * in a server farm generated the current page. +// * +// * @return string +// */ +// function wfHostname() { +// static $host; +// if (is_null($host)) { +// # Hostname overriding +// global $wgOverrideHostname; +// if ($wgOverrideHostname !== false) { +// # Set static and skip any detection +// $host = $wgOverrideHostname; +// return $host; // } // -// return $message; -// } -// -// /** -// * Fetch server name for use in error reporting etc. -// * Use real server name if available, so we know which machine -// * in a server farm generated the current page. -// * -// * @return String -// */ -// function wfHostname() { -// static $host; -// if (is_null($host)) { -// -// # Hostname overriding -// global $wgOverrideHostname; -// if ($wgOverrideHostname !== false) { -// # Set static and skip any detection -// $host = $wgOverrideHostname; -// return $host; -// } -// -// if (function_exists('posix_uname')) { -// // This function not present on Windows -// $uname = posix_uname(); -// } else { -// $uname = false; -// } -// if (is_array($uname) && isset($uname['nodename'])) { -// $host = $uname['nodename']; -// } elseif (getenv('COMPUTERNAME')) { -// # Windows computer name +// if (function_exists('posix_uname')) { +// // This function not present on Windows +// $uname = posix_uname(); +// } else { +// $uname = false; +// } +// if (is_array($uname) && isset($uname['nodename'])) { +// $host = $uname['nodename']; +// } elseif (getenv('COMPUTERNAME')) { +// # Windows computer name // $host = getenv('COMPUTERNAME'); -// } else { -// # This may be a virtual server. -// $host = $_SERVER['SERVER_NAME']; -// } +// } else { +// # This may be a virtual server. +// $host = $_SERVER['SERVER_NAME']; // } -// return $host; // } +// return $host; +// } // -// /** -// * Returns a script tag that stores the amount of time it took MediaWiki to -// * handle the request in milliseconds as 'wgBackendResponseTime'. -// * -// * If $wgShowHostnames is true, the script will also set 'wgHostname' to the -// * hostname of the server handling the request. -// * -// * @return String -// */ -// function wfReportTime() { -// global $wgRequestTime, $wgShowHostnames; +// /** +// * Returns a script tag that stores the amount of time it took MediaWiki to +// * handle the request in milliseconds as 'wgBackendResponseTime'. +// * +// * If $wgShowHostnames is true, the script will also set 'wgHostname' to the +// * hostname of the server handling the request. +// * +// * @param string|null $nonce Value from OutputPage::getCSPNonce +// * @return string|WrappedString HTML +// */ +// function wfReportTime($nonce = null) { +// global $wgShowHostnames; // -// $responseTime = round((microtime(true) - $wgRequestTime) * 1000); -// $reportVars = [ 'wgBackendResponseTime' => $responseTime ]; -// if ($wgShowHostnames) { -// $reportVars['wgHostname'] = wfHostname(); -// } -// return Skin::makeVariablesScript($reportVars); +// $elapsed = (microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']); +// // seconds to milliseconds +// $responseTime = round($elapsed * 1000); +// $reportVars = [ 'wgBackendResponseTime' => $responseTime ]; +// if ($wgShowHostnames) { +// $reportVars['wgHostname'] = wfHostname(); // } +// return Skin::makeVariablesScript($reportVars, $nonce); +// } // -// /** -// * Safety wrapper for debug_backtrace(). -// * -// * Will return an empty array if debug_backtrace is disabled, otherwise -// * the output from debug_backtrace() (trimmed). -// * -// * @param int $limit This parameter can be used to limit the number of stack frames returned -// * -// * @return array Array of backtrace information -// */ -// function wfDebugBacktrace($limit = 0) { -// static $disabled = null; +// /** +// * Safety wrapper for debug_backtrace(). +// * +// * Will return an empty array if debug_backtrace is disabled, otherwise +// * the output from debug_backtrace() (trimmed). +// * +// * @param int $limit This parameter can be used to limit the number of stack frames returned +// * +// * @return array Array of backtrace information +// */ +// function wfDebugBacktrace($limit = 0) { +// static $disabled = null; // -// if (is_null($disabled)) { -// $disabled = !function_exists('debug_backtrace'); -// if ($disabled) { -// wfDebug("debug_backtrace() is disabled\n"); -// } -// } +// if (is_null($disabled)) { +// $disabled = !function_exists('debug_backtrace'); // if ($disabled) { -// return []; -// } -// -// if ($limit) { -// return array_slice(debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1), 1); -// } else { -// return array_slice(debug_backtrace(), 1); +// wfDebug("debug_backtrace() is disabled\n"); // } // } -// -// /** -// * Get a debug backtrace as a String -// * -// * @param boolean|null $raw If true, the return value is plain text. If false, HTML. -// * Defaults to $wgCommandLineMode if unset. -// * @return String -// * @since 1.25 Supports $raw parameter. -// */ -// function wfBacktrace($raw = null) { -// global $wgCommandLineMode; -// -// if ($raw === null) { -// $raw = $wgCommandLineMode; -// } -// -// if ($raw) { -// $frameFormat = "%s line %s calls %s()\n"; -// $traceFormat = "%s"; -// } else { -// $frameFormat = "
  • %s line %s calls %s()
  • \n"; -// $traceFormat = "\n"; -// } -// -// $frames = array_map(function ($frame) use ($frameFormat) { -// $file = !empty($frame['file']) ? basename($frame['file']) : '-'; -// $line = isset($frame['line']) ? $frame['line'] : '-'; -// $call = $frame['function']; -// if (!empty($frame['class'])) { -// $call = $frame['class'] . $frame['type'] . $call; -// } -// return sprintf($frameFormat, $file, $line, $call); -// }, wfDebugBacktrace()); -// -// return sprintf($traceFormat, implode('', $frames)); +// if ($disabled) { +// return []; // } // -// /** -// * Get the name of the function which called this function -// * wfGetCaller(1) is the function with the wfGetCaller() call (ie. __FUNCTION__) -// * wfGetCaller(2) [default] is the caller of the function running wfGetCaller() -// * wfGetCaller(3) is the parent of that. -// * -// * @param int $level -// * @return String -// */ -// function wfGetCaller($level = 2) { -// $backtrace = wfDebugBacktrace($level + 1); -// if (isset($backtrace[$level])) { -// return wfFormatStackFrame($backtrace[$level]); -// } else { -// return 'unknown'; +// if ($limit) { +// return array_slice(debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1), 1); +// } else { +// return array_slice(debug_backtrace(), 1); +// } +// } +// +// /** +// * Get a debug backtrace as a string +// * +// * @param bool|null $raw If true, the return value is plain text. If false, HTML. +// * Defaults to $wgCommandLineMode if unset. +// * @return string +// * @since 1.25 Supports $raw parameter. +// */ +// function wfBacktrace($raw = null) { +// global $wgCommandLineMode; +// +// if ($raw === null) { +// $raw = $wgCommandLineMode; +// } +// +// if ($raw) { +// $frameFormat = "%s line %s calls %s()\n"; +// $traceFormat = "%s"; +// } else { +// $frameFormat = "
  • %s line %s calls %s()
  • \n"; +// $traceFormat = "\n"; +// } +// +// $frames = array_map(function ($frame) use ($frameFormat) { +// $file = !empty($frame['file']) ? basename($frame['file']) : '-'; +// $line = $frame['line'] ?? '-'; +// $call = $frame['function']; +// if (!empty($frame['class'])) { +// $call = $frame['class'] . $frame['type'] . $call; // } +// return sprintf($frameFormat, $file, $line, $call); +// }, wfDebugBacktrace()); +// +// return sprintf($traceFormat, implode('', $frames)); +// } +// +// /** +// * Get the name of the function which called this function +// * wfGetCaller(1) is the function with the wfGetCaller() call (ie. __FUNCTION__) +// * wfGetCaller(2) [default] is the caller of the function running wfGetCaller() +// * wfGetCaller(3) is the parent of that. +// * +// * @param int $level +// * @return string +// */ +// function wfGetCaller($level = 2) { +// $backtrace = wfDebugBacktrace($level + 1); +// if (isset($backtrace[$level])) { +// return wfFormatStackFrame($backtrace[$level]); +// } else { +// return 'unknown'; // } +// } // -// /** -// * Return a String consisting of callers in the stack. Useful sometimes -// * for profiling specific points. -// * -// * @param int $limit The maximum depth of the stack frame to return, or false for the entire stack. -// * @return String -// */ -// function wfGetAllCallers($limit = 3) { -// $trace = array_reverse(wfDebugBacktrace()); -// if (!$limit || $limit > count($trace) - 1) { -// $limit = count($trace) - 1; -// } -// $trace = array_slice($trace, -$limit - 1, $limit); -// return implode('/', array_map('wfFormatStackFrame', $trace)); +// /** +// * Return a string consisting of callers in the stack. Useful sometimes +// * for profiling specific points. +// * +// * @param int $limit The maximum depth of the stack frame to return, or false for the entire stack. +// * @return string +// */ +// function wfGetAllCallers($limit = 3) { +// $trace = array_reverse(wfDebugBacktrace()); +// if (!$limit || $limit > count($trace) - 1) { +// $limit = count($trace) - 1; // } +// $trace = array_slice($trace, -$limit - 1, $limit); +// return implode('/', array_map('wfFormatStackFrame', $trace)); +// } // -// /** -// * Return a String representation of frame -// * -// * @param array $frame -// * @return String -// */ -// function wfFormatStackFrame($frame) { -// if (!isset($frame['function'])) { -// return 'NO_FUNCTION_GIVEN'; -// } -// return isset($frame['class']) && isset($frame['type']) ? -// $frame['class'] . $frame['type'] . $frame['function'] : -// $frame['function']; +// /** +// * Return a string representation of frame +// * +// * @param array $frame +// * @return string +// */ +// function wfFormatStackFrame($frame) { +// if (!isset($frame['function'])) { +// return 'NO_FUNCTION_GIVEN'; // } +// return isset($frame['class']) && isset($frame['type']) ? +// $frame['class'] . $frame['type'] . $frame['function'] : +// $frame['function']; +// } // -// /* Some generic result counters, pulled out of SearchEngine */ +// /* Some generic result counters, pulled out of SearchEngine */ // -// /** -// * @todo document -// * -// * @param int $offset -// * @param int $limit -// * @return String -// */ -// function wfShowingResults($offset, $limit) { -// return wfMessage('showingresults')->numParams($limit, $offset + 1)->parse(); -// } +// /** +// * @todo document +// * +// * @param int $offset +// * @param int $limit +// * @return string +// */ +// function wfShowingResults($offset, $limit) { +// return wfMessage('showingresults').numParams($limit, $offset + 1).parse(); +// } // -// /** -// * Whether the client accept gzip encoding -// * -// * Uses the Accept-Encoding header to check if the client supports gzip encoding. -// * Use this when considering to send a gzip-encoded response to the client. -// * -// * @param boolean $force Forces another check even if we already have a cached result. -// * @return boolean -// */ -// function wfClientAcceptsGzip($force = false) { -// static $result = null; -// if ($result === null || $force) { -// $result = false; -// if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])) { -// # @todo FIXME: We may want to blacklist some broken browsers -// $m = []; -// if (preg_match( -// '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/', -// $_SERVER['HTTP_ACCEPT_ENCODING'], -// $m -// ) -// ) { -// if (isset($m[2]) && ($m[1] == 'q') && ($m[2] == 0)) { -// $result = false; -// return $result; -// } -// wfDebug("wfClientAcceptsGzip: client accepts gzip.\n"); -// $result = true; +// /** +// * Whether the client accept gzip encoding +// * +// * Uses the Accept-Encoding header to check if the client supports gzip encoding. +// * Use this when considering to send a gzip-encoded response to the client. +// * +// * @param bool $force Forces another check even if we already have a cached result. +// * @return bool +// */ +// function wfClientAcceptsGzip($force = false) { +// static $result = null; +// if ($result === null || $force) { +// $result = false; +// if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])) { +// # @todo FIXME: We may want to blacklist some broken browsers +// $m = []; +// if (preg_match( +// '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/', +// $_SERVER['HTTP_ACCEPT_ENCODING'], +// $m +// ) +// ) { +// if (isset($m[2]) && ($m[1] == 'q') && ($m[2] == 0)) { +// $result = false; +// return $result; // } +// wfDebug("wfClientAcceptsGzip: client accepts gzip.\n"); +// $result = true; // } // } -// return $result; // } +// return $result; +// } // -// /** -// * Escapes the given text so that it may be output using addWikiText() -// * without any linking, formatting, etc. making its way through. This -// * is achieved by substituting certain characters with HTML entities. -// * As required by the callers, "" is not used. -// * -// * @param String $text Text to be escaped -// * @return String -// */ -// function wfEscapeWikiText($text) { -// global $wgEnableMagicLinks; -// static $repl = null, $repl2 = null; -// if ($repl === null || defined('MW_PARSER_TEST') || defined('MW_PHPUNIT_TEST')) { -// // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache -// // in those situations -// $repl = [ -// '"' => '"', '&' => '&', "'" => ''', '<' => '<', -// '=' => '=', '>' => '>', '[' => '[', ']' => ']', -// '{' => '{', '|' => '|', '}' => '}', ';' => ';', -// "\n#" => "\n#", "\r#" => "\r#", -// "\n*" => "\n*", "\r*" => "\r*", -// "\n:" => "\n:", "\r:" => "\r:", -// "\n " => "\n ", "\r " => "\r ", -// "\n\n" => "\n ", "\r\n" => " \n", -// "\n\r" => "\n ", "\r\r" => "\r ", -// "\n\t" => "\n ", "\r\t" => "\r ", // "\n\t\n" is treated like "\n\n" -// "\n----" => "\n----", "\r----" => "\r----", -// '__' => '__', '://' => '://', -// ]; +// /** +// * Escapes the given text so that it may be output using addWikiText() +// * without any linking, formatting, etc. making its way through. This +// * is achieved by substituting certain characters with HTML entities. +// * As required by the callers, "" is not used. +// * +// * @param string $text Text to be escaped +// * @param-taint $text escapes_html +// * @return string +// */ +// function wfEscapeWikiText($text) { +// global $wgEnableMagicLinks; +// static $repl = null, $repl2 = null; +// if ($repl === null || defined('MW_PARSER_TEST') || defined('MW_PHPUNIT_TEST')) { +// // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache +// // in those situations +// $repl = [ +// '"' => '"', '&' => '&', "'" => ''', '<' => '<', +// '=' => '=', '>' => '>', '[' => '[', ']' => ']', +// '{' => '{', '|' => '|', '}' => '}', ';' => ';', +// "\n#" => "\n#", "\r#" => "\r#", +// "\n*" => "\n*", "\r*" => "\r*", +// "\n:" => "\n:", "\r:" => "\r:", +// "\n " => "\n ", "\r " => "\r ", +// "\n\n" => "\n ", "\r\n" => " \n", +// "\n\r" => "\n ", "\r\r" => "\r ", +// "\n\t" => "\n ", "\r\t" => "\r ", // "\n\t\n" is treated like "\n\n" +// "\n----" => "\n----", "\r----" => "\r----", +// '__' => '__', '://' => '://', +// ]; // -// $magicLinks = array_keys(array_filter($wgEnableMagicLinks)); -// // We have to catch everything "\s" matches in PCRE -// foreach ($magicLinks as $magic) { -// $repl["$magic "] = "$magic "; -// $repl["$magic\t"] = "$magic "; -// $repl["$magic\r"] = "$magic "; -// $repl["$magic\n"] = "$magic "; -// $repl["$magic\f"] = "$magic "; -// } -// -// // And handle protocols that don't use "://" -// global $wgUrlProtocols; -// $repl2 = []; -// foreach ($wgUrlProtocols as $prot) { -// if (substr($prot, -1) === ':') { -// $repl2[] = preg_quote(substr($prot, 0, -1), '/'); -// } -// } -// $repl2 = $repl2 ? '/\b(' . implode('|', $repl2) . '):/i' : '/^(?!)/'; +// $magicLinks = array_keys(array_filter($wgEnableMagicLinks)); +// // We have to catch everything "\s" matches in PCRE +// foreach ($magicLinks as $magic) { +// $repl["$magic "] = "$magic "; +// $repl["$magic\t"] = "$magic "; +// $repl["$magic\r"] = "$magic "; +// $repl["$magic\n"] = "$magic "; +// $repl["$magic\f"] = "$magic "; // } -// $text = substr(strtr("\n$text", $repl), 1); -// $text = preg_replace($repl2, '$1:', $text); -// return $text; -// } // -// /** -// * Sets dest to source and returns the original value of dest -// * If source is NULL, it just returns the value, it doesn't set the variable -// * If force is true, it will set the value even if source is NULL -// * -// * @param mixed $dest -// * @param mixed $source -// * @param boolean $force -// * @return mixed -// */ -// function wfSetVar(&$dest, $source, $force = false) { -// $temp = $dest; -// if (!is_null($source) || $force) { -// $dest = $source; -// } -// return $temp; -// } -// -// /** -// * As for wfSetVar except setting a bit -// * -// * @param int $dest -// * @param int $bit -// * @param boolean $state -// * -// * @return boolean -// */ -// function wfSetBit(&$dest, $bit, $state = true) { -// $temp = (boolean)($dest & $bit); -// if (!is_null($state)) { -// if ($state) { -// $dest |= $bit; -// } else { -// $dest &= ~$bit; +// // And handle protocols that don't use "://" +// global $wgUrlProtocols; +// $repl2 = []; +// foreach ($wgUrlProtocols as $prot) { +// if (substr($prot, -1) === ':') { +// $repl2[] = preg_quote(substr($prot, 0, -1), '/'); // } // } -// return $temp; +// $repl2 = $repl2 ? '/\b(' . implode('|', $repl2) . '):/i' : '/^(?!)/'; // } +// $text = substr(strtr("\n$text", $repl), 1); +// $text = preg_replace($repl2, '$1:', $text); +// return $text; +// } // -// /** -// * A wrapper around the PHP function var_export(). -// * Either print it or add it to the regular output ($wgOut). -// * -// * @param mixed $var A PHP variable to dump. -// */ -// function wfVarDump($var) { -// global $wgOut; -// $s = str_replace("\n", "
    \n", var_export($var, true) . "\n"); -// if (headers_sent() || !isset($wgOut) || !is_object($wgOut)) { -// print $s; +// /** +// * Sets dest to source and returns the original value of dest +// * If source is NULL, it just returns the value, it doesn't set the variable +// * If force is true, it will set the value even if source is NULL +// * +// * @param mixed &$dest +// * @param mixed $source +// * @param bool $force +// * @return mixed +// */ +// function wfSetVar(&$dest, $source, $force = false) { +// $temp = $dest; +// if (!is_null($source) || $force) { +// $dest = $source; +// } +// return $temp; +// } +// +// /** +// * As for wfSetVar except setting a bit +// * +// * @param int &$dest +// * @param int $bit +// * @param bool $state +// * +// * @return bool +// */ +// function wfSetBit(&$dest, $bit, $state = true) { +// $temp = (bool)($dest & $bit); +// if (!is_null($state)) { +// if ($state) { +// $dest |= $bit; // } else { -// $wgOut->addHTML($s); +// $dest &= ~$bit; // } // } +// return $temp; +// } // -// /** -// * Provide a simple HTTP error. -// * -// * @param int|String $code -// * @param String $label -// * @param String $desc -// */ -// function wfHttpError($code, $label, $desc) { -// global $wgOut; -// HttpStatus::header($code); -// if ($wgOut) { -// $wgOut->disable(); -// $wgOut->sendCacheControl(); -// } +// /** +// * A wrapper around the PHP function var_export(). +// * Either print it or add it to the regular output ($wgOut). +// * +// * @param mixed $var A PHP variable to dump. +// */ +// function wfVarDump($var) { +// global $wgOut; +// $s = str_replace("\n", "
    \n", var_export($var, true) . "\n"); +// if (headers_sent() || !isset($wgOut) || !is_object($wgOut)) { +// print $s; +// } else { +// $wgOut.addHTML($s); +// } +// } // -// header('Content-type: text/html; charset=utf-8'); -// print '' . -// '' . -// htmlspecialchars($label) . -// '

    ' . -// htmlspecialchars($label) . -// '

    ' . -// nl2br(htmlspecialchars($desc)) . -// "

    \n"; +// /** +// * Provide a simple HTTP error. +// * +// * @param int|string $code +// * @param string $label +// * @param string $desc +// */ +// function wfHttpError($code, $label, $desc) { +// global $wgOut; +// HttpStatus::header($code); +// if ($wgOut) { +// $wgOut.disable(); +// $wgOut.sendCacheControl(); // } // -// /** -// * Clear away any user-level output buffers, discarding contents. -// * -// * Suitable for 'starting afresh', for instance when streaming -// * relatively large amounts of data without buffering, or wanting to -// * output image files without ob_gzhandler's compression. -// * -// * The optional $resetGzipEncoding parameter controls suppression of -// * the Content-Encoding header sent by ob_gzhandler; by default it -// * is left. See comments for wfClearOutputBuffers() for why it would -// * be used. -// * -// * Note that some PHP configuration options may add output buffer -// * layers which cannot be removed; these are left in place. -// * -// * @param boolean $resetGzipEncoding -// */ -// function wfResetOutputBuffers($resetGzipEncoding = true) { -// if ($resetGzipEncoding) { -// // Suppress Content-Encoding and Content-length -// // headers from 1.10+s wfOutputHandler -// global $wgDisableOutputCompression; -// $wgDisableOutputCompression = true; -// } -// while ($status = ob_get_status()) { -// if (isset($status['flags'])) { -// $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE; -// $deleteable = ($status['flags'] & $flags) === $flags; -// } elseif (isset($status['del'])) { -// $deleteable = $status['del']; -// } else { -// // Guess that any PHP-@gplx.Internal protected setting can't be removed. -// $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */ -// } -// if (!$deleteable) { -// // Give up, and hope the result doesn't break -// // output behavior. -// break; -// } -// if ($status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier') { -// // Unit testing barrier to prevent this function from breaking PHPUnit. -// break; -// } -// if (!ob_end_clean()) { -// // Could not remove output buffer handler; abort now -// // to avoid getting in some kind of infinite loop. -// break; -// } -// if ($resetGzipEncoding) { -// if ($status['name'] == 'ob_gzhandler') { -// // Reset the 'Content-Encoding' field set by this handler -// // so we can start fresh. -// header_remove('Content-Encoding'); -// break; -// } -// } -// } +// MediaWiki\HeaderCallback::warnIfHeadersSent(); +// header('Content-type: text/html; charset=utf-8'); +// print '' . +// '' . +// htmlspecialchars($label) . +// '

    ' . +// htmlspecialchars($label) . +// '

    ' . +// nl2br(htmlspecialchars($desc)) . +// "

    \n"; +// } +// +// /** +// * Clear away any user-level output buffers, discarding contents. +// * +// * Suitable for 'starting afresh', for instance when streaming +// * relatively large amounts of data without buffering, or wanting to +// * output image files without ob_gzhandler's compression. +// * +// * The optional $resetGzipEncoding parameter controls suppression of +// * the Content-Encoding header sent by ob_gzhandler; by default it +// * is left. See comments for wfClearOutputBuffers() for why it would +// * be used. +// * +// * Note that some PHP configuration options may add output buffer +// * layers which cannot be removed; these are left in place. +// * +// * @param bool $resetGzipEncoding +// */ +// function wfResetOutputBuffers($resetGzipEncoding = true) { +// if ($resetGzipEncoding) { +// // Suppress Content-Encoding and Content-Length +// // headers from OutputHandler::handle. +// global $wgDisableOutputCompression; +// $wgDisableOutputCompression = true; // } -// -// /** -// * More legible than passing a 'false' parameter to wfResetOutputBuffers(): -// * -// * Clear away output buffers, but keep the Content-Encoding header -// * produced by ob_gzhandler, if any. -// * -// * This should be used for HTTP 304 responses, where you need to -// * preserve the Content-Encoding header of the real result, but -// * also need to suppress the output of ob_gzhandler to keep to spec -// * and avoid breaking Firefox in rare cases where the headers and -// * body are broken over two packets. -// */ -// function wfClearOutputBuffers() { -// wfResetOutputBuffers(false); -// } -// -// /** -// * Converts an Accept-* header into an array mapping String values to quality -// * factors -// * -// * @param String $accept -// * @param String $def Default -// * @return float[] Associative array of String => float pairs -// */ -// function wfAcceptToPrefs($accept, $def = '*/*') { -// # No arg means accept anything (per HTTP spec) -// if (!$accept) { -// return [ $def => 1.0 ]; -// } -// -// $prefs = []; -// -// $parts = explode(',', $accept); -// -// foreach ($parts as $part) { -// # @todo FIXME: Doesn't deal with params like 'text/html; level=1' -// $values = explode(';', trim($part)); -// $match = []; -// if (count($values) == 1) { -// $prefs[$values[0]] = 1.0; -// } elseif (preg_match('/q\s*=\s*(\d*\.\d+)/', $values[1], $match)) { -// $prefs[$values[0]] = floatval($match[1]); -// } -// } -// -// return $prefs; -// } -// -// /** -// * Checks if a given MIME type matches any of the keys in the given -// * array. Basic wildcards are accepted in the array keys. -// * -// * Returns the matching MIME type (or wildcard) if a match, otherwise -// * NULL if no match. -// * -// * @param String $type -// * @param array $avail -// * @return String -// * @private -// */ -// function mimeTypeMatch($type, $avail) { -// if (array_key_exists($type, $avail)) { -// return $type; +// while ($status = ob_get_status()) { +// if (isset($status['flags'])) { +// $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE; +// $deleteable = ($status['flags'] & $flags) === $flags; +// } elseif (isset($status['del'])) { +// $deleteable = $status['del']; // } else { -// $mainType = explode('/', $type)[0]; -// if (array_key_exists("$mainType/*", $avail)) { -// return "$mainType/*"; -// } elseif (array_key_exists('*/*', $avail)) { -// return '*/*'; -// } else { -// return null; -// } +// // Guess that any PHP-internal setting can't be removed. +// $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */ +// } +// if (!$deleteable) { +// // Give up, and hope the result doesn't break +// // output behavior. +// break; +// } +// if ($status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier') { +// // Unit testing barrier to prevent this function from breaking PHPUnit. +// break; +// } +// if (!ob_end_clean()) { +// // Could not remove output buffer handler; abort now +// // to avoid getting in some kind of infinite loop. +// break; +// } +// if ($resetGzipEncoding && $status['name'] == 'ob_gzhandler') { +// // Reset the 'Content-Encoding' field set by this handler +// // so we can start fresh. +// header_remove('Content-Encoding'); +// break; +// } +// } +// } +// +// /** +// * More legible than passing a 'false' parameter to wfResetOutputBuffers(): +// * +// * Clear away output buffers, but keep the Content-Encoding header +// * produced by ob_gzhandler, if any. +// * +// * This should be used for HTTP 304 responses, where you need to +// * preserve the Content-Encoding header of the real result, but +// * also need to suppress the output of ob_gzhandler to keep to spec +// * and avoid breaking Firefox in rare cases where the headers and +// * body are broken over two packets. +// */ +// function wfClearOutputBuffers() { +// wfResetOutputBuffers(false); +// } +// +// /** +// * Converts an Accept-* header into an array mapping string values to quality +// * factors +// * +// * @param string $accept +// * @param string $def Default +// * @return float[] Associative array of string => float pairs +// */ +// function wfAcceptToPrefs($accept, $def = '*/*') { +// # No arg means accept anything (per HTTP spec) +// if (!$accept) { +// return [ $def => 1.0 ]; +// } +// +// $prefs = []; +// +// $parts = explode(',', $accept); +// +// foreach ($parts as $part) { +// # @todo FIXME: Doesn't deal with params like 'text/html; level=1' +// $values = explode(';', trim($part)); +// $match = []; +// if (count($values) == 1) { +// $prefs[$values[0]] = 1.0; +// } elseif (preg_match('/q\s*=\s*(\d*\.\d+)/', $values[1], $match)) { +// $prefs[$values[0]] = floatval($match[1]); // } // } // -// /** -// * Returns the 'best' match between a client's requested internet media types -// * and the server's list of available types. Each list should be an associative -// * array of type to preference (preference is a float between 0.0 and 1.0). -// * Wildcards in the types are acceptable. -// * -// * @param array $cprefs Client's acceptable type list -// * @param array $sprefs Server's offered types -// * @return String -// * -// * @todo FIXME: Doesn't handle params like 'text/plain; charset=UTF-8' -// * XXX: generalize to negotiate other stuff -// */ -// function wfNegotiateType($cprefs, $sprefs) { -// $combine = []; +// return $prefs; +// } // -// foreach (array_keys($sprefs) as $type) { -// $subType = explode('/', $type)[1]; -// if ($subType != '*') { -// $ckey = mimeTypeMatch($type, $cprefs); -// if ($ckey) { -// $combine[$type] = $sprefs[$type] * $cprefs[$ckey]; -// } -// } -// } -// -// foreach (array_keys($cprefs) as $type) { -// $subType = explode('/', $type)[1]; -// if ($subType != '*' && !array_key_exists($type, $sprefs)) { -// $skey = mimeTypeMatch($type, $sprefs); -// if ($skey) { -// $combine[$type] = $sprefs[$skey] * $cprefs[$type]; -// } -// } -// } -// -// $bestq = 0; -// $besttype = null; -// -// foreach (array_keys($combine) as $type) { -// if ($combine[$type] > $bestq) { -// $besttype = $type; -// $bestq = $combine[$type]; -// } -// } -// -// return $besttype; -// } -// -// /** -// * Reference-counted warning suppression -// * -// * @deprecated since 1.26, use MediaWiki\suppressWarnings() directly -// * @param boolean $end -// */ -// function wfSuppressWarnings($end = false) { -// MediaWiki\suppressWarnings($end); -// } -// -// /** -// * @deprecated since 1.26, use MediaWiki\restoreWarnings() directly -// * Restore error level to previous value -// */ -// function wfRestoreWarnings() { -// MediaWiki\suppressWarnings(true); -// } -// -// /** -// * Get a timestamp String in one of various formats -// * -// * @param mixed $outputtype A timestamp in one of the supported formats, the -// * function will autodetect which format is supplied and act accordingly. -// * @param mixed $ts Optional timestamp to convert, default 0 for the current time -// * @return String|boolean String / false The same date in the format specified in $outputtype or false -// */ -// function wfTimestamp($outputtype = TS_UNIX, $ts = 0) { -// $ret = MWTimestamp::convert($outputtype, $ts); -// if ($ret === false) { -// wfDebug("wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n"); -// } -// return $ret; -// } -// -// /** -// * Return a formatted timestamp, or null if input is null. -// * For dealing with nullable timestamp columns in the database. -// * -// * @param int $outputtype -// * @param String $ts -// * @return String -// */ -// function wfTimestampOrNull($outputtype = TS_UNIX, $ts = null) { -// if (is_null($ts)) { +// /** +// * Checks if a given MIME type matches any of the keys in the given +// * array. Basic wildcards are accepted in the array keys. +// * +// * Returns the matching MIME type (or wildcard) if a match, otherwise +// * NULL if no match. +// * +// * @param string $type +// * @param array $avail +// * @return string +// * @private +// */ +// function mimeTypeMatch($type, $avail) { +// if (array_key_exists($type, $avail)) { +// return $type; +// } else { +// $mainType = explode('/', $type)[0]; +// if (array_key_exists("$mainType/*", $avail)) { +// return "$mainType/*"; +// } elseif (array_key_exists('*/*', $avail)) { +// return '*/*'; +// } else { // return null; -// } else { -// return wfTimestamp($outputtype, $ts); +// } +// } +// } +// +// /** +// * Returns the 'best' match between a client's requested internet media types +// * and the server's list of available types. Each list should be an associative +// * array of type to preference (preference is a float between 0.0 and 1.0). +// * Wildcards in the types are acceptable. +// * +// * @param array $cprefs Client's acceptable type list +// * @param array $sprefs Server's offered types +// * @return string +// * +// * @todo FIXME: Doesn't handle params like 'text/plain; charset=UTF-8' +// * XXX: generalize to negotiate other stuff +// */ +// function wfNegotiateType($cprefs, $sprefs) { +// $combine = []; +// +// foreach (array_keys($sprefs) as $type) { +// $subType = explode('/', $type)[1]; +// if ($subType != '*') { +// $ckey = mimeTypeMatch($type, $cprefs); +// if ($ckey) { +// $combine[$type] = $sprefs[$type] * $cprefs[$ckey]; +// } // } // } // -// /** -// * Convenience function; returns MediaWiki timestamp for the present time. -// * -// * @return String -// */ -// function wfTimestampNow() { -// # return NOW -// return MWTimestamp::now(TS_MW); +// foreach (array_keys($cprefs) as $type) { +// $subType = explode('/', $type)[1]; +// if ($subType != '*' && !array_key_exists($type, $sprefs)) { +// $skey = mimeTypeMatch($type, $sprefs); +// if ($skey) { +// $combine[$type] = $sprefs[$skey] * $cprefs[$type]; +// } +// } // } // -// /** -// * Check if the operating system is Windows -// * -// * @return boolean True if it's Windows, false otherwise. -// */ -// function wfIsWindows() { -// static $isWindows = null; -// if ($isWindows === null) { -// $isWindows = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'; +// $bestq = 0; +// $besttype = null; +// +// foreach (array_keys($combine) as $type) { +// if ($combine[$type] > $bestq) { +// $besttype = $type; +// $bestq = $combine[$type]; // } -// return $isWindows; // } // -// /** -// * Check if we are running under HHVM -// * -// * @return boolean -// */ -// function wfIsHHVM() { -// return defined('HHVM_VERSION'); +// return $besttype; +// } +// +// /** +// * Reference-counted warning suppression +// * +// * @deprecated since 1.26, use Wikimedia\suppressWarnings() directly +// * @param bool $end +// */ +// function wfSuppressWarnings($end = false) { +// Wikimedia\suppressWarnings($end); +// } +// +// /** +// * @deprecated since 1.26, use Wikimedia\restoreWarnings() directly +// * Restore error level to previous value +// */ +// function wfRestoreWarnings() { +// Wikimedia\restoreWarnings(); +// } +// +// /** +// * Get a timestamp string in one of various formats +// * +// * @param mixed $outputtype A timestamp in one of the supported formats, the +// * function will autodetect which format is supplied and act accordingly. +// * @param mixed $ts Optional timestamp to convert, default 0 for the current time +// * @return string|bool String / false The same date in the format specified in $outputtype or false +// */ +// function wfTimestamp($outputtype = TS_UNIX, $ts = 0) { +// $ret = MWTimestamp::convert($outputtype, $ts); +// if ($ret === false) { +// wfDebug("wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n"); +// } +// return $ret; +// } +// +// /** +// * Return a formatted timestamp, or null if input is null. +// * For dealing with nullable timestamp columns in the database. +// * +// * @param int $outputtype +// * @param string|null $ts +// * @return string +// */ +// function wfTimestampOrNull($outputtype = TS_UNIX, $ts = null) { +// if (is_null($ts)) { +// return null; +// } else { +// return wfTimestamp($outputtype, $ts); +// } +// } +// +// /** +// * Convenience function; returns MediaWiki timestamp for the present time. +// * +// * @return string +// */ +// function wfTimestampNow() { +// # return NOW +// return MWTimestamp::now(TS_MW); +// } +// +// /** +// * Check if the operating system is Windows +// * +// * @return bool True if it's Windows, false otherwise. +// */ +// function wfIsWindows() { +// static $isWindows = null; +// if ($isWindows === null) { +// $isWindows = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'; +// } +// return $isWindows; +// } +// +// /** +// * Check if we are running under HHVM +// * +// * @return bool +// */ +// function wfIsHHVM() { +// return defined('HHVM_VERSION'); +// } +// +// /** +// * Check if we are running from the commandline +// * +// * @since 1.31 +// * @return bool +// */ +// function wfIsCLI() { +// return PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg'; +// } +// +// /** +// * Tries to get the system directory for temporary files. First +// * $wgTmpDirectory is checked, and then the TMPDIR, TMP, and TEMP +// * environment variables are then checked in sequence, then +// * sys_get_temp_dir(), then upload_tmp_dir from php.ini. +// * +// * NOTE: When possible, use instead the tmpfile() function to create +// * temporary files to avoid race conditions on file creation, etc. +// * +// * @return string +// */ +// function wfTempDir() { +// global $wgTmpDirectory; +// +// if ($wgTmpDirectory !== false) { +// return $wgTmpDirectory; // } // -// /** -// * Tries to get the system directory for temporary files. First -// * $wgTmpDirectory is checked, and then the TMPDIR, TMP, and TEMP -// * environment variables are then checked in sequence, then -// * sys_get_temp_dir(), then upload_tmp_dir from php.ini. -// * -// * NOTE: When possible, use instead the tmpfile() function to create -// * temporary files to avoid race conditions on file creation, etc. -// * -// * @return String -// */ -// function wfTempDir() { -// global $wgTmpDirectory; +// return TempFSFile::getUsableTempDirectory(); +// } // -// if ($wgTmpDirectory !== false) { -// return $wgTmpDirectory; -// } +// /** +// * Make directory, and make all parent directories if they don't exist +// * +// * @param string $dir Full path to directory to create +// * @param int|null $mode Chmod value to use, default is $wgDirectoryMode +// * @param string|null $caller Optional caller param for debugging. +// * @throws MWException +// * @return bool +// */ +// function wfMkdirParents($dir, $mode = null, $caller = null) { +// global $wgDirectoryMode; // -// return TempFSFile::getUsableTempDirectory(); +// if (FileBackend::isStoragePath($dir)) { // sanity +// throw new MWException(__FUNCTION__ . " given storage path '$dir'."); // } // -// /** -// * Make directory, and make all parent directories if they don't exist -// * -// * @param String $dir Full path to directory to create -// * @param int $mode Chmod value to use, default is $wgDirectoryMode -// * @param String $caller Optional caller param for debugging. -// * @throws MWException -// * @return boolean -// */ -// function wfMkdirParents($dir, $mode = null, $caller = null) { -// global $wgDirectoryMode; +// if (!is_null($caller)) { +// wfDebug("$caller: called wfMkdirParents($dir)\n"); +// } // -// if (FileBackend::isStoragePath($dir)) { // sanity -// throw new MWException(__FUNCTION__ . " given storage path '$dir'."); -// } +// if (strval($dir) === '' || is_dir($dir)) { +// return true; +// } // -// if (!is_null($caller)) { -// wfDebug("$caller: called wfMkdirParents($dir)\n"); -// } +// $dir = str_replace([ '\\', '/' ], DIRECTORY_SEPARATOR, $dir); // -// if (strval($dir) === '' || is_dir($dir)) { +// if (is_null($mode)) { +// $mode = $wgDirectoryMode; +// } +// +// // Turn off the normal warning, we're doing our own below +// Wikimedia\suppressWarnings(); +// $ok = mkdir($dir, $mode, true); // PHP5 <3 +// Wikimedia\restoreWarnings(); +// +// if (!$ok) { +// // directory may have been created on another request since we last checked +// if (is_dir($dir)) { // return true; // } // -// $dir = str_replace([ '\\', '/' ], DIRECTORY_SEPARATOR, $dir); -// -// if (is_null($mode)) { -// $mode = $wgDirectoryMode; -// } -// -// // Turn off the normal warning, we're doing our own below -// MediaWiki\suppressWarnings(); -// $ok = mkdir($dir, $mode, true); // PHP5 <3 -// MediaWiki\restoreWarnings(); -// -// if (!$ok) { -// // directory may have been created on another request since we last checked -// if (is_dir($dir)) { -// return true; -// } -// -// // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis. -// wfLogWarning(sprintf("failed to mkdir \"%s\" mode 0%o", $dir, $mode)); -// } -// return $ok; +// // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis. +// wfLogWarning(sprintf("failed to mkdir \"%s\" mode 0%o", $dir, $mode)); // } +// return $ok; +// } // -// /** -// * Remove a directory and all its content. -// * Does not hide error. -// * @param String $dir -// */ -// function wfRecursiveRemoveDir($dir) { -// wfDebug(__FUNCTION__ . "($dir)\n"); -// // taken from https://secure.php.net/manual/en/function.rmdir.php#98622 -// if (is_dir($dir)) { -// $objects = scandir($dir); -// foreach ($objects as $Object) { -// if ($Object != "." && $Object != "..") { -// if (filetype($dir . '/' . $Object) == "dir") { -// wfRecursiveRemoveDir($dir . '/' . $Object); -// } else { -// unlink($dir . '/' . $Object); -// } -// } -// } -// reset($objects); -// rmdir($dir); -// } -// } -// -// /** -// * @param int $nr The number to format -// * @param int $acc The number of digits after the decimal point, default 2 -// * @param boolean $round Whether or not to round the value, default true -// * @return String -// */ -// function wfPercent($nr, $acc = 2, $round = true) { -// $ret = sprintf("%.${acc}f", $nr); -// return $round ? round($ret, $acc) . '%' : "$ret%"; -// } -// -// /** -// * Safety wrapper around ini_get() for boolean settings. -// * The values returned from ini_get() are pre-normalized for settings -// * set via php.ini or php_flag/php_admin_flag... but *not* -// * for those set via php_value/php_admin_value. -// * -// * It's fairly common for people to use php_value instead of php_flag, -// * which can leave you with an 'off' setting giving a false positive -// * for code that just takes the ini_get() return value as a boolean. -// * -// * To make things extra interesting, setting via php_value accepts -// * "true" and "yes" as true, but php.ini and php_flag consider them false. :) -// * Unrecognized values go false... again opposite PHP's own coercion -// * from String to boolean. -// * -// * Luckily, 'properly' set settings will always come back as '0' or '1', -// * so we only have to worry about them and the 'improper' settings. -// * -// * I frickin' hate PHP... :P -// * -// * @param String $setting -// * @return boolean -// */ -// function wfIniGetBool($setting) { -// $val = strtolower(ini_get($setting)); -// // 'on' and 'true' can't have whitespace around them, but '1' can. -// return $val == 'on' -// || $val == 'true' -// || $val == 'yes' -// || preg_match("/^\s*[+-]?0*[1-9]/", $val); // approx C atoi() function -// } -// -// /** -// * Version of escapeshellarg() that works better on Windows. -// * -// * Originally, this fixed the incorrect use of single quotes on Windows -// * (https://bugs.php.net/bug.php?id=26285) and the locale problems on Linux in -// * PHP 5.2.6+ (bug backported to earlier distro releases of PHP). -// * -// * @param String ... strings to escape and glue together, or a single array of strings parameter -// * @return String -// */ -// function wfEscapeShellArg(/*...*/) { -// wfInitShellLocale(); -// -// $args = func_get_args(); -// if (count($args) === 1 && is_array(reset($args))) { -// // If only one argument has been passed, and that argument is an array, -// // treat it as a list of arguments -// $args = reset($args); -// } -// -// $first = true; -// $retVal = ''; -// foreach ($args as $arg) { -// if (!$first) { -// $retVal .= ' '; -// } else { -// $first = false; -// } -// -// if (wfIsWindows()) { -// // Escaping for an MSVC-style command line parser and CMD.EXE -// // @codingStandardsIgnoreStart For long URLs -// // Refs: -// // * https://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html -// // * https://technet.microsoft.com/en-us/library/cc723564.aspx -// // * T15518 -// // * CR r63214 -// // Double the backslashes before any double quotes. Escape the double quotes. -// // @codingStandardsIgnoreEnd -// $tokens = preg_split('/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE); -// $arg = ''; -// $iteration = 0; -// foreach ($tokens as $token) { -// if ($iteration % 2 == 1) { -// // Delimiter, a double quote preceded by zero or more slashes -// $arg .= str_replace('\\', '\\\\', substr($token, 0, -1)) . '\\"'; -// } elseif ($iteration % 4 == 2) { -// // ^ in $token will be outside quotes, need to be escaped -// $arg .= str_replace('^', '^^', $token); -// } else { // $iteration % 4 == 0 -// // ^ in $token will appear inside double quotes, so leave as is -// $arg .= $token; -// } -// $iteration++; -// } -// // Double the backslashes before the end of the String, because -// // we will soon add a quote -// $m = []; -// if (preg_match('/^(.*?)(\\\\+)$/', $arg, $m)) { -// $arg = $m[1] . str_replace('\\', '\\\\', $m[2]); -// } -// -// // Add surrounding quotes -// $retVal .= '"' . $arg . '"'; -// } else { -// $retVal .= escapeshellarg($arg); -// } -// } -// return $retVal; -// } -// -// /** -// * Check if wfShellExec() is effectively disabled via php.ini config -// * -// * @return boolean|String False or 'disabled' -// * @since 1.22 -// */ -// function wfShellExecDisabled() { -// static $disabled = null; -// if (is_null($disabled)) { -// if (!function_exists('proc_open')) { -// wfDebug("proc_open() is disabled\n"); -// $disabled = 'disabled'; -// } else { -// $disabled = false; -// } -// } -// return $disabled; -// } -// -// /** -// * Execute a shell command, with time and memory limits mirrored from the PHP -// * configuration if supported. -// * -// * @param String|String[] $cmd If String, a properly shell-escaped command line, -// * or an array of unescaped arguments, in which case each value will be escaped -// * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'" -// * @param null|mixed &$retval Optional, will receive the program's exit code. -// * (non-zero is usually failure). If there is an error from -// * read, select, or proc_open(), this will be set to -1. -// * @param array $environ Optional environment variables which should be -// * added to the executed command environment. -// * @param array $limits Optional array with limits(filesize, memory, time, walltime) -// * this overwrites the global wgMaxShell* limits. -// * @param array $options Array of options: -// * - duplicateStderr: Set this to true to duplicate stderr to stdout, -// * including errors from limit.sh -// * - profileMethod: By default this function will profile based on the calling -// * method. Set this to a String for an alternative method to profile from -// * -// * @return String Collected stdout as a String -// */ -// function wfShellExec($cmd, &$retval = null, $environ = [], -// $limits = [], $options = [] -// ) { -// global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime, -// $wgMaxShellWallClockTime, $wgShellCgroup; -// -// $disabled = wfShellExecDisabled(); -// if ($disabled) { -// $retval = 1; -// return 'Unable to run external programs, proc_open() is disabled.'; -// } -// -// $includeStderr = isset($options['duplicateStderr']) && $options['duplicateStderr']; -// $profileMethod = isset($options['profileMethod']) ? $options['profileMethod'] : wfGetCaller(); -// -// wfInitShellLocale(); -// -// $envcmd = ''; -// foreach ($environ as $k => $v) { -// if (wfIsWindows()) { -// /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves -// * appear in the environment variable, so we must use carat escaping as documented in -// * https://technet.microsoft.com/en-us/library/cc723564.aspx -// * Note however that the quote isn't listed there, but is needed, and the parentheses -// * are listed there but doesn't appear to need it. -// */ -// $envcmd .= "set $k=" . preg_replace('/([&|()<>^"])/', '^\\1', $v) . '&& '; -// } else { -// /* Assume this is a POSIX shell, thus required to accept variable assignments before the command -// * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01 -// */ -// $envcmd .= "$k=" . escapeshellarg($v) . ' '; -// } -// } -// if (is_array($cmd)) { -// $cmd = wfEscapeShellArg($cmd); -// } -// -// $cmd = $envcmd . $cmd; -// -// $useLogPipe = false; -// if (is_executable('/bin/bash')) { -// $time = intval(isset($limits['time']) ? $limits['time'] : $wgMaxShellTime); -// if (isset($limits['walltime'])) { -// $wallTime = intval($limits['walltime']); -// } elseif (isset($limits['time'])) { -// $wallTime = $time; -// } else { -// $wallTime = intval($wgMaxShellWallClockTime); -// } -// $mem = intval(isset($limits['memory']) ? $limits['memory'] : $wgMaxShellMemory); -// $filesize = intval(isset($limits['filesize']) ? $limits['filesize'] : $wgMaxShellFileSize); -// -// if ($time > 0 || $mem > 0 || $filesize > 0 || $wallTime > 0) { -// $cmd = '/bin/bash ' . escapeshellarg("$IP/includes/limit.sh") . ' ' . -// escapeshellarg($cmd) . ' ' . -// escapeshellarg( -// "MW_INCLUDE_STDERR=" . ($includeStderr ? '1' : '') . ';' . -// "MW_CPU_LIMIT=$time; " . -// 'MW_CGROUP=' . escapeshellarg($wgShellCgroup) . '; ' . -// "MW_MEM_LIMIT=$mem; " . -// "MW_FILE_SIZE_LIMIT=$filesize; " . -// "MW_WALL_CLOCK_LIMIT=$wallTime; " . -// "MW_USE_LOG_PIPE=yes" -// ); -// $useLogPipe = true; -// } elseif ($includeStderr) { -// $cmd .= ' 2>&1'; -// } -// } elseif ($includeStderr) { -// $cmd .= ' 2>&1'; -// } -// wfDebug("wfShellExec: $cmd\n"); -// -// // Don't try to execute commands that exceed Linux's MAX_ARG_STRLEN. -// // Other platforms may be more accomodating, but we don't want to be -// // accomodating, because very long commands probably include user -// // input. See T129506. -// if (strlen($cmd) > SHELL_MAX_ARG_STRLEN) { -// throw new Exception(__METHOD__ . -// '(): total length of $cmd must not exceed SHELL_MAX_ARG_STRLEN'); -// } -// -// $desc = [ -// 0 => [ 'file', 'php://stdin', 'r' ], -// 1 => [ 'pipe', 'w' ], -// 2 => [ 'file', 'php://stderr', 'w' ] ]; -// if ($useLogPipe) { -// $desc[3] = [ 'pipe', 'w' ]; -// } -// $pipes = null; -// $scoped = Profiler::instance()->scopedProfileIn(__FUNCTION__ . '-' . $profileMethod); -// $proc = proc_open($cmd, $desc, $pipes); -// if (!$proc) { -// wfDebugLog('exec', "proc_open() failed: $cmd"); -// $retval = -1; -// return ''; -// } -// $outBuffer = $logBuffer = ''; -// $emptyArray = []; -// $status = false; -// $logMsg = false; -// -// /* According to the documentation, it is possible for stream_select() -// * to fail due to EINTR. I haven't managed to induce this in testing -// * despite sending various signals. If it did happen, the error -// * message would take the form: -// * -// * stream_select(): unable to select [4]: Interrupted system call (max_fd=5) -// * -// * where [4] is the value of the macro EINTR and "Interrupted system -// * call" is String which according to the Linux manual is "possibly" -// * localised according to LC_MESSAGES. -// */ -// $eintr = defined('SOCKET_EINTR') ? SOCKET_EINTR : 4; -// $eintrMessage = "stream_select(): unable to select [$eintr]"; -// -// $running = true; -// $timeout = null; -// $numReadyPipes = 0; -// -// while ($running === true || $numReadyPipes !== 0) { -// if ($running) { -// $status = proc_get_status($proc); -// // If the process has terminated, switch to nonblocking selects -// // for getting any data still waiting to be read. -// if (!$status['running']) { -// $running = false; -// $timeout = 0; -// } -// } -// -// $readyPipes = $pipes; -// -// // Clear last error -// // @codingStandardsIgnoreStart Generic.PHP.NoSilencedErrors.Discouraged -// @trigger_error(''); -// $numReadyPipes = @stream_select($readyPipes, $emptyArray, $emptyArray, $timeout); -// if ($numReadyPipes === false) { -// // @codingStandardsIgnoreEnd -// $error = error_get_last(); -// if (strncmp($error['message'], $eintrMessage, strlen($eintrMessage)) == 0) { -// continue; +// /** +// * Remove a directory and all its content. +// * Does not hide error. +// * @param string $dir +// */ +// function wfRecursiveRemoveDir($dir) { +// wfDebug(__FUNCTION__ . "($dir)\n"); +// // taken from https://secure.php.net/manual/en/function.rmdir.php#98622 +// if (is_dir($dir)) { +// $objects = scandir($dir); +// foreach ($objects as $object) { +// if ($object != "." && $object != "..") { +// if (filetype($dir . '/' . $object) == "dir") { +// wfRecursiveRemoveDir($dir . '/' . $object); // } else { -// trigger_error($error['message'], E_USER_WARNING); -// $logMsg = $error['message']; -// break; -// } -// } -// foreach ($readyPipes as $fd => $pipe) { -// $block = fread($pipe, 65536); -// if ($block === '') { -// // End of file -// fclose($pipes[$fd]); -// unset($pipes[$fd]); -// if (!$pipes) { -// break 2; -// } -// } elseif ($block === false) { -// // Read error -// $logMsg = "Error reading from pipe"; -// break 2; -// } elseif ($fd == 1) { -// // From stdout -// $outBuffer .= $block; -// } elseif ($fd == 3) { -// // From log FD -// $logBuffer .= $block; -// if (strpos($block, "\n") !== false) { -// $lines = explode("\n", $logBuffer); -// $logBuffer = array_pop($lines); -// foreach ($lines as $line) { -// wfDebugLog('exec', $line); -// } -// } +// unlink($dir . '/' . $object); // } // } // } +// reset($objects); +// rmdir($dir); +// } +// } // -// foreach ($pipes as $pipe) { -// fclose($pipe); -// } +// /** +// * @param int $nr The number to format +// * @param int $acc The number of digits after the decimal point, default 2 +// * @param bool $round Whether or not to round the value, default true +// * @return string +// */ +// function wfPercent($nr, $acc = 2, $round = true) { +// $ret = sprintf("%.${acc}f", $nr); +// return $round ? round($ret, $acc) . '%' : "$ret%"; +// } // -// // Use the status previously collected if possible, since proc_get_status() -// // just calls waitpid() which will not return anything useful the second time. -// if ($running) { -// $status = proc_get_status($proc); -// } +// /** +// * Safety wrapper around ini_get() for boolean settings. +// * The values returned from ini_get() are pre-normalized for settings +// * set via php.ini or php_flag/php_admin_flag... but *not* +// * for those set via php_value/php_admin_value. +// * +// * It's fairly common for people to use php_value instead of php_flag, +// * which can leave you with an 'off' setting giving a false positive +// * for code that just takes the ini_get() return value as a boolean. +// * +// * To make things extra interesting, setting via php_value accepts +// * "true" and "yes" as true, but php.ini and php_flag consider them false. :) +// * Unrecognized values go false... again opposite PHP's own coercion +// * from string to bool. +// * +// * Luckily, 'properly' set settings will always come back as '0' or '1', +// * so we only have to worry about them and the 'improper' settings. +// * +// * I frickin' hate PHP... :P +// * +// * @param string $setting +// * @return bool +// */ +// function wfIniGetBool($setting) { +// return wfStringToBool(ini_get($setting)); +// } // -// if ($logMsg !== false) { -// // Read/select error -// $retval = -1; -// proc_close($proc); -// } elseif ($status['signaled']) { -// $logMsg = "Exited with signal {$status['termsig']}"; -// $retval = 128 + $status['termsig']; -// proc_close($proc); -// } else { -// if ($status['running']) { -// $retval = proc_close($proc); -// } else { -// $retval = $status['exitcode']; -// proc_close($proc); -// } -// if ($retval == 127) { -// $logMsg = "Possibly missing executable file"; -// } elseif ($retval >= 129 && $retval <= 192) { -// $logMsg = "Probably exited with signal " . ($retval - 128); -// } -// } +// /** +// * Convert string value to boolean, when the following are interpreted as true: +// * - on +// * - true +// * - yes +// * - Any number, except 0 +// * All other strings are interpreted as false. +// * +// * @param string $val +// * @return bool +// * @since 1.31 +// */ +// function wfStringToBool($val) { +// $val = strtolower($val); +// // 'on' and 'true' can't have whitespace around them, but '1' can. +// return $val == 'on' +// || $val == 'true' +// || $val == 'yes' +// || preg_match("/^\s*[+-]?0*[1-9]/", $val); // approx C atoi() function +// } // -// if ($logMsg !== false) { -// wfDebugLog('exec', "$logMsg: $cmd"); -// } +// /** +// * Version of escapeshellarg() that works better on Windows. +// * +// * Originally, this fixed the incorrect use of single quotes on Windows +// * (https://bugs.php.net/bug.php?id=26285) and the locale problems on Linux in +// * PHP 5.2.6+ (bug backported to earlier distro releases of PHP). +// * +// * @param string|string[] ...$args strings to escape and glue together, +// * or a single array of strings parameter +// * @return string +// * @deprecated since 1.30 use MediaWiki\Shell\Shell::escape() +// */ +// function wfEscapeShellArg(...$args) { +// return Shell::escape(...$args); +// } // -// return $outBuffer; +// /** +// * Execute a shell command, with time and memory limits mirrored from the PHP +// * configuration if supported. +// * +// * @param string|string[] $cmd If string, a properly shell-escaped command line, +// * or an array of unescaped arguments, in which case each value will be escaped +// * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'" +// * @param null|mixed &$retval Optional, will receive the program's exit code. +// * (non-zero is usually failure). If there is an error from +// * read, select, or proc_open(), this will be set to -1. +// * @param array $environ Optional environment variables which should be +// * added to the executed command environment. +// * @param array $limits Optional array with limits(filesize, memory, time, walltime) +// * this overwrites the global wgMaxShell* limits. +// * @param array $options Array of options: +// * - duplicateStderr: Set this to true to duplicate stderr to stdout, +// * including errors from limit.sh +// * - profileMethod: By default this function will profile based on the calling +// * method. Set this to a string for an alternative method to profile from +// * +// * @return string Collected stdout as a string +// * @deprecated since 1.30 use class MediaWiki\Shell\Shell +// */ +// function wfShellExec($cmd, &$retval = null, $environ = [], +// $limits = [], $options = [] +// ) { +// if (Shell::isDisabled()) { +// $retval = 1; +// // Backwards compatibility be upon us... +// return 'Unable to run external programs, proc_open() is disabled.'; // } // -// /** -// * Execute a shell command, returning both stdout and stderr. Convenience -// * function, as all the arguments to wfShellExec can become unwieldy. -// * -// * @note This also includes errors from limit.sh, e.g. if $wgMaxShellFileSize is exceeded. -// * @param String|String[] $cmd If String, a properly shell-escaped command line, -// * or an array of unescaped arguments, in which case each value will be escaped -// * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'" -// * @param null|mixed &$retval Optional, will receive the program's exit code. -// * (non-zero is usually failure) -// * @param array $environ Optional environment variables which should be -// * added to the executed command environment. -// * @param array $limits Optional array with limits(filesize, memory, time, walltime) -// * this overwrites the global wgMaxShell* limits. -// * @return String Collected stdout and stderr as a String -// */ -// function wfShellExecWithStderr($cmd, &$retval = null, $environ = [], $limits = []) { -// return wfShellExec($cmd, $retval, $environ, $limits, -// [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ]); +// if (is_array($cmd)) { +// $cmd = Shell::escape($cmd); // } // -// /** -// * Workaround for https://bugs.php.net/bug.php?id=45132 -// * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale -// */ -// function wfInitShellLocale() { -// static $done = false; -// if ($done) { -// return; -// } -// $done = true; -// global $wgShellLocale; -// putenv("LC_CTYPE=$wgShellLocale"); -// setlocale(LC_CTYPE, $wgShellLocale); +// $includeStderr = isset($options['duplicateStderr']) && $options['duplicateStderr']; +// $profileMethod = $options['profileMethod'] ?? wfGetCaller(); +// +// try { +// $result = Shell::command([]) +// .unsafeParams((array)$cmd) +// .environment($environ) +// .limits($limits) +// .includeStderr($includeStderr) +// .profileMethod($profileMethod) +// // For b/c +// .restrict(Shell::RESTRICT_NONE) +// .execute(); +// } catch (ProcOpenError $ex) { +// $retval = -1; +// return ''; // } // -// /** -// * Generate a shell-escaped command line String to run a MediaWiki cli script. -// * Note that $parameters should be a flat array and an option with an argument -// * should consist of two consecutive items in the array (do not use "--option value"). -// * -// * @param String $script MediaWiki cli script path -// * @param array $parameters Arguments and options to the script -// * @param array $options Associative array of options: -// * 'php': The path to the php executable -// * 'wrapper': Path to a PHP wrapper to handle the maintenance script -// * @return String -// */ -// function wfShellWikiCmd($script, array $parameters = [], array $options = []) { -// global $wgXophpCli; -// // Give site config file a chance to run the script in a wrapper. -// // The caller may likely want to call wfBasename() on $script. -// Hooks::run('wfShellWikiCmd', [ &$script, &$parameters, &$options ]); -// $cmd = isset($options['php']) ? [ $options['php'] ] : [ $wgXophpCli ]; -// if (isset($options['wrapper'])) { -// $cmd[] = $options['wrapper']; -// } -// $cmd[] = $script; -// // Escape each parameter for shell -// return wfEscapeShellArg(array_merge($cmd, $parameters)); +// $retval = $result.getExitCode(); +// +// return $result.getStdout(); +// } +// +// /** +// * Execute a shell command, returning both stdout and stderr. Convenience +// * function, as all the arguments to wfShellExec can become unwieldy. +// * +// * @note This also includes errors from limit.sh, e.g. if $wgMaxShellFileSize is exceeded. +// * @param string|string[] $cmd If string, a properly shell-escaped command line, +// * or an array of unescaped arguments, in which case each value will be escaped +// * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'" +// * @param null|mixed &$retval Optional, will receive the program's exit code. +// * (non-zero is usually failure) +// * @param array $environ Optional environment variables which should be +// * added to the executed command environment. +// * @param array $limits Optional array with limits(filesize, memory, time, walltime) +// * this overwrites the global wgMaxShell* limits. +// * @return string Collected stdout and stderr as a string +// * @deprecated since 1.30 use class MediaWiki\Shell\Shell +// */ +// function wfShellExecWithStderr($cmd, &$retval = null, $environ = [], $limits = []) { +// return wfShellExec($cmd, $retval, $environ, $limits, +// [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ]); +// } +// +// /** +// * Generate a shell-escaped command line string to run a MediaWiki cli script. +// * Note that $parameters should be a flat array and an option with an argument +// * should consist of two consecutive items in the array (do not use "--option value"). +// * +// * @deprecated since 1.31, use Shell::makeScriptCommand() +// * +// * @param string $script MediaWiki cli script path +// * @param array $parameters Arguments and options to the script +// * @param array $options Associative array of options: +// * 'php': The path to the php executable +// * 'wrapper': Path to a PHP wrapper to handle the maintenance script +// * @return string +// */ +// function wfShellWikiCmd($script, array $parameters = [], array $options = []) { +// global $wgPhpCli; +// // Give site config file a chance to run the script in a wrapper. +// // The caller may likely want to call wfBasename() on $script. +// Hooks::run('wfShellWikiCmd', [ &$script, &$parameters, &$options ]); +// $cmd = [ $options['php'] ?? $wgPhpCli ]; +// if (isset($options['wrapper'])) { +// $cmd[] = $options['wrapper']; // } +// $cmd[] = $script; +// // Escape each parameter for shell +// return Shell::escape(array_merge($cmd, $parameters)); +// } // -// /** -// * wfMerge attempts to merge differences between three texts. -// * Returns true for a clean merge and false for failure or a conflict. -// * -// * @param String $old -// * @param String $mine -// * @param String $yours -// * @param String $result -// * @return boolean -// */ -// function wfMerge($old, $mine, $yours, &$result) { -// global $wgDiff3; +// /** +// * wfMerge attempts to merge differences between three texts. +// * Returns true for a clean merge and false for failure or a conflict. +// * +// * @param string $old +// * @param string $mine +// * @param string $yours +// * @param string &$result +// * @param string|null &$mergeAttemptResult +// * @return bool +// */ +// function wfMerge($old, $mine, $yours, &$result, &$mergeAttemptResult = null) { +// global $wgDiff3; // -// # This check may also protect against code injection in -// # case of broken installations. -// MediaWiki\suppressWarnings(); -// $haveDiff3 = $wgDiff3 && file_exists($wgDiff3); -// MediaWiki\restoreWarnings(); +// # This check may also protect against code injection in +// # case of broken installations. +// Wikimedia\suppressWarnings(); +// $haveDiff3 = $wgDiff3 && file_exists($wgDiff3); +// Wikimedia\restoreWarnings(); // -// if (!$haveDiff3) { -// wfDebug("diff3 not found\n"); -// return false; -// } -// -// # Make temporary files -// $td = wfTempDir(); -// $oldtextFile = fopen($oldtextName = tempnam($td, 'merge-old-'), 'w'); -// $mytextFile = fopen($mytextName = tempnam($td, 'merge-mine-'), 'w'); -// $yourtextFile = fopen($yourtextName = tempnam($td, 'merge-your-'), 'w'); -// -// # NOTE: diff3 issues a warning to stderr if any of the files does not end with -// # a newline character. To avoid this, we normalize the trailing whitespace before -// # creating the diff. -// -// fwrite($oldtextFile, rtrim($old) . "\n"); -// fclose($oldtextFile); -// fwrite($mytextFile, rtrim($mine) . "\n"); -// fclose($mytextFile); -// fwrite($yourtextFile, rtrim($yours) . "\n"); -// fclose($yourtextFile); -// -// # Check for a conflict -// $cmd = wfEscapeShellArg($wgDiff3, '-a', '--overlap-only', $mytextName, -// $oldtextName, $yourtextName); -// $handle = popen($cmd, 'r'); -// -// if (fgets($handle, 1024)) { -// $conflict = true; -// } else { -// $conflict = false; -// } -// pclose($handle); -// -// # Merge differences -// $cmd = wfEscapeShellArg($wgDiff3, '-a', '-e', '--merge', $mytextName, -// $oldtextName, $yourtextName); -// $handle = popen($cmd, 'r'); -// $result = ''; -// do { -// $data = fread($handle, 8192); -// if (strlen($data) == 0) { -// break; -// } -// $result .= $data; -// } while (true); -// pclose($handle); -// unlink($mytextName); -// unlink($oldtextName); -// unlink($yourtextName); -// -// if ($result === '' && $old !== '' && !$conflict) { -// wfDebug("Unexpected null result from diff3. Command: $cmd\n"); -// $conflict = true; -// } -// return !$conflict; -// } -// -// /** -// * Returns unified plain-text diff of two texts. -// * "Useful" for machine processing of diffs. -// * -// * @deprecated since 1.25, use DiffEngine/UnifiedDiffFormatter directly -// * -// * @param String $before The text before the changes. -// * @param String $after The text after the changes. -// * @param String $params Command-line options for the diff command. -// * @return String Unified diff of $before and $after -// */ -// function wfDiff($before, $after, $params = '-u') { -// if ($before == $after) { -// return ''; -// } -// -// global $wgDiff; -// MediaWiki\suppressWarnings(); -// $haveDiff = $wgDiff && file_exists($wgDiff); -// MediaWiki\restoreWarnings(); -// -// # This check may also protect against code injection in -// # case of broken installations. -// if (!$haveDiff) { -// wfDebug("diff executable not found\n"); -// $diffs = new Diff(explode("\n", $before), explode("\n", $after)); -// $format = new UnifiedDiffFormatter(); -// return $format->format($diffs); -// } -// -// # Make temporary files -// $td = wfTempDir(); -// $oldtextFile = fopen($oldtextName = tempnam($td, 'merge-old-'), 'w'); -// $newtextFile = fopen($newtextName = tempnam($td, 'merge-your-'), 'w'); -// -// fwrite($oldtextFile, $before); -// fclose($oldtextFile); -// fwrite($newtextFile, $after); -// fclose($newtextFile); -// -// // Get the diff of the two files -// $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg($oldtextName, $newtextName); -// -// $h = popen($cmd, 'r'); -// if (!$h) { -// unlink($oldtextName); -// unlink($newtextName); -// throw new Exception(__METHOD__ . '(): popen() failed'); -// } -// -// $diff = ''; -// -// do { -// $data = fread($h, 8192); -// if (strlen($data) == 0) { -// break; -// } -// $diff .= $data; -// } while (true); -// -// // Clean up -// pclose($h); -// unlink($oldtextName); -// unlink($newtextName); -// -// // Kill the --- and +++ lines. They're not useful. -// $diff_lines = explode("\n", $diff); -// if (isset($diff_lines[0]) && strpos($diff_lines[0], '---') === 0) { -// unset($diff_lines[0]); -// } -// if (isset($diff_lines[1]) && strpos($diff_lines[1], '+++') === 0) { -// unset($diff_lines[1]); -// } -// -// $diff = implode("\n", $diff_lines); -// -// return $diff; -// } -// -// /** -// * This function works like "use VERSION" in Perl, the program will die with a -// * backtrace if the current version of PHP is less than the version provided -// * -// * This is useful for extensions which due to their nature are not kept in sync -// * with releases, and might depend on other versions of PHP than the main code -// * -// * Note: PHP might die due to parsing errors in some cases before it ever -// * manages to call this function, such is life -// * -// * @see perldoc -f use -// * -// * @param String|int|float $req_ver The version to check, can be a String, an integer, or a float -// * @throws MWException -// */ -// function wfUsePHP($req_ver) { -// $php_ver = PHP_VERSION; -// -// if (version_compare($php_ver, (String)$req_ver, '<')) { -// throw new MWException("PHP $req_ver required--this is only $php_ver"); -// } -// } -// -// /** -// * This function works like "use VERSION" in Perl except it checks the version -// * of MediaWiki, the program will die with a backtrace if the current version -// * of MediaWiki is less than the version provided. -// * -// * This is useful for extensions which due to their nature are not kept in sync -// * with releases -// * -// * Note: Due to the behavior of PHP's version_compare() which is used in this -// * function, if you want to allow the 'wmf' development versions add a 'c' (or -// * any single letter other than 'a', 'b' or 'p') as a post-fix to your -// * targeted version number. For example if you wanted to allow any variation -// * of 1.22 use `wfUseMW('1.22c')`. Using an 'a' or 'b' instead of 'c' will -// * not result in the same comparison due to the @gplx.Internal protected logic of -// * version_compare(). -// * -// * @see perldoc -f use -// * -// * @deprecated since 1.26, use the "requires' property of extension.json -// * @param String|int|float $req_ver The version to check, can be a String, an integer, or a float -// * @throws MWException -// */ -// function wfUseMW($req_ver) { -// global $wgVersion; -// -// if (version_compare($wgVersion, (String)$req_ver, '<')) { -// throw new MWException("MediaWiki $req_ver required--this is only $wgVersion"); -// } -// } -// -// /** -// * Return the final portion of a pathname. -// * Reimplemented because PHP5's "basename()" is buggy with multibyte text. -// * https://bugs.php.net/bug.php?id=33898 -// * -// * PHP's basename() only considers '\' a pathchar on Windows and Netware. -// * We'll consider it so always, as we don't want '\s' in our Unix paths either. -// * -// * @param String $path -// * @param String $suffix String to remove if present -// * @return String -// */ -// function wfBaseName($path, $suffix = '') { -// if ($suffix == '') { -// $encSuffix = ''; -// } else { -// $encSuffix = '(?:' . preg_quote($suffix, '#') . ')?'; -// } -// -// $matches = []; -// if (preg_match("#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches)) { -// return $matches[1]; -// } else { -// return ''; -// } -// } -// -// /** -// * Generate a relative path name to the given file. -// * May explode on non-matching case-insensitive paths, -// * funky symlinks, etc. -// * -// * @param String $path Absolute destination path including target filename -// * @param String $from Absolute source path, directory only -// * @return String -// */ -// function wfRelativePath($path, $from) { -// // Normalize mixed input on Windows... -// $path = str_replace('/', DIRECTORY_SEPARATOR, $path); -// $from = str_replace('/', DIRECTORY_SEPARATOR, $from); -// -// // Trim trailing slashes -- fix for drive root -// $path = rtrim($path, DIRECTORY_SEPARATOR); -// $from = rtrim($from, DIRECTORY_SEPARATOR); -// -// $pieces = explode(DIRECTORY_SEPARATOR, dirname($path)); -// $against = explode(DIRECTORY_SEPARATOR, $from); -// -// if ($pieces[0] !== $against[0]) { -// // Non-matching Windows drive letters? -// // Return a full path. -// return $path; -// } -// -// // Trim off common prefix -// while (count($pieces) && count($against) -// && $pieces[0] == $against[0]) { -// array_shift($pieces); -// array_shift($against); -// } -// -// // relative dots to bump us to the parent -// while (count($against)) { -// array_unshift($pieces, '..'); -// array_shift($against); -// } -// -// array_push($pieces, wfBaseName($path)); -// -// return implode(DIRECTORY_SEPARATOR, $pieces); -// } -// -// /** -// * Convert an arbitrarily-long digit String from one numeric super -// * to another, optionally zero-padding to a minimum column width. -// * -// * Supports super 2 through 36; digit values 10-36 are represented -// * as lowercase letters a-z. Input is case-insensitive. -// * -// * @deprecated since 1.27 Use Wikimedia\base_convert() directly -// * -// * @param String $input Input number -// * @param int $sourceBase Base of the input number -// * @param int $destBase Desired super of the output -// * @param int $pad Minimum number of digits in the output (pad with zeroes) -// * @param boolean $lowercase Whether to output in lowercase or uppercase -// * @param String $engine Either "gmp", "bcmath", or "php" -// * @return String|boolean The output number as a String, or false on error -// */ -// function wfBaseConvert($input, $sourceBase, $destBase, $pad = 1, -// $lowercase = true, $engine = 'auto' -// ) { -// return Wikimedia\base_convert($input, $sourceBase, $destBase, $pad, $lowercase, $engine); -// } -// -// /** -// * @deprecated since 1.27, PHP's session generation isn't used with -// * MediaWiki\Session\SessionManager -// */ -// function wfFixSessionID() { -// wfDeprecated(__FUNCTION__, '1.27'); -// } -// -// /** -// * Reset the session id -// * -// * @deprecated since 1.27, use MediaWiki\Session\SessionManager instead -// * @since 1.22 -// */ -// function wfResetSessionID() { -// wfDeprecated(__FUNCTION__, '1.27'); -// $session = SessionManager::getGlobalSession(); -// $delay = $session->delaySave(); -// -// $session->resetId(); -// -// // Make sure a session is started, since that's what the old -// // wfResetSessionID() did. -// if (session_id() !== $session->getId()) { -// wfSetupSession($session->getId()); -// } -// -// ScopedCallback::consume($delay); -// } -// -// /** -// * Initialise php session -// * -// * @deprecated since 1.27, use MediaWiki\Session\SessionManager instead. -// * Generally, "using" SessionManager will be calling ->getSessionById() or -// * ::getGlobalSession() (depending on whether you were passing $sessionId -// * here), then calling $session->persist(). -// * @param boolean|String $sessionId -// */ -// function wfSetupSession($sessionId = false) { -// wfDeprecated(__FUNCTION__, '1.27'); -// -// if ($sessionId) { -// session_id($sessionId); -// } -// -// $session = SessionManager::getGlobalSession(); -// $session->persist(); -// -// if (session_id() !== $session->getId()) { -// session_id($session->getId()); -// } -// MediaWiki\quietCall('session_start'); -// } -// -// /** -// * Get an Object from the precompiled serialized directory -// * -// * @param String $name -// * @return mixed The variable on success, false on failure -// */ -// function wfGetPrecompiledData($name) { -// global $IP; -// -// $file = "$IP/serialized/$name"; -// if (file_exists($file)) { -// $blob = file_get_contents($file); -// if ($blob) { -// return unserialize($blob); -// } -// } +// if (!$haveDiff3) { +// wfDebug("diff3 not found\n"); // return false; // } // -// /** -// * Make a cache key for the local wiki. -// * -// * @param String $args,... -// * @return String -// */ -// function wfMemcKey(/*...*/) { -// return call_user_func_array( -// [ ObjectCache::getLocalClusterInstance(), 'makeKey' ], -// func_get_args() -// ); +// # Make temporary files +// $td = wfTempDir(); +// $oldtextFile = fopen($oldtextName = tempnam($td, 'merge-old-'), 'w'); +// $mytextFile = fopen($mytextName = tempnam($td, 'merge-mine-'), 'w'); +// $yourtextFile = fopen($yourtextName = tempnam($td, 'merge-your-'), 'w'); +// +// # NOTE: diff3 issues a warning to stderr if any of the files does not end with +// # a newline character. To avoid this, we normalize the trailing whitespace before +// # creating the diff. +// +// fwrite($oldtextFile, rtrim($old) . "\n"); +// fclose($oldtextFile); +// fwrite($mytextFile, rtrim($mine) . "\n"); +// fclose($mytextFile); +// fwrite($yourtextFile, rtrim($yours) . "\n"); +// fclose($yourtextFile); +// +// # Check for a conflict +// $cmd = Shell::escape($wgDiff3, '-a', '--overlap-only', $mytextName, +// $oldtextName, $yourtextName); +// $handle = popen($cmd, 'r'); +// +// $mergeAttemptResult = ''; +// do { +// $data = fread($handle, 8192); +// if (strlen($data) == 0) { +// break; +// } +// $mergeAttemptResult .= $data; +// } while (true); +// pclose($handle); +// +// $conflict = $mergeAttemptResult !== ''; +// +// # Merge differences +// $cmd = Shell::escape($wgDiff3, '-a', '-e', '--merge', $mytextName, +// $oldtextName, $yourtextName); +// $handle = popen($cmd, 'r'); +// $result = ''; +// do { +// $data = fread($handle, 8192); +// if (strlen($data) == 0) { +// break; +// } +// $result .= $data; +// } while (true); +// pclose($handle); +// unlink($mytextName); +// unlink($oldtextName); +// unlink($yourtextName); +// +// if ($result === '' && $old !== '' && !$conflict) { +// wfDebug("Unexpected null result from diff3. Command: $cmd\n"); +// $conflict = true; +// } +// return !$conflict; +// } +// +// /** +// * Returns unified plain-text diff of two texts. +// * "Useful" for machine processing of diffs. +// * +// * @deprecated since 1.25, use DiffEngine/UnifiedDiffFormatter directly +// * +// * @param string $before The text before the changes. +// * @param string $after The text after the changes. +// * @param string $params Command-line options for the diff command. +// * @return string Unified diff of $before and $after +// */ +// function wfDiff($before, $after, $params = '-u') { +// if ($before == $after) { +// return ''; // } // -// /** -// * Make a cache key for a foreign DB. -// * -// * Must match what wfMemcKey() would produce in context of the foreign wiki. -// * -// * @param String $db -// * @param String $prefix -// * @param String $args,... -// * @return String -// */ -// function wfForeignMemcKey($db, $prefix /*...*/) { -// $args = array_slice(func_get_args(), 2); -// $keyspace = $prefix ? "$db-$prefix" : $db; -// return call_user_func_array( -// [ ObjectCache::getLocalClusterInstance(), 'makeKeyInternal' ], -// [ $keyspace, $args ] -// ); +// global $wgDiff; +// Wikimedia\suppressWarnings(); +// $haveDiff = $wgDiff && file_exists($wgDiff); +// Wikimedia\restoreWarnings(); +// +// # This check may also protect against code injection in +// # case of broken installations. +// if (!$haveDiff) { +// wfDebug("diff executable not found\n"); +// $diffs = new Diff(explode("\n", $before), explode("\n", $after)); +// $format = new UnifiedDiffFormatter(); +// return $format.format($diffs); // } // -// /** -// * Make a cache key with database-agnostic prefix. -// * -// * Doesn't have a wiki-specific namespace. Uses a generic 'global' prefix -// * instead. Must have a prefix as otherwise keys that use a database name -// * in the first segment will clash with wfMemcKey/wfForeignMemcKey. -// * -// * @since 1.26 -// * @param String $args,... -// * @return String -// */ -// function wfGlobalCacheKey(/*...*/) { -// return call_user_func_array( -// [ ObjectCache::getLocalClusterInstance(), 'makeGlobalKey' ], -// func_get_args() -// ); +// # Make temporary files +// $td = wfTempDir(); +// $oldtextFile = fopen($oldtextName = tempnam($td, 'merge-old-'), 'w'); +// $newtextFile = fopen($newtextName = tempnam($td, 'merge-your-'), 'w'); +// +// fwrite($oldtextFile, $before); +// fclose($oldtextFile); +// fwrite($newtextFile, $after); +// fclose($newtextFile); +// +// // Get the diff of the two files +// $cmd = "$wgDiff " . $params . ' ' . Shell::escape($oldtextName, $newtextName); +// +// $h = popen($cmd, 'r'); +// if (!$h) { +// unlink($oldtextName); +// unlink($newtextName); +// throw new Exception(__METHOD__ . '(): popen() failed'); // } // -// /** -// * Get an ASCII String identifying this wiki -// * This is used as a prefix in memcached keys -// * -// * @return String -// */ -// function wfWikiID() { -// global $wgDBprefix, $wgDBname; -// if ($wgDBprefix) { -// return "$wgDBname-$wgDBprefix"; -// } else { -// return $wgDBname; +// $diff = ''; +// +// do { +// $data = fread($h, 8192); +// if (strlen($data) == 0) { +// break; +// } +// $diff .= $data; +// } while (true); +// +// // Clean up +// pclose($h); +// unlink($oldtextName); +// unlink($newtextName); +// +// // Kill the --- and +++ lines. They're not useful. +// $diff_lines = explode("\n", $diff); +// if (isset($diff_lines[0]) && strpos($diff_lines[0], '---') === 0) { +// unset($diff_lines[0]); +// } +// if (isset($diff_lines[1]) && strpos($diff_lines[1], '+++') === 0) { +// unset($diff_lines[1]); +// } +// +// $diff = implode("\n", $diff_lines); +// +// return $diff; +// } +// +// /** +// * Return the final portion of a pathname. +// * Reimplemented because PHP5's "basename()" is buggy with multibyte text. +// * https://bugs.php.net/bug.php?id=33898 +// * +// * PHP's basename() only considers '\' a pathchar on Windows and Netware. +// * We'll consider it so always, as we don't want '\s' in our Unix paths either. +// * +// * @param string $path +// * @param string $suffix String to remove if present +// * @return string +// */ +// function wfBaseName($path, $suffix = '') { +// if ($suffix == '') { +// $encSuffix = ''; +// } else { +// $encSuffix = '(?:' . preg_quote($suffix, '#') . ')?'; +// } +// +// $matches = []; +// if (preg_match("#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches)) { +// return $matches[1]; +// } else { +// return ''; +// } +// } +// +// /** +// * Generate a relative path name to the given file. +// * May explode on non-matching case-insensitive paths, +// * funky symlinks, etc. +// * +// * @param string $path Absolute destination path including target filename +// * @param string $from Absolute source path, directory only +// * @return string +// */ +// function wfRelativePath($path, $from) { +// // Normalize mixed input on Windows... +// $path = str_replace('/', DIRECTORY_SEPARATOR, $path); +// $from = str_replace('/', DIRECTORY_SEPARATOR, $from); +// +// // Trim trailing slashes -- fix for drive root +// $path = rtrim($path, DIRECTORY_SEPARATOR); +// $from = rtrim($from, DIRECTORY_SEPARATOR); +// +// $pieces = explode(DIRECTORY_SEPARATOR, dirname($path)); +// $against = explode(DIRECTORY_SEPARATOR, $from); +// +// if ($pieces[0] !== $against[0]) { +// // Non-matching Windows drive letters? +// // Return a full path. +// return $path; +// } +// +// // Trim off common prefix +// while (count($pieces) && count($against) +// && $pieces[0] == $against[0]) { +// array_shift($pieces); +// array_shift($against); +// } +// +// // relative dots to bump us to the parent +// while (count($against)) { +// array_unshift($pieces, '..'); +// array_shift($against); +// } +// +// array_push($pieces, wfBaseName($path)); +// +// return implode(DIRECTORY_SEPARATOR, $pieces); +// } +// +// /** +// * Reset the session id +// * +// * @deprecated since 1.27, use MediaWiki\Session\SessionManager instead +// * @since 1.22 +// */ +// function wfResetSessionID() { +// wfDeprecated(__FUNCTION__, '1.27'); +// $session = SessionManager::getGlobalSession(); +// $delay = $session.delaySave(); +// +// $session.resetId(); +// +// // Make sure a session is started, since that's what the old +// // wfResetSessionID() did. +// if (session_id() !== $session.getId()) { +// wfSetupSession($session.getId()); +// } +// +// ScopedCallback::consume($delay); +// } +// +// /** +// * Initialise php session +// * +// * @deprecated since 1.27, use MediaWiki\Session\SessionManager instead. +// * Generally, "using" SessionManager will be calling .getSessionById() or +// * ::getGlobalSession() (depending on whether you were passing $sessionId +// * here), then calling $session.persist(). +// * @param bool|string $sessionId +// */ +// function wfSetupSession($sessionId = false) { +// wfDeprecated(__FUNCTION__, '1.27'); +// +// if ($sessionId) { +// session_id($sessionId); +// } +// +// $session = SessionManager::getGlobalSession(); +// $session.persist(); +// +// if (session_id() !== $session.getId()) { +// session_id($session.getId()); +// } +// Wikimedia\quietCall('session_start'); +// } +// +// /** +// * Get an object from the precompiled serialized directory +// * +// * @param string $name +// * @return mixed The variable on success, false on failure +// */ +// function wfGetPrecompiledData($name) { +// global $IP; +// +// $file = "$IP/serialized/$name"; +// if (file_exists($file)) { +// $blob = file_get_contents($file); +// if ($blob) { +// return unserialize($blob); +// } +// } +// return false; +// } +// +// /** +// * Make a cache key for the local wiki. +// * +// * @deprecated since 1.30 Call makeKey on a BagOStuff instance +// * @param string ...$args +// * @return string +// */ +// function wfMemcKey(...$args) { +// return ObjectCache::getLocalClusterInstance().makeKey(...$args); +// } +// +// /** +// * Make a cache key for a foreign DB. +// * +// * Must match what wfMemcKey() would produce in context of the foreign wiki. +// * +// * @param string $db +// * @param string $prefix +// * @param string ...$args +// * @return string +// */ +// function wfForeignMemcKey($db, $prefix, ...$args) { +// $keyspace = $prefix ? "$db-$prefix" : $db; +// return ObjectCache::getLocalClusterInstance().makeKeyInternal($keyspace, $args); +// } +// +// /** +// * Make a cache key with database-agnostic prefix. +// * +// * Doesn't have a wiki-specific namespace. Uses a generic 'global' prefix +// * instead. Must have a prefix as otherwise keys that use a database name +// * in the first segment will clash with wfMemcKey/wfForeignMemcKey. +// * +// * @deprecated since 1.30 Call makeGlobalKey on a BagOStuff instance +// * @since 1.26 +// * @param string ...$args +// * @return string +// */ +// function wfGlobalCacheKey(...$args) { +// return ObjectCache::getLocalClusterInstance().makeGlobalKey(...$args); +// } +// +// /** +// * Get an ASCII string identifying this wiki +// * This is used as a prefix in memcached keys +// * +// * @return string +// */ +// function wfWikiID() { +// global $wgDBprefix, $wgDBname; +// if ($wgDBprefix) { +// return "$wgDBname-$wgDBprefix"; +// } else { +// return $wgDBname; +// } +// } +// +// /** +// * Get a Database object. +// * +// * @param int $db Index of the connection to get. May be DB_MASTER for the +// * master (for write queries), DB_REPLICA for potentially lagged read +// * queries, or an integer >= 0 for a particular server. +// * +// * @param string|string[] $groups Query groups. An array of group names that this query +// * belongs to. May contain a single string if the query is only +// * in one group. +// * +// * @param string|bool $wiki The wiki ID, or false for the current wiki +// * +// * Note: multiple calls to wfGetDB(DB_REPLICA) during the course of one request +// * will always return the same object, unless the underlying connection or load +// * balancer is manually destroyed. +// * +// * Note 2: use $this.getDB() in maintenance scripts that may be invoked by +// * updater to ensure that a proper database is being updated. +// * +// * @todo Replace calls to wfGetDB with calls to LoadBalancer::getConnection() +// * on an injected instance of LoadBalancer. +// * +// * @return \Wikimedia\Rdbms\Database +// */ +// function wfGetDB($db, $groups = [], $wiki = false) { +// return wfGetLB($wiki).getConnection($db, $groups, $wiki); +// } +// +// /** +// * Get a load balancer object. +// * +// * @deprecated since 1.27, use MediaWikiServices::getInstance().getDBLoadBalancer() +// * or MediaWikiServices::getInstance().getDBLoadBalancerFactory() instead. +// * +// * @param string|bool $wiki Wiki ID, or false for the current wiki +// * @return \Wikimedia\Rdbms\LoadBalancer +// */ +// function wfGetLB($wiki = false) { +// if ($wiki === false) { +// return MediaWikiServices::getInstance().getDBLoadBalancer(); +// } else { +// $factory = MediaWikiServices::getInstance().getDBLoadBalancerFactory(); +// return $factory.getMainLB($wiki); +// } +// } +// +// /** +// * Get the load balancer factory object +// * +// * @deprecated since 1.27, use MediaWikiServices::getInstance().getDBLoadBalancerFactory() instead. +// * +// * @return \Wikimedia\Rdbms\LBFactory +// */ +// function wfGetLBFactory() { +// return MediaWikiServices::getInstance().getDBLoadBalancerFactory(); +// } +// +// /** +// * Find a file. +// * Shortcut for RepoGroup::singleton().findFile() +// * +// * @param string|Title $title String or Title object +// * @param array $options Associative array of options (see RepoGroup::findFile) +// * @return File|bool File, or false if the file does not exist +// */ +// function wfFindFile($title, $options = []) { +// return RepoGroup::singleton().findFile($title, $options); +// } +// +// /** +// * Get an object referring to a locally registered file. +// * Returns a valid placeholder object if the file does not exist. +// * +// * @param Title|string $title +// * @return LocalFile|null A File, or null if passed an invalid Title +// */ +// function wfLocalFile($title) { +// return RepoGroup::singleton().getLocalRepo().newFile($title); +// } +// +// /** +// * Should low-performance queries be disabled? +// * +// * @return bool +// * @codeCoverageIgnore +// */ +// function wfQueriesMustScale() { +// global $wgMiserMode; +// return $wgMiserMode +// || (SiteStats::pages() > 100000 +// && SiteStats::edits() > 1000000 +// && SiteStats::users() > 10000); +// } +// +// /** +// * Get the path to a specified script file, respecting file +// * extensions; this is a wrapper around $wgScriptPath etc. +// * except for 'index' and 'load' which use $wgScript/$wgLoadScript +// * +// * @param string $script Script filename, sans extension +// * @return string +// */ +// function wfScript($script = 'index') { +// global $wgScriptPath, $wgScript, $wgLoadScript; +// if ($script === 'index') { +// return $wgScript; +// } elseif ($script === 'load') { +// return $wgLoadScript; +// } else { +// return "{$wgScriptPath}/{$script}.php"; +// } +// } +// +// /** +// * Get the script URL. +// * +// * @return string Script URL +// */ +// function wfGetScriptUrl() { +// if (isset($_SERVER['SCRIPT_NAME'])) { +// /* as it was called, minus the query string. +// * +// * Some sites use Apache rewrite rules to handle subdomains, +// * and have PHP set up in a weird way that causes PHP_SELF +// * to contain the rewritten URL instead of the one that the +// * outside world sees. +// * +// * If in this mode, use SCRIPT_URL instead, which mod_rewrite +// * provides containing the "before" URL. +// */ +// return $_SERVER['SCRIPT_NAME']; +// } else { +// return $_SERVER['URL']; +// } +// } +// +// /** +// * Convenience function converts boolean values into "true" +// * or "false" (string) values +// * +// * @param bool $value +// * @return string +// */ +// function wfBoolToStr($value) { +// return $value ? 'true' : 'false'; +// } +// +// /** +// * Get a platform-independent path to the null file, e.g. /dev/null +// * +// * @return string +// */ +// function wfGetNull() { +// return wfIsWindows() ? 'NUL' : '/dev/null'; +// } +// +// /** +// * Waits for the replica DBs to catch up to the master position +// * +// * Use this when updating very large numbers of rows, as in maintenance scripts, +// * to avoid causing too much lag. Of course, this is a no-op if there are no replica DBs. +// * +// * By default this waits on the main DB cluster of the current wiki. +// * If $cluster is set to "*" it will wait on all DB clusters, including +// * external ones. If the lag being waiting on is caused by the code that +// * does this check, it makes since to use $ifWritesSince, particularly if +// * cluster is "*", to avoid excess overhead. +// * +// * Never call this function after a big DB write that is still in a transaction. +// * This only makes sense after the possible lag inducing changes were committed. +// * +// * @param float|null $ifWritesSince Only wait if writes were done since this UNIX timestamp +// * @param string|bool $wiki Wiki identifier accepted by wfGetLB +// * @param string|bool $cluster Cluster name accepted by LBFactory. Default: false. +// * @param int|null $timeout Max wait time. Default: 60 seconds (cli), 1 second (web) +// * @return bool Success (able to connect and no timeouts reached) +// * @deprecated since 1.27 Use LBFactory::waitForReplication +// */ +// function wfWaitForSlaves( +// $ifWritesSince = null, $wiki = false, $cluster = false, $timeout = null +// ) { +// $lbFactory = MediaWikiServices::getInstance().getDBLoadBalancerFactory(); +// +// if ($cluster === '*') { +// $cluster = false; +// $domain = false; +// } elseif ($wiki === false) { +// $domain = $lbFactory.getLocalDomainID(); +// } else { +// $domain = $wiki; +// } +// +// $opts = [ +// 'domain' => $domain, +// 'cluster' => $cluster, +// // B/C: first argument used to be "max seconds of lag"; ignore such values +// 'ifWritesSince' => ($ifWritesSince > 1e9) ? $ifWritesSince : null +// ]; +// if ($timeout !== null) { +// $opts['timeout'] = $timeout; +// } +// +// return $lbFactory.waitForReplication($opts); +// } +// +// /** +// * Count down from $seconds to zero on the terminal, with a one-second pause +// * between showing each number. For use in command-line scripts. +// * +// * @deprecated since 1.31, use Maintenance::countDown() +// * +// * @codeCoverageIgnore +// * @param int $seconds +// */ +// function wfCountDown($seconds) { +// wfDeprecated(__FUNCTION__, '1.31'); +// for ($i = $seconds; $i >= 0; $i--) { +// if ($i != $seconds) { +// echo str_repeat("\x08", strlen($i + 1)); +// } +// echo $i; +// flush(); +// if ($i) { +// sleep(1); +// } +// } +// echo "\n"; +// } +// +// /** +// * Replace all invalid characters with '-'. +// * Additional characters can be defined in $wgIllegalFileChars (see T22489). +// * By default, $wgIllegalFileChars includes ':', '/', '\'. +// * +// * @param string $name Filename to process +// * @return string +// */ +// function wfStripIllegalFilenameChars($name) { +// global $wgIllegalFileChars; +// $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : ''; +// $name = preg_replace( +// "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/", +// '-', +// $name +// ); +// // $wgIllegalFileChars may not include '/' and '\', so we still need to do this +// $name = wfBaseName($name); +// return $name; +// } +// +// /** +// * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit +// * +// * @return int Resulting value of the memory limit. +// */ +// function wfMemoryLimit() { +// global $wgMemoryLimit; +// $memlimit = wfShorthandToInteger(ini_get('memory_limit')); +// if ($memlimit != -1) { +// $conflimit = wfShorthandToInteger($wgMemoryLimit); +// if ($conflimit == -1) { +// wfDebug("Removing PHP's memory limit\n"); +// Wikimedia\suppressWarnings(); +// ini_set('memory_limit', $conflimit); +// Wikimedia\restoreWarnings(); +// return $conflimit; +// } elseif ($conflimit > $memlimit) { +// wfDebug("Raising PHP's memory limit to $conflimit bytes\n"); +// Wikimedia\suppressWarnings(); +// ini_set('memory_limit', $conflimit); +// Wikimedia\restoreWarnings(); +// return $conflimit; +// } +// } +// return $memlimit; +// } +// +// /** +// * Set PHP's time limit to the larger of php.ini or $wgTransactionalTimeLimit +// * +// * @return int Prior time limit +// * @since 1.26 +// */ +// function wfTransactionalTimeLimit() { +// global $wgTransactionalTimeLimit; +// +// $timeLimit = ini_get('max_execution_time'); +// // Note that CLI scripts use 0 +// if ($timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit) { +// set_time_limit($wgTransactionalTimeLimit); +// } +// +// ignore_user_abort(true); // ignore client disconnects +// +// return $timeLimit; +// } +// +// /** +// * Converts shorthand byte notation to integer form +// * +// * @param string $string +// * @param int $default Returned if $string is empty +// * @return int +// */ +// function wfShorthandToInteger($string = '', $default = -1) { +// $string = trim($string); +// if ($string === '') { +// return $default; +// } +// $last = $string[strlen($string) - 1]; +// $val = intval($string); +// switch ($last) { +// case 'g': +// case 'G': +// $val *= 1024; +// // break intentionally missing +// case 'm': +// case 'M': +// $val *= 1024; +// // break intentionally missing +// case 'k': +// case 'K': +// $val *= 1024; +// } +// +// return $val; +// } +// +// /** +// * Get the normalised IETF language tag +// * See unit test for examples. +// * See mediawiki.language.bcp47 for the JavaScript implementation. +// * +// * @deprecated since 1.31, use LanguageCode::bcp47() directly. +// * +// * @param string $code The language code. +// * @return string The language code which complying with BCP 47 standards. +// */ +// function wfBCP47($code) { +// wfDeprecated(__METHOD__, '1.31'); +// return LanguageCode::bcp47($code); +// } +// +// /** +// * Get a specific cache object. +// * +// * @deprecated since 1.32, use ObjectCache::getInstance() instead +// * @param int|string $cacheType A CACHE_* constants, or other key in $wgObjectCaches +// * @return BagOStuff +// */ +// function wfGetCache($cacheType) { +// return ObjectCache::getInstance($cacheType); +// } +// +// /** +// * Get the main cache object +// * +// * @deprecated since 1.32, use ObjectCache::getLocalClusterInstance() instead +// * @return BagOStuff +// */ +// function wfGetMainCache() { +// return ObjectCache::getLocalClusterInstance(); +// } +// +// /** +// * Get the cache object used by the message cache +// * +// * @return BagOStuff +// */ +// function wfGetMessageCacheStorage() { +// global $wgMessageCacheType; +// return ObjectCache::getInstance($wgMessageCacheType); +// } +// +// /** +// * Wrapper around php's unpack. +// * +// * @param string $format The format string (See php's docs) +// * @param string $data A binary string of binary data +// * @param int|bool $length The minimum length of $data or false. This is to +// * prevent reading beyond the end of $data. false to disable the check. +// * +// * Also be careful when using this function to read unsigned 32 bit integer +// * because php might make it negative. +// * +// * @throws MWException If $data not long enough, or if unpack fails +// * @return array Associative array of the extracted data +// */ +// function wfUnpack($format, $data, $length = false) { +// if ($length !== false) { +// $realLen = strlen($data); +// if ($realLen < $length) { +// throw new MWException("Tried to use wfUnpack on a " +// . "string of length $realLen, but needed one " +// . "of at least length $length." +// ); // } // } // -// /** -// * Split a wiki ID into DB name and table prefix -// * -// * @param String $wiki -// * -// * @return array -// */ -// function wfSplitWikiID($wiki) { -// $bits = explode('-', $wiki, 2); -// if (count($bits) < 2) { -// $bits[] = ''; +// Wikimedia\suppressWarnings(); +// $result = unpack($format, $data); +// Wikimedia\restoreWarnings(); +// +// if ($result === false) { +// // If it cannot extract the packed data. +// throw new MWException("unpack could not unpack binary data"); +// } +// return $result; +// } +// +// /** +// * Determine if an image exists on the 'bad image list'. +// * +// * The format of MediaWiki:Bad_image_list is as follows: +// * * Only list items (lines starting with "*") are considered +// * * The first link on a line must be a link to a bad image +// * * Any subsequent links on the same line are considered to be exceptions, +// * i.e. articles where the image may occur inline. +// * +// * @param string $name The image name to check +// * @param Title|bool $contextTitle The page on which the image occurs, if known +// * @param string|null $blacklist Wikitext of a file blacklist +// * @return bool +// */ +// function wfIsBadImage($name, $contextTitle = false, $blacklist = null) { +// # Handle redirects; callers almost always hit wfFindFile() anyway, +// # so just use that method because it has a fast process cache. +// $file = wfFindFile($name); // get the final name +// $name = $file ? $file.getTitle().getDBkey() : $name; +// +// # Run the extension hook +// $bad = false; +// if (!Hooks::run('BadImage', [ $name, &$bad ])) { +// return (bool)$bad; +// } +// +// $cache = ObjectCache::getLocalServerInstance('hash'); +// $key = $cache.makeKey( +// 'bad-image-list', ($blacklist === null) ? 'default' : md5($blacklist) +// ); +// $badImages = $cache.get($key); +// +// if ($badImages === false) { // cache miss +// if ($blacklist === null) { +// $blacklist = wfMessage('bad_image_list').inContentLanguage().plain(); // site list // } -// return $bits; -// } -// -// /** -// * Get a Database Object. -// * -// * @param int $db Index of the connection to get. May be DB_MASTER for the -// * master (for write queries), DB_REPLICA for potentially lagged read -// * queries, or an integer >= 0 for a particular server. -// * -// * @param String|String[] $groups Query groups. An array of group names that this query -// * belongs to. May contain a single String if the query is only -// * in one group. -// * -// * @param String|boolean $wiki The wiki ID, or false for the current wiki -// * -// * Note: multiple calls to wfGetDB(DB_REPLICA) during the course of one request -// * will always return the same Object, unless the underlying connection or load -// * balancer is manually destroyed. -// * -// * Note 2: use $this->getDB() in maintenance scripts that may be invoked by -// * updater to ensure that a proper database is being updated. -// * -// * @todo Replace calls to wfGetDB with calls to LoadBalancer::getConnection() -// * on an injected instance of LoadBalancer. -// * -// * @return Database -// */ -// function wfGetDB($db, $groups = [], $wiki = false) { -// return wfGetLB($wiki)->getConnection($db, $groups, $wiki); -// } -// -// /** -// * Get a load balancer Object. -// * -// * @deprecated since 1.27, use MediaWikiServices::getDBLoadBalancer() -// * or MediaWikiServices::getDBLoadBalancerFactory() instead. -// * -// * @param String|boolean $wiki Wiki ID, or false for the current wiki -// * @return LoadBalancer -// */ -// function wfGetLB($wiki = false) { -// if ($wiki === false) { -// return \MediaWiki\MediaWikiServices::getInstance()->getDBLoadBalancer(); -// } else { -// $factory = \MediaWiki\MediaWikiServices::getInstance()->getDBLoadBalancerFactory(); -// return $factory->getMainLB($wiki); -// } -// } -// -// /** -// * Get the load balancer factory Object -// * -// * @deprecated since 1.27, use MediaWikiServices::getDBLoadBalancerFactory() instead. -// * -// * @return LBFactory -// */ -// function wfGetLBFactory() { -// return \MediaWiki\MediaWikiServices::getInstance()->getDBLoadBalancerFactory(); -// } -// -// /** -// * Find a file. -// * Shortcut for RepoGroup::singleton()->findFile() -// * -// * @param String $title String or Title Object -// * @param array $options Associative array of options (see RepoGroup::findFile) -// * @return File|boolean File, or false if the file does not exist -// */ -// function wfFindFile($title, $options = []) { -// return RepoGroup::singleton()->findFile($title, $options); -// } -// -// /** -// * Get an Object referring to a locally registered file. -// * Returns a valid placeholder Object if the file does not exist. -// * -// * @param Title|String $title -// * @return LocalFile|null A File, or null if passed an invalid Title -// */ -// function wfLocalFile($title) { -// return RepoGroup::singleton()->getLocalRepo()->newFile($title); -// } -// -// /** -// * Should low-performance queries be disabled? -// * -// * @return boolean -// * @codeCoverageIgnore -// */ -// function wfQueriesMustScale() { -// global $wgMiserMode; -// return $wgMiserMode -// || (SiteStats::pages() > 100000 -// && SiteStats::edits() > 1000000 -// && SiteStats::users() > 10000); -// } -// -// /** -// * Get the path to a specified script file, respecting file -// * extensions; this is a wrapper around $wgScriptPath etc. -// * except for 'index' and 'load' which use $wgScript/$wgLoadScript -// * -// * @param String $script Script filename, sans extension -// * @return String -// */ -// function wfScript($script = 'index') { -// global $wgScriptPath, $wgScript, $wgLoadScript; -// if ($script === 'index') { -// return $wgScript; -// } elseif ($script === 'load') { -// return $wgLoadScript; -// } else { -// return "{$wgScriptPath}/{$script}.php"; -// } -// } -// -// /** -// * Get the script URL. -// * -// * @return String Script URL -// */ -// function wfGetScriptUrl() { -// if (isset($_SERVER['SCRIPT_NAME'])) { -// /* as it was called, minus the query String. -// * -// * Some sites use Apache rewrite rules to handle subdomains, -// * and have PHP set up in a weird way that causes PHP_SELF -// * to contain the rewritten URL instead of the one that the -// * outside world sees. -// * -// * If in this mode, use SCRIPT_URL instead, which mod_rewrite -// * provides containing the "before" URL. -// */ -// return $_SERVER['SCRIPT_NAME']; -// } else { -// return $_SERVER['URL']; -// } -// } -// -// /** -// * Convenience function converts boolean values into "true" -// * or "false" (String) values -// * -// * @param boolean $value -// * @return String -// */ -// function wfBoolToStr($value) { -// return $value ? 'true' : 'false'; -// } -// -// /** -// * Get a platform-independent path to the null file, e.g. /dev/null -// * -// * @return String -// */ -// function wfGetNull() { -// return wfIsWindows() ? 'NUL' : '/dev/null'; -// } -// -// /** -// * Waits for the replica DBs to catch up to the master position -// * -// * Use this when updating very large numbers of rows, as in maintenance scripts, -// * to avoid causing too much lag. Of course, this is a no-op if there are no replica DBs. -// * -// * By default this waits on the main DB cluster of the current wiki. -// * If $cluster is set to "*" it will wait on all DB clusters, including -// * external ones. If the lag being waiting on is caused by the code that -// * does this check, it makes since to use $ifWritesSince, particularly if -// * cluster is "*", to avoid excess overhead. -// * -// * Never call this function after a big DB write that is still in a transaction. -// * This only makes sense after the possible lag inducing changes were committed. -// * -// * @param float|null $ifWritesSince Only wait if writes were done since this UNIX timestamp -// * @param String|boolean $wiki Wiki identifier accepted by wfGetLB -// * @param String|boolean $cluster Cluster name accepted by LBFactory. Default: false. -// * @param int|null $timeout Max wait time. Default: 1 day (cli), ~10 seconds (web) -// * @return boolean Success (able to connect and no timeouts reached) -// * @deprecated since 1.27 Use LBFactory::waitForReplication -// */ -// function wfWaitForSlaves( -// $ifWritesSince = null, $wiki = false, $cluster = false, $timeout = null -// ) { -// if ($timeout === null) { -// $timeout = (PHP_SAPI === 'cli') ? 86400 : 10; -// } -// -// if ($cluster === '*') { -// $cluster = false; -// $wiki = false; -// } elseif ($wiki === false) { -// $wiki = wfWikiID(); -// } -// -// try { -// wfGetLBFactory()->waitForReplication([ -// 'wiki' => $wiki, -// 'cluster' => $cluster, -// 'timeout' => $timeout, -// // B/C: first argument used to be "max seconds of lag"; ignore such values -// 'ifWritesSince' => ($ifWritesSince > 1e9) ? $ifWritesSince : null -// ]); -// } catch (DBReplicationWaitError $e) { -// return false; -// } -// -// return true; -// } -// -// /** -// * Count down from $seconds to zero on the terminal, with a one-second pause -// * between showing each number. For use in command-line scripts. -// * -// * @codeCoverageIgnore -// * @param int $seconds -// */ -// function wfCountDown($seconds) { -// for ($i = $seconds; $i >= 0; $i--) { -// if ($i != $seconds) { -// echo str_repeat("\x08", strlen($i + 1)); +// # Build the list now +// $badImages = []; +// $lines = explode("\n", $blacklist); +// foreach ($lines as $line) { +// # List items only +// if (substr($line, 0, 1) !== '*') { +// continue; // } -// echo $i; -// flush(); -// if ($i) { -// sleep(1); +// +// # Find all links +// $m = []; +// if (!preg_match_all('/\[\[:?(.*?)\]\]/', $line, $m)) { +// continue; // } -// } -// echo "\n"; -// } // -// /** -// * Replace all invalid characters with '-'. -// * Additional characters can be defined in $wgIllegalFileChars (see T22489). -// * By default, $wgIllegalFileChars includes ':', '/', '\'. -// * -// * @param String $name Filename to process -// * @return String -// */ -// function wfStripIllegalFilenameChars($name) { -// global $wgIllegalFileChars; -// $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : ''; -// $name = preg_replace( -// "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/", -// '-', -// $name -// ); -// // $wgIllegalFileChars may not include '/' and '\', so we still need to do this -// $name = wfBaseName($name); -// return $name; -// } -// -// /** -// * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit -// * -// * @return int Resulting value of the memory limit. -// */ -// function wfMemoryLimit() { -// global $wgMemoryLimit; -// $memlimit = wfShorthandToInteger(ini_get('memory_limit')); -// if ($memlimit != -1) { -// $conflimit = wfShorthandToInteger($wgMemoryLimit); -// if ($conflimit == -1) { -// wfDebug("Removing PHP's memory limit\n"); -// MediaWiki\suppressWarnings(); -// ini_set('memory_limit', $conflimit); -// MediaWiki\restoreWarnings(); -// return $conflimit; -// } elseif ($conflimit > $memlimit) { -// wfDebug("Raising PHP's memory limit to $conflimit bytes\n"); -// MediaWiki\suppressWarnings(); -// ini_set('memory_limit', $conflimit); -// MediaWiki\restoreWarnings(); -// return $conflimit; -// } -// } -// return $memlimit; -// } -// -// /** -// * Set PHP's time limit to the larger of php.ini or $wgTransactionalTimeLimit -// * -// * @return int Prior time limit -// * @since 1.26 -// */ -// function wfTransactionalTimeLimit() { -// global $wgTransactionalTimeLimit; -// -// $timeLimit = ini_get('max_execution_time'); -// // Note that CLI scripts use 0 -// if ($timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit) { -// set_time_limit($wgTransactionalTimeLimit); -// } -// -// ignore_user_abort(true); // ignore client disconnects -// -// return $timeLimit; -// } -// -// /** -// * Converts shorthand byte notation to integer form -// * -// * @param String $String -// * @param int $default Returned if $String is empty -// * @return int -// */ -// function wfShorthandToInteger($String = '', $default = -1) { -// $String = trim($String); -// if ($String === '') { -// return $default; -// } -// $last = $String[strlen($String) - 1]; -// $val = intval($String); -// switch ($last) { -// case 'g': -// case 'G': -// $val *= 1024; -// // break intentionally missing -// case 'm': -// case 'M': -// $val *= 1024; -// // break intentionally missing -// case 'k': -// case 'K': -// $val *= 1024; -// } -// -// return $val; -// } -// -// /** -// * Get the normalised IETF language tag -// * See unit test for examples. -// * -// * @param String $code The language code. -// * @return String The language code which complying with BCP 47 standards. -// */ -// function wfBCP47($code) { -// $codeSegment = explode('-', $code); -// $codeBCP = []; -// foreach ($codeSegment as $segNo => $seg) { -// // when previous segment is x, it is a private segment and should be lc -// if ($segNo > 0 && strtolower($codeSegment[($segNo - 1)]) == 'x') { -// $codeBCP[$segNo] = strtolower($seg); -// // ISO 3166 country code -// } elseif ((strlen($seg) == 2) && ($segNo > 0)) { -// $codeBCP[$segNo] = strtoupper($seg); -// // ISO 15924 script code -// } elseif ((strlen($seg) == 4) && ($segNo > 0)) { -// $codeBCP[$segNo] = ucfirst(strtolower($seg)); -// // Use lowercase for other cases -// } else { -// $codeBCP[$segNo] = strtolower($seg); -// } -// } -// $langCode = implode('-', $codeBCP); -// return $langCode; -// } -// -// /** -// * Get a specific cache Object. -// * -// * @param int|String $cacheType A CACHE_* constants, or other key in $wgObjectCaches -// * @return BagOStuff -// */ -// function wfGetCache($cacheType) { -// return ObjectCache::getInstance($cacheType); -// } -// -// /** -// * Get the main cache Object -// * -// * @return BagOStuff -// */ -// function wfGetMainCache() { -// global $wgMainCacheType; -// return ObjectCache::getInstance($wgMainCacheType); -// } -// -// /** -// * Get the cache Object used by the message cache -// * -// * @return BagOStuff -// */ -// function wfGetMessageCacheStorage() { -// global $wgMessageCacheType; -// return ObjectCache::getInstance($wgMessageCacheType); -// } -// -// /** -// * Get the cache Object used by the parser cache -// * -// * @return BagOStuff -// */ -// function wfGetParserCacheStorage() { -// global $wgParserCacheType; -// return ObjectCache::getInstance($wgParserCacheType); -// } -// -// /** -// * Call hook functions defined in $wgHooks -// * -// * @param String $event Event name -// * @param array $args Parameters passed to hook functions -// * @param String|null $deprecatedVersion Optionally mark hook as deprecated with version number -// * -// * @return boolean True if no handler aborted the hook -// * @deprecated since 1.25 - use Hooks::run -// */ -// function wfRunHooks($event, array $args = [], $deprecatedVersion = null) { -// return Hooks::run($event, $args, $deprecatedVersion); -// } -// -// /** -// * Wrapper around php's unpack. -// * -// * @param String $format The format String (See php's docs) -// * @param String $data A binary String of binary data -// * @param int|boolean $length The minimum length of $data or false. This is to -// * prevent reading beyond the end of $data. false to disable the check. -// * -// * Also be careful when using this function to read unsigned 32 bit integer -// * because php might make it negative. -// * -// * @throws MWException If $data not long enough, or if unpack fails -// * @return array Associative array of the extracted data -// */ -// function wfUnpack($format, $data, $length = false) { -// if ($length !== false) { -// $realLen = strlen($data); -// if ($realLen < $length) { -// throw new MWException("Tried to use wfUnpack on a " -// . "String of length $realLen, but needed one " -// . "of at least length $length." -// ); -// } -// } -// -// MediaWiki\suppressWarnings(); -// $result = unpack($format, $data); -// MediaWiki\restoreWarnings(); -// -// if ($result === false) { -// // If it cannot extract the packed data. -// throw new MWException("unpack could not unpack binary data"); -// } -// return $result; -// } -// -// /** -// * Determine if an image exists on the 'bad image list'. -// * -// * The format of MediaWiki:Bad_image_list is as follows: -// * * Only list items (lines starting with "*") are considered -// * * The first link on a line must be a link to a bad image -// * * Any subsequent links on the same line are considered to be exceptions, -// * i.e. articles where the image may occur inline. -// * -// * @param String $name The image name to check -// * @param Title|boolean $contextTitle The page on which the image occurs, if known -// * @param String $blacklist Wikitext of a file blacklist -// * @return boolean -// */ -// function wfIsBadImage($name, $contextTitle = false, $blacklist = null) { -// # Handle redirects; callers almost always hit wfFindFile() anyway, -// # so just use that method because it has a fast process cache. -// $file = wfFindFile($name); // get the final name -// $name = $file ? $file->getTitle()->getDBkey() : $name; -// -// # Run the extension hook -// $bad = false; -// if (!Hooks::run('BadImage', [ $name, &$bad ])) { -// return (boolean)$bad; -// } -// -// $cache = ObjectCache::getLocalServerInstance('hash'); -// $key = wfMemcKey('bad-image-list', ($blacklist === null) ? 'default' : md5($blacklist)); -// $badImages = $cache->get($key); -// -// if ($badImages === false) { // cache miss -// if ($blacklist === null) { -// $blacklist = wfMessage('bad_image_list')->inContentLanguage()->plain(); // site list -// } -// # Build the list now -// $badImages = []; -// $lines = explode("\n", $blacklist); -// foreach ($lines as $line) { -// # List items only -// if (substr($line, 0, 1) !== '*') { -// continue; -// } -// -// # Find all links -// $m = []; -// if (!preg_match_all('/\[\[:?(.*?)\]\]/', $line, $m)) { -// continue; -// } -// -// $exceptions = []; -// $imageDBkey = false; -// foreach ($m[1] as $i => $titleText) { -// $title = Title::newFromText($titleText); -// if (!is_null($title)) { -// if ($i == 0) { -// $imageDBkey = $title->getDBkey(); -// } else { -// $exceptions[$title->getPrefixedDBkey()] = true; -// } +// $exceptions = []; +// $imageDBkey = false; +// foreach ($m[1] as $i => $titleText) { +// $title = Title::newFromText($titleText); +// if (!is_null($title)) { +// if ($i == 0) { +// $imageDBkey = $title.getDBkey(); +// } else { +// $exceptions[$title.getPrefixedDBkey()] = true; // } // } -// -// if ($imageDBkey !== false) { -// $badImages[$imageDBkey] = $exceptions; -// } // } -// $cache->set($key, $badImages, 60); +// +// if ($imageDBkey !== false) { +// $badImages[$imageDBkey] = $exceptions; +// } // } -// -// $contextKey = $contextTitle ? $contextTitle->getPrefixedDBkey() : false; -// $bad = isset($badImages[$name]) && !isset($badImages[$name][$contextKey]); -// -// return $bad; +// $cache.set($key, $badImages, 60); // } // -// /** -// * Determine whether the client at a given source IP is likely to be able to -// * access the wiki via HTTPS. -// * -// * @param String $ip The IPv4/6 address in the normal human-readable form -// * @return boolean -// */ -// function wfCanIPUseHTTPS($ip) { -// $canDo = true; -// Hooks::run('CanIPUseHTTPS', [ $ip, &$canDo ]); -// return !!$canDo; +// $contextKey = $contextTitle ? $contextTitle.getPrefixedDBkey() : false; +// $bad = isset($badImages[$name]) && !isset($badImages[$name][$contextKey]); +// +// return $bad; +// } +// +// /** +// * Determine whether the client at a given source IP is likely to be able to +// * access the wiki via HTTPS. +// * +// * @param string $ip The IPv4/6 address in the normal human-readable form +// * @return bool +// */ +// function wfCanIPUseHTTPS($ip) { +// $canDo = true; +// Hooks::run('CanIPUseHTTPS', [ $ip, &$canDo ]); +// return (bool)$canDo; +// } +// +// /** +// * Determine input string is represents as infinity +// * +// * @param string $str The string to determine +// * @return bool +// * @since 1.25 +// */ +// function wfIsInfinity($str) { +// // These are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js). +// $infinityValues = [ 'infinite', 'indefinite', 'infinity', 'never' ]; +// return in_array($str, $infinityValues); +// } +// +// /** +// * Returns true if these thumbnail parameters match one that MediaWiki +// * requests from file description pages and/or parser output. +// * +// * $params is considered non-standard if they involve a non-standard +// * width or any non-default parameters aside from width and page number. +// * The number of possible files with standard parameters is far less than +// * that of all combinations; rate-limiting for them can thus be more generious. +// * +// * @param File $file +// * @param array $params +// * @return bool +// * @since 1.24 Moved from thumb.php to GlobalFunctions in 1.25 +// */ +// function wfThumbIsStandard(File $file, array $params) { +// global $wgThumbLimits, $wgImageLimits, $wgResponsiveImages; +// +// $multipliers = [ 1 ]; +// if ($wgResponsiveImages) { +// // These available sizes are hardcoded currently elsewhere in MediaWiki. +// // @see Linker::processResponsiveImages +// $multipliers[] = 1.5; +// $multipliers[] = 2; // } // -// /** -// * Determine input String is represents as infinity -// * -// * @param String $str The String to determine -// * @return boolean -// * @since 1.25 -// */ -// function wfIsInfinity($str) { -// $infinityValues = [ 'infinite', 'indefinite', 'infinity', 'never' ]; -// return in_array($str, $infinityValues); +// $handler = $file.getHandler(); +// if (!$handler || !isset($params['width'])) { +// return false; // } // -// /** -// * Returns true if these thumbnail parameters match one that MediaWiki -// * requests from file description pages and/or parser output. -// * -// * $params is considered non-standard if they involve a non-standard -// * width or any non-default parameters aside from width and page number. -// * The number of possible files with standard parameters is far less than -// * that of all combinations; rate-limiting for them can thus be more generious. -// * -// * @param File $file -// * @param array $params -// * @return boolean -// * @since 1.24 Moved from thumb.php to GlobalFunctions in 1.25 -// */ -// function wfThumbIsStandard(File $file, array $params) { -// global $wgThumbLimits, $wgImageLimits, $wgResponsiveImages; +// $basicParams = []; +// if (isset($params['page'])) { +// $basicParams['page'] = $params['page']; +// } // -// $multipliers = [ 1 ]; -// if ($wgResponsiveImages) { -// // These available sizes are hardcoded currently elsewhere in MediaWiki. -// // @see Linker::processResponsiveImages -// $multipliers[] = 1.5; -// $multipliers[] = 2; +// $thumbLimits = []; +// $imageLimits = []; +// // Expand limits to account for multipliers +// foreach ($multipliers as $multiplier) { +// $thumbLimits = array_merge($thumbLimits, array_map( +// function ($width) use ($multiplier) { +// return round($width * $multiplier); +// }, $wgThumbLimits) +// ); +// $imageLimits = array_merge($imageLimits, array_map( +// function ($pair) use ($multiplier) { +// return [ +// round($pair[0] * $multiplier), +// round($pair[1] * $multiplier), +// ]; +// }, $wgImageLimits) +// ); +// } +// +// // Check if the width matches one of $wgThumbLimits +// if (in_array($params['width'], $thumbLimits)) { +// $normalParams = $basicParams + [ 'width' => $params['width'] ]; +// // Append any default values to the map (e.g. "lossy", "lossless", ...) +// $handler.normaliseParams($file, $normalParams); +// } else { +// // If not, then check if the width matchs one of $wgImageLimits +// $match = false; +// foreach ($imageLimits as $pair) { +// $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ]; +// // Decide whether the thumbnail should be scaled on width or height. +// // Also append any default values to the map (e.g. "lossy", "lossless", ...) +// $handler.normaliseParams($file, $normalParams); +// // Check if this standard thumbnail size maps to the given width +// if ($normalParams['width'] == $params['width']) { +// $match = true; +// break; +// } // } +// if (!$match) { +// return false; // not standard for description pages +// } +// } // -// $handler = $file->getHandler(); -// if (!$handler || !isset($params['width'])) { +// // Check that the given values for non-page, non-width, params are just defaults +// foreach ($params as $key => $value) { +// if (!isset($normalParams[$key]) || $normalParams[$key] != $value) { // return false; // } -// -// $basicParams = []; -// if (isset($params['page'])) { -// $basicParams['page'] = $params['page']; -// } -// -// $thumbLimits = []; -// $imageLimits = []; -// // Expand limits to account for multipliers -// foreach ($multipliers as $multiplier) { -// $thumbLimits = array_merge($thumbLimits, array_map( -// function ($width) use ($multiplier) { -// return round($width * $multiplier); -// }, $wgThumbLimits) -// ); -// $imageLimits = array_merge($imageLimits, array_map( -// function ($pair) use ($multiplier) { -// return [ -// round($pair[0] * $multiplier), -// round($pair[1] * $multiplier), -// ]; -// }, $wgImageLimits) -// ); -// } -// -// // Check if the width matches one of $wgThumbLimits -// if (in_array($params['width'], $thumbLimits)) { -// $normalParams = $basicParams + [ 'width' => $params['width'] ]; -// // Append any default values to the map (e.g. "lossy", "lossless", ...) -// $handler->normaliseParams($file, $normalParams); -// } else { -// // If not, then check if the width matchs one of $wgImageLimits -// $match = false; -// foreach ($imageLimits as $pair) { -// $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ]; -// // Decide whether the thumbnail should be scaled on width or height. -// // Also append any default values to the map (e.g. "lossy", "lossless", ...) -// $handler->normaliseParams($file, $normalParams); -// // Check if this standard thumbnail size maps to the given width -// if ($normalParams['width'] == $params['width']) { -// $match = true; -// break; -// } -// } -// if (!$match) { -// return false; // not standard for description pages -// } -// } -// -// // Check that the given values for non-page, non-width, params are just defaults -// foreach ($params as $key => $value) { -// if (!isset($normalParams[$key]) || $normalParams[$key] != $value) { -// return false; -// } -// } -// -// return true; // } // -// /** -// * Merges two (possibly) 2 dimensional arrays into the target array ($baseArray). -// * -// * Values that exist in both values will be combined with += (all values of the array -// * of $newValues will be added to the values of the array of $baseArray, while values, -// * that exists in both, the value of $baseArray will be used). -// * -// * @param array $baseArray The array where you want to add the values of $newValues to -// * @param array $newValues An array with new values -// * @return array The combined array -// * @since 1.26 -// */ -// function wfArrayPlus2d(array $baseArray, array $newValues) { -// // First merge items that are in both arrays -// foreach ($baseArray as $name => &$groupVal) { -// if (isset($newValues[$name])) { -// $groupVal += $newValues[$name]; -// } -// } -// // Now add items that didn't exist yet -// $baseArray += $newValues; +// return true; +// } // -// return $baseArray; +// /** +// * Merges two (possibly) 2 dimensional arrays into the target array ($baseArray). +// * +// * Values that exist in both values will be combined with += (all values of the array +// * of $newValues will be added to the values of the array of $baseArray, while values, +// * that exists in both, the value of $baseArray will be used). +// * +// * @param array $baseArray The array where you want to add the values of $newValues to +// * @param array $newValues An array with new values +// * @return array The combined array +// * @since 1.26 +// */ +// function wfArrayPlus2d(array $baseArray, array $newValues) { +// // First merge items that are in both arrays +// foreach ($baseArray as $name => &$groupVal) { +// if (isset($newValues[$name])) { +// $groupVal += $newValues[$name]; +// } // } -} +// // Now add items that didn't exist yet +// $baseArray += $newValues; +// +// return $baseArray; +// } +// +// /** +// * Get system resource usage of current request context. +// * Invokes the getrusage(2) system call, requesting RUSAGE_SELF if on PHP5 +// * or RUSAGE_THREAD if on HHVM. Returns false if getrusage is not available. +// * +// * @since 1.24 +// * @return array|bool Resource usage data or false if no data available. +// */ +// function wfGetRusage() { +// if (!function_exists('getrusage')) { +// return false; +// } elseif (defined('HHVM_VERSION') && PHP_OS === 'Linux') { +// return getrusage(2 /* RUSAGE_THREAD */); +// } else { +// return getrusage(0 /* RUSAGE_SELF */); +// } +// } +} \ No newline at end of file diff --git a/400_xowa/src/gplx/xowa/mediawiki/includes/XomwRevision.java b/400_xowa/src/gplx/xowa/mediawiki/includes/XomwRevision.java index 72eae4d38..e830af086 100644 --- a/400_xowa/src/gplx/xowa/mediawiki/includes/XomwRevision.java +++ b/400_xowa/src/gplx/xowa/mediawiki/includes/XomwRevision.java @@ -1,6 +1,6 @@ /* XOWA: the XOWA Offline Wiki Application -Copyright (C) 2012-2017 gnosygnu@gmail.com +Copyright (C) 2012-2020 gnosygnu@gmail.com XOWA is licensed under the terms of the General Public License (GPL) Version 3, or alternatively under the terms of the Apache License Version 2.0. @@ -13,31 +13,37 @@ The terms of each license can be found in the source code repository: GPLv3 License: https://github.com/gnosygnu/xowa/blob/master/LICENSE-GPLv3.txt Apache License: https://github.com/gnosygnu/xowa/blob/master/LICENSE-APACHE2.txt */ -package gplx.xowa.mediawiki.includes; import gplx.*; import gplx.xowa.*; import gplx.xowa.mediawiki.*; -import gplx.xowa.mediawiki.includes.dao.*; +package gplx.xowa.mediawiki.includes; +import gplx.xowa.mediawiki.XophpInt_; +import gplx.xowa.mediawiki.XophpObject_; +import gplx.xowa.mediawiki.XophpType_; +import gplx.xowa.mediawiki.includes.Revision.XomwRevisionRecord; +import gplx.xowa.mediawiki.includes.content.XomwContent; +import gplx.xowa.mediawiki.includes.dao.XomwIDBAccessObject; import gplx.xowa.mediawiki.includes.libs.rdbms.database.XomwIDatabase; import gplx.xowa.mediawiki.includes.linkers.XomwLinkTarget; +import gplx.xowa.mediawiki.includes.user.XomwUser; // MW.SRC:1.33.1 /** * @+deprecated since 1.31, use RevisionRecord, RevisionStore, and BlobStore instead. */ public class XomwRevision implements XomwIDBAccessObject { -// -// /** @var RevisionRecord */ -// protected $mRecord; -// -// // Revision deletion constants -// static final DELETED_TEXT = RevisionRecord::DELETED_TEXT; -// static final DELETED_COMMENT = RevisionRecord::DELETED_COMMENT; -// static final DELETED_USER = RevisionRecord::DELETED_USER; -// static final DELETED_RESTRICTED = RevisionRecord::DELETED_RESTRICTED; -// static final SUPPRESSED_USER = RevisionRecord::SUPPRESSED_USER; -// static final SUPPRESSED_ALL = RevisionRecord::SUPPRESSED_ALL; -// -// // Audience options for accessors -// static final FOR_PUBLIC = RevisionRecord::FOR_PUBLIC; -// static final FOR_THIS_USER = RevisionRecord::FOR_THIS_USER; -// static final RAW = RevisionRecord::RAW; + + /** @var RevisionRecord */ + protected XomwRevisionRecord mRecord; + + // Revision deletion constants + static final int DELETED_TEXT = XomwRevisionRecord.DELETED_TEXT; + static final int DELETED_COMMENT = XomwRevisionRecord.DELETED_COMMENT; + static final int DELETED_USER = XomwRevisionRecord.DELETED_USER; + static final int DELETED_RESTRICTED = XomwRevisionRecord.DELETED_RESTRICTED; + static final int SUPPRESSED_USER = XomwRevisionRecord.SUPPRESSED_USER; + static final int SUPPRESSED_ALL = XomwRevisionRecord.SUPPRESSED_ALL; + + // Audience options for accessors + static final int FOR_PUBLIC = XomwRevisionRecord.FOR_PUBLIC; + static final int FOR_THIS_USER = XomwRevisionRecord.FOR_THIS_USER; + static final int RAW = XomwRevisionRecord.RAW; // // static final TEXT_CACHE_GROUP = SqlBlobStore::TEXT_CACHE_GROUP; // @@ -46,10 +52,10 @@ public class XomwRevision implements XomwIDBAccessObject { // */ // protected static function getRevisionStore($wiki = false) { // if ($wiki) { -// return MediaWikiServices::getInstance()->getRevisionStoreFactory() -// ->getRevisionStore($wiki); +// return MediaWikiServices::getInstance().getRevisionStoreFactory() +// .getRevisionStore($wiki); // } else { -// return MediaWikiServices::getInstance()->getRevisionStore(); +// return MediaWikiServices::getInstance().getRevisionStore(); // } // } // @@ -57,14 +63,14 @@ public class XomwRevision implements XomwIDBAccessObject { // * @return RevisionLookup // */ // protected static function getRevisionLookup() { -// return MediaWikiServices::getInstance()->getRevisionLookup(); +// return MediaWikiServices::getInstance().getRevisionLookup(); // } // // /** // * @return RevisionFactory // */ // protected static function getRevisionFactory() { -// return MediaWikiServices::getInstance()->getRevisionFactory(); +// return MediaWikiServices::getInstance().getRevisionFactory(); // } // // /** @@ -74,8 +80,8 @@ public class XomwRevision implements XomwIDBAccessObject { // */ // protected static function getBlobStore($wiki = false) { // $store = MediaWikiServices::getInstance() -// ->getBlobStoreFactory() -// ->newSqlBlobStore($wiki); +// .getBlobStoreFactory() +// .newSqlBlobStore($wiki); // // if (!$store instanceof SqlBlobStore) { // throw new RuntimeException( @@ -101,7 +107,7 @@ public class XomwRevision implements XomwIDBAccessObject { */ public static XomwRevision newFromId(int id) {return newFromId(id, 0);} public static XomwRevision newFromId(int id, int flags) { -// $rec = self::getRevisionLookup()->getRevisionById($id, $flags); +// $rec = self::getRevisionLookup().getRevisionById($id, $flags); // return $rec ? new Revision($rec, $flags) : null; return null; } @@ -122,7 +128,7 @@ public class XomwRevision implements XomwIDBAccessObject { */ public static XomwRevision newFromTitle(XomwLinkTarget linkTarget) {return newFromTitle(linkTarget, 0, 0);} public static XomwRevision newFromTitle(XomwLinkTarget linkTarget, int id, int flags) { -// $rec = self::getRevisionLookup()->getRevisionByTitle($linkTarget, $id, $flags); +// $rec = self::getRevisionLookup().getRevisionByTitle($linkTarget, $id, $flags); // return $rec ? new Revision($rec, $flags) : null; return null; } @@ -142,7 +148,7 @@ public class XomwRevision implements XomwIDBAccessObject { // * @return Revision|null // */ // public static function newFromPageId($pageId, $revId = 0, $flags = 0) { -// $rec = self::getRevisionLookup()->getRevisionByPageId($pageId, $revId, $flags); +// $rec = self::getRevisionLookup().getRevisionByPageId($pageId, $revId, $flags); // return $rec ? new Revision($rec, $flags) : null; // } // @@ -182,8 +188,8 @@ public class XomwRevision implements XomwIDBAccessObject { // $title = $overrides['title']; // } // if ($title !== null) { -// if (isset($row->ar_namespace) && isset($row->ar_title)) { -// $title = Title::makeTitle($row->ar_namespace, $row->ar_title); +// if (isset($row.ar_namespace) && isset($row.ar_title)) { +// $title = Title::makeTitle($row.ar_namespace, $row.ar_title); // } else { // throw new InvalidArgumentException( // 'A Title or ar_namespace and ar_title must be given' @@ -191,7 +197,7 @@ public class XomwRevision implements XomwIDBAccessObject { // } // } // -// $rec = self::getRevisionFactory()->newRevisionFromArchiveRow($row, 0, $title, $overrides); +// $rec = self::getRevisionFactory().newRevisionFromArchiveRow($row, 0, $title, $overrides); // return new Revision($rec, self::READ_NORMAL, $title); // } // @@ -209,9 +215,9 @@ public class XomwRevision implements XomwIDBAccessObject { // */ // public static function newFromRow($row) { // if (is_array($row)) { -// $rec = self::getRevisionFactory()->newMutableRevisionFromArray($row); +// $rec = self::getRevisionFactory().newMutableRevisionFromArray($row); // } else { -// $rec = self::getRevisionFactory()->newRevisionFromRow($row); +// $rec = self::getRevisionFactory().newRevisionFromRow($row); // } // // return new Revision($rec); @@ -229,7 +235,7 @@ public class XomwRevision implements XomwIDBAccessObject { // */ // public static function loadFromId($db, $id) { // wfDeprecated(__METHOD__, '1.31'); // no known callers -// $rec = self::getRevisionStore()->loadRevisionFromId($db, $id); +// $rec = self::getRevisionStore().loadRevisionFromId($db, $id); // return $rec ? new Revision($rec) : null; // } // @@ -246,7 +252,7 @@ public class XomwRevision implements XomwIDBAccessObject { // * @return Revision|null // */ // public static function loadFromPageId($db, $pageid, $id = 0) { -// $rec = self::getRevisionStore()->loadRevisionFromPageId($db, $pageid, $id); +// $rec = self::getRevisionStore().loadRevisionFromPageId($db, $pageid, $id); // return $rec ? new Revision($rec) : null; // } // @@ -263,7 +269,7 @@ public class XomwRevision implements XomwIDBAccessObject { // * @return Revision|null // */ // public static function loadFromTitle($db, $title, $id = 0) { -// $rec = self::getRevisionStore()->loadRevisionFromTitle($db, $title, $id); +// $rec = self::getRevisionStore().loadRevisionFromTitle($db, $title, $id); // return $rec ? new Revision($rec) : null; // } // @@ -281,7 +287,7 @@ public class XomwRevision implements XomwIDBAccessObject { // * @return Revision|null // */ // public static function loadFromTimestamp($db, $title, $timestamp) { -// $rec = self::getRevisionStore()->loadRevisionFromTimestamp($db, $title, $timestamp); +// $rec = self::getRevisionStore().loadRevisionFromTimestamp($db, $title, $timestamp); // return $rec ? new Revision($rec) : null; // } // @@ -334,7 +340,7 @@ public class XomwRevision implements XomwIDBAccessObject { // if ($wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW) { // // If code is using this instead of self::getQueryInfo(), there's a // // decent chance it's going to try to directly access -// // $row->rev_user or $row->rev_user_text and we can't give it +// // $row.rev_user or $row.rev_user_text and we can't give it // // useful values here once those aren't being used anymore. // throw new BadMethodCallException( // 'Cannot use ' . __METHOD__ @@ -345,7 +351,7 @@ public class XomwRevision implements XomwIDBAccessObject { // if (!($wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD)) { // // If code is using this instead of self::getQueryInfo(), there's a // // decent chance it's going to try to directly access -// // $row->rev_text_id or $row->rev_content_model and we can't give it +// // $row.rev_text_id or $row.rev_content_model and we can't give it // // useful values here once those aren't being written anymore, // // and may not exist at all. // throw new BadMethodCallException( @@ -371,7 +377,7 @@ public class XomwRevision implements XomwIDBAccessObject { // 'rev_sha1', // ]; // -// $fields += CommentStore::getStore()->getFields('rev_comment'); +// $fields += CommentStore::getStore().getFields('rev_comment'); // // if ($wgContentHandlerUseDB) { // $fields[] = 'rev_content_format'; @@ -394,7 +400,7 @@ public class XomwRevision implements XomwIDBAccessObject { // if ($wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW) { // // If code is using this instead of self::getQueryInfo(), there's a // // decent chance it's going to try to directly access -// // $row->ar_user or $row->ar_user_text and we can't give it +// // $row.ar_user or $row.ar_user_text and we can't give it // // useful values here once those aren't being used anymore. // throw new BadMethodCallException( // 'Cannot use ' . __METHOD__ @@ -405,7 +411,7 @@ public class XomwRevision implements XomwIDBAccessObject { // if (!($wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD)) { // // If code is using this instead of self::getQueryInfo(), there's a // // decent chance it's going to try to directly access -// // $row->ar_text_id or $row->ar_content_model and we can't give it +// // $row.ar_text_id or $row.ar_content_model and we can't give it // // useful values here once those aren't being written anymore, // // and may not exist at all. // throw new BadMethodCallException( @@ -432,7 +438,7 @@ public class XomwRevision implements XomwIDBAccessObject { // 'ar_sha1', // ]; // -// $fields += CommentStore::getStore()->getFields('ar_comment'); +// $fields += CommentStore::getStore().getFields('ar_comment'); // // if ($wgContentHandlerUseDB) { // $fields[] = 'ar_content_format'; @@ -492,12 +498,12 @@ public class XomwRevision implements XomwIDBAccessObject { // * - 'user': Join with the user table, and select the user name // * - 'text': Join with the text table, and select fields to load page text // * @return array With three keys: -// * - tables: (String[]) to include in the `$table` to `IDatabase->select()` -// * - fields: (String[]) to include in the `$vars` to `IDatabase->select()` -// * - joins: (array) to include in the `$join_conds` to `IDatabase->select()` +// * - tables: (String[]) to include in the `$table` to `IDatabase.select()` +// * - fields: (String[]) to include in the `$vars` to `IDatabase.select()` +// * - joins: (array) to include in the `$join_conds` to `IDatabase.select()` // */ // public static function getQueryInfo($options = []) { -// return self::getRevisionStore()->getQueryInfo($options); +// return self::getRevisionStore().getQueryInfo($options); // } // // /** @@ -506,12 +512,12 @@ public class XomwRevision implements XomwIDBAccessObject { // * @since 1.31 // * @deprecated since 1.31, use RevisionStore::getArchiveQueryInfo() instead. // * @return array With three keys: -// * - tables: (String[]) to include in the `$table` to `IDatabase->select()` -// * - fields: (String[]) to include in the `$vars` to `IDatabase->select()` -// * - joins: (array) to include in the `$join_conds` to `IDatabase->select()` +// * - tables: (String[]) to include in the `$table` to `IDatabase.select()` +// * - fields: (String[]) to include in the `$vars` to `IDatabase.select()` +// * - joins: (array) to include in the `$join_conds` to `IDatabase.select()` // */ // public static function getArchiveQueryInfo() { -// return self::getRevisionStore()->getArchiveQueryInfo(); +// return self::getRevisionStore().getArchiveQueryInfo(); // } // // /** @@ -524,7 +530,7 @@ public class XomwRevision implements XomwIDBAccessObject { // * @return array // */ // public static function getParentLengths($db, array $revIds) { -// return self::getRevisionStore()->listRevisionSizes($db, $revIds); +// return self::getRevisionStore().listRevisionSizes($db, $revIds); // } // // /** @@ -538,7 +544,7 @@ public class XomwRevision implements XomwIDBAccessObject { // global $wgUser; // // if ($row instanceof RevisionRecord) { -// $this->mRecord = $row; +// this.mRecord = $row; // } elseif (is_array($row)) { // // If no user is specified, fall back to using the global user Object, to stay // // compatible with pre-1.31 behavior. @@ -546,16 +552,16 @@ public class XomwRevision implements XomwIDBAccessObject { // $row['user'] = $wgUser; // } // -// $this->mRecord = self::getRevisionFactory()->newMutableRevisionFromArray( +// this.mRecord = self::getRevisionFactory().newMutableRevisionFromArray( // $row, // $queryFlags, -// $this->ensureTitle($row, $queryFlags, $title) +// this.ensureTitle($row, $queryFlags, $title) // ); // } elseif (is_object($row)) { -// $this->mRecord = self::getRevisionFactory()->newRevisionFromRow( +// this.mRecord = self::getRevisionFactory().newRevisionFromRow( // $row, // $queryFlags, -// $this->ensureTitle($row, $queryFlags, $title) +// this.ensureTitle($row, $queryFlags, $title) // ); // } else { // throw new InvalidArgumentException( @@ -563,7 +569,7 @@ public class XomwRevision implements XomwIDBAccessObject { // ); // } // -// Assert::postcondition($this->mRecord !== null, 'Failed to construct a RevisionRecord'); +// Assert::postcondition(this.mRecord !== null, 'Failed to construct a RevisionRecord'); // } // // /** @@ -593,19 +599,19 @@ public class XomwRevision implements XomwIDBAccessObject { // $pageId = $row['page'] ?? 0; // $revId = $row['id'] ?? 0; // } else { -// $pageId = $row->rev_page ?? 0; -// $revId = $row->rev_id ?? 0; +// $pageId = $row.rev_page ?? 0; +// $revId = $row.rev_id ?? 0; // } // // try { -// $title = self::getRevisionStore()->getTitle($pageId, $revId, $queryFlags); +// $title = self::getRevisionStore().getTitle($pageId, $revId, $queryFlags); // } catch (RevisionAccessException $ex) { // // construct a dummy title! -// wfLogWarning(__METHOD__ . ': ' . $ex->getMessage()); +// wfLogWarning(__METHOD__ . ': ' . $ex.getMessage()); // // // NOTE: this Title will only be used inside RevisionRecord // $title = Title::makeTitleSafe(NS_SPECIAL, "Badtitle/ID=$pageId"); -// $title->resetArticleID($pageId); +// $title.resetArticleID($pageId); // } // // return $title; @@ -615,7 +621,7 @@ public class XomwRevision implements XomwIDBAccessObject { // * @return RevisionRecord // */ // public function getRevisionRecord() { -// return $this->mRecord; +// return this.mRecord; // } /** @@ -624,8 +630,7 @@ public class XomwRevision implements XomwIDBAccessObject { * @return int|null */ public int getId() { -// return $this->mRecord->getId(); - return -1; + return this.mRecord.getId(); } // // /** @@ -641,8 +646,8 @@ public class XomwRevision implements XomwIDBAccessObject { // * @throws MWException // */ // public function setId($id) { -// if ($this->mRecord instanceof MutableRevisionRecord) { -// $this->mRecord->setId(intval($id)); +// if (this.mRecord instanceof MutableRevisionRecord) { +// this.mRecord.setId(intval($id)); // } else { // throw new MWException(__METHOD__ . ' is not supported on this instance'); // } @@ -663,9 +668,9 @@ public class XomwRevision implements XomwIDBAccessObject { // * @throws MWException // */ // public function setUserIdAndName($id, $name) { -// if ($this->mRecord instanceof MutableRevisionRecord) { +// if (this.mRecord instanceof MutableRevisionRecord) { // $user = User::newFromAnyId(intval($id), $name, null); -// $this->mRecord->setUser($user); +// this.mRecord.setUser($user); // } else { // throw new MWException(__METHOD__ . ' is not supported on this instance'); // } @@ -675,7 +680,7 @@ public class XomwRevision implements XomwIDBAccessObject { // * @return SlotRecord // */ // private function getMainSlotRaw() { -// return $this->mRecord->getSlot(SlotRecord::MAIN, RevisionRecord::RAW); +// return this.mRecord.getSlot(SlotRecord::MAIN, RevisionRecord::RAW); // } // // /** @@ -684,16 +689,16 @@ public class XomwRevision implements XomwIDBAccessObject { // * // * If the content is stored elsewhere, this returns null. // * -// * @deprecated since 1.31, use RevisionRecord()->getSlot()->getContentAddress() to +// * @deprecated since 1.31, use RevisionRecord().getSlot().getContentAddress() to // * get that actual address that can be used with BlobStore::getBlob(); or use // * RevisionRecord::hasSameContent() to check if two revisions have the same content. // * // * @return int|null // */ // public function getTextId() { -// $slot = $this->getMainSlotRaw(); -// return $slot->hasAddress() -// ? self::getBlobStore()->getTextIdFromAddress($slot->getAddress()) +// $slot = this.getMainSlotRaw(); +// return $slot.hasAddress() +// ? self::getBlobStore().getTextIdFromAddress($slot.getAddress()) // : null; // } // @@ -704,7 +709,7 @@ public class XomwRevision implements XomwIDBAccessObject { // * parent revision. Null indicates that the parent revision is not known. // */ // public function getParentId() { -// return $this->mRecord->getParentId(); +// return this.mRecord.getParentId(); // } // // /** @@ -714,7 +719,7 @@ public class XomwRevision implements XomwIDBAccessObject { // */ // public function getSize() { // try { -// return $this->mRecord->getSize(); +// return this.mRecord.getSize(); // } catch (RevisionAccessException $ex) { // return null; // } @@ -727,25 +732,26 @@ public class XomwRevision implements XomwIDBAccessObject { // */ // public function getSha1() { // try { -// return $this->mRecord->getSha1(); +// return this.mRecord.getSha1(); // } catch (RevisionAccessException $ex) { // return null; // } // } // -// /** -// * Returns the title of the page associated with this entry. -// * Since 1.31, this will never return null. -// * -// * Will do a query, when title is not set and id is given. -// * -// * @return Title -// */ -// public function getTitle() { -// $linkTarget = $this->mRecord->getPageAsLinkTarget(); + /** + * Returns the title of the page associated with this entry. + * Since 1.31, this will never return null. + * + * Will do a query, when title is not set and id is given. + * + * @return Title + */ + public XomwTitle getTitle() { +// $linkTarget = this.mRecord.getPageAsLinkTarget(); // return Title::newFromLinkTarget($linkTarget); -// } -// + return null; + } + // /** // * Set the title of the revision // * @@ -754,24 +760,24 @@ public class XomwRevision implements XomwIDBAccessObject { // * @param Title $title // */ // public function setTitle($title) { -// if (!$title->equals($this->getTitle())) { +// if (!$title.equals(this.getTitle())) { // throw new InvalidArgumentException( -// $title->getPrefixedText() +// $title.getPrefixedText() // . ' is not the same as ' -// . $this->mRecord->getPageAsLinkTarget()->__toString() +// . this.mRecord.getPageAsLinkTarget().__toString() // ); // } // } -// -// /** -// * Get the page ID -// * -// * @return int|null -// */ -// public function getPage() { -// return $this->mRecord->getPageId(); -// } -// + + /** + * Get the page ID + * + * @return int|null + */ + public int getPage() { + return this.mRecord.getPageId(); + } + // /** // * Fetch revision's user id if it's available to the specified audience. // * If the specified audience does not have access to it, zero will be @@ -792,8 +798,8 @@ public class XomwRevision implements XomwIDBAccessObject { // $user = $wgUser; // } // -// $user = $this->mRecord->getUser($audience, $user); -// return $user ? $user->getId() : 0; +// $user = this.mRecord.getUser($audience, $user); +// return $user ? $user.getId() : 0; // } // // /** @@ -816,8 +822,8 @@ public class XomwRevision implements XomwIDBAccessObject { // $user = $wgUser; // } // -// $user = $this->mRecord->getUser($audience, $user); -// return $user ? $user->getName() : ''; +// $user = this.mRecord.getUser($audience, $user); +// return $user ? $user.getName() : ''; // } // // /** @@ -838,22 +844,22 @@ public class XomwRevision implements XomwIDBAccessObject { // $user = $wgUser; // } // -// $comment = $this->mRecord->getComment($audience, $user); -// return $comment === null ? null : $comment->text; +// $comment = this.mRecord.getComment($audience, $user); +// return $comment === null ? null : $comment.text; // } // // /** // * @return boolean // */ // public function isMinor() { -// return $this->mRecord->isMinor(); +// return this.mRecord.isMinor(); // } // // /** // * @return int Rcid of the unpatrolled row, zero if there isn't one // */ // public function isUnpatrolled() { -// return self::getRevisionStore()->getRcIdIfUnpatrolled($this->mRecord); +// return self::getRevisionStore().getRcIdIfUnpatrolled(this.mRecord); // } // // /** @@ -866,7 +872,7 @@ public class XomwRevision implements XomwIDBAccessObject { // * @return RecentChange|null // */ // public function getRecentChange($flags = 0) { -// return self::getRevisionStore()->getRecentChange($this->mRecord, $flags); +// return self::getRevisionStore().getRecentChange(this.mRecord, $flags); // } // // /** @@ -875,7 +881,7 @@ public class XomwRevision implements XomwIDBAccessObject { // * @return boolean // */ // public function isDeleted($field) { -// return $this->mRecord->isDeleted($field); +// return this.mRecord.isDeleted($field); // } // // /** @@ -884,24 +890,25 @@ public class XomwRevision implements XomwIDBAccessObject { // * @return int // */ // public function getVisibility() { -// return $this->mRecord->getVisibility(); +// return this.mRecord.getVisibility(); // } -// -// /** -// * Fetch revision content if it's available to the specified audience. -// * If the specified audience does not have the ability to view this -// * revision, or the content could not be loaded, null will be returned. -// * -// * @param int $audience One of: -// * Revision::FOR_PUBLIC to be displayed to all users -// * Revision::FOR_THIS_USER to be displayed to $user -// * Revision::RAW get the text regardless of permissions -// * @param User|null $user User Object to check for, only if FOR_THIS_USER is passed -// * to the $audience parameter -// * @since 1.21 -// * @return Content|null -// */ -// public function getContent($audience = self::FOR_PUBLIC, User $user = null) { + + /** + * Fetch revision content if it's available to the specified audience. + * If the specified audience does not have the ability to view this + * revision, or the content could not be loaded, null will be returned. + * + * @param int $audience One of: + * Revision::FOR_PUBLIC to be displayed to all users + * Revision::FOR_THIS_USER to be displayed to $user + * Revision::RAW get the text regardless of permissions + * @param User|null $user User Object to check for, only if FOR_THIS_USER is passed + * to the $audience parameter + * @since 1.21 + * @return Content|null + */ + public XomwContent getContent() {return getContent(FOR_PUBLIC, null);} + public XomwContent getContent(int audience, XomwUser user) { // global $wgUser; // // if ($audience === self::FOR_THIS_USER && !$user) { @@ -909,13 +916,14 @@ public class XomwRevision implements XomwIDBAccessObject { // } // // try { -// return $this->mRecord->getContent(SlotRecord::MAIN, $audience, $user); +// return this.mRecord.getContent(SlotRecord::MAIN, $audience, $user); // } // catch (RevisionAccessException $e) { // return null; // } -// } -// + return null; + } + // /** // * Get original serialized data (without checking view restrictions) // * @@ -925,8 +933,8 @@ public class XomwRevision implements XomwIDBAccessObject { // * @return String // */ // public function getSerializedData() { -// $slot = $this->getMainSlotRaw(); -// return $slot->getContent()->serialize(); +// $slot = this.getMainSlotRaw(); +// return $slot.getContent().serialize(); // } // // /** @@ -942,7 +950,7 @@ public class XomwRevision implements XomwIDBAccessObject { // * see the CONTENT_MODEL_XXX constants. // */ // public function getContentModel() { -// return $this->getMainSlotRaw()->getModel(); +// return this.getMainSlotRaw().getModel(); // } // // /** @@ -957,11 +965,11 @@ public class XomwRevision implements XomwIDBAccessObject { // * see the CONTENT_FORMAT_XXX constants. // */ // public function getContentFormat() { -// $format = $this->getMainSlotRaw()->getFormat(); +// $format = this.getMainSlotRaw().getFormat(); // // if ($format === null) { // // if no format was stored along with the blob, fall back to default format -// $format = $this->getContentHandler()->getDefaultFormat(); +// $format = this.getContentHandler().getDefaultFormat(); // } // // return $format; @@ -974,21 +982,21 @@ public class XomwRevision implements XomwIDBAccessObject { // * @return ContentHandler // */ // public function getContentHandler() { -// return ContentHandler::getForModelID($this->getContentModel()); +// return ContentHandler::getForModelID(this.getContentModel()); // } // // /** // * @return String // */ // public function getTimestamp() { -// return $this->mRecord->getTimestamp(); +// return this.mRecord.getTimestamp(); // } // // /** // * @return boolean // */ // public function isCurrent() { -// return ($this->mRecord instanceof RevisionStoreRecord) && $this->mRecord->isCurrent(); +// return (this.mRecord instanceof RevisionStoreRecord) && this.mRecord.isCurrent(); // } // // /** @@ -997,8 +1005,8 @@ public class XomwRevision implements XomwIDBAccessObject { // * @return Revision|null // */ // public function getPrevious() { -// $title = $this->getTitle(); -// $rec = self::getRevisionLookup()->getPreviousRevision($this->mRecord, $title); +// $title = this.getTitle(); +// $rec = self::getRevisionLookup().getPreviousRevision(this.mRecord, $title); // return $rec ? new Revision($rec, self::READ_NORMAL, $title) : null; // } // @@ -1008,8 +1016,8 @@ public class XomwRevision implements XomwIDBAccessObject { // * @return Revision|null // */ // public function getNext() { -// $title = $this->getTitle(); -// $rec = self::getRevisionLookup()->getNextRevision($this->mRecord, $title); +// $title = this.getTitle(); +// $rec = self::getRevisionLookup().getNextRevision(this.mRecord, $title); // return $rec ? new Revision($rec, self::READ_NORMAL, $title) : null; // } // @@ -1044,7 +1052,7 @@ public class XomwRevision implements XomwIDBAccessObject { // $textField = $prefix . 'text'; // $flagsField = $prefix . 'flags'; // -// if (isset($row->$textField)) { +// if (isset($row.$textField)) { // if (!($wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD)) { // // The text field was read, but it's no longer being populated! // // We could gloss over this by using the text when it's there and loading @@ -1057,7 +1065,7 @@ public class XomwRevision implements XomwIDBAccessObject { // ); // } // -// $text = $row->$textField; +// $text = $row.$textField; // } else { // // Missing text field, we are probably looking at the MCR-enabled DB schema. // @@ -1069,28 +1077,28 @@ public class XomwRevision implements XomwIDBAccessObject { // // $store = self::getRevisionStore($wiki); // $rev = $prefix === 'ar_' -// ? $store->newRevisionFromArchiveRow($row) -// : $store->newRevisionFromRow($row); +// ? $store.newRevisionFromArchiveRow($row) +// : $store.newRevisionFromRow($row); // -// $content = $rev->getContent(SlotRecord::MAIN); -// return $content ? $content->serialize() : false; +// $content = $rev.getContent(SlotRecord::MAIN); +// return $content ? $content.serialize() : false; // } // -// if (isset($row->$flagsField)) { -// $flags = explode(',', $row->$flagsField); +// if (isset($row.$flagsField)) { +// $flags = explode(',', $row.$flagsField); // } else { // $flags = []; // } // -// $cacheKey = isset($row->old_id) -// ? SqlBlobStore::makeAddressFromTextId($row->old_id) +// $cacheKey = isset($row.old_id) +// ? SqlBlobStore::makeAddressFromTextId($row.old_id) // : null; // -// $revisionText = self::getBlobStore($wiki)->expandBlob($text, $flags, $cacheKey); +// $revisionText = self::getBlobStore($wiki).expandBlob($text, $flags, $cacheKey); // // if ($revisionText === false) { -// if (isset($row->old_id)) { -// wfLogWarning(__METHOD__ . ": Bad data in text row {$row->old_id}! "); +// if (isset($row.old_id)) { +// wfLogWarning(__METHOD__ . ": Bad data in text row {$row.old_id}! "); // } else { // wfLogWarning(__METHOD__ . ": Bad data in text row! "); // } @@ -1111,7 +1119,7 @@ public class XomwRevision implements XomwIDBAccessObject { // * @return String // */ // public static function compressRevisionText(&$text) { -// return self::getBlobStore()->compressData($text); +// return self::getBlobStore().compressData($text); // } // // /** @@ -1127,7 +1135,7 @@ public class XomwRevision implements XomwIDBAccessObject { // return false; // } // -// return self::getBlobStore()->decompressData($text, $flags); +// return self::getBlobStore().decompressData($text, $flags); // } // // /** @@ -1141,23 +1149,23 @@ public class XomwRevision implements XomwIDBAccessObject { // public function insertOn($dbw) { // global $wgUser; // -// // Note that $this->mRecord->getId() will typically return null here, but not always, +// // Note that this.mRecord.getId() will typically return null here, but not always, // // e.g. not when restoring a revision. // -// if ($this->mRecord->getUser(RevisionRecord::RAW) === null) { -// if ($this->mRecord instanceof MutableRevisionRecord) { -// $this->mRecord->setUser($wgUser); +// if (this.mRecord.getUser(RevisionRecord::RAW) === null) { +// if (this.mRecord instanceof MutableRevisionRecord) { +// this.mRecord.setUser($wgUser); // } else { // throw new MWException('Cannot insert revision with no associated user.'); // } // } // -// $rec = self::getRevisionStore()->insertRevisionOn($this->mRecord, $dbw); +// $rec = self::getRevisionStore().insertRevisionOn(this.mRecord, $dbw); // -// $this->mRecord = $rec; -// Assert::postcondition($this->mRecord !== null, 'Failed to acquire a RevisionRecord'); +// this.mRecord = $rec; +// Assert::postcondition(this.mRecord !== null, 'Failed to acquire a RevisionRecord'); // -// return $rec->getId(); +// return $rec.getId(); // } // // /** @@ -1197,7 +1205,7 @@ public class XomwRevision implements XomwIDBAccessObject { // return null; // } // -// $rec = self::getRevisionStore()->newNullRevision($dbw, $title, $comment, $minor, $user); +// $rec = self::getRevisionStore().newNullRevision($dbw, $title, $comment, $minor, $user); // // return $rec ? new Revision($rec) : null; // } @@ -1213,7 +1221,7 @@ public class XomwRevision implements XomwIDBAccessObject { // * @return boolean // */ // public function userCan($field, User $user = null) { -// return self::userCanBitfield($this->getVisibility(), $field, $user); +// return self::userCanBitfield(this.getVisibility(), $field, $user); // } // // /** @@ -1251,7 +1259,7 @@ public class XomwRevision implements XomwIDBAccessObject { // * @return String|boolean False if not found // */ // static function getTimestampFromId($title, $id, $flags = 0) { -// return self::getRevisionStore()->getTimestampFromId($title, $id, $flags); +// return self::getRevisionStore().getTimestampFromId($title, $id, $flags); // } // // /** @@ -1262,7 +1270,7 @@ public class XomwRevision implements XomwIDBAccessObject { // * @return int // */ // static function countByPageId($db, $id) { -// return self::getRevisionStore()->countRevisionsByPageId($db, $id); +// return self::getRevisionStore().countRevisionsByPageId($db, $id); // } // // /** @@ -1273,7 +1281,7 @@ public class XomwRevision implements XomwIDBAccessObject { // * @return int // */ // static function countByTitle($db, $title) { -// return self::getRevisionStore()->countRevisionsByTitle($db, $title); +// return self::getRevisionStore().countRevisionsByTitle($db, $title); // } // // /** @@ -1297,7 +1305,7 @@ public class XomwRevision implements XomwIDBAccessObject { // $db = wfGetDB($db); // } // -// return self::getRevisionStore()->userWasLastToEdit($db, $pageId, $userId, $since); +// return self::getRevisionStore().userWasLastToEdit($db, $pageId, $userId, $since); // } /** @@ -1322,7 +1330,7 @@ public class XomwRevision implements XomwIDBAccessObject { return null; } -// $record = self::getRevisionLookup()->getKnownCurrentRevision($title, $revId); +// $record = self::getRevisionLookup().getKnownCurrentRevision($title, $revId); // return $record ? new Revision($record) : false; return null; } diff --git a/400_xowa/src/gplx/xowa/mediawiki/includes/XomwTitle.java b/400_xowa/src/gplx/xowa/mediawiki/includes/XomwTitle.java index 55ea8913d..e37e88084 100644 --- a/400_xowa/src/gplx/xowa/mediawiki/includes/XomwTitle.java +++ b/400_xowa/src/gplx/xowa/mediawiki/includes/XomwTitle.java @@ -1,3 +1,13 @@ +package gplx.xowa.mediawiki.includes; +// MW.SRC:1.33.1 + +import gplx.xowa.mediawiki.XophpArray; +import gplx.xowa.mediawiki.XophpBool_; +import gplx.xowa.mediawiki.XophpInt_; +import gplx.xowa.mediawiki.XophpString_; +import gplx.xowa.mediawiki.includes.dao.XomwIDBAccessObject; +import gplx.xowa.mediawiki.includes.linkers.XomwLinkTarget; + /** * Represents a title within MediaWiki. * Optionally may contain an interwiki designation or namespace. @@ -6,159 +16,159 @@ * @note Consider using a TitleValue object instead. TitleValue is more lightweight * and does not rely on global state or the database. */ -public class XomwTitle { // implements LinkTarget, IDBAccessObject +public class XomwTitle implements XomwLinkTarget, XomwIDBAccessObject { // /** @var MapCacheLRU|null */ // private static $titleCache = null; -// -// /** -// * Title::newFromText maintains a cache to avoid expensive re-normalization of -// * commonly used titles. On a batch operation this can become a memory leak -// * if not bounded. After hitting this many titles reset the cache. -// */ -// const CACHE_MAX = 1000; -// -// /** -// * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends -// * to use the master DB -// */ -// const GAID_FOR_UPDATE = 1; -// -// /** -// * Flag for use with factory methods like newFromLinkTarget() that have -// * a $forceClone parameter. If set, the method must return a new instance. -// * Without this flag, some factory methods may return existing instances. -// * -// * @since 1.33 -// */ -// const NEW_CLONE = 'clone'; -// -// /** -// * @name Private member variables -// * Please use the accessor functions instead. -// * @private -// */ -// // @{ -// -// /** @var string Text form (spaces not underscores) of the main part */ -// public $mTextform = ''; -// -// /** @var string URL-encoded form of the main part */ -// public $mUrlform = ''; -// -// /** @var string Main part with underscores */ -// public $mDbkeyform = ''; -// -// /** @var string Database key with the initial letter in the case specified by the user */ -// protected $mUserCaseDBKey; -// -// /** @var int Namespace index, i.e. one of the NS_xxxx constants */ -// public $mNamespace = NS_MAIN; -// -// /** @var string Interwiki prefix */ -// public $mInterwiki = ''; -// -// /** @var bool Was this Title created from a string with a local interwiki prefix? */ -// private $mLocalInterwiki = false; -// -// /** @var string Title fragment (i.e. the bit after the #) */ -// public $mFragment = ''; -// -// /** @var int Article ID, fetched from the link cache on demand */ -// public $mArticleID = -1; -// -// /** @var bool|int ID of most recent revision */ -// protected $mLatestID = false; -// -// /** -// * @var bool|string ID of the page's content model, i.e. one of the -// * CONTENT_MODEL_XXX constants -// */ -// private $mContentModel = false; -// -// /** -// * @var bool If a content model was forced via setContentModel() -// * this will be true to avoid having other code paths reset it -// */ -// private $mForcedContentModel = false; -// -// /** @var int Estimated number of revisions; null of not loaded */ -// private $mEstimateRevisions; -// -// /** @var array Array of groups allowed to edit this article */ -// public $mRestrictions = []; -// -// /** -// * @var string|bool Comma-separated set of permission keys -// * indicating who can move or edit the page from the page table, (pre 1.10) rows. -// * Edit and move sections are separated by a colon -// * Example: "edit=autoconfirmed,sysop:move=sysop" -// */ -// protected $mOldRestrictions = false; -// -// /** @var bool Cascade restrictions on this page to included templates and images? */ -// public $mCascadeRestriction; -// -// /** Caching the results of getCascadeProtectionSources */ -// public $mCascadingRestrictions; -// -// /** @var array When do the restrictions on this page expire? */ -// protected $mRestrictionsExpiry = []; -// -// /** @var bool Are cascading restrictions in effect on this page? */ -// protected $mHasCascadingRestrictions; -// -// /** @var array Where are the cascading restrictions coming from on this page? */ -// public $mCascadeSources; -// -// /** @var bool Boolean for initialisation on demand */ -// public $mRestrictionsLoaded = false; -// -// /** -// * Text form including namespace/interwiki, initialised on demand -// * -// * Only public to share cache with TitleFormatter -// * -// * @private -// * @var string|null -// */ -// public $prefixedText = null; -// -// /** @var mixed Cached value for getTitleProtection (create protection) */ -// public $mTitleProtection; -// -// /** -// * @var int Namespace index when there is no namespace. Don't change the -// * following default, NS_MAIN is hardcoded in several places. See T2696. -// * Zero except in {{transclusion}} tags. -// */ -// public $mDefaultNamespace = NS_MAIN; -// -// /** @var int The page length, 0 for special pages */ -// protected $mLength = -1; -// -// /** @var null Is the article at this title a redirect? */ -// public $mRedirect = null; -// -// /** @var array Associative array of user ID -> timestamp/false */ -// private $mNotificationTimestamp = []; -// -// /** @var bool Whether a page has any subpages */ -// private $mHasSubpages; -// -// /** @var bool The (string) language code of the page's language and content code. */ -// private $mPageLanguage = false; -// -// /** @var string|bool|null The page language code from the database, null if not saved in -// * the database or false if not loaded, yet. */ -// private $mDbPageLanguage = false; -// -// /** @var TitleValue|null A corresponding TitleValue object */ -// private $mTitleValue = null; -// -// /** @var bool|null Would deleting this page be a big deletion? */ -// private $mIsBigDeletion = null; -// // @} -// + + /** + * Title::newFromText maintains a cache to avoid expensive re-normalization of + * commonly used titles. On a batch operation this can become a memory leak + * if not bounded. After hitting this many titles reset the cache. + */ + private static final int CACHE_MAX = 1000; + + /** + * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends + * to use the master DB + */ + private static final int GAID_FOR_UPDATE = 1; + + /** + * Flag for use with factory methods like newFromLinkTarget() that have + * a $forceClone parameter. If set, the method must return a new instance. + * Without this flag, some factory methods may return existing instances. + * + * @since 1.33 + */ + private static String NEW_CLONE = "clone"; + + /** + * @name Private member variables + * Please use the accessor functions instead. + * @private + */ + // @{ + + /** @var string Text form (spaces not underscores) of the main part */ + public String mTextform = ""; + + /** @var string URL-encoded form of the main part */ + public String mUrlform = ""; + + /** @var string Main part with underscores */ + public String mDbkeyform = ""; + + /** @var string Database key with the initial letter in the case specified by the user */ + protected String mUserCaseDBKey; + + /** @var int Namespace index, i.e. one of the NS_xxxx constants */ + public int mNamespace = XomwDefines.NS_MAIN; + + /** @var string Interwiki prefix */ + public String mInterwiki = ""; + + /** @var bool Was this Title created from a string with a local interwiki prefix? */ + private boolean mLocalInterwiki = false; + + /** @var string Title fragment (i.e. the bit after the #) */ + public String mFragment = ""; + + /** @var int Article ID, fetched from the link cache on demand */ + public int mArticleID = -1; + + /** @var bool|int ID of most recent revision */ + protected int mLatestID = XophpInt_.False; + + /** + * @var bool|string ID of the page's content model, i.e. one of the + * CONTENT_MODEL_XXX constants + */ + private String mContentModel = XophpString_.False; + + /** + * @var bool If a content model was forced via setContentModel() + * this will be true to avoid having other code paths reset it + */ + private boolean mForcedContentModel = false; + + /** @var int Estimated number of revisions; null of not loaded */ + private int mEstimateRevisions; + + /** @var array Array of groups allowed to edit this article */ + public XophpArray mRestrictions = new XophpArray(); + + /** + * @var string|bool Comma-separated set of permission keys + * indicating who can move or edit the page from the page table, (pre 1.10) rows. + * Edit and move sections are separated by a colon + * Example: "edit=autoconfirmed,sysop:move=sysop" + */ + protected String mOldRestrictions = XophpString_.False; + + /** @var bool Cascade restrictions on this page to included templates and images? */ + public boolean mCascadeRestriction; + + /** Caching the results of getCascadeProtectionSources */ +// public mCascadingRestrictions; + + /** @var array When do the restrictions on this page expire? */ + protected XophpArray mRestrictionsExpiry = new XophpArray(); + + /** @var bool Are cascading restrictions in effect on this page? */ + protected boolean mHasCascadingRestrictions; + + /** @var array Where are the cascading restrictions coming from on this page? */ + public XophpArray mCascadeSources; + + /** @var bool Boolean for initialisation on demand */ + public boolean mRestrictionsLoaded = false; + + /** + * Text form including namespace/interwiki, initialised on demand + * + * Only public to share cache with TitleFormatter + * + * @private + * @var string|null + */ + public String prefixedText = null; + + /** @var mixed Cached value for getTitleProtection (create protection) */ +// public mTitleProtection; + + /** + * @var int Namespace index when there is no namespace. Don't change the + * following default, NS_MAIN is hardcoded in several places. See T2696. + * Zero except in {{transclusion}} tags. + */ + public int mDefaultNamespace = XomwDefines.NS_MAIN; + + /** @var int The page length, 0 for special pages */ + protected int mLength = -1; + + /** @var null Is the article at this title a redirect? */ +// public mRedirect = null; + + /** @var array Associative array of user ID . timestamp/false */ + private XophpArray mNotificationTimestamp = new XophpArray(); + + /** @var bool Whether a page has any subpages */ + private boolean mHasSubpages; + + /** @var bool The (string) language code of the page's language and content code. */ + private boolean mPageLanguage = false; + + /** @var string|bool|null The page language code from the database, null if not saved in + * the database or false if not loaded, yet. */ + private String mDbPageLanguage = XophpString_.False; + + /** @var TitleValue|null A corresponding TitleValue object */ + private XomwTitle mTitleValue = null; + + /** @var bool|null Would deleting this page be a big deletion? */ + private boolean mIsBigDeletion = XophpBool_.Null; + // @} + // /** // * B/C kludge: provide a TitleParser for use by Title. // * Ideally, Title would have no methods that need this. @@ -168,7 +178,7 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return TitleFormatter // */ // private static function getTitleFormatter() { -// return MediaWikiServices::getInstance()->getTitleFormatter(); +// return MediaWikiServices::getInstance().getTitleFormatter(); // } // // /** @@ -180,7 +190,7 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return InterwikiLookup // */ // private static function getInterwikiLookup() { -// return MediaWikiServices::getInstance()->getInterwikiLookup(); +// return MediaWikiServices::getInstance().getInterwikiLookup(); // } // // /** @@ -197,14 +207,14 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * interwiki prefixes // * @return Title|null Title, or null on an error // */ -// public static function newFromDBkey( $key ) { +// public static function newFromDBkey($key) { // $t = new self(); -// $t->mDbkeyform = $key; +// $t.mDbkeyform = $key; // // try { -// $t->secureAndSplit(); +// $t.secureAndSplit(); // return $t; -// } catch ( MalformedTitleException $ex ) { +// } catch (MalformedTitleException $ex) { // return null; // } // } @@ -220,8 +230,8 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * // * @return Title // */ -// public static function newFromTitleValue( TitleValue $titleValue, $forceClone = '' ) { -// return self::newFromLinkTarget( $titleValue, $forceClone ); +// public static function newFromTitleValue(TitleValue $titleValue, $forceClone = "") { +// return self::newFromLinkTarget($titleValue, $forceClone); // } // // /** @@ -235,20 +245,20 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * // * @return Title // */ -// public static function newFromLinkTarget( LinkTarget $linkTarget, $forceClone = '' ) { -// if ( $linkTarget instanceof Title ) { +// public static function newFromLinkTarget(LinkTarget $linkTarget, $forceClone = "") { +// if ($linkTarget instanceof Title) { // // Special case if it's already a Title object -// if ( $forceClone === self::NEW_CLONE ) { +// if ($forceClone === self::NEW_CLONE) { // return clone $linkTarget; // } else { // return $linkTarget; // } // } // return self::makeTitle( -// $linkTarget->getNamespace(), -// $linkTarget->getText(), -// $linkTarget->getFragment(), -// $linkTarget->getInterwiki() +// $linkTarget.getNamespace(), +// $linkTarget.getText(), +// $linkTarget.getFragment(), +// $linkTarget.getInterwiki() // ); // } // @@ -272,18 +282,18 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @throws InvalidArgumentException // * @return Title|null Title or null on an error. // */ -// public static function newFromText( $text, $defaultNamespace = NS_MAIN ) { +// public static function newFromText($text, $defaultNamespace = NS_MAIN) { // // DWIM: Integers can be passed in here when page titles are used as array keys. -// if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) { -// throw new InvalidArgumentException( '$text must be a string.' ); +// if ($text !== null && !is_string($text) && !is_int($text)) { +// throw new InvalidArgumentException('$text must be a string.'); // } -// if ( $text === null ) { +// if ($text === null) { // return null; // } // // try { -// return self::newFromTextThrow( (string)$text, $defaultNamespace ); -// } catch ( MalformedTitleException $ex ) { +// return self::newFromTextThrow((string)$text, $defaultNamespace); +// } catch (MalformedTitleException $ex) { // return null; // } // } @@ -309,13 +319,13 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @throws MalformedTitleException If the title is invalid // * @return Title // */ -// public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN ) { -// if ( is_object( $text ) ) { -// throw new MWException( '$text must be a string, given an object' ); -// } elseif ( $text === null ) { +// public static function newFromTextThrow($text, $defaultNamespace = NS_MAIN) { +// if (is_object($text)) { +// throw new MWException('$text must be a string, given an object'); +// } elseif ($text === null) { // // Legacy code relies on MalformedTitleException being thrown in this case // // (happens when URL with no title in it is parsed). TODO fix -// throw new MalformedTitleException( 'title-invalid-empty' ); +// throw new MalformedTitleException('title-invalid-empty'); // } // // $titleCache = self::getTitleCache(); @@ -324,23 +334,23 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // // Title normalization and parsing can become expensive on pages with many // // links, so we can save a little time by caching them. // // In theory these are value objects and won't get changed... -// if ( $defaultNamespace == NS_MAIN ) { -// $t = $titleCache->get( $text ); -// if ( $t ) { +// if ($defaultNamespace == NS_MAIN) { +// $t = $titleCache.get($text); +// if ($t) { // return $t; // } // } // // // Convert things like é ā or 〗 into normalized (T16952) text -// $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text ); +// $filteredText = Sanitizer::decodeCharReferencesAndNormalize($text); // // $t = new Title(); -// $t->mDbkeyform = strtr( $filteredText, ' ', '_' ); -// $t->mDefaultNamespace = (int)$defaultNamespace; +// $t.mDbkeyform = strtr($filteredText, ' ', '_'); +// $t.mDefaultNamespace = (int)$defaultNamespace; // -// $t->secureAndSplit(); -// if ( $defaultNamespace == NS_MAIN ) { -// $titleCache->set( $text, $t ); +// $t.secureAndSplit(); +// if ($defaultNamespace == NS_MAIN) { +// $titleCache.set($text, $t); // } // return $t; // } @@ -349,10 +359,10 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText(). // * // * Example of wrong and broken code: -// * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) ); +// * $title = Title::newFromURL($wgRequest.getVal('title')); // * // * Example of right code: -// * $title = Title::newFromText( $wgRequest->getVal( 'title' ) ); +// * $title = Title::newFromText($wgRequest.getVal('title')); // * // * Create a new Title from URL-encoded text. Ensures that // * the given title's length does not exceed the maximum. @@ -360,22 +370,22 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param string $url The title, as might be taken from a URL // * @return Title|null The new object, or null on an error // */ -// public static function newFromURL( $url ) { +// public static function newFromURL($url) { // $t = new Title(); // // # For compatibility with old buggy URLs. "+" is usually not valid in titles, // # but some URLs used it as a space replacement and they still come // # from some external search tools. -// if ( strpos( self::legalChars(), '+' ) === false ) { -// $url = strtr( $url, '+', ' ' ); +// if (strpos(self::legalChars(), '+') === false) { +// $url = strtr($url, '+', ' '); // } // -// $t->mDbkeyform = strtr( $url, ' ', '_' ); +// $t.mDbkeyform = strtr($url, ' ', '_'); // // try { -// $t->secureAndSplit(); +// $t.secureAndSplit(); // return $t; -// } catch ( MalformedTitleException $ex ) { +// } catch (MalformedTitleException $ex) { // return null; // } // } @@ -384,8 +394,8 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return MapCacheLRU // */ // private static function getTitleCache() { -// if ( self::$titleCache === null ) { -// self::$titleCache = new MapCacheLRU( self::CACHE_MAX ); +// if (self::$titleCache === null) { +// self::$titleCache = new MapCacheLRU(self::CACHE_MAX); // } // return self::$titleCache; // } @@ -405,12 +415,12 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // 'page_len', 'page_is_redirect', 'page_latest', // ]; // -// if ( $wgContentHandlerUseDB ) { -// $fields[] = 'page_content_model'; +// if ($wgContentHandlerUseDB) { +// $fieldsnew XophpArray() = 'page_content_model'; // } // -// if ( $wgPageLanguageUseDB ) { -// $fields[] = 'page_lang'; +// if ($wgPageLanguageUseDB) { +// $fieldsnew XophpArray() = 'page_lang'; // } // // return $fields; @@ -423,16 +433,16 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param int $flags Use Title::GAID_FOR_UPDATE to use master // * @return Title|null The new object, or null on an error // */ -// public static function newFromID( $id, $flags = 0 ) { -// $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_REPLICA ); -// $row = $db->selectRow( +// public static function newFromID($id, $flags = 0) { +// $db = ($flags & self::GAID_FOR_UPDATE) ? wfGetDB(DB_MASTER) : wfGetDB(DB_REPLICA); +// $row = $db.selectRow( // 'page', // self::getSelectFields(), // [ 'page_id' => $id ], // __METHOD__ // ); -// if ( $row !== false ) { -// $title = self::newFromRow( $row ); +// if ($row !== false) { +// $title = self::newFromRow($row); // } else { // $title = null; // } @@ -443,25 +453,25 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // /** // * Make an array of titles from an array of IDs // * -// * @param int[] $ids Array of IDs -// * @return Title[] Array of Titles +// * @param intnew XophpArray() $ids Array of IDs +// * @return Titlenew XophpArray() Array of Titles // */ -// public static function newFromIDs( $ids ) { -// if ( !count( $ids ) ) { -// return []; +// public static function newFromIDs($ids) { +// if (!count($ids)) { +// return new XophpArray(); // } -// $dbr = wfGetDB( DB_REPLICA ); +// $dbr = wfGetDB(DB_REPLICA); // -// $res = $dbr->select( +// $res = $dbr.select( // 'page', // self::getSelectFields(), // [ 'page_id' => $ids ], // __METHOD__ // ); // -// $titles = []; -// foreach ( $res as $row ) { -// $titles[] = self::newFromRow( $row ); +// $titles = new XophpArray(); +// foreach ($res as $row) { +// $titlesnew XophpArray() = self::newFromRow($row); // } // return $titles; // } @@ -472,9 +482,9 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param stdClass $row Object database row (needs at least page_title,page_namespace) // * @return Title Corresponding Title // */ -// public static function newFromRow( $row ) { -// $t = self::makeTitle( $row->page_namespace, $row->page_title ); -// $t->loadFromRow( $row ); +// public static function newFromRow($row) { +// $t = self::makeTitle($row.page_namespace, $row.page_title); +// $t.loadFromRow($row); // return $t; // } // @@ -484,38 +494,38 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * // * @param stdClass|bool $row Database row // */ -// public function loadFromRow( $row ) { -// if ( $row ) { // page found -// if ( isset( $row->page_id ) ) { -// $this->mArticleID = (int)$row->page_id; +// public function loadFromRow($row) { +// if ($row) { // page found +// if (isset($row.page_id)) { +// this.mArticleID = (int)$row.page_id; // } -// if ( isset( $row->page_len ) ) { -// $this->mLength = (int)$row->page_len; +// if (isset($row.page_len)) { +// this.mLength = (int)$row.page_len; // } -// if ( isset( $row->page_is_redirect ) ) { -// $this->mRedirect = (bool)$row->page_is_redirect; +// if (isset($row.page_is_redirect)) { +// this.mRedirect = (bool)$row.page_is_redirect; // } -// if ( isset( $row->page_latest ) ) { -// $this->mLatestID = (int)$row->page_latest; +// if (isset($row.page_latest)) { +// this.mLatestID = (int)$row.page_latest; // } -// if ( !$this->mForcedContentModel && isset( $row->page_content_model ) ) { -// $this->mContentModel = (string)$row->page_content_model; -// } elseif ( !$this->mForcedContentModel ) { -// $this->mContentModel = false; # initialized lazily in getContentModel() +// if (!this.mForcedContentModel && isset($row.page_content_model)) { +// this.mContentModel = (string)$row.page_content_model; +// } elseif (!this.mForcedContentModel) { +// this.mContentModel = false; # initialized lazily in getContentModel() // } -// if ( isset( $row->page_lang ) ) { -// $this->mDbPageLanguage = (string)$row->page_lang; +// if (isset($row.page_lang)) { +// this.mDbPageLanguage = (string)$row.page_lang; // } -// if ( isset( $row->page_restrictions ) ) { -// $this->mOldRestrictions = $row->page_restrictions; +// if (isset($row.page_restrictions)) { +// this.mOldRestrictions = $row.page_restrictions; // } // } else { // page not found -// $this->mArticleID = 0; -// $this->mLength = 0; -// $this->mRedirect = false; -// $this->mLatestID = 0; -// if ( !$this->mForcedContentModel ) { -// $this->mContentModel = false; # initialized lazily in getContentModel() +// this.mArticleID = 0; +// this.mLength = 0; +// this.mRedirect = false; +// this.mLatestID = 0; +// if (!this.mForcedContentModel) { +// this.mContentModel = false; # initialized lazily in getContentModel() // } // } // } @@ -542,16 +552,16 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param string $interwiki The interwiki prefix // * @return Title The new object // */ -// public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) { +// public static function makeTitle($ns, $title, $fragment = "", $interwiki = "") { // $t = new Title(); -// $t->mInterwiki = $interwiki; -// $t->mFragment = $fragment; -// $t->mNamespace = $ns = (int)$ns; -// $t->mDbkeyform = strtr( $title, ' ', '_' ); -// $t->mArticleID = ( $ns >= 0 ) ? -1 : 0; -// $t->mUrlform = wfUrlencode( $t->mDbkeyform ); -// $t->mTextform = strtr( $title, '_', ' ' ); -// $t->mContentModel = false; # initialized lazily in getContentModel() +// $t.mInterwiki = $interwiki; +// $t.mFragment = $fragment; +// $t.mNamespace = $ns = (int)$ns; +// $t.mDbkeyform = strtr($title, ' ', '_'); +// $t.mArticleID = ($ns >= 0) ? -1 : 0; +// $t.mUrlform = wfUrlencode($t.mDbkeyform); +// $t.mTextform = strtr($title, '_', ' '); +// $t.mContentModel = false; # initialized lazily in getContentModel() // return $t; // } // @@ -570,21 +580,21 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param string $interwiki Interwiki prefix // * @return Title|null The new object, or null on an error // */ -// public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) { +// public static function makeTitleSafe($ns, $title, $fragment = "", $interwiki = "") { // // NOTE: ideally, this would just call makeTitle() and then isValid(), // // but presently, that means more overhead on a potential performance hotspot. // -// if ( !MWNamespace::exists( $ns ) ) { +// if (!MWNamespace::exists($ns)) { // return null; // } // // $t = new Title(); -// $t->mDbkeyform = self::makeName( $ns, $title, $fragment, $interwiki, true ); +// $t.mDbkeyform = self::makeName($ns, $title, $fragment, $interwiki, true); // // try { -// $t->secureAndSplit(); +// $t.secureAndSplit(); // return $t; -// } catch ( MalformedTitleException $ex ) { +// } catch (MalformedTitleException $ex) { // return null; // } // } @@ -599,10 +609,10 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return Title The new object // */ // public static function newMainPage() { -// $title = self::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() ); +// $title = self::newFromText(wfMessage('mainpage').inContentLanguage().text()); // // Don't give fatal errors if the message is broken -// if ( !$title ) { -// $title = self::newFromText( 'Main Page' ); +// if (!$title) { +// $title = self::newFromText('Main Page'); // } // return $title; // } @@ -613,20 +623,20 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param int $id The page_id of the article // * @return Title|null An object representing the article, or null if no such article was found // */ -// public static function nameOf( $id ) { -// $dbr = wfGetDB( DB_REPLICA ); +// public static function nameOf($id) { +// $dbr = wfGetDB(DB_REPLICA); // -// $s = $dbr->selectRow( +// $s = $dbr.selectRow( // 'page', // [ 'page_namespace', 'page_title' ], // [ 'page_id' => $id ], // __METHOD__ // ); -// if ( $s === false ) { +// if ($s === false) { // return null; // } // -// $n = self::makeName( $s->page_namespace, $s->page_title ); +// $n = self::makeName($s.page_namespace, $s.page_title); // return $n; // } // @@ -649,21 +659,21 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param string $byteClass // * @return string // */ -// public static function convertByteClassToUnicodeClass( $byteClass ) { -// $length = strlen( $byteClass ); +// public static function convertByteClassToUnicodeClass($byteClass) { +// $length = strlen($byteClass); // // Input token queue -// $x0 = $x1 = $x2 = ''; +// $x0 = $x1 = $x2 = ""; // // Decoded queue -// $d0 = $d1 = $d2 = ''; +// $d0 = $d1 = $d2 = ""; // // Decoded integer codepoints // $ord0 = $ord1 = $ord2 = 0; // // Re-encoded queue -// $r0 = $r1 = $r2 = ''; +// $r0 = $r1 = $r2 = ""; // // Output -// $out = ''; +// $out = ""; // // Flags // $allowUnicode = false; -// for ( $pos = 0; $pos < $length; $pos++ ) { +// for ($pos = 0; $pos < $length; $pos++) { // // Shift the queues down // $x2 = $x1; // $x1 = $x0; @@ -675,16 +685,16 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // $r1 = $r0; // // Load the current input token and decoded values // $inChar = $byteClass[$pos]; -// if ( $inChar == '\\' ) { -// if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos + 1 ) ) { +// if ($inChar == '\\') { +// if (preg_match('/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos + 1)) { // $x0 = $inChar . $m[0]; -// $d0 = chr( hexdec( $m[1] ) ); -// $pos += strlen( $m[0] ); -// } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos + 1 ) ) { +// $d0 = chr(hexdec($m[1])); +// $pos += strlen($m[0]); +// } elseif (preg_match('/[0-7]{3}/A', $byteClass, $m, 0, $pos + 1)) { // $x0 = $inChar . $m[0]; -// $d0 = chr( octdec( $m[0] ) ); -// $pos += strlen( $m[0] ); -// } elseif ( $pos + 1 >= $length ) { +// $d0 = chr(octdec($m[0])); +// $pos += strlen($m[0]); +// } elseif ($pos + 1 >= $length) { // $x0 = $d0 = '\\'; // } else { // $d0 = $byteClass[$pos + 1]; @@ -694,29 +704,29 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // } else { // $x0 = $d0 = $inChar; // } -// $ord0 = ord( $d0 ); +// $ord0 = ord($d0); // // Load the current re-encoded value -// if ( $ord0 < 32 || $ord0 == 0x7f ) { -// $r0 = sprintf( '\x%02x', $ord0 ); -// } elseif ( $ord0 >= 0x80 ) { +// if ($ord0 < 32 || $ord0 == 0x7f) { +// $r0 = sprintf('\x%02x', $ord0); +// } elseif ($ord0 >= 0x80) { // // Allow unicode if a single high-bit character appears -// $r0 = sprintf( '\x%02x', $ord0 ); +// $r0 = sprintf('\x%02x', $ord0); // $allowUnicode = true; // // @phan-suppress-next-line PhanParamSuspiciousOrder false positive -// } elseif ( strpos( '-\\[]^', $d0 ) !== false ) { +// } elseif (strpos('-\\new XophpArray()^', $d0) !== false) { // $r0 = '\\' . $d0; // } else { // $r0 = $d0; // } // // Do the output -// if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) { +// if ($x0 !== "" && $x1 === '-' && $x2 !== "") { // // Range -// if ( $ord2 > $ord0 ) { +// if ($ord2 > $ord0) { // // Empty range -// } elseif ( $ord0 >= 0x80 ) { +// } elseif ($ord0 >= 0x80) { // // Unicode range // $allowUnicode = true; -// if ( $ord2 < 0x80 ) { +// if ($ord2 < 0x80) { // // Keep the non-unicode section of the range // $out .= "$r2-\\x7F"; // } @@ -725,19 +735,19 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // $out .= "$r2-$r0"; // } // // Reset state to the initial value -// $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = ''; -// } elseif ( $ord2 < 0x80 ) { +// $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = ""; +// } elseif ($ord2 < 0x80) { // // ASCII character // $out .= $r2; // } // } -// if ( $ord1 < 0x80 ) { +// if ($ord1 < 0x80) { // $out .= $r1; // } -// if ( $ord0 < 0x80 ) { +// if ($ord0 < 0x80) { // $out .= $r0; // } -// if ( $allowUnicode ) { +// if ($allowUnicode) { // $out .= '\u0080-\uFFFF'; // } // return $out; @@ -754,19 +764,19 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * $ns instead of the localized version. // * @return string The prefixed form of the title // */ -// public static function makeName( $ns, $title, $fragment = '', $interwiki = '', +// public static function makeName($ns, $title, $fragment = "", $interwiki = "", // $canonicalNamespace = false // ) { -// if ( $canonicalNamespace ) { -// $namespace = MWNamespace::getCanonicalName( $ns ); +// if ($canonicalNamespace) { +// $namespace = MWNamespace::getCanonicalName($ns); // } else { -// $namespace = MediaWikiServices::getInstance()->getContentLanguage()->getNsText( $ns ); +// $namespace = MediaWikiServices::getInstance().getContentLanguage().getNsText($ns); // } -// $name = $namespace == '' ? $title : "$namespace:$title"; -// if ( strval( $interwiki ) != '' ) { +// $name = $namespace == "" ? $title : "$namespace:$title"; +// if (strval($interwiki) != "") { // $name = "$interwiki:$name"; // } -// if ( strval( $fragment ) != '' ) { +// if (strval($fragment) != "") { // $name .= '#' . $fragment; // } // return $name; @@ -780,9 +790,9 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * // * @return int Result of string comparison, or namespace comparison // */ -// public static function compare( LinkTarget $a, LinkTarget $b ) { -// return $a->getNamespace() <=> $b->getNamespace() -// ?: strcmp( $a->getText(), $b->getText() ); +// public static function compare(LinkTarget $a, LinkTarget $b) { +// return $a.getNamespace() <=> $b.getNamespace() +// ?: strcmp($a.getText(), $b.getText()); // } // // /** @@ -800,15 +810,15 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return bool // */ // public function isValid() { -// if ( !MWNamespace::exists( $this->mNamespace ) ) { +// if (!MWNamespace::exists(this.mNamespace)) { // return false; // } // // try { -// $parser = MediaWikiServices::getInstance()->getTitleParser(); -// $parser->parseTitle( $this->mDbkeyform, $this->mNamespace ); +// $parser = MediaWikiServices::getInstance().getTitleParser(); +// $parser.parseTitle(this.mDbkeyform, this.mNamespace); // return true; -// } catch ( MalformedTitleException $ex ) { +// } catch (MalformedTitleException $ex) { // return false; // } // } @@ -816,47 +826,47 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // /** // * Determine whether the object refers to a page within // * this project (either this wiki or a wiki with a local -// * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local ) +// * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local) // * // * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise // */ // public function isLocal() { -// if ( $this->isExternal() ) { -// $iw = self::getInterwikiLookup()->fetch( $this->mInterwiki ); -// if ( $iw ) { -// return $iw->isLocal(); +// if (this.isExternal()) { +// $iw = self::getInterwikiLookup().fetch(this.mInterwiki); +// if ($iw) { +// return $iw.isLocal(); // } // } // return true; // } -// -// /** -// * Is this Title interwiki? -// * -// * @return bool -// */ -// public function isExternal() { -// return $this->mInterwiki !== ''; -// } -// -// /** -// * Get the interwiki prefix -// * -// * Use Title::isExternal to check if a interwiki is set -// * -// * @return string Interwiki prefix -// */ -// public function getInterwiki() { -// return $this->mInterwiki; -// } -// + + /** + * Is this Title interwiki? + * + * @return bool + */ + public boolean isExternal() { + return XophpString_.eq_not(this.mInterwiki, ""); + } + + /** + * Get the interwiki prefix + * + * Use Title::isExternal to check if a interwiki is set + * + * @return string Interwiki prefix + */ + public String getInterwiki() { + return this.mInterwiki; + } + // /** // * Was this a local interwiki link? // * // * @return bool // */ // public function wasLocalInterwiki() { -// return $this->mLocalInterwiki; +// return this.mLocalInterwiki; // } // // /** @@ -866,11 +876,11 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return bool True if this is transcludable // */ // public function isTrans() { -// if ( !$this->isExternal() ) { +// if (!this.isExternal()) { // return false; // } // -// return self::getInterwikiLookup()->fetch( $this->mInterwiki )->isTranscludable(); +// return self::getInterwikiLookup().fetch(this.mInterwiki).isTranscludable(); // } // // /** @@ -879,11 +889,11 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return string|false The DB name // */ // public function getTransWikiID() { -// if ( !$this->isExternal() ) { +// if (!this.isExternal()) { // return false; // } // -// return self::getInterwikiLookup()->fetch( $this->mInterwiki )->getWikiID(); +// return self::getInterwikiLookup().fetch(this.mInterwiki).getWikiID(); // } // // /** @@ -896,50 +906,50 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return TitleValue|null // */ // public function getTitleValue() { -// if ( $this->mTitleValue === null ) { +// if (this.mTitleValue === null) { // try { -// $this->mTitleValue = new TitleValue( -// $this->mNamespace, -// $this->mDbkeyform, -// $this->mFragment, -// $this->mInterwiki +// this.mTitleValue = new TitleValue( +// this.mNamespace, +// this.mDbkeyform, +// this.mFragment, +// this.mInterwiki // ); -// } catch ( InvalidArgumentException $ex ) { -// wfDebug( __METHOD__ . ': Can\'t create a TitleValue for [[' . -// $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" ); +// } catch (InvalidArgumentException $ex) { +// wfDebug(__METHOD__ . ': Can\'t create a TitleValue for [[' . +// this.getPrefixedText() . ']]: ' . $ex.getMessage() . "\n"); // } // } // -// return $this->mTitleValue; +// return this.mTitleValue; // } -// -// /** -// * Get the text form (spaces not underscores) of the main part -// * -// * @return string Main part of the title -// */ -// public function getText() { -// return $this->mTextform; -// } -// + + /** + * Get the text form (spaces not underscores) of the main part + * + * @return string Main part of the title + */ + public String getText() { + return this.mTextform; + } + // /** // * Get the URL-encoded form of the main part // * // * @return string Main part of the title, URL-encoded // */ // public function getPartialURL() { -// return $this->mUrlform; +// return this.mUrlform; // } -// -// /** -// * Get the main part with underscores -// * -// * @return string Main part of the title, with underscores -// */ -// public function getDBkey() { -// return $this->mDbkeyform; -// } -// + + /** + * Get the main part with underscores + * + * @return string Main part of the title, with underscores + */ + public String getDBkey() { + return this.mDbkeyform; + } + // /** // * Get the DB key with the initial letter case as specified by the user // * @deprecated since 1.33; please use Title::getDBKey() instead @@ -947,23 +957,23 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return string DB key // */ // function getUserCaseDBKey() { -// if ( !is_null( $this->mUserCaseDBKey ) ) { -// return $this->mUserCaseDBKey; +// if (!is_null(this.mUserCaseDBKey)) { +// return this.mUserCaseDBKey; // } else { -// // If created via makeTitle(), $this->mUserCaseDBKey is not set. -// return $this->mDbkeyform; +// // If created via makeTitle(), this.mUserCaseDBKey is not set. +// return this.mDbkeyform; // } // } -// -// /** -// * Get the namespace index, i.e. one of the NS_xxxx constants. -// * -// * @return int Namespace index -// */ -// public function getNamespace() { -// return $this->mNamespace; -// } -// + + /** + * Get the namespace index, i.e. one of the NS_xxxx constants. + * + * @return int Namespace index + */ + public int getNamespace() { + return this.mNamespace; + } + // /** // * Get the page's content model id, see the CONTENT_MODEL_XXX constants. // * @@ -972,31 +982,31 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update // * @return string Content model id // */ -// public function getContentModel( $flags = 0 ) { -// if ( !$this->mForcedContentModel -// && ( !$this->mContentModel || $flags === self::GAID_FOR_UPDATE ) -// && $this->getArticleID( $flags ) +// public function getContentModel($flags = 0) { +// if (!this.mForcedContentModel +// && (!this.mContentModel || $flags === self::GAID_FOR_UPDATE) +// && this.getArticleID($flags) // ) { -// $linkCache = MediaWikiServices::getInstance()->getLinkCache(); -// $linkCache->addLinkObj( $this ); # in case we already had an article ID -// $this->mContentModel = $linkCache->getGoodLinkFieldObj( $this, 'model' ); +// $linkCache = MediaWikiServices::getInstance().getLinkCache(); +// $linkCache.addLinkObj(this); # in case we already had an article ID +// this.mContentModel = $linkCache.getGoodLinkFieldObj(this, 'model'); // } // -// if ( !$this->mContentModel ) { -// $this->mContentModel = ContentHandler::getDefaultModelFor( $this ); +// if (!this.mContentModel) { +// this.mContentModel = ContentHandler::getDefaultModelFor(this); // } // -// return $this->mContentModel; +// return this.mContentModel; // } // // /** // * Convenience method for checking a title's content model name // * // * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants). -// * @return bool True if $this->getContentModel() == $id +// * @return bool True if this.getContentModel() == $id // */ -// public function hasContentModel( $id ) { -// return $this->getContentModel() == $id; +// public function hasContentModel($id) { +// return this.getContentModel() == $id; // } // // /** @@ -1010,9 +1020,9 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @since 1.28 // * @param string $model CONTENT_MODEL_XXX constant // */ -// public function setContentModel( $model ) { -// $this->mContentModel = $model; -// $this->mForcedContentModel = true; +// public function setContentModel($model) { +// this.mContentModel = $model; +// this.mForcedContentModel = true; // } // // /** @@ -1021,20 +1031,20 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return string|false Namespace text // */ // public function getNsText() { -// if ( $this->isExternal() ) { +// if (this.isExternal()) { // // This probably shouldn't even happen, except for interwiki transclusion. // // If possible, use the canonical name for the foreign namespace. -// $nsText = MWNamespace::getCanonicalName( $this->mNamespace ); -// if ( $nsText !== false ) { +// $nsText = MWNamespace::getCanonicalName(this.mNamespace); +// if ($nsText !== false) { // return $nsText; // } // } // // try { // $formatter = self::getTitleFormatter(); -// return $formatter->getNamespaceName( $this->mNamespace, $this->mDbkeyform ); -// } catch ( InvalidArgumentException $ex ) { -// wfDebug( __METHOD__ . ': ' . $ex->getMessage() . "\n" ); +// return $formatter.getNamespaceName(this.mNamespace, this.mDbkeyform); +// } catch (InvalidArgumentException $ex) { +// wfDebug(__METHOD__ . ': ' . $ex.getMessage() . "\n"); // return false; // } // } @@ -1045,8 +1055,8 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return string Namespace text // */ // public function getSubjectNsText() { -// return MediaWikiServices::getInstance()->getContentLanguage()-> -// getNsText( MWNamespace::getSubject( $this->mNamespace ) ); +// return MediaWikiServices::getInstance().getContentLanguage(). +// getNsText(MWNamespace::getSubject(this.mNamespace)); // } // // /** @@ -1055,8 +1065,8 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return string Namespace text // */ // public function getTalkNsText() { -// return MediaWikiServices::getInstance()->getContentLanguage()-> -// getNsText( MWNamespace::getTalk( $this->mNamespace ) ); +// return MediaWikiServices::getInstance().getContentLanguage(). +// getNsText(MWNamespace::getTalk(this.mNamespace)); // } // // /** @@ -1068,7 +1078,7 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return bool True if this title either is a talk page or can have a talk page associated. // */ // public function canHaveTalkPage() { -// return MWNamespace::hasTalkNamespace( $this->mNamespace ); +// return MWNamespace::hasTalkNamespace(this.mNamespace); // } // // /** @@ -1077,7 +1087,7 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return bool // */ // public function canExist() { -// return $this->mNamespace >= NS_MAIN; +// return this.mNamespace >= NS_MAIN; // } // // /** @@ -1086,7 +1096,7 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return bool // */ // public function isWatchable() { -// return !$this->isExternal() && MWNamespace::isWatchable( $this->mNamespace ); +// return !this.isExternal() && MWNamespace::isWatchable(this.mNamespace); // } // // /** @@ -1095,7 +1105,7 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return bool // */ // public function isSpecialPage() { -// return $this->mNamespace == NS_SPECIAL; +// return this.mNamespace == NS_SPECIAL; // } // // /** @@ -1104,12 +1114,12 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param string $name The special page name // * @return bool // */ -// public function isSpecial( $name ) { -// if ( $this->isSpecialPage() ) { -// list( $thisName, /* $subpage */ ) = -// MediaWikiServices::getInstance()->getSpecialPageFactory()-> -// resolveAlias( $this->mDbkeyform ); -// if ( $name == $thisName ) { +// public function isSpecial($name) { +// if (this.isSpecialPage()) { +// list(thisName, /* $subpage */) = +// MediaWikiServices::getInstance().getSpecialPageFactory(). +// resolveAlias(this.mDbkeyform); +// if ($name == thisName) { // return true; // } // } @@ -1118,53 +1128,54 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // // /** // * If the Title refers to a special page alias which is not the local default, resolve -// * the alias, and localise the name as necessary. Otherwise, return $this +// * the alias, and localise the name as necessary. Otherwise, return this // * // * @return Title // */ // public function fixSpecialName() { -// if ( $this->isSpecialPage() ) { -// $spFactory = MediaWikiServices::getInstance()->getSpecialPageFactory(); -// list( $canonicalName, $par ) = $spFactory->resolveAlias( $this->mDbkeyform ); -// if ( $canonicalName ) { -// $localName = $spFactory->getLocalNameFor( $canonicalName, $par ); -// if ( $localName != $this->mDbkeyform ) { -// return self::makeTitle( NS_SPECIAL, $localName ); +// if (this.isSpecialPage()) { +// $spFactory = MediaWikiServices::getInstance().getSpecialPageFactory(); +// list($canonicalName, $par) = $spFactory.resolveAlias(this.mDbkeyform); +// if ($canonicalName) { +// $localName = $spFactory.getLocalNameFor($canonicalName, $par); +// if ($localName != this.mDbkeyform) { +// return self::makeTitle(NS_SPECIAL, $localName); // } // } // } -// return $this; -// } -// -// /** -// * Returns true if the title is inside the specified namespace. -// * -// * Please make use of this instead of comparing to getNamespace() -// * This function is much more resistant to changes we may make -// * to namespaces than code that makes direct comparisons. -// * @param int $ns The namespace -// * @return bool -// * @since 1.19 -// */ -// public function inNamespace( $ns ) { -// return MWNamespace::equals( $this->mNamespace, $ns ); +// return this; // } + + /** + * Returns true if the title is inside the specified namespace. + * + * Please make use of this instead of comparing to getNamespace() + * This function is much more resistant to changes we may make + * to namespaces than code that makes direct comparisons. + * @param int $ns The namespace + * @return bool + * @since 1.19 + */ + public boolean inNamespace(int ns) { +// return MWNamespace::equals(this.mNamespace, $ns); + return false; + } // // /** // * Returns true if the title is inside one of the specified namespaces. // * -// * @param int|int[] $namespaces,... The namespaces to check for +// * @param int|intnew XophpArray() $namespaces,... The namespaces to check for // * @return bool // * @since 1.19 // */ -// public function inNamespaces( /* ... */ ) { +// public function inNamespaces(/* ... */) { // $namespaces = func_get_args(); -// if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) { +// if (count($namespaces) > 0 && is_array($namespaces[0])) { // $namespaces = $namespaces[0]; // } // -// foreach ( $namespaces as $ns ) { -// if ( $this->inNamespace( $ns ) ) { +// foreach ($namespaces as $ns) { +// if (this.inNamespace($ns)) { // return true; // } // } @@ -1185,8 +1196,8 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param int $ns // * @return bool // */ -// public function hasSubjectNamespace( $ns ) { -// return MWNamespace::subjectEquals( $this->mNamespace, $ns ); +// public function hasSubjectNamespace($ns) { +// return MWNamespace::subjectEquals(this.mNamespace, $ns); // } // // /** @@ -1197,7 +1208,7 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return bool // */ // public function isContentPage() { -// return MWNamespace::isContent( $this->mNamespace ); +// return MWNamespace::isContent(this.mNamespace); // } // // /** @@ -1207,13 +1218,13 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return bool // */ // public function isMovable() { -// if ( !MWNamespace::isMovable( $this->mNamespace ) || $this->isExternal() ) { +// if (!MWNamespace::isMovable(this.mNamespace) || this.isExternal()) { // // Interwiki title or immovable namespace. Hooks don't get to override here // return false; // } // // $result = true; -// Hooks::run( 'TitleIsMovable', [ $this, &$result ] ); +// Hooks::run('TitleIsMovable', [ this, &$result ]); // return $result; // } // @@ -1221,14 +1232,14 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * Is this the mainpage? // * @note Title::newFromText seems to be sufficiently optimized by the title // * cache that we don't need to over-optimize by doing direct comparisons and -// * accidentally creating new bugs where $title->equals( Title::newFromText() ) -// * ends up reporting something differently than $title->isMainPage(); +// * accidentally creating new bugs where $title.equals(Title::newFromText()) +// * ends up reporting something differently than $title.isMainPage(); // * // * @since 1.18 // * @return bool // */ // public function isMainPage() { -// return $this->equals( self::newMainPage() ); +// return this.equals(self::newMainPage()); // } // // /** @@ -1237,8 +1248,8 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return bool // */ // public function isSubpage() { -// return MWNamespace::hasSubpages( $this->mNamespace ) -// ? strpos( $this->getText(), '/' ) !== false +// return MWNamespace::hasSubpages(this.mNamespace) +// ? strpos(this.getText(), '/') !== false // : false; // } // @@ -1250,8 +1261,8 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // public function isConversionTable() { // // @todo ConversionTable should become a separate content model. // -// return $this->mNamespace == NS_MEDIAWIKI && -// strpos( $this->getText(), 'Conversiontable/' ) === 0; +// return this.mNamespace == NS_MEDIAWIKI && +// strpos(this.getText(), 'Conversiontable/') === 0; // } // // /** @@ -1260,7 +1271,7 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return bool // */ // public function isWikitextPage() { -// return $this->hasContentModel( CONTENT_MODEL_WIKITEXT ); +// return this.hasContentModel(CONTENT_MODEL_WIKITEXT); // } // // /** @@ -1279,9 +1290,9 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // */ // public function isSiteConfigPage() { // return ( -// $this->isSiteCssConfigPage() -// || $this->isSiteJsonConfigPage() -// || $this->isSiteJsConfigPage() +// this.isSiteCssConfigPage() +// || this.isSiteJsonConfigPage() +// || this.isSiteJsConfigPage() // ); // } // @@ -1293,9 +1304,9 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // */ // public function isUserConfigPage() { // return ( -// $this->isUserCssConfigPage() -// || $this->isUserJsonConfigPage() -// || $this->isUserJsConfigPage() +// this.isUserCssConfigPage() +// || this.isUserJsonConfigPage() +// || this.isUserJsConfigPage() // ); // } // @@ -1306,13 +1317,13 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @since 1.31 // */ // public function getSkinFromConfigSubpage() { -// $subpage = explode( '/', $this->mTextform ); -// $subpage = $subpage[count( $subpage ) - 1]; -// $lastdot = strrpos( $subpage, '.' ); -// if ( $lastdot === false ) { +// $subpage = explode('/', this.mTextform); +// $subpage = $subpage[count($subpage) - 1]; +// $lastdot = strrpos($subpage, '.'); +// if ($lastdot === false) { // return $subpage; # Never happens: only called for names ending in '.css'/'.json'/'.js' // } -// return substr( $subpage, 0, $lastdot ); +// return substr($subpage, 0, $lastdot); // } // // /** @@ -1323,9 +1334,9 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // */ // public function isUserCssConfigPage() { // return ( -// NS_USER == $this->mNamespace -// && $this->isSubpage() -// && $this->hasContentModel( CONTENT_MODEL_CSS ) +// NS_USER == this.mNamespace +// && this.isSubpage() +// && this.hasContentModel(CONTENT_MODEL_CSS) // ); // } // @@ -1337,9 +1348,9 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // */ // public function isUserJsonConfigPage() { // return ( -// NS_USER == $this->mNamespace -// && $this->isSubpage() -// && $this->hasContentModel( CONTENT_MODEL_JSON ) +// NS_USER == this.mNamespace +// && this.isSubpage() +// && this.hasContentModel(CONTENT_MODEL_JSON) // ); // } // @@ -1351,9 +1362,9 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // */ // public function isUserJsConfigPage() { // return ( -// NS_USER == $this->mNamespace -// && $this->isSubpage() -// && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) +// NS_USER == this.mNamespace +// && this.isSubpage() +// && this.hasContentModel(CONTENT_MODEL_JAVASCRIPT) // ); // } // @@ -1365,12 +1376,12 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // */ // public function isSiteCssConfigPage() { // return ( -// NS_MEDIAWIKI == $this->mNamespace +// NS_MEDIAWIKI == this.mNamespace // && ( -// $this->hasContentModel( CONTENT_MODEL_CSS ) +// this.hasContentModel(CONTENT_MODEL_CSS) // // paranoia - a MediaWiki: namespace page with mismatching extension and content // // model is probably by mistake and might get handled incorrectly (see e.g. T112937) -// || substr( $this->mDbkeyform, -4 ) === '.css' +// || substr(this.mDbkeyform, -4) === '.css' // ) // ); // } @@ -1383,12 +1394,12 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // */ // public function isSiteJsonConfigPage() { // return ( -// NS_MEDIAWIKI == $this->mNamespace +// NS_MEDIAWIKI == this.mNamespace // && ( -// $this->hasContentModel( CONTENT_MODEL_JSON ) +// this.hasContentModel(CONTENT_MODEL_JSON) // // paranoia - a MediaWiki: namespace page with mismatching extension and content // // model is probably by mistake and might get handled incorrectly (see e.g. T112937) -// || substr( $this->mDbkeyform, -5 ) === '.json' +// || substr(this.mDbkeyform, -5) === '.json' // ) // ); // } @@ -1401,12 +1412,12 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // */ // public function isSiteJsConfigPage() { // return ( -// NS_MEDIAWIKI == $this->mNamespace +// NS_MEDIAWIKI == this.mNamespace // && ( -// $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) +// this.hasContentModel(CONTENT_MODEL_JAVASCRIPT) // // paranoia - a MediaWiki: namespace page with mismatching extension and content // // model is probably by mistake and might get handled incorrectly (see e.g. T112937) -// || substr( $this->mDbkeyform, -3 ) === '.js' +// || substr(this.mDbkeyform, -3) === '.js' // ) // ); // } @@ -1420,11 +1431,11 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // public function isRawHtmlMessage() { // global $wgRawHtmlMessages; // -// if ( !$this->inNamespace( NS_MEDIAWIKI ) ) { +// if (!this.inNamespace(NS_MEDIAWIKI)) { // return false; // } -// $message = lcfirst( $this->getRootTitle()->getDBkey() ); -// return in_array( $message, $wgRawHtmlMessages, true ); +// $message = lcfirst(this.getRootTitle().getDBkey()); +// return in_array($message, $wgRawHtmlMessages, true); // } // // /** @@ -1433,7 +1444,7 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return bool // */ // public function isTalkPage() { -// return MWNamespace::isTalk( $this->mNamespace ); +// return MWNamespace::isTalk(this.mNamespace); // } // // /** @@ -1442,7 +1453,7 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return Title The object for the talk page // */ // public function getTalkPage() { -// return self::makeTitle( MWNamespace::getTalk( $this->mNamespace ), $this->mDbkeyform ); +// return self::makeTitle(MWNamespace::getTalk(this.mNamespace), this.mDbkeyform); // } // // /** @@ -1455,11 +1466,11 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * or null if no associated talk page can exist, according to canHaveTalkPage(). // */ // public function getTalkPageIfDefined() { -// if ( !$this->canHaveTalkPage() ) { +// if (!this.canHaveTalkPage()) { // return null; // } // -// return $this->getTalkPage(); +// return this.getTalkPage(); // } // // /** @@ -1470,11 +1481,11 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // */ // public function getSubjectPage() { // // Is this the same title? -// $subjectNS = MWNamespace::getSubject( $this->mNamespace ); -// if ( $this->mNamespace == $subjectNS ) { -// return $this; +// $subjectNS = MWNamespace::getSubject(this.mNamespace); +// if (this.mNamespace == $subjectNS) { +// return this; // } -// return self::makeTitle( $subjectNS, $this->mDbkeyform ); +// return self::makeTitle($subjectNS, this.mDbkeyform); // } // // /** @@ -1486,16 +1497,16 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return Title // */ // public function getOtherPage() { -// if ( $this->isSpecialPage() ) { -// throw new MWException( 'Special pages cannot have other pages' ); +// if (this.isSpecialPage()) { +// throw new MWException('Special pages cannot have other pages'); // } -// if ( $this->isTalkPage() ) { -// return $this->getSubjectPage(); +// if (this.isTalkPage()) { +// return this.getSubjectPage(); // } else { -// if ( !$this->canHaveTalkPage() ) { -// throw new MWException( "{$this->getPrefixedText()} does not have an other page" ); +// if (!this.canHaveTalkPage()) { +// throw new MWException("{this.getPrefixedText()} does not have an other page"); // } -// return $this->getTalkPage(); +// return this.getTalkPage(); // } // } // @@ -1505,48 +1516,48 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return int Default namespace index // */ // public function getDefaultNamespace() { -// return $this->mDefaultNamespace; +// return this.mDefaultNamespace; // } -// -// /** -// * Get the Title fragment (i.e.\ the bit after the #) in text form -// * -// * Use Title::hasFragment to check for a fragment -// * -// * @return string Title fragment -// */ -// public function getFragment() { -// return $this->mFragment; -// } -// -// /** -// * Check if a Title fragment is set -// * -// * @return bool -// * @since 1.23 -// */ -// public function hasFragment() { -// return $this->mFragment !== ''; -// } -// + + /** + * Get the Title fragment (i.e.\ the bit after the #) in text form + * + * Use Title::hasFragment to check for a fragment + * + * @return string Title fragment + */ + public String getFragment() { + return this.mFragment; + } + + /** + * Check if a Title fragment is set + * + * @return bool + * @since 1.23 + */ + public boolean hasFragment() { + return XophpString_.eq_not(this.mFragment, ""); + } + // /** // * Get the fragment in URL form, including the "#" character if there is one // * // * @return string Fragment in URL form // */ // public function getFragmentForURL() { -// if ( !$this->hasFragment() ) { -// return ''; -// } elseif ( $this->isExternal() ) { +// if (!this.hasFragment()) { +// return ""; +// } elseif (this.isExternal()) { // // Note: If the interwiki is unknown, it's treated as a namespace on the local wiki, // // so we treat it like a local interwiki. -// $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki ); -// if ( $interwiki && !$interwiki->isLocal() ) { -// return '#' . Sanitizer::escapeIdForExternalInterwiki( $this->mFragment ); +// $interwiki = self::getInterwikiLookup().fetch(this.mInterwiki); +// if ($interwiki && !$interwiki.isLocal()) { +// return '#' . Sanitizer::escapeIdForExternalInterwiki(this.mFragment); // } // } // -// return '#' . Sanitizer::escapeIdForLink( $this->mFragment ); +// return '#' . Sanitizer::escapeIdForLink(this.mFragment); // } // // /** @@ -1561,26 +1572,27 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @private // * @param string $fragment Text // */ -// public function setFragment( $fragment ) { -// $this->mFragment = strtr( substr( $fragment, 1 ), '_', ' ' ); +// public function setFragment($fragment) { +// this.mFragment = strtr(substr($fragment, 1), '_', ' '); // } -// -// /** -// * Creates a new Title for a different fragment of the same page. -// * -// * @since 1.27 -// * @param string $fragment -// * @return Title -// */ -// public function createFragmentTarget( $fragment ) { + + /** + * Creates a new Title for a different fragment of the same page. + * + * @since 1.27 + * @param string $fragment + * @return Title + */ + public XomwTitle createFragmentTarget(String fragment) { // return self::makeTitle( -// $this->mNamespace, -// $this->getText(), +// this.mNamespace, +// this.getText(), // $fragment, -// $this->mInterwiki +// this.mInterwiki // ); -// } -// + return null; + } + // /** // * Prefix some arbitrary text with the namespace or interwiki prefix // * of this object @@ -1588,19 +1600,19 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param string $name The text // * @return string The prefixed text // */ -// private function prefix( $name ) { -// $p = ''; -// if ( $this->isExternal() ) { -// $p = $this->mInterwiki . ':'; +// private function prefix($name) { +// $p = ""; +// if (this.isExternal()) { +// $p = this.mInterwiki . ':'; // } // -// if ( $this->mNamespace != 0 ) { -// $nsText = $this->getNsText(); +// if (this.mNamespace != 0) { +// $nsText = this.getNsText(); // -// if ( $nsText === false ) { +// if ($nsText === false) { // // See T165149. Awkward, but better than erroneously linking to the main namespace. -// $nsText = MediaWikiServices::getInstance()->getContentLanguage()-> -// getNsText( NS_SPECIAL ) . ":Badtitle/NS{$this->mNamespace}"; +// $nsText = MediaWikiServices::getInstance().getContentLanguage(). +// getNsText(NS_SPECIAL) . ":Badtitle/NS{this.mNamespace}"; // } // // $p .= $nsText . ':'; @@ -1615,34 +1627,34 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * any interwiki and namespace prefixes // */ // public function getPrefixedDBkey() { -// $s = $this->prefix( $this->mDbkeyform ); -// $s = strtr( $s, ' ', '_' ); +// $s = this.prefix(this.mDbkeyform); +// $s = strtr($s, ' ', '_'); // return $s; // } -// -// /** -// * Get the prefixed title with spaces. -// * This is the form usually used for display -// * -// * @return string The prefixed title, with spaces -// */ -// public function getPrefixedText() { -// if ( $this->prefixedText === null ) { -// $s = $this->prefix( $this->mTextform ); -// $s = strtr( $s, '_', ' ' ); -// $this->prefixedText = $s; + + /** + * Get the prefixed title with spaces. + * This is the form usually used for display + * + * @return string The prefixed title, with spaces + */ + public String getPrefixedText() { +// if (this.prefixedText == null) { +// String s = this.prefix(this.mTextform); +// s = strtr(s, '_', ' '); +// this.prefixedText = s; // } -// return $this->prefixedText; -// } -// -// /** -// * Return a string representation of this title -// * -// * @return string Representation of this title -// */ -// public function __toString() { -// return $this->getPrefixedText(); -// } + return this.prefixedText; + } + + /** + * Return a string representation of this title + * + * @return string Representation of this title + */ + public String __toString() { + return this.getPrefixedText(); + } // // /** // * Get the prefixed title with spaces, plus any fragment @@ -1651,9 +1663,9 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return string The prefixed title, with spaces and the fragment, including '#' // */ // public function getFullText() { -// $text = $this->getPrefixedText(); -// if ( $this->hasFragment() ) { -// $text .= '#' . $this->mFragment; +// $text = this.getPrefixedText(); +// if (this.hasFragment()) { +// $text .= '#' . this.mFragment; // } // return $text; // } @@ -1663,7 +1675,7 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * // * @par Example: // * @code -// * Title::newFromText('User:Foo/Bar/Baz')->getRootText(); +// * Title::newFromText('User:Foo/Bar/Baz').getRootText(); // * # returns: 'Foo' // * @endcode // * @@ -1671,11 +1683,11 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @since 1.20 // */ // public function getRootText() { -// if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) { -// return $this->getText(); +// if (!MWNamespace::hasSubpages(this.mNamespace)) { +// return this.getText(); // } // -// return strtok( $this->getText(), '/' ); +// return strtok(this.getText(), '/'); // } // // /** @@ -1683,7 +1695,7 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * // * @par Example: // * @code -// * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle(); +// * Title::newFromText('User:Foo/Bar/Baz').getRootTitle(); // * # returns: Title{User:Foo} // * @endcode // * @@ -1691,7 +1703,7 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @since 1.20 // */ // public function getRootTitle() { -// return self::makeTitle( $this->mNamespace, $this->getRootText() ); +// return self::makeTitle(this.mNamespace, this.getRootText()); // } // // /** @@ -1699,25 +1711,25 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * // * @par Example: // * @code -// * Title::newFromText('User:Foo/Bar/Baz')->getBaseText(); +// * Title::newFromText('User:Foo/Bar/Baz').getBaseText(); // * # returns: 'Foo/Bar' // * @endcode // * // * @return string Base name // */ // public function getBaseText() { -// $text = $this->getText(); -// if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) { +// $text = this.getText(); +// if (!MWNamespace::hasSubpages(this.mNamespace)) { // return $text; // } // -// $lastSlashPos = strrpos( $text, '/' ); +// $lastSlashPos = strrpos($text, '/'); // // Don't discard the real title if there's no subpage involved -// if ( $lastSlashPos === false ) { +// if ($lastSlashPos === false) { // return $text; // } // -// return substr( $text, 0, $lastSlashPos ); +// return substr($text, 0, $lastSlashPos); // } // // /** @@ -1725,7 +1737,7 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * // * @par Example: // * @code -// * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle(); +// * Title::newFromText('User:Foo/Bar/Baz').getBaseTitle(); // * # returns: Title{User:Foo/Bar} // * @endcode // * @@ -1733,7 +1745,7 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @since 1.20 // */ // public function getBaseTitle() { -// return self::makeTitle( $this->mNamespace, $this->getBaseText() ); +// return self::makeTitle(this.mNamespace, this.getBaseText()); // } // // /** @@ -1741,18 +1753,18 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * // * @par Example: // * @code -// * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText(); +// * Title::newFromText('User:Foo/Bar/Baz').getSubpageText(); // * # returns: "Baz" // * @endcode // * // * @return string Subpage name // */ // public function getSubpageText() { -// if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) { -// return $this->mTextform; +// if (!MWNamespace::hasSubpages(this.mNamespace)) { +// return this.mTextform; // } -// $parts = explode( '/', $this->mTextform ); -// return $parts[count( $parts ) - 1]; +// $parts = explode('/', this.mTextform); +// return $parts[count($parts) - 1]; // } // // /** @@ -1760,7 +1772,7 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * // * @par Example: // * @code -// * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf"); +// * Title::newFromText('User:Foo/Bar/Baz').getSubpage("Asdf"); // * # returns: Title{User:Foo/Bar/Baz/Asdf} // * @endcode // * @@ -1768,8 +1780,8 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return Title|null Subpage title, or null on an error // * @since 1.20 // */ -// public function getSubpage( $text ) { -// return self::makeTitleSafe( $this->mNamespace, $this->getText() . '/' . $text ); +// public function getSubpage($text) { +// return self::makeTitleSafe(this.mNamespace, this.getText() . '/' . $text); // } // // /** @@ -1778,8 +1790,8 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return string URL-encoded subpage name // */ // public function getSubpageUrlForm() { -// $text = $this->getSubpageText(); -// $text = wfUrlencode( strtr( $text, ' ', '_' ) ); +// $text = this.getSubpageText(); +// $text = wfUrlencode(strtr($text, ' ', '_')); // return $text; // } // @@ -1789,8 +1801,8 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return string The URL-encoded form // */ // public function getPrefixedURL() { -// $s = $this->prefix( $this->mDbkeyform ); -// $s = wfUrlencode( strtr( $s, ' ', '_' ) ); +// $s = this.prefix(this.mDbkeyform); +// $s = wfUrlencode(strtr($s, ' ', '_')); // return $s; // } // @@ -1804,28 +1816,28 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * // * @since 1.19 (r105919) // * @param array|string $query -// * @param string|string[]|bool $query2 +// * @param string|stringnew XophpArray()|bool $query2 // * @return string // */ -// private static function fixUrlQueryArgs( $query, $query2 = false ) { -// if ( $query2 !== false ) { -// wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " . +// private static function fixUrlQueryArgs($query, $query2 = false) { +// if ($query2 !== false) { +// wfDeprecated("Title::get{Canonical,Full,Link,Local,Internal}URL " . // "method called with a second parameter is deprecated. Add your " . -// "parameter to an array passed as the first parameter.", "1.19" ); +// "parameter to an array passed as the first parameter.", "1.19"); // } -// if ( is_array( $query ) ) { -// $query = wfArrayToCgi( $query ); +// if (is_array($query)) { +// $query = wfArrayToCgi($query); // } -// if ( $query2 ) { -// if ( is_string( $query2 ) ) { +// if ($query2) { +// if (is_string($query2)) { // // $query2 is a string, we will consider this to be // // a deprecated $variant argument and add it to the query -// $query2 = wfArrayToCgi( [ 'variant' => $query2 ] ); +// $query2 = wfArrayToCgi([ 'variant' => $query2 ]); // } else { -// $query2 = wfArrayToCgi( $query2 ); +// $query2 = wfArrayToCgi($query2); // } // // If we have $query content add a & to it first -// if ( $query ) { +// if ($query) { // $query .= '&'; // } // // Now append the queries together @@ -1840,27 +1852,27 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * // * @see self::getLocalURL for the arguments. // * @see wfExpandUrl -// * @param string|string[] $query -// * @param string|string[]|bool $query2 +// * @param string|stringnew XophpArray() $query +// * @param string|stringnew XophpArray()|bool $query2 // * @param string|int|null $proto Protocol type to use in URL // * @return string The URL // */ -// public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) { -// $query = self::fixUrlQueryArgs( $query, $query2 ); +// public function getFullURL($query = "", $query2 = false, $proto = PROTO_RELATIVE) { +// $query = self::fixUrlQueryArgs($query, $query2); // // # Hand off all the decisions on urls to getLocalURL -// $url = $this->getLocalURL( $query ); +// $url = this.getLocalURL($query); // // # Expand the url to make it a full url. Note that getLocalURL has the // # potential to output full urls for a variety of reasons, so we use // # wfExpandUrl instead of simply prepending $wgServer -// $url = wfExpandUrl( $url, $proto ); +// $url = wfExpandUrl($url, $proto); // // # Finally, add the fragment. -// $url .= $this->getFragmentForURL(); -// // Avoid PHP 7.1 warning from passing $this by reference -// $titleRef = $this; -// Hooks::run( 'GetFullURL', [ &$titleRef, &$url, $query ] ); +// $url .= this.getFragmentForURL(); +// // Avoid PHP 7.1 warning from passing this by reference +// $titleRef = this; +// Hooks::run('GetFullURL', [ &$titleRef, &$url, $query ]); // return $url; // } // @@ -1880,15 +1892,15 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param string $proto Protocol type to use in URL // * @return string A url suitable to use in an HTTP location header. // */ -// public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT ) { -// $target = $this; -// if ( $this->isExternal() ) { +// public function getFullUrlForRedirect($query = "", $proto = PROTO_CURRENT) { +// $target = this; +// if (this.isExternal()) { // $target = SpecialPage::getTitleFor( // 'GoToInterwiki', -// $this->getPrefixedDBkey() +// this.getPrefixedDBkey() // ); // } -// return $target->getFullURL( $query, false, $proto ); +// return $target.getFullURL($query, false, $proto); // } // // /** @@ -1901,11 +1913,11 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * valid to link, locally, to the current Title. // * @see self::newFromText to produce a Title object. // * -// * @param string|string[] $query An optional query string, +// * @param string|stringnew XophpArray() $query An optional query string, // * not used for interwiki links. Can be specified as an associative array as well, -// * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped). +// * e.g., array('action' => 'edit') (keys and values will be URL-escaped). // * Some query patterns will trigger various shorturl path replacements. -// * @param string|string[]|bool $query2 An optional secondary query array. This one MUST +// * @param string|stringnew XophpArray()|bool $query2 An optional secondary query array. This one MUST // * be an array. If a string is passed it will be interpreted as a deprecated // * variant argument and urlencoded into a variant= argument. // * This second query argument will be added to the $query @@ -1914,85 +1926,85 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * // * @return string String of the URL. // */ -// public function getLocalURL( $query = '', $query2 = false ) { +// public function getLocalURL($query = "", $query2 = false) { // global $wgArticlePath, $wgScript, $wgServer, $wgRequest; // -// $query = self::fixUrlQueryArgs( $query, $query2 ); +// $query = self::fixUrlQueryArgs($query, $query2); // -// $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki ); -// if ( $interwiki ) { -// $namespace = $this->getNsText(); -// if ( $namespace != '' ) { +// $interwiki = self::getInterwikiLookup().fetch(this.mInterwiki); +// if ($interwiki) { +// $namespace = this.getNsText(); +// if ($namespace != "") { // # Can this actually happen? Interwikis shouldn't be parsed. // # Yes! It can in interwiki transclusion. But... it probably shouldn't. // $namespace .= ':'; // } -// $url = $interwiki->getURL( $namespace . $this->mDbkeyform ); -// $url = wfAppendQuery( $url, $query ); +// $url = $interwiki.getURL($namespace . this.mDbkeyform); +// $url = wfAppendQuery($url, $query); // } else { -// $dbkey = wfUrlencode( $this->getPrefixedDBkey() ); -// if ( $query == '' ) { -// $url = str_replace( '$1', $dbkey, $wgArticlePath ); -// // Avoid PHP 7.1 warning from passing $this by reference -// $titleRef = $this; -// Hooks::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] ); +// $dbkey = wfUrlencode(this.getPrefixedDBkey()); +// if ($query == "") { +// $url = str_replace('$1', $dbkey, $wgArticlePath); +// // Avoid PHP 7.1 warning from passing this by reference +// $titleRef = this; +// Hooks::run('GetLocalURL::Article', [ &$titleRef, &$url ]); // } else { // global $wgVariantArticlePath, $wgActionPaths; // $url = false; -// $matches = []; +// $matches = new XophpArray(); // -// if ( !empty( $wgActionPaths ) -// && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) +// if (!empty($wgActionPaths) +// && preg_match('/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches) // ) { -// $action = urldecode( $matches[2] ); -// if ( isset( $wgActionPaths[$action] ) ) { +// $action = urldecode($matches[2]); +// if (isset($wgActionPaths[$action])) { // $query = $matches[1]; -// if ( isset( $matches[4] ) ) { +// if (isset($matches[4])) { // $query .= $matches[4]; // } -// $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] ); -// if ( $query != '' ) { -// $url = wfAppendQuery( $url, $query ); +// $url = str_replace('$1', $dbkey, $wgActionPaths[$action]); +// if ($query != "") { +// $url = wfAppendQuery($url, $query); // } // } // } // -// if ( $url === false +// if ($url === false // && $wgVariantArticlePath -// && preg_match( '/^variant=([^&]*)$/', $query, $matches ) -// && $this->getPageLanguage()->equals( -// MediaWikiServices::getInstance()->getContentLanguage() ) -// && $this->getPageLanguage()->hasVariants() +// && preg_match('/^variant=([^&]*)$/', $query, $matches) +// && this.getPageLanguage().equals( +// MediaWikiServices::getInstance().getContentLanguage()) +// && this.getPageLanguage().hasVariants() // ) { -// $variant = urldecode( $matches[1] ); -// if ( $this->getPageLanguage()->hasVariant( $variant ) ) { +// $variant = urldecode($matches[1]); +// if (this.getPageLanguage().hasVariant($variant)) { // // Only do the variant replacement if the given variant is a valid // // variant for the page's language. -// $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath ); -// $url = str_replace( '$1', $dbkey, $url ); +// $url = str_replace('$2', urlencode($variant), $wgVariantArticlePath); +// $url = str_replace('$1', $dbkey, $url); // } // } // -// if ( $url === false ) { -// if ( $query == '-' ) { -// $query = ''; +// if ($url === false) { +// if ($query == '-') { +// $query = ""; // } // $url = "{$wgScript}?title={$dbkey}&{$query}"; // } // } -// // Avoid PHP 7.1 warning from passing $this by reference -// $titleRef = $this; -// Hooks::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] ); +// // Avoid PHP 7.1 warning from passing this by reference +// $titleRef = this; +// Hooks::run('GetLocalURL::Internal', [ &$titleRef, &$url, $query ]); // // // @todo FIXME: This causes breakage in various places when we // // actually expected a local URL and end up with dupe prefixes. -// if ( $wgRequest->getVal( 'action' ) == 'render' ) { +// if ($wgRequest.getVal('action') == 'render') { // $url = $wgServer . $url; // } // } -// // Avoid PHP 7.1 warning from passing $this by reference -// $titleRef = $this; -// Hooks::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] ); +// // Avoid PHP 7.1 warning from passing this by reference +// $titleRef = this; +// Hooks::run('GetLocalURL', [ &$titleRef, &$url, $query ]); // return $url; // } // @@ -2006,20 +2018,20 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * The result obviously should not be URL-escaped, but does need to be // * HTML-escaped if it's being output in HTML. // * -// * @param string|string[] $query +// * @param string|stringnew XophpArray() $query // * @param bool $query2 // * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded, // * or false (default) for no expansion // * @see self::getLocalURL for the arguments. // * @return string The URL // */ -// public function getLinkURL( $query = '', $query2 = false, $proto = false ) { -// if ( $this->isExternal() || $proto !== false ) { -// $ret = $this->getFullURL( $query, $query2, $proto ); -// } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) { -// $ret = $this->getFragmentForURL(); +// public function getLinkURL($query = "", $query2 = false, $proto = false) { +// if (this.isExternal() || $proto !== false) { +// $ret = this.getFullURL($query, $query2, $proto); +// } elseif (this.getPrefixedText() === "" && this.hasFragment()) { +// $ret = this.getFragmentForURL(); // } else { -// $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL(); +// $ret = this.getLocalURL($query, $query2) . this.getFragmentForURL(); // } // return $ret; // } @@ -2034,18 +2046,18 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * protocol-relative, the URL will be expanded to http:// // * // * @see self::getLocalURL for the arguments. -// * @param string|string[] $query +// * @param string|stringnew XophpArray() $query // * @param string|bool $query2 Deprecated // * @return string The URL // */ -// public function getInternalURL( $query = '', $query2 = false ) { +// public function getInternalURL($query = "", $query2 = false) { // global $wgInternalServer, $wgServer; -// $query = self::fixUrlQueryArgs( $query, $query2 ); +// $query = self::fixUrlQueryArgs($query, $query2); // $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer; -// $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP ); -// // Avoid PHP 7.1 warning from passing $this by reference -// $titleRef = $this; -// Hooks::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] ); +// $url = wfExpandUrl($server . this.getLocalURL($query), PROTO_HTTP); +// // Avoid PHP 7.1 warning from passing this by reference +// $titleRef = this; +// Hooks::run('GetInternalURL', [ &$titleRef, &$url, $query ]); // return $url; // } // @@ -2057,17 +2069,17 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment // * // * @see self::getLocalURL for the arguments. -// * @param string|string[] $query +// * @param string|stringnew XophpArray() $query // * @param string|bool $query2 Deprecated // * @return string The URL // * @since 1.18 // */ -// public function getCanonicalURL( $query = '', $query2 = false ) { -// $query = self::fixUrlQueryArgs( $query, $query2 ); -// $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL ); -// // Avoid PHP 7.1 warning from passing $this by reference -// $titleRef = $this; -// Hooks::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] ); +// public function getCanonicalURL($query = "", $query2 = false) { +// $query = self::fixUrlQueryArgs($query, $query2); +// $url = wfExpandUrl(this.getLocalURL($query) . this.getFragmentForURL(), PROTO_CANONICAL); +// // Avoid PHP 7.1 warning from passing this by reference +// $titleRef = this; +// Hooks::run('GetCanonicalURL', [ &$titleRef, &$url, $query ]); // return $url; // } // @@ -2077,10 +2089,10 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return string The URL, or a null string if this is an interwiki link // */ // public function getEditURL() { -// if ( $this->isExternal() ) { -// return ''; +// if (this.isExternal()) { +// return ""; // } -// $s = $this->getLocalURL( 'action=edit' ); +// $s = this.getLocalURL('action=edit'); // // return $s; // } @@ -2102,11 +2114,11 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @throws Exception // * // * @deprecated since 1.33, -// * use MediaWikiServices::getInstance()->getPermissionManager()->quickUserCan(..) instead +// * use MediaWikiServices::getInstance().getPermissionManager().quickUserCan(..) instead // * // */ -// public function quickUserCan( $action, $user = null ) { -// return $this->userCan( $action, $user, false ); +// public function quickUserCan($action, $user = null) { +// return this.userCan($action, $user, false); // } // // /** @@ -2121,24 +2133,24 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @throws Exception // * // * @deprecated since 1.33, -// * use MediaWikiServices::getInstance()->getPermissionManager()->userCan(..) instead +// * use MediaWikiServices::getInstance().getPermissionManager().userCan(..) instead // * // */ -// public function userCan( $action, $user = null, $rigor = PermissionManager::RIGOR_SECURE ) { -// if ( !$user instanceof User ) { +// public function userCan($action, $user = null, $rigor = PermissionManager::RIGOR_SECURE) { +// if (!$user instanceof User) { // global $wgUser; // $user = $wgUser; // } // // // TODO: this is for b/c, eventually will be removed -// if ( $rigor === true ) { +// if ($rigor === true) { // $rigor = PermissionManager::RIGOR_SECURE; // b/c -// } elseif ( $rigor === false ) { +// } elseif ($rigor === false) { // $rigor = PermissionManager::RIGOR_QUICK; // b/c // } // -// return MediaWikiServices::getInstance()->getPermissionManager() -// ->userCan( $action, $user, $this, $rigor ); +// return MediaWikiServices::getInstance().getPermissionManager() +// .userCan($action, $user, this, $rigor); // } // // /** @@ -2159,21 +2171,21 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @throws Exception // * // * @deprecated since 1.33, -// * use MediaWikiServices::getInstance()->getPermissionManager()->getUserPermissionsErrors() +// * use MediaWikiServices::getInstance().getPermissionManager().getUserPermissionsErrors() // * // */ // public function getUserPermissionsErrors( -// $action, $user, $rigor = PermissionManager::RIGOR_SECURE, $ignoreErrors = [] +// $action, $user, $rigor = PermissionManager::RIGOR_SECURE, $ignoreErrors = new XophpArray() // ) { // // TODO: this is for b/c, eventually will be removed -// if ( $rigor === true ) { +// if ($rigor === true) { // $rigor = PermissionManager::RIGOR_SECURE; // b/c -// } elseif ( $rigor === false ) { +// } elseif ($rigor === false) { // $rigor = PermissionManager::RIGOR_QUICK; // b/c // } // -// return MediaWikiServices::getInstance()->getPermissionManager() -// ->getPermissionErrors( $action, $user, $this, $rigor, $ignoreErrors ); +// return MediaWikiServices::getInstance().getPermissionManager() +// .getPermissionErrors($action, $user, this, $rigor, $ignoreErrors); // } // // /** @@ -2184,22 +2196,22 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * // * @return array List of errors // */ -// private function resultToError( $errors, $result ) { -// if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) { +// private function resultToError($errors, $result) { +// if (is_array($result) && count($result) && !is_array($result[0])) { // // A single array representing an error -// $errors[] = $result; -// } elseif ( is_array( $result ) && is_array( $result[0] ) ) { +// $errorsnew XophpArray() = $result; +// } elseif (is_array($result) && is_array($result[0])) { // // A nested array representing multiple errors -// $errors = array_merge( $errors, $result ); -// } elseif ( $result !== '' && is_string( $result ) ) { +// $errors = array_merge($errors, $result); +// } elseif ($result !== "" && is_string($result)) { // // A string representing a message-id -// $errors[] = [ $result ]; -// } elseif ( $result instanceof MessageSpecifier ) { +// $errorsnew XophpArray() = [ $result ]; +// } elseif ($result instanceof MessageSpecifier) { // // A message specifier representing an error -// $errors[] = [ $result ]; -// } elseif ( $result === false ) { +// $errorsnew XophpArray() = [ $result ]; +// } elseif ($result === false) { // // a generic "We don't want them to do that" -// $errors[] = [ 'badaccess-group0' ]; +// $errorsnew XophpArray() = [ 'badaccess-group0' ]; // } // return $errors; // } @@ -2211,15 +2223,15 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * titles that do not exist // * @return array // */ -// public static function getFilteredRestrictionTypes( $exists = true ) { +// public static function getFilteredRestrictionTypes($exists = true) { // global $wgRestrictionTypes; // $types = $wgRestrictionTypes; -// if ( $exists ) { +// if ($exists) { // # Remove the create restriction for existing titles -// $types = array_diff( $types, [ 'create' ] ); +// $types = array_diff($types, [ 'create' ]); // } else { // # Only the create and upload restrictions apply to non-existing titles -// $types = array_intersect( $types, [ 'create', 'upload' ] ); +// $types = array_intersect($types, [ 'create', 'upload' ]); // } // return $types; // } @@ -2230,21 +2242,21 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return array Applicable restriction types // */ // public function getRestrictionTypes() { -// if ( $this->isSpecialPage() ) { -// return []; +// if (this.isSpecialPage()) { +// return new XophpArray(); // } // -// $types = self::getFilteredRestrictionTypes( $this->exists() ); +// $types = self::getFilteredRestrictionTypes(this.exists()); // -// if ( $this->mNamespace != NS_FILE ) { +// if (this.mNamespace != NS_FILE) { // # Remove the upload restriction for non-file titles -// $types = array_diff( $types, [ 'upload' ] ); +// $types = array_diff($types, [ 'upload' ]); // } // -// Hooks::run( 'TitleGetRestrictionTypes', [ $this, &$types ] ); +// Hooks::run('TitleGetRestrictionTypes', [ this, &$types ]); // -// wfDebug( __METHOD__ . ': applicable restrictions to [[' . -// $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" ); +// wfDebug(__METHOD__ . ': applicable restrictions to [[' . +// this.getPrefixedText() . ']] are {' . implode(',', $types) . "}\n"); // // return $types; // } @@ -2257,12 +2269,12 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * protection, or false if there's none. // */ // public function getTitleProtection() { -// $protection = $this->getTitleProtectionInternal(); -// if ( $protection ) { -// if ( $protection['permission'] == 'sysop' ) { +// $protection = this.getTitleProtectionInternal(); +// if ($protection) { +// if ($protection['permission'] == 'sysop') { // $protection['permission'] = 'editprotected'; // B/C // } -// if ( $protection['permission'] == 'autoconfirmed' ) { +// if ($protection['permission'] == 'autoconfirmed') { // $protection['permission'] = 'editsemiprotected'; // B/C // } // } @@ -2272,69 +2284,69 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // /** // * Fetch title protection settings // * -// * To work correctly, $this->loadRestrictions() needs to have access to the +// * To work correctly, this.loadRestrictions() needs to have access to the // * actual protections in the database without munging 'sysop' => // * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other -// * callers probably want $this->getTitleProtection() instead. +// * callers probably want this.getTitleProtection() instead. // * // * @return array|bool // */ // protected function getTitleProtectionInternal() { // // Can't protect pages in special namespaces -// if ( $this->mNamespace < 0 ) { +// if (this.mNamespace < 0) { // return false; // } // // // Can't protect pages that exist. -// if ( $this->exists() ) { +// if (this.exists()) { // return false; // } // -// if ( $this->mTitleProtection === null ) { -// $dbr = wfGetDB( DB_REPLICA ); +// if (this.mTitleProtection === null) { +// $dbr = wfGetDB(DB_REPLICA); // $commentStore = CommentStore::getStore(); -// $commentQuery = $commentStore->getJoin( 'pt_reason' ); -// $res = $dbr->select( +// $commentQuery = $commentStore.getJoin('pt_reason'); +// $res = $dbr.select( // [ 'protected_titles' ] + $commentQuery['tables'], // [ // 'user' => 'pt_user', // 'expiry' => 'pt_expiry', // 'permission' => 'pt_create_perm' // ] + $commentQuery['fields'], -// [ 'pt_namespace' => $this->mNamespace, 'pt_title' => $this->mDbkeyform ], +// [ 'pt_namespace' => this.mNamespace, 'pt_title' => this.mDbkeyform ], // __METHOD__, -// [], +// new XophpArray(), // $commentQuery['joins'] // ); // // // fetchRow returns false if there are no rows. -// $row = $dbr->fetchRow( $res ); -// if ( $row ) { -// $this->mTitleProtection = [ +// $row = $dbr.fetchRow($res); +// if ($row) { +// this.mTitleProtection = [ // 'user' => $row['user'], -// 'expiry' => $dbr->decodeExpiry( $row['expiry'] ), +// 'expiry' => $dbr.decodeExpiry($row['expiry']), // 'permission' => $row['permission'], -// 'reason' => $commentStore->getComment( 'pt_reason', $row )->text, +// 'reason' => $commentStore.getComment('pt_reason', $row).text, // ]; // } else { -// $this->mTitleProtection = false; +// this.mTitleProtection = false; // } // } -// return $this->mTitleProtection; +// return this.mTitleProtection; // } // // /** // * Remove any title protection due to page existing // */ // public function deleteTitleProtection() { -// $dbw = wfGetDB( DB_MASTER ); +// $dbw = wfGetDB(DB_MASTER); // -// $dbw->delete( +// $dbw.delete( // 'protected_titles', -// [ 'pt_namespace' => $this->mNamespace, 'pt_title' => $this->mDbkeyform ], +// [ 'pt_namespace' => this.mNamespace, 'pt_title' => this.mDbkeyform ], // __METHOD__ // ); -// $this->mTitleProtection = false; +// this.mTitleProtection = false; // } // // /** @@ -2344,25 +2356,25 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param string $action Action to check (default: edit) // * @return bool // */ -// public function isSemiProtected( $action = 'edit' ) { +// public function isSemiProtected($action = 'edit') { // global $wgSemiprotectedRestrictionLevels; // -// $restrictions = $this->getRestrictions( $action ); +// $restrictions = this.getRestrictions($action); // $semi = $wgSemiprotectedRestrictionLevels; -// if ( !$restrictions || !$semi ) { +// if (!$restrictions || !$semi) { // // Not protected, or all protection is full protection // return false; // } // // // Remap autoconfirmed to editsemiprotected for BC -// foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) { +// foreach (array_keys($semi, 'autoconfirmed') as $key) { // $semi[$key] = 'editsemiprotected'; // } -// foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) { +// foreach (array_keys($restrictions, 'autoconfirmed') as $key) { // $restrictions[$key] = 'editsemiprotected'; // } // -// return !array_diff( $restrictions, $semi ); +// return !array_diff($restrictions, $semi); // } // // /** @@ -2372,22 +2384,22 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * by default checks all actions. // * @return bool // */ -// public function isProtected( $action = '' ) { +// public function isProtected($action = "") { // global $wgRestrictionLevels; // -// $restrictionTypes = $this->getRestrictionTypes(); +// $restrictionTypes = this.getRestrictionTypes(); // // # Special pages have inherent protection -// if ( $this->isSpecialPage() ) { +// if (this.isSpecialPage()) { // return true; // } // // # Check regular protection levels -// foreach ( $restrictionTypes as $type ) { -// if ( $action == $type || $action == '' ) { -// $r = $this->getRestrictions( $type ); -// foreach ( $wgRestrictionLevels as $level ) { -// if ( in_array( $level, $r ) && $level != '' ) { +// foreach ($restrictionTypes as $type) { +// if ($action == $type || $action == "") { +// $r = this.getRestrictions($type); +// foreach ($wgRestrictionLevels as $level) { +// if (in_array($level, $r) && $level != "") { // return true; // } // } @@ -2404,12 +2416,12 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param User $user User object to check permissions // * @return bool // */ -// public function isNamespaceProtected( User $user ) { +// public function isNamespaceProtected(User $user) { // global $wgNamespaceProtection; // -// if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) { -// foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) { -// if ( $right != '' && !$user->isAllowed( $right ) ) { +// if (isset($wgNamespaceProtection[this.mNamespace])) { +// foreach ((array)$wgNamespaceProtection[this.mNamespace] as $right) { +// if ($right != "" && !$user.isAllowed($right)) { // return true; // } // } @@ -2423,8 +2435,8 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return bool If the page is subject to cascading restrictions. // */ // public function isCascadeProtected() { -// list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false ); -// return ( $sources > 0 ); +// list($sources, /* $restrictions */) = this.getCascadeProtectionSources(false); +// return ($sources > 0); // } // // /** @@ -2436,8 +2448,8 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return bool Whether or not the specified information has been loaded // * @since 1.23 // */ -// public function areCascadeProtectionSourcesLoaded( $getPages = true ) { -// return $getPages ? $this->mCascadeSources !== null : $this->mHasCascadingRestrictions !== null; +// public function areCascadeProtectionSourcesLoaded($getPages = true) { +// return $getPages ? this.mCascadeSources !== null : this.mHasCascadingRestrictions !== null; // } // // /** @@ -2453,68 +2465,68 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * Title::getAllRestrictions(), or an empty array if $getPages is // * false. // */ -// public function getCascadeProtectionSources( $getPages = true ) { -// $pagerestrictions = []; +// public function getCascadeProtectionSources($getPages = true) { +// $pagerestrictions = new XophpArray(); // -// if ( $this->mCascadeSources !== null && $getPages ) { -// return [ $this->mCascadeSources, $this->mCascadingRestrictions ]; -// } elseif ( $this->mHasCascadingRestrictions !== null && !$getPages ) { -// return [ $this->mHasCascadingRestrictions, $pagerestrictions ]; +// if (this.mCascadeSources !== null && $getPages) { +// return [ this.mCascadeSources, this.mCascadingRestrictions ]; +// } elseif (this.mHasCascadingRestrictions !== null && !$getPages) { +// return [ this.mHasCascadingRestrictions, $pagerestrictions ]; // } // -// $dbr = wfGetDB( DB_REPLICA ); +// $dbr = wfGetDB(DB_REPLICA); // -// if ( $this->mNamespace == NS_FILE ) { +// if (this.mNamespace == NS_FILE) { // $tables = [ 'imagelinks', 'page_restrictions' ]; // $where_clauses = [ -// 'il_to' => $this->mDbkeyform, +// 'il_to' => this.mDbkeyform, // 'il_from=pr_page', // 'pr_cascade' => 1 // ]; // } else { // $tables = [ 'templatelinks', 'page_restrictions' ]; // $where_clauses = [ -// 'tl_namespace' => $this->mNamespace, -// 'tl_title' => $this->mDbkeyform, +// 'tl_namespace' => this.mNamespace, +// 'tl_title' => this.mDbkeyform, // 'tl_from=pr_page', // 'pr_cascade' => 1 // ]; // } // -// if ( $getPages ) { +// if ($getPages) { // $cols = [ 'pr_page', 'page_namespace', 'page_title', // 'pr_expiry', 'pr_type', 'pr_level' ]; -// $where_clauses[] = 'page_id=pr_page'; -// $tables[] = 'page'; +// $where_clausesnew XophpArray() = 'page_id=pr_page'; +// $tablesnew XophpArray() = 'page'; // } else { // $cols = [ 'pr_expiry' ]; // } // -// $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ ); +// $res = $dbr.select($tables, $cols, $where_clauses, __METHOD__); // -// $sources = $getPages ? [] : false; +// $sources = $getPages ? new XophpArray() : false; // $now = wfTimestampNow(); // -// foreach ( $res as $row ) { -// $expiry = $dbr->decodeExpiry( $row->pr_expiry ); -// if ( $expiry > $now ) { -// if ( $getPages ) { -// $page_id = $row->pr_page; -// $page_ns = $row->page_namespace; -// $page_title = $row->page_title; -// $sources[$page_id] = self::makeTitle( $page_ns, $page_title ); +// foreach ($res as $row) { +// $expiry = $dbr.decodeExpiry($row.pr_expiry); +// if ($expiry > $now) { +// if ($getPages) { +// $page_id = $row.pr_page; +// $page_ns = $row.page_namespace; +// $page_title = $row.page_title; +// $sources[$page_id] = self::makeTitle($page_ns, $page_title); // # Add groups needed for each restriction type if its not already there // # Make sure this restriction type still exists // -// if ( !isset( $pagerestrictions[$row->pr_type] ) ) { -// $pagerestrictions[$row->pr_type] = []; +// if (!isset($pagerestrictions[$row.pr_type])) { +// $pagerestrictions[$row.pr_type] = new XophpArray(); // } // // if ( -// isset( $pagerestrictions[$row->pr_type] ) -// && !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] ) +// isset($pagerestrictions[$row.pr_type]) +// && !in_array($row.pr_level, $pagerestrictions[$row.pr_type]) // ) { -// $pagerestrictions[$row->pr_type][] = $row->pr_level; +// $pagerestrictions[$row.pr_type]new XophpArray() = $row.pr_level; // } // } else { // $sources = true; @@ -2522,11 +2534,11 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // } // } // -// if ( $getPages ) { -// $this->mCascadeSources = $sources; -// $this->mCascadingRestrictions = $pagerestrictions; +// if ($getPages) { +// this.mCascadeSources = $sources; +// this.mCascadingRestrictions = $pagerestrictions; // } else { -// $this->mHasCascadingRestrictions = $sources; +// this.mHasCascadingRestrictions = $sources; // } // // return [ $sources, $pagerestrictions ]; @@ -2540,7 +2552,7 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @since 1.23 // */ // public function areRestrictionsLoaded() { -// return $this->mRestrictionsLoaded; +// return this.mRestrictionsLoaded; // } // // /** @@ -2552,11 +2564,11 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * and 'autoconfirmed' are also allowed for backwards compatibility. These should // * be mapped to 'editprotected' and 'editsemiprotected' respectively. // */ -// public function getRestrictions( $action ) { -// if ( !$this->mRestrictionsLoaded ) { -// $this->loadRestrictions(); +// public function getRestrictions($action) { +// if (!this.mRestrictionsLoaded) { +// this.loadRestrictions(); // } -// return $this->mRestrictions[$action] ?? []; +// return this.mRestrictions[$action] ?? new XophpArray(); // } // // /** @@ -2567,10 +2579,10 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @since 1.23 // */ // public function getAllRestrictions() { -// if ( !$this->mRestrictionsLoaded ) { -// $this->loadRestrictions(); +// if (!this.mRestrictionsLoaded) { +// this.loadRestrictions(); // } -// return $this->mRestrictions; +// return this.mRestrictions; // } // // /** @@ -2580,11 +2592,11 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever // * or not protected at all, or false if the action is not recognised. // */ -// public function getRestrictionExpiry( $action ) { -// if ( !$this->mRestrictionsLoaded ) { -// $this->loadRestrictions(); +// public function getRestrictionExpiry($action) { +// if (!this.mRestrictionsLoaded) { +// this.loadRestrictions(); // } -// return $this->mRestrictionsExpiry[$action] ?? false; +// return this.mRestrictionsExpiry[$action] ?? false; // } // // /** @@ -2593,11 +2605,11 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return bool // */ // function areRestrictionsCascading() { -// if ( !$this->mRestrictionsLoaded ) { -// $this->loadRestrictions(); +// if (!this.mRestrictionsLoaded) { +// this.loadRestrictions(); // } // -// return $this->mCascadeRestriction; +// return this.mCascadeRestriction; // } // // /** @@ -2611,72 +2623,72 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * Edit and move sections are separated by a colon // * Example: "edit=autoconfirmed,sysop:move=sysop" // */ -// public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) { +// public function loadRestrictionsFromRows($rows, $oldFashionedRestrictions = null) { // // This function will only read rows from a table that we migrated away // // from before adding READ_LATEST support to loadRestrictions, so we // // don't need to support reading from DB_MASTER here. -// $dbr = wfGetDB( DB_REPLICA ); +// $dbr = wfGetDB(DB_REPLICA); // -// $restrictionTypes = $this->getRestrictionTypes(); +// $restrictionTypes = this.getRestrictionTypes(); // -// foreach ( $restrictionTypes as $type ) { -// $this->mRestrictions[$type] = []; -// $this->mRestrictionsExpiry[$type] = 'infinity'; +// foreach ($restrictionTypes as $type) { +// this.mRestrictions[$type] = new XophpArray(); +// this.mRestrictionsExpiry[$type] = 'infinity'; // } // -// $this->mCascadeRestriction = false; +// this.mCascadeRestriction = false; // // # Backwards-compatibility: also load the restrictions from the page record (old format). -// if ( $oldFashionedRestrictions !== null ) { -// $this->mOldRestrictions = $oldFashionedRestrictions; +// if ($oldFashionedRestrictions !== null) { +// this.mOldRestrictions = $oldFashionedRestrictions; // } // -// if ( $this->mOldRestrictions === false ) { -// $linkCache = MediaWikiServices::getInstance()->getLinkCache(); -// $linkCache->addLinkObj( $this ); # in case we already had an article ID -// $this->mOldRestrictions = $linkCache->getGoodLinkFieldObj( $this, 'restrictions' ); +// if (this.mOldRestrictions === false) { +// $linkCache = MediaWikiServices::getInstance().getLinkCache(); +// $linkCache.addLinkObj(this); # in case we already had an article ID +// this.mOldRestrictions = $linkCache.getGoodLinkFieldObj(this, 'restrictions'); // } // -// if ( $this->mOldRestrictions != '' ) { -// foreach ( explode( ':', trim( $this->mOldRestrictions ) ) as $restrict ) { -// $temp = explode( '=', trim( $restrict ) ); -// if ( count( $temp ) == 1 ) { +// if (this.mOldRestrictions != "") { +// foreach (explode(':', trim(this.mOldRestrictions)) as $restrict) { +// $temp = explode('=', trim($restrict)); +// if (count($temp) == 1) { // // old old format should be treated as edit/move restriction -// $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) ); -// $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) ); +// this.mRestrictions['edit'] = explode(',', trim($temp[0])); +// this.mRestrictions['move'] = explode(',', trim($temp[0])); // } else { -// $restriction = trim( $temp[1] ); -// if ( $restriction != '' ) { // some old entries are empty -// $this->mRestrictions[$temp[0]] = explode( ',', $restriction ); +// $restriction = trim($temp[1]); +// if ($restriction != "") { // some old entries are empty +// this.mRestrictions[$temp[0]] = explode(',', $restriction); // } // } // } // } // -// if ( count( $rows ) ) { +// if (count($rows)) { // # Current system - load second to make them override. // $now = wfTimestampNow(); // // # Cycle through all the restrictions. -// foreach ( $rows as $row ) { +// foreach ($rows as $row) { // // Don't take care of restrictions types that aren't allowed -// if ( !in_array( $row->pr_type, $restrictionTypes ) ) { +// if (!in_array($row.pr_type, $restrictionTypes)) { // continue; // } // -// $expiry = $dbr->decodeExpiry( $row->pr_expiry ); +// $expiry = $dbr.decodeExpiry($row.pr_expiry); // // // Only apply the restrictions if they haven't expired! -// if ( !$expiry || $expiry > $now ) { -// $this->mRestrictionsExpiry[$row->pr_type] = $expiry; -// $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) ); +// if (!$expiry || $expiry > $now) { +// this.mRestrictionsExpiry[$row.pr_type] = $expiry; +// this.mRestrictions[$row.pr_type] = explode(',', trim($row.pr_level)); // -// $this->mCascadeRestriction |= $row->pr_cascade; +// this.mCascadeRestriction |= $row.pr_cascade; // } // } // } // -// $this->mRestrictionsLoaded = true; +// this.mRestrictionsLoaded = true; // } // // /** @@ -2689,21 +2701,21 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param int $flags A bit field. If self::READ_LATEST is set, skip replicas and read // * from the master DB. // */ -// public function loadRestrictions( $oldFashionedRestrictions = null, $flags = 0 ) { -// $readLatest = DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST ); -// if ( $this->mRestrictionsLoaded && !$readLatest ) { +// public function loadRestrictions($oldFashionedRestrictions = null, $flags = 0) { +// $readLatest = DBAccessObjectUtils::hasFlags($flags, self::READ_LATEST); +// if (this.mRestrictionsLoaded && !$readLatest) { // return; // } // // // TODO: should probably pass $flags into getArticleID, but it seems hacky // // to mix READ_LATEST and GAID_FOR_UPDATE, even if they have the same value. // // Maybe deprecate GAID_FOR_UPDATE now that we implement IDBAccessObject? -// $id = $this->getArticleID(); -// if ( $id ) { +// $id = this.getArticleID(); +// if ($id) { // $fname = __METHOD__; -// $loadRestrictionsFromDb = function ( IDatabase $dbr ) use ( $fname, $id ) { +// $loadRestrictionsFromDb = function (IDatabase $dbr) use ($fname, $id) { // return iterator_to_array( -// $dbr->select( +// $dbr.select( // 'page_restrictions', // [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ], // [ 'pr_page' => $id ], @@ -2712,50 +2724,50 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // ); // }; // -// if ( $readLatest ) { -// $dbr = wfGetDB( DB_MASTER ); -// $rows = $loadRestrictionsFromDb( $dbr ); +// if ($readLatest) { +// $dbr = wfGetDB(DB_MASTER); +// $rows = $loadRestrictionsFromDb($dbr); // } else { -// $cache = MediaWikiServices::getInstance()->getMainWANObjectCache(); -// $rows = $cache->getWithSetCallback( +// $cache = MediaWikiServices::getInstance().getMainWANObjectCache(); +// $rows = $cache.getWithSetCallback( // // Page protections always leave a new null revision -// $cache->makeKey( 'page-restrictions', 'v1', $id, $this->getLatestRevID() ), +// $cache.makeKey('page-restrictions', 'v1', $id, this.getLatestRevID()), // $cache::TTL_DAY, -// function ( $curValue, &$ttl, array &$setOpts ) use ( $loadRestrictionsFromDb ) { -// $dbr = wfGetDB( DB_REPLICA ); +// function ($curValue, &$ttl, array &$setOpts) use ($loadRestrictionsFromDb) { +// $dbr = wfGetDB(DB_REPLICA); // -// $setOpts += Database::getCacheSetOptions( $dbr ); -// $lb = MediaWikiServices::getInstance()->getDBLoadBalancer(); -// if ( $lb->hasOrMadeRecentMasterChanges() ) { +// $setOpts += Database::getCacheSetOptions($dbr); +// $lb = MediaWikiServices::getInstance().getDBLoadBalancer(); +// if ($lb.hasOrMadeRecentMasterChanges()) { // // @TODO: cleanup Title cache and caller assumption mess in general // $ttl = WANObjectCache::TTL_UNCACHEABLE; // } // -// return $loadRestrictionsFromDb( $dbr ); +// return $loadRestrictionsFromDb($dbr); // } // ); // } // -// $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions ); +// this.loadRestrictionsFromRows($rows, $oldFashionedRestrictions); // } else { -// $title_protection = $this->getTitleProtectionInternal(); +// $title_protection = this.getTitleProtectionInternal(); // -// if ( $title_protection ) { +// if ($title_protection) { // $now = wfTimestampNow(); -// $expiry = wfGetDB( DB_REPLICA )->decodeExpiry( $title_protection['expiry'] ); +// $expiry = wfGetDB(DB_REPLICA).decodeExpiry($title_protection['expiry']); // -// if ( !$expiry || $expiry > $now ) { +// if (!$expiry || $expiry > $now) { // // Apply the restrictions -// $this->mRestrictionsExpiry['create'] = $expiry; -// $this->mRestrictions['create'] = -// explode( ',', trim( $title_protection['permission'] ) ); +// this.mRestrictionsExpiry['create'] = $expiry; +// this.mRestrictions['create'] = +// explode(',', trim($title_protection['permission'])); // } else { // Get rid of the old restrictions -// $this->mTitleProtection = false; +// this.mTitleProtection = false; // } // } else { -// $this->mRestrictionsExpiry['create'] = 'infinity'; +// this.mRestrictionsExpiry['create'] = 'infinity'; // } -// $this->mRestrictionsLoaded = true; +// this.mRestrictionsLoaded = true; // } // } // @@ -2764,8 +2776,8 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * This is used when updating protection from WikiPage::doUpdateRestrictions(). // */ // public function flushRestrictions() { -// $this->mRestrictionsLoaded = false; -// $this->mTitleProtection = null; +// this.mRestrictionsLoaded = false; +// this.mTitleProtection = null; // } // // /** @@ -2774,39 +2786,39 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows // */ // static function purgeExpiredRestrictions() { -// if ( wfReadOnly() ) { +// if (wfReadOnly()) { // return; // } // -// DeferredUpdates::addUpdate( new AtomicSectionUpdate( -// wfGetDB( DB_MASTER ), +// DeferredUpdates::addUpdate(new AtomicSectionUpdate( +// wfGetDB(DB_MASTER), // __METHOD__, -// function ( IDatabase $dbw, $fname ) { -// $config = MediaWikiServices::getInstance()->getMainConfig(); -// $ids = $dbw->selectFieldValues( +// function (IDatabase $dbw, $fname) { +// $config = MediaWikiServices::getInstance().getMainConfig(); +// $ids = $dbw.selectFieldValues( // 'page_restrictions', // 'pr_id', -// [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ], +// [ 'pr_expiry < ' . $dbw.addQuotes($dbw.timestamp()) ], // $fname, -// [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470 +// [ 'LIMIT' => $config.get('UpdateRowsPerQuery') ] // T135470 // ); -// if ( $ids ) { -// $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname ); +// if ($ids) { +// $dbw.delete('page_restrictions', [ 'pr_id' => $ids ], $fname); // } // } -// ) ); +// )); // -// DeferredUpdates::addUpdate( new AtomicSectionUpdate( -// wfGetDB( DB_MASTER ), +// DeferredUpdates::addUpdate(new AtomicSectionUpdate( +// wfGetDB(DB_MASTER), // __METHOD__, -// function ( IDatabase $dbw, $fname ) { -// $dbw->delete( +// function (IDatabase $dbw, $fname) { +// $dbw.delete( // 'protected_titles', -// [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ], +// [ 'pt_expiry < ' . $dbw.addQuotes($dbw.timestamp()) ], // $fname // ); // } -// ) ); +// )); // } // // /** @@ -2815,7 +2827,7 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return bool // */ // public function hasSubpages() { -// if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) { +// if (!MWNamespace::hasSubpages(this.mNamespace)) { // # Duh // return false; // } @@ -2824,15 +2836,15 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // # alone to cache the result. There's no point in having it hanging // # around uninitialized in every Title object; therefore we only add it // # if needed and don't declare it statically. -// if ( $this->mHasSubpages === null ) { -// $this->mHasSubpages = false; -// $subpages = $this->getSubpages( 1 ); -// if ( $subpages instanceof TitleArray ) { -// $this->mHasSubpages = (bool)$subpages->count(); +// if (this.mHasSubpages === null) { +// this.mHasSubpages = false; +// $subpages = this.getSubpages(1); +// if ($subpages instanceof TitleArray) { +// this.mHasSubpages = (bool)$subpages.count(); // } // } // -// return $this->mHasSubpages; +// return this.mHasSubpages; // } // // /** @@ -2842,20 +2854,20 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return TitleArray|array TitleArray, or empty array if this page's namespace // * doesn't allow subpages // */ -// public function getSubpages( $limit = -1 ) { -// if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) { -// return []; +// public function getSubpages($limit = -1) { +// if (!MWNamespace::hasSubpages(this.mNamespace)) { +// return new XophpArray(); // } // -// $dbr = wfGetDB( DB_REPLICA ); -// $conds['page_namespace'] = $this->mNamespace; -// $conds[] = 'page_title ' . $dbr->buildLike( $this->mDbkeyform . '/', $dbr->anyString() ); -// $options = []; -// if ( $limit > -1 ) { +// $dbr = wfGetDB(DB_REPLICA); +// $conds['page_namespace'] = this.mNamespace; +// $condsnew XophpArray() = 'page_title ' . $dbr.buildLike(this.mDbkeyform . '/', $dbr.anyString()); +// $options = new XophpArray(); +// if ($limit > -1) { // $options['LIMIT'] = $limit; // } // return TitleArray::newFromResult( -// $dbr->select( 'page', +// $dbr.select('page', // [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ], // $conds, // __METHOD__, @@ -2870,18 +2882,18 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return int The number of archived revisions // */ // public function isDeleted() { -// if ( $this->mNamespace < 0 ) { +// if (this.mNamespace < 0) { // $n = 0; // } else { -// $dbr = wfGetDB( DB_REPLICA ); +// $dbr = wfGetDB(DB_REPLICA); // -// $n = $dbr->selectField( 'archive', 'COUNT(*)', -// [ 'ar_namespace' => $this->mNamespace, 'ar_title' => $this->mDbkeyform ], +// $n = $dbr.selectField('archive', 'COUNT(*)', +// [ 'ar_namespace' => this.mNamespace, 'ar_title' => this.mDbkeyform ], // __METHOD__ // ); -// if ( $this->mNamespace == NS_FILE ) { -// $n += $dbr->selectField( 'filearchive', 'COUNT(*)', -// [ 'fa_name' => $this->mDbkeyform ], +// if (this.mNamespace == NS_FILE) { +// $n += $dbr.selectField('filearchive', 'COUNT(*)', +// [ 'fa_name' => this.mDbkeyform ], // __METHOD__ // ); // } @@ -2895,48 +2907,49 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return bool // */ // public function isDeletedQuick() { -// if ( $this->mNamespace < 0 ) { +// if (this.mNamespace < 0) { // return false; // } -// $dbr = wfGetDB( DB_REPLICA ); -// $deleted = (bool)$dbr->selectField( 'archive', '1', -// [ 'ar_namespace' => $this->mNamespace, 'ar_title' => $this->mDbkeyform ], +// $dbr = wfGetDB(DB_REPLICA); +// $deleted = (bool)$dbr.selectField('archive', '1', +// [ 'ar_namespace' => this.mNamespace, 'ar_title' => this.mDbkeyform ], // __METHOD__ // ); -// if ( !$deleted && $this->mNamespace == NS_FILE ) { -// $deleted = (bool)$dbr->selectField( 'filearchive', '1', -// [ 'fa_name' => $this->mDbkeyform ], +// if (!$deleted && this.mNamespace == NS_FILE) { +// $deleted = (bool)$dbr.selectField('filearchive', '1', +// [ 'fa_name' => this.mDbkeyform ], // __METHOD__ // ); // } // return $deleted; // } -// -// /** -// * Get the article ID for this Title from the link cache, -// * adding it if necessary -// * -// * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select -// * for update -// * @return int The ID -// */ -// public function getArticleID( $flags = 0 ) { -// if ( $this->mNamespace < 0 ) { -// $this->mArticleID = 0; -// return $this->mArticleID; + + /** + * Get the article ID for this Title from the link cache, + * adding it if necessary + * + * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select + * for update + * @return int The ID + */ + public int getArticleID() {return getArticleID(0);} + public int getArticleID(int flags) { + if (this.mNamespace < 0) { + this.mArticleID = 0; + return this.mArticleID; + } +// $linkCache = MediaWikiServices::getInstance().getLinkCache(); +// if (flags & self::GAID_FOR_UPDATE) { +// $oldUpdate = $linkCache.forUpdate(true); +// $linkCache.clearLink(this); +// this.mArticleID = $linkCache.addLinkObj(this); +// $linkCache.forUpdate($oldUpdate); +// } elseif (this.mArticleID == -1) { +// this.mArticleID = $linkCache.addLinkObj(this); // } -// $linkCache = MediaWikiServices::getInstance()->getLinkCache(); -// if ( $flags & self::GAID_FOR_UPDATE ) { -// $oldUpdate = $linkCache->forUpdate( true ); -// $linkCache->clearLink( $this ); -// $this->mArticleID = $linkCache->addLinkObj( $this ); -// $linkCache->forUpdate( $oldUpdate ); -// } elseif ( $this->mArticleID == -1 ) { -// $this->mArticleID = $linkCache->addLinkObj( $this ); -// } -// return $this->mArticleID; -// } -// + return this.mArticleID; + } + // /** // * Is this an article that is a redirect page? // * Uses link cache, adding it if necessary @@ -2944,32 +2957,32 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update // * @return bool // */ -// public function isRedirect( $flags = 0 ) { -// if ( !is_null( $this->mRedirect ) ) { -// return $this->mRedirect; +// public function isRedirect($flags = 0) { +// if (!is_null(this.mRedirect)) { +// return this.mRedirect; // } -// if ( !$this->getArticleID( $flags ) ) { -// $this->mRedirect = false; -// return $this->mRedirect; +// if (!this.getArticleID($flags)) { +// this.mRedirect = false; +// return this.mRedirect; // } // -// $linkCache = MediaWikiServices::getInstance()->getLinkCache(); -// $linkCache->addLinkObj( $this ); # in case we already had an article ID -// $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' ); -// if ( $cached === null ) { +// $linkCache = MediaWikiServices::getInstance().getLinkCache(); +// $linkCache.addLinkObj(this); # in case we already had an article ID +// $cached = $linkCache.getGoodLinkFieldObj(this, 'redirect'); +// if ($cached === null) { // # Trust LinkCache's state over our own // # LinkCache is telling us that the page doesn't exist, despite there being cached -// # data relating to an existing page in $this->mArticleID. Updaters should clear +// # data relating to an existing page in this.mArticleID. Updaters should clear // # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is // # set, then LinkCache will definitely be up to date here, since getArticleID() forces // # LinkCache to refresh its data from the master. -// $this->mRedirect = false; -// return $this->mRedirect; +// this.mRedirect = false; +// return this.mRedirect; // } // -// $this->mRedirect = (bool)$cached; +// this.mRedirect = (bool)$cached; // -// return $this->mRedirect; +// return this.mRedirect; // } // // /** @@ -2979,26 +2992,26 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update // * @return int // */ -// public function getLength( $flags = 0 ) { -// if ( $this->mLength != -1 ) { -// return $this->mLength; +// public function getLength($flags = 0) { +// if (this.mLength != -1) { +// return this.mLength; // } -// if ( !$this->getArticleID( $flags ) ) { -// $this->mLength = 0; -// return $this->mLength; +// if (!this.getArticleID($flags)) { +// this.mLength = 0; +// return this.mLength; // } -// $linkCache = MediaWikiServices::getInstance()->getLinkCache(); -// $linkCache->addLinkObj( $this ); # in case we already had an article ID -// $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' ); -// if ( $cached === null ) { +// $linkCache = MediaWikiServices::getInstance().getLinkCache(); +// $linkCache.addLinkObj(this); # in case we already had an article ID +// $cached = $linkCache.getGoodLinkFieldObj(this, 'length'); +// if ($cached === null) { // # Trust LinkCache's state over our own, as for isRedirect() -// $this->mLength = 0; -// return $this->mLength; +// this.mLength = 0; +// return this.mLength; // } // -// $this->mLength = intval( $cached ); +// this.mLength = intval($cached); // -// return $this->mLength; +// return this.mLength; // } // // /** @@ -3007,26 +3020,26 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update // * @return int Int or 0 if the page doesn't exist // */ -// public function getLatestRevID( $flags = 0 ) { -// if ( !( $flags & self::GAID_FOR_UPDATE ) && $this->mLatestID !== false ) { -// return intval( $this->mLatestID ); +// public function getLatestRevID($flags = 0) { +// if (!($flags & self::GAID_FOR_UPDATE) && this.mLatestID !== false) { +// return intval(this.mLatestID); // } -// if ( !$this->getArticleID( $flags ) ) { -// $this->mLatestID = 0; -// return $this->mLatestID; +// if (!this.getArticleID($flags)) { +// this.mLatestID = 0; +// return this.mLatestID; // } -// $linkCache = MediaWikiServices::getInstance()->getLinkCache(); -// $linkCache->addLinkObj( $this ); # in case we already had an article ID -// $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' ); -// if ( $cached === null ) { +// $linkCache = MediaWikiServices::getInstance().getLinkCache(); +// $linkCache.addLinkObj(this); # in case we already had an article ID +// $cached = $linkCache.getGoodLinkFieldObj(this, 'revision'); +// if ($cached === null) { // # Trust LinkCache's state over our own, as for isRedirect() -// $this->mLatestID = 0; -// return $this->mLatestID; +// this.mLatestID = 0; +// return this.mLatestID; // } // -// $this->mLatestID = intval( $cached ); +// this.mLatestID = intval($cached); // -// return $this->mLatestID; +// return this.mLatestID; // } // // /** @@ -3039,34 +3052,34 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * // * @param int $newid The new Article ID // */ -// public function resetArticleID( $newid ) { -// $linkCache = MediaWikiServices::getInstance()->getLinkCache(); -// $linkCache->clearLink( $this ); +// public function resetArticleID($newid) { +// $linkCache = MediaWikiServices::getInstance().getLinkCache(); +// $linkCache.clearLink(this); // -// if ( $newid === false ) { -// $this->mArticleID = -1; +// if ($newid === false) { +// this.mArticleID = -1; // } else { -// $this->mArticleID = intval( $newid ); +// this.mArticleID = intval($newid); // } -// $this->mRestrictionsLoaded = false; -// $this->mRestrictions = []; -// $this->mOldRestrictions = false; -// $this->mRedirect = null; -// $this->mLength = -1; -// $this->mLatestID = false; -// $this->mContentModel = false; -// $this->mEstimateRevisions = null; -// $this->mPageLanguage = false; -// $this->mDbPageLanguage = false; -// $this->mIsBigDeletion = null; +// this.mRestrictionsLoaded = false; +// this.mRestrictions = new XophpArray(); +// this.mOldRestrictions = false; +// this.mRedirect = null; +// this.mLength = -1; +// this.mLatestID = false; +// this.mContentModel = false; +// this.mEstimateRevisions = null; +// this.mPageLanguage = false; +// this.mDbPageLanguage = false; +// this.mIsBigDeletion = null; // } // // public static function clearCaches() { -// $linkCache = MediaWikiServices::getInstance()->getLinkCache(); -// $linkCache->clear(); +// $linkCache = MediaWikiServices::getInstance().getLinkCache(); +// $linkCache.clear(); // // $titleCache = self::getTitleCache(); -// $titleCache->clear(); +// $titleCache.clear(); // } // // /** @@ -3076,9 +3089,9 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param int $ns Namespace index, defaults to NS_MAIN // * @return string Containing capitalized title // */ -// public static function capitalize( $text, $ns = NS_MAIN ) { -// if ( MWNamespace::isCapitalized( $ns ) ) { -// return MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $text ); +// public static function capitalize($text, $ns = NS_MAIN) { +// if (MWNamespace::isCapitalized($ns)) { +// return MediaWikiServices::getInstance().getContentLanguage().ucfirst($text); // } else { // return $text; // } @@ -3103,24 +3116,24 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // // @note: getTitleParser() returns a TitleParser implementation which does not have a // // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does // /** @var MediaWikiTitleCodec $titleCodec */ -// $titleCodec = MediaWikiServices::getInstance()->getTitleParser(); +// $titleCodec = MediaWikiServices::getInstance().getTitleParser(); // // MalformedTitleException can be thrown here -// $parts = $titleCodec->splitTitleString( $this->mDbkeyform, $this->mDefaultNamespace ); +// $parts = $titleCodec.splitTitleString(this.mDbkeyform, this.mDefaultNamespace); // // # Fill fields -// $this->setFragment( '#' . $parts['fragment'] ); -// $this->mInterwiki = $parts['interwiki']; -// $this->mLocalInterwiki = $parts['local_interwiki']; -// $this->mNamespace = $parts['namespace']; -// $this->mUserCaseDBKey = $parts['user_case_dbkey']; +// this.setFragment('#' . $parts['fragment']); +// this.mInterwiki = $parts['interwiki']; +// this.mLocalInterwiki = $parts['local_interwiki']; +// this.mNamespace = $parts['namespace']; +// this.mUserCaseDBKey = $parts['user_case_dbkey']; // -// $this->mDbkeyform = $parts['dbkey']; -// $this->mUrlform = wfUrlencode( $this->mDbkeyform ); -// $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' ); +// this.mDbkeyform = $parts['dbkey']; +// this.mUrlform = wfUrlencode(this.mDbkeyform); +// this.mTextform = strtr(this.mDbkeyform, '_', ' '); // // # We already know that some pages won't be in the database! -// if ( $this->isExternal() || $this->isSpecialPage() ) { -// $this->mArticleID = 0; +// if (this.isExternal() || this.isSpecialPage()) { +// this.mArticleID = 0; // } // // return true; @@ -3136,34 +3149,34 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param array $options May be FOR UPDATE // * @param string $table Table name // * @param string $prefix Fields prefix -// * @return Title[] Array of Title objects linking here +// * @return Titlenew XophpArray() Array of Title objects linking here // */ -// public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) { -// if ( count( $options ) > 0 ) { -// $db = wfGetDB( DB_MASTER ); +// public function getLinksTo($options = new XophpArray(), $table = 'pagelinks', $prefix = 'pl') { +// if (count($options) > 0) { +// $db = wfGetDB(DB_MASTER); // } else { -// $db = wfGetDB( DB_REPLICA ); +// $db = wfGetDB(DB_REPLICA); // } // -// $res = $db->select( +// $res = $db.select( // [ 'page', $table ], // self::getSelectFields(), // [ // "{$prefix}_from=page_id", -// "{$prefix}_namespace" => $this->mNamespace, -// "{$prefix}_title" => $this->mDbkeyform ], +// "{$prefix}_namespace" => this.mNamespace, +// "{$prefix}_title" => this.mDbkeyform ], // __METHOD__, // $options // ); // -// $retVal = []; -// if ( $res->numRows() ) { -// $linkCache = MediaWikiServices::getInstance()->getLinkCache(); -// foreach ( $res as $row ) { -// $titleObj = self::makeTitle( $row->page_namespace, $row->page_title ); -// if ( $titleObj ) { -// $linkCache->addGoodLinkObjFromRow( $titleObj, $row ); -// $retVal[] = $titleObj; +// $retVal = new XophpArray(); +// if ($res.numRows()) { +// $linkCache = MediaWikiServices::getInstance().getLinkCache(); +// foreach ($res as $row) { +// $titleObj = self::makeTitle($row.page_namespace, $row.page_title); +// if ($titleObj) { +// $linkCache.addGoodLinkObjFromRow($titleObj, $row); +// $retValnew XophpArray() = $titleObj; // } // } // } @@ -3178,10 +3191,10 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * On heavily-used templates it will max out the memory. // * // * @param array $options Query option to Database::select() -// * @return Title[] Array of Title the Title objects linking here +// * @return Titlenew XophpArray() Array of Title the Title objects linking here // */ -// public function getTemplateLinksTo( $options = [] ) { -// return $this->getLinksTo( $options, 'templatelinks', 'tl' ); +// public function getTemplateLinksTo($options = new XophpArray()) { +// return this.getLinksTo($options, 'templatelinks', 'tl'); // } // // /** @@ -3196,21 +3209,21 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param string $prefix Fields prefix // * @return array Array of Title objects linking here // */ -// public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) { -// $id = $this->getArticleID(); +// public function getLinksFrom($options = new XophpArray(), $table = 'pagelinks', $prefix = 'pl') { +// $id = this.getArticleID(); // // # If the page doesn't exist; there can't be any link from this page -// if ( !$id ) { -// return []; +// if (!$id) { +// return new XophpArray(); // } // -// $db = wfGetDB( DB_REPLICA ); +// $db = wfGetDB(DB_REPLICA); // // $blNamespace = "{$prefix}_namespace"; // $blTitle = "{$prefix}_title"; // // $pageQuery = WikiPage::getQueryInfo(); -// $res = $db->select( +// $res = $db.select( // [ $table, 'nestpage' => $pageQuery['tables'] ], // array_merge( // [ $blNamespace, $blTitle ], @@ -3225,16 +3238,16 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // ] ] + $pageQuery['joins'] // ); // -// $retVal = []; -// $linkCache = MediaWikiServices::getInstance()->getLinkCache(); -// foreach ( $res as $row ) { -// if ( $row->page_id ) { -// $titleObj = self::newFromRow( $row ); +// $retVal = new XophpArray(); +// $linkCache = MediaWikiServices::getInstance().getLinkCache(); +// foreach ($res as $row) { +// if ($row.page_id) { +// $titleObj = self::newFromRow($row); // } else { -// $titleObj = self::makeTitle( $row->$blNamespace, $row->$blTitle ); -// $linkCache->addBadLinkObj( $titleObj ); +// $titleObj = self::makeTitle($row.$blNamespace, $row.$blTitle); +// $linkCache.addBadLinkObj($titleObj); // } -// $retVal[] = $titleObj; +// $retValnew XophpArray() = $titleObj; // } // // return $retVal; @@ -3248,10 +3261,10 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * On heavily-used templates it will max out the memory. // * // * @param array $options May be FOR UPDATE -// * @return Title[] Array of Title the Title objects used here +// * @return Titlenew XophpArray() Array of Title the Title objects used here // */ -// public function getTemplateLinksFrom( $options = [] ) { -// return $this->getLinksFrom( $options, 'templatelinks', 'tl' ); +// public function getTemplateLinksFrom($options = new XophpArray()) { +// return this.getLinksFrom($options, 'templatelinks', 'tl'); // } // // /** @@ -3260,23 +3273,23 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * // * @todo check if needed (used only in SpecialBrokenRedirects.php, and // * should use redirect table in this case). -// * @return Title[] Array of Title the Title objects +// * @return Titlenew XophpArray() Array of Title the Title objects // */ // public function getBrokenLinksFrom() { -// if ( $this->getArticleID() == 0 ) { +// if (this.getArticleID() == 0) { // # All links from article ID 0 are false positives -// return []; +// return new XophpArray(); // } // -// $dbr = wfGetDB( DB_REPLICA ); -// $res = $dbr->select( +// $dbr = wfGetDB(DB_REPLICA); +// $res = $dbr.select( // [ 'page', 'pagelinks' ], // [ 'pl_namespace', 'pl_title' ], // [ -// 'pl_from' => $this->getArticleID(), +// 'pl_from' => this.getArticleID(), // 'page_namespace IS NULL' // ], -// __METHOD__, [], +// __METHOD__, new XophpArray(), // [ // 'page' => [ // 'LEFT JOIN', @@ -3285,9 +3298,9 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // ] // ); // -// $retVal = []; -// foreach ( $res as $row ) { -// $retVal[] = self::makeTitle( $row->pl_namespace, $row->pl_title ); +// $retVal = new XophpArray(); +// foreach ($res as $row) { +// $retValnew XophpArray() = self::makeTitle($row.pl_namespace, $row.pl_title); // } // return $retVal; // } @@ -3296,32 +3309,32 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * Get a list of URLs to purge from the CDN cache when this // * page changes // * -// * @return string[] Array of String the URLs +// * @return stringnew XophpArray() Array of String the URLs // */ // public function getCdnUrls() { // $urls = [ -// $this->getInternalURL(), -// $this->getInternalURL( 'action=history' ) +// this.getInternalURL(), +// this.getInternalURL('action=history') // ]; // -// $pageLang = $this->getPageLanguage(); -// if ( $pageLang->hasVariants() ) { -// $variants = $pageLang->getVariants(); -// foreach ( $variants as $vCode ) { -// $urls[] = $this->getInternalURL( $vCode ); +// $pageLang = this.getPageLanguage(); +// if ($pageLang.hasVariants()) { +// $variants = $pageLang.getVariants(); +// foreach ($variants as $vCode) { +// $urlsnew XophpArray() = this.getInternalURL($vCode); // } // } // // // If we are looking at a css/js user subpage, purge the action=raw. -// if ( $this->isUserJsConfigPage() ) { -// $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' ); -// } elseif ( $this->isUserJsonConfigPage() ) { -// $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' ); -// } elseif ( $this->isUserCssConfigPage() ) { -// $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' ); +// if (this.isUserJsConfigPage()) { +// $urlsnew XophpArray() = this.getInternalURL('action=raw&ctype=text/javascript'); +// } elseif (this.isUserJsonConfigPage()) { +// $urlsnew XophpArray() = this.getInternalURL('action=raw&ctype=application/json'); +// } elseif (this.isUserCssConfigPage()) { +// $urlsnew XophpArray() = this.getInternalURL('action=raw&ctype=text/css'); // } // -// Hooks::run( 'TitleSquidURLs', [ $this, &$urls ] ); +// Hooks::run('TitleSquidURLs', [ this, &$urls ]); // return $urls; // } // @@ -3330,7 +3343,7 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // */ // public function purgeSquid() { // DeferredUpdates::addUpdate( -// new CdnCacheUpdate( $this->getCdnUrls() ), +// new CdnCacheUpdate(this.getCdnUrls()), // DeferredUpdates::PRESEND // ); // } @@ -3345,21 +3358,21 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param string $reason Is the log summary of the move, used for spam checking // * @return array|bool True on success, getUserPermissionsErrors()-like array on failure // */ -// public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) { +// public function isValidMoveOperation(&$nt, $auth = true, $reason = "") { // global $wgUser; // -// if ( !( $nt instanceof Title ) ) { +// if (!($nt instanceof Title)) { // // Normally we'd add this to $errors, but we'll get // // lots of syntax errors if $nt is not an object // return [ [ 'badtitletext' ] ]; // } // -// $mp = new MovePage( $this, $nt ); -// $errors = $mp->isValidMove()->getErrorsArray(); -// if ( $auth ) { +// $mp = new MovePage(this, $nt); +// $errors = $mp.isValidMove().getErrorsArray(); +// if ($auth) { // $errors = wfMergeErrorArrays( // $errors, -// $mp->checkPermissions( $wgUser, $reason )->getErrorsArray() +// $mp.checkPermissions($wgUser, $reason).getErrorsArray() // ); // } // @@ -3379,27 +3392,27 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param array $changeTags Applied to the entry in the move log and redirect page revision // * @return array|bool True on success, getUserPermissionsErrors()-like array on failure // */ -// public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true, -// array $changeTags = [] +// public function moveTo(&$nt, $auth = true, $reason = "", $createRedirect = true, +// array $changeTags = new XophpArray() // ) { // global $wgUser; -// $err = $this->isValidMoveOperation( $nt, $auth, $reason ); -// if ( is_array( $err ) ) { +// $err = this.isValidMoveOperation($nt, $auth, $reason); +// if (is_array($err)) { // // Auto-block user's IP if the account was "hard" blocked -// $wgUser->spreadAnyEditBlock(); +// $wgUser.spreadAnyEditBlock(); // return $err; // } // // Check suppressredirect permission -// if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) { +// if ($auth && !$wgUser.isAllowed('suppressredirect')) { // $createRedirect = true; // } // -// $mp = new MovePage( $this, $nt ); -// $status = $mp->move( $wgUser, $reason, $createRedirect, $changeTags ); -// if ( $status->isOK() ) { +// $mp = new MovePage(this, $nt); +// $status = $mp.move($wgUser, $reason, $createRedirect, $changeTags); +// if ($status.isOK()) { // return true; // } else { -// return $status->getErrorsArray(); +// return $status.getErrorsArray(); // } // } // @@ -3417,35 +3430,35 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * getUserPermissionsErrors()-like error array with numeric indices if // * no pages were moved // */ -// public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true, -// array $changeTags = [] +// public function moveSubpages($nt, $auth = true, $reason = "", $createRedirect = true, +// array $changeTags = new XophpArray() // ) { // global $wgMaximumMovedPages; // // Check permissions -// if ( !$this->userCan( 'move-subpages' ) ) { +// if (!this.userCan('move-subpages')) { // return [ // [ 'cant-move-subpages' ], // ]; // } // // Do the source and target namespaces support subpages? -// if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) { +// if (!MWNamespace::hasSubpages(this.mNamespace)) { // return [ -// [ 'namespace-nosubpages', MWNamespace::getCanonicalName( $this->mNamespace ) ], +// [ 'namespace-nosubpages', MWNamespace::getCanonicalName(this.mNamespace) ], // ]; // } -// if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) { +// if (!MWNamespace::hasSubpages($nt.getNamespace())) { // return [ -// [ 'namespace-nosubpages', MWNamespace::getCanonicalName( $nt->getNamespace() ) ], +// [ 'namespace-nosubpages', MWNamespace::getCanonicalName($nt.getNamespace()) ], // ]; // } // -// $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 ); -// $retval = []; +// $subpages = this.getSubpages($wgMaximumMovedPages + 1); +// $retval = new XophpArray(); // $count = 0; -// foreach ( $subpages as $oldSubpage ) { +// foreach ($subpages as $oldSubpage) { // $count++; -// if ( $count > $wgMaximumMovedPages ) { -// $retval[$oldSubpage->getPrefixedText()] = [ +// if ($count > $wgMaximumMovedPages) { +// $retval[$oldSubpage.getPrefixedText()] = [ // [ 'movepage-max-pages', $wgMaximumMovedPages ], // ]; // break; @@ -3453,32 +3466,32 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // // // We don't know whether this function was called before // // or after moving the root page, so check both -// // $this and $nt -// if ( $oldSubpage->getArticleID() == $this->getArticleID() -// || $oldSubpage->getArticleID() == $nt->getArticleID() +// // this and $nt +// if ($oldSubpage.getArticleID() == this.getArticleID() +// || $oldSubpage.getArticleID() == $nt.getArticleID() // ) { // // When moving a page to a subpage of itself, // // don't move it twice // continue; // } // $newPageName = preg_replace( -// '#^' . preg_quote( $this->mDbkeyform, '#' ) . '#', -// StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # T23234 -// $oldSubpage->getDBkey() ); -// if ( $oldSubpage->isTalkPage() ) { -// $newNs = $nt->getTalkPage()->getNamespace(); +// '#^' . preg_quote(this.mDbkeyform, '#') . '#', +// StringUtils::escapeRegexReplacement($nt.getDBkey()), # T23234 +// $oldSubpage.getDBkey()); +// if ($oldSubpage.isTalkPage()) { +// $newNs = $nt.getTalkPage().getNamespace(); // } else { -// $newNs = $nt->getSubjectPage()->getNamespace(); +// $newNs = $nt.getSubjectPage().getNamespace(); // } // # T16385: we need makeTitleSafe because the new page names may // # be longer than 255 characters. -// $newSubpage = self::makeTitleSafe( $newNs, $newPageName ); +// $newSubpage = self::makeTitleSafe($newNs, $newPageName); // -// $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags ); -// if ( $success === true ) { -// $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText(); +// $success = $oldSubpage.moveTo($newSubpage, $auth, $reason, $createRedirect, $changeTags); +// if ($success === true) { +// $retval[$oldSubpage.getPrefixedText()] = $newSubpage.getPrefixedText(); // } else { -// $retval[$oldSubpage->getPrefixedText()] = $success; +// $retval[$oldSubpage.getPrefixedText()] = $success; // } // } // return $retval; @@ -3493,36 +3506,36 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // public function isSingleRevRedirect() { // global $wgContentHandlerUseDB; // -// $dbw = wfGetDB( DB_MASTER ); +// $dbw = wfGetDB(DB_MASTER); // // # Is it a redirect? // $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ]; -// if ( $wgContentHandlerUseDB ) { -// $fields[] = 'page_content_model'; +// if ($wgContentHandlerUseDB) { +// $fieldsnew XophpArray() = 'page_content_model'; // } // -// $row = $dbw->selectRow( 'page', +// $row = $dbw.selectRow('page', // $fields, -// $this->pageCond(), +// this.pageCond(), // __METHOD__, // [ 'FOR UPDATE' ] // ); // # Cache some fields we may want -// $this->mArticleID = $row ? intval( $row->page_id ) : 0; -// $this->mRedirect = $row ? (bool)$row->page_is_redirect : false; -// $this->mLatestID = $row ? intval( $row->page_latest ) : false; -// $this->mContentModel = $row && isset( $row->page_content_model ) -// ? strval( $row->page_content_model ) +// this.mArticleID = $row ? intval($row.page_id) : 0; +// this.mRedirect = $row ? (bool)$row.page_is_redirect : false; +// this.mLatestID = $row ? intval($row.page_latest) : false; +// this.mContentModel = $row && isset($row.page_content_model) +// ? strval($row.page_content_model) // : false; // -// if ( !$this->mRedirect ) { +// if (!this.mRedirect) { // return false; // } // # Does the article have a history? -// $row = $dbw->selectField( [ 'page', 'revision' ], +// $row = $dbw.selectField([ 'page', 'revision' ], // 'rev_id', -// [ 'page_namespace' => $this->mNamespace, -// 'page_title' => $this->mDbkeyform, +// [ 'page_namespace' => this.mNamespace, +// 'page_title' => this.mDbkeyform, // 'page_id=rev_page', // 'page_latest != rev_id' // ], @@ -3530,54 +3543,54 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // [ 'FOR UPDATE' ] // ); // # Return true if there was no history -// return ( $row === false ); +// return ($row === false); // } // // /** -// * Checks if $this can be moved to a given Title +// * Checks if this can be moved to a given Title // * - Selects for update, so don't call it unless you mean business // * // * @deprecated since 1.25, use MovePage's methods instead // * @param Title $nt The new title to check // * @return bool // */ -// public function isValidMoveTarget( $nt ) { +// public function isValidMoveTarget($nt) { // # Is it an existing file? -// if ( $nt->getNamespace() == NS_FILE ) { -// $file = wfLocalFile( $nt ); -// $file->load( File::READ_LATEST ); -// if ( $file->exists() ) { -// wfDebug( __METHOD__ . ": file exists\n" ); +// if ($nt.getNamespace() == NS_FILE) { +// $file = wfLocalFile($nt); +// $file.load(File::READ_LATEST); +// if ($file.exists()) { +// wfDebug(__METHOD__ . ": file exists\n"); // return false; // } // } // # Is it a redirect with no history? -// if ( !$nt->isSingleRevRedirect() ) { -// wfDebug( __METHOD__ . ": not a one-rev redirect\n" ); +// if (!$nt.isSingleRevRedirect()) { +// wfDebug(__METHOD__ . ": not a one-rev redirect\n"); // return false; // } // # Get the article text -// $rev = Revision::newFromTitle( $nt, false, Revision::READ_LATEST ); -// if ( !is_object( $rev ) ) { +// $rev = Revision::newFromTitle($nt, false, Revision::READ_LATEST); +// if (!is_object($rev)) { // return false; // } -// $content = $rev->getContent(); +// $content = $rev.getContent(); // # Does the redirect point to the source? // # Or is it a broken self-redirect, usually caused by namespace collisions? -// $redirTitle = $content ? $content->getRedirectTarget() : null; +// $redirTitle = $content ? $content.getRedirectTarget() : null; // -// if ( $redirTitle ) { -// if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() && -// $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) { -// wfDebug( __METHOD__ . ": redirect points to other page\n" ); +// if ($redirTitle) { +// if ($redirTitle.getPrefixedDBkey() != this.getPrefixedDBkey() && +// $redirTitle.getPrefixedDBkey() != $nt.getPrefixedDBkey()) { +// wfDebug(__METHOD__ . ": redirect points to other page\n"); // return false; // } else { // return true; // } // } else { // # Fail safe (not a redirect after all. strange.) -// wfDebug( __METHOD__ . ": failsafe: database sais " . $nt->getPrefixedDBkey() . -// " is a redirect, but it doesn't contain a valid redirect.\n" ); +// wfDebug(__METHOD__ . ": failsafe: database sais " . $nt.getPrefixedDBkey() . +// " is a redirect, but it doesn't contain a valid redirect.\n"); // return false; // } // } @@ -3590,29 +3603,29 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * $parent => $currentarticle // */ // public function getParentCategories() { -// $data = []; +// $data = new XophpArray(); // -// $titleKey = $this->getArticleID(); +// $titleKey = this.getArticleID(); // -// if ( $titleKey === 0 ) { +// if ($titleKey === 0) { // return $data; // } // -// $dbr = wfGetDB( DB_REPLICA ); +// $dbr = wfGetDB(DB_REPLICA); // -// $res = $dbr->select( +// $res = $dbr.select( // 'categorylinks', // 'cl_to', // [ 'cl_from' => $titleKey ], // __METHOD__ // ); // -// if ( $res->numRows() > 0 ) { -// $contLang = MediaWikiServices::getInstance()->getContentLanguage(); -// foreach ( $res as $row ) { -// // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to); -// $data[$contLang->getNsText( NS_CATEGORY ) . ':' . $row->cl_to] = -// $this->getFullText(); +// if ($res.numRows() > 0) { +// $contLang = MediaWikiServices::getInstance().getContentLanguage(); +// foreach ($res as $row) { +// // $datanew XophpArray() = Title::newFromText($contLang.getNsText (NS_CATEGORY).':'.$row.cl_to); +// $data[$contLang.getNsText(NS_CATEGORY) . ':' . $row.cl_to] = +// this.getFullText(); // } // } // return $data; @@ -3624,19 +3637,19 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param array $children Array with the children in the keys, to check for circular refs // * @return array Tree of parent categories // */ -// public function getParentCategoryTree( $children = [] ) { -// $stack = []; -// $parents = $this->getParentCategories(); +// public function getParentCategoryTree($children = new XophpArray()) { +// $stack = new XophpArray(); +// $parents = this.getParentCategories(); // -// if ( $parents ) { -// foreach ( $parents as $parent => $current ) { -// if ( array_key_exists( $parent, $children ) ) { +// if ($parents) { +// foreach ($parents as $parent => $current) { +// if (array_key_exists($parent, $children)) { // # Circular reference -// $stack[$parent] = []; +// $stack[$parent] = new XophpArray(); // } else { -// $nt = self::newFromText( $parent ); -// if ( $nt ) { -// $stack[$parent] = $nt->getParentCategoryTree( $children + [ $parent => 1 ] ); +// $nt = self::newFromText($parent); +// if ($nt) { +// $stack[$parent] = $nt.getParentCategoryTree($children + [ $parent => 1 ]); // } // } // } @@ -3652,11 +3665,11 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return array Array suitable for the $where parameter of DB::select() // */ // public function pageCond() { -// if ( $this->mArticleID > 0 ) { +// if (this.mArticleID > 0) { // // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs -// return [ 'page_id' => $this->mArticleID ]; +// return [ 'page_id' => this.mArticleID ]; // } else { -// return [ 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform ]; +// return [ 'page_namespace' => this.mNamespace, 'page_title' => this.mDbkeyform ]; // } // } // @@ -3667,39 +3680,39 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param string $dir 'next' or 'prev' // * @return int|bool New revision ID, or false if none exists // */ -// private function getRelativeRevisionID( $revId, $flags, $dir ) { +// private function getRelativeRevisionID($revId, $flags, $dir) { // $revId = (int)$revId; -// if ( $dir === 'next' ) { +// if ($dir === 'next') { // $op = '>'; // $sort = 'ASC'; -// } elseif ( $dir === 'prev' ) { +// } elseif ($dir === 'prev') { // $op = '<'; // $sort = 'DESC'; // } else { -// throw new InvalidArgumentException( '$dir must be "next" or "prev"' ); +// throw new InvalidArgumentException('$dir must be "next" or "prev"'); // } // -// if ( $flags & self::GAID_FOR_UPDATE ) { -// $db = wfGetDB( DB_MASTER ); +// if ($flags & self::GAID_FOR_UPDATE) { +// $db = wfGetDB(DB_MASTER); // } else { -// $db = wfGetDB( DB_REPLICA, 'contributions' ); +// $db = wfGetDB(DB_REPLICA, 'contributions'); // } // // // Intentionally not caring if the specified revision belongs to this // // page. We only care about the timestamp. -// $ts = $db->selectField( 'revision', 'rev_timestamp', [ 'rev_id' => $revId ], __METHOD__ ); -// if ( $ts === false ) { -// $ts = $db->selectField( 'archive', 'ar_timestamp', [ 'ar_rev_id' => $revId ], __METHOD__ ); -// if ( $ts === false ) { +// $ts = $db.selectField('revision', 'rev_timestamp', [ 'rev_id' => $revId ], __METHOD__); +// if ($ts === false) { +// $ts = $db.selectField('archive', 'ar_timestamp', [ 'ar_rev_id' => $revId ], __METHOD__); +// if ($ts === false) { // // Or should this throw an InvalidArgumentException or something? // return false; // } // } -// $ts = $db->addQuotes( $ts ); +// $ts = $db.addQuotes($ts); // -// $revId = $db->selectField( 'revision', 'rev_id', +// $revId = $db.selectField('revision', 'rev_id', // [ -// 'rev_page' => $this->getArticleID( $flags ), +// 'rev_page' => this.getArticleID($flags), // "rev_timestamp $op $ts OR (rev_timestamp = $ts AND rev_id $op $revId)" // ], // __METHOD__, @@ -3709,10 +3722,10 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // ] // ); // -// if ( $revId === false ) { +// if ($revId === false) { // return false; // } else { -// return intval( $revId ); +// return intval($revId); // } // } // @@ -3723,8 +3736,8 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param int $flags Title::GAID_FOR_UPDATE // * @return int|bool Old revision ID, or false if none exists // */ -// public function getPreviousRevisionID( $revId, $flags = 0 ) { -// return $this->getRelativeRevisionID( $revId, $flags, 'prev' ); +// public function getPreviousRevisionID($revId, $flags = 0) { +// return this.getRelativeRevisionID($revId, $flags, 'prev'); // } // // /** @@ -3734,8 +3747,8 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param int $flags Title::GAID_FOR_UPDATE // * @return int|bool Next revision ID, or false if none exists // */ -// public function getNextRevisionID( $revId, $flags = 0 ) { -// return $this->getRelativeRevisionID( $revId, $flags, 'next' ); +// public function getNextRevisionID($revId, $flags = 0) { +// return this.getRelativeRevisionID($revId, $flags, 'next'); // } // // /** @@ -3744,12 +3757,12 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param int $flags Title::GAID_FOR_UPDATE // * @return Revision|null If page doesn't exist // */ -// public function getFirstRevision( $flags = 0 ) { -// $pageId = $this->getArticleID( $flags ); -// if ( $pageId ) { -// $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_REPLICA ); +// public function getFirstRevision($flags = 0) { +// $pageId = this.getArticleID($flags); +// if ($pageId) { +// $db = ($flags & self::GAID_FOR_UPDATE) ? wfGetDB(DB_MASTER) : wfGetDB(DB_REPLICA); // $revQuery = Revision::getQueryInfo(); -// $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'], +// $row = $db.selectRow($revQuery['tables'], $revQuery['fields'], // [ 'rev_page' => $pageId ], // __METHOD__, // [ @@ -3758,8 +3771,8 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // ], // $revQuery['joins'] // ); -// if ( $row ) { -// return new Revision( $row, 0, $this ); +// if ($row) { +// return new Revision($row, 0, this); // } // } // return null; @@ -3771,9 +3784,9 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param int $flags Title::GAID_FOR_UPDATE // * @return string|null MW timestamp // */ -// public function getEarliestRevTime( $flags = 0 ) { -// $rev = $this->getFirstRevision( $flags ); -// return $rev ? $rev->getTimestamp() : null; +// public function getEarliestRevTime($flags = 0) { +// $rev = this.getFirstRevision($flags); +// return $rev ? $rev.getTimestamp() : null; // } // // /** @@ -3782,8 +3795,8 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return bool // */ // public function isNewPage() { -// $dbr = wfGetDB( DB_REPLICA ); -// return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ ); +// $dbr = wfGetDB(DB_REPLICA); +// return (bool)$dbr.selectField('page', 'page_is_new', this.pageCond(), __METHOD__); // } // // /** @@ -3794,25 +3807,25 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // public function isBigDeletion() { // global $wgDeleteRevisionsLimit; // -// if ( !$wgDeleteRevisionsLimit ) { +// if (!$wgDeleteRevisionsLimit) { // return false; // } // -// if ( $this->mIsBigDeletion === null ) { -// $dbr = wfGetDB( DB_REPLICA ); +// if (this.mIsBigDeletion === null) { +// $dbr = wfGetDB(DB_REPLICA); // -// $revCount = $dbr->selectRowCount( +// $revCount = $dbr.selectRowCount( // 'revision', // '1', -// [ 'rev_page' => $this->getArticleID() ], +// [ 'rev_page' => this.getArticleID() ], // __METHOD__, // [ 'LIMIT' => $wgDeleteRevisionsLimit + 1 ] // ); // -// $this->mIsBigDeletion = $revCount > $wgDeleteRevisionsLimit; +// this.mIsBigDeletion = $revCount > $wgDeleteRevisionsLimit; // } // -// return $this->mIsBigDeletion; +// return this.mIsBigDeletion; // } // // /** @@ -3821,17 +3834,17 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return int // */ // public function estimateRevisionCount() { -// if ( !$this->exists() ) { +// if (!this.exists()) { // return 0; // } // -// if ( $this->mEstimateRevisions === null ) { -// $dbr = wfGetDB( DB_REPLICA ); -// $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*', -// [ 'rev_page' => $this->getArticleID() ], __METHOD__ ); +// if (this.mEstimateRevisions === null) { +// $dbr = wfGetDB(DB_REPLICA); +// this.mEstimateRevisions = $dbr.estimateRowCount('revision', '*', +// [ 'rev_page' => this.getArticleID() ], __METHOD__); // } // -// return $this->mEstimateRevisions; +// return this.mEstimateRevisions; // } // // /** @@ -3843,30 +3856,30 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations // * @return int Number of revisions between these revisions. // */ -// public function countRevisionsBetween( $old, $new, $max = null ) { -// if ( !( $old instanceof Revision ) ) { -// $old = Revision::newFromTitle( $this, (int)$old ); +// public function countRevisionsBetween($old, $new, $max = null) { +// if (!($old instanceof Revision)) { +// $old = Revision::newFromTitle(this, (int)$old); // } -// if ( !( $new instanceof Revision ) ) { -// $new = Revision::newFromTitle( $this, (int)$new ); +// if (!($new instanceof Revision)) { +// $new = Revision::newFromTitle(this, (int)$new); // } -// if ( !$old || !$new ) { +// if (!$old || !$new) { // return 0; // nothing to compare // } -// $dbr = wfGetDB( DB_REPLICA ); +// $dbr = wfGetDB(DB_REPLICA); // $conds = [ -// 'rev_page' => $this->getArticleID(), -// 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ), -// 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) ) +// 'rev_page' => this.getArticleID(), +// 'rev_timestamp > ' . $dbr.addQuotes($dbr.timestamp($old.getTimestamp())), +// 'rev_timestamp < ' . $dbr.addQuotes($dbr.timestamp($new.getTimestamp())) // ]; -// if ( $max !== null ) { -// return $dbr->selectRowCount( 'revision', '1', +// if ($max !== null) { +// return $dbr.selectRowCount('revision', '1', // $conds, // __METHOD__, // [ 'LIMIT' => $max + 1 ] // extra to detect truncation // ); // } else { -// return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__ ); +// return (int)$dbr.selectField('revision', 'count(*)', $conds, __METHOD__); // } // } // @@ -3886,60 +3899,60 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * Unknown option values are ignored. // * @return array|null Names of revision authors in the range; null if not both revisions exist // */ -// public function getAuthorsBetween( $old, $new, $limit, $options = [] ) { -// if ( !( $old instanceof Revision ) ) { -// $old = Revision::newFromTitle( $this, (int)$old ); +// public function getAuthorsBetween($old, $new, $limit, $options = new XophpArray()) { +// if (!($old instanceof Revision)) { +// $old = Revision::newFromTitle(this, (int)$old); // } -// if ( !( $new instanceof Revision ) ) { -// $new = Revision::newFromTitle( $this, (int)$new ); +// if (!($new instanceof Revision)) { +// $new = Revision::newFromTitle(this, (int)$new); // } // // XXX: what if Revision objects are passed in, but they don't refer to this title? -// // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID() +// // Add $old.getPage() != $new.getPage() || $old.getPage() != this.getArticleID() // // in the sanity check below? -// if ( !$old || !$new ) { +// if (!$old || !$new) { // return null; // nothing to compare // } -// $authors = []; +// $authors = new XophpArray(); // $old_cmp = '>'; // $new_cmp = '<'; // $options = (array)$options; -// if ( in_array( 'include_old', $options ) ) { +// if (in_array('include_old', $options)) { // $old_cmp = '>='; // } -// if ( in_array( 'include_new', $options ) ) { +// if (in_array('include_new', $options)) { // $new_cmp = '<='; // } -// if ( in_array( 'include_both', $options ) ) { +// if (in_array('include_both', $options)) { // $old_cmp = '>='; // $new_cmp = '<='; // } // // No DB query needed if $old and $new are the same or successive revisions: -// if ( $old->getId() === $new->getId() ) { -// return ( $old_cmp === '>' && $new_cmp === '<' ) ? -// [] : -// [ $old->getUserText( Revision::RAW ) ]; -// } elseif ( $old->getId() === $new->getParentId() ) { -// if ( $old_cmp === '>=' && $new_cmp === '<=' ) { -// $authors[] = $old->getUserText( Revision::RAW ); -// if ( $old->getUserText( Revision::RAW ) != $new->getUserText( Revision::RAW ) ) { -// $authors[] = $new->getUserText( Revision::RAW ); +// if ($old.getId() === $new.getId()) { +// return ($old_cmp === '>' && $new_cmp === '<') ? +// new XophpArray() : +// [ $old.getUserText(Revision::RAW) ]; +// } elseif ($old.getId() === $new.getParentId()) { +// if ($old_cmp === '>=' && $new_cmp === '<=') { +// $authorsnew XophpArray() = $old.getUserText(Revision::RAW); +// if ($old.getUserText(Revision::RAW) != $new.getUserText(Revision::RAW)) { +// $authorsnew XophpArray() = $new.getUserText(Revision::RAW); // } -// } elseif ( $old_cmp === '>=' ) { -// $authors[] = $old->getUserText( Revision::RAW ); -// } elseif ( $new_cmp === '<=' ) { -// $authors[] = $new->getUserText( Revision::RAW ); +// } elseif ($old_cmp === '>=') { +// $authorsnew XophpArray() = $old.getUserText(Revision::RAW); +// } elseif ($new_cmp === '<=') { +// $authorsnew XophpArray() = $new.getUserText(Revision::RAW); // } // return $authors; // } -// $dbr = wfGetDB( DB_REPLICA ); +// $dbr = wfGetDB(DB_REPLICA); // $revQuery = Revision::getQueryInfo(); -// $authors = $dbr->selectFieldValues( +// $authors = $dbr.selectFieldValues( // $revQuery['tables'], // $revQuery['fields']['rev_user_text'], // [ -// 'rev_page' => $this->getArticleID(), -// "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ), -// "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) ) +// 'rev_page' => this.getArticleID(), +// "rev_timestamp $old_cmp " . $dbr.addQuotes($dbr.timestamp($old.getTimestamp())), +// "rev_timestamp $new_cmp " . $dbr.addQuotes($dbr.timestamp($new.getTimestamp())) // ], __METHOD__, // [ 'DISTINCT', 'LIMIT' => $limit + 1 ], // add one so caller knows it was truncated // $revQuery['joins'] @@ -3961,9 +3974,9 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * Unknown option values are ignored. // * @return int Number of revision authors in the range; zero if not both revisions exist // */ -// public function countAuthorsBetween( $old, $new, $limit, $options = [] ) { -// $authors = $this->getAuthorsBetween( $old, $new, $limit, $options ); -// return $authors ? count( $authors ) : 0; +// public function countAuthorsBetween($old, $new, $limit, $options = new XophpArray()) { +// $authors = this.getAuthorsBetween($old, $new, $limit, $options); +// return $authors ? count($authors) : 0; // } // // /** @@ -3972,11 +3985,11 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param Title $title // * @return bool // */ -// public function equals( Title $title ) { +// public function equals(Title $title) { // // Note: === is necessary for proper matching of number-like titles. -// return $this->mInterwiki === $title->mInterwiki -// && $this->mNamespace == $title->mNamespace -// && $this->mDbkeyform === $title->mDbkeyform; +// return this.mInterwiki === $title.mInterwiki +// && this.mNamespace == $title.mNamespace +// && this.mDbkeyform === $title.mDbkeyform; // } // // /** @@ -3985,10 +3998,10 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param Title $title // * @return bool // */ -// public function isSubpageOf( Title $title ) { -// return $this->mInterwiki === $title->mInterwiki -// && $this->mNamespace == $title->mNamespace -// && strpos( $this->mDbkeyform, $title->mDbkeyform . '/' ) === 0; +// public function isSubpageOf(Title $title) { +// return this.mInterwiki === $title.mInterwiki +// && this.mNamespace == $title.mNamespace +// && strpos(this.mDbkeyform, $title.mDbkeyform . '/') === 0; // } // // /** @@ -4002,9 +4015,9 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * from master/for update // * @return bool // */ -// public function exists( $flags = 0 ) { -// $exists = $this->getArticleID( $flags ) != 0; -// Hooks::run( 'TitleExists', [ $this, &$exists ] ); +// public function exists($flags = 0) { +// $exists = this.getArticleID($flags) != 0; +// Hooks::run('TitleExists', [ this, &$exists ]); // return $exists; // } // @@ -4037,31 +4050,31 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param Title $title // * @param bool|null $isKnown // */ -// Hooks::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] ); +// Hooks::run('TitleIsAlwaysKnown', [ this, &$isKnown ]); // -// if ( !is_null( $isKnown ) ) { +// if (!is_null($isKnown)) { // return $isKnown; // } // -// if ( $this->isExternal() ) { +// if (this.isExternal()) { // return true; // any interwiki link might be viewable, for all we know // } // -// switch ( $this->mNamespace ) { +// switch (this.mNamespace) { // case NS_MEDIA: // case NS_FILE: // // file exists, possibly in a foreign repo -// return (bool)wfFindFile( $this ); +// return (bool)wfFindFile(this); // case NS_SPECIAL: // // valid special page -// return MediaWikiServices::getInstance()->getSpecialPageFactory()-> -// exists( $this->mDbkeyform ); +// return MediaWikiServices::getInstance().getSpecialPageFactory(). +// exists(this.mDbkeyform); // case NS_MAIN: // // selflink, possibly with fragment -// return $this->mDbkeyform == ''; +// return this.mDbkeyform == ""; // case NS_MEDIAWIKI: // // known system message -// return $this->hasSourceText() !== false; +// return this.hasSourceText() !== false; // default: // return false; // } @@ -4079,7 +4092,7 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return bool // */ // public function isKnown() { -// return $this->isAlwaysKnown() || $this->exists(); +// return this.isAlwaysKnown() || this.exists(); // } // // /** @@ -4088,21 +4101,21 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return bool // */ // public function hasSourceText() { -// if ( $this->exists() ) { +// if (this.exists()) { // return true; // } // -// if ( $this->mNamespace == NS_MEDIAWIKI ) { +// if (this.mNamespace == NS_MEDIAWIKI) { // // If the page doesn't exist but is a known system message, default // // message content will be displayed, same for language subpages- // // Use always content language to avoid loading hundreds of languages // // to get the link color. -// $contLang = MediaWikiServices::getInstance()->getContentLanguage(); -// list( $name, ) = MessageCache::singleton()->figureMessage( -// $contLang->lcfirst( $this->getText() ) +// $contLang = MediaWikiServices::getInstance().getContentLanguage(); +// list($name,) = MessageCache::singleton().figureMessage( +// $contLang.lcfirst(this.getText()) // ); -// $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false ); -// return $message->exists(); +// $message = wfMessage($name).inLanguage($contLang).useDatabase(false); +// return $message.exists(); // } // // return false; @@ -4146,17 +4159,17 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return string|bool // */ // public function getDefaultMessageText() { -// if ( $this->mNamespace != NS_MEDIAWIKI ) { // Just in case +// if (this.mNamespace != NS_MEDIAWIKI) { // Just in case // return false; // } // -// list( $name, $lang ) = MessageCache::singleton()->figureMessage( -// MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $this->getText() ) +// list($name, $lang) = MessageCache::singleton().figureMessage( +// MediaWikiServices::getInstance().getContentLanguage().lcfirst(this.getText()) // ); -// $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false ); +// $message = wfMessage($name).inLanguage($lang).useDatabase(false); // -// if ( $message->exists() ) { -// return $message->plain(); +// if ($message.exists()) { +// return $message.plain(); // } else { // return false; // } @@ -4168,36 +4181,36 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param string|null $purgeTime [optional] TS_MW timestamp // * @return bool True if the update succeeded // */ -// public function invalidateCache( $purgeTime = null ) { -// if ( wfReadOnly() ) { +// public function invalidateCache($purgeTime = null) { +// if (wfReadOnly()) { // return false; -// } elseif ( $this->mArticleID === 0 ) { +// } elseif (this.mArticleID === 0) { // return true; // avoid gap locking if we know it's not there // } // -// $dbw = wfGetDB( DB_MASTER ); -// $dbw->onTransactionPreCommitOrIdle( -// function () use ( $dbw ) { +// $dbw = wfGetDB(DB_MASTER); +// $dbw.onTransactionPreCommitOrIdle( +// function () use ($dbw) { // ResourceLoaderWikiModule::invalidateModuleCache( -// $this, null, null, $dbw->getDomainID() ); +// this, null, null, $dbw.getDomainID()); // }, // __METHOD__ // ); // -// $conds = $this->pageCond(); +// $conds = this.pageCond(); // DeferredUpdates::addUpdate( // new AutoCommitUpdate( // $dbw, // __METHOD__, -// function ( IDatabase $dbw, $fname ) use ( $conds, $purgeTime ) { -// $dbTimestamp = $dbw->timestamp( $purgeTime ?: time() ); -// $dbw->update( +// function (IDatabase $dbw, $fname) use ($conds, $purgeTime) { +// $dbTimestamp = $dbw.timestamp($purgeTime ?: time()); +// $dbw.update( // 'page', // [ 'page_touched' => $dbTimestamp ], -// $conds + [ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ], +// $conds + [ 'page_touched < ' . $dbw.addQuotes($dbTimestamp) ], // $fname // ); -// MediaWikiServices::getInstance()->getLinkCache()->invalidateTitle( $this ); +// MediaWikiServices::getInstance().getLinkCache().invalidateTitle(this); // } // ), // DeferredUpdates::PRESEND @@ -4212,10 +4225,10 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * on the number of links. Typically called on create and delete. // */ // public function touchLinks() { -// DeferredUpdates::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) ); -// if ( $this->mNamespace == NS_CATEGORY ) { +// DeferredUpdates::addUpdate(new HTMLCacheUpdate(this, 'pagelinks', 'page-touch')); +// if (this.mNamespace == NS_CATEGORY) { // DeferredUpdates::addUpdate( -// new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' ) +// new HTMLCacheUpdate(this, 'categorylinks', 'category-touch') // ); // } // } @@ -4226,11 +4239,11 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param IDatabase|null $db // * @return string|false Last-touched timestamp // */ -// public function getTouched( $db = null ) { -// if ( $db === null ) { -// $db = wfGetDB( DB_REPLICA ); +// public function getTouched($db = null) { +// if ($db === null) { +// $db = wfGetDB(DB_REPLICA); // } -// $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ ); +// $touched = $db.selectField('page', 'page_touched', this.pageCond(), __METHOD__); // return $touched; // } // @@ -4240,36 +4253,36 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param User|null $user // * @return string|null // */ -// public function getNotificationTimestamp( $user = null ) { +// public function getNotificationTimestamp($user = null) { // global $wgUser; // // // Assume current user if none given -// if ( !$user ) { +// if (!$user) { // $user = $wgUser; // } // // Check cache first -// $uid = $user->getId(); -// if ( !$uid ) { +// $uid = $user.getId(); +// if (!$uid) { // return false; // } // // avoid isset here, as it'll return false for null entries -// if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) { -// return $this->mNotificationTimestamp[$uid]; +// if (array_key_exists($uid, this.mNotificationTimestamp)) { +// return this.mNotificationTimestamp[$uid]; // } // // Don't cache too much! -// if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) { -// $this->mNotificationTimestamp = []; +// if (count(this.mNotificationTimestamp) >= self::CACHE_MAX) { +// this.mNotificationTimestamp = new XophpArray(); // } // -// $store = MediaWikiServices::getInstance()->getWatchedItemStore(); -// $watchedItem = $store->getWatchedItem( $user, $this ); -// if ( $watchedItem ) { -// $this->mNotificationTimestamp[$uid] = $watchedItem->getNotificationTimestamp(); +// $store = MediaWikiServices::getInstance().getWatchedItemStore(); +// $watchedItem = $store.getWatchedItem($user, this); +// if ($watchedItem) { +// this.mNotificationTimestamp[$uid] = $watchedItem.getNotificationTimestamp(); // } else { -// $this->mNotificationTimestamp[$uid] = false; +// this.mNotificationTimestamp[$uid] = false; // } // -// return $this->mNotificationTimestamp[$uid]; +// return this.mNotificationTimestamp[$uid]; // } // // /** @@ -4278,23 +4291,23 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param string $prepend Defaults to 'nstab-' // * @return string XML 'id' name // */ -// public function getNamespaceKey( $prepend = 'nstab-' ) { +// public function getNamespaceKey($prepend = 'nstab-') { // // Gets the subject namespace of this title -// $subjectNS = MWNamespace::getSubject( $this->mNamespace ); +// $subjectNS = MWNamespace::getSubject(this.mNamespace); // // Prefer canonical namespace name for HTML IDs -// $namespaceKey = MWNamespace::getCanonicalName( $subjectNS ); -// if ( $namespaceKey === false ) { +// $namespaceKey = MWNamespace::getCanonicalName($subjectNS); +// if ($namespaceKey === false) { // // Fallback to localised text -// $namespaceKey = $this->getSubjectNsText(); +// $namespaceKey = this.getSubjectNsText(); // } // // Makes namespace key lowercase -// $namespaceKey = MediaWikiServices::getInstance()->getContentLanguage()->lc( $namespaceKey ); +// $namespaceKey = MediaWikiServices::getInstance().getContentLanguage().lc($namespaceKey); // // Uses main -// if ( $namespaceKey == '' ) { +// if ($namespaceKey == "") { // $namespaceKey = 'main'; // } // // Changes file to image for backwards compatibility -// if ( $namespaceKey == 'file' ) { +// if ($namespaceKey == 'file') { // $namespaceKey = 'image'; // } // return $prepend . $namespaceKey; @@ -4304,35 +4317,35 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * Get all extant redirects to this Title // * // * @param int|null $ns Single namespace to consider; null to consider all namespaces -// * @return Title[] Array of Title redirects to this title +// * @return Titlenew XophpArray() Array of Title redirects to this title // */ -// public function getRedirectsHere( $ns = null ) { -// $redirs = []; +// public function getRedirectsHere($ns = null) { +// $redirs = new XophpArray(); // -// $dbr = wfGetDB( DB_REPLICA ); +// $dbr = wfGetDB(DB_REPLICA); // $where = [ -// 'rd_namespace' => $this->mNamespace, -// 'rd_title' => $this->mDbkeyform, +// 'rd_namespace' => this.mNamespace, +// 'rd_title' => this.mDbkeyform, // 'rd_from = page_id' // ]; -// if ( $this->isExternal() ) { -// $where['rd_interwiki'] = $this->mInterwiki; +// if (this.isExternal()) { +// $where['rd_interwiki'] = this.mInterwiki; // } else { -// $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL'; +// $wherenew XophpArray() = 'rd_interwiki = ' . $dbr.addQuotes("") . ' OR rd_interwiki IS NULL'; // } -// if ( !is_null( $ns ) ) { +// if (!is_null($ns)) { // $where['page_namespace'] = $ns; // } // -// $res = $dbr->select( +// $res = $dbr.select( // [ 'redirect', 'page' ], // [ 'page_namespace', 'page_title' ], // $where, // __METHOD__ // ); // -// foreach ( $res as $row ) { -// $redirs[] = self::newFromRow( $row ); +// foreach ($res as $row) { +// $redirsnew XophpArray() = self::newFromRow($row); // } // return $redirs; // } @@ -4345,14 +4358,14 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // public function isValidRedirectTarget() { // global $wgInvalidRedirectTargets; // -// if ( $this->isSpecialPage() ) { +// if (this.isSpecialPage()) { // // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here -// if ( $this->isSpecial( 'Userlogout' ) ) { +// if (this.isSpecial('Userlogout')) { // return false; // } // -// foreach ( $wgInvalidRedirectTargets as $target ) { -// if ( $this->isSpecial( $target ) ) { +// foreach ($wgInvalidRedirectTargets as $target) { +// if (this.isSpecial($target)) { // return false; // } // } @@ -4367,7 +4380,7 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @return BacklinkCache // */ // public function getBacklinkCache() { -// return BacklinkCache::get( $this ); +// return BacklinkCache::get(this); // } // // /** @@ -4380,7 +4393,7 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // // $bannedNamespaces = $wgExemptFromUserRobotsControl ?? MWNamespace::getContentNamespaces(); // -// return !in_array( $this->mNamespace, $bannedNamespaces ); +// return !in_array(this.mNamespace, $bannedNamespaces); // } // // /** @@ -4393,20 +4406,20 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * prefix. // * @return string // */ -// public function getCategorySortkey( $prefix = '' ) { -// $unprefixed = $this->getText(); +// public function getCategorySortkey($prefix = "") { +// $unprefixed = this.getText(); // // // Anything that uses this hook should only depend // // on the Title object passed in, and should probably // // tell the users to run updateCollations.php --force // // in order to re-sort existing category relations. -// Hooks::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] ); -// if ( $prefix !== '' ) { +// Hooks::run('GetDefaultSortkey', [ this, &$unprefixed ]); +// if ($prefix !== "") { // # Separate with a line feed, so the unprefixed part is only used as // # a tiebreaker when two pages have the exact same prefix. // # In UCA, tab is the only character that can sort above LF // # so we strip both of them from the original prefix. -// $prefix = strtr( $prefix, "\n\t", ' ' ); +// $prefix = strtr($prefix, "\n\t", ' '); // return "$prefix\n$unprefixed"; // } // return $unprefixed; @@ -4424,13 +4437,13 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // // // check, if the page language could be saved in the database, and if so and // // the value is not requested already, lookup the page language using LinkCache -// if ( $wgPageLanguageUseDB && $this->mDbPageLanguage === false ) { -// $linkCache = MediaWikiServices::getInstance()->getLinkCache(); -// $linkCache->addLinkObj( $this ); -// $this->mDbPageLanguage = $linkCache->getGoodLinkFieldObj( $this, 'lang' ); +// if ($wgPageLanguageUseDB && this.mDbPageLanguage === false) { +// $linkCache = MediaWikiServices::getInstance().getLinkCache(); +// $linkCache.addLinkObj(this); +// this.mDbPageLanguage = $linkCache.getGoodLinkFieldObj(this, 'lang'); // } // -// return $this->mDbPageLanguage; +// return this.mDbPageLanguage; // } // // /** @@ -4443,29 +4456,29 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // */ // public function getPageLanguage() { // global $wgLang, $wgLanguageCode; -// if ( $this->isSpecialPage() ) { +// if (this.isSpecialPage()) { // // special pages are in the user language // return $wgLang; // } // // // Checking if DB language is set -// $dbPageLanguage = $this->getDbPageLanguageCode(); -// if ( $dbPageLanguage ) { -// return wfGetLangObj( $dbPageLanguage ); +// $dbPageLanguage = this.getDbPageLanguageCode(); +// if ($dbPageLanguage) { +// return wfGetLangObj($dbPageLanguage); // } // -// if ( !$this->mPageLanguage || $this->mPageLanguage[1] !== $wgLanguageCode ) { +// if (!this.mPageLanguage || this.mPageLanguage[1] !== $wgLanguageCode) { // // Note that this may depend on user settings, so the cache should // // be only per-request. // // NOTE: ContentHandler::getPageLanguage() may need to load the // // content to determine the page language! // // Checking $wgLanguageCode hasn't changed for the benefit of unit // // tests. -// $contentHandler = ContentHandler::getForTitle( $this ); -// $langObj = $contentHandler->getPageLanguage( $this ); -// $this->mPageLanguage = [ $langObj->getCode(), $wgLanguageCode ]; +// $contentHandler = ContentHandler::getForTitle(this); +// $langObj = $contentHandler.getPageLanguage(this); +// this.mPageLanguage = [ $langObj.getCode(), $wgLanguageCode ]; // } else { -// $langObj = Language::factory( $this->mPageLanguage[0] ); +// $langObj = Language::factory(this.mPageLanguage[0]); // } // // return $langObj; @@ -4482,24 +4495,24 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // public function getPageViewLanguage() { // global $wgLang; // -// if ( $this->isSpecialPage() ) { +// if (this.isSpecialPage()) { // // If the user chooses a variant, the content is actually // // in a language whose code is the variant code. -// $variant = $wgLang->getPreferredVariant(); -// if ( $wgLang->getCode() !== $variant ) { -// return Language::factory( $variant ); +// $variant = $wgLang.getPreferredVariant(); +// if ($wgLang.getCode() !== $variant) { +// return Language::factory($variant); // } // // return $wgLang; // } // // // Checking if DB language is set -// $dbPageLanguage = $this->getDbPageLanguageCode(); -// if ( $dbPageLanguage ) { -// $pageLang = wfGetLangObj( $dbPageLanguage ); -// $variant = $pageLang->getPreferredVariant(); -// if ( $pageLang->getCode() !== $variant ) { -// $pageLang = Language::factory( $variant ); +// $dbPageLanguage = this.getDbPageLanguageCode(); +// if ($dbPageLanguage) { +// $pageLang = wfGetLangObj($dbPageLanguage); +// $variant = $pageLang.getPreferredVariant(); +// if ($pageLang.getCode() !== $variant) { +// $pageLang = Language::factory($variant); // } // // return $pageLang; @@ -4508,8 +4521,8 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // // @note Can't be cached persistently, depends on user settings. // // @note ContentHandler::getPageViewLanguage() may need to load the // // content to determine the page language! -// $contentHandler = ContentHandler::getForTitle( $this ); -// $pageLang = $contentHandler->getPageViewLanguage( $this ); +// $contentHandler = ContentHandler::getForTitle(this); +// $pageLang = $contentHandler.getPageViewLanguage(this); // return $pageLang; // } // @@ -4523,43 +4536,43 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // * @param int $oldid Revision ID that's being edited // * @return array // */ -// public function getEditNotices( $oldid = 0 ) { -// $notices = []; +// public function getEditNotices($oldid = 0) { +// $notices = new XophpArray(); // // // Optional notice for the entire namespace -// $editnotice_ns = 'editnotice-' . $this->mNamespace; -// $msg = wfMessage( $editnotice_ns ); -// if ( $msg->exists() ) { -// $html = $msg->parseAsBlock(); +// $editnotice_ns = 'editnotice-' . this.mNamespace; +// $msg = wfMessage($editnotice_ns); +// if ($msg.exists()) { +// $html = $msg.parseAsBlock(); // // Edit notices may have complex logic, but output nothing (T91715) -// if ( trim( $html ) !== '' ) { +// if (trim($html) !== "") { // $notices[$editnotice_ns] = Html::rawElement( // 'div', // [ 'class' => [ // 'mw-editnotice', // 'mw-editnotice-namespace', -// Sanitizer::escapeClass( "mw-$editnotice_ns" ) +// Sanitizer::escapeClass("mw-$editnotice_ns") // ] ], // $html // ); // } // } // -// if ( MWNamespace::hasSubpages( $this->mNamespace ) ) { +// if (MWNamespace::hasSubpages(this.mNamespace)) { // // Optional notice for page itself and any parent page // $editnotice_base = $editnotice_ns; -// foreach ( explode( '/', $this->mDbkeyform ) as $part ) { +// foreach (explode('/', this.mDbkeyform) as $part) { // $editnotice_base .= '-' . $part; -// $msg = wfMessage( $editnotice_base ); -// if ( $msg->exists() ) { -// $html = $msg->parseAsBlock(); -// if ( trim( $html ) !== '' ) { +// $msg = wfMessage($editnotice_base); +// if ($msg.exists()) { +// $html = $msg.parseAsBlock(); +// if (trim($html) !== "") { // $notices[$editnotice_base] = Html::rawElement( // 'div', // [ 'class' => [ // 'mw-editnotice', // 'mw-editnotice-base', -// Sanitizer::escapeClass( "mw-$editnotice_base" ) +// Sanitizer::escapeClass("mw-$editnotice_base") // ] ], // $html // ); @@ -4568,17 +4581,17 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // } // } else { // // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys -// $editnoticeText = $editnotice_ns . '-' . strtr( $this->mDbkeyform, '/', '-' ); -// $msg = wfMessage( $editnoticeText ); -// if ( $msg->exists() ) { -// $html = $msg->parseAsBlock(); -// if ( trim( $html ) !== '' ) { +// $editnoticeText = $editnotice_ns . '-' . strtr(this.mDbkeyform, '/', '-'); +// $msg = wfMessage($editnoticeText); +// if ($msg.exists()) { +// $html = $msg.parseAsBlock(); +// if (trim($html) !== "") { // $notices[$editnoticeText] = Html::rawElement( // 'div', // [ 'class' => [ // 'mw-editnotice', // 'mw-editnotice-page', -// Sanitizer::escapeClass( "mw-$editnoticeText" ) +// Sanitizer::escapeClass("mw-$editnoticeText") // ] ], // $html // ); @@ -4586,7 +4599,7 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // } // } // -// Hooks::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] ); +// Hooks::run('TitleGetEditNotices', [ this, $oldid, &$notices ]); // return $notices; // } // @@ -4606,9 +4619,9 @@ public class XomwTitle { // implements LinkTarget, IDBAccessObject // } // // public function __wakeup() { -// $this->mArticleID = ( $this->mNamespace >= 0 ) ? -1 : 0; -// $this->mUrlform = wfUrlencode( $this->mDbkeyform ); -// $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' ); +// this.mArticleID = (this.mNamespace >= 0) ? -1 : 0; +// this.mUrlform = wfUrlencode(this.mDbkeyform); +// this.mTextform = strtr(this.mDbkeyform, '_', ' '); // } } diff --git a/400_xowa/src/gplx/xowa/mediawiki/includes/XomwTitleOld.java b/400_xowa/src/gplx/xowa/mediawiki/includes/XomwTitleOld.java index fd473f62e..b4abab604 100644 --- a/400_xowa/src/gplx/xowa/mediawiki/includes/XomwTitleOld.java +++ b/400_xowa/src/gplx/xowa/mediawiki/includes/XomwTitleOld.java @@ -25,7 +25,7 @@ import gplx.xowa.mediawiki.includes.title.*; * @note Consider using a TitleValue Object instead. TitleValue is more lightweight * and does not rely on global state or the database. */ -public class XomwTitleOld implements XomwLinkTarget { +public class XomwTitleOld { // implements XomwLinkTarget // /** @var HashBagOStuff */ // static private $titleCache = null; // diff --git a/400_xowa/src/gplx/xowa/mediawiki/includes/content/XomwAbstractContent.java b/400_xowa/src/gplx/xowa/mediawiki/includes/content/XomwAbstractContent.java index 2eeeb6cc7..8f2383a5b 100644 --- a/400_xowa/src/gplx/xowa/mediawiki/includes/content/XomwAbstractContent.java +++ b/400_xowa/src/gplx/xowa/mediawiki/includes/content/XomwAbstractContent.java @@ -1,6 +1,6 @@ /* XOWA: the XOWA Offline Wiki Application -Copyright (C) 2012-2017 gnosygnu@gmail.com +Copyright (C) 2012-2020 gnosygnu@gmail.com XOWA is licensed under the terms of the General Public License (GPL) Version 3, or alternatively under the terms of the Apache License Version 2.0. @@ -13,9 +13,14 @@ The terms of each license can be found in the source code repository: GPLv3 License: https://github.com/gnosygnu/xowa/blob/master/LICENSE-GPLv3.txt Apache License: https://github.com/gnosygnu/xowa/blob/master/LICENSE-APACHE2.txt */ -package gplx.xowa.mediawiki.includes.content; import gplx.*; import gplx.xowa.*; import gplx.xowa.mediawiki.*; import gplx.xowa.mediawiki.includes.*; -import gplx.xowa.mediawiki.includes.exception.*; -import gplx.xowa.mediawiki.includes.parsers.*; +package gplx.xowa.mediawiki.includes.content; + +import gplx.Err_; +import gplx.xowa.mediawiki.includes.XomwMagicWord; +import gplx.xowa.mediawiki.includes.XomwTitleOld; +import gplx.xowa.mediawiki.includes.exception.XomwMWException; +import gplx.xowa.mediawiki.includes.parsers.XomwParserOptions; +import gplx.xowa.mediawiki.includes.parsers.XomwParserOutput; /** * A content Object represents page content, e.g. the text to show on a page. * Content objects have no knowledge about how they relate to Wiki pages. @@ -530,7 +535,7 @@ public abstract class XomwAbstractContent implements XomwContent { // } public abstract byte[] getTextForSearchIndex(); - public abstract byte[] getWikitextForTransclusion(); + public abstract String getWikitextForTransclusion(); public abstract byte[] getTextForSummary(int maxLength); diff --git a/400_xowa/src/gplx/xowa/mediawiki/includes/content/XomwContent.java b/400_xowa/src/gplx/xowa/mediawiki/includes/content/XomwContent.java index 57c73c0a1..f4c0ba5dd 100644 --- a/400_xowa/src/gplx/xowa/mediawiki/includes/content/XomwContent.java +++ b/400_xowa/src/gplx/xowa/mediawiki/includes/content/XomwContent.java @@ -52,7 +52,7 @@ public interface XomwContent { * @todo Used in WikiPage and MessageCache to get message text. Not so * nice. What should we use instead?! */ - byte[] getWikitextForTransclusion(); + String getWikitextForTransclusion(); /** * Returns a textual representation of the content suitable for use in edit diff --git a/400_xowa/src/gplx/xowa/mediawiki/includes/linkers/XomwLinkTarget.java b/400_xowa/src/gplx/xowa/mediawiki/includes/linkers/XomwLinkTarget.java index 591d16dc1..a2954e958 100644 --- a/400_xowa/src/gplx/xowa/mediawiki/includes/linkers/XomwLinkTarget.java +++ b/400_xowa/src/gplx/xowa/mediawiki/includes/linkers/XomwLinkTarget.java @@ -20,93 +20,93 @@ package gplx.xowa.mediawiki.includes.linkers; * @since 1.27 */ public interface XomwLinkTarget { -// -// /** -// * Get the namespace index. -// * @since 1.27 -// * -// * @return int Namespace index -// */ -// public int getNamespace(); -// -// /** -// * Convenience function to test if it is in the namespace -// * @since 1.27 -// * -// * @param int $ns -// * @return bool -// */ -// public boolean inNamespace(int ns); -// -// /** -// * Get the link fragment (i.e. the bit after the #) in text form. -// * @since 1.27 -// * -// * @return string link fragment -// */ -// public String getFragment(); -// -// /** -// * Whether the link target has a fragment -// * @since 1.27 -// * -// * @return bool -// */ -// public boolean hasFragment(); -// -// /** -// * Get the main part with underscores. -// * @since 1.27 -// * -// * @return string Main part of the link, with underscores (for use in href attributes) -// */ -// public String getDBkey(); -// -// /** -// * Returns the link in text form, without namespace prefix or fragment. -// * This is computed from the DB key by replacing any underscores with spaces. -// * @since 1.27 -// * -// * @return string -// */ -// public String getText(); -// -// /** -// * Creates a new LinkTarget for a different fragment of the same page. -// * It is expected that the same type of object will be returned, but the -// * only requirement is that it is a LinkTarget. -// * @since 1.27 -// * -// * @param string $fragment The fragment name, or "" for the entire page. -// * -// * @return LinkTarget -// */ -// public XomwLinkTarget createFragmentTarget(String fragment); -// -// /** -// * Whether this LinkTarget has an interwiki component -// * @since 1.27 -// * -// * @return bool -// */ -// public boolean isExternal(); -// -// /** -// * The interwiki component of this LinkTarget -// * @since 1.27 -// * -// * @return string -// */ -// public String getInterwiki(); -// -// /** -// * Returns an informative human readable representation of the link target, -// * for use in logging and debugging. There is no requirement for the return -// * value to have any relationship with the input of TitleParser. -// * @since 1.31 -// * -// * @return string -// */ -// public String __toString(); + + /** + * Get the namespace index. + * @since 1.27 + * + * @return int Namespace index + */ + public int getNamespace(); + + /** + * Convenience function to test if it is in the namespace + * @since 1.27 + * + * @param int $ns + * @return bool + */ + public boolean inNamespace(int ns); + + /** + * Get the link fragment (i.e. the bit after the #) in text form. + * @since 1.27 + * + * @return string link fragment + */ + public String getFragment(); + + /** + * Whether the link target has a fragment + * @since 1.27 + * + * @return bool + */ + public boolean hasFragment(); + + /** + * Get the main part with underscores. + * @since 1.27 + * + * @return string Main part of the link, with underscores (for use in href attributes) + */ + public String getDBkey(); + + /** + * Returns the link in text form, without namespace prefix or fragment. + * This is computed from the DB key by replacing any underscores with spaces. + * @since 1.27 + * + * @return string + */ + public String getText(); + + /** + * Creates a new LinkTarget for a different fragment of the same page. + * It is expected that the same type of object will be returned, but the + * only requirement is that it is a LinkTarget. + * @since 1.27 + * + * @param string $fragment The fragment name, or "" for the entire page. + * + * @return LinkTarget + */ + public XomwLinkTarget createFragmentTarget(String fragment); + + /** + * Whether this LinkTarget has an interwiki component + * @since 1.27 + * + * @return bool + */ + public boolean isExternal(); + + /** + * The interwiki component of this LinkTarget + * @since 1.27 + * + * @return string + */ + public String getInterwiki(); + + /** + * Returns an informative human readable representation of the link target, + * for use in logging and debugging. There is no requirement for the return + * value to have any relationship with the input of TitleParser. + * @since 1.31 + * + * @return string + */ + public String __toString(); } diff --git a/400_xowa/src/gplx/xowa/mediawiki/includes/parsers/XomwParser.java b/400_xowa/src/gplx/xowa/mediawiki/includes/parsers/XomwParser.java index 430a82698..77c9966a4 100644 --- a/400_xowa/src/gplx/xowa/mediawiki/includes/parsers/XomwParser.java +++ b/400_xowa/src/gplx/xowa/mediawiki/includes/parsers/XomwParser.java @@ -16,6 +16,7 @@ Apache License: https://github.com/gnosygnu/xowa/blob/master/LICENSE-APACHE2.txt package gplx.xowa.mediawiki.includes.parsers; import gplx.*; import gplx.xowa.*; import gplx.xowa.mediawiki.*; import gplx.xowa.mediawiki.includes.*; import gplx.core.btries.*; import gplx.core.net.*; +import gplx.xowa.mediawiki.includes.content.XomwContent; import gplx.xowa.mediawiki.includes.xohtml.*; import gplx.xowa.mediawiki.includes.linkers.*; import gplx.xowa.mediawiki.includes.parsers.tables.*; @@ -4505,10 +4506,10 @@ Tfds.Write(nowiki, isHTML, forceRawInterwiki, isChildObj, isLocalObj, titleText, * * @return array */ - public static XophpArray statelessFetchTemplate(XomwTitleOld title, XomwParser parser) { // $parser = false + public static XophpArray statelessFetchTemplate(XomwTitle title, XomwParser parser) { // $parser = false String text = XophpString_.False; boolean skip = false; - XomwTitleOld finalTitle = title; + XomwTitle finalTitle = title; XophpArray deps = XophpArray.New(); // Loop to fetch the article, with up to 1 redirect @@ -4547,26 +4548,27 @@ Tfds.Write(nowiki, isHTML, forceRawInterwiki, isChildObj, isLocalObj, titleText, .Add("title", title) .Add("page_id", title.getArticleID()) .Add("rev_id", rev_id)); -// if (rev && !title.equals(rev.getTitle())) { + if (XophpObject_.is_true(rev) && !title.equals(rev.getTitle())) { // We fetched a rev from a different title; register it too... -// deps.Add(XophpArray.New() -// .Add("title", rev.getTitle()) -// .Add("page_id", rev.getPage()) -// .Add("rev_id", rev_id)); -// } + deps.Add(XophpArray.New() + .Add("title", rev.getTitle()) + .Add("page_id", rev.getPage()) + .Add("rev_id", rev_id)); + } + XomwContent content; if (XophpObject_.is_true(rev)) { -// content = rev.getContent(); -// text = content ? content.getWikitextForTransclusion() : null; -// + content = rev.getContent(); + text = XophpObject_.is_true(content) ? content.getWikitextForTransclusion() : null; + // Hooks::run('ParserFetchTemplate', // [ parser, title, rev, &text, &deps ]); -// -// if (text === false || text === null) { -// text = false; -// break; -// } - } else if (title.getNamespace() == NS_MEDIAWIKI) { + + if (XophpString_.is_false(text) || XophpString_.is_null(text)) { + text = XophpString_.False; + break; + } + } else if (title.getNamespace() == XomwDefines.NS_MEDIAWIKI) { // message = wfMessage(MediaWikiServices::getInstance().getContentLanguage(). // lcfirst(title.getText())).inContentLanguage(); // if (!message.exists()) {