Руководство:LocalSettings.php

This page is a translated version of the page Manual:LocalSettings.php and the translation is 57% complete.
Внимание Внимание: Не редактируйте файл LocalSettings.php с помощью текстовых редакторов Notepad, TextEdit или других текстовых редакторов, которые добавляют в файлы маркеры последовательности байтов. Это приведёт к невыполнению PHP в вашей вики. Вместо этого используйте редакторы кода, например, Vim, Notepad++ или Atom. Они правильно обрабатывают кодировку файла. Их также можно использовать для восстановления файлов после повреждения их текстовыми редакторами.

Файл LocalSettings.php предоставляет базовые настройки конфигурации (основанные на файле DefaultSettings.php ) MediaWiki. Вам следует потратить некоторое время, чтобы изучить настройки в этом файле. Этот файл обычно генерируется веб-интерфейсом установщика MediaWiki но вы можете менять параметры, по возможности совместно с настройками Apache. Для установки MediaWiki как вики-фермы, может использоваться файл CommonSettings.php .

Расположение на сервере

Файл LocalSettings.php не является вики-страницей и вы не можете получить к нему доступ из веб-браузера. Это файл в файловой системе сервера. Его содержимое генерируется в процессе начальной настройки wiki и конечный файл должен быть скопирован на сервер вручную. Файл должен располагаться в папке, в которую установлена MediaWiki, на одном уровне с такими папками как includes/ и skins/ и такими файлами как api.php. Если там нет этого файла, вики вообще не будет работать — если вики работает, файл находится там. Если вы не знаете, где это находится, вы можете ввести в окне терминала команду наподобие find / -iname LocalSettings.php -print, чтобы найти это.

