Manual:Using custom namespaces/ru
В дополнение к встроенным пространствам имён, можно добавлять пользовательские, с отдельным содержанием. Что позволяет сделать более логическую организацию материалов.
Своими пространствами имён проще управлять с помощью конфигурационной директивы $wgExtraNamespaces
.
Так же можно определять псевдонимы для своих пространств имён (а, равно, и встроенных) при помощи конфигурационной директивы $wgNamespaceAliases
.
Некоторые расширения упрощают создание собственных пространств имён.
Примерами могут служить NamespaceManager и BlueSpiceNamespaceManager .
Создание своего пространства имён
Вы регистрируете дополнительные пространства имен, добавляя их в глобальную переменную $wgExtraNamespaces
в файле "LocalSettings.php" .
Все пространства имён требуют уникальный числовой индекс в этом массиве.
Как пример простого создания своего пространства имён, добавляя следующие строки в файл "LocalSettings.php" определяем пространство "Foo" 3000 и связанное с ним пространство "Foo_talk".
Обратите внимание, что наличие пространства имён обсуждения, связанного с вашим пользовательским пространством имён, в настоящее время является жёстким требованием.
// Определяем константы для добавляемых пространств.
define("NS_FOO", 3000); // Это ДОЛЖНО быть чётным.
define("NS_FOO_TALK", 3001); // Это ДОЛЖНО быть идущим подряд нечётным числом.
// Добавляем пространства имён.
$wgExtraNamespaces[NS_FOO] = "Foo";
$wgExtraNamespaces[NS_FOO_TALK] = "Foo_talk"; // Обратите внимание на подчёркивания в именах пространств имён.
- Подберите свободное (незанятое) число
- По принятому соглашению, пространства имён имеющие номера 100-199 зарезервированы для специфических пространств, хотя существуют несколько расширений, которые не придерживаются данного соглашения. Создатели расширений используют большие номера, до 32767. Выбирая свой индекс, вы должны избегать любых чисел уже определённых в extension default namespaces , потому что вы можете захотеть установить это расширение позже. Числа от 3000 до 4999 зарезервированы для системных администраторов, чтобы определить свои пользовательские пространства имён. (Кроме того, желательно избегать повторения любых названий пространств имён, которые совпадают с поставляемыми с помощью расширений.)
- Чётное, затем нечётное
- Обратите внимание, что индекс пространства имён равен 3000 в вышеприведённом примере.
- чётный индекс пространства имён указывает на пространство имён содержания.
- непосредственно следующий нечётный индекс указывает на связанное с ним пространство имён обсуждения ("talk")
- Создаём также пространство имён обсуждения
- Обычно создаётся пространство имён обсуждения «Обсуждение» вместе с каждым пользовательским пространством. В этом примере, если вы переименуете страницу в пространство имён «Foo», появится вопрос о переименовании соответствующей страницы обсуждения (при её наличии), и если вы подтвердите её переименование, MediaWiki will разместит её в пространство имён «Foo talk».
- Без пробелов
- В названиях пространств имён используйте подчёркивания вместо пробелов. Имя "My Namespace" неверно; вместо него используйте "My_Namespace".
- Без дефисов
Заглавные буквы не допускают использования дефисов, но их всё равно можно смело добавлять к заголовку префикса. Пример:
$wgExtraNamespaces[NS_FOOFOO] = "Foo-Foo";
- Name the numbers you pick
- The example defines constants for the namespace IDs, so that you can refer to these namespaces later on in the configuration, for example in
$wgNamespaceProtection
,$wgNamespacesWithSubpages
, or$wgExtraGenderNamespaces
.
Также вы можете задать дополнительные настройки для нового пространства имён.
$wgNamespaceProtection[NS_FOO] = [ 'editfoo' ]; // разрешение «editfoo», необходимое для редактирования страниц в пространстве имён
$wgNamespacesWithSubpages[NS_FOO] = true; // subpages enabled for the foo namespace
$wgGroupPermissions['sysop']['editfoo'] = true; // permission "editfoo" granted to users in the "sysop" group
- Сделайте это раньше
- Manipulation of
$wgExtraNamespaces
must be completed during MediaWiki initialization, i.e. in case an extension etc. should work with the newly created custom namespace, make sure that you define and name them prior to invoking the respective extension. For instance it cannot be manipulated in a post-initialization hook like$wgExtensionFunctions
.
- Остерегайтесь столкновений с протоколами URL
- MediaWiki's linking code knows about a number of URL protocols, defined in the $wgUrlProtocols variable. If your namespace name is identical to one of these protocols, you're going to have trouble creating [[wikilinks]] to pages in your custom namespace. This most commonly arises when someone tries to create a "News" namespace, because
news:
is a URL protocol for NNTP newsgroups. - To avoid this issue, you can deregister the relevant URL protocol by adding the following code to the "LocalSettings.php" file (replacing
news
by the lowercased name of the protocol you wish to remove):
$wgUrlProtocols = array_diff( $wgUrlProtocols, array( 'news:' ) );
В расширениях
Версия MediaWiki: | ≥ 1.25 Gerrit change 166705 |
Extensions often add their own namespaces, such as the Flow extension's "Topic" namespace.
The extension.json registration system has a namespaces
key for an extension to list its namespaces.
Из расширения Gadgets :
"namespaces": [
{
"id": 2300,
"constant": "NS_GADGET",
"name": "Gadget",
"protection": "gadgets-edit"
},
{
"id": 2301,
"constant": "NS_GADGET_TALK",
"name": "Gadget_talk"
},
]
You can also set other namespace-related settings here, such as whether it should be a content namespace or not; see Руководство:Extension.json/Schema for the available properties.
If namespace registration is conditional (for example EventLogging only defines its "Schema" namespace on the wiki where it stores schemas), the extension should add "conditional": true
to the namespace definition in extension.json
, and also register a handler for the CanonicalNamespaces hook there which decides whether to register the namespace or not.
The hook handler should only change the $namespaces
with which it is called; all other settings of the namespace should still be registered in the extension.json
.
If those settings should also be dynamic, do not change $wgContentNamespaces
, $wgNamespaceContentModels
etc. in the CanonicalNamespaces hook handler (it will have no effect – T288819); instead, you will have to set them earlier, such as in a callback (not in $wgExtensionFunctions
).
Note that adding an extension to LocalSettings.php does not necessarily make relevant namespace constants available as globals for other extensions.
Content namespaces
When building the site statistics page (see Special:Statistics), MediaWiki uses values stored in the database to calculate certain totals. One particular total is the "number of articles" or "number of content pages" figure.
For a page to be considered an article, or proper content, it must:
- Be in the main namespace, or a defined content namespace
- Not be a redirect page
- Contain at least one internal link, as configured by
$wgArticleCountMethod
.
When creating custom namespaces to hold additional content, it is a good idea to indicate this in the configuration. This is done via the $wgContentNamespaces configuration directive.
To extend the example above, one might add the following to the "LocalSettings.php" file:
$wgContentNamespaces[] = 3000;
- или
$wgContentNamespaces[] = NS_FOO;
MediaWiki will now consider pages in the "Foo" namespace to be articles, if they meet the remaining criteria, and will include them when updating the site statistics counters.
Running maintenance scripts
When adjusting the value of configuration parameter $wgContentNamespaces
, it is a good idea to run either the "path/to/maintenance/updateArticleCount.php or "path/to/maintenance/initSiteStats.php" script to update the internal statistics cache (see Руководство:Скрипты обслуживания ).
Почему вам может понадобиться собственное пространство имён
Есть несколько причин, по которым вам это может понадобиться:
- A custom namespace can be used to hold content that should not be shown on the search results page, for example pages that are used only for transclusion.
- Certain namespaces require additional privilege(s) for editing.
- You want certain namespaces not to be subjected to certain limitations or default settings ($wgNoFollowNsExceptions for example)
- A uniform prefix for specific content(s), which is searchable for that namespace only
- If you're a MW developer, sometimes you need to have a custom namespace for your extension(s)
Работа с существующими страницами
When storing page records, MediaWiki uses a namespace's numerical index, along with the remaining title text. Thus, when a page is created in a namespace that doesn't exist, e.g. "Bar:Some page", it is treated as being in the main namespace.
This can cause problems if adding a custom namespace definition for "Bar" at a later date, as MediaWiki will look for a page indexed via the proper namespace, but won't be able to find it, thus making the content inaccessible.
You can use the NamespaceDupes maintenance script to correct this problem. It will find pages in the main namespace with a prefix matching any of the defined namespaces, and update their records.
If you are not able to run maintenance scripts, then the following approach might be suitable:
- Comment out the namespace definition in the configuration file
- Access each affected page (use Special:PrefixIndex on your wiki to find them), and move it out of the pseudo-namespace, e.g. move "Bar:Some page" to "Bar2:Some page"
- Un-comment the namespace definition
- Move the affected pages back into the new namespace
Удаление пользовательских пространств имён
The problem addressed above also occurs when a custom namespace definition is removed; MediaWiki is no longer aware of the numerical index for the namespace, and attempts to search the main namespace for the desired pages, leading to inaccessible content. Это случается редко, поскольку большинству сайтов не требуется удалять пространства имён, но это является проблемой.
Версия MediaWiki: | ≥ 1.43 Gerrit change 1052196 |
You can use the CleanupTitles maintenance script to correct this problem. It will find pages any namespace that is no longer defined, and update their records. The pages will be moved to the main namespace with an added prefix like NS123:, unless specified otherwise by parameters to the script.
As above, you can also temporarily restore the namespace configuration and move the pages from the user interface (or delete them).
Переименование пользовательских пространств имён
Предположим, что вам необходимо переименовать пользовательское пространство имён «Foo» в «New», не выполняя массового перемещения страниц.
Самый простой способ добиться этого — сохранить идентификатор пространства имён (здесь «3000
»), а также константу пространства имён (здесь «NS_FOO
»), изменить (видимое) название пространства имён и добавить старое в качестве псевдонима.
define("NS_FOO", 3000);
$wgExtraNamespaces[NS_FOO] = "Foo";
define("NS_FOO", 3000);
$wgExtraNamespaces[NS_FOO] = "New";
$wgNamespaceAliases['Foo'] = NS_FOO;
Note that some extensions store namespace names in plain text instead of their internal IDs, and should therefore be dealt with extra care. Examples include:
- The Translate extension creates pages with the source page's name (containing the namespace prefix) under the Translations namespace, e.g. Translations:Manual:Using custom namespaces/117/es for the Spanish translation of the 117th message on this page. When you change the namespace's name, translatable pages should be handled as if they were moved .
Избежание конфликтов пространств имён
In order for you to avoid namespace conflicts e.g. your namespace has the same number as a namespace defined by an extension, the extension namespace list shows you which numbers to avoid to prevent conflicts.
Defining $wgNamespacesToBeSearchedDefault , $wgNamespacesWithSubpages , $wgContentNamespaces or $wgNamespaceAliases for an ID not associated to any existing namespace in $wgExtraNamespaces doesn't break the wiki; MediaWiki gracefully ignores such configurations.
Стилизация пространств имён
Например, чтобы установить цвет фона страниц в определённом пространстве имен (и связанном с ним пространстве имён обсуждения), вы можете добавить следующий код в common.css:
.ns-3000 #content, .ns-3001 #content { background-color: #f3f3ff; }
.ns-3000 div.thumb, .ns-3001 div.thumb { border-color: #f3f3ff; }
где 3000
— это индекс пространства имён, а #f3f3ff
— это цвет, который вы хотите использовать в качестве цвета фона.
You might also want to change the name of the tab from its default (the namespace's name). This is located in your system messages at MediaWiki:nstab-namespace.
См. также
- Руководство:Пространство имён
- Namespace manager - as originally proposed for MW1.6-wikidata and its successors. Currently in use by the OmegaWiki project.
Site administration
Расширения
- Категория:Расширения пространства имён
- Extension:NamespaceManager – for management of namespaces
- Extension:BlueSpiceNamespaceManager – lets you create custom namespaces
- Extension:SpecialNamespaces – a modified version of the Extension:Interwiki which changes it to provide a namespace manager as a special page.
- Расширение:Lockdown – to control access to namespaces
Для разработчиков расширений
- Extension namespace registration - Список пользовательских пространств имён, зарегистрированных расширениями. Если вы определяете константу для пользовательского пространства имён, укажите её здесь.