Manual:Using custom namespaces/ru

В дополнение к встроенным пространствам имён, можно добавлять пользовательские, с отдельным содержанием. Что позволяет сделать более логическую организацию материалов.

Своими пространствами имён проще управлять с помощью конфигурационной директивы. Так же можно определять псевдонимы для своих пространств имён (а, равно, и встроенных) при помощи конфигурационной директивы. Some extensions make it easy for you to create custom namespaces. Examples include and.



Создание своего пространства имён
Вы регистрируете дополнительные пространства имен, добавляя их в глобальную переменную в файле. Все пространства имён требуют уникальный числовой индекс в этом массиве. Как пример простого создания своего пространства имён, добавляя следующие строки в файл определяем пространство "Foo" 3000 и связанное с ним пространство "Foo_talk":


 * Подберите свободное (незанятое) число
 * По принятому соглашению, пространства имён имеющие номера 100-199 зарезервированы для специфических пространств, хотя существуют несколько расширений, которые не придерживаются данного соглашения. Создатели расширений используют большие номера, до 32767. Выбирая свой индекс, вы должны избегать любых чисел уже определённых в extension default namespaces, потому что вы можете захотеть установить это расширение позже. Числа от 3000 до 4999 зарезервированы для системных администраторов, чтобы определить свои пользовательские пространства имен. (Кроме того, желательно избегать повторения любых названий пространств имён, которые совпадают с поставляемыми с помощью расширений.)


 * Четное, затем нечетное.
 * Обратите внимание, что индекс пространства имён равен 3000 в вышеприведённом примере.
 * "чётный" индекс пространства имён указывает на пространство имён содержания.
 * непосредственно следующий "нечётный" индекс указывает на связанное пространство имён обсуждения ("talk")


 * Создаём также пространство имён обсуждения
 * Обычно создаётся пространство имён обсуждения "Talk" вместе с каждым пользовательским пространством. В этом примере, если вы переименуете страницу в пространство имён «Foo», появится вопрос о переименовании соответствующей страницы обсуждения (при её наличии), и если вы подтвердите её переименование, MediaWiki will разместит её в пространство имён «Foo talk».


 * Без пробелов
 * В названиях пространств имён используйте подчёркивания вместо пробелов. Имя 'My Namespace' неверно; вместо него используйте 'My_Namespace'.

The uppercase part does not permit hyphens but they can still be safely added to the prefix title. Пример:
 * Без дефисов


 * 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, , or.

Также вы можете задать дополнительные настройки для нового пространства имён.


 * Do it early
 * Manipulation of  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.


 * Watch out for collisions with URL protocols
 * MediaWiki's linking code knows about a number of URL protocols, defined in the 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   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  by the lowercased name of the protocol you wish to remove):

In extensions
Extensions often add their own namespaces, such as the extension's "Topic" namespace. An extension can unconditionally add to  as described above, or if its namespace registration is conditional (for example  only defines its "Schema" namespace on the wiki where it stores schemas), then it can add a handler function for the  hook that decides what to do.

The timing of registering extensions is subtle. Functions that extensions register with are executed too late to register additional namespaces. So extensions should bind the  hook at file scope (in  ) and check there whether the wiki should activate the extra namespace or not. Extensions can configure namespace permissions and content handlers unconditionally at file scope since they do not require the namespace to actually be created.

The  registration system has a   key for an extension to list its namespaces that should always exist. Из расширения :

It also supports the  hook. Extensions should prefer extension registration over CanonicalNamespaces. 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

When creating custom namespaces to hold additional content, it is a good idea to indicate this in the configuration. This is done via the configuration directive.

To extend the example above, one might add the following to the "LocalSettings.php" file:


 * or

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, 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 ).

Why you would want a custom namespace
There are several reasons you might want this:


 * 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 ( 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)

Dealing with existing pages
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.

To correct this problem, there are three main approaches.

Move conflicting pages
If the number of pages affected is small (e.g. "Bar" held five pages created before the namespace was defined in the site configuration), then the following approach might be suitable:


 * 1) Comment out the namespace definition in the configuration file
 * 1) Access each affected page, and move it out of the pseudo-namespace, e.g. move "Bar:Some page" to "Bar2:Some page"
 * 1) Un-comment the namespace definition
 * 1) Move the affected pages back into the new namespace

Use a maintenance script
Within the maintenance directory, there is a maintenance script which performs the above operation more effectively for a large number of pages;  It is simple to use, but as with all MediaWiki maintenance scripts, consult the available usage information first (use  as an option).

Use a database query
To move all pages "Bar:Some page" into namespace 3000, make the following database query:

To handle discussion pages:

After such fiddling, run the script and the  script to update internal links and search results in your wiki. Note that external search engines like Google will take some time to update their index.

Removing custom namespaces
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. This is a rare occurrence, since most sites will not need namespaces removed, but it is a problem. (See mailing list discussion).

Example on how to remove and the Topic namespace:


 * Uninstall Flow
 * Temporarily add $wgExtraNamespaces[2600] = 'Topic'; to the config
 * Use deleteBatch.php to delete all pages in the Topic namespace
 * Remove the $wgExtraNamespaces config

Renaming custom namespaces
Suppose that you need to rename custom namespace "Foo" to "New" without performing a mass move of pages. The easiest way to achieve this is to preserve the namespace ID (here " ") as well as the namespace constant (here " "), modify the (visible) namespace title and add the old one as an alias.

change  to

Avoid namespace conflicts
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, , $wgContentNamespaces or for an ID not associated to any existing namespace in $wgExtraNamespaces doesn't break the wiki; MediaWiki gracefully ignores such configurations.

Styling namespaces
For example, to set the background color of pages in a particular namespace (and its associated talk namespace) you can add the following code to your common.css:

where  is the namespace's index and   is the color you want as its background color.

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.



См. также
Currently in use by the OmegaWiki project.
 * - for management of namespaces
 * - for management of namespaces
 * - for management of namespaces
 * Namespace manager - as originally proposed for MW1.6-wikidata and its successors.
 * - to use a different skin in a namespace
 * - a modified version of the which changes it to provide a namespace manager as a special page.
 * - to control access to namespaces
 * Extension namespace registration