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

From MediaWiki.org
Jump to navigation Jump to search
This page is a translated version of the page Manual:LocalSettings.php and the translation is 28% complete.

Other languages:
Bahasa Indonesia • ‎Deutsch • ‎English • ‎Nederlands • ‎Tiếng Việt • ‎Türkçe • ‎dansk • ‎español • ‎français • ‎français cadien • ‎italiano • ‎magyar • ‎polski • ‎português • ‎português do Brasil • ‎čeština • ‎Ελληνικά • ‎български • ‎русский • ‎العربية • ‎ತುಳು • ‎中文 • ‎日本語 • ‎한국어
Внимание Внимание: Don't edit LocalSettings.php with document editors like Notepad, TextEdit, or other text editors that add byte order marks to files. These break the PHP runtime of your wiki. Instead, use a code editor, e.g. Vim, Notepad++, or Atom. These handle file encodings properly. They can also be used to repair files previously broken by document editors.

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

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

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

(If you are using Vagrant, see also MediaWiki-Vagrant#MediaWiki_settings.)

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

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

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

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

Когда вы редактируете LocalSettings.php, убедитесь, что сохранили его в правильной кодировке. Следует использовать кодировку "ANSI as 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; проверьте документацию соответствующего расширения для дальнейших инструкций.

В MediaWiki 1.16 и ранее было важно не размещать расширения до строки require_once "includes/DefaultSettings.php";; это очистит массивы функций установки расширений(?), и расширения не будут установлены, и возможно сделает вашу вики недоступной. С 1.17 больше не необходимо в LocalSettings.php подключать DefaultSettings.php.

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

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

До 1.17, этот файл генерировался скриптом установки и располагался в директории config. По состоянию на 1.17, этот файл больше не записывается в ваш веб-сервер по соображениям безопасности. It is now offered as a download, which you must then upload to your server for your wiki to begin working. For a more complete explanation, see this explanation.

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

See the configuration settings index and the comments included in the settings files for help on what all the variables do. A short listing of the most important variables, as well as the most requested features, is listed below.

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

Include path

The $IP (include path) variable holds the local file path to the base installation of your wiki. Since MediaWiki 1.17, MediaWiki is setting $IP automatically - setting it manually in LocalSettings.php is no longer needed. It will default to the current working directory automatically and can be used without the need to manually define it.

The DefaultSettings.php file gets loaded from the directory designated by the IP variable.

Имя сайта

$wgSitename holds the name of your wiki setup. This name gets included many times throughout the system, such as via MediaWiki:Pagetitle. For instance, the Wikipedia tagline "From Wikipedia, the free encyclopedia" makes use of this setting.

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

Some translations of interface are ready for inflection of site name. You can set proper forms of word in variables $wgGrammarForms (for example please refer to the $wgSitename documentation page).

Язык сайта

$wgLanguageCode controls the language of your wiki's interface. While users can switch the language they see in their preferences, this variable sets the default language that all anonymous users and most registered users see.

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

$wgScriptPath is the URL path prefix to access the main MediaWiki script that is the central acting piece of code of MediaWiki. This setting should correspond to the Apache settings, especially if you are using Apache's rewrite rules.

Имя сервера

$wgServer can be used optionally to overwrite the automatic detection. When the wiki is accessed from either the localhost where it runs, from an intranet or from the internet, e-mail notifications and a few other computed messages would be usually delivered with the different URLs. Using $wgServer overwrites the detection and the server name will be constant.

If www.example.com is the server address of your wiki as seen from the internet, add a line such as

$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.

Имя скрипта

$wgScript is the name of the main (index) MediaWiki PHP script, named index.php by default. Changing the script name is probably not a good idea. However, if you feel the urge to do so, this is the place to make your changes. Make sure you know what you are doing.

Redirect script name

$wgRedirectScript specifies the URL path to the redirect script which handles redirects in MediaWiki. This setting is similar to wgScript as you can configure the exact name of the script. As mentioned above, this is probably not a good idea unless you really know what you are doing.

Путь к статье

$wgArticlePath is the path to use when accessing a page in MediaWiki. The path should contain the path to the main script (usually making use of $wgScript) and use the $1 placeholder for the article name.

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 Manual:Short URL for more information on URL configuration.

Typical values are:

"$wgScript/$1" pass the article name with separator "/"
"$wgScript?title=$1" pass the article name as a parameter (old style)
"/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.

Upload location

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

Next, try to find the line that looks like this in LocalSettings.php:

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

If there's no such line, you can copy and paste the line above at the end of the file.

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.

Contact info

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

$wgPasswordSender is the e-mail address where e-mail 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.

User rights

$wgGroupPermissions is an associative array, controlling permissions for creating and editing pages for your different user groups. In this array, custom permission levels can be created, and permission levels for the different user groups can be set. See Help:User rights for more information about the different permissions and user groups available.

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.

Enabling subpages

In LocalSettings.php, subpages are enabled on a per-namespace basis using $wgNamespacesWithSubpages . For example, to enable subpages in the main namespace:

$wgNamespacesWithSubpages[NS_MAIN] = 1;

Image uploads

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/ru for detailed information and trouble-shooting.

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

$wgFileExtensions = array('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

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 $wgLocalInterwiki variable to the preferred name.

Language of user interface

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.

Note: 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 here for a list of the localisation statistics of 1.34.0-wmf.1 (706b1e8). See translatewiki.net for the statistics per released version.

Setting copyright for the site

  • $wgRightsPage is the page on the wiki that covers the copyrights that it falls under. Usually, this will be Project:Copyrights.
  • $wgRightsUrl is the page describing full details of your license. (For the GNU FDL, for example, this would be http://www.gnu.org/licenses/fdl.html.)
  • $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.
    Note: 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.

Example: setting a Creative Commons license

To set a Creative Commons license do the following:

 <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;

Custom namespaces

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". See Custom namespaces for more information as to how to do so.

Skins

The default skin of the site can be modified via $wgDefaultSkin .

См. также