(Если вы используете Vagrant, смотрите MediaWiki-Vagrant#MediaWiki_settings.)

Безопасность

LocalSettings.php обычно содержит конфеденциальные данные, такие как логины базы данных. Эти данные никогда не должны быть публичными! Из-за нарушений безопасности где-то на сервере, может случиться, что другие пользователи могут просматривать содержимое файлов. Чтобы повысить безопасность ваших данных, вы должны соответствующим образом установить UNIX-разрешения для этого файла: пользователь веб-сервера должен иметь доступ к этому файлу. Если это тот же аккаунт, как у владельца файла, то вы можете установить права на 600. Иногда пользователь веб-сервера не является владельцем файла, но он входит в UNIX-группу владельца. В этом случае подойдут права 640. Для улучшения безопасности вам следует уменьшить права настолько, насколько возможно.

Дополнительно вы можете создать пользователя MySQL, который имеет доступ только к базе данных, используемой вики, и написать эти учетные данные пользователя базы данных в файле LocalSettings.php. Также вы можете настроить ваш сервер баз данных так, чтобы он принимал соединения только от localhost - это предотвратит доступ извне, в случае утечки учетных данных.

См. также Manual:Securing database passwords для метода перемещения конфиденциальных частей LocalSettings.php в другой файл в другом каталоге.

Содержимое файла

Когда вы редактируете LocalSettings.php, убедитесь, что сохранили его в правильной кодировке. Следует использовать кодировку "ANSI как UTF-8" — это кодировка UTF-8 без указания порядка байтов (byte order mark (BOM)).

LocalSettings.php содержит PHP код, в основном содержащий определения переменных и их значений. Изменение настроек обычно означает изменение значений PHP-переменных. Ваши изменения вступят в силу сразу после сохранения файла на сервере: ничего не требуется "перезапускать" в ручную. Так или иначе, в некоторых случаях вам потребуется очистить кеш вашего браузера, чтобы увидеть изменения.

Значения по умолчанию для большинства настроек установлены в includes/DefaultSettings.php, которые не надо изменять; если переменная, которую вы хотите изменить, еще отсутствует в LocalSettings.php, скопируйте соответствующую строку из DefaultSettings.php и измените ее в LocalSettings.php. В LocalSettings.php вы можете добавлять новые строки в конце.

Так же в файле могут быть строки наподобие 'require_once "$IP/extensions/extension.php";', которые указывают на расширения. Эти строки включают соответствующее расширение в вики. Для расширений могут потребоваться настройки значений других переменных в LocalSettings.php; проверьте документацию соответствующего расширения для дальнейших инструкций.

Как и большинство PHP-файлов в MediaWiki, LocalSettings.php не заканчивается закрывающим PHP-тегом ?>. Это защищает от случайного добавления информации после этого тега. PHP нормально работает без закрывающего тега.

Если ваша вики на MediaWiki вики-ферме, вы можете не иметь доступа изменить (и, возможно, даже прочитать) файл LocalSettings.php (см., например, [1]). Компания вики-фермы может разрешить или не разрешить внести изменения, которые вы хотите произвести. Возможно она хочет оставить большинство настроек одинаковыми на всех вики в вики-фермах.

По причинам безопасности этот файл не записывается на ваш веб-сервер автоматически. Вместо этого предлагается загрузить его, а затем выгрузить на сервер с вики, после чего вики заработает. Более подробную информацию смотрите в этом описании.

Обзор доступных настроек

См. указатель настроек конфигурации и комментарии, включенные в файлы настроек, для получения справки о том, что делают все переменные. Ниже приведен краткий список наиболее важных переменных, а также наиболее востребованных функций.

Стандартные настройки

Путь установки

Переменная $IP (install path) содержит путь к локальным файлам с основным каталогом установки вашей вики. Начиная MediaWiki 1.18, система устанавливает $IP автоматически. Больше не нужно вручную настраивать $IP в LocalSettings.php. $IP будет выбран по умолчанию для текущей рабочей директории и может использоваться без необходимости переопределения вручную. Attempting to set $IP (or MW_INSTALL_PATH) in LocalSettings.php may produce unexpected results.

Файл DefaultSettings.php загружается из директории, указанной в переменной IP.

Имя сайта

$wgSitename содержит имя вашей настройки вики. Это имя многократно включается в систему, например, через MediaWiki:Pagetitle. Например, эта настройка используется в слогане Википедии «Из Википедии, свободной энциклопедии».

Склонение имени сайта

Некоторые переводы интерфейса уже готовы к изменению названия сайта. Вы можете установить правильные формы слова в переменных $wgGrammarForms (например, обратитесь к странице документации $wgSitename ).

Язык сайта

$wgLanguageCode контролирует язык интерфейса вики. Зарегистрированные пользователи могут переключить язык интерфейса в своих настройках, но эта переменная устанавливает язык по умолчанию, который будут видеть незарегистрированные пользователей и основная часть зарегистрированных пользователей (пока не сменят).

Путь к скрипту

$wgScriptPath — это префикс URL-адреса для доступа к основному скрипту MediaWiki, который является центральной частью кода MediaWiki. Этот параметр должен соответствовать настройкам Apache, особенно если вы используете правила перезаписи Apache.

Имя сервера

$wgServer содержит базовый URL-адрес сервера, включая протокол, но без завершающей косой черты и без подкаталога, если он есть. Когда доступ к вики осуществляется с локального хоста, на котором она работает, из интрасети или из Интернета, уведомления по электронной почте и несколько других вычисляемых сообщений обычно доставляются с разными URL-адресами.

Начиная с MediaWiki 1.34 $wgServer должен быть установлен в LocalSettings.php. До этого MediaWiki пытался автоматически определить имя сервера, и $wgServer был необязательным, чтобы переопределить автоматическое определение.

Если www.example.com — это адрес сервера вашей вики, видимый из Интернета, добавьте строку, например

$wgServer = 'http://www.example.com';

The magic word variable {{SERVER}} can be used on wiki pages; it equals the value of $wgServer; however, on a wiki, such as those in the Wikimedia family, where relative urls are used, it will not fully expand, for example here it displays //www.mediawiki.org, which can neither be clicked nor copy-pasted into the address bar as it is.

You can also use a protocol relative URL as shown below. When using a protocol relative URL, be sure to set $wgCanonicalServer. $wgCanonicalServer is needed for some places in the code where an origin with a protocol and hostname is needed.

$wgServer = '//www.example.com';
$wgCanonicalServer = 'https://www.example.com';

Имя скрипта

$wgScript это имя основного (index) MediaWiki PHP скрипта, который по умолчанию называется index.php. Изменение имени скрипта вероятно не самая лучшая идея. Тем не менее, если вам необходимо сделать это, то изменения можно сделать здесь. Убедитесь в том, что вы понимаете что вы делаете.

Путь к статье

$wgArticlePath это путь, который используется во время доступа к странице на MediaWiki.

Этот путь состоит из пути к основному скрипту (обычно используется $wgScript) и переменной $1, которая заменится на имя статьи во время работы.

If you are using Apache rewrite rules to create pretty and short URLs, you probably need to adjust $wgArticlePath to address the right path. Note that wgArticlePath is used to construct URLs from within MediaWiki. If you make a mistake here, internal links will show up incorrectly while you still may be able to access the main page by specifying the correct URL manually. See Руководство:Короткий URL-адрес for more information on URL configuration.

Типичные значения:

"$wgScript/$1" передать имя статьи после разделителя "/"
"$wgScript?title=$1" передать имя статьи как параметр (старый стиль)
"/mypath/$1" custom path. Use Apache rewrite rules to convert "mypath" to the proper path accessing the main script

Расположение таблиц стиля (stylesheet)

Use $wgStylePath to set the URL path to the place where the stylesheets (CSS) for the MediaWiki installation are located. $wgStyleDirectory should point the same place, but note that this is a local file system path for use in internal scripts accessing the file system.

Расположение загружаемых файлов

The upload directory is the place where files uploaded by the users are stored. $wgUploadPath specifies the URL path, $wgUploadDirectory points to the local file system path.

Логотип

$wgLogo specifies which graphical logo is displayed in the top left corner of all MediaWiki pages. These steps replace the default logo in the /wiki/skins/common/images/ directory, replacing /wiki with the path to the directory where you installed the MediaWiki software.

First, copy whatever logo you want into the /wiki/skins/common/images/ directory (replacing /wiki with the path to the directory where you installed the MediaWiki software).

Далее, в файле LocalSettings.php попробуйте найти строку в файле, которая похожа на:

$wgLogo = "$wgStylePath/common/images/wiki.png";

Если такой строки нет, то вы можете скопировать строку выше и вставить её в конец файла.

Then, modify that line to point to your logo. The logo must be web accessible. The value of this variable is passed to the web browser, which uses it to fetch the logo. If in doubt, a good way to pick what to put here is navigate to the logo in your web browser (for example, this wiki the url of the logo is http://upload.wikimedia.org/wikipedia/mediawiki/b/bc/Wiki.png ), and put the full URL as the value of this variable.

Some people just replace the skins/common/images/wiki.png file with their logo. This is not recommended, as the customized logo would be overwritten on upgrade.

MediaWiki 1.35 introduced $wgLogos , which allows multiple versions of the same logo. An example of using multiple logos is shown below.

$wgLogos = [
	'1x' => "$wgStylePath/common/images/1x_version.png",
	'1.5x' => "$wgStylePath/common/1.5x_version.png",
	...
	'tagline' => [
		'src' => "$wgStylePath/common/tagline_version.png",
		'width' => 135,
		'height' => 15,
	],
];

Контактная информация

$wgEmergencyContact is the email address of the user to contact if something goes wrong. This email address is used to send internal bug reports to. As an administrator, you want to include your email address here.

$wgPasswordSender is the email address where email gets sent from, when passwords are sent out to users who have forgotten their passwords. Choose an address people can reply to in case of trouble or confusion.

Настройки базы данных

MediaWiki needs access to the database (currently either MySQL or PostgreSQL) to store pages, modifications, user information, and a lot more things.

$wgDBserver contains the hostname where the database is hosted on. In most cases this will be just "localhost" as the database is run on the same system, but for distributed installations, you need to fill in the fully qualified domain name of the computer running the database.

$wgDBname is the database name of the database to be used by MediaWiki. A single MySQL or PostgreSQL installation can store more than one database and you can even run many MediaWiki installations on a single server. Make sure you have stated the correct database name here and use different database names for different wiki installations on the same database server.

$wgDBuser and $wgDBpassword contain the login name and password to be used by MediaWiki to access the database. Make sure the specified user has the proper access rights to be able to manipulate the wiki's table on the database server.

Also see Manual:Securing database passwords for a method to move the sensitive parts of LocalSettings.php to a different file in a different directory.

Права пользователей

$wgGroupPermissions — это ассоциативный массив, управляющий разрешениями на создание и редактирование страниц для различных групп пользователей. В этом массиве можно создавать настраиваемые уровни разрешений и устанавливать уровни разрешений для различных групп пользователей. См. Help:User rights для получения дополнительной информации о различных разрешениях и доступных группах пользователей.

Force capital links

By default, no page name can start with a lowercase Roman letter: in an attempt to do so the first letter is converted to uppercase; if a link target, included page, image or category is specified with a name starting with a lowercase letter, the actual target etc. is the page starting with the corresponding capital.

Alternatively page names can start with a lowercase letter, in addition to the possibilities of starting with a capital, a digit, etc. For that you must adjust $wgCapitalLinks . Setting it to false allows lowercase characters, true chooses the default behavior.

Включение подстраниц

В LocalSettings.php подстраницы включаются для каждого пространства имен с помощью $wgNamespacesWithSubpages . Например, чтобы включить подстраницы в основном пространстве имен:

$wgNamespacesWithSubpages[NS_MAIN] = 1;

Загрузка изображений

Before users are allowed to upload files to the MediaWiki system, you have to enable that feature. Make sure the Upload Directory is properly configured and writeable by the Apache web server process. Then set $wgEnableUploads to true to allow uploading in the web user interface.

i.e. Here's some example code from includes/DefaultSettings.php to put in LocalSettings.php:

$wgUploadPath       = "$wgScriptPath/uploads";      ## Wiki 1.5 defaults to /images, but allows more than just images
$wgUploadDirectory  = "$IP/uploads";                ## Wiki 1.5 defaults to /images, but allows more than just images

## To enable image uploads, make sure the above '$wgUploadPath' directory is writable by Apache User or group.
## ''(i.e.  chmod og+w uploads images)''  then the following should be true:
$wgEnableUploads       = true;

$wgUseImageMagick      = true;
$wgImageMagickConvertCommand = "/usr/bin/convert";

## If you want to use image uploads under safe mode, create the directories images/archive, images/thumb and
## images/temp, and make them all writable. Then uncomment this, if it's not already uncommented:
$wgHashedUploadDirectory = false;

If you want to be able to resize images on the fly to support thumbnails, MediaWiki needs a working ImageMagick installation. Set $wgUseImageMagick to true once you have installed and tested ImageMagick on your system. Make sure $wgImageMagickConvertCommand points to the proper location of the convert command of your installation, that the command is executable by the web server process, and $wgMaxShellMemory is large enough. See Manual:Image administration#Image thumbnailing for detailed information and troubleshooting.

Also, you may want to modify the list of accepted extensions, which is stored within $wgFileExtensions :

$wgFileExtensions = [ 'png', 'jpg', 'jpeg', 'ogg', 'doc', 'xls', 'ppt', 'mp3', 'sxc', 'pdf' ];

In case ImageMagick outputs an error message similar to the following:

Fatal error: mime_magic could not be initialized, magic file is not available in includes/MimeMagic.php on line 506

then try adding the following line to LocalSettings.php:

$wgMimeDetectorCommand = "file -bi";

Поддержка интервики

InterWiki support is built into MediaWiki but you need to configure the prefix to be used for your internal links. This prefix is usually the same as $wgSitename , but in case you need to change that, you set the $wgLocalInterwikis variable to the preferred name.


Язык пользовательского интерфейса

MediaWiki allows for a variety of localized user interfaces languages instead of the English default. If you want to run your wiki in a non-English language, set the $wgLanguageCode variable to the proper language code (e.g. "de" for German, "es" for Spanish, etc.)

You may use any of the languages with a file in the directory languages/i18n. E.g. if you find es.json, then you can use "es" for Spanish. Do not use "Es" with a capital letter. Although it seems to work, not all texts are translated.

After changing the language code, you will need to run a PHP script to make it work. In a terminal window, change to your wiki directory, change to the maintenance folder, and enter php rebuildMessages.php --rebuild. On Windows, the PHP folder might not be in your PATH environment variable and you'll have to prefix php with the path to the program.

Not all languages are supported. See the translation statistics on TranslateWiki for an up-to-date list of which languages are supported and to what extent. That list reflects the current state of MediaWiki core, so depending on what version you are using there may be a discrepancy.

Setting copyright for the site

  • $wgRightsText is the text in the footer that follows "Content is available under". It will be linked to the page specified in $wgRightsPage.
  • $wgRightsIcon is the URL of the image placed at the left of the footer.
If $wgRightsPage is non-empty, the link in the copyright/license notice will link to that page on your site. If $wgRightsPage is empty then the copyright/license notice will link to $wgRightsUrl instead.

To modify the copyright statements of the site, add something like this to LocalSettings.php:

$wgRightsPage = "YourWiki:Copyright";
$wgRightsText = "copyright YourWiki";

Afterwards, edit MediaWiki:Copyright to provide an appropriate message, using "$1" to indicate the position where the link to your copyright page will be.

Пример: установка лиценции Creative Commons

To set a Creative Commons license do the following:

  • Examine the returned HTML code, e.g.:
<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/3.0/">
<img alt="Creative Commons License" border="0" src="http://creativecommons.org/images/public/somerights30.png" />
</a>
This work is licensed under a
<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/3.0/">
Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License</a>.
  • For $wgRightsURL enter the href info from the first anchor:
$wgRightsUrl = "http://creativecommons.org/licenses/by-nc-sa/3.0/";
  • For $wgRightsText enter the text the second anchor links from (add the "a" to the Wiki variable for a more grammatically correct version)
$wgRightsText = "a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License";
  • For $wgRightsIcon enter the src info from the img link in the first anchor. You want to copy the badge to your own site instead of using the one from the Creative Commons site.
$wgRightsIcon = "http://creativecommons.org/images/public/somerights30.png";
  • For using RDF metadata about copyright add one or both of the following lines to your LocalSettings.php:
$wgEnableCreativeCommonsRdf = true;
$wgEnableDublinCoreRdf = true;


Настраиваемые пространства имён

By declaring $wgExtraNamespaces , and modifying $wgNamespacesWithSubpages , and $wgNamespacesToBeSearchedDefault , extra namespaces can be added to a MediaWiki installation; and by declaring the $wgNamespaceAliases array namespace aliases can be added. Take heed not to have any pages already titled in that namespace, for instance if you had a page called "Technical:Support" and you created the Technical: namespace, then that page would not only be lost, but you cannot remove it from Special:Allpages. To fix this delete the namespace, move "Technical:Support" to "Support" in mainspace, delete the redirect, reinsert the namespace, and move it back to "Technical:Support". См. справку по настраиваемым пространствам имён для дополнительной информации.

Темы оформления

Скин по умолчанию может быть изменён с помощью $wgDefaultSkin .

Смотрите также

  • LocalSettingsGenerator.php исходный код, который в процессе установки генерирует изначальное содержимое файла LocalSettings.php.
  • Вики-семьи могут использовать одну и ту же страницу LocalSettings.php.
  • Manual:Securing database passwords - руководство по защите паролей к базе данных и файла LocalSettings.php